@camstack/server 0.1.3

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 (133) hide show
  1. package/.env.example +17 -0
  2. package/package.json +55 -0
  3. package/src/__tests__/addon-install-e2e.test.ts +75 -0
  4. package/src/__tests__/addon-pages-e2e.test.ts +178 -0
  5. package/src/__tests__/addon-route-session.test.ts +17 -0
  6. package/src/__tests__/addon-settings-router.spec.ts +62 -0
  7. package/src/__tests__/addon-upload.spec.ts +355 -0
  8. package/src/__tests__/agent-registry.spec.ts +162 -0
  9. package/src/__tests__/agent-status-page.spec.ts +84 -0
  10. package/src/__tests__/auth-session-cookie.test.ts +21 -0
  11. package/src/__tests__/cap-providers/cap-usage-graph.spec.ts +23 -0
  12. package/src/__tests__/cap-providers/compute-topology-categories.spec.ts +64 -0
  13. package/src/__tests__/cap-routers/_meta.spec.ts +200 -0
  14. package/src/__tests__/cap-routers/addon-settings.router.spec.ts +106 -0
  15. package/src/__tests__/cap-routers/device-manager-aggregate.router.spec.ts +142 -0
  16. package/src/__tests__/cap-routers/harness.ts +159 -0
  17. package/src/__tests__/cap-routers/metrics-provider.router.spec.ts +119 -0
  18. package/src/__tests__/cap-routers/null-provider-guard.spec.ts +66 -0
  19. package/src/__tests__/cap-routers/pipeline-executor.router.spec.ts +135 -0
  20. package/src/__tests__/cap-routers/settings-store.router.spec.ts +247 -0
  21. package/src/__tests__/capability-e2e.test.ts +386 -0
  22. package/src/__tests__/cli-e2e.test.ts +129 -0
  23. package/src/__tests__/core-cap-bridge.spec.ts +89 -0
  24. package/src/__tests__/embedded-deps-e2e.test.ts +109 -0
  25. package/src/__tests__/event-bus-proxy-router.spec.ts +72 -0
  26. package/src/__tests__/fixtures/mock-analysis-addon-a.ts +37 -0
  27. package/src/__tests__/fixtures/mock-analysis-addon-b.ts +37 -0
  28. package/src/__tests__/fixtures/mock-log-addon.ts +37 -0
  29. package/src/__tests__/fixtures/mock-storage-addon.ts +40 -0
  30. package/src/__tests__/framework-allowlist.spec.ts +95 -0
  31. package/src/__tests__/https-e2e.test.ts +118 -0
  32. package/src/__tests__/lifecycle-e2e.test.ts +140 -0
  33. package/src/__tests__/live-events-subscription.spec.ts +150 -0
  34. package/src/__tests__/moleculer-register-node-idempotency.spec.ts +229 -0
  35. package/src/__tests__/oauth2-account-linking.spec.ts +736 -0
  36. package/src/__tests__/post-boot-restart.spec.ts +161 -0
  37. package/src/__tests__/singleton-contention.test.ts +487 -0
  38. package/src/__tests__/streaming-diagnostic.test.ts +512 -0
  39. package/src/__tests__/streaming-scale.test.ts +280 -0
  40. package/src/agent-status-page.ts +121 -0
  41. package/src/api/__tests__/addons-custom.spec.ts +134 -0
  42. package/src/api/__tests__/capabilities.router.test.ts +47 -0
  43. package/src/api/addon-upload.ts +472 -0
  44. package/src/api/addons-custom.router.ts +100 -0
  45. package/src/api/auth-whoami.ts +99 -0
  46. package/src/api/bridge-addons.router.ts +120 -0
  47. package/src/api/capabilities.router.ts +226 -0
  48. package/src/api/core/__tests__/auth-router-totp.spec.ts +256 -0
  49. package/src/api/core/addon-settings.router.ts +124 -0
  50. package/src/api/core/agents.router.ts +87 -0
  51. package/src/api/core/auth.router.ts +303 -0
  52. package/src/api/core/cap-providers.ts +993 -0
  53. package/src/api/core/capabilities.router.ts +119 -0
  54. package/src/api/core/collection-preference.ts +40 -0
  55. package/src/api/core/event-bus-proxy.router.ts +45 -0
  56. package/src/api/core/hwaccel.router.ts +81 -0
  57. package/src/api/core/live-events.router.ts +60 -0
  58. package/src/api/core/logs.router.ts +162 -0
  59. package/src/api/core/notifications.router.ts +65 -0
  60. package/src/api/core/repl.router.ts +41 -0
  61. package/src/api/core/settings-backend.router.ts +142 -0
  62. package/src/api/core/stream-probe.router.ts +57 -0
  63. package/src/api/core/system-events.router.ts +116 -0
  64. package/src/api/health/health.routes.ts +123 -0
  65. package/src/api/oauth2/__tests__/oauth2-routes.spec.ts +52 -0
  66. package/src/api/oauth2/consent-page.ts +42 -0
  67. package/src/api/oauth2/oauth2-routes.ts +248 -0
  68. package/src/api/trpc/__tests__/scope-access-device.spec.ts +223 -0
  69. package/src/api/trpc/__tests__/scope-access.spec.ts +107 -0
  70. package/src/api/trpc/cap-mount-helpers.ts +225 -0
  71. package/src/api/trpc/core-cap-bridge.ts +152 -0
  72. package/src/api/trpc/generated-cap-mounts.ts +707 -0
  73. package/src/api/trpc/generated-cap-routers.ts +6340 -0
  74. package/src/api/trpc/scope-access.ts +110 -0
  75. package/src/api/trpc/trpc.context.ts +255 -0
  76. package/src/api/trpc/trpc.middleware.ts +140 -0
  77. package/src/api/trpc/trpc.router.ts +275 -0
  78. package/src/auth/session-cookie.ts +44 -0
  79. package/src/boot/boot-config.ts +278 -0
  80. package/src/boot/post-boot.service.ts +103 -0
  81. package/src/core/addon/__tests__/addon-registry-capability.test.ts +53 -0
  82. package/src/core/addon/addon-package.service.ts +1684 -0
  83. package/src/core/addon/addon-registry.service.ts +2926 -0
  84. package/src/core/addon/addon-search.service.ts +90 -0
  85. package/src/core/addon/addon-settings-provider.ts +276 -0
  86. package/src/core/addon/addon.tokens.ts +2 -0
  87. package/src/core/addon-bridge/addon-bridge.service.ts +125 -0
  88. package/src/core/addon-pages/addon-pages.service.spec.ts +117 -0
  89. package/src/core/addon-pages/addon-pages.service.ts +80 -0
  90. package/src/core/addon-widgets/addon-widgets.service.ts +92 -0
  91. package/src/core/agent/agent-registry.service.ts +507 -0
  92. package/src/core/auth/auth.service.spec.ts +88 -0
  93. package/src/core/auth/auth.service.ts +8 -0
  94. package/src/core/capability/capability.service.ts +57 -0
  95. package/src/core/config/config.schema.ts +3 -0
  96. package/src/core/config/config.service.spec.ts +175 -0
  97. package/src/core/config/config.service.ts +7 -0
  98. package/src/core/events/event-bus.service.spec.ts +212 -0
  99. package/src/core/events/event-bus.service.ts +85 -0
  100. package/src/core/feature/feature.service.spec.ts +96 -0
  101. package/src/core/feature/feature.service.ts +8 -0
  102. package/src/core/lifecycle/lifecycle-state-machine.spec.ts +168 -0
  103. package/src/core/lifecycle/lifecycle-state-machine.ts +3 -0
  104. package/src/core/logging/log-ring-buffer.ts +3 -0
  105. package/src/core/logging/logging.service.spec.ts +247 -0
  106. package/src/core/logging/logging.service.ts +129 -0
  107. package/src/core/logging/scoped-logger.ts +3 -0
  108. package/src/core/moleculer/moleculer.service.ts +612 -0
  109. package/src/core/network/network-quality.service.spec.ts +47 -0
  110. package/src/core/network/network-quality.service.ts +5 -0
  111. package/src/core/notification/notification-wrapper.service.ts +36 -0
  112. package/src/core/notification/toast-wrapper.service.ts +31 -0
  113. package/src/core/provider/provider.tokens.ts +1 -0
  114. package/src/core/repl/repl-engine.service.spec.ts +417 -0
  115. package/src/core/repl/repl-engine.service.ts +156 -0
  116. package/src/core/storage/fs-storage-backend.spec.ts +70 -0
  117. package/src/core/storage/fs-storage-backend.ts +3 -0
  118. package/src/core/storage/settings-store.spec.ts +213 -0
  119. package/src/core/storage/settings-store.ts +2 -0
  120. package/src/core/storage/sql-schema.spec.ts +140 -0
  121. package/src/core/storage/sql-schema.ts +3 -0
  122. package/src/core/storage/storage-location-manager.spec.ts +121 -0
  123. package/src/core/storage/storage-location-manager.ts +3 -0
  124. package/src/core/storage/storage.service.spec.ts +73 -0
  125. package/src/core/storage/storage.service.ts +3 -0
  126. package/src/core/streaming/stream-probe.service.ts +212 -0
  127. package/src/core/topology/topology-emitter.service.ts +101 -0
  128. package/src/launcher.ts +309 -0
  129. package/src/main.ts +1049 -0
  130. package/src/manual-boot.ts +322 -0
  131. package/tsconfig.build.json +8 -0
  132. package/tsconfig.json +21 -0
  133. package/vitest.config.ts +26 -0
