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,268 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Type } from '@sinclair/typebox';
3
+ import { Executor } from '../../src/executor.js';
4
+ import { FunctionModule } from '../../src/decorator.js';
5
+ import { Registry } from '../../src/registry/registry.js';
6
+ import { ACL } from '../../src/acl.js';
7
+ import { Context, createIdentity } from '../../src/context.js';
8
+ import { Config } from '../../src/config.js';
9
+ import {
10
+ ACLDeniedError,
11
+ CallDepthExceededError,
12
+ CallFrequencyExceededError,
13
+ CircularCallError,
14
+ } from '../../src/errors.js';
15
+
16
+ function makeModule(id: string, fn?: (inputs: Record<string, unknown>, ctx: Context) => Record<string, unknown> | Promise<Record<string, unknown>>): FunctionModule {
17
+ return new FunctionModule({
18
+ execute: fn ?? (() => ({ value: 'ok' })),
19
+ moduleId: id,
20
+ inputSchema: Type.Object({}),
21
+ outputSchema: Type.Object({ value: Type.String() }),
22
+ description: `Module ${id}`,
23
+ });
24
+ }
25
+
26
+ describe('ACL Integration', () => {
27
+ it('wildcard pattern allows matching modules', async () => {
28
+ const registry = new Registry();
29
+ registry.register('math.add', new FunctionModule({
30
+ execute: (inputs) => ({ result: (inputs['a'] as number) + (inputs['b'] as number) }),
31
+ moduleId: 'math.add',
32
+ inputSchema: Type.Object({ a: Type.Number(), b: Type.Number() }),
33
+ outputSchema: Type.Object({ result: Type.Number() }),
34
+ description: 'Add two numbers',
35
+ }));
36
+ registry.register('io.read', makeModule('io.read'));
37
+
38
+ const acl = new ACL([
39
+ { callers: ['*'], targets: ['math.*'], effect: 'allow', description: 'Allow math' },
40
+ ], 'deny');
41
+
42
+ const executor = new Executor({ registry, acl });
43
+
44
+ const result = await executor.call('math.add', { a: 2, b: 3 });
45
+ expect(result['result']).toBe(5);
46
+
47
+ await expect(executor.call('io.read', {})).rejects.toThrow(ACLDeniedError);
48
+ });
49
+
50
+ it('external caller denied by default', async () => {
51
+ const registry = new Registry();
52
+ registry.register('test.mod', makeModule('test.mod'));
53
+
54
+ const acl = new ACL([], 'deny');
55
+ const executor = new Executor({ registry, acl });
56
+
57
+ // No context = null caller = @external
58
+ await expect(executor.call('test.mod', {})).rejects.toThrow(ACLDeniedError);
59
+ });
60
+
61
+ it('system identity type allowed via conditions', async () => {
62
+ const registry = new Registry();
63
+ registry.register('test.mod', makeModule('test.mod'));
64
+
65
+ const acl = new ACL([
66
+ {
67
+ callers: ['*'],
68
+ targets: ['*'],
69
+ effect: 'allow',
70
+ description: 'Allow system identity',
71
+ conditions: { identity_types: ['system'] },
72
+ },
73
+ ], 'deny');
74
+
75
+ const executor = new Executor({ registry, acl });
76
+
77
+ // System identity - allowed
78
+ const sysCtx = Context.create(executor, createIdentity('sys', 'system'));
79
+ const result = await executor.call('test.mod', {}, sysCtx);
80
+ expect(result['value']).toBe('ok');
81
+
82
+ // User identity - denied
83
+ const userCtx = Context.create(executor, createIdentity('user1', 'user'));
84
+ await expect(executor.call('test.mod', {}, userCtx)).rejects.toThrow(ACLDeniedError);
85
+ });
86
+
87
+ it('role-based conditions', async () => {
88
+ const registry = new Registry();
89
+ registry.register('test.mod', makeModule('test.mod'));
90
+
91
+ const acl = new ACL([
92
+ {
93
+ callers: ['*'],
94
+ targets: ['*'],
95
+ effect: 'allow',
96
+ description: 'Allow admin role',
97
+ conditions: { roles: ['admin'] },
98
+ },
99
+ ], 'deny');
100
+
101
+ const executor = new Executor({ registry, acl });
102
+
103
+ // Admin role - allowed
104
+ const adminCtx = Context.create(executor, createIdentity('admin1', 'user', ['admin']));
105
+ const result = await executor.call('test.mod', {}, adminCtx);
106
+ expect(result['value']).toBe('ok');
107
+
108
+ // Viewer role - denied
109
+ const viewerCtx = Context.create(executor, createIdentity('viewer1', 'user', ['viewer']));
110
+ await expect(executor.call('test.mod', {}, viewerCtx)).rejects.toThrow(ACLDeniedError);
111
+ });
112
+
113
+ it('max call depth condition in ACL', async () => {
114
+ const registry = new Registry();
115
+ registry.register('test.mod', makeModule('test.mod'));
116
+
117
+ const acl = new ACL([
118
+ {
119
+ callers: ['*'],
120
+ targets: ['*'],
121
+ effect: 'allow',
122
+ description: 'Allow up to depth 2',
123
+ conditions: { max_call_depth: 2 },
124
+ },
125
+ ], 'deny');
126
+
127
+ const executor = new Executor({ registry, acl });
128
+
129
+ // Shallow call - allowed
130
+ const ctx = Context.create(executor);
131
+ const result = await executor.call('test.mod', {}, ctx);
132
+ expect(result['value']).toBe('ok');
133
+
134
+ // Deep call chain (depth > 2) - denied by ACL condition
135
+ const deepCtx = new Context(
136
+ crypto.randomUUID(),
137
+ 'caller1',
138
+ ['mod1', 'mod2', 'mod3'],
139
+ executor,
140
+ null,
141
+ null,
142
+ {},
143
+ );
144
+ await expect(executor.call('test.mod', {}, deepCtx)).rejects.toThrow(ACLDeniedError);
145
+ });
146
+
147
+ it('multiple rules: first match wins', async () => {
148
+ const registry = new Registry();
149
+ registry.register('secret.data', makeModule('secret.data'));
150
+ registry.register('public.data', makeModule('public.data'));
151
+
152
+ const acl = new ACL([
153
+ { callers: ['*'], targets: ['secret.*'], effect: 'deny', description: 'Deny secret' },
154
+ { callers: ['*'], targets: ['*'], effect: 'allow', description: 'Allow rest' },
155
+ ], 'deny');
156
+
157
+ const executor = new Executor({ registry, acl });
158
+
159
+ await expect(executor.call('secret.data', {})).rejects.toThrow(ACLDeniedError);
160
+
161
+ const result = await executor.call('public.data', {});
162
+ expect(result['value']).toBe('ok');
163
+ });
164
+
165
+ it('addRule inserts at front and takes precedence', async () => {
166
+ const registry = new Registry();
167
+ registry.register('test.mod', makeModule('test.mod'));
168
+
169
+ const acl = new ACL([
170
+ { callers: ['*'], targets: ['*'], effect: 'deny', description: 'Deny all' },
171
+ ], 'deny');
172
+
173
+ const executor = new Executor({ registry, acl });
174
+
175
+ // Initially denied
176
+ await expect(executor.call('test.mod', {})).rejects.toThrow(ACLDeniedError);
177
+
178
+ // Add allow rule at front
179
+ acl.addRule({
180
+ callers: ['*'],
181
+ targets: ['test.mod'],
182
+ effect: 'allow',
183
+ description: 'Allow test.mod',
184
+ });
185
+
186
+ // Now allowed
187
+ const result = await executor.call('test.mod', {});
188
+ expect(result['value']).toBe('ok');
189
+ });
190
+ });
191
+
192
+ describe('Safety Checks', () => {
193
+ it('call depth exceeded', async () => {
194
+ const registry = new Registry();
195
+ registry.register('mod.recursive', new FunctionModule({
196
+ execute: async (inputs: Record<string, unknown>, context: Context) => {
197
+ const depth = inputs['depth'] as number;
198
+ if (depth > 0) {
199
+ const exec = context.executor as Executor;
200
+ return await exec.call('mod.recursive', { depth: depth - 1 }, context);
201
+ }
202
+ return { depth: 0 };
203
+ },
204
+ moduleId: 'mod.recursive',
205
+ inputSchema: Type.Object({ depth: Type.Number() }),
206
+ outputSchema: Type.Object({ depth: Type.Number() }),
207
+ description: 'Recursive module',
208
+ }));
209
+
210
+ const config = new Config({ executor: { max_call_depth: 3 } });
211
+ const executor = new Executor({ registry, config });
212
+
213
+ await expect(executor.call('mod.recursive', { depth: 10 })).rejects.toThrow(CallDepthExceededError);
214
+ });
215
+
216
+ it('circular call detection', async () => {
217
+ const registry = new Registry();
218
+
219
+ registry.register('mod.a', new FunctionModule({
220
+ execute: async (_inputs: Record<string, unknown>, context: Context) => {
221
+ const exec = context.executor as Executor;
222
+ return await exec.call('mod.b', {}, context);
223
+ },
224
+ moduleId: 'mod.a',
225
+ inputSchema: Type.Object({}),
226
+ outputSchema: Type.Object({ value: Type.String() }),
227
+ description: 'Module A',
228
+ }));
229
+
230
+ registry.register('mod.b', new FunctionModule({
231
+ execute: async (_inputs: Record<string, unknown>, context: Context) => {
232
+ const exec = context.executor as Executor;
233
+ return await exec.call('mod.a', {}, context);
234
+ },
235
+ moduleId: 'mod.b',
236
+ inputSchema: Type.Object({}),
237
+ outputSchema: Type.Object({ value: Type.String() }),
238
+ description: 'Module B',
239
+ }));
240
+
241
+ const executor = new Executor({ registry });
242
+
243
+ await expect(executor.call('mod.a', {})).rejects.toThrow(CircularCallError);
244
+ });
245
+
246
+ it('call frequency exceeded', async () => {
247
+ const registry = new Registry();
248
+ registry.register('mod.freq', new FunctionModule({
249
+ execute: async (inputs: Record<string, unknown>, context: Context) => {
250
+ const count = inputs['count'] as number;
251
+ if (count > 0) {
252
+ const exec = context.executor as Executor;
253
+ return await exec.call('mod.freq', { count: count - 1 }, context);
254
+ }
255
+ return { count: 0 };
256
+ },
257
+ moduleId: 'mod.freq',
258
+ inputSchema: Type.Object({ count: Type.Number() }),
259
+ outputSchema: Type.Object({ count: Type.Number() }),
260
+ description: 'Frequent module',
261
+ }));
262
+
263
+ const config = new Config({ executor: { max_module_repeat: 2 } });
264
+ const executor = new Executor({ registry, config });
265
+
266
+ await expect(executor.call('mod.freq', { count: 5 })).rejects.toThrow(CallFrequencyExceededError);
267
+ });
268
+ });
@@ -0,0 +1,194 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+ import { Type } from '@sinclair/typebox';
6
+ import { BindingLoader } from '../../src/bindings.js';
7
+ import { Registry } from '../../src/registry/registry.js';
8
+ import { Executor } from '../../src/executor.js';
9
+ import { FunctionModule } from '../../src/decorator.js';
10
+ import { Context, createIdentity } from '../../src/context.js';
11
+ import { InMemoryExporter, TracingMiddleware } from '../../src/observability/tracing.js';
12
+ import { MetricsCollector, MetricsMiddleware } from '../../src/observability/metrics.js';
13
+
14
+ let tmpDir: string;
15
+ let registry: Registry;
16
+ let loader: BindingLoader;
17
+
18
+ beforeEach(() => {
19
+ tmpDir = mkdtempSync(join(tmpdir(), 'binding-executor-test-'));
20
+ registry = new Registry();
21
+ loader = new BindingLoader();
22
+ });
23
+
24
+ afterEach(() => {
25
+ rmSync(tmpDir, { recursive: true, force: true });
26
+ });
27
+
28
+ function writeTempModule(filename: string, content: string): string {
29
+ const filePath = join(tmpDir, filename);
30
+ writeFileSync(filePath, content, 'utf-8');
31
+ return filePath;
32
+ }
33
+
34
+ function writeTempYaml(filename: string, content: string): string {
35
+ const filePath = join(tmpDir, filename);
36
+ writeFileSync(filePath, content, 'utf-8');
37
+ return filePath;
38
+ }
39
+
40
+ describe('Binding + Registry + Executor', () => {
41
+ it('loads binding and executes through executor', async () => {
42
+ const modPath = writeTempModule(
43
+ 'greet.mjs',
44
+ 'export function greet(inputs) { return { greeting: "Hello, " + inputs.name }; }\n',
45
+ );
46
+ const yamlPath = writeTempYaml(
47
+ 'greet.binding.yaml',
48
+ `bindings:\n - module_id: "test.greet"\n target: "${modPath}:greet"\n description: "Greet module"\n`,
49
+ );
50
+
51
+ await loader.loadBindings(yamlPath, registry);
52
+ expect(registry.has('test.greet')).toBe(true);
53
+
54
+ const executor = new Executor({ registry });
55
+ const result = await executor.call('test.greet', { name: 'World' });
56
+ expect(result['greeting']).toBe('Hello, World');
57
+ });
58
+
59
+ it('binding with inline schemas validates inputs', async () => {
60
+ const modPath = writeTempModule(
61
+ 'validated.mjs',
62
+ 'export function handle(inputs) { return { result: inputs.name }; }\n',
63
+ );
64
+ const yamlPath = writeTempYaml(
65
+ 'validated.binding.yaml',
66
+ `bindings:\n - module_id: "test.validated"\n target: "${modPath}:handle"\n input_schema:\n type: object\n properties:\n name:\n type: string\n required:\n - name\n`,
67
+ );
68
+
69
+ await loader.loadBindings(yamlPath, registry);
70
+ const executor = new Executor({ registry });
71
+
72
+ // Valid input succeeds
73
+ const result = await executor.call('test.validated', { name: 'Alice' });
74
+ expect(result['result']).toBe('Alice');
75
+
76
+ // Invalid input fails (number instead of string)
77
+ await expect(executor.call('test.validated', { name: 123 })).rejects.toThrow();
78
+ });
79
+
80
+ it('loads multiple bindings from directory and executes all', async () => {
81
+ const modPath = writeTempModule(
82
+ 'multi.mjs',
83
+ 'export function alpha() { return { id: "alpha" }; }\nexport function beta() { return { id: "beta" }; }\n',
84
+ );
85
+
86
+ writeTempYaml(
87
+ 'alpha.binding.yaml',
88
+ `bindings:\n - module_id: "dir.alpha"\n target: "${modPath}:alpha"\n`,
89
+ );
90
+ writeTempYaml(
91
+ 'beta.binding.yaml',
92
+ `bindings:\n - module_id: "dir.beta"\n target: "${modPath}:beta"\n`,
93
+ );
94
+
95
+ await loader.loadBindingDir(tmpDir, registry);
96
+ expect(registry.has('dir.alpha')).toBe(true);
97
+ expect(registry.has('dir.beta')).toBe(true);
98
+
99
+ const executor = new Executor({ registry });
100
+
101
+ const r1 = await executor.call('dir.alpha', {});
102
+ expect(r1['id']).toBe('alpha');
103
+
104
+ const r2 = await executor.call('dir.beta', {});
105
+ expect(r2['id']).toBe('beta');
106
+ });
107
+
108
+ it('binding module with tracing and metrics', async () => {
109
+ const modPath = writeTempModule(
110
+ 'traced.mjs',
111
+ 'export function handler(inputs) { return { ok: true }; }\n',
112
+ );
113
+ const yamlPath = writeTempYaml(
114
+ 'traced.binding.yaml',
115
+ `bindings:\n - module_id: "test.traced"\n target: "${modPath}:handler"\n`,
116
+ );
117
+
118
+ await loader.loadBindings(yamlPath, registry);
119
+
120
+ const exporter = new InMemoryExporter();
121
+ const metrics = new MetricsCollector();
122
+ const executor = new Executor({
123
+ registry,
124
+ middlewares: [new TracingMiddleware(exporter), new MetricsMiddleware(metrics)],
125
+ });
126
+
127
+ const result = await executor.call('test.traced', {});
128
+ expect(result['ok']).toBe(true);
129
+
130
+ // Verify span exported
131
+ const spans = exporter.getSpans();
132
+ expect(spans).toHaveLength(1);
133
+ expect(spans[0].status).toBe('ok');
134
+ expect(spans[0].attributes['moduleId']).toBe('test.traced');
135
+
136
+ // Verify metrics recorded
137
+ const snap = metrics.snapshot();
138
+ const counters = snap['counters'] as Record<string, number>;
139
+ expect(counters['apcore_module_calls_total|module_id=test.traced,status=success']).toBe(1);
140
+ });
141
+
142
+ it('binding module receives context with identity', async () => {
143
+ const modPath = writeTempModule(
144
+ 'ctx_aware.mjs',
145
+ 'export function handle(inputs, context) { return { callerId: context?.callerId ?? "none", hasIdentity: context?.identity != null }; }\n',
146
+ );
147
+ const yamlPath = writeTempYaml(
148
+ 'ctx.binding.yaml',
149
+ `bindings:\n - module_id: "test.ctx"\n target: "${modPath}:handle"\n`,
150
+ );
151
+
152
+ await loader.loadBindings(yamlPath, registry);
153
+
154
+ const executor = new Executor({ registry });
155
+ const identity = createIdentity('user123', 'user', ['admin']);
156
+ const ctx = Context.create(executor, identity);
157
+
158
+ const result = await executor.call('test.ctx', {}, ctx);
159
+ expect(result['hasIdentity']).toBe(true);
160
+ });
161
+
162
+ it('mixed bindings and FunctionModule in same registry', async () => {
163
+ // Register FunctionModule directly
164
+ registry.register('direct.add', new FunctionModule({
165
+ execute: (inputs) => ({ sum: (inputs['a'] as number) + (inputs['b'] as number) }),
166
+ moduleId: 'direct.add',
167
+ inputSchema: Type.Object({ a: Type.Number(), b: Type.Number() }),
168
+ outputSchema: Type.Object({ sum: Type.Number() }),
169
+ description: 'Direct add',
170
+ }));
171
+
172
+ // Load binding
173
+ const modPath = writeTempModule(
174
+ 'multiply.mjs',
175
+ 'export function multiply(inputs) { return { product: inputs.a * inputs.b }; }\n',
176
+ );
177
+ const yamlPath = writeTempYaml(
178
+ 'multiply.binding.yaml',
179
+ `bindings:\n - module_id: "binding.multiply"\n target: "${modPath}:multiply"\n`,
180
+ );
181
+ await loader.loadBindings(yamlPath, registry);
182
+
183
+ expect(registry.has('direct.add')).toBe(true);
184
+ expect(registry.has('binding.multiply')).toBe(true);
185
+
186
+ const executor = new Executor({ registry });
187
+
188
+ const addResult = await executor.call('direct.add', { a: 5, b: 3 });
189
+ expect(addResult['sum']).toBe(8);
190
+
191
+ const mulResult = await executor.call('binding.multiply', { a: 5, b: 3 });
192
+ expect(mulResult['product']).toBe(15);
193
+ });
194
+ });
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Type } from '@sinclair/typebox';
3
+ import { Context, createIdentity } from '../../src/context.js';
4
+ import { Executor } from '../../src/executor.js';
5
+ import { FunctionModule } from '../../src/decorator.js';
6
+ import { Registry } from '../../src/registry/registry.js';
7
+ import { ACL } from '../../src/acl.js';
8
+ import { Middleware } from '../../src/middleware/base.js';
9
+ import { MetricsCollector, MetricsMiddleware } from '../../src/observability/metrics.js';
10
+ import { InMemoryExporter, TracingMiddleware } from '../../src/observability/tracing.js';
11
+
12
+ describe('E2E Flow', () => {
13
+ it('full pipeline: register, execute, collect metrics', async () => {
14
+ const registry = new Registry();
15
+ const greet = new FunctionModule({
16
+ execute: (inputs) => ({ greeting: `Hello, ${inputs['name']}!` }),
17
+ moduleId: 'example.greet',
18
+ inputSchema: Type.Object({ name: Type.String() }),
19
+ outputSchema: Type.Object({ greeting: Type.String() }),
20
+ description: 'Greet a user',
21
+ });
22
+ registry.register('example.greet', greet);
23
+
24
+ const metrics = new MetricsCollector();
25
+ const exporter = new InMemoryExporter();
26
+ const executor = new Executor({
27
+ registry,
28
+ middlewares: [
29
+ new MetricsMiddleware(metrics),
30
+ new TracingMiddleware(exporter),
31
+ ],
32
+ });
33
+
34
+ const result = await executor.call('example.greet', { name: 'World' });
35
+ expect(result['greeting']).toBe('Hello, World!');
36
+
37
+ const snap = metrics.snapshot();
38
+ const counters = snap['counters'] as Record<string, number>;
39
+ expect(counters['apcore_module_calls_total|module_id=example.greet,status=success']).toBe(1);
40
+
41
+ const spans = exporter.getSpans();
42
+ expect(spans).toHaveLength(1);
43
+ expect(spans[0].status).toBe('ok');
44
+ });
45
+
46
+ it('ACL deny blocks execution', async () => {
47
+ const registry = new Registry();
48
+ registry.register('secret', new FunctionModule({
49
+ execute: () => ({ data: 'classified' }),
50
+ moduleId: 'secret',
51
+ inputSchema: Type.Object({}),
52
+ outputSchema: Type.Object({ data: Type.String() }),
53
+ description: 'Secret module',
54
+ }));
55
+
56
+ const acl = new ACL([
57
+ { callers: ['@external'], targets: ['secret'], effect: 'deny', description: 'block externals' },
58
+ ], 'deny');
59
+
60
+ const executor = new Executor({ registry, acl });
61
+ await expect(executor.call('secret')).rejects.toThrow();
62
+ });
63
+
64
+ it('multiple module calls with context chaining', async () => {
65
+ const registry = new Registry();
66
+ const modA = new FunctionModule({
67
+ execute: (inputs) => ({ value: (inputs['x'] as number) * 2 }),
68
+ moduleId: 'math.double',
69
+ inputSchema: Type.Object({ x: Type.Number() }),
70
+ outputSchema: Type.Object({ value: Type.Number() }),
71
+ description: 'Double a number',
72
+ });
73
+ const modB = new FunctionModule({
74
+ execute: (inputs) => ({ value: (inputs['x'] as number) + 10 }),
75
+ moduleId: 'math.addTen',
76
+ inputSchema: Type.Object({ x: Type.Number() }),
77
+ outputSchema: Type.Object({ value: Type.Number() }),
78
+ description: 'Add ten',
79
+ });
80
+ registry.register('math.double', modA);
81
+ registry.register('math.addTen', modB);
82
+
83
+ const executor = new Executor({ registry });
84
+ const ctx = Context.create(executor, createIdentity('test-user'));
85
+
86
+ const r1 = await executor.call('math.double', { x: 5 }, ctx);
87
+ expect(r1['value']).toBe(10);
88
+
89
+ const r2 = await executor.call('math.addTen', { x: r1['value'] as number }, ctx);
90
+ expect(r2['value']).toBe(20);
91
+ });
92
+
93
+ it('middleware intercepts and transforms', async () => {
94
+ const registry = new Registry();
95
+ registry.register('echo', new FunctionModule({
96
+ execute: (inputs) => ({ echo: inputs['msg'] }),
97
+ moduleId: 'echo',
98
+ inputSchema: Type.Object({ msg: Type.String() }),
99
+ outputSchema: Type.Object({ echo: Type.String() }),
100
+ description: 'Echo back',
101
+ }));
102
+
103
+ class UppercaseMiddleware extends Middleware {
104
+ override after(
105
+ _moduleId: string,
106
+ _inputs: Record<string, unknown>,
107
+ output: Record<string, unknown>,
108
+ ): Record<string, unknown> {
109
+ return { echo: (output['echo'] as string).toUpperCase() };
110
+ }
111
+ }
112
+
113
+ const executor = new Executor({ registry, middlewares: [new UppercaseMiddleware()] });
114
+ const result = await executor.call('echo', { msg: 'hello' });
115
+ expect(result['echo']).toBe('HELLO');
116
+ });
117
+ });