@camstack/kernel 0.1.2 → 0.1.4
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.
- package/dist/addon-installer-WQBOEZQT.mjs +6 -0
- package/dist/chunk-GJ3DKNOD.mjs +494 -0
- package/dist/chunk-GJ3DKNOD.mjs.map +1 -0
- package/dist/chunk-LZOMFHX3.mjs +38 -0
- package/dist/chunk-RHK5CCAL.mjs +154 -0
- package/dist/{chunk-S5YWNNPK.mjs.map → chunk-RHK5CCAL.mjs.map} +1 -1
- package/dist/index.d.mts +18 -18
- package/dist/index.d.ts +18 -18
- package/dist/index.js +2037 -1697
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1462 -1231
- package/dist/index.mjs.map +1 -1
- package/dist/worker/addon-worker-entry.js +427 -270
- package/dist/worker/addon-worker-entry.js.map +1 -1
- package/dist/worker/addon-worker-entry.mjs +8 -5
- package/dist/worker/addon-worker-entry.mjs.map +1 -1
- package/package.json +3 -2
- package/dist/addon-installer-L224DWJS.mjs +0 -8
- package/dist/chunk-BJTO5JO5.mjs +0 -11
- package/dist/chunk-K454DUQR.mjs +0 -389
- package/dist/chunk-K454DUQR.mjs.map +0 -1
- package/dist/chunk-S5YWNNPK.mjs +0 -135
- /package/dist/{addon-installer-L224DWJS.mjs.map → addon-installer-WQBOEZQT.mjs.map} +0 -0
- /package/dist/{chunk-BJTO5JO5.mjs.map → chunk-LZOMFHX3.mjs.map} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,1291 +1,1522 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-
|
|
2
|
+
require_worker_process_manager
|
|
3
|
+
} from "./chunk-RHK5CCAL.mjs";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
symlinkAddonsToNodeModules
|
|
14
|
-
} from "./chunk-K454DUQR.mjs";
|
|
15
|
-
import "./chunk-BJTO5JO5.mjs";
|
|
5
|
+
require_addon_installer,
|
|
6
|
+
require_fs_utils
|
|
7
|
+
} from "./chunk-GJ3DKNOD.mjs";
|
|
8
|
+
import {
|
|
9
|
+
__commonJS,
|
|
10
|
+
__require,
|
|
11
|
+
__toESM
|
|
12
|
+
} from "./chunk-LZOMFHX3.mjs";
|
|
16
13
|
|
|
17
|
-
// src/addon-loader.
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
39
|
-
for (const scopeEntry of scopeEntries) {
|
|
40
|
-
if (!scopeEntry.isDirectory()) continue;
|
|
41
|
-
await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
|
|
42
|
-
}
|
|
43
|
-
continue;
|
|
44
|
-
}
|
|
45
|
-
await this.tryLoadAddon(path.join(addonsDir, entry.name));
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
async tryLoadAddon(addonDir) {
|
|
49
|
-
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
50
|
-
if (!fs.existsSync(pkgJsonPath)) return;
|
|
51
|
-
try {
|
|
52
|
-
await this.loadFromAddonDir(addonDir);
|
|
53
|
-
} catch (err) {
|
|
54
|
-
console.warn(`Failed to load addon from ${addonDir}: ${err}`);
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
/** Load addon from a specific directory (package.json + dist/) */
|
|
58
|
-
async loadFromAddonDir(addonDir) {
|
|
59
|
-
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
60
|
-
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
61
|
-
const packageName = pkgJson["name"];
|
|
62
|
-
const packageVersion = pkgJson["version"] ?? "0.0.0";
|
|
63
|
-
const manifest = pkgJson["camstack"];
|
|
64
|
-
if (!manifest?.addons?.length) return;
|
|
65
|
-
for (const declaration of manifest.addons) {
|
|
66
|
-
const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
|
|
67
|
-
let entryPath = path.resolve(addonDir, entryFile);
|
|
68
|
-
if (!fs.existsSync(entryPath)) {
|
|
69
|
-
const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
|
|
70
|
-
const alternatives = [
|
|
71
|
-
`${base}.cjs`,
|
|
72
|
-
`${base}.mjs`,
|
|
73
|
-
path.resolve(addonDir, "dist", "index.js"),
|
|
74
|
-
path.resolve(addonDir, "dist", "index.cjs"),
|
|
75
|
-
path.resolve(addonDir, "dist", "index.mjs"),
|
|
76
|
-
path.resolve(addonDir, declaration.entry)
|
|
77
|
-
];
|
|
78
|
-
entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
|
|
79
|
-
}
|
|
80
|
-
if (!fs.existsSync(entryPath)) {
|
|
81
|
-
throw new Error(`Entry not found: ${entryPath}`);
|
|
82
|
-
}
|
|
83
|
-
const mod = await import(entryPath);
|
|
84
|
-
const AddonClass = resolveAddonClass(mod);
|
|
85
|
-
if (!AddonClass) {
|
|
86
|
-
throw new Error(`No addon class in ${entryPath}`);
|
|
87
|
-
}
|
|
88
|
-
this.addons.set(declaration.id, {
|
|
89
|
-
declaration,
|
|
90
|
-
packageName,
|
|
91
|
-
packageVersion,
|
|
92
|
-
packageDisplayName: manifest.displayName,
|
|
93
|
-
addonClass: AddonClass
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
/** Load addon from a direct path (for development/testing) */
|
|
98
|
-
async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
|
|
99
|
-
const mod = await import(modulePath);
|
|
100
|
-
const AddonClass = resolveAddonClass(mod);
|
|
101
|
-
if (!AddonClass) {
|
|
102
|
-
throw new Error(`Module ${modulePath} has no default export`);
|
|
103
|
-
}
|
|
104
|
-
this.addons.set(addonId, {
|
|
105
|
-
declaration: {
|
|
106
|
-
id: addonId,
|
|
107
|
-
entry: modulePath,
|
|
108
|
-
slot: "detector",
|
|
109
|
-
...declaration
|
|
110
|
-
},
|
|
111
|
-
packageName,
|
|
112
|
-
packageVersion,
|
|
113
|
-
addonClass: AddonClass
|
|
14
|
+
// src/addon-loader.js
|
|
15
|
+
var require_addon_loader = __commonJS({
|
|
16
|
+
"src/addon-loader.js"(exports) {
|
|
17
|
+
"use strict";
|
|
18
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
19
|
+
if (k2 === void 0) k2 = k;
|
|
20
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
21
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
22
|
+
desc = { enumerable: true, get: function() {
|
|
23
|
+
return m[k];
|
|
24
|
+
} };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === void 0) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
114
35
|
});
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
engines = /* @__PURE__ */ new Map();
|
|
146
|
-
/**
|
|
147
|
-
* Get or create an addon engine for the given effective config.
|
|
148
|
-
* Cameras with the same addonId + effective config share the same engine.
|
|
149
|
-
*/
|
|
150
|
-
async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
|
|
151
|
-
const effectiveConfig = { ...globalConfig, ...cameraOverride };
|
|
152
|
-
const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
153
|
-
const existing = this.engines.get(configKey);
|
|
154
|
-
if (existing) return existing;
|
|
155
|
-
const addon = this.loader.createInstance(addonId);
|
|
156
|
-
await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
|
|
157
|
-
this.engines.set(configKey, addon);
|
|
158
|
-
return addon;
|
|
159
|
-
}
|
|
160
|
-
/** Get all active engines */
|
|
161
|
-
getActiveEngines() {
|
|
162
|
-
return new Map(this.engines);
|
|
163
|
-
}
|
|
164
|
-
/** Shutdown a specific engine by its config key */
|
|
165
|
-
async shutdownEngine(configKey) {
|
|
166
|
-
const engine = this.engines.get(configKey);
|
|
167
|
-
if (engine) {
|
|
168
|
-
await engine.shutdown();
|
|
169
|
-
this.engines.delete(configKey);
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
/** Shutdown all engines */
|
|
173
|
-
async shutdownAll() {
|
|
174
|
-
for (const [, engine] of this.engines) {
|
|
175
|
-
await engine.shutdown();
|
|
36
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function(mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) {
|
|
49
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
50
|
+
}
|
|
51
|
+
__setModuleDefault(result, mod);
|
|
52
|
+
return result;
|
|
53
|
+
};
|
|
54
|
+
})();
|
|
55
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
56
|
+
exports.AddonLoader = void 0;
|
|
57
|
+
var fs = __importStar(__require("fs"));
|
|
58
|
+
var path = __importStar(__require("path"));
|
|
59
|
+
function resolveAddonClass(mod) {
|
|
60
|
+
let candidate = mod["default"] ?? mod[Object.keys(mod)[0]];
|
|
61
|
+
if (candidate && typeof candidate === "object" && "default" in candidate) {
|
|
62
|
+
candidate = candidate["default"];
|
|
63
|
+
}
|
|
64
|
+
return typeof candidate === "function" ? candidate : void 0;
|
|
176
65
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
66
|
+
var AddonLoader2 = class {
|
|
67
|
+
addons = /* @__PURE__ */ new Map();
|
|
68
|
+
/** Scan addons directory and load all addon packages.
|
|
69
|
+
* Supports scoped layout: addons/@scope/package-name/ */
|
|
70
|
+
async loadFromDirectory(addonsDir) {
|
|
71
|
+
if (!fs.existsSync(addonsDir))
|
|
72
|
+
return;
|
|
73
|
+
const entries = fs.readdirSync(addonsDir, { withFileTypes: true });
|
|
74
|
+
for (const entry of entries) {
|
|
75
|
+
if (!entry.isDirectory())
|
|
76
|
+
continue;
|
|
77
|
+
if (entry.name.startsWith("@")) {
|
|
78
|
+
const scopeDir = path.join(addonsDir, entry.name);
|
|
79
|
+
const scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
80
|
+
for (const scopeEntry of scopeEntries) {
|
|
81
|
+
if (!scopeEntry.isDirectory())
|
|
82
|
+
continue;
|
|
83
|
+
await this.tryLoadAddon(path.join(scopeDir, scopeEntry.name));
|
|
84
|
+
}
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
await this.tryLoadAddon(path.join(addonsDir, entry.name));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async tryLoadAddon(addonDir) {
|
|
91
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
92
|
+
if (!fs.existsSync(pkgJsonPath))
|
|
93
|
+
return;
|
|
94
|
+
try {
|
|
95
|
+
await this.loadFromAddonDir(addonDir);
|
|
96
|
+
} catch (err) {
|
|
97
|
+
console.warn(`Failed to load addon from ${addonDir}: ${err}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Load addon from a specific directory (package.json + dist/) */
|
|
101
|
+
async loadFromAddonDir(addonDir) {
|
|
102
|
+
const pkgJsonPath = path.join(addonDir, "package.json");
|
|
103
|
+
const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, "utf-8"));
|
|
104
|
+
const packageName = pkgJson["name"];
|
|
105
|
+
const packageVersion = pkgJson["version"] ?? "0.0.0";
|
|
106
|
+
const manifest = pkgJson["camstack"];
|
|
107
|
+
if (!manifest?.addons?.length)
|
|
108
|
+
return;
|
|
109
|
+
for (const declaration of manifest.addons) {
|
|
110
|
+
const entryFile = declaration.entry.replace(/^\.\//, "").replace(/^src\//, "dist/").replace(/\.ts$/, ".js");
|
|
111
|
+
let entryPath = path.resolve(addonDir, entryFile);
|
|
112
|
+
if (!fs.existsSync(entryPath)) {
|
|
113
|
+
const base = entryPath.replace(/\.(js|cjs|mjs)$/, "");
|
|
114
|
+
const alternatives = [
|
|
115
|
+
`${base}.cjs`,
|
|
116
|
+
`${base}.mjs`,
|
|
117
|
+
path.resolve(addonDir, "dist", "index.js"),
|
|
118
|
+
path.resolve(addonDir, "dist", "index.cjs"),
|
|
119
|
+
path.resolve(addonDir, "dist", "index.mjs"),
|
|
120
|
+
path.resolve(addonDir, declaration.entry)
|
|
121
|
+
];
|
|
122
|
+
entryPath = alternatives.find((p) => fs.existsSync(p)) ?? entryPath;
|
|
123
|
+
}
|
|
124
|
+
if (!fs.existsSync(entryPath)) {
|
|
125
|
+
throw new Error(`Entry not found: ${entryPath}`);
|
|
126
|
+
}
|
|
127
|
+
const mod = await Promise.resolve(`${entryPath}`).then((s) => __importStar(__require(s)));
|
|
128
|
+
const AddonClass = resolveAddonClass(mod);
|
|
129
|
+
if (!AddonClass) {
|
|
130
|
+
throw new Error(`No addon class in ${entryPath}`);
|
|
131
|
+
}
|
|
132
|
+
this.addons.set(declaration.id, {
|
|
133
|
+
declaration,
|
|
134
|
+
packageName,
|
|
135
|
+
packageVersion,
|
|
136
|
+
packageDisplayName: manifest.displayName,
|
|
137
|
+
addonClass: AddonClass
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** Load addon from a direct path (for development/testing) */
|
|
142
|
+
async loadFromPath(addonId, modulePath, packageName, declaration, packageVersion = "0.0.0") {
|
|
143
|
+
const mod = await Promise.resolve(`${modulePath}`).then((s) => __importStar(__require(s)));
|
|
144
|
+
const AddonClass = resolveAddonClass(mod);
|
|
145
|
+
if (!AddonClass) {
|
|
146
|
+
throw new Error(`Module ${modulePath} has no default export`);
|
|
147
|
+
}
|
|
148
|
+
this.addons.set(addonId, {
|
|
149
|
+
declaration: {
|
|
150
|
+
id: addonId,
|
|
151
|
+
entry: modulePath,
|
|
152
|
+
slot: "detector",
|
|
153
|
+
...declaration
|
|
154
|
+
},
|
|
155
|
+
packageName,
|
|
156
|
+
packageVersion,
|
|
157
|
+
addonClass: AddonClass
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/** Get a registered addon by ID */
|
|
161
|
+
getAddon(addonId) {
|
|
162
|
+
return this.addons.get(addonId);
|
|
163
|
+
}
|
|
164
|
+
/** List all registered addons */
|
|
165
|
+
listAddons() {
|
|
166
|
+
return [...this.addons.values()];
|
|
167
|
+
}
|
|
168
|
+
/** Check if an addon is registered */
|
|
169
|
+
hasAddon(addonId) {
|
|
170
|
+
return this.addons.has(addonId);
|
|
171
|
+
}
|
|
172
|
+
/** Create a new instance of an addon (not yet initialized) */
|
|
173
|
+
createInstance(addonId) {
|
|
174
|
+
const registered = this.addons.get(addonId);
|
|
175
|
+
if (!registered) {
|
|
176
|
+
throw new Error(`Addon "${addonId}" is not registered`);
|
|
177
|
+
}
|
|
178
|
+
return new registered.addonClass();
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
exports.AddonLoader = AddonLoader2;
|
|
186
182
|
}
|
|
187
|
-
};
|
|
183
|
+
});
|
|
188
184
|
|
|
189
|
-
// src/
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
} catch {
|
|
185
|
+
// src/addon-engine-manager.js
|
|
186
|
+
var require_addon_engine_manager = __commonJS({
|
|
187
|
+
"src/addon-engine-manager.js"(exports) {
|
|
188
|
+
"use strict";
|
|
189
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
190
|
+
exports.AddonEngineManager = void 0;
|
|
191
|
+
var node_crypto_1 = __require("crypto");
|
|
192
|
+
var AddonEngineManager2 = class {
|
|
193
|
+
loader;
|
|
194
|
+
baseContext;
|
|
195
|
+
engines = /* @__PURE__ */ new Map();
|
|
196
|
+
constructor(loader, baseContext) {
|
|
197
|
+
this.loader = loader;
|
|
198
|
+
this.baseContext = baseContext;
|
|
205
199
|
}
|
|
206
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Get or create an addon engine for the given effective config.
|
|
202
|
+
* Cameras with the same addonId + effective config share the same engine.
|
|
203
|
+
*/
|
|
204
|
+
async getOrCreateEngine(addonId, globalConfig, cameraOverride) {
|
|
205
|
+
const effectiveConfig = { ...globalConfig, ...cameraOverride };
|
|
206
|
+
const configKey = `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
207
|
+
const existing = this.engines.get(configKey);
|
|
208
|
+
if (existing)
|
|
209
|
+
return existing;
|
|
210
|
+
const addon = this.loader.createInstance(addonId);
|
|
211
|
+
await addon.initialize({ ...this.baseContext, addonConfig: effectiveConfig });
|
|
212
|
+
this.engines.set(configKey, addon);
|
|
213
|
+
return addon;
|
|
214
|
+
}
|
|
215
|
+
/** Get all active engines */
|
|
216
|
+
getActiveEngines() {
|
|
217
|
+
return new Map(this.engines);
|
|
218
|
+
}
|
|
219
|
+
/** Shutdown a specific engine by its config key */
|
|
220
|
+
async shutdownEngine(configKey) {
|
|
221
|
+
const engine = this.engines.get(configKey);
|
|
222
|
+
if (engine) {
|
|
223
|
+
await engine.shutdown();
|
|
224
|
+
this.engines.delete(configKey);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/** Shutdown all engines */
|
|
228
|
+
async shutdownAll() {
|
|
229
|
+
for (const [, engine] of this.engines) {
|
|
230
|
+
await engine.shutdown();
|
|
231
|
+
}
|
|
232
|
+
this.engines.clear();
|
|
233
|
+
}
|
|
234
|
+
/** Compute a deterministic config key (visible for tests) */
|
|
235
|
+
computeConfigKey(addonId, effectiveConfig) {
|
|
236
|
+
return `${addonId}:${this.hashConfig(effectiveConfig)}`;
|
|
237
|
+
}
|
|
238
|
+
hashConfig(config) {
|
|
239
|
+
const sorted = JSON.stringify(config, Object.keys(config).sort());
|
|
240
|
+
return (0, node_crypto_1.createHash)("md5").update(sorted).digest("hex").slice(0, 12);
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
exports.AddonEngineManager = AddonEngineManager2;
|
|
207
244
|
}
|
|
208
|
-
|
|
209
|
-
}
|
|
245
|
+
});
|
|
210
246
|
|
|
211
|
-
// src/
|
|
212
|
-
var
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
declaration,
|
|
233
|
-
available: /* @__PURE__ */ new Map(),
|
|
234
|
-
activeAddonId: null,
|
|
235
|
-
activeProvider: null,
|
|
236
|
-
activeCollection: [],
|
|
237
|
-
consumers: /* @__PURE__ */ new Set()
|
|
247
|
+
// src/workspace-detect.js
|
|
248
|
+
var require_workspace_detect = __commonJS({
|
|
249
|
+
"src/workspace-detect.js"(exports) {
|
|
250
|
+
"use strict";
|
|
251
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
252
|
+
if (k2 === void 0) k2 = k;
|
|
253
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
254
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
255
|
+
desc = { enumerable: true, get: function() {
|
|
256
|
+
return m[k];
|
|
257
|
+
} };
|
|
258
|
+
}
|
|
259
|
+
Object.defineProperty(o, k2, desc);
|
|
260
|
+
}) : (function(o, m, k, k2) {
|
|
261
|
+
if (k2 === void 0) k2 = k;
|
|
262
|
+
o[k2] = m[k];
|
|
263
|
+
}));
|
|
264
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
|
|
265
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
266
|
+
}) : function(o, v) {
|
|
267
|
+
o["default"] = v;
|
|
238
268
|
});
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
269
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
|
|
270
|
+
var ownKeys = function(o) {
|
|
271
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
272
|
+
var ar = [];
|
|
273
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
274
|
+
return ar;
|
|
275
|
+
};
|
|
276
|
+
return ownKeys(o);
|
|
277
|
+
};
|
|
278
|
+
return function(mod) {
|
|
279
|
+
if (mod && mod.__esModule) return mod;
|
|
280
|
+
var result = {};
|
|
281
|
+
if (mod != null) {
|
|
282
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
283
|
+
}
|
|
284
|
+
__setModuleDefault(result, mod);
|
|
285
|
+
return result;
|
|
286
|
+
};
|
|
287
|
+
})();
|
|
288
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
289
|
+
exports.detectWorkspacePackagesDir = detectWorkspacePackagesDir2;
|
|
290
|
+
var fs = __importStar(__require("fs"));
|
|
291
|
+
var path = __importStar(__require("path"));
|
|
292
|
+
function detectWorkspacePackagesDir2(startDir) {
|
|
293
|
+
let current = path.resolve(startDir);
|
|
294
|
+
for (let i = 0; i < 6; i++) {
|
|
295
|
+
current = path.dirname(current);
|
|
296
|
+
const packagesDir = path.join(current, "packages");
|
|
297
|
+
const rootPkgJson = path.join(current, "package.json");
|
|
298
|
+
if (fs.existsSync(packagesDir) && fs.existsSync(rootPkgJson)) {
|
|
265
299
|
try {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
300
|
+
const rootPkg = JSON.parse(fs.readFileSync(rootPkgJson, "utf-8"));
|
|
301
|
+
if (rootPkg.workspaces || rootPkg.name === "camstack-server" || rootPkg.name === "camstack") {
|
|
302
|
+
return packagesDir;
|
|
303
|
+
}
|
|
304
|
+
} catch {
|
|
270
305
|
}
|
|
271
306
|
}
|
|
272
307
|
}
|
|
308
|
+
return null;
|
|
273
309
|
}
|
|
274
310
|
}
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// src/capability-registry.js
|
|
314
|
+
var require_capability_registry = __commonJS({
|
|
315
|
+
"src/capability-registry.js"(exports) {
|
|
316
|
+
"use strict";
|
|
317
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
318
|
+
exports.CapabilityRegistry = void 0;
|
|
319
|
+
var CapabilityRegistry2 = class {
|
|
320
|
+
logger;
|
|
321
|
+
configReader;
|
|
322
|
+
capabilities = /* @__PURE__ */ new Map();
|
|
323
|
+
/** Per-device singleton overrides: deviceId → (capability → addonId) */
|
|
324
|
+
deviceOverrides = /* @__PURE__ */ new Map();
|
|
325
|
+
/** Per-device collection filters: deviceId → (capability → addonIds[]) */
|
|
326
|
+
deviceCollectionFilters = /* @__PURE__ */ new Map();
|
|
327
|
+
constructor(logger, configReader) {
|
|
328
|
+
this.logger = logger;
|
|
329
|
+
this.configReader = configReader;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Declare a capability (typically called when addon manifests are loaded).
|
|
333
|
+
* Must be called before registerProvider/registerConsumer for that capability.
|
|
334
|
+
*/
|
|
335
|
+
declareCapability(declaration) {
|
|
336
|
+
if (this.capabilities.has(declaration.name)) {
|
|
337
|
+
this.logger.debug(`Capability "${declaration.name}" already declared, skipping`);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
this.capabilities.set(declaration.name, {
|
|
341
|
+
declaration,
|
|
342
|
+
available: /* @__PURE__ */ new Map(),
|
|
343
|
+
activeAddonId: null,
|
|
344
|
+
activeProvider: null,
|
|
345
|
+
activeCollection: [],
|
|
346
|
+
consumers: /* @__PURE__ */ new Set()
|
|
347
|
+
});
|
|
348
|
+
this.logger.debug(`Capability declared: ${declaration.name} (mode=${declaration.mode})`);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Register a capability provider (called by addon loader when addon is enabled).
|
|
352
|
+
* For singleton: auto-activates if user-preferred or first registered.
|
|
353
|
+
* For collection: adds to active set and notifies consumers.
|
|
354
|
+
*/
|
|
355
|
+
registerProvider(capability, addonId, provider) {
|
|
356
|
+
const state = this.capabilities.get(capability);
|
|
357
|
+
if (!state) {
|
|
358
|
+
this.logger.warn(`Cannot register provider for undeclared capability "${capability}"`);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
state.available.set(addonId, provider);
|
|
362
|
+
this.logger.info(`Provider registered: ${addonId} \u2192 ${capability}`);
|
|
363
|
+
if (state.declaration.mode === "singleton") {
|
|
364
|
+
const userChoice = this.configReader(capability);
|
|
365
|
+
if (userChoice === addonId) {
|
|
366
|
+
this.activateSingleton(state, addonId, provider);
|
|
367
|
+
} else if (userChoice === void 0 && state.activeAddonId === null) {
|
|
368
|
+
this.activateSingleton(state, addonId, provider);
|
|
369
|
+
}
|
|
370
|
+
} else {
|
|
371
|
+
state.activeCollection.push({ addonId, provider });
|
|
372
|
+
for (const consumer of state.consumers) {
|
|
373
|
+
if (consumer.onAdded) {
|
|
374
|
+
try {
|
|
375
|
+
consumer.onAdded(provider);
|
|
376
|
+
} catch (error) {
|
|
377
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
378
|
+
this.logger.error(`Consumer onAdded failed for ${capability}: ${msg}`);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Unregister a provider (called when addon is disabled/uninstalled).
|
|
386
|
+
*/
|
|
387
|
+
unregisterProvider(capability, addonId) {
|
|
388
|
+
const state = this.capabilities.get(capability);
|
|
389
|
+
if (!state)
|
|
390
|
+
return;
|
|
391
|
+
const provider = state.available.get(addonId);
|
|
392
|
+
state.available.delete(addonId);
|
|
393
|
+
if (state.declaration.mode === "singleton") {
|
|
394
|
+
if (state.activeAddonId === addonId) {
|
|
395
|
+
state.activeAddonId = null;
|
|
396
|
+
state.activeProvider = null;
|
|
397
|
+
this.logger.info(`Singleton deactivated: ${capability} (was ${addonId})`);
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
const idx = state.activeCollection.findIndex((e) => e.addonId === addonId);
|
|
401
|
+
if (idx !== -1) {
|
|
402
|
+
state.activeCollection.splice(idx, 1);
|
|
403
|
+
for (const consumer of state.consumers) {
|
|
404
|
+
if (consumer.onRemoved && provider !== void 0) {
|
|
405
|
+
try {
|
|
406
|
+
consumer.onRemoved(provider);
|
|
407
|
+
} catch (error) {
|
|
408
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
409
|
+
this.logger.error(`Consumer onRemoved failed for ${capability}: ${msg}`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Register a consumer that wants to be notified when providers change.
|
|
418
|
+
* If a provider is already active, the consumer is immediately notified.
|
|
419
|
+
* Returns a disposer function for cleanup.
|
|
420
|
+
*/
|
|
421
|
+
registerConsumer(registration) {
|
|
422
|
+
const state = this.capabilities.get(registration.capability);
|
|
423
|
+
if (!state) {
|
|
424
|
+
this.logger.debug(`Consumer registered for undeclared capability "${registration.capability}" \u2014 auto-declaring`);
|
|
425
|
+
this.declareCapability({ name: registration.capability, mode: "singleton" });
|
|
426
|
+
return this.registerConsumer(registration);
|
|
427
|
+
}
|
|
428
|
+
const untypedReg = registration;
|
|
429
|
+
state.consumers.add(untypedReg);
|
|
430
|
+
if (state.declaration.mode === "singleton") {
|
|
431
|
+
if (state.activeProvider !== null && registration.onSet) {
|
|
295
432
|
try {
|
|
296
|
-
|
|
433
|
+
registration.onSet(state.activeProvider);
|
|
297
434
|
} catch (error) {
|
|
298
435
|
const msg = error instanceof Error ? error.message : String(error);
|
|
299
|
-
this.logger.error(`Consumer
|
|
436
|
+
this.logger.error(`Consumer onSet (immediate) failed for ${registration.capability}: ${msg}`);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
} else {
|
|
440
|
+
if (registration.onAdded) {
|
|
441
|
+
for (const entry of state.activeCollection) {
|
|
442
|
+
try {
|
|
443
|
+
registration.onAdded(entry.provider);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
446
|
+
this.logger.error(`Consumer onAdded (immediate) failed for ${registration.capability}: ${msg}`);
|
|
447
|
+
}
|
|
300
448
|
}
|
|
301
449
|
}
|
|
302
450
|
}
|
|
451
|
+
return () => {
|
|
452
|
+
state.consumers.delete(untypedReg);
|
|
453
|
+
};
|
|
303
454
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
455
|
+
/**
|
|
456
|
+
* Get the active singleton provider for a capability.
|
|
457
|
+
* Returns null if none set.
|
|
458
|
+
*/
|
|
459
|
+
getSingleton(capability) {
|
|
460
|
+
const state = this.capabilities.get(capability);
|
|
461
|
+
if (!state || state.declaration.mode !== "singleton")
|
|
462
|
+
return null;
|
|
463
|
+
return state.activeProvider ?? null;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Get all active collection providers for a capability.
|
|
467
|
+
*/
|
|
468
|
+
getCollection(capability) {
|
|
469
|
+
const state = this.capabilities.get(capability);
|
|
470
|
+
if (!state || state.declaration.mode !== "collection")
|
|
471
|
+
return [];
|
|
472
|
+
return state.activeCollection.map((e) => e.provider);
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Set which addon should be the active singleton for a capability.
|
|
476
|
+
* Call with `immediate: true` to also swap the runtime provider now
|
|
477
|
+
* (consumers' onSet will be awaited).
|
|
478
|
+
*/
|
|
479
|
+
async setActiveSingleton(capability, addonId, immediate = false) {
|
|
480
|
+
const state = this.capabilities.get(capability);
|
|
481
|
+
if (!state) {
|
|
482
|
+
throw new Error(`Unknown capability: ${capability}`);
|
|
483
|
+
}
|
|
484
|
+
if (state.declaration.mode !== "singleton") {
|
|
485
|
+
throw new Error(`Capability "${capability}" is not a singleton`);
|
|
486
|
+
}
|
|
487
|
+
const provider = state.available.get(addonId);
|
|
488
|
+
if (!provider) {
|
|
489
|
+
throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
|
|
490
|
+
}
|
|
491
|
+
if (immediate) {
|
|
492
|
+
await this.activateSingletonAsync(state, addonId, provider);
|
|
327
493
|
}
|
|
494
|
+
this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
|
|
328
495
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
496
|
+
/**
|
|
497
|
+
* Get the mode declared for a capability.
|
|
498
|
+
*/
|
|
499
|
+
getMode(capability) {
|
|
500
|
+
return this.capabilities.get(capability)?.declaration.mode;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* List all registered capabilities with their providers.
|
|
504
|
+
*/
|
|
505
|
+
listCapabilities() {
|
|
506
|
+
const result = [];
|
|
507
|
+
for (const [name, state] of this.capabilities) {
|
|
508
|
+
result.push({
|
|
509
|
+
name,
|
|
510
|
+
mode: state.declaration.mode,
|
|
511
|
+
providers: [...state.available.keys()],
|
|
512
|
+
activeProvider: state.activeAddonId
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
return result;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Check if all dependencies for a capability are satisfied (have active providers).
|
|
519
|
+
*/
|
|
520
|
+
areDependenciesMet(declaration) {
|
|
521
|
+
if (!declaration.dependsOn?.length)
|
|
522
|
+
return true;
|
|
523
|
+
return declaration.dependsOn.every((dep) => {
|
|
524
|
+
const state = this.capabilities.get(dep);
|
|
525
|
+
if (!state)
|
|
526
|
+
return false;
|
|
527
|
+
if (state.declaration.mode === "singleton") {
|
|
528
|
+
return state.activeProvider !== null;
|
|
529
|
+
}
|
|
530
|
+
return state.activeCollection.length > 0;
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Get the dependency-ordered list of capability names for boot sequencing.
|
|
535
|
+
* Returns capabilities sorted topologically by dependsOn.
|
|
536
|
+
* Throws if a cycle is detected.
|
|
537
|
+
*/
|
|
538
|
+
getBootOrder() {
|
|
539
|
+
const visited = /* @__PURE__ */ new Set();
|
|
540
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
541
|
+
const order = [];
|
|
542
|
+
const visit = (name) => {
|
|
543
|
+
if (visited.has(name))
|
|
544
|
+
return;
|
|
545
|
+
if (visiting.has(name)) {
|
|
546
|
+
throw new Error(`Circular dependency detected involving capability "${name}"`);
|
|
547
|
+
}
|
|
548
|
+
visiting.add(name);
|
|
549
|
+
const state = this.capabilities.get(name);
|
|
550
|
+
if (state?.declaration.dependsOn) {
|
|
551
|
+
for (const dep of state.declaration.dependsOn) {
|
|
552
|
+
visit(dep);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
visiting.delete(name);
|
|
556
|
+
visited.add(name);
|
|
557
|
+
order.push(name);
|
|
558
|
+
};
|
|
559
|
+
for (const name of this.capabilities.keys()) {
|
|
560
|
+
visit(name);
|
|
561
|
+
}
|
|
562
|
+
return order;
|
|
563
|
+
}
|
|
564
|
+
// ---- Per-device overrides ----
|
|
565
|
+
/**
|
|
566
|
+
* Set a per-device singleton override. When resolveForDevice is called for
|
|
567
|
+
* this device + capability, the specified addon's provider is returned
|
|
568
|
+
* instead of the global singleton.
|
|
569
|
+
*/
|
|
570
|
+
setDeviceOverride(deviceId, capability, addonId) {
|
|
571
|
+
const state = this.capabilities.get(capability);
|
|
572
|
+
if (!state) {
|
|
573
|
+
this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
if (!state.available.has(addonId)) {
|
|
577
|
+
this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
let deviceMap = this.deviceOverrides.get(deviceId);
|
|
581
|
+
if (!deviceMap) {
|
|
582
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
583
|
+
this.deviceOverrides.set(deviceId, deviceMap);
|
|
584
|
+
}
|
|
585
|
+
deviceMap.set(capability, addonId);
|
|
586
|
+
this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Clear a per-device singleton override, reverting to the global singleton.
|
|
590
|
+
*/
|
|
591
|
+
clearDeviceOverride(deviceId, capability) {
|
|
592
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
593
|
+
if (!deviceMap)
|
|
594
|
+
return;
|
|
595
|
+
deviceMap.delete(capability);
|
|
596
|
+
if (deviceMap.size === 0) {
|
|
597
|
+
this.deviceOverrides.delete(deviceId);
|
|
598
|
+
}
|
|
599
|
+
this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
|
|
600
|
+
}
|
|
601
|
+
/**
|
|
602
|
+
* Get all per-device singleton overrides for a device.
|
|
603
|
+
* Returns a Map of capability name to addon ID.
|
|
604
|
+
*/
|
|
605
|
+
getDeviceOverrides(deviceId) {
|
|
606
|
+
return new Map(this.deviceOverrides.get(deviceId) ?? []);
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Resolve a singleton provider for a specific device.
|
|
610
|
+
* 1. Check device override — return that addon's provider
|
|
611
|
+
* 2. Fallback to global singleton
|
|
612
|
+
*/
|
|
613
|
+
resolveForDevice(capability, deviceId) {
|
|
614
|
+
const state = this.capabilities.get(capability);
|
|
615
|
+
if (!state || state.declaration.mode !== "singleton")
|
|
616
|
+
return null;
|
|
617
|
+
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
618
|
+
if (deviceMap) {
|
|
619
|
+
const overrideAddonId = deviceMap.get(capability);
|
|
620
|
+
if (overrideAddonId) {
|
|
621
|
+
const provider = state.available.get(overrideAddonId);
|
|
622
|
+
if (provider)
|
|
623
|
+
return provider;
|
|
624
|
+
this.logger.warn(`Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
return state.activeProvider ?? null;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Set a per-device collection filter. When resolveCollectionForDevice is called
|
|
631
|
+
* for this device + capability, only providers from the specified addon IDs
|
|
632
|
+
* are returned instead of the full collection.
|
|
633
|
+
*/
|
|
634
|
+
setDeviceCollectionFilter(deviceId, capability, addonIds) {
|
|
635
|
+
const state = this.capabilities.get(capability);
|
|
636
|
+
if (!state) {
|
|
637
|
+
this.logger.warn(`Cannot set device collection filter for undeclared capability "${capability}"`);
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
let deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
641
|
+
if (!deviceMap) {
|
|
642
|
+
deviceMap = /* @__PURE__ */ new Map();
|
|
643
|
+
this.deviceCollectionFilters.set(deviceId, deviceMap);
|
|
644
|
+
}
|
|
645
|
+
deviceMap.set(capability, [...addonIds]);
|
|
646
|
+
this.logger.info(`Device collection filter set: ${deviceId} \u2192 ${capability} = [${addonIds.join(", ")}]`);
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Clear a per-device collection filter, reverting to the full collection.
|
|
650
|
+
*/
|
|
651
|
+
clearDeviceCollectionFilter(deviceId, capability) {
|
|
652
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
653
|
+
if (!deviceMap)
|
|
654
|
+
return;
|
|
655
|
+
deviceMap.delete(capability);
|
|
656
|
+
if (deviceMap.size === 0) {
|
|
657
|
+
this.deviceCollectionFilters.delete(deviceId);
|
|
658
|
+
}
|
|
659
|
+
this.logger.info(`Device collection filter cleared: ${deviceId} \u2192 ${capability}`);
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Resolve collection providers for a specific device.
|
|
663
|
+
* If a filter exists for the device + capability, only those addon's providers are returned.
|
|
664
|
+
* If no filter exists, the full collection is returned.
|
|
665
|
+
*/
|
|
666
|
+
resolveCollectionForDevice(capability, deviceId) {
|
|
667
|
+
const state = this.capabilities.get(capability);
|
|
668
|
+
if (!state || state.declaration.mode !== "collection")
|
|
669
|
+
return [];
|
|
670
|
+
const deviceMap = this.deviceCollectionFilters.get(deviceId);
|
|
671
|
+
if (deviceMap) {
|
|
672
|
+
const filterAddonIds = deviceMap.get(capability);
|
|
673
|
+
if (filterAddonIds) {
|
|
674
|
+
const filterSet = new Set(filterAddonIds);
|
|
675
|
+
return state.activeCollection.filter((e) => filterSet.has(e.addonId)).map((e) => e.provider);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
return state.activeCollection.map((e) => e.provider);
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Get a specific addon's provider by addon ID, regardless of whether it's the active singleton.
|
|
682
|
+
* Useful for per-device overrides that need to look up any registered provider.
|
|
683
|
+
*/
|
|
684
|
+
getProviderByAddonId(capability, addonId) {
|
|
685
|
+
const state = this.capabilities.get(capability);
|
|
686
|
+
if (!state)
|
|
687
|
+
return null;
|
|
688
|
+
const provider = state.available.get(addonId);
|
|
689
|
+
return provider ?? null;
|
|
690
|
+
}
|
|
691
|
+
activateSingleton(state, addonId, provider) {
|
|
692
|
+
state.activeAddonId = addonId;
|
|
693
|
+
state.activeProvider = provider;
|
|
694
|
+
this.logger.info(`Singleton activated: ${state.declaration.name} \u2192 ${addonId}`);
|
|
695
|
+
for (const consumer of state.consumers) {
|
|
696
|
+
if (consumer.onSet) {
|
|
697
|
+
try {
|
|
698
|
+
consumer.onSet(provider);
|
|
699
|
+
} catch (error) {
|
|
700
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
701
|
+
this.logger.error(`Consumer onSet failed for ${state.declaration.name}: ${msg}`);
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
async activateSingletonAsync(state, addonId, provider) {
|
|
707
|
+
state.activeAddonId = addonId;
|
|
708
|
+
state.activeProvider = provider;
|
|
709
|
+
this.logger.info(`Singleton activated (async): ${state.declaration.name} \u2192 ${addonId}`);
|
|
710
|
+
for (const consumer of state.consumers) {
|
|
711
|
+
if (consumer.onSet) {
|
|
712
|
+
try {
|
|
713
|
+
await consumer.onSet(provider);
|
|
714
|
+
} catch (error) {
|
|
715
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
716
|
+
this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
|
|
717
|
+
}
|
|
337
718
|
}
|
|
338
719
|
}
|
|
339
720
|
}
|
|
340
|
-
}
|
|
341
|
-
return () => {
|
|
342
|
-
state.consumers.delete(untypedReg);
|
|
343
721
|
};
|
|
722
|
+
exports.CapabilityRegistry = CapabilityRegistry2;
|
|
344
723
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Set which addon should be the active singleton for a capability.
|
|
364
|
-
* Call with `immediate: true` to also swap the runtime provider now
|
|
365
|
-
* (consumers' onSet will be awaited).
|
|
366
|
-
*/
|
|
367
|
-
async setActiveSingleton(capability, addonId, immediate = false) {
|
|
368
|
-
const state = this.capabilities.get(capability);
|
|
369
|
-
if (!state) {
|
|
370
|
-
throw new Error(`Unknown capability: ${capability}`);
|
|
371
|
-
}
|
|
372
|
-
if (state.declaration.mode !== "singleton") {
|
|
373
|
-
throw new Error(`Capability "${capability}" is not a singleton`);
|
|
374
|
-
}
|
|
375
|
-
const provider = state.available.get(addonId);
|
|
376
|
-
if (!provider) {
|
|
377
|
-
throw new Error(`No provider "${addonId}" registered for capability "${capability}"`);
|
|
378
|
-
}
|
|
379
|
-
if (immediate) {
|
|
380
|
-
await this.activateSingletonAsync(state, addonId, provider);
|
|
381
|
-
}
|
|
382
|
-
this.logger.info(`Singleton preference set: ${capability} \u2192 ${addonId}`);
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* Get the mode declared for a capability.
|
|
386
|
-
*/
|
|
387
|
-
getMode(capability) {
|
|
388
|
-
return this.capabilities.get(capability)?.declaration.mode;
|
|
389
|
-
}
|
|
390
|
-
/**
|
|
391
|
-
* List all registered capabilities with their providers.
|
|
392
|
-
*/
|
|
393
|
-
listCapabilities() {
|
|
394
|
-
const result = [];
|
|
395
|
-
for (const [name, state] of this.capabilities) {
|
|
396
|
-
result.push({
|
|
397
|
-
name,
|
|
398
|
-
mode: state.declaration.mode,
|
|
399
|
-
providers: [...state.available.keys()],
|
|
400
|
-
activeProvider: state.activeAddonId
|
|
401
|
-
});
|
|
724
|
+
});
|
|
725
|
+
|
|
726
|
+
// src/infra-capabilities.js
|
|
727
|
+
var require_infra_capabilities = __commonJS({
|
|
728
|
+
"src/infra-capabilities.js"(exports) {
|
|
729
|
+
"use strict";
|
|
730
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
731
|
+
exports.INFRA_CAPABILITIES = void 0;
|
|
732
|
+
exports.isInfraCapability = isInfraCapability2;
|
|
733
|
+
exports.INFRA_CAPABILITIES = [
|
|
734
|
+
{ name: "storage", required: true },
|
|
735
|
+
{ name: "settings-store", required: true },
|
|
736
|
+
{ name: "log-destination", required: false }
|
|
737
|
+
];
|
|
738
|
+
var infraNames = new Set(exports.INFRA_CAPABILITIES.map((c) => c.name));
|
|
739
|
+
function isInfraCapability2(name) {
|
|
740
|
+
return infraNames.has(name);
|
|
402
741
|
}
|
|
403
|
-
return result;
|
|
404
742
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
// src/config-schema.js
|
|
746
|
+
var require_config_schema = __commonJS({
|
|
747
|
+
"src/config-schema.js"(exports) {
|
|
748
|
+
"use strict";
|
|
749
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
750
|
+
exports.RUNTIME_DEFAULTS = exports.bootstrapSchema = exports.DEFAULT_DATA_PATH = void 0;
|
|
751
|
+
var zod_1 = __require("zod");
|
|
752
|
+
exports.DEFAULT_DATA_PATH = "camstack-data";
|
|
753
|
+
exports.bootstrapSchema = zod_1.z.object({
|
|
754
|
+
/** Server mode: 'hub' (full server) or 'agent' (worker node) */
|
|
755
|
+
mode: zod_1.z.enum(["hub", "agent"]).default("hub"),
|
|
756
|
+
server: zod_1.z.object({
|
|
757
|
+
port: zod_1.z.number().default(4443),
|
|
758
|
+
host: zod_1.z.string().default("0.0.0.0"),
|
|
759
|
+
dataPath: zod_1.z.string().default(exports.DEFAULT_DATA_PATH)
|
|
760
|
+
}).default({}),
|
|
761
|
+
auth: zod_1.z.object({
|
|
762
|
+
jwtSecret: zod_1.z.string().nullable().default(null),
|
|
763
|
+
adminUsername: zod_1.z.string().default("admin"),
|
|
764
|
+
adminPassword: zod_1.z.string().default(process.env.ADMIN_PASSWORD ?? "changeme")
|
|
765
|
+
}).default({}),
|
|
766
|
+
/** Hub connection config — only used when mode='agent' */
|
|
767
|
+
hub: zod_1.z.object({
|
|
768
|
+
url: zod_1.z.string().default("ws://localhost:4443/agent"),
|
|
769
|
+
token: zod_1.z.string().default("")
|
|
770
|
+
}).default({}),
|
|
771
|
+
/** Agent-specific config — only used when mode='agent' */
|
|
772
|
+
agent: zod_1.z.object({
|
|
773
|
+
name: zod_1.z.string().default(""),
|
|
774
|
+
/** Port for the agent status page (minimal HTML) */
|
|
775
|
+
statusPort: zod_1.z.number().default(4444)
|
|
776
|
+
}).default({}),
|
|
777
|
+
/** TLS configuration */
|
|
778
|
+
tls: zod_1.z.object({
|
|
779
|
+
/** Enable HTTPS (default: true) */
|
|
780
|
+
enabled: zod_1.z.boolean().default(true),
|
|
781
|
+
/** Path to custom cert file (PEM). If not set, auto-generates self-signed. */
|
|
782
|
+
certPath: zod_1.z.string().optional(),
|
|
783
|
+
/** Path to custom key file (PEM). Required if certPath is set. */
|
|
784
|
+
keyPath: zod_1.z.string().optional()
|
|
785
|
+
}).default({})
|
|
417
786
|
});
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
787
|
+
exports.RUNTIME_DEFAULTS = {
|
|
788
|
+
"features.streaming": true,
|
|
789
|
+
"features.notifications": true,
|
|
790
|
+
"features.objectDetection": false,
|
|
791
|
+
"features.remoteAccess": true,
|
|
792
|
+
"features.agentCluster": false,
|
|
793
|
+
"features.smartHome": true,
|
|
794
|
+
"features.recordings": true,
|
|
795
|
+
"features.backup": true,
|
|
796
|
+
"features.repl": true,
|
|
797
|
+
"retention.detectionEventsDays": 30,
|
|
798
|
+
"retention.audioLevelsDays": 7,
|
|
799
|
+
"logging.level": "info",
|
|
800
|
+
"logging.retentionDays": 30,
|
|
801
|
+
"eventBus.ringBufferSize": 1e4,
|
|
802
|
+
"storage.provider": "sqlite-storage",
|
|
803
|
+
"storage.locations": {
|
|
804
|
+
data: "camstack-data/data",
|
|
805
|
+
media: "camstack-data/media",
|
|
806
|
+
recordings: "camstack-data/recordings",
|
|
807
|
+
cache: "/tmp/camstack-cache",
|
|
808
|
+
logs: "camstack-data/logs",
|
|
809
|
+
models: "camstack-data/models"
|
|
810
|
+
},
|
|
811
|
+
"providers": [],
|
|
812
|
+
// Recording
|
|
813
|
+
"recording.segmentDurationSeconds": 4,
|
|
814
|
+
"recording.defaultRetentionDays": 30,
|
|
815
|
+
// Streaming ports are addon-specific (go2rtc owns its defaults)
|
|
816
|
+
// FFmpeg
|
|
817
|
+
"ffmpeg.binaryPath": "ffmpeg",
|
|
818
|
+
"ffmpeg.hwAccel": "auto",
|
|
819
|
+
"ffmpeg.threadCount": 0,
|
|
820
|
+
// Detection defaults
|
|
821
|
+
"detection.defaultMotionFps": 2,
|
|
822
|
+
"detection.defaultDetectionFps": 5,
|
|
823
|
+
"detection.defaultCooldownSeconds": 10,
|
|
824
|
+
"detection.defaultConfidenceThreshold": 0.4,
|
|
825
|
+
"detection.trackerMaxAgeFrames": 30,
|
|
826
|
+
"detection.trackerMinHits": 3,
|
|
827
|
+
"detection.trackerIouThreshold": 0.3,
|
|
828
|
+
// Backup retention is addon-specific (local-backup owns its default)
|
|
829
|
+
// Auth (runtime)
|
|
830
|
+
"auth.tokenExpiry": "24h"
|
|
443
831
|
};
|
|
444
|
-
for (const name of this.capabilities.keys()) {
|
|
445
|
-
visit(name);
|
|
446
|
-
}
|
|
447
|
-
return order;
|
|
448
|
-
}
|
|
449
|
-
// ---- Per-device overrides ----
|
|
450
|
-
/**
|
|
451
|
-
* Set a per-device singleton override. When resolveForDevice is called for
|
|
452
|
-
* this device + capability, the specified addon's provider is returned
|
|
453
|
-
* instead of the global singleton.
|
|
454
|
-
*/
|
|
455
|
-
setDeviceOverride(deviceId, capability, addonId) {
|
|
456
|
-
const state = this.capabilities.get(capability);
|
|
457
|
-
if (!state) {
|
|
458
|
-
this.logger.warn(`Cannot set device override for undeclared capability "${capability}"`);
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
if (!state.available.has(addonId)) {
|
|
462
|
-
this.logger.warn(`Cannot set device override: addon "${addonId}" not registered for "${capability}"`);
|
|
463
|
-
return;
|
|
464
|
-
}
|
|
465
|
-
let deviceMap = this.deviceOverrides.get(deviceId);
|
|
466
|
-
if (!deviceMap) {
|
|
467
|
-
deviceMap = /* @__PURE__ */ new Map();
|
|
468
|
-
this.deviceOverrides.set(deviceId, deviceMap);
|
|
469
|
-
}
|
|
470
|
-
deviceMap.set(capability, addonId);
|
|
471
|
-
this.logger.info(`Device override set: ${deviceId} \u2192 ${capability} = ${addonId}`);
|
|
472
|
-
}
|
|
473
|
-
/**
|
|
474
|
-
* Clear a per-device singleton override, reverting to the global singleton.
|
|
475
|
-
*/
|
|
476
|
-
clearDeviceOverride(deviceId, capability) {
|
|
477
|
-
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
478
|
-
if (!deviceMap) return;
|
|
479
|
-
deviceMap.delete(capability);
|
|
480
|
-
if (deviceMap.size === 0) {
|
|
481
|
-
this.deviceOverrides.delete(deviceId);
|
|
482
|
-
}
|
|
483
|
-
this.logger.info(`Device override cleared: ${deviceId} \u2192 ${capability}`);
|
|
484
832
|
}
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
const state = this.capabilities.get(capability);
|
|
499
|
-
if (!state || state.declaration.mode !== "singleton") return null;
|
|
500
|
-
const deviceMap = this.deviceOverrides.get(deviceId);
|
|
501
|
-
if (deviceMap) {
|
|
502
|
-
const overrideAddonId = deviceMap.get(capability);
|
|
503
|
-
if (overrideAddonId) {
|
|
504
|
-
const provider = state.available.get(overrideAddonId);
|
|
505
|
-
if (provider) return provider;
|
|
506
|
-
this.logger.warn(
|
|
507
|
-
`Device override for ${deviceId}/${capability} references unregistered addon "${overrideAddonId}" \u2014 falling back to global`
|
|
508
|
-
);
|
|
833
|
+
});
|
|
834
|
+
|
|
835
|
+
// src/config-manager.js
|
|
836
|
+
var require_config_manager = __commonJS({
|
|
837
|
+
"src/config-manager.js"(exports) {
|
|
838
|
+
"use strict";
|
|
839
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
840
|
+
if (k2 === void 0) k2 = k;
|
|
841
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
842
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
843
|
+
desc = { enumerable: true, get: function() {
|
|
844
|
+
return m[k];
|
|
845
|
+
} };
|
|
509
846
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
847
|
+
Object.defineProperty(o, k2, desc);
|
|
848
|
+
}) : (function(o, m, k, k2) {
|
|
849
|
+
if (k2 === void 0) k2 = k;
|
|
850
|
+
o[k2] = m[k];
|
|
851
|
+
}));
|
|
852
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {
|
|
853
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
854
|
+
}) : function(o, v) {
|
|
855
|
+
o["default"] = v;
|
|
856
|
+
});
|
|
857
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
|
|
858
|
+
var ownKeys = function(o) {
|
|
859
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
860
|
+
var ar = [];
|
|
861
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
862
|
+
return ar;
|
|
863
|
+
};
|
|
864
|
+
return ownKeys(o);
|
|
865
|
+
};
|
|
866
|
+
return function(mod) {
|
|
867
|
+
if (mod && mod.__esModule) return mod;
|
|
868
|
+
var result = {};
|
|
869
|
+
if (mod != null) {
|
|
870
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
871
|
+
}
|
|
872
|
+
__setModuleDefault(result, mod);
|
|
873
|
+
return result;
|
|
874
|
+
};
|
|
875
|
+
})();
|
|
876
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
877
|
+
exports.ConfigManager = void 0;
|
|
878
|
+
var fs = __importStar(__require("fs"));
|
|
879
|
+
var yaml = __importStar(__require("js-yaml"));
|
|
880
|
+
var config_schema_js_1 = require_config_schema();
|
|
881
|
+
var ENV_VAR_MAP = {
|
|
882
|
+
CAMSTACK_PORT: "server.port",
|
|
883
|
+
CAMSTACK_HOST: "server.host",
|
|
884
|
+
CAMSTACK_DATA: "server.dataPath",
|
|
885
|
+
CAMSTACK_JWT_SECRET: "auth.jwtSecret",
|
|
886
|
+
CAMSTACK_ADMIN_USER: "auth.adminUsername",
|
|
887
|
+
CAMSTACK_ADMIN_PASS: "auth.adminPassword"
|
|
888
|
+
};
|
|
889
|
+
var ConfigManager2 = class _ConfigManager {
|
|
890
|
+
configPath;
|
|
891
|
+
// Non-readonly so update() can sync the in-memory view after a write.
|
|
892
|
+
bootstrapConfig;
|
|
893
|
+
settingsStore = null;
|
|
894
|
+
constructor(configPath) {
|
|
895
|
+
this.configPath = configPath;
|
|
896
|
+
const rawYaml = this.loadYaml();
|
|
897
|
+
const merged = this.applyEnvOverrides(rawYaml);
|
|
898
|
+
this.bootstrapConfig = config_schema_js_1.bootstrapSchema.parse(merged);
|
|
899
|
+
this.warnDefaultCredentials();
|
|
558
900
|
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
901
|
+
/** Called by main.ts after the SQLite DB is ready (Phase 2). */
|
|
902
|
+
setSettingsStore(store) {
|
|
903
|
+
this.settingsStore = store;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Get a config value by dot-notation path.
|
|
907
|
+
* Priority: bootstrap config -> SQL system_settings -> RUNTIME_DEFAULTS fallback.
|
|
908
|
+
*/
|
|
909
|
+
get(path) {
|
|
910
|
+
const bootstrapValue = this.getFromBootstrap(path);
|
|
911
|
+
if (bootstrapValue !== void 0) {
|
|
912
|
+
return bootstrapValue;
|
|
913
|
+
}
|
|
914
|
+
if (this.settingsStore !== null) {
|
|
915
|
+
const sqlValue = this.settingsStore.getSystem(path);
|
|
916
|
+
if (sqlValue !== void 0) {
|
|
917
|
+
return sqlValue;
|
|
918
|
+
}
|
|
919
|
+
const sqlNested = this.getNestedFromSystemSettings(path);
|
|
920
|
+
if (sqlNested !== void 0) {
|
|
921
|
+
return sqlNested;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
if (path in config_schema_js_1.RUNTIME_DEFAULTS) {
|
|
925
|
+
return config_schema_js_1.RUNTIME_DEFAULTS[path];
|
|
926
|
+
}
|
|
927
|
+
const nested = this.getFromRuntimeDefaults(path);
|
|
928
|
+
if (nested !== void 0) {
|
|
929
|
+
return nested;
|
|
583
930
|
}
|
|
931
|
+
return void 0;
|
|
584
932
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
if (consumer.onSet) {
|
|
593
|
-
try {
|
|
594
|
-
await consumer.onSet(provider);
|
|
595
|
-
} catch (error) {
|
|
596
|
-
const msg = error instanceof Error ? error.message : String(error);
|
|
597
|
-
this.logger.error(`Consumer onSet (async) failed for ${state.declaration.name}: ${msg}`);
|
|
933
|
+
/**
|
|
934
|
+
* Write a value to SQL system_settings.
|
|
935
|
+
* Throws if the settings store is not yet wired.
|
|
936
|
+
*/
|
|
937
|
+
set(key, value) {
|
|
938
|
+
if (this.settingsStore === null) {
|
|
939
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
598
940
|
}
|
|
941
|
+
this.settingsStore.setSystem(key, value);
|
|
599
942
|
}
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
// src/config-manager.ts
|
|
616
|
-
import * as fs3 from "fs";
|
|
617
|
-
import * as yaml from "js-yaml";
|
|
618
|
-
|
|
619
|
-
// src/config-schema.ts
|
|
620
|
-
import { z } from "zod";
|
|
621
|
-
var DEFAULT_DATA_PATH = "camstack-data";
|
|
622
|
-
var bootstrapSchema = z.object({
|
|
623
|
-
/** Server mode: 'hub' (full server) or 'agent' (worker node) */
|
|
624
|
-
mode: z.enum(["hub", "agent"]).default("hub"),
|
|
625
|
-
server: z.object({
|
|
626
|
-
port: z.number().default(4443),
|
|
627
|
-
host: z.string().default("0.0.0.0"),
|
|
628
|
-
dataPath: z.string().default(DEFAULT_DATA_PATH)
|
|
629
|
-
}).default({}),
|
|
630
|
-
auth: z.object({
|
|
631
|
-
jwtSecret: z.string().nullable().default(null),
|
|
632
|
-
adminUsername: z.string().default("admin"),
|
|
633
|
-
adminPassword: z.string().default(process.env.ADMIN_PASSWORD ?? "changeme")
|
|
634
|
-
}).default({}),
|
|
635
|
-
/** Hub connection config — only used when mode='agent' */
|
|
636
|
-
hub: z.object({
|
|
637
|
-
url: z.string().default("ws://localhost:4443/agent"),
|
|
638
|
-
token: z.string().default("")
|
|
639
|
-
}).default({}),
|
|
640
|
-
/** Agent-specific config — only used when mode='agent' */
|
|
641
|
-
agent: z.object({
|
|
642
|
-
name: z.string().default(""),
|
|
643
|
-
/** Port for the agent status page (minimal HTML) */
|
|
644
|
-
statusPort: z.number().default(4444)
|
|
645
|
-
}).default({}),
|
|
646
|
-
/** TLS configuration */
|
|
647
|
-
tls: z.object({
|
|
648
|
-
/** Enable HTTPS (default: true) */
|
|
649
|
-
enabled: z.boolean().default(true),
|
|
650
|
-
/** Path to custom cert file (PEM). If not set, auto-generates self-signed. */
|
|
651
|
-
certPath: z.string().optional(),
|
|
652
|
-
/** Path to custom key file (PEM). Required if certPath is set. */
|
|
653
|
-
keyPath: z.string().optional()
|
|
654
|
-
}).default({})
|
|
655
|
-
});
|
|
656
|
-
var RUNTIME_DEFAULTS = {
|
|
657
|
-
"features.streaming": true,
|
|
658
|
-
"features.notifications": true,
|
|
659
|
-
"features.objectDetection": false,
|
|
660
|
-
"features.remoteAccess": true,
|
|
661
|
-
"features.agentCluster": false,
|
|
662
|
-
"features.smartHome": true,
|
|
663
|
-
"features.recordings": true,
|
|
664
|
-
"features.backup": true,
|
|
665
|
-
"features.repl": true,
|
|
666
|
-
"retention.detectionEventsDays": 30,
|
|
667
|
-
"retention.audioLevelsDays": 7,
|
|
668
|
-
"logging.level": "info",
|
|
669
|
-
"logging.retentionDays": 30,
|
|
670
|
-
"eventBus.ringBufferSize": 1e4,
|
|
671
|
-
"storage.provider": "sqlite-storage",
|
|
672
|
-
"storage.locations": {
|
|
673
|
-
data: "camstack-data/data",
|
|
674
|
-
media: "camstack-data/media",
|
|
675
|
-
recordings: "camstack-data/recordings",
|
|
676
|
-
cache: "/tmp/camstack-cache",
|
|
677
|
-
logs: "camstack-data/logs",
|
|
678
|
-
models: "camstack-data/models"
|
|
679
|
-
},
|
|
680
|
-
"providers": [],
|
|
681
|
-
// Recording
|
|
682
|
-
"recording.segmentDurationSeconds": 4,
|
|
683
|
-
"recording.defaultRetentionDays": 30,
|
|
684
|
-
// Streaming ports are addon-specific (go2rtc owns its defaults)
|
|
685
|
-
// FFmpeg
|
|
686
|
-
"ffmpeg.binaryPath": "ffmpeg",
|
|
687
|
-
"ffmpeg.hwAccel": "auto",
|
|
688
|
-
"ffmpeg.threadCount": 0,
|
|
689
|
-
// Detection defaults
|
|
690
|
-
"detection.defaultMotionFps": 2,
|
|
691
|
-
"detection.defaultDetectionFps": 5,
|
|
692
|
-
"detection.defaultCooldownSeconds": 10,
|
|
693
|
-
"detection.defaultConfidenceThreshold": 0.4,
|
|
694
|
-
"detection.trackerMaxAgeFrames": 30,
|
|
695
|
-
"detection.trackerMinHits": 3,
|
|
696
|
-
"detection.trackerIouThreshold": 0.3,
|
|
697
|
-
// Backup retention is addon-specific (local-backup owns its default)
|
|
698
|
-
// Auth (runtime)
|
|
699
|
-
"auth.tokenExpiry": "24h"
|
|
700
|
-
};
|
|
701
|
-
|
|
702
|
-
// src/config-manager.ts
|
|
703
|
-
var ENV_VAR_MAP = {
|
|
704
|
-
CAMSTACK_PORT: "server.port",
|
|
705
|
-
CAMSTACK_HOST: "server.host",
|
|
706
|
-
CAMSTACK_DATA: "server.dataPath",
|
|
707
|
-
CAMSTACK_JWT_SECRET: "auth.jwtSecret",
|
|
708
|
-
CAMSTACK_ADMIN_USER: "auth.adminUsername",
|
|
709
|
-
CAMSTACK_ADMIN_PASS: "auth.adminPassword"
|
|
710
|
-
};
|
|
711
|
-
var ConfigManager = class _ConfigManager {
|
|
712
|
-
constructor(configPath) {
|
|
713
|
-
this.configPath = configPath;
|
|
714
|
-
const rawYaml = this.loadYaml();
|
|
715
|
-
const merged = this.applyEnvOverrides(rawYaml);
|
|
716
|
-
this.bootstrapConfig = bootstrapSchema.parse(merged);
|
|
717
|
-
this.warnDefaultCredentials();
|
|
718
|
-
}
|
|
719
|
-
// Non-readonly so update() can sync the in-memory view after a write.
|
|
720
|
-
bootstrapConfig;
|
|
721
|
-
settingsStore = null;
|
|
722
|
-
/** Called by main.ts after the SQLite DB is ready (Phase 2). */
|
|
723
|
-
setSettingsStore(store) {
|
|
724
|
-
this.settingsStore = store;
|
|
725
|
-
}
|
|
726
|
-
/**
|
|
727
|
-
* Get a config value by dot-notation path.
|
|
728
|
-
* Priority: bootstrap config -> SQL system_settings -> RUNTIME_DEFAULTS fallback.
|
|
729
|
-
*/
|
|
730
|
-
get(path3) {
|
|
731
|
-
const bootstrapValue = this.getFromBootstrap(path3);
|
|
732
|
-
if (bootstrapValue !== void 0) {
|
|
733
|
-
return bootstrapValue;
|
|
734
|
-
}
|
|
735
|
-
if (this.settingsStore !== null) {
|
|
736
|
-
const sqlValue = this.settingsStore.getSystem(path3);
|
|
737
|
-
if (sqlValue !== void 0) {
|
|
738
|
-
return sqlValue;
|
|
943
|
+
/**
|
|
944
|
+
* Bulk-read all system_settings keys that belong to a logical section.
|
|
945
|
+
* A "section" is the first segment of a dot-notation key (e.g. 'features', 'logging').
|
|
946
|
+
*/
|
|
947
|
+
getSection(section) {
|
|
948
|
+
if (this.settingsStore !== null) {
|
|
949
|
+
const nested = this.getNestedFromSystemSettings(section);
|
|
950
|
+
if (nested !== void 0)
|
|
951
|
+
return nested;
|
|
952
|
+
}
|
|
953
|
+
const bootstrapValue = this.bootstrapConfig[section];
|
|
954
|
+
if (bootstrapValue !== void 0 && bootstrapValue !== null && typeof bootstrapValue === "object") {
|
|
955
|
+
return bootstrapValue;
|
|
956
|
+
}
|
|
957
|
+
return this.getFromRuntimeDefaults(section) ?? {};
|
|
739
958
|
}
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
959
|
+
/**
|
|
960
|
+
* Bulk-write a section of runtime settings to SQL system_settings.
|
|
961
|
+
* Each entry in `data` is stored as `section.key`.
|
|
962
|
+
*/
|
|
963
|
+
setSection(section, data) {
|
|
964
|
+
if (this.settingsStore === null) {
|
|
965
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
966
|
+
}
|
|
967
|
+
for (const [key, value] of Object.entries(data)) {
|
|
968
|
+
this.settingsStore.setSystem(`${section}.${key}`, value);
|
|
969
|
+
}
|
|
743
970
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
}
|
|
904
|
-
let raw = {};
|
|
905
|
-
if (fs3.existsSync(this.configPath)) {
|
|
906
|
-
raw = yaml.load(fs3.readFileSync(this.configPath, "utf-8")) ?? {};
|
|
907
|
-
}
|
|
908
|
-
const existing = raw[section] ?? {};
|
|
909
|
-
raw[section] = { ...existing, ...data };
|
|
910
|
-
const validation = bootstrapSchema.safeParse(raw);
|
|
911
|
-
if (!validation.success) {
|
|
912
|
-
throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
|
|
913
|
-
}
|
|
914
|
-
const tmpPath = `${this.configPath}.tmp`;
|
|
915
|
-
fs3.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
|
|
916
|
-
fs3.renameSync(tmpPath, this.configPath);
|
|
917
|
-
this.bootstrapConfig = validation.data;
|
|
918
|
-
}
|
|
919
|
-
/**
|
|
920
|
-
* Deep-set a value in a nested plain object using a dot-notation path.
|
|
921
|
-
* Returns a new object (immutable).
|
|
922
|
-
*/
|
|
923
|
-
setNested(obj, path3, value) {
|
|
924
|
-
const [head, ...rest] = path3.split(".");
|
|
925
|
-
if (!head) return obj;
|
|
926
|
-
if (rest.length === 0) {
|
|
927
|
-
return { ...obj, [head]: value };
|
|
928
|
-
}
|
|
929
|
-
const child = obj[head] ?? {};
|
|
930
|
-
return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
|
|
931
|
-
}
|
|
932
|
-
/**
|
|
933
|
-
* Apply env var overrides onto the raw YAML object.
|
|
934
|
-
* Only bootstrap-level env vars are applied.
|
|
935
|
-
*/
|
|
936
|
-
applyEnvOverrides(raw) {
|
|
937
|
-
let result = { ...raw };
|
|
938
|
-
for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
|
|
939
|
-
const envValue = process.env[envKey];
|
|
940
|
-
if (envValue === void 0 || envValue === "") continue;
|
|
941
|
-
const coerced = configPath === "server.port" ? Number(envValue) : envValue;
|
|
942
|
-
result = this.setNested(result, configPath, coerced);
|
|
943
|
-
console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
|
|
944
|
-
}
|
|
945
|
-
return result;
|
|
946
|
-
}
|
|
947
|
-
loadYaml() {
|
|
948
|
-
if (!fs3.existsSync(this.configPath)) {
|
|
949
|
-
console.warn(
|
|
950
|
-
`[ConfigManager] Config file not found at: ${this.configPath}
|
|
971
|
+
// ---------------------------------------------------------------------------
|
|
972
|
+
// Addon / Provider / Device scoped config
|
|
973
|
+
// ---------------------------------------------------------------------------
|
|
974
|
+
/** Read all config for an addon from addon_settings. */
|
|
975
|
+
getAddonConfig(addonId) {
|
|
976
|
+
if (this.settingsStore !== null) {
|
|
977
|
+
return this.settingsStore.getAllAddon(addonId);
|
|
978
|
+
}
|
|
979
|
+
return this.getFromBootstrap(`addons.${addonId}`) ?? {};
|
|
980
|
+
}
|
|
981
|
+
/** Write (bulk-replace) config for an addon to addon_settings. */
|
|
982
|
+
setAddonConfig(addonId, config) {
|
|
983
|
+
if (this.settingsStore === null) {
|
|
984
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
985
|
+
}
|
|
986
|
+
this.settingsStore.setAllAddon(addonId, config);
|
|
987
|
+
}
|
|
988
|
+
/** Read all config for a provider from provider_settings. */
|
|
989
|
+
getProviderConfig(providerId) {
|
|
990
|
+
if (this.settingsStore !== null) {
|
|
991
|
+
return this.settingsStore.getAllProvider(providerId);
|
|
992
|
+
}
|
|
993
|
+
return {};
|
|
994
|
+
}
|
|
995
|
+
/** Write (upsert) a single key for a provider to provider_settings. */
|
|
996
|
+
setProviderConfig(providerId, key, value) {
|
|
997
|
+
if (this.settingsStore === null) {
|
|
998
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
999
|
+
}
|
|
1000
|
+
this.settingsStore.setProvider(providerId, key, value);
|
|
1001
|
+
}
|
|
1002
|
+
/** Read all config for a device from device_settings. */
|
|
1003
|
+
getDeviceConfig(deviceId) {
|
|
1004
|
+
if (this.settingsStore !== null) {
|
|
1005
|
+
return this.settingsStore.getAllDevice(deviceId);
|
|
1006
|
+
}
|
|
1007
|
+
return {};
|
|
1008
|
+
}
|
|
1009
|
+
/** Write (upsert) a single key for a device to device_settings. */
|
|
1010
|
+
setDeviceConfig(deviceId, key, value) {
|
|
1011
|
+
if (this.settingsStore === null) {
|
|
1012
|
+
throw new Error("[ConfigManager] SettingsStore not initialized -- call setSettingsStore() first");
|
|
1013
|
+
}
|
|
1014
|
+
this.settingsStore.setDevice(deviceId, key, value);
|
|
1015
|
+
}
|
|
1016
|
+
/** Get a value from the parsed bootstrap config */
|
|
1017
|
+
getBootstrap(path) {
|
|
1018
|
+
return this.getFromBootstrap(path);
|
|
1019
|
+
}
|
|
1020
|
+
/** Features accessor -- reads from SQL when available, falls back to RUNTIME_DEFAULTS */
|
|
1021
|
+
get features() {
|
|
1022
|
+
const g = (key) => this.get(`features.${key}`) ?? config_schema_js_1.RUNTIME_DEFAULTS[`features.${key}`];
|
|
1023
|
+
return {
|
|
1024
|
+
streaming: g("streaming"),
|
|
1025
|
+
notifications: g("notifications"),
|
|
1026
|
+
objectDetection: g("objectDetection"),
|
|
1027
|
+
remoteAccess: g("remoteAccess"),
|
|
1028
|
+
agentCluster: g("agentCluster"),
|
|
1029
|
+
smartHome: g("smartHome"),
|
|
1030
|
+
recordings: g("recordings"),
|
|
1031
|
+
backup: g("backup"),
|
|
1032
|
+
repl: g("repl")
|
|
1033
|
+
};
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Returns a merged view of bootstrap config + runtime defaults for backward compat.
|
|
1037
|
+
*/
|
|
1038
|
+
get raw() {
|
|
1039
|
+
const features = {
|
|
1040
|
+
streaming: config_schema_js_1.RUNTIME_DEFAULTS["features.streaming"],
|
|
1041
|
+
notifications: config_schema_js_1.RUNTIME_DEFAULTS["features.notifications"],
|
|
1042
|
+
objectDetection: config_schema_js_1.RUNTIME_DEFAULTS["features.objectDetection"],
|
|
1043
|
+
remoteAccess: config_schema_js_1.RUNTIME_DEFAULTS["features.remoteAccess"],
|
|
1044
|
+
agentCluster: config_schema_js_1.RUNTIME_DEFAULTS["features.agentCluster"],
|
|
1045
|
+
smartHome: config_schema_js_1.RUNTIME_DEFAULTS["features.smartHome"],
|
|
1046
|
+
recordings: config_schema_js_1.RUNTIME_DEFAULTS["features.recordings"],
|
|
1047
|
+
backup: config_schema_js_1.RUNTIME_DEFAULTS["features.backup"],
|
|
1048
|
+
repl: config_schema_js_1.RUNTIME_DEFAULTS["features.repl"]
|
|
1049
|
+
};
|
|
1050
|
+
return {
|
|
1051
|
+
...this.bootstrapConfig,
|
|
1052
|
+
features,
|
|
1053
|
+
storage: config_schema_js_1.RUNTIME_DEFAULTS["storage.locations"] !== void 0 ? {
|
|
1054
|
+
provider: config_schema_js_1.RUNTIME_DEFAULTS["storage.provider"],
|
|
1055
|
+
locations: config_schema_js_1.RUNTIME_DEFAULTS["storage.locations"]
|
|
1056
|
+
} : { provider: "sqlite-storage", locations: {} },
|
|
1057
|
+
logging: {
|
|
1058
|
+
level: config_schema_js_1.RUNTIME_DEFAULTS["logging.level"],
|
|
1059
|
+
retentionDays: config_schema_js_1.RUNTIME_DEFAULTS["logging.retentionDays"]
|
|
1060
|
+
},
|
|
1061
|
+
eventBus: {
|
|
1062
|
+
ringBufferSize: config_schema_js_1.RUNTIME_DEFAULTS["eventBus.ringBufferSize"]
|
|
1063
|
+
},
|
|
1064
|
+
retention: {
|
|
1065
|
+
detectionEventsDays: config_schema_js_1.RUNTIME_DEFAULTS["retention.detectionEventsDays"],
|
|
1066
|
+
audioLevelsDays: config_schema_js_1.RUNTIME_DEFAULTS["retention.audioLevelsDays"]
|
|
1067
|
+
},
|
|
1068
|
+
providers: config_schema_js_1.RUNTIME_DEFAULTS["providers"]
|
|
1069
|
+
};
|
|
1070
|
+
}
|
|
1071
|
+
/** Sections that live in config.yaml. Everything else goes to SQL. */
|
|
1072
|
+
static BOOTSTRAP_SECTIONS = /* @__PURE__ */ new Set(["server", "auth", "mode"]);
|
|
1073
|
+
/**
|
|
1074
|
+
* Atomically update one top-level section of config.yaml and sync in-memory.
|
|
1075
|
+
* Only bootstrap sections (server, auth, mode) are written to YAML.
|
|
1076
|
+
* Runtime settings must use setSection() which writes to SQL.
|
|
1077
|
+
*/
|
|
1078
|
+
update(section, data) {
|
|
1079
|
+
if (!_ConfigManager.BOOTSTRAP_SECTIONS.has(section)) {
|
|
1080
|
+
throw new Error(`[ConfigManager] Section "${section}" is a runtime setting \u2014 use setSection() to write to DB, not update() which writes to config.yaml`);
|
|
1081
|
+
}
|
|
1082
|
+
let raw = {};
|
|
1083
|
+
if (fs.existsSync(this.configPath)) {
|
|
1084
|
+
raw = yaml.load(fs.readFileSync(this.configPath, "utf-8")) ?? {};
|
|
1085
|
+
}
|
|
1086
|
+
const existing = raw[section] ?? {};
|
|
1087
|
+
raw[section] = { ...existing, ...data };
|
|
1088
|
+
const validation = config_schema_js_1.bootstrapSchema.safeParse(raw);
|
|
1089
|
+
if (!validation.success) {
|
|
1090
|
+
throw new Error(`[ConfigManager] Invalid config update for section "${section}": ${validation.error.message}`);
|
|
1091
|
+
}
|
|
1092
|
+
const tmpPath = `${this.configPath}.tmp`;
|
|
1093
|
+
fs.writeFileSync(tmpPath, yaml.dump(raw, { lineWidth: 120, indent: 2, quotingType: '"' }), "utf-8");
|
|
1094
|
+
fs.renameSync(tmpPath, this.configPath);
|
|
1095
|
+
this.bootstrapConfig = validation.data;
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Deep-set a value in a nested plain object using a dot-notation path.
|
|
1099
|
+
* Returns a new object (immutable).
|
|
1100
|
+
*/
|
|
1101
|
+
setNested(obj, path, value) {
|
|
1102
|
+
const [head, ...rest] = path.split(".");
|
|
1103
|
+
if (!head)
|
|
1104
|
+
return obj;
|
|
1105
|
+
if (rest.length === 0) {
|
|
1106
|
+
return { ...obj, [head]: value };
|
|
1107
|
+
}
|
|
1108
|
+
const child = obj[head] ?? {};
|
|
1109
|
+
return { ...obj, [head]: this.setNested(child, rest.join("."), value) };
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Apply env var overrides onto the raw YAML object.
|
|
1113
|
+
* Only bootstrap-level env vars are applied.
|
|
1114
|
+
*/
|
|
1115
|
+
applyEnvOverrides(raw) {
|
|
1116
|
+
let result = { ...raw };
|
|
1117
|
+
for (const [envKey, configPath] of Object.entries(ENV_VAR_MAP)) {
|
|
1118
|
+
const envValue = process.env[envKey];
|
|
1119
|
+
if (envValue === void 0 || envValue === "")
|
|
1120
|
+
continue;
|
|
1121
|
+
const coerced = configPath === "server.port" ? Number(envValue) : envValue;
|
|
1122
|
+
result = this.setNested(result, configPath, coerced);
|
|
1123
|
+
console.log(`[ConfigManager] Env override applied: ${envKey} \u2192 ${configPath}`);
|
|
1124
|
+
}
|
|
1125
|
+
return result;
|
|
1126
|
+
}
|
|
1127
|
+
loadYaml() {
|
|
1128
|
+
if (!fs.existsSync(this.configPath)) {
|
|
1129
|
+
console.warn(`[ConfigManager] Config file not found at: ${this.configPath}
|
|
951
1130
|
\u2192 Using built-in defaults. Set CONFIG_PATH env var or create the file.
|
|
952
|
-
\u2192 Example path from project root: ./server/backend/data/config.yaml`
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
return parsed;
|
|
960
|
-
}
|
|
961
|
-
warnDefaultCredentials() {
|
|
962
|
-
if (this.bootstrapConfig.auth.adminPassword === "changeme") {
|
|
963
|
-
console.warn(
|
|
964
|
-
`[ConfigManager] Warning: Using default admin password "changeme". Set auth.adminPassword in your config.yaml or the ADMIN_PASSWORD env var.`
|
|
965
|
-
);
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
getFromBootstrap(path3) {
|
|
969
|
-
const keys = path3.split(".");
|
|
970
|
-
let current = this.bootstrapConfig;
|
|
971
|
-
for (const key of keys) {
|
|
972
|
-
if (current === null || current === void 0 || typeof current !== "object") {
|
|
973
|
-
return void 0;
|
|
1131
|
+
\u2192 Example path from project root: ./server/backend/data/config.yaml`);
|
|
1132
|
+
return {};
|
|
1133
|
+
}
|
|
1134
|
+
const content = fs.readFileSync(this.configPath, "utf-8");
|
|
1135
|
+
const parsed = yaml.load(content) ?? {};
|
|
1136
|
+
console.log(`[ConfigManager] Loaded config from: ${this.configPath}`);
|
|
1137
|
+
return parsed;
|
|
974
1138
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
getFromRuntimeDefaults(path3) {
|
|
980
|
-
const prefix = path3 + ".";
|
|
981
|
-
const result = {};
|
|
982
|
-
let found = false;
|
|
983
|
-
for (const [key, value] of Object.entries(RUNTIME_DEFAULTS)) {
|
|
984
|
-
if (key.startsWith(prefix)) {
|
|
985
|
-
const subKey = key.slice(prefix.length);
|
|
986
|
-
result[subKey] = value;
|
|
987
|
-
found = true;
|
|
1139
|
+
warnDefaultCredentials() {
|
|
1140
|
+
if (this.bootstrapConfig.auth.adminPassword === "changeme") {
|
|
1141
|
+
console.warn(`[ConfigManager] Warning: Using default admin password "changeme". Set auth.adminPassword in your config.yaml or the ADMIN_PASSWORD env var.`);
|
|
1142
|
+
}
|
|
988
1143
|
}
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1144
|
+
getFromBootstrap(path) {
|
|
1145
|
+
const keys = path.split(".");
|
|
1146
|
+
let current = this.bootstrapConfig;
|
|
1147
|
+
for (const key of keys) {
|
|
1148
|
+
if (current === null || current === void 0 || typeof current !== "object") {
|
|
1149
|
+
return void 0;
|
|
1150
|
+
}
|
|
1151
|
+
current = current[key];
|
|
1152
|
+
}
|
|
1153
|
+
return current;
|
|
1154
|
+
}
|
|
1155
|
+
getFromRuntimeDefaults(path) {
|
|
1156
|
+
const prefix = path + ".";
|
|
1157
|
+
const result = {};
|
|
1158
|
+
let found = false;
|
|
1159
|
+
for (const [key, value] of Object.entries(config_schema_js_1.RUNTIME_DEFAULTS)) {
|
|
1160
|
+
if (key.startsWith(prefix)) {
|
|
1161
|
+
const subKey = key.slice(prefix.length);
|
|
1162
|
+
result[subKey] = value;
|
|
1163
|
+
found = true;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return found ? result : void 0;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Perform a prefix-based nested lookup against SQL system_settings.
|
|
1170
|
+
* e.g. path='features' matches keys 'features.streaming', 'features.notifications', etc.
|
|
1171
|
+
* Returns an object keyed by the sub-key, or undefined if nothing is found.
|
|
1172
|
+
*/
|
|
1173
|
+
getNestedFromSystemSettings(path) {
|
|
1174
|
+
if (this.settingsStore === null)
|
|
1175
|
+
return void 0;
|
|
1176
|
+
const all = this.settingsStore.getAllSystem();
|
|
1177
|
+
const prefix = path + ".";
|
|
1178
|
+
const result = {};
|
|
1179
|
+
let found = false;
|
|
1180
|
+
for (const [key, value] of Object.entries(all)) {
|
|
1181
|
+
if (key.startsWith(prefix)) {
|
|
1182
|
+
result[key.slice(prefix.length)] = value;
|
|
1183
|
+
found = true;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return found ? result : void 0;
|
|
1007
1187
|
}
|
|
1008
|
-
}
|
|
1009
|
-
return found ? result : void 0;
|
|
1010
|
-
}
|
|
1011
|
-
};
|
|
1012
|
-
|
|
1013
|
-
// src/worker/addon-worker-host.ts
|
|
1014
|
-
import { fork } from "child_process";
|
|
1015
|
-
var INFRA_ADDON_IDS = /* @__PURE__ */ new Set([
|
|
1016
|
-
"filesystem-storage",
|
|
1017
|
-
"sqlite-settings",
|
|
1018
|
-
"winston-logging"
|
|
1019
|
-
]);
|
|
1020
|
-
var AddonWorkerHost = class {
|
|
1021
|
-
workers = /* @__PURE__ */ new Map();
|
|
1022
|
-
options;
|
|
1023
|
-
heartbeatTimer = null;
|
|
1024
|
-
/** Set of addons that failed to fork and fell back to in-process */
|
|
1025
|
-
fallbackInProcess = /* @__PURE__ */ new Set();
|
|
1026
|
-
constructor(options) {
|
|
1027
|
-
this.options = {
|
|
1028
|
-
workerEntryPath: options.workerEntryPath,
|
|
1029
|
-
devMode: options.devMode ?? false,
|
|
1030
|
-
forceInProcess: options.forceInProcess ?? process.env.CAMSTACK_FORCE_INPROCESS === "true",
|
|
1031
|
-
heartbeatIntervalMs: options.heartbeatIntervalMs ?? 5e3,
|
|
1032
|
-
heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 3e4,
|
|
1033
|
-
maxCrashesInWindow: options.maxCrashesInWindow ?? 3,
|
|
1034
|
-
crashWindowMs: options.crashWindowMs ?? 6e4,
|
|
1035
|
-
shutdownTimeoutMs: options.shutdownTimeoutMs ?? 1e4,
|
|
1036
|
-
onWorkerLog: options.onWorkerLog
|
|
1037
1188
|
};
|
|
1189
|
+
exports.ConfigManager = ConfigManager2;
|
|
1038
1190
|
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
const workerEnv = {
|
|
1072
|
-
PATH: process.env.PATH ?? "",
|
|
1073
|
-
HOME: process.env.HOME ?? "",
|
|
1074
|
-
NODE_ENV: process.env.NODE_ENV ?? "production",
|
|
1075
|
-
NODE_TLS_REJECT_UNAUTHORIZED: "0",
|
|
1076
|
-
// Accept self-signed cert
|
|
1077
|
-
CAMSTACK_WORKER_HUB_URL: `wss://localhost:${process.env.CAMSTACK_PORT ?? "4443"}/trpc`,
|
|
1078
|
-
CAMSTACK_WORKER_TOKEN: workerToken ?? "",
|
|
1079
|
-
CAMSTACK_ADDON_ID: addonId,
|
|
1080
|
-
CAMSTACK_ADDON_DIR: addonDir,
|
|
1081
|
-
CAMSTACK_ADDON_CONFIG: JSON.stringify(config),
|
|
1082
|
-
CAMSTACK_DATA_DIR: dataDir ?? `camstack-data/addons-data/${addonId}`,
|
|
1083
|
-
CAMSTACK_LOCATION_PATHS: JSON.stringify(locationPaths ?? storagePaths)
|
|
1084
|
-
};
|
|
1085
|
-
const forkOptions = {
|
|
1086
|
-
stdio: ["inherit", "inherit", "inherit", "ipc"],
|
|
1087
|
-
execArgv: [],
|
|
1088
|
-
env: workerEnv
|
|
1089
|
-
};
|
|
1090
|
-
const child = fork(this.options.workerEntryPath, [], forkOptions);
|
|
1091
|
-
const worker = {
|
|
1092
|
-
addonId,
|
|
1093
|
-
process: child,
|
|
1094
|
-
state: "starting",
|
|
1095
|
-
startedAt: Date.now(),
|
|
1096
|
-
lastHeartbeat: Date.now(),
|
|
1097
|
-
restartCount: 0,
|
|
1098
|
-
crashTimestamps: [],
|
|
1099
|
-
cpuPercent: 0,
|
|
1100
|
-
memoryRss: 0,
|
|
1101
|
-
workerToken
|
|
1102
|
-
};
|
|
1103
|
-
this.workers.set(addonId, worker);
|
|
1104
|
-
child.on("message", (msg) => {
|
|
1105
|
-
if (msg.type === "LOG" && this.options.onWorkerLog) {
|
|
1106
|
-
this.options.onWorkerLog({
|
|
1107
|
-
addonId,
|
|
1108
|
-
level: msg.level,
|
|
1109
|
-
message: msg.message,
|
|
1110
|
-
scope: ["hub", addonId],
|
|
1111
|
-
meta: msg.context
|
|
1112
|
-
});
|
|
1113
|
-
} else if (msg.type === "STATS") {
|
|
1114
|
-
worker.cpuPercent = msg.cpu;
|
|
1115
|
-
worker.memoryRss = msg.memory;
|
|
1191
|
+
});
|
|
1192
|
+
|
|
1193
|
+
// src/worker/addon-worker-host.js
|
|
1194
|
+
var require_addon_worker_host = __commonJS({
|
|
1195
|
+
"src/worker/addon-worker-host.js"(exports) {
|
|
1196
|
+
"use strict";
|
|
1197
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1198
|
+
exports.AddonWorkerHost = void 0;
|
|
1199
|
+
var node_child_process_1 = __require("child_process");
|
|
1200
|
+
var INFRA_ADDON_IDS = /* @__PURE__ */ new Set([
|
|
1201
|
+
"filesystem-storage",
|
|
1202
|
+
"sqlite-settings",
|
|
1203
|
+
"winston-logging"
|
|
1204
|
+
]);
|
|
1205
|
+
var AddonWorkerHost2 = class {
|
|
1206
|
+
workers = /* @__PURE__ */ new Map();
|
|
1207
|
+
options;
|
|
1208
|
+
heartbeatTimer = null;
|
|
1209
|
+
/** Set of addons that failed to fork and fell back to in-process */
|
|
1210
|
+
fallbackInProcess = /* @__PURE__ */ new Set();
|
|
1211
|
+
constructor(options) {
|
|
1212
|
+
this.options = {
|
|
1213
|
+
workerEntryPath: options.workerEntryPath,
|
|
1214
|
+
devMode: options.devMode ?? false,
|
|
1215
|
+
forceInProcess: options.forceInProcess ?? process.env.CAMSTACK_FORCE_INPROCESS === "true",
|
|
1216
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? 5e3,
|
|
1217
|
+
heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 3e4,
|
|
1218
|
+
maxCrashesInWindow: options.maxCrashesInWindow ?? 3,
|
|
1219
|
+
crashWindowMs: options.crashWindowMs ?? 6e4,
|
|
1220
|
+
shutdownTimeoutMs: options.shutdownTimeoutMs ?? 1e4,
|
|
1221
|
+
onWorkerLog: options.onWorkerLog
|
|
1222
|
+
};
|
|
1116
1223
|
}
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
if (!lines) return;
|
|
1121
|
-
if (this.options.onWorkerLog) {
|
|
1122
|
-
this.options.onWorkerLog({
|
|
1123
|
-
addonId,
|
|
1124
|
-
level: "info",
|
|
1125
|
-
message: lines,
|
|
1126
|
-
scope: ["hub", addonId, "__stdout"]
|
|
1127
|
-
});
|
|
1128
|
-
} else {
|
|
1129
|
-
console.log(`[Worker:${addonId}] ${lines}`);
|
|
1224
|
+
/** Check if an addon is infrastructure (must stay in-process) */
|
|
1225
|
+
isInfraAddon(addonId) {
|
|
1226
|
+
return INFRA_ADDON_IDS.has(addonId);
|
|
1130
1227
|
}
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1228
|
+
/** Check if an addon fell back to in-process after fork failure */
|
|
1229
|
+
isFallbackInProcess(addonId) {
|
|
1230
|
+
return this.fallbackInProcess.has(addonId);
|
|
1231
|
+
}
|
|
1232
|
+
/** Mark an addon as fallen back to in-process */
|
|
1233
|
+
markFallbackInProcess(addonId) {
|
|
1234
|
+
this.fallbackInProcess.add(addonId);
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Determine if an addon should be forked.
|
|
1238
|
+
* Default: fork everything except infra addons.
|
|
1239
|
+
* Addons can opt out with `inProcess: true` in declaration.
|
|
1240
|
+
* Emergency fallback: CAMSTACK_FORCE_INPROCESS=true disables all forking.
|
|
1241
|
+
*/
|
|
1242
|
+
shouldFork(addonId, declaration) {
|
|
1243
|
+
if (this.options.forceInProcess)
|
|
1244
|
+
return false;
|
|
1245
|
+
if (this.options.devMode)
|
|
1246
|
+
return false;
|
|
1247
|
+
if (this.isInfraAddon(addonId))
|
|
1248
|
+
return false;
|
|
1249
|
+
if (this.fallbackInProcess.has(addonId))
|
|
1250
|
+
return false;
|
|
1251
|
+
if (declaration?.inProcess === true)
|
|
1252
|
+
return false;
|
|
1253
|
+
if (declaration?.forkable !== true)
|
|
1254
|
+
return false;
|
|
1255
|
+
return true;
|
|
1256
|
+
}
|
|
1257
|
+
/** Fork a worker for an addon */
|
|
1258
|
+
async forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1259
|
+
if (this.workers.has(addonId)) {
|
|
1260
|
+
throw new Error(`Worker for addon "${addonId}" already exists`);
|
|
1261
|
+
}
|
|
1262
|
+
const workerEnv = {
|
|
1263
|
+
PATH: process.env.PATH ?? "",
|
|
1264
|
+
HOME: process.env.HOME ?? "",
|
|
1265
|
+
NODE_ENV: process.env.NODE_ENV ?? "production",
|
|
1266
|
+
NODE_TLS_REJECT_UNAUTHORIZED: "0",
|
|
1267
|
+
// Accept self-signed cert
|
|
1268
|
+
CAMSTACK_WORKER_HUB_URL: `wss://localhost:${process.env.CAMSTACK_PORT ?? "4443"}/trpc`,
|
|
1269
|
+
CAMSTACK_WORKER_TOKEN: workerToken ?? "",
|
|
1270
|
+
CAMSTACK_ADDON_ID: addonId,
|
|
1271
|
+
CAMSTACK_ADDON_DIR: addonDir,
|
|
1272
|
+
CAMSTACK_ADDON_CONFIG: JSON.stringify(config),
|
|
1273
|
+
CAMSTACK_DATA_DIR: dataDir ?? `camstack-data/addons-data/${addonId}`,
|
|
1274
|
+
CAMSTACK_LOCATION_PATHS: JSON.stringify(locationPaths ?? storagePaths)
|
|
1275
|
+
};
|
|
1276
|
+
const forkOptions = {
|
|
1277
|
+
stdio: ["inherit", "inherit", "inherit", "ipc"],
|
|
1278
|
+
execArgv: [],
|
|
1279
|
+
env: workerEnv
|
|
1280
|
+
};
|
|
1281
|
+
const child = (0, node_child_process_1.fork)(this.options.workerEntryPath, [], forkOptions);
|
|
1282
|
+
const worker = {
|
|
1137
1283
|
addonId,
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1284
|
+
process: child,
|
|
1285
|
+
state: "starting",
|
|
1286
|
+
startedAt: Date.now(),
|
|
1287
|
+
lastHeartbeat: Date.now(),
|
|
1288
|
+
restartCount: 0,
|
|
1289
|
+
crashTimestamps: [],
|
|
1290
|
+
cpuPercent: 0,
|
|
1291
|
+
memoryRss: 0,
|
|
1292
|
+
workerToken
|
|
1293
|
+
};
|
|
1294
|
+
this.workers.set(addonId, worker);
|
|
1295
|
+
child.on("message", (msg) => {
|
|
1296
|
+
if (msg.type === "LOG" && this.options.onWorkerLog) {
|
|
1297
|
+
this.options.onWorkerLog({
|
|
1298
|
+
addonId,
|
|
1299
|
+
level: msg.level,
|
|
1300
|
+
message: msg.message,
|
|
1301
|
+
scope: ["hub", addonId],
|
|
1302
|
+
meta: msg.context
|
|
1303
|
+
});
|
|
1304
|
+
} else if (msg.type === "STATS") {
|
|
1305
|
+
worker.cpuPercent = msg.cpu;
|
|
1306
|
+
worker.memoryRss = msg.memory;
|
|
1307
|
+
}
|
|
1308
|
+
});
|
|
1309
|
+
child.stdout?.on("data", (chunk) => {
|
|
1310
|
+
const lines = chunk.toString().trim();
|
|
1311
|
+
if (!lines)
|
|
1312
|
+
return;
|
|
1313
|
+
if (this.options.onWorkerLog) {
|
|
1314
|
+
this.options.onWorkerLog({
|
|
1315
|
+
addonId,
|
|
1316
|
+
level: "info",
|
|
1317
|
+
message: lines,
|
|
1318
|
+
scope: ["hub", addonId, "__stdout"]
|
|
1319
|
+
});
|
|
1320
|
+
} else {
|
|
1321
|
+
console.log(`[Worker:${addonId}] ${lines}`);
|
|
1322
|
+
}
|
|
1323
|
+
});
|
|
1324
|
+
child.stderr?.on("data", (chunk) => {
|
|
1325
|
+
const lines = chunk.toString().trim();
|
|
1326
|
+
if (!lines)
|
|
1327
|
+
return;
|
|
1328
|
+
if (this.options.onWorkerLog) {
|
|
1329
|
+
this.options.onWorkerLog({
|
|
1330
|
+
addonId,
|
|
1331
|
+
level: "error",
|
|
1332
|
+
message: lines,
|
|
1333
|
+
scope: ["hub", addonId, "__stderr"]
|
|
1334
|
+
});
|
|
1335
|
+
} else {
|
|
1336
|
+
console.error(`[Worker:${addonId}:ERR] ${lines}`);
|
|
1337
|
+
}
|
|
1338
|
+
});
|
|
1339
|
+
child.on("exit", (code) => {
|
|
1340
|
+
this.handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken);
|
|
1341
|
+
});
|
|
1342
|
+
child.on("error", (err) => {
|
|
1343
|
+
console.error(`[WorkerHost] Worker ${addonId} error:`, err.message);
|
|
1344
|
+
});
|
|
1345
|
+
await new Promise((resolve, reject) => {
|
|
1346
|
+
const timeout = setTimeout(() => {
|
|
1347
|
+
reject(new Error(`Worker ${addonId} did not become ready within 30s`));
|
|
1348
|
+
}, 3e4);
|
|
1349
|
+
const readyCheck = (msg) => {
|
|
1350
|
+
if (msg.type === "READY") {
|
|
1351
|
+
clearTimeout(timeout);
|
|
1352
|
+
child.off("message", readyCheck);
|
|
1353
|
+
worker.state = "running";
|
|
1354
|
+
resolve();
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
child.on("message", readyCheck);
|
|
1141
1358
|
});
|
|
1142
|
-
} else {
|
|
1143
|
-
console.error(`[Worker:${addonId}:ERR] ${lines}`);
|
|
1144
1359
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1360
|
+
/** List all workers with stats */
|
|
1361
|
+
listWorkers() {
|
|
1362
|
+
return [...this.workers.values()].map((w) => ({
|
|
1363
|
+
addonId: w.addonId,
|
|
1364
|
+
pid: w.process.pid ?? 0,
|
|
1365
|
+
state: w.state,
|
|
1366
|
+
cpuPercent: w.cpuPercent,
|
|
1367
|
+
memoryRss: w.memoryRss,
|
|
1368
|
+
uptimeSeconds: Math.round((Date.now() - w.startedAt) / 1e3),
|
|
1369
|
+
restartCount: w.restartCount,
|
|
1370
|
+
subProcesses: []
|
|
1371
|
+
}));
|
|
1372
|
+
}
|
|
1373
|
+
/** Gracefully shutdown a single worker by addon ID */
|
|
1374
|
+
async shutdownWorkerById(addonId) {
|
|
1375
|
+
const worker = this.workers.get(addonId);
|
|
1376
|
+
if (!worker) {
|
|
1377
|
+
throw new Error(`No worker found for addon "${addonId}"`);
|
|
1162
1378
|
}
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
if (worker.state
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
|
|
1248
|
-
console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
|
|
1249
|
-
});
|
|
1250
|
-
}, backoff);
|
|
1251
|
-
}
|
|
1252
|
-
async shutdownWorker(addonId, worker) {
|
|
1253
|
-
worker.state = "stopping";
|
|
1254
|
-
worker.process.kill("SIGTERM");
|
|
1255
|
-
await new Promise((resolve3) => {
|
|
1256
|
-
const timeout = setTimeout(() => {
|
|
1257
|
-
console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
|
|
1258
|
-
worker.process.kill("SIGKILL");
|
|
1259
|
-
resolve3();
|
|
1260
|
-
}, this.options.shutdownTimeoutMs);
|
|
1261
|
-
worker.process.on("exit", () => {
|
|
1262
|
-
clearTimeout(timeout);
|
|
1263
|
-
resolve3();
|
|
1264
|
-
});
|
|
1265
|
-
});
|
|
1379
|
+
await this.shutdownWorker(addonId, worker);
|
|
1380
|
+
this.workers.delete(addonId);
|
|
1381
|
+
}
|
|
1382
|
+
/** Gracefully shutdown all workers */
|
|
1383
|
+
async shutdownAll() {
|
|
1384
|
+
if (this.heartbeatTimer) {
|
|
1385
|
+
clearInterval(this.heartbeatTimer);
|
|
1386
|
+
this.heartbeatTimer = null;
|
|
1387
|
+
}
|
|
1388
|
+
const shutdowns = [...this.workers.entries()].map(([addonId, worker]) => this.shutdownWorker(addonId, worker));
|
|
1389
|
+
await Promise.allSettled(shutdowns);
|
|
1390
|
+
this.workers.clear();
|
|
1391
|
+
}
|
|
1392
|
+
/** Start heartbeat monitoring — workers now report heartbeat via tRPC, not IPC PING */
|
|
1393
|
+
startHeartbeatMonitoring() {
|
|
1394
|
+
this.heartbeatTimer = setInterval(() => {
|
|
1395
|
+
const now = Date.now();
|
|
1396
|
+
for (const [addonId, worker] of this.workers) {
|
|
1397
|
+
if (worker.state !== "running")
|
|
1398
|
+
continue;
|
|
1399
|
+
if (now - worker.lastHeartbeat > this.options.heartbeatTimeoutMs) {
|
|
1400
|
+
console.warn(`[WorkerHost] Worker ${addonId} heartbeat timeout \u2014 marking unresponsive`);
|
|
1401
|
+
worker.state = "crashed";
|
|
1402
|
+
worker.process.kill("SIGKILL");
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
}, this.options.heartbeatIntervalMs);
|
|
1406
|
+
}
|
|
1407
|
+
/** Update heartbeat timestamp for a worker (called when agent.heartbeat arrives) */
|
|
1408
|
+
updateWorkerHeartbeat(addonId, cpuPercent, memoryRss) {
|
|
1409
|
+
const worker = this.workers.get(addonId);
|
|
1410
|
+
if (!worker)
|
|
1411
|
+
return;
|
|
1412
|
+
worker.lastHeartbeat = Date.now();
|
|
1413
|
+
if (cpuPercent !== void 0)
|
|
1414
|
+
worker.cpuPercent = cpuPercent;
|
|
1415
|
+
if (memoryRss !== void 0)
|
|
1416
|
+
worker.memoryRss = memoryRss;
|
|
1417
|
+
}
|
|
1418
|
+
handleWorkerExit(addonId, code, addonDir, config, storagePaths, dataDir, locationPaths, workerToken) {
|
|
1419
|
+
const worker = this.workers.get(addonId);
|
|
1420
|
+
if (!worker)
|
|
1421
|
+
return;
|
|
1422
|
+
if (worker.state === "stopping") {
|
|
1423
|
+
worker.state = "stopped";
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
worker.state = "crashed";
|
|
1427
|
+
console.error(`[WorkerHost] Worker ${addonId} exited with code ${code}`);
|
|
1428
|
+
const now = Date.now();
|
|
1429
|
+
worker.crashTimestamps.push(now);
|
|
1430
|
+
const recentCrashes = worker.crashTimestamps.filter((t) => now - t < this.options.crashWindowMs);
|
|
1431
|
+
worker.crashTimestamps = recentCrashes;
|
|
1432
|
+
if (recentCrashes.length >= this.options.maxCrashesInWindow) {
|
|
1433
|
+
console.error(`[WorkerHost] Worker ${addonId} crashed ${recentCrashes.length} times in ${this.options.crashWindowMs}ms \u2014 not restarting`);
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
const backoff = Math.min(2e3 * (worker.restartCount + 1), 3e4);
|
|
1437
|
+
console.log(`[WorkerHost] Restarting worker ${addonId} in ${backoff}ms`);
|
|
1438
|
+
setTimeout(() => {
|
|
1439
|
+
worker.restartCount++;
|
|
1440
|
+
this.workers.delete(addonId);
|
|
1441
|
+
this.forkWorker(addonId, addonDir, config, storagePaths, dataDir, locationPaths, workerToken).catch((err) => {
|
|
1442
|
+
console.error(`[WorkerHost] Failed to restart worker ${addonId}:`, err);
|
|
1443
|
+
});
|
|
1444
|
+
}, backoff);
|
|
1445
|
+
}
|
|
1446
|
+
async shutdownWorker(addonId, worker) {
|
|
1447
|
+
worker.state = "stopping";
|
|
1448
|
+
worker.process.kill("SIGTERM");
|
|
1449
|
+
await new Promise((resolve) => {
|
|
1450
|
+
const timeout = setTimeout(() => {
|
|
1451
|
+
console.warn(`[WorkerHost] Worker ${addonId} did not exit within ${this.options.shutdownTimeoutMs}ms \u2014 SIGKILL`);
|
|
1452
|
+
worker.process.kill("SIGKILL");
|
|
1453
|
+
resolve();
|
|
1454
|
+
}, this.options.shutdownTimeoutMs);
|
|
1455
|
+
worker.process.on("exit", () => {
|
|
1456
|
+
clearTimeout(timeout);
|
|
1457
|
+
resolve();
|
|
1458
|
+
});
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
};
|
|
1462
|
+
exports.AddonWorkerHost = AddonWorkerHost2;
|
|
1266
1463
|
}
|
|
1267
|
-
};
|
|
1464
|
+
});
|
|
1465
|
+
|
|
1466
|
+
// src/index.ts
|
|
1467
|
+
var import_addon_loader = __toESM(require_addon_loader());
|
|
1468
|
+
var import_addon_engine_manager = __toESM(require_addon_engine_manager());
|
|
1469
|
+
var import_addon_installer = __toESM(require_addon_installer());
|
|
1470
|
+
var import_fs_utils = __toESM(require_fs_utils());
|
|
1471
|
+
var import_workspace_detect = __toESM(require_workspace_detect());
|
|
1472
|
+
var import_capability_registry = __toESM(require_capability_registry());
|
|
1473
|
+
var import_infra_capabilities = __toESM(require_infra_capabilities());
|
|
1474
|
+
var import_config_manager = __toESM(require_config_manager());
|
|
1475
|
+
var import_config_schema = __toESM(require_config_schema());
|
|
1476
|
+
var import_addon_worker_host = __toESM(require_addon_worker_host());
|
|
1477
|
+
var import_worker_process_manager = __toESM(require_worker_process_manager());
|
|
1478
|
+
var export_AddonEngineManager = import_addon_engine_manager.AddonEngineManager;
|
|
1479
|
+
var export_AddonInstaller = import_addon_installer.AddonInstaller;
|
|
1480
|
+
var export_AddonLoader = import_addon_loader.AddonLoader;
|
|
1481
|
+
var export_AddonWorkerHost = import_addon_worker_host.AddonWorkerHost;
|
|
1482
|
+
var export_CapabilityRegistry = import_capability_registry.CapabilityRegistry;
|
|
1483
|
+
var export_ConfigManager = import_config_manager.ConfigManager;
|
|
1484
|
+
var export_DEFAULT_DATA_PATH = import_config_schema.DEFAULT_DATA_PATH;
|
|
1485
|
+
var export_INFRA_CAPABILITIES = import_infra_capabilities.INFRA_CAPABILITIES;
|
|
1486
|
+
var export_RUNTIME_DEFAULTS = import_config_schema.RUNTIME_DEFAULTS;
|
|
1487
|
+
var export_WorkerProcessManager = import_worker_process_manager.WorkerProcessManager;
|
|
1488
|
+
var export_bootstrapSchema = import_config_schema.bootstrapSchema;
|
|
1489
|
+
var export_copyDirRecursive = import_fs_utils.copyDirRecursive;
|
|
1490
|
+
var export_copyExtraFileDirs = import_fs_utils.copyExtraFileDirs;
|
|
1491
|
+
var export_detectWorkspacePackagesDir = import_workspace_detect.detectWorkspacePackagesDir;
|
|
1492
|
+
var export_ensureDir = import_fs_utils.ensureDir;
|
|
1493
|
+
var export_ensureLibraryBuilt = import_fs_utils.ensureLibraryBuilt;
|
|
1494
|
+
var export_installPackageFromNpmSync = import_fs_utils.installPackageFromNpmSync;
|
|
1495
|
+
var export_isInfraCapability = import_infra_capabilities.isInfraCapability;
|
|
1496
|
+
var export_isSourceNewer = import_fs_utils.isSourceNewer;
|
|
1497
|
+
var export_stripCamstackDeps = import_fs_utils.stripCamstackDeps;
|
|
1498
|
+
var export_symlinkAddonsToNodeModules = import_fs_utils.symlinkAddonsToNodeModules;
|
|
1268
1499
|
export {
|
|
1269
|
-
AddonEngineManager,
|
|
1270
|
-
AddonInstaller,
|
|
1271
|
-
AddonLoader,
|
|
1272
|
-
AddonWorkerHost,
|
|
1273
|
-
CapabilityRegistry,
|
|
1274
|
-
ConfigManager,
|
|
1275
|
-
DEFAULT_DATA_PATH,
|
|
1276
|
-
INFRA_CAPABILITIES,
|
|
1277
|
-
RUNTIME_DEFAULTS,
|
|
1278
|
-
WorkerProcessManager,
|
|
1279
|
-
bootstrapSchema,
|
|
1280
|
-
copyDirRecursive,
|
|
1281
|
-
copyExtraFileDirs,
|
|
1282
|
-
detectWorkspacePackagesDir,
|
|
1283
|
-
ensureDir,
|
|
1284
|
-
ensureLibraryBuilt,
|
|
1285
|
-
installPackageFromNpmSync,
|
|
1286
|
-
isInfraCapability,
|
|
1287
|
-
isSourceNewer,
|
|
1288
|
-
stripCamstackDeps,
|
|
1289
|
-
symlinkAddonsToNodeModules
|
|
1500
|
+
export_AddonEngineManager as AddonEngineManager,
|
|
1501
|
+
export_AddonInstaller as AddonInstaller,
|
|
1502
|
+
export_AddonLoader as AddonLoader,
|
|
1503
|
+
export_AddonWorkerHost as AddonWorkerHost,
|
|
1504
|
+
export_CapabilityRegistry as CapabilityRegistry,
|
|
1505
|
+
export_ConfigManager as ConfigManager,
|
|
1506
|
+
export_DEFAULT_DATA_PATH as DEFAULT_DATA_PATH,
|
|
1507
|
+
export_INFRA_CAPABILITIES as INFRA_CAPABILITIES,
|
|
1508
|
+
export_RUNTIME_DEFAULTS as RUNTIME_DEFAULTS,
|
|
1509
|
+
export_WorkerProcessManager as WorkerProcessManager,
|
|
1510
|
+
export_bootstrapSchema as bootstrapSchema,
|
|
1511
|
+
export_copyDirRecursive as copyDirRecursive,
|
|
1512
|
+
export_copyExtraFileDirs as copyExtraFileDirs,
|
|
1513
|
+
export_detectWorkspacePackagesDir as detectWorkspacePackagesDir,
|
|
1514
|
+
export_ensureDir as ensureDir,
|
|
1515
|
+
export_ensureLibraryBuilt as ensureLibraryBuilt,
|
|
1516
|
+
export_installPackageFromNpmSync as installPackageFromNpmSync,
|
|
1517
|
+
export_isInfraCapability as isInfraCapability,
|
|
1518
|
+
export_isSourceNewer as isSourceNewer,
|
|
1519
|
+
export_stripCamstackDeps as stripCamstackDeps,
|
|
1520
|
+
export_symlinkAddonsToNodeModules as symlinkAddonsToNodeModules
|
|
1290
1521
|
};
|
|
1291
1522
|
//# sourceMappingURL=index.mjs.map
|