apcore-js 0.1.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 (142) hide show
  1. package/.claude/settings.local.json +11 -0
  2. package/.gitmessage +60 -0
  3. package/.pre-commit-config.yaml +28 -0
  4. package/CHANGELOG.md +47 -0
  5. package/CLAUDE.md +68 -0
  6. package/README.md +131 -0
  7. package/apcore-logo.svg +79 -0
  8. package/package.json +37 -0
  9. package/planning/acl-system/overview.md +54 -0
  10. package/planning/acl-system/plan.md +92 -0
  11. package/planning/acl-system/state.json +76 -0
  12. package/planning/acl-system/tasks/acl-core.md +226 -0
  13. package/planning/acl-system/tasks/acl-rule.md +92 -0
  14. package/planning/acl-system/tasks/conditional-rules.md +259 -0
  15. package/planning/acl-system/tasks/pattern-matching.md +152 -0
  16. package/planning/acl-system/tasks/yaml-loading.md +271 -0
  17. package/planning/core-executor/overview.md +53 -0
  18. package/planning/core-executor/plan.md +88 -0
  19. package/planning/core-executor/state.json +76 -0
  20. package/planning/core-executor/tasks/async-support.md +106 -0
  21. package/planning/core-executor/tasks/execution-pipeline.md +113 -0
  22. package/planning/core-executor/tasks/redaction.md +85 -0
  23. package/planning/core-executor/tasks/safety-checks.md +65 -0
  24. package/planning/core-executor/tasks/setup.md +75 -0
  25. package/planning/decorator-bindings/overview.md +62 -0
  26. package/planning/decorator-bindings/plan.md +104 -0
  27. package/planning/decorator-bindings/state.json +87 -0
  28. package/planning/decorator-bindings/tasks/binding-directory.md +79 -0
  29. package/planning/decorator-bindings/tasks/binding-loader.md +148 -0
  30. package/planning/decorator-bindings/tasks/explicit-schemas.md +85 -0
  31. package/planning/decorator-bindings/tasks/function-module.md +127 -0
  32. package/planning/decorator-bindings/tasks/module-factory.md +89 -0
  33. package/planning/decorator-bindings/tasks/schema-modes.md +142 -0
  34. package/planning/middleware-system/overview.md +48 -0
  35. package/planning/middleware-system/plan.md +102 -0
  36. package/planning/middleware-system/state.json +65 -0
  37. package/planning/middleware-system/tasks/adapters.md +170 -0
  38. package/planning/middleware-system/tasks/base.md +115 -0
  39. package/planning/middleware-system/tasks/logging-middleware.md +304 -0
  40. package/planning/middleware-system/tasks/manager.md +313 -0
  41. package/planning/observability/overview.md +53 -0
  42. package/planning/observability/plan.md +119 -0
  43. package/planning/observability/state.json +98 -0
  44. package/planning/observability/tasks/context-logger.md +201 -0
  45. package/planning/observability/tasks/exporters.md +121 -0
  46. package/planning/observability/tasks/metrics-collector.md +162 -0
  47. package/planning/observability/tasks/metrics-middleware.md +141 -0
  48. package/planning/observability/tasks/obs-logging-middleware.md +179 -0
  49. package/planning/observability/tasks/span-model.md +120 -0
  50. package/planning/observability/tasks/tracing-middleware.md +179 -0
  51. package/planning/overview.md +81 -0
  52. package/planning/registry-system/overview.md +57 -0
  53. package/planning/registry-system/plan.md +114 -0
  54. package/planning/registry-system/state.json +109 -0
  55. package/planning/registry-system/tasks/dependencies.md +157 -0
  56. package/planning/registry-system/tasks/entry-point.md +148 -0
  57. package/planning/registry-system/tasks/metadata.md +198 -0
  58. package/planning/registry-system/tasks/registry-core.md +323 -0
  59. package/planning/registry-system/tasks/scanner.md +172 -0
  60. package/planning/registry-system/tasks/schema-export.md +261 -0
  61. package/planning/registry-system/tasks/types.md +124 -0
  62. package/planning/registry-system/tasks/validation.md +177 -0
  63. package/planning/schema-system/overview.md +56 -0
  64. package/planning/schema-system/plan.md +121 -0
  65. package/planning/schema-system/state.json +98 -0
  66. package/planning/schema-system/tasks/exporter.md +153 -0
  67. package/planning/schema-system/tasks/loader.md +106 -0
  68. package/planning/schema-system/tasks/ref-resolver.md +133 -0
  69. package/planning/schema-system/tasks/strict-mode.md +140 -0
  70. package/planning/schema-system/tasks/typebox-generation.md +133 -0
  71. package/planning/schema-system/tasks/types-and-annotations.md +160 -0
  72. package/planning/schema-system/tasks/validator.md +149 -0
  73. package/src/acl.ts +188 -0
  74. package/src/bindings.ts +208 -0
  75. package/src/config.ts +24 -0
  76. package/src/context.ts +75 -0
  77. package/src/decorator.ts +110 -0
  78. package/src/errors.ts +369 -0
  79. package/src/executor.ts +348 -0
  80. package/src/index.ts +81 -0
  81. package/src/middleware/adapters.ts +54 -0
  82. package/src/middleware/base.ts +33 -0
  83. package/src/middleware/index.ts +6 -0
  84. package/src/middleware/logging.ts +103 -0
  85. package/src/middleware/manager.ts +105 -0
  86. package/src/module.ts +41 -0
  87. package/src/observability/context-logger.ts +201 -0
  88. package/src/observability/index.ts +4 -0
  89. package/src/observability/metrics.ts +212 -0
  90. package/src/observability/tracing.ts +187 -0
  91. package/src/registry/dependencies.ts +99 -0
  92. package/src/registry/entry-point.ts +64 -0
  93. package/src/registry/index.ts +8 -0
  94. package/src/registry/metadata.ts +111 -0
  95. package/src/registry/registry.ts +314 -0
  96. package/src/registry/scanner.ts +150 -0
  97. package/src/registry/schema-export.ts +177 -0
  98. package/src/registry/types.ts +32 -0
  99. package/src/registry/validation.ts +38 -0
  100. package/src/schema/annotations.ts +67 -0
  101. package/src/schema/exporter.ts +93 -0
  102. package/src/schema/index.ts +14 -0
  103. package/src/schema/loader.ts +270 -0
  104. package/src/schema/ref-resolver.ts +235 -0
  105. package/src/schema/strict.ts +128 -0
  106. package/src/schema/types.ts +73 -0
  107. package/src/schema/validator.ts +82 -0
  108. package/src/utils/index.ts +1 -0
  109. package/src/utils/pattern.ts +30 -0
  110. package/tests/helpers.ts +30 -0
  111. package/tests/integration/test-acl-safety.test.ts +268 -0
  112. package/tests/integration/test-binding-executor.test.ts +194 -0
  113. package/tests/integration/test-e2e-flow.test.ts +117 -0
  114. package/tests/integration/test-error-propagation.test.ts +259 -0
  115. package/tests/integration/test-middleware-chain.test.ts +120 -0
  116. package/tests/integration/test-observability-integration.test.ts +438 -0
  117. package/tests/observability/test-context-logger.test.ts +123 -0
  118. package/tests/observability/test-metrics.test.ts +89 -0
  119. package/tests/observability/test-tracing.test.ts +131 -0
  120. package/tests/registry/test-dependencies.test.ts +70 -0
  121. package/tests/registry/test-entry-point.test.ts +133 -0
  122. package/tests/registry/test-metadata.test.ts +265 -0
  123. package/tests/registry/test-registry.test.ts +140 -0
  124. package/tests/registry/test-scanner.test.ts +257 -0
  125. package/tests/registry/test-schema-export.test.ts +224 -0
  126. package/tests/registry/test-validation.test.ts +75 -0
  127. package/tests/schema/test-loader.test.ts +97 -0
  128. package/tests/schema/test-ref-resolver.test.ts +105 -0
  129. package/tests/schema/test-strict.test.ts +139 -0
  130. package/tests/schema/test-validator.test.ts +64 -0
  131. package/tests/test-acl.test.ts +206 -0
  132. package/tests/test-bindings.test.ts +227 -0
  133. package/tests/test-config.test.ts +76 -0
  134. package/tests/test-context.test.ts +151 -0
  135. package/tests/test-decorator.test.ts +173 -0
  136. package/tests/test-errors.test.ts +204 -0
  137. package/tests/test-executor.test.ts +252 -0
  138. package/tests/test-middleware-manager.test.ts +185 -0
  139. package/tests/test-middleware.test.ts +86 -0
  140. package/tsconfig.build.json +8 -0
  141. package/tsconfig.json +20 -0
  142. package/vitest.config.ts +18 -0