@@ -0,0 +1,386 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -- test file, mock typing */
2
+ // server/backend/src/__tests__/capability-e2e.test.ts
3
+ //
4
+ // Server-level E2E tests: exercises the CapabilityRegistry through patterns
5
+ // matching the real AddonRegistryService boot flow, using mock addons.
6
+ //
7
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
8
+ import { CapabilityRegistry, INFRA_CAPABILITIES } from '@camstack/kernel'
9
+ import type { IScopedLogger, CapabilityDeclaration } from '@camstack/types'
10
+ import { MockAnalysisAddonA } from './fixtures/mock-analysis-addon-a'
11
+ import { MockAnalysisAddonB } from './fixtures/mock-analysis-addon-b'
12
+ import { MockLogAddon } from './fixtures/mock-log-addon'
13
+ import { MockStorageAddon } from './fixtures/mock-storage-addon'
14
+ import type { ICamstackAddon } from '@camstack/types'
15
+
16
+ // --- Helpers ----------------------------------------------------------------
17
+
18
+ function createMockLogger(): IScopedLogger {
19
+ return {
20
+ error: vi.fn(),
21
+ warn: vi.fn(),
22
+ info: vi.fn(),
23
+ debug: vi.fn(),
24
+ child: vi.fn().mockReturnThis(),
25
+ }
26
+ }
27
+
28
+ interface AddonEntry {
29
+ readonly addon: ICamstackAddon
30
+ initialized: boolean
31
+ }
32
+
33
+ /**
34
+ * Lightweight harness that mirrors AddonRegistryService boot sequence
35
+ * without requiring NestJS DI.
36
+ */
37
+ class TestAddonHarness {
38
+ readonly registry: CapabilityRegistry
39
+ private readonly addonEntries = new Map<string, AddonEntry>()
40
+
41
+ constructor(configPrefs: Record<string, string> = {}) {
42
+ this.registry = new CapabilityRegistry(createMockLogger())
43
+ this.registry.setConfigReader((cap) => configPrefs[cap])
44
+ this.registry.ready()
45
+ }
46
+
47
+ /** Register an addon (mimics AddonRegistryService.registerAddon) */
48
+ registerAddon(addon: ICamstackAddon): void {
49
+
50
+ this.addonEntries.set(addon.manifest.id, { addon, initialized: false })
51
+ }
52
+
53
+ /** Declare capabilities from an addon manifest.
54
+ * Post-session-5-A5: `declareFromManifest` no longer synthesizes a
55
+ * minimal CapabilityState — it only attaches metadata (dependsOn,
56
+ * autoActivate). We must first call `declareCapability` with a full
57
+ * definition for each cap so the state exists in the registry. */
58
+ declareCapabilities(addon: ICamstackAddon): void {
59
+ const caps = this.getAddonCapabilities(addon)
60
+ for (const cap of caps) {
61
+ // Create a full definition so the registry has a CapabilityState.
62
+ // Mode is inferred from the cap name for test convenience.
63
+ const mode = cap.name === 'log-destination' ? 'collection' as const : 'singleton' as const
64
+ this.registry.declareCapability({ name: cap.name, scope: 'system', mode, methods: {} })
65
+ this.registry.declareFromManifest(cap)
66
+ }
67
+ }
68
+
69
+ /** Initialize an addon and wire its capabilities */
70
+ async initializeAddon(id: string): Promise<void> {
71
+ const entry = this.addonEntries.get(id)
72
+ if (!entry) throw new Error(`Addon "${id}" not registered`)
73
+ if (entry.initialized) return
74
+
75
+ // Simulate minimal context with registerProvider that wires into the registry
76
+ const self = this
77
+
78
+ const context = {
79
+ registerProvider(capName: string, provider: unknown) {
80
+ self.registry.registerProvider(capName, id, provider)
81
+ },
82
+ } as any
83
+ const result = await entry.addon.initialize(context)
84
+ // Mirror the real addon-registry.service behaviour: process the return
85
+ // value which may be ProviderRegistration[] or AddonInitResult.
86
+ if (result) {
87
+ const regs = Array.isArray(result) ? result : (result as any).providers ?? []
88
+ for (const reg of regs) {
89
+ const capName: string = typeof reg.capability === 'string'
90
+ ? reg.capability
91
+ : (reg.capability as any)?.name ?? String(reg.capability)
92
+ self.registry.registerProvider(capName, id, reg.provider)
93
+ }
94
+ }
95
+ entry.initialized = true
96
+ }
97
+
98
+ /** Shutdown an addon and unregister its capabilities */
99
+ async shutdownAddon(id: string): Promise<void> {
100
+ const entry = this.addonEntries.get(id)
101
+ if (!entry) throw new Error(`Addon "${id}" not registered`)
102
+
103
+ const caps = this.getAddonCapabilities(entry.addon)
104
+ for (const cap of caps) {
105
+ this.registry.unregisterProvider(cap.name, id)
106
+ }
107
+
108
+
109
+ await entry.addon.shutdown()
110
+ entry.initialized = false
111
+ }
112
+
113
+ /** Full boot sequence mimicking AddonRegistryService.onModuleInit */
114
+ async boot(enabledIds: string[]): Promise<void> {
115
+ // 1. Declare capabilities from all registered addons
116
+ for (const [, entry] of this.addonEntries) {
117
+ this.declareCapabilities(entry.addon)
118
+ }
119
+
120
+ // 2. Phase 1: infra addons
121
+ for (const infra of INFRA_CAPABILITIES) {
122
+ const addonId = this.findAddonForCapability(infra.name, enabledIds)
123
+ if (addonId) {
124
+ await this.initializeAddon(addonId)
125
+ } else if (infra.required) {
126
+ throw new Error(`No addon provides required infrastructure capability "${infra.name}"`)
127
+ }
128
+ }
129
+
130
+ // 3. Phase 2: remaining addons (dependency-ordered)
131
+ const bootOrder = this.registry.getBootOrder()
132
+ const infraNames = new Set(INFRA_CAPABILITIES.map((c) => c.name))
133
+
134
+ for (const capName of bootOrder) {
135
+ if (infraNames.has(capName)) continue
136
+ for (const id of enabledIds) {
137
+ const entry = this.addonEntries.get(id)
138
+ if (!entry || entry.initialized) continue
139
+ const provides = this.getAddonCapabilities(entry.addon)
140
+ if (provides.some((c) => c.name === capName)) {
141
+ await this.initializeAddon(id)
142
+ }
143
+ }
144
+ }
145
+
146
+ // 4. Enable remaining addons
147
+ for (const id of enabledIds) {
148
+ const entry = this.addonEntries.get(id)
149
+ if (entry && !entry.initialized) {
150
+ await this.initializeAddon(id)
151
+ }
152
+ }
153
+ }
154
+
155
+ private getAddonCapabilities(addon: ICamstackAddon): CapabilityDeclaration[] {
156
+
157
+ const manifest = addon.manifest as any
158
+
159
+ if (!manifest.capabilities) return []
160
+
161
+ return manifest.capabilities.map((cap: string | CapabilityDeclaration) => {
162
+ if (typeof cap === 'string') {
163
+ const decl: CapabilityDeclaration = { name: cap }
164
+ return decl
165
+ }
166
+ return cap
167
+ })
168
+ }
169
+
170
+ private findAddonForCapability(capName: string, enabledIds: string[]): string | null {
171
+ for (const id of enabledIds) {
172
+ const entry = this.addonEntries.get(id)
173
+ if (!entry) continue
174
+ const caps = this.getAddonCapabilities(entry.addon)
175
+ if (caps.some((c) => c.name === capName)) return id
176
+ }
177
+ return null
178
+ }
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // 1. Full boot lifecycle
183
+ // ---------------------------------------------------------------------------
184
+ describe('Server E2E: Full boot lifecycle', () => {
185
+ it('boots infra addons first, then non-infra, all capabilities listed', async () => {
186
+ const harness = new TestAddonHarness()
187
+
188
+ const storageAddon = new MockStorageAddon()
189
+ const logAddon = new MockLogAddon()
190
+ const analysisAddonA = new MockAnalysisAddonA()
191
+
192
+ harness.registerAddon(storageAddon)
193
+ harness.registerAddon(logAddon)
194
+ harness.registerAddon(analysisAddonA)
195
+
196
+ await harness.boot(['mock-storage', 'mock-log-addon', 'mock-analysis-a'])
197
+
198
+ // Verify infra addons enabled
199
+ expect(storageAddon.isInitialized()).toBe(true)
200
+ expect(logAddon.isInitialized()).toBe(true)
201
+ expect(analysisAddonA.isInitialized()).toBe(true)
202
+
203
+ // Verify providers accessible via registry
204
+ expect(harness.registry.getSingleton('storage')).toBe(storageAddon.provider)
205
+ expect(harness.registry.getCollection('log-destination')).toContain(logAddon.provider)
206
+ expect(harness.registry.getSingleton('object-detector')).toBe(analysisAddonA.provider)
207
+
208
+ // Verify listCapabilities
209
+ const list = harness.registry.listCapabilities()
210
+ expect(list.length).toBeGreaterThanOrEqual(3)
211
+ expect(list.find((c) => c.name === 'storage')?.activeProvider).toBe('mock-storage')
212
+ expect(list.find((c) => c.name === 'log-destination')?.providers).toContain('mock-log-addon')
213
+ expect(list.find((c) => c.name === 'object-detector')?.activeProvider).toBe('mock-analysis-a')
214
+ })
215
+
216
+ it('throws when required infra capability is missing', async () => {
217
+ const harness = new TestAddonHarness()
218
+
219
+ const logAddon = new MockLogAddon()
220
+ harness.registerAddon(logAddon)
221
+
222
+ await expect(harness.boot(['mock-log-addon'])).rejects.toThrow(/required.*storage/i)
223
+ })
224
+ })
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // 2. Singleton swap via harness
228
+ // ---------------------------------------------------------------------------
229
+ describe('Server E2E: Singleton swap', () => {
230
+ it('swaps analysis provider via setActiveSingleton', async () => {
231
+ const harness = new TestAddonHarness()
232
+
233
+ const storageAddon = new MockStorageAddon()
234
+ const analysisA = new MockAnalysisAddonA()
235
+ const analysisB = new MockAnalysisAddonB()
236
+
237
+ harness.registerAddon(storageAddon)
238
+ harness.registerAddon(analysisA)
239
+ harness.registerAddon(analysisB)
240
+
241
+ await harness.boot(['mock-storage', 'mock-analysis-a', 'mock-analysis-b'])
242
+
243
+ // A is default (first registered)
244
+ expect(harness.registry.getSingleton('object-detector')).toBe(analysisA.provider)
245
+
246
+ // Swap to B
247
+ await harness.registry.setActiveSingleton('object-detector', 'mock-analysis-b', true)
248
+ expect(harness.registry.getSingleton('object-detector')).toBe(analysisB.provider)
249
+ })
250
+ })
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // 3. Collection addon add/remove
254
+ // ---------------------------------------------------------------------------
255
+ describe('Server E2E: Collection addon add/remove', () => {
256
+ it('adds and removes log destinations dynamically', async () => {
257
+ const harness = new TestAddonHarness()
258
+
259
+ const storageAddon = new MockStorageAddon()
260
+ const logAddon = new MockLogAddon()
261
+
262
+ harness.registerAddon(storageAddon)
263
+ harness.registerAddon(logAddon)
264
+
265
+ await harness.boot(['mock-storage', 'mock-log-addon'])
266
+
267
+ expect(harness.registry.getCollection('log-destination')).toHaveLength(1)
268
+
269
+ // Dynamically add a second log destination
270
+ const logAddon2 = new MockLogAddon()
271
+
272
+ ;(logAddon2 as any).manifest = {
273
+ ...logAddon2.manifest,
274
+ id: 'mock-log-addon-2',
275
+ name: 'Mock Log Destination 2',
276
+ }
277
+ harness.registerAddon(logAddon2)
278
+ harness.declareCapabilities(logAddon2)
279
+ await harness.initializeAddon('mock-log-addon-2')
280
+
281
+ expect(harness.registry.getCollection('log-destination')).toHaveLength(2)
282
+
283
+ // Disable the second
284
+ await harness.shutdownAddon('mock-log-addon-2')
285
+ expect(harness.registry.getCollection('log-destination')).toHaveLength(1)
286
+ })
287
+ })
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // 4. Addon disable/re-enable
291
+ // ---------------------------------------------------------------------------
292
+ describe('Server E2E: Addon disable/re-enable', () => {
293
+ it('disabling an addon removes its provider, re-enabling restores it', async () => {
294
+ const harness = new TestAddonHarness()
295
+
296
+ const storageAddon = new MockStorageAddon()
297
+ const analysisA = new MockAnalysisAddonA()
298
+
299
+ harness.registerAddon(storageAddon)
300
+ harness.registerAddon(analysisA)
301
+
302
+ await harness.boot(['mock-storage', 'mock-analysis-a'])
303
+
304
+ expect(harness.registry.getSingleton('object-detector')).toBe(analysisA.provider)
305
+
306
+ // Disable analysis addon
307
+ await harness.shutdownAddon('mock-analysis-a')
308
+ expect(harness.registry.getSingleton('object-detector')).toBeNull()
309
+
310
+ // Re-enable
311
+ await harness.initializeAddon('mock-analysis-a')
312
+ expect(harness.registry.getSingleton('object-detector')).toBe(analysisA.provider)
313
+ })
314
+ })
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // 5. tRPC capabilities endpoints (logic-level, no HTTP)
318
+ // ---------------------------------------------------------------------------
319
+ describe('Server E2E: tRPC capabilities endpoints (logic-level)', () => {
320
+ let harness: TestAddonHarness
321
+
322
+ beforeEach(async () => {
323
+ harness = new TestAddonHarness()
324
+
325
+ const storageAddon = new MockStorageAddon()
326
+ const analysisA = new MockAnalysisAddonA()
327
+ const analysisB = new MockAnalysisAddonB()
328
+ const logAddon = new MockLogAddon()
329
+
330
+ harness.registerAddon(storageAddon)
331
+ harness.registerAddon(analysisA)
332
+ harness.registerAddon(analysisB)
333
+ harness.registerAddon(logAddon)
334
+
335
+ await harness.boot(['mock-storage', 'mock-analysis-a', 'mock-analysis-b', 'mock-log-addon'])
336
+ })
337
+
338
+ it('listCapabilities returns all declared capabilities', () => {
339
+ const list = harness.registry.listCapabilities()
340
+ const names = list.map((c) => c.name)
341
+
342
+ expect(names).toContain('storage')
343
+ expect(names).toContain('object-detector')
344
+ expect(names).toContain('log-destination')
345
+ })
346
+
347
+ it('getCapability for storage returns CapabilityInfo with provider', () => {
348
+ const list = harness.registry.listCapabilities()
349
+ const storage = list.find((c) => c.name === 'storage')
350
+
351
+ expect(storage).toBeDefined()
352
+ expect(storage!.mode).toBe('singleton')
353
+ expect(storage!.providers).toContain('mock-storage')
354
+ expect(storage!.activeProvider).toBe('mock-storage')
355
+ })
356
+
357
+ it('setActiveSingleton swaps the active analysis provider', async () => {
358
+ const listBefore = harness.registry.listCapabilities()
359
+ const analysisBefore = listBefore.find((c) => c.name === 'object-detector')!
360
+ expect(analysisBefore.activeProvider).toBe('mock-analysis-a')
361
+
362
+ await harness.registry.setActiveSingleton('object-detector', 'mock-analysis-b', true)
363
+
364
+ const listAfter = harness.registry.listCapabilities()
365
+ const analysisAfter = listAfter.find((c) => c.name === 'object-detector')!
366
+ expect(analysisAfter.activeProvider).toBe('mock-analysis-b')
367
+ })
368
+
369
+ it('setActiveSingleton throws for unknown capability', async () => {
370
+ await expect(
371
+ harness.registry.setActiveSingleton('nonexistent', 'some-addon', true),
372
+ ).rejects.toThrow(/[Uu]nknown/)
373
+ })
374
+
375
+ it('setActiveSingleton throws for collection capability', async () => {
376
+ await expect(
377
+ harness.registry.setActiveSingleton('log-destination', 'mock-log-addon', true),
378
+ ).rejects.toThrow(/singleton/)
379
+ })
380
+
381
+ it('setActiveSingleton throws for unregistered provider', async () => {
382
+ await expect(
383
+ harness.registry.setActiveSingleton('storage', 'nonexistent-addon', true),
384
+ ).rejects.toThrow(/[Nn]o provider/)
385
+ })
386
+ })
@@ -0,0 +1,129 @@
1
+ /**
2
+ * CLI E2E tests — verify `camstack serve` and `camstack agent` boot correctly.
3
+ *
4
+ * These tests spawn real processes using the CLI entry point and verify:
5
+ * - Server starts and responds on the configured port
6
+ * - Agent starts and attempts hub connection
7
+ * - Info command prints version and platform
8
+ *
9
+ * Uses random ports to avoid conflicts with running servers.
10
+ *
11
+ * The serve/agent tests require the full server build (@camstack/server/main.js)
12
+ * and are gated behind CAMSTACK_TEST_CLI_FULL=true.
13
+ */
14
+ import { describe, it, expect, afterEach } from 'vitest'
15
+ import { fork, type ChildProcess } from 'node:child_process'
16
+ import { resolve } from 'node:path'
17
+ import * as https from 'node:https'
18
+ import * as fs from 'node:fs'
19
+
20
+ const CLI_PATH = resolve(__dirname, '../../../../packages/cli/dist/cli.js')
21
+ const TEST_DATA_DIR = resolve(__dirname, '../../../../.test-data-cli-e2e')
22
+
23
+ const CLI_EXISTS = fs.existsSync(CLI_PATH)
24
+
25
+ // Random port in 10000-60000 range
26
+ function randomPort(): number {
27
+ return 10000 + Math.floor(Math.random() * 50000)
28
+ }
29
+
30
+ function waitForPort(port: number, timeoutMs: number = 15000): Promise<void> {
31
+ return new Promise((resolve, reject) => {
32
+ const deadline = Date.now() + timeoutMs
33
+ const check = () => {
34
+ const req = https.request(
35
+ { hostname: '127.0.0.1', port, path: '/', method: 'GET', rejectUnauthorized: false },
36
+ (res) => { res.resume(); resolve() },
37
+ )
38
+ req.on('error', () => {
39
+ if (Date.now() > deadline) {
40
+ reject(new Error(`Port ${port} not responding after ${timeoutMs}ms`))
41
+ } else {
42
+ setTimeout(check, 500)
43
+ }
44
+ })
45
+ req.end()
46
+ }
47
+ check()
48
+ })
49
+ }
50
+
51
+ describe('CLI E2E', () => {
52
+ const processes: ChildProcess[] = []
53
+
54
+ afterEach(async () => {
55
+ for (const proc of processes) {
56
+ proc.kill('SIGTERM')
57
+ }
58
+ processes.length = 0
59
+ // Small delay for cleanup
60
+ await new Promise((r) => setTimeout(r, 500))
61
+ })
62
+
63
+ // Full server boot tests require the entire build chain
64
+ const fullTest = process.env.CAMSTACK_TEST_CLI_FULL === 'true' && CLI_EXISTS ? it : it.skip
65
+
66
+ fullTest('camstack serve boots and responds on HTTPS', async () => {
67
+ const port = randomPort()
68
+ const proc = fork(CLI_PATH, ['serve', '--port', String(port), '--data', TEST_DATA_DIR], {
69
+ stdio: 'pipe',
70
+ env: { ...process.env, CAMSTACK_TLS_ENABLED: 'true' },
71
+ })
72
+ processes.push(proc)
73
+
74
+ await waitForPort(port)
75
+
76
+ // Verify HTTPS response
77
+ const body = await new Promise<string>((resolve, reject) => {
78
+ const req = https.request(
79
+ { hostname: '127.0.0.1', port, path: '/', method: 'GET', rejectUnauthorized: false },
80
+ (res) => {
81
+ let data = ''
82
+ res.on('data', (chunk) => { data += chunk })
83
+ res.on('end', () => resolve(data))
84
+ },
85
+ )
86
+ req.on('error', reject)
87
+ req.end()
88
+ })
89
+
90
+ // Should return something (admin UI or health endpoint)
91
+ expect(body.length).toBeGreaterThan(0)
92
+ }, 30000)
93
+
94
+ fullTest('camstack agent boots and stays alive', async () => {
95
+ const proc = fork(CLI_PATH, [
96
+ 'agent', '--hub', '127.0.0.1', '--token', 'test_token', '--port', String(randomPort()),
97
+ ], {
98
+ stdio: 'pipe',
99
+ env: {
100
+ ...process.env,
101
+ CAMSTACK_AGENT_NAME: 'test-agent',
102
+ CAMSTACK_DATA: TEST_DATA_DIR,
103
+ },
104
+ })
105
+ processes.push(proc)
106
+
107
+ // Agent should start even if hub is unreachable (retries in background)
108
+ await new Promise((r) => setTimeout(r, 5000))
109
+
110
+ // Process should still be alive (not crashed)
111
+ expect(proc.exitCode).toBeNull()
112
+ }, 15000)
113
+
114
+ it.skipIf(!CLI_EXISTS)('camstack info prints version and platform', async () => {
115
+ const output = await new Promise<string>((resolve, reject) => {
116
+ let stdout = ''
117
+ const proc = fork(CLI_PATH, ['info'], { stdio: 'pipe' })
118
+ proc.stdout?.on('data', (chunk) => { stdout += chunk })
119
+ proc.on('exit', (code) => {
120
+ if (code === 0) resolve(stdout)
121
+ else reject(new Error(`Exit code ${code}`))
122
+ })
123
+ })
124
+
125
+ expect(output).toContain('camstack v')
126
+ expect(output).toContain('Platform:')
127
+ expect(output).toContain('Node.js:')
128
+ }, 10000)
129
+ })
@@ -0,0 +1,89 @@
1
+ import { describe, it, expect, afterEach } from 'vitest'
2
+ import { ServiceBroker } from 'moleculer'
3
+ import { z } from 'zod'
4
+ import { CORE_CAP_SERVICE_NAME } from '@camstack/kernel'
5
+ import { trpcRouter, publicProcedure, protectedProcedure } from '../api/trpc/trpc.middleware.js'
6
+ import { buildCoreCapService } from '../api/trpc/core-cap-bridge.js'
7
+ import type { AppRouter } from '../api/trpc/trpc.router.js'
8
+
9
+ /**
10
+ * Synthetic router covering every branch of `buildCoreCapService`:
11
+ * - a core namespace with a query + a mutation
12
+ * - a camelCase core namespace (kebab-case action name)
13
+ * - a core namespace with a subscription (must be skipped)
14
+ * - a non-core namespace (must be excluded)
15
+ * - the deliberately-excluded `auth` namespace
16
+ * - a `protectedProcedure` (must pass under the trusted mesh ctx)
17
+ */
18
+ function makeRouter() {
19
+ return trpcRouter({
20
+ system: trpcRouter({
21
+ info: publicProcedure.query(() => ({ version: '9.9.9' })),
22
+ setRetentionConfig: protectedProcedure
23
+ .input(z.object({ days: z.number() }))
24
+ .mutation(({ input }) => ({ days: input.days })),
25
+ }),
26
+ streamProbe: trpcRouter({
27
+ probe: publicProcedure.query(() => ({ ok: true })),
28
+ }),
29
+ toast: trpcRouter({
30
+ onToast: publicProcedure.subscription(async function* () {
31
+ yield 1
32
+ }),
33
+ }),
34
+ deviceManager: trpcRouter({
35
+ listAll: publicProcedure.query(() => []),
36
+ }),
37
+ auth: trpcRouter({
38
+ login: publicProcedure.query(() => 'token'),
39
+ }),
40
+ })
41
+ }
42
+
43
+ function asAppRouter(router: ReturnType<typeof makeRouter>): AppRouter {
44
+ // The synthetic router is structurally a tRPC router; the cast lets
45
+ // the test exercise `buildCoreCapService` without booting every
46
+ // backend service the real appRouter depends on.
47
+ return router as unknown as AppRouter
48
+ }
49
+
50
+ describe('buildCoreCapService', () => {
51
+ let broker: ServiceBroker
52
+
53
+ afterEach(async () => {
54
+ if (broker) await broker.stop()
55
+ })
56
+
57
+ it('exposes core query + mutation procedures as kebab-cased actions', () => {
58
+ const schema = buildCoreCapService(asAppRouter(makeRouter()))
59
+ expect(schema.name).toBe(CORE_CAP_SERVICE_NAME)
60
+ expect(schema.actions?.['system.info']).toBeDefined()
61
+ expect(schema.actions?.['system.setRetentionConfig']).toBeDefined()
62
+ expect(schema.actions?.['stream-probe.probe']).toBeDefined()
63
+ })
64
+
65
+ it('excludes non-core namespaces, the auth router, and subscriptions', () => {
66
+ const schema = buildCoreCapService(asAppRouter(makeRouter()))
67
+ expect(schema.actions?.['device-manager.listAll']).toBeUndefined()
68
+ expect(schema.actions?.['auth.login']).toBeUndefined()
69
+ expect(schema.actions?.['toast.onToast']).toBeUndefined()
70
+ })
71
+
72
+ it('routes a bridged query through the trusted mesh caller', async () => {
73
+ broker = new ServiceBroker({ nodeID: 'test', transporter: 'Fake', logger: false })
74
+ broker.createService(buildCoreCapService(asAppRouter(makeRouter())))
75
+ await broker.start()
76
+
77
+ const result = await broker.call(`${CORE_CAP_SERVICE_NAME}.system.info`)
78
+ expect(result).toEqual({ version: '9.9.9' })
79
+ })
80
+
81
+ it('passes protectedProcedure under the synthetic admin mesh identity', async () => {
82
+ broker = new ServiceBroker({ nodeID: 'test', transporter: 'Fake', logger: false })
83
+ broker.createService(buildCoreCapService(asAppRouter(makeRouter())))
84
+ await broker.start()
85
+
86
+ const result = await broker.call(`${CORE_CAP_SERVICE_NAME}.system.setRetentionConfig`, { days: 30 })
87
+ expect(result).toEqual({ days: 30 })
88
+ })
89
+ })