@@ -0,0 +1,212 @@
1
+ /**
2
+ * In-memory metrics collection with Prometheus export.
3
+ */
4
+
5
+ import type { Context } from '../context.js';
6
+ import { ModuleError } from '../errors.js';
7
+ import { Middleware } from '../middleware/base.js';
8
+
9
+ const DESCRIPTIONS: Record<string, string> = {
10
+ apcore_module_calls_total: 'Total module calls',
11
+ apcore_module_errors_total: 'Total module errors',
12
+ apcore_module_duration_seconds: 'Module execution duration',
13
+ };
14
+
15
+ function labelsKey(labels: Record<string, string>): string {
16
+ return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`).join(',');
17
+ }
18
+
19
+ export class MetricsCollector {
20
+ static readonly DEFAULT_BUCKETS: number[] = [
21
+ 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
22
+ ];
23
+
24
+ private _buckets: number[];
25
+ private _counters: Map<string, number> = new Map();
26
+ private _histogramSums: Map<string, number> = new Map();
27
+ private _histogramCounts: Map<string, number> = new Map();
28
+ private _histogramBuckets: Map<string, number> = new Map();
29
+
30
+ constructor(buckets?: number[]) {
31
+ this._buckets = buckets ? [...buckets].sort((a, b) => a - b) : [...MetricsCollector.DEFAULT_BUCKETS];
32
+ }
33
+
34
+ increment(name: string, labels: Record<string, string>, amount: number = 1): void {
35
+ const key = `${name}|${labelsKey(labels)}`;
36
+ this._counters.set(key, (this._counters.get(key) ?? 0) + amount);
37
+ }
38
+
39
+ observe(name: string, labels: Record<string, string>, value: number): void {
40
+ const lk = labelsKey(labels);
41
+ const key = `${name}|${lk}`;
42
+
43
+ this._histogramSums.set(key, (this._histogramSums.get(key) ?? 0) + value);
44
+ this._histogramCounts.set(key, (this._histogramCounts.get(key) ?? 0) + 1);
45
+
46
+ for (const b of this._buckets) {
47
+ if (value <= b) {
48
+ const bkey = `${name}|${lk}|${b}`;
49
+ this._histogramBuckets.set(bkey, (this._histogramBuckets.get(bkey) ?? 0) + 1);
50
+ }
51
+ }
52
+ // +Inf bucket
53
+ const infKey = `${name}|${lk}|Inf`;
54
+ this._histogramBuckets.set(infKey, (this._histogramBuckets.get(infKey) ?? 0) + 1);
55
+ }
56
+
57
+ snapshot(): Record<string, unknown> {
58
+ return {
59
+ counters: Object.fromEntries(this._counters),
60
+ histograms: {
61
+ sums: Object.fromEntries(this._histogramSums),
62
+ counts: Object.fromEntries(this._histogramCounts),
63
+ buckets: Object.fromEntries(this._histogramBuckets),
64
+ },
65
+ };
66
+ }
67
+
68
+ reset(): void {
69
+ this._counters.clear();
70
+ this._histogramSums.clear();
71
+ this._histogramCounts.clear();
72
+ this._histogramBuckets.clear();
73
+ }
74
+
75
+ exportPrometheus(): string {
76
+ const lines: string[] = [];
77
+ const counterNames = new Set<string>();
78
+ const histNames = new Set<string>();
79
+
80
+ // Counters
81
+ for (const [compositeKey, value] of [...this._counters.entries()].sort()) {
82
+ const [name, lk] = compositeKey.split('|', 2);
83
+ if (!counterNames.has(name)) {
84
+ const desc = DESCRIPTIONS[name] ?? name;
85
+ lines.push(`# HELP ${name} ${desc}`);
86
+ lines.push(`# TYPE ${name} counter`);
87
+ counterNames.add(name);
88
+ }
89
+ const labelsStr = formatLabels(parseLabels(lk));
90
+ lines.push(`${name}${labelsStr} ${value}`);
91
+ }
92
+
93
+ // Histograms
94
+ const histKeys = [...this._histogramSums.keys()].sort();
95
+ for (const compositeKey of histKeys) {
96
+ const [name, lk] = compositeKey.split('|', 2);
97
+ if (!histNames.has(name)) {
98
+ const desc = DESCRIPTIONS[name] ?? name;
99
+ lines.push(`# HELP ${name} ${desc}`);
100
+ lines.push(`# TYPE ${name} histogram`);
101
+ histNames.add(name);
102
+ }
103
+
104
+ const labelsDict = parseLabels(lk);
105
+ const labelsStr = formatLabels(labelsDict);
106
+
107
+ for (const b of this._buckets) {
108
+ const bkey = `${name}|${lk}|${b}`;
109
+ const count = this._histogramBuckets.get(bkey) ?? 0;
110
+ const leStr = String(b);
111
+ const leLabels = { ...labelsDict, le: leStr };
112
+ lines.push(`${name}_bucket${formatLabels(leLabels)} ${count}`);
113
+ }
114
+
115
+ const infKey = `${name}|${lk}|Inf`;
116
+ const infCount = this._histogramBuckets.get(infKey) ?? 0;
117
+ const infLabels = { ...labelsDict, le: '+Inf' };
118
+ lines.push(`${name}_bucket${formatLabels(infLabels)} ${infCount}`);
119
+
120
+ const sumVal = this._histogramSums.get(compositeKey) ?? 0;
121
+ const countVal = this._histogramCounts.get(compositeKey) ?? 0;
122
+ lines.push(`${name}_sum${labelsStr} ${sumVal}`);
123
+ lines.push(`${name}_count${labelsStr} ${countVal}`);
124
+ }
125
+
126
+ return lines.length > 0 ? lines.join('\n') + '\n' : '';
127
+ }
128
+
129
+ incrementCalls(moduleId: string, status: string): void {
130
+ this.increment('apcore_module_calls_total', { module_id: moduleId, status });
131
+ }
132
+
133
+ incrementErrors(moduleId: string, errorCode: string): void {
134
+ this.increment('apcore_module_errors_total', { module_id: moduleId, error_code: errorCode });
135
+ }
136
+
137
+ observeDuration(moduleId: string, durationSeconds: number): void {
138
+ this.observe('apcore_module_duration_seconds', { module_id: moduleId }, durationSeconds);
139
+ }
140
+ }
141
+
142
+ function parseLabels(lk: string): Record<string, string> {
143
+ if (!lk) return {};
144
+ const result: Record<string, string> = {};
145
+ for (const pair of lk.split(',')) {
146
+ const [k, v] = pair.split('=', 2);
147
+ if (k) result[k] = v ?? '';
148
+ }
149
+ return result;
150
+ }
151
+
152
+ function formatLabels(labels: Record<string, string>): string {
153
+ const entries = Object.entries(labels);
154
+ if (entries.length === 0) return '';
155
+ const sorted = entries.sort(([a], [b]) => {
156
+ if (a === 'le') return 1;
157
+ if (b === 'le') return -1;
158
+ return a.localeCompare(b);
159
+ });
160
+ const pairs = sorted.map(([k, v]) => `${k}="${v}"`).join(',');
161
+ return `{${pairs}}`;
162
+ }
163
+
164
+ export class MetricsMiddleware extends Middleware {
165
+ private _collector: MetricsCollector;
166
+
167
+ constructor(collector: MetricsCollector) {
168
+ super();
169
+ this._collector = collector;
170
+ }
171
+
172
+ override before(
173
+ _moduleId: string,
174
+ _inputs: Record<string, unknown>,
175
+ context: Context,
176
+ ): null {
177
+ const starts = (context.data['_metrics_starts'] as number[]) ?? [];
178
+ starts.push(performance.now());
179
+ context.data['_metrics_starts'] = starts;
180
+ return null;
181
+ }
182
+
183
+ override after(
184
+ moduleId: string,
185
+ _inputs: Record<string, unknown>,
186
+ _output: Record<string, unknown>,
187
+ context: Context,
188
+ ): null {
189
+ const starts = context.data['_metrics_starts'] as number[];
190
+ const startTime = starts.pop()!;
191
+ const durationS = (performance.now() - startTime) / 1000;
192
+ this._collector.incrementCalls(moduleId, 'success');
193
+ this._collector.observeDuration(moduleId, durationS);
194
+ return null;
195
+ }
196
+
197
+ override onError(
198
+ moduleId: string,
199
+ _inputs: Record<string, unknown>,
200
+ error: Error,
201
+ context: Context,
202
+ ): null {
203
+ const starts = context.data['_metrics_starts'] as number[];
204
+ const startTime = starts.pop()!;
205
+ const durationS = (performance.now() - startTime) / 1000;
206
+ const errorCode = error instanceof ModuleError ? error.code : error.constructor.name;
207
+ this._collector.incrementCalls(moduleId, 'error');
208
+ this._collector.incrementErrors(moduleId, errorCode);
209
+ this._collector.observeDuration(moduleId, durationS);
210
+ return null;
211
+ }
212
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Tracing system: Span, SpanExporter implementations, and TracingMiddleware.
3
+ */
4
+
5
+ import { randomBytes } from 'node:crypto';
6
+ import type { Context } from '../context.js';
7
+ import { Middleware } from '../middleware/base.js';
8
+
9
+ export interface Span {
10
+ traceId: string;
11
+ name: string;
12
+ startTime: number;
13
+ spanId: string;
14
+ parentSpanId: string | null;
15
+ attributes: Record<string, unknown>;
16
+ endTime: number | null;
17
+ status: string;
18
+ events: Array<Record<string, unknown>>;
19
+ }
20
+
21
+ export function createSpan(options: {
22
+ traceId: string;
23
+ name: string;
24
+ startTime: number;
25
+ spanId?: string;
26
+ parentSpanId?: string | null;
27
+ attributes?: Record<string, unknown>;
28
+ }): Span {
29
+ return {
30
+ traceId: options.traceId,
31
+ name: options.name,
32
+ startTime: options.startTime,
33
+ spanId: options.spanId ?? randomBytes(8).toString('hex'),
34
+ parentSpanId: options.parentSpanId ?? null,
35
+ attributes: options.attributes ?? {},
36
+ endTime: null,
37
+ status: 'ok',
38
+ events: [],
39
+ };
40
+ }
41
+
42
+ export interface SpanExporter {
43
+ export(span: Span): void;
44
+ }
45
+
46
+ export class StdoutExporter implements SpanExporter {
47
+ export(span: Span): void {
48
+ console.log(JSON.stringify(span));
49
+ }
50
+ }
51
+
52
+ export class InMemoryExporter implements SpanExporter {
53
+ private _spans: Span[] = [];
54
+ private _maxSpans: number;
55
+
56
+ constructor(maxSpans: number = 10_000) {
57
+ this._maxSpans = maxSpans;
58
+ }
59
+
60
+ export(span: Span): void {
61
+ this._spans.push(span);
62
+ while (this._spans.length > this._maxSpans) {
63
+ this._spans.shift();
64
+ }
65
+ }
66
+
67
+ getSpans(): Span[] {
68
+ return [...this._spans];
69
+ }
70
+
71
+ clear(): void {
72
+ this._spans = [];
73
+ }
74
+ }
75
+
76
+ const VALID_STRATEGIES = new Set(['full', 'proportional', 'error_first', 'off']);
77
+
78
+ export class TracingMiddleware extends Middleware {
79
+ private _exporter: SpanExporter;
80
+ private _samplingRate: number;
81
+ private _samplingStrategy: string;
82
+
83
+ constructor(
84
+ exporter: SpanExporter,
85
+ samplingRate: number = 1.0,
86
+ samplingStrategy: string = 'full',
87
+ ) {
88
+ super();
89
+ if (samplingRate < 0.0 || samplingRate > 1.0) {
90
+ throw new Error(`sampling_rate must be between 0.0 and 1.0, got ${samplingRate}`);
91
+ }
92
+ if (!VALID_STRATEGIES.has(samplingStrategy)) {
93
+ throw new Error(`sampling_strategy must be one of ${[...VALID_STRATEGIES].join(', ')}, got '${samplingStrategy}'`);
94
+ }
95
+ this._exporter = exporter;
96
+ this._samplingRate = samplingRate;
97
+ this._samplingStrategy = samplingStrategy;
98
+ }
99
+
100
+ private _shouldSample(context: Context): boolean {
101
+ const existing = context.data['_tracing_sampled'];
102
+ if (typeof existing === 'boolean') return existing;
103
+
104
+ let decision: boolean;
105
+ if (this._samplingStrategy === 'full') {
106
+ decision = true;
107
+ } else if (this._samplingStrategy === 'off') {
108
+ decision = false;
109
+ } else {
110
+ decision = Math.random() < this._samplingRate;
111
+ }
112
+
113
+ context.data['_tracing_sampled'] = decision;
114
+ return decision;
115
+ }
116
+
117
+ override before(
118
+ moduleId: string,
119
+ _inputs: Record<string, unknown>,
120
+ context: Context,
121
+ ): null {
122
+ this._shouldSample(context);
123
+
124
+ const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
125
+ context.data['_tracing_spans'] = spansStack;
126
+ const parentSpanId = spansStack.length > 0 ? spansStack[spansStack.length - 1].spanId : null;
127
+
128
+ const span = createSpan({
129
+ traceId: context.traceId,
130
+ name: 'apcore.module.execute',
131
+ startTime: performance.now(),
132
+ parentSpanId,
133
+ attributes: {
134
+ moduleId,
135
+ method: 'execute',
136
+ callerId: context.callerId,
137
+ },
138
+ });
139
+ spansStack.push(span);
140
+ return null;
141
+ }
142
+
143
+ override after(
144
+ moduleId: string,
145
+ _inputs: Record<string, unknown>,
146
+ _output: Record<string, unknown>,
147
+ context: Context,
148
+ ): null {
149
+ const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
150
+ if (spansStack.length === 0) return null;
151
+
152
+ const span = spansStack.pop()!;
153
+ span.endTime = performance.now();
154
+ span.status = 'ok';
155
+ span.attributes['duration_ms'] = span.endTime - span.startTime;
156
+ span.attributes['success'] = true;
157
+
158
+ if (context.data['_tracing_sampled']) {
159
+ this._exporter.export(span);
160
+ }
161
+ return null;
162
+ }
163
+
164
+ override onError(
165
+ moduleId: string,
166
+ _inputs: Record<string, unknown>,
167
+ error: Error,
168
+ context: Context,
169
+ ): null {
170
+ const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
171
+ if (spansStack.length === 0) return null;
172
+
173
+ const span = spansStack.pop()!;
174
+ span.endTime = performance.now();
175
+ span.status = 'error';
176
+ span.attributes['duration_ms'] = span.endTime - span.startTime;
177
+ span.attributes['success'] = false;
178
+ span.attributes['error_code'] = (error as unknown as Record<string, unknown>)['code'] ?? error.constructor.name;
179
+
180
+ const shouldExport =
181
+ this._samplingStrategy === 'error_first' || context.data['_tracing_sampled'];
182
+ if (shouldExport) {
183
+ this._exporter.export(span);
184
+ }
185
+ return null;
186
+ }
187
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Dependency resolution via Kahn's topological sort.
3
+ */
4
+
5
+ import { CircularDependencyError, ModuleLoadError } from '../errors.js';
6
+ import type { DependencyInfo } from './types.js';
7
+
8
+ export function resolveDependencies(
9
+ modules: Array<[string, DependencyInfo[]]>,
10
+ knownIds?: Set<string> | null,
11
+ ): string[] {
12
+ if (modules.length === 0) return [];
13
+
14
+ const ids = knownIds ?? new Set(modules.map(([id]) => id));
15
+
16
+ // Build graph and in-degree
17
+ const graph = new Map<string, Set<string>>();
18
+ const inDegree = new Map<string, number>();
19
+
20
+ for (const [modId] of modules) {
21
+ inDegree.set(modId, 0);
22
+ }
23
+
24
+ for (const [moduleId, deps] of modules) {
25
+ for (const dep of deps) {
26
+ if (!ids.has(dep.moduleId)) {
27
+ if (dep.optional) continue;
28
+ throw new ModuleLoadError(moduleId, `Required dependency '${dep.moduleId}' not found`);
29
+ }
30
+ if (!graph.has(dep.moduleId)) graph.set(dep.moduleId, new Set());
31
+ graph.get(dep.moduleId)!.add(moduleId);
32
+ inDegree.set(moduleId, (inDegree.get(moduleId) ?? 0) + 1);
33
+ }
34
+ }
35
+
36
+ // Initialize queue with zero-in-degree nodes (sorted for determinism)
37
+ const queue: string[] = [...inDegree.entries()]
38
+ .filter(([, deg]) => deg === 0)
39
+ .map(([id]) => id)
40
+ .sort();
41
+
42
+ const loadOrder: string[] = [];
43
+ while (queue.length > 0) {
44
+ const modId = queue.shift()!;
45
+ loadOrder.push(modId);
46
+ const dependents = graph.get(modId);
47
+ if (dependents) {
48
+ for (const dependent of [...dependents].sort()) {
49
+ const newDeg = (inDegree.get(dependent) ?? 1) - 1;
50
+ inDegree.set(dependent, newDeg);
51
+ if (newDeg === 0) {
52
+ queue.push(dependent);
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ // Check for cycles
59
+ if (loadOrder.length < modules.length) {
60
+ const ordered = new Set(loadOrder);
61
+ const remaining = new Set(modules.filter(([id]) => !ordered.has(id)).map(([id]) => id));
62
+ const cyclePath = extractCycle(modules, remaining);
63
+ throw new CircularDependencyError(cyclePath);
64
+ }
65
+
66
+ return loadOrder;
67
+ }
68
+
69
+ function extractCycle(
70
+ modules: Array<[string, DependencyInfo[]]>,
71
+ remaining: Set<string>,
72
+ ): string[] {
73
+ const depMap = new Map<string, string[]>();
74
+ for (const [modId, deps] of modules) {
75
+ if (remaining.has(modId)) {
76
+ depMap.set(modId, deps.filter((d) => remaining.has(d.moduleId)).map((d) => d.moduleId));
77
+ }
78
+ }
79
+
80
+ const start = remaining.values().next().value as string;
81
+ const visited: string[] = [start];
82
+ const visitedSet = new Set([start]);
83
+ let current = start;
84
+
85
+ while (true) {
86
+ const nexts = depMap.get(current) ?? [];
87
+ if (nexts.length === 0) break;
88
+ const nxt = nexts[0];
89
+ if (visitedSet.has(nxt)) {
90
+ const idx = visited.indexOf(nxt);
91
+ return [...visited.slice(idx), nxt];
92
+ }
93
+ visited.push(nxt);
94
+ visitedSet.add(nxt);
95
+ current = nxt;
96
+ }
97
+
98
+ return [...remaining, remaining.values().next().value as string];
99
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Entry point resolution for discovered module files.
3
+ */
4
+
5
+ import { ModuleLoadError } from '../errors.js';
6
+ import { validateModule } from './validation.js';
7
+
8
+ export function snakeToPascal(name: string): string {
9
+ if (!name) return '';
10
+ return name.split('_').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');
11
+ }
12
+
13
+ function isModuleClass(obj: unknown): boolean {
14
+ if (typeof obj !== 'object' || obj === null) return false;
15
+ const record = obj as Record<string, unknown>;
16
+ return (
17
+ record['inputSchema'] != null &&
18
+ typeof record['inputSchema'] === 'object' &&
19
+ record['outputSchema'] != null &&
20
+ typeof record['outputSchema'] === 'object' &&
21
+ typeof record['description'] === 'string' &&
22
+ typeof record['execute'] === 'function'
23
+ );
24
+ }
25
+
26
+ export async function resolveEntryPoint(
27
+ filePath: string,
28
+ meta?: Record<string, unknown> | null,
29
+ ): Promise<unknown> {
30
+ let loaded: Record<string, unknown>;
31
+ try {
32
+ loaded = await import(filePath);
33
+ } catch (e) {
34
+ throw new ModuleLoadError(filePath, `Failed to import module: ${e}`);
35
+ }
36
+
37
+ // Meta override mode
38
+ if (meta && 'entry_point' in meta) {
39
+ const className = (meta['entry_point'] as string).split(':').pop()!;
40
+ const cls = loaded[className];
41
+ if (cls == null) {
42
+ throw new ModuleLoadError(filePath, `Entry point class '${className}' not found`);
43
+ }
44
+ return cls;
45
+ }
46
+
47
+ // Auto-infer: look for default export first, then named exports
48
+ if (loaded['default'] && isModuleClass(loaded['default'])) {
49
+ return loaded['default'];
50
+ }
51
+
52
+ const candidates: unknown[] = [];
53
+ for (const [, value] of Object.entries(loaded)) {
54
+ if (isModuleClass(value)) {
55
+ candidates.push(value);
56
+ }
57
+ }
58
+
59
+ if (candidates.length === 1) return candidates[0];
60
+ if (candidates.length === 0) {
61
+ throw new ModuleLoadError(filePath, 'No Module subclass found in file');
62
+ }
63
+ throw new ModuleLoadError(filePath, 'Ambiguous entry point: multiple Module subclasses found');
64
+ }
@@ -0,0 +1,8 @@
1
+ export { Registry } from './registry.js';
2
+ export type { ModuleDescriptor, DiscoveredModule, DependencyInfo } from './types.js';
3
+ export { validateModule } from './validation.js';
4
+ export { resolveDependencies } from './dependencies.js';
5
+ export { scanExtensions, scanMultiRoot } from './scanner.js';
6
+ export { resolveEntryPoint, snakeToPascal } from './entry-point.js';
7
+ export { loadMetadata, parseDependencies, mergeModuleMetadata, loadIdMap } from './metadata.js';
8
+ export { getSchema, exportSchema, getAllSchemas, exportAllSchemas } from './schema-export.js';
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Metadata and ID map loading for the registry system.
3
+ */
4
+
5
+ import { readFileSync, existsSync } from 'node:fs';
6
+ import yaml from 'js-yaml';
7
+ import { ConfigError, ConfigNotFoundError } from '../errors.js';
8
+ import type { DependencyInfo } from './types.js';
9
+
10
+ export function loadMetadata(metaPath: string): Record<string, unknown> {
11
+ if (!existsSync(metaPath)) return {};
12
+
13
+ const content = readFileSync(metaPath, 'utf-8');
14
+ let parsed: unknown;
15
+ try {
16
+ parsed = yaml.load(content);
17
+ } catch (e) {
18
+ throw new ConfigError(`Invalid YAML in metadata file: ${metaPath}`);
19
+ }
20
+
21
+ if (parsed === null || parsed === undefined) return {};
22
+ if (typeof parsed !== 'object' || Array.isArray(parsed)) {
23
+ throw new ConfigError(`Metadata file must be a YAML mapping: ${metaPath}`);
24
+ }
25
+
26
+ return parsed as Record<string, unknown>;
27
+ }
28
+
29
+ export function parseDependencies(depsRaw: Array<Record<string, unknown>>): DependencyInfo[] {
30
+ if (!depsRaw || depsRaw.length === 0) return [];
31
+
32
+ const result: DependencyInfo[] = [];
33
+ for (const dep of depsRaw) {
34
+ const moduleId = dep['module_id'] as string | undefined;
35
+ if (!moduleId) {
36
+ console.warn(`[apcore:metadata] Dependency entry missing 'module_id', skipping`);
37
+ continue;
38
+ }
39
+ result.push({
40
+ moduleId,
41
+ version: (dep['version'] as string) ?? null,
42
+ optional: (dep['optional'] as boolean) ?? false,
43
+ });
44
+ }
45
+ return result;
46
+ }
47
+
48
+ export function mergeModuleMetadata(
49
+ moduleObj: Record<string, unknown>,
50
+ meta: Record<string, unknown>,
51
+ ): Record<string, unknown> {
52
+ const codeDesc = (moduleObj['description'] as string) ?? '';
53
+ const codeName = (moduleObj['name'] as string) ?? null;
54
+ const codeTags = (moduleObj['tags'] as string[]) ?? [];
55
+ const codeVersion = (moduleObj['version'] as string) ?? '1.0.0';
56
+ const codeAnnotations = moduleObj['annotations'] ?? null;
57
+ const codeExamples = (moduleObj['examples'] as unknown[]) ?? [];
58
+ const codeMetadata = (moduleObj['metadata'] as Record<string, unknown>) ?? {};
59
+ const codeDocs = (moduleObj['documentation'] as string) ?? null;
60
+
61
+ const yamlMetadata = (meta['metadata'] as Record<string, unknown>) ?? {};
62
+ const mergedMetadata = { ...codeMetadata, ...yamlMetadata };
63
+
64
+ return {
65
+ description: (meta['description'] as string) || codeDesc,
66
+ name: (meta['name'] as string) || codeName,
67
+ tags: meta['tags'] != null ? meta['tags'] : codeTags || [],
68
+ version: (meta['version'] as string) || codeVersion,
69
+ annotations: meta['annotations'] != null ? meta['annotations'] : codeAnnotations,
70
+ examples: meta['examples'] != null ? meta['examples'] : codeExamples || [],
71
+ metadata: mergedMetadata,
72
+ documentation: (meta['documentation'] as string) || codeDocs,
73
+ };
74
+ }
75
+
76
+ export function loadIdMap(idMapPath: string): Record<string, Record<string, unknown>> {
77
+ if (!existsSync(idMapPath)) {
78
+ throw new ConfigNotFoundError(idMapPath);
79
+ }
80
+
81
+ const content = readFileSync(idMapPath, 'utf-8');
82
+ let parsed: unknown;
83
+ try {
84
+ parsed = yaml.load(content);
85
+ } catch (e) {
86
+ throw new ConfigError(`Invalid YAML in ID map file: ${idMapPath}`);
87
+ }
88
+
89
+ if (typeof parsed !== 'object' || parsed === null || !('mappings' in (parsed as Record<string, unknown>))) {
90
+ throw new ConfigError("ID map must contain a 'mappings' list");
91
+ }
92
+
93
+ const mappings = (parsed as Record<string, unknown>)['mappings'];
94
+ if (!Array.isArray(mappings)) {
95
+ throw new ConfigError("ID map must contain a 'mappings' list");
96
+ }
97
+
98
+ const result: Record<string, Record<string, unknown>> = {};
99
+ for (const entry of mappings) {
100
+ const filePath = (entry as Record<string, unknown>)['file'] as string;
101
+ if (!filePath) {
102
+ console.warn(`[apcore:metadata] ID map entry missing 'file' field, skipping`);
103
+ continue;
104
+ }
105
+ result[filePath] = {
106
+ id: ((entry as Record<string, unknown>)['id'] as string) ?? filePath,
107
+ class: (entry as Record<string, unknown>)['class'] ?? null,
108
+ };
109
+ }
110
+ return result;
111
+ }