@camstack/server 1.2.820 → 1.2.822

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/api/trpc/generated-cap-mounts.js +3 -1
  3. package/dist/api/trpc/generated-cap-routers.js +1863 -1697
  4. package/package.json +10 -24
  5. package/system/dist/{agent-https-XHjvcSEq.mjs → agent-https-C4yxMErF.mjs} +1 -1
  6. package/system/dist/{agent-https-CbysxRlV.js → agent-https-SGBI0xP8.js} +1 -1
  7. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  8. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  9. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  10. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  11. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  12. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  13. package/system/dist/builtins/autotrack/index.js +1 -1
  14. package/system/dist/builtins/autotrack/index.mjs +1 -1
  15. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  16. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  17. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  18. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  19. package/system/dist/builtins/camera-grid/index.js +1 -1
  20. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  21. package/system/dist/builtins/composer/composer.addon.js +3 -3
  22. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  23. package/system/dist/builtins/console-logging/index.js +1 -1
  24. package/system/dist/builtins/console-logging/index.mjs +1 -1
  25. package/system/dist/builtins/core-blocks/actions-service.d.ts +16 -0
  26. package/system/dist/builtins/core-blocks/core-blocks.addon.js +158 -9
  27. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +158 -9
  28. package/system/dist/builtins/core-blocks/device-template-door.d.ts +25 -0
  29. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +5 -0
  30. package/system/dist/builtins/core-blocks/hero-layout-service.d.ts +2 -0
  31. package/system/dist/builtins/core-blocks/scheduler/scheduler-engine.d.ts +5 -0
  32. package/system/dist/builtins/core-blocks/step-condition-door.d.ts +19 -0
  33. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  34. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  35. package/system/dist/builtins/device-manager/device-manager.addon.d.ts +7 -0
  36. package/system/dist/builtins/device-manager/device-manager.addon.js +655 -2
  37. package/system/dist/builtins/device-manager/device-manager.addon.mjs +653 -1
  38. package/system/dist/builtins/device-manager/device-template/template-host.d.ts +60 -0
  39. package/system/dist/builtins/device-manager/device-template-actions.d.ts +33 -0
  40. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  41. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  42. package/system/dist/builtins/keychain/index.js +4 -4
  43. package/system/dist/builtins/keychain/index.mjs +4 -4
  44. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  46. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  47. package/system/dist/builtins/local-auth/local-auth.addon.mjs +2 -2
  48. package/system/dist/builtins/local-network/local-network.addon.js +2 -2
  49. package/system/dist/builtins/local-network/local-network.addon.mjs +2 -2
  50. package/system/dist/builtins/loki-logging/index.js +1 -1
  51. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  52. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  54. package/system/dist/builtins/platform-probe/index.js +1 -1
  55. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  56. package/system/dist/builtins/record-entries/index.js +1 -1
  57. package/system/dist/builtins/record-entries/index.mjs +1 -1
  58. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  60. package/system/dist/builtins/snapshot/index.js +1 -1
  61. package/system/dist/builtins/snapshot/index.mjs +1 -1
  62. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  64. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  65. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  66. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  68. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  70. package/system/dist/builtins/system-config/system-config.addon.js +9 -9
  71. package/system/dist/builtins/system-config/system-config.addon.mjs +6 -6
  72. package/system/dist/builtins/winston-logging/index.js +1 -1
  73. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  74. package/system/dist/{capture-engine-CKtkENOg.js → capture-engine-6MVUyUry.js} +1 -1
  75. package/system/dist/{capture-engine-WSpdP-gE.mjs → capture-engine-BSjE-CQA.mjs} +1 -1
  76. package/system/dist/{composition-sources-6Qx72gmK.js → composition-sources-BBAOXZdC.js} +1 -1
  77. package/system/dist/{composition-sources-Dr6uwBGw.mjs → composition-sources-C8T9DRbZ.mjs} +1 -1
  78. package/system/dist/{constants-URzk8siY.mjs → constants-CReG6K4k.mjs} +1 -1
  79. package/system/dist/{constants-BchSDmTD.js → constants-v0g9--wN.js} +1 -1
  80. package/system/dist/{device-ca-kANxsBE5.js → device-ca-BFcBTfff.js} +1 -1
  81. package/system/dist/{device-ca-Bu1E5Vgr.mjs → device-ca-cX8qUs2s.mjs} +1 -1
  82. package/system/dist/device-template-worker.js +5 -7032
  83. package/system/dist/device-template-worker.mjs +1 -7026
  84. package/system/dist/{dist-R_mOSFtH.js → dist-C2czR9xK.js} +2077 -167
  85. package/system/dist/{dist-C0Df8iJl.mjs → dist-DjBZ1HhF.mjs} +2036 -168
  86. package/system/dist/file-host-worker.js +1 -1
  87. package/system/dist/file-host-worker.mjs +1 -1
  88. package/system/dist/{hub-mdns-ciao-pxgLcmqO.mjs → hub-mdns-ciao-Cnr8xiSd.mjs} +2 -2
  89. package/system/dist/{hub-mdns-ciao-2AZ3ucDO.js → hub-mdns-ciao-CpCleue0.js} +2 -2
  90. package/system/dist/index.js +8 -8
  91. package/system/dist/index.mjs +8 -8
  92. package/system/dist/{legacy-integration-rows-door-Cj58BS60.mjs → legacy-integration-rows-door-CGajkVPh.mjs} +1 -1
  93. package/system/dist/{legacy-integration-rows-door-g4CeLJ9g.js → legacy-integration-rows-door-DhW6mPZj.js} +1 -1
  94. package/system/dist/{restore-archive-CAh7u-rY.js → restore-archive-BLab80kx.js} +7 -7
  95. package/system/dist/{restore-archive-Bd7fgVo8.mjs → restore-archive-eA7L58KT.mjs} +8 -8
  96. package/system/dist/template-protocol-BmMM5VBf.mjs +7033 -0
  97. package/system/dist/template-protocol-CTP4eAo_.js +7059 -0
  98. package/system/dist/{wal-maintenance-DMf2oEQ-.mjs → wal-maintenance-DeBxoOFh.mjs} +0 -0
  99. package/system/dist/{wal-maintenance--0liHBxL.js → wal-maintenance-DhnSF7K-.js} +0 -0
  100. package/system/package.json +1 -1
@@ -2,18 +2,23 @@ Object.defineProperties(exports, {
2
2
  __esModule: { value: true },
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
- require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-R_mOSFtH.js");
5
+ const require_chunk = require("../../chunk-Cek0wNdY.js");
6
+ const require_dist = require("../../dist-C2czR9xK.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
9
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
10
10
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
11
11
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
12
+ const require_template_protocol = require("../../template-protocol-CTP4eAo_.js");
12
13
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
13
14
  let zod = require("zod");
14
15
  let node_crypto = require("node:crypto");
15
16
  let _camstack_types_node = require("@camstack/types/node");
17
+ let node_path = require("node:path");
18
+ node_path = require_chunk.__toESM(node_path);
16
19
  let _camstack_types_addon = require("@camstack/types/addon");
20
+ let node_module = require("node:module");
21
+ let node_worker_threads = require("node:worker_threads");
17
22
  //#region src/builtins/device-manager/adoption-job-engine.ts
18
23
  /** How many finished jobs are kept per (addonId, integrationId). */
19
24
  var JOB_HISTORY = 20;
@@ -8010,6 +8015,617 @@ async function runLinkedDevicesManualBackfillAtBoot(pctx) {
8010
8015
  } });
8011
8016
  }
8012
8017
  //#endregion
8018
+ //#region src/builtins/device-manager/device-template/mirror-resolver.ts
8019
+ /** The slices the mirror must hold so these devices' templates can render. */
8020
+ function templateMirrorSources(devices) {
8021
+ return devices.flatMap((device) => device.caps.map((cap) => ({
8022
+ kind: "device",
8023
+ deviceId: device.deviceId,
8024
+ cap
8025
+ })));
8026
+ }
8027
+ function mirrorTemplateResolver(mirror, devices, unitOf) {
8028
+ const byAlias = /* @__PURE__ */ new Map();
8029
+ for (const device of devices) if (!byAlias.has(device.alias)) byAlias.set(device.alias, device);
8030
+ return { viewOf(alias) {
8031
+ const device = byAlias.get(alias);
8032
+ if (device === void 0) return void 0;
8033
+ const slices = {};
8034
+ for (const cap of device.caps) {
8035
+ const slice = mirror.sliceOf(device.deviceId, cap);
8036
+ if (slice !== void 0) slices[cap] = slice;
8037
+ }
8038
+ return {
8039
+ deviceId: device.deviceId,
8040
+ addonId: device.addonId,
8041
+ stableId: device.stableId,
8042
+ slices,
8043
+ ...unitOf !== void 0 ? { unitOf } : {}
8044
+ };
8045
+ } };
8046
+ }
8047
+ //#endregion
8048
+ //#region src/builtins/device-manager/device-template/template-host.ts
8049
+ /**
8050
+ * The hub side of device value templates (D1021 run-time contract): the one
8051
+ * place a consumer's template becomes text. It names the devices a template
8052
+ * refers to (aliases), refuses the ones the caller was not proven to see,
8053
+ * fills a `ConditionMirror` with the slices those devices hold NOW, and hands
8054
+ * the renderer a resolver over that mirror. A consumer (an action step, a
8055
+ * scheduler point, a notification rule, a generated automation block) reaches
8056
+ * it only through `device-manager.renderDeviceTemplates`; there is no second
8057
+ * renderer and no second copy of the state.
8058
+ */
8059
+ var DeviceTemplateHost = class {
8060
+ deps;
8061
+ constructor(deps) {
8062
+ this.deps = deps;
8063
+ }
8064
+ /**
8065
+ * Which devices a template names, without rendering it. `allowed` is the set
8066
+ * of device ids the caller was proven to see; `undefined` means no
8067
+ * restriction (an admin, a system run). A restricted caller gets the same
8068
+ * answer for an alias that does not exist and one it may not see.
8069
+ */
8070
+ async check(source, allowed) {
8071
+ const analysis = this.deps.renderer.validate(source);
8072
+ if (!analysis.ok) return {
8073
+ ok: false,
8074
+ reason: analysis.refusal.reason,
8075
+ message: analysis.refusal.message
8076
+ };
8077
+ const aliases = [];
8078
+ for (const alias of new Set(analysis.refs.map((ref) => ref.alias))) {
8079
+ const row = await this.deps.findByAlias(alias);
8080
+ aliases.push({
8081
+ alias,
8082
+ deviceId: row === null ? null : row.deviceId,
8083
+ allowed: allowed === void 0 || row !== null && allowed.has(row.deviceId),
8084
+ row
8085
+ });
8086
+ }
8087
+ return {
8088
+ ok: true,
8089
+ aliases
8090
+ };
8091
+ }
8092
+ /** Render every template; answers are index-aligned with the questions. */
8093
+ async render(sources, allowed) {
8094
+ const checks = await Promise.all(sources.map((source) => this.check(source, allowed)));
8095
+ const rows = /* @__PURE__ */ new Map();
8096
+ for (const check of checks) {
8097
+ if (!check.ok) continue;
8098
+ for (const use of check.aliases) {
8099
+ if (!use.allowed || use.row === null || rows.has(use.alias)) continue;
8100
+ rows.set(use.alias, {
8101
+ ...use.row,
8102
+ caps: await this.deps.capsOf(use.row.deviceId)
8103
+ });
8104
+ }
8105
+ }
8106
+ const entries = [...rows.values()];
8107
+ const mirror = new require_dist.ConditionMirror(templateMirrorSources(entries));
8108
+ const report = await mirror.refresh({
8109
+ fetchSlice: (deviceId, cap) => this.deps.fetchSlice(deviceId, cap),
8110
+ fetchStableIds: async () => /* @__PURE__ */ new Map()
8111
+ });
8112
+ if (report.kept > 0) this.deps.logger.debug("template mirror kept no value for some slices", { meta: { ...report } });
8113
+ const resolver = mirrorTemplateResolver(mirror, entries, this.deps.unitOf);
8114
+ const out = [];
8115
+ let warned = false;
8116
+ for (const [index, source] of sources.entries()) {
8117
+ const check = checks[index];
8118
+ if (check === void 0 || !check.ok) {
8119
+ out.push({
8120
+ ok: false,
8121
+ refusal: {
8122
+ reason: check === void 0 ? "render-failed" : check.reason,
8123
+ message: check === void 0 ? "no check" : check.message
8124
+ },
8125
+ trace: []
8126
+ });
8127
+ continue;
8128
+ }
8129
+ const refused = check.aliases.find((use) => !use.allowed);
8130
+ if (refused !== void 0) {
8131
+ if (!warned) {
8132
+ warned = true;
8133
+ this.deps.logger.warn("device template refused — it names a device the caller was not proven to see", {
8134
+ ...refused.deviceId === null ? {} : { tags: { deviceId: refused.deviceId } },
8135
+ meta: { alias: refused.alias }
8136
+ });
8137
+ }
8138
+ out.push({
8139
+ ok: false,
8140
+ refusal: {
8141
+ reason: "out-of-scope",
8142
+ message: `the template names "${refused.alias}", a device this caller cannot see`
8143
+ },
8144
+ trace: []
8145
+ });
8146
+ continue;
8147
+ }
8148
+ const rendered = await this.deps.renderer.render(source, resolver);
8149
+ out.push(rendered.ok ? {
8150
+ ok: true,
8151
+ text: rendered.text,
8152
+ trace: [...rendered.trace]
8153
+ } : {
8154
+ ok: false,
8155
+ refusal: rendered.refusal,
8156
+ trace: [...rendered.trace]
8157
+ });
8158
+ }
8159
+ return out;
8160
+ }
8161
+ };
8162
+ //#endregion
8163
+ //#region src/builtins/device-manager/device-template/template-renderer.ts
8164
+ /**
8165
+ * The hub's device value-template renderer (D1021).
8166
+ *
8167
+ * Owner: device-manager. It owns the device rows and the aliases a template
8168
+ * names, and this directory is the only one allowed to import nunjucks
8169
+ * (guard `check-device-template-grammar`).
8170
+ *
8171
+ * A render is: vet the template (`analyzeTemplate`), resolve every reference
8172
+ * against the devices' current slices, build a context of only the values the
8173
+ * template names, and hand it to a worker thread under a wall-time budget. A
8174
+ * worker that overruns is terminated and respawned on the next render. What a
8175
+ * reference cannot resolve renders `—` and goes into the trace; an ambiguous
8176
+ * `alias.field` refuses the whole render, naming the capabilities.
8177
+ */
8178
+ /** `dist/device-template-worker.js` at the package root, found through its own `package.json`. */
8179
+ function defaultTemplateWorkerPath() {
8180
+ const require_ = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
8181
+ const packageRoot = node_path.dirname(require_.resolve("@camstack/server/system/package.json"));
8182
+ return node_path.join(packageRoot, "dist", "device-template-worker.js");
8183
+ }
8184
+ /** Room for the hidden source-unit arguments the renderer adds to `unit()` calls. */
8185
+ var REWRITE_ALLOWANCE = 2048;
8186
+ /**
8187
+ * The cold start of the worker thread (loading nunjucks) is NOT part of a
8188
+ * render's budget: the budget timer starts only once the worker has announced
8189
+ * `ready`. A thread that never does is killed after this long, and the next
8190
+ * render respawns it.
8191
+ */
8192
+ var SPAWN_TIMEOUT_MS = 1e4;
8193
+ var DEFAULT_MAX_QUEUE = 16;
8194
+ var DEFAULT_BREAKER_THRESHOLD = 3;
8195
+ var DEFAULT_BREAKER_WINDOW_MS = 6e4;
8196
+ var BREAKER_MAX_TEMPLATES = 256;
8197
+ function isReadyMessage(value) {
8198
+ return typeof value === "object" && value !== null && Reflect.get(value, "ready") === true;
8199
+ }
8200
+ /** Copy a value as plain data only: primitives, arrays and plain objects. Anything else (functions, class instances) is dropped. */
8201
+ function plainCopy(value, depth = 0) {
8202
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
8203
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
8204
+ if (depth > 8) return void 0;
8205
+ if (Array.isArray(value)) return value.map((item) => plainCopy(item, depth + 1));
8206
+ if (typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
8207
+ const out = Object.create(null);
8208
+ for (const key of Object.keys(value)) out[key] = plainCopy(Reflect.get(value, key), depth + 1);
8209
+ return out;
8210
+ }
8211
+ }
8212
+ /** The context under construction: containers this builder made, so a longer path never writes into a caller's value. */
8213
+ var ContextTree = class {
8214
+ root = Object.create(null);
8215
+ ours = /* @__PURE__ */ new WeakSet();
8216
+ constructor() {
8217
+ this.ours.add(this.root);
8218
+ }
8219
+ isOurs(value) {
8220
+ return typeof value === "object" && value !== null && this.ours.has(value);
8221
+ }
8222
+ place(alias, keys, value) {
8223
+ let cursor = this.root;
8224
+ let key = alias;
8225
+ for (const next of keys) {
8226
+ const existing = cursor[key];
8227
+ if (existing !== void 0 && !this.isOurs(existing)) return;
8228
+ let child;
8229
+ if (this.isOurs(existing)) child = existing;
8230
+ else {
8231
+ child = Object.create(null);
8232
+ this.ours.add(child);
8233
+ cursor[key] = child;
8234
+ }
8235
+ cursor = child;
8236
+ key = String(next);
8237
+ }
8238
+ cursor[key] = value;
8239
+ }
8240
+ };
8241
+ function offsetOf(source, lineno, colno) {
8242
+ const lines = source.split("\n");
8243
+ if (lineno < 0 || lineno >= lines.length) return void 0;
8244
+ let offset = 0;
8245
+ for (let i = 0; i < lineno; i += 1) offset += (lines[i]?.length ?? 0) + 1;
8246
+ return offset + colno;
8247
+ }
8248
+ /** Insert `"<source unit>", ` as the first argument of each `unit(` call so the worker converts from the field's base unit. */
8249
+ function withUnitHints(source, hints) {
8250
+ const located = hints.map((entry) => ({
8251
+ entry,
8252
+ offset: offsetOf(source, entry.site.lineno, entry.site.colno)
8253
+ })).filter((item) => item.offset !== void 0).toSorted((a, b) => b.offset - a.offset);
8254
+ let out = source;
8255
+ for (const { entry, offset } of located) {
8256
+ if (!out.startsWith("unit", offset)) continue;
8257
+ const open = out.indexOf("(", offset + 4);
8258
+ if (open < 0) continue;
8259
+ out = `${out.slice(0, open + 1)}${JSON.stringify(entry.hint)}, ${out.slice(open + 1)}`;
8260
+ }
8261
+ return out;
8262
+ }
8263
+ function refText(ref) {
8264
+ return [ref.alias, ...ref.path.map(String)].join(".");
8265
+ }
8266
+ var DeviceTemplateRenderer = class {
8267
+ workerPath;
8268
+ execArgv;
8269
+ budgetMs;
8270
+ now;
8271
+ worker = null;
8272
+ ready = null;
8273
+ nextId = 1;
8274
+ pending = /* @__PURE__ */ new Map();
8275
+ queue = Promise.resolve();
8276
+ waiting = 0;
8277
+ spawnTimeoutMs;
8278
+ maxQueue;
8279
+ breakerThreshold;
8280
+ breakerWindowMs;
8281
+ breakers = /* @__PURE__ */ new Map();
8282
+ constructor(options = {}) {
8283
+ this.workerPath = options.workerPath ?? defaultTemplateWorkerPath();
8284
+ this.execArgv = options.workerExecArgv;
8285
+ this.budgetMs = options.budgetMs ?? 50;
8286
+ this.now = options.now ?? Date.now;
8287
+ this.spawnTimeoutMs = options.spawnTimeoutMs ?? SPAWN_TIMEOUT_MS;
8288
+ this.maxQueue = options.maxQueue ?? DEFAULT_MAX_QUEUE;
8289
+ this.breakerThreshold = options.breakerThreshold ?? DEFAULT_BREAKER_THRESHOLD;
8290
+ this.breakerWindowMs = options.breakerWindowMs ?? DEFAULT_BREAKER_WINDOW_MS;
8291
+ }
8292
+ /** Vet a template without rendering it: its references, or the refusal. */
8293
+ validate(source) {
8294
+ return require_template_protocol.analyzeTemplate(source, require_dist.DEVICE_TEMPLATE_FILTERS, require_dist.DEVICE_TEMPLATE_MAX_LENGTH);
8295
+ }
8296
+ async render(source, resolver) {
8297
+ const analysis = this.validate(source);
8298
+ if (!analysis.ok) return {
8299
+ ok: false,
8300
+ refusal: analysis.refusal,
8301
+ trace: []
8302
+ };
8303
+ const prepared = this.prepare(source, analysis, resolver);
8304
+ if ("refusal" in prepared) return {
8305
+ ok: false,
8306
+ refusal: prepared.refusal,
8307
+ trace: [...prepared.trace]
8308
+ };
8309
+ const open = this.breakers.get(source);
8310
+ if (open !== void 0 && open.openUntil > Date.now()) return {
8311
+ ok: false,
8312
+ refusal: {
8313
+ reason: "budget-exceeded",
8314
+ message: `this template overran its ${this.budgetMs} ms budget ${open.timeouts} times in a row; it is not run again for ${Math.ceil((open.openUntil - Date.now()) / 1e3)} s`
8315
+ },
8316
+ trace: [...prepared.trace]
8317
+ };
8318
+ if (this.waiting >= this.maxQueue) return {
8319
+ ok: false,
8320
+ refusal: {
8321
+ reason: "busy",
8322
+ message: `${this.maxQueue} renders are already waiting`
8323
+ },
8324
+ trace: [...prepared.trace]
8325
+ };
8326
+ this.waiting += 1;
8327
+ let response;
8328
+ try {
8329
+ response = await this.enqueue(prepared);
8330
+ } finally {
8331
+ this.waiting -= 1;
8332
+ }
8333
+ this.noteOutcome(source, response);
8334
+ if (response.ok) {
8335
+ const poisoned = Array.from({ length: response.poisoned }, () => ({
8336
+ ref: "<expression>",
8337
+ reason: "unavailable"
8338
+ }));
8339
+ return {
8340
+ ok: true,
8341
+ text: response.text,
8342
+ trace: [...prepared.trace, ...poisoned]
8343
+ };
8344
+ }
8345
+ return {
8346
+ ok: false,
8347
+ refusal: {
8348
+ reason: response.reason,
8349
+ message: response.message
8350
+ },
8351
+ trace: [...prepared.trace]
8352
+ };
8353
+ }
8354
+ noteOutcome(source, response) {
8355
+ if (response.ok || response.reason !== "timeout") {
8356
+ this.breakers.delete(source);
8357
+ return;
8358
+ }
8359
+ const state = this.breakers.get(source) ?? {
8360
+ timeouts: 0,
8361
+ openUntil: 0
8362
+ };
8363
+ state.timeouts += 1;
8364
+ if (state.timeouts >= this.breakerThreshold) state.openUntil = Date.now() + this.breakerWindowMs;
8365
+ this.breakers.delete(source);
8366
+ this.breakers.set(source, state);
8367
+ for (const key of this.breakers.keys()) {
8368
+ if (this.breakers.size <= BREAKER_MAX_TEMPLATES) break;
8369
+ this.breakers.delete(key);
8370
+ }
8371
+ }
8372
+ dispose() {
8373
+ this.killWorker("disposed");
8374
+ }
8375
+ prepare(source, analysis, resolver) {
8376
+ const trace = [];
8377
+ const tree = new ContextTree();
8378
+ const resolvedFor = /* @__PURE__ */ new Map();
8379
+ for (const ref of analysis.refs) {
8380
+ const view = resolver.viewOf(ref.alias);
8381
+ if (view === void 0) {
8382
+ trace.push({
8383
+ ref: refText(ref),
8384
+ reason: "unknown-alias"
8385
+ });
8386
+ continue;
8387
+ }
8388
+ const resolved = require_dist.resolveTemplateRef(view, ref.path);
8389
+ if (resolved.kind === "ambiguous") return {
8390
+ refusal: {
8391
+ reason: "ambiguous-field",
8392
+ message: `"${ref.alias}.${resolved.field}" is ambiguous: capabilities ${resolved.caps.join(", ")} all carry "${resolved.field}"; write ${ref.alias}.<capability>.${resolved.field}`
8393
+ },
8394
+ trace
8395
+ };
8396
+ if (resolved.kind === "missing") {
8397
+ trace.push({
8398
+ ref: refText(ref),
8399
+ reason: resolved.reason
8400
+ });
8401
+ continue;
8402
+ }
8403
+ resolvedFor.set(JSON.stringify([ref.alias, ref.path]), {
8404
+ view,
8405
+ cap: resolved.cap,
8406
+ fieldPath: resolved.fieldPath
8407
+ });
8408
+ if (resolved.value === null) trace.push({
8409
+ ref: refText(ref),
8410
+ reason: "unavailable"
8411
+ });
8412
+ tree.place(ref.alias, ref.path, plainCopy(resolved.value));
8413
+ }
8414
+ return {
8415
+ source: withUnitHints(source, analysis.unitSites.map((site) => {
8416
+ const hit = site.ref === void 0 ? void 0 : resolvedFor.get(JSON.stringify([site.ref.alias, site.ref.path]));
8417
+ return {
8418
+ site,
8419
+ hint: hit?.view.unitOf?.(hit.cap, hit.fieldPath) ?? ""
8420
+ };
8421
+ })),
8422
+ context: tree.root,
8423
+ trace
8424
+ };
8425
+ }
8426
+ enqueue(prepared) {
8427
+ const run = async () => this.renderOne(prepared);
8428
+ const result = this.queue.then(run, run);
8429
+ this.queue = result.catch(() => void 0);
8430
+ return result;
8431
+ }
8432
+ async renderOne(prepared) {
8433
+ const id = this.nextId;
8434
+ this.nextId += 1;
8435
+ let worker;
8436
+ try {
8437
+ worker = await this.ensureWorker();
8438
+ } catch (err) {
8439
+ return {
8440
+ id,
8441
+ ok: false,
8442
+ reason: "render-failed",
8443
+ message: err instanceof Error ? err.message : String(err)
8444
+ };
8445
+ }
8446
+ const response = new Promise((resolve) => {
8447
+ this.pending.set(id, {
8448
+ worker,
8449
+ resolve
8450
+ });
8451
+ });
8452
+ const request = {
8453
+ id,
8454
+ source: prepared.source,
8455
+ context: prepared.context,
8456
+ nowMs: this.now()
8457
+ };
8458
+ try {
8459
+ worker.postMessage(request);
8460
+ } catch (err) {
8461
+ this.pending.delete(id);
8462
+ return {
8463
+ id,
8464
+ ok: false,
8465
+ reason: "render-failed",
8466
+ message: err instanceof Error ? err.message : String(err)
8467
+ };
8468
+ }
8469
+ let timer;
8470
+ const timeout = new Promise((resolve) => {
8471
+ timer = setTimeout(() => {
8472
+ resolve({
8473
+ id,
8474
+ ok: false,
8475
+ reason: "timeout",
8476
+ message: `render took longer than ${this.budgetMs} ms`
8477
+ });
8478
+ }, this.budgetMs);
8479
+ });
8480
+ const outcome = await Promise.race([response, timeout]);
8481
+ if (timer !== void 0) clearTimeout(timer);
8482
+ this.pending.delete(id);
8483
+ if (!outcome.ok && outcome.reason === "timeout") this.killWorker("budget overrun");
8484
+ return outcome;
8485
+ }
8486
+ ensureWorker() {
8487
+ const existing = this.worker;
8488
+ if (existing !== null && this.ready !== null) return this.ready.then(() => existing);
8489
+ const limits = {
8490
+ allowedFilters: require_dist.DEVICE_TEMPLATE_FILTERS,
8491
+ maxSourceLength: require_dist.DEVICE_TEMPLATE_MAX_LENGTH + REWRITE_ALLOWANCE,
8492
+ maxOutput: require_dist.DEVICE_TEMPLATE_MAX_OUTPUT,
8493
+ unavailable: "—"
8494
+ };
8495
+ const worker = new node_worker_threads.Worker(this.workerPath, {
8496
+ workerData: limits,
8497
+ ...this.execArgv !== void 0 ? { execArgv: [...this.execArgv] } : {},
8498
+ resourceLimits: {
8499
+ maxOldGenerationSizeMb: 64,
8500
+ maxYoungGenerationSizeMb: 16,
8501
+ stackSizeMb: 4
8502
+ }
8503
+ });
8504
+ this.worker = worker;
8505
+ this.ready = new Promise((resolve, reject) => {
8506
+ const timer = setTimeout(() => {
8507
+ reject(/* @__PURE__ */ new Error("template worker did not start"));
8508
+ if (this.worker === worker) this.dropWorker();
8509
+ worker.terminate();
8510
+ }, this.spawnTimeoutMs);
8511
+ worker.on("message", (message) => {
8512
+ if (isReadyMessage(message)) {
8513
+ clearTimeout(timer);
8514
+ resolve();
8515
+ return;
8516
+ }
8517
+ if (require_template_protocol.isRenderResponse(message)) this.pending.get(message.id)?.resolve(message);
8518
+ });
8519
+ worker.on("error", (err) => {
8520
+ clearTimeout(timer);
8521
+ reject(err instanceof Error ? err : new Error(String(err)));
8522
+ this.failPending(worker, err instanceof Error ? err.message : String(err));
8523
+ if (this.worker === worker) this.dropWorker();
8524
+ });
8525
+ worker.on("exit", () => {
8526
+ clearTimeout(timer);
8527
+ this.failPending(worker, "template worker exited");
8528
+ if (this.worker === worker) this.dropWorker();
8529
+ });
8530
+ });
8531
+ worker.unref();
8532
+ return this.ready.then(() => worker);
8533
+ }
8534
+ /** Fail only the renders that were running on THIS worker: a killed worker's late `exit` must not fail the next one. */
8535
+ failPending(worker, message) {
8536
+ for (const [id, entry] of this.pending) {
8537
+ if (entry.worker !== worker) continue;
8538
+ entry.resolve({
8539
+ id,
8540
+ ok: false,
8541
+ reason: "render-failed",
8542
+ message
8543
+ });
8544
+ this.pending.delete(id);
8545
+ }
8546
+ }
8547
+ dropWorker() {
8548
+ this.worker = null;
8549
+ this.ready = null;
8550
+ }
8551
+ killWorker(_why) {
8552
+ const worker = this.worker;
8553
+ this.dropWorker();
8554
+ if (worker !== null) worker.terminate();
8555
+ }
8556
+ };
8557
+ //#endregion
8558
+ //#region src/builtins/device-manager/device-template-actions.ts
8559
+ /**
8560
+ * `device-manager.renderDeviceTemplates` / `checkDeviceTemplates` (D1021): the
8561
+ * provider side of the ONE door to the template renderer. The renderer is built
8562
+ * on first use (a worker is spawned lazily by it) and disposed at shutdown.
8563
+ */
8564
+ /** The D944 base unit of a numeric runtime field, from the cap's own schema. */
8565
+ var baseUnitOfRuntimeField = (cap, path) => {
8566
+ const field = path[0];
8567
+ if (typeof field !== "string") return void 0;
8568
+ return require_dist.runtimeFieldUnit(cap, field);
8569
+ };
8570
+ var DeviceTemplateActions = class {
8571
+ logger;
8572
+ deps;
8573
+ makeRenderer;
8574
+ renderer = null;
8575
+ host = null;
8576
+ constructor(logger, deps, makeRenderer = () => new DeviceTemplateRenderer()) {
8577
+ this.logger = logger;
8578
+ this.deps = deps;
8579
+ this.makeRenderer = makeRenderer;
8580
+ }
8581
+ hostOf() {
8582
+ if (this.host === null) {
8583
+ this.renderer = this.makeRenderer();
8584
+ this.host = new DeviceTemplateHost({
8585
+ renderer: this.renderer,
8586
+ findByAlias: this.deps.findByAlias,
8587
+ capsOf: this.deps.capsOf,
8588
+ fetchSlice: this.deps.fetchSlice,
8589
+ unitOf: baseUnitOfRuntimeField,
8590
+ logger: this.logger.child("templates")
8591
+ });
8592
+ }
8593
+ return this.host;
8594
+ }
8595
+ async render(input) {
8596
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8597
+ return { results: await this.hostOf().render(input.templates, allowed) };
8598
+ }
8599
+ async check(input) {
8600
+ const allowed = input.allowedDeviceIds === void 0 ? void 0 : new Set(input.allowedDeviceIds);
8601
+ const host = this.hostOf();
8602
+ const results = [];
8603
+ for (const source of input.templates) {
8604
+ const check = await host.check(source, allowed);
8605
+ results.push(check.ok ? {
8606
+ ok: true,
8607
+ aliases: check.aliases.map((use) => ({
8608
+ alias: use.alias,
8609
+ deviceId: use.deviceId,
8610
+ allowed: use.allowed
8611
+ }))
8612
+ } : {
8613
+ ok: false,
8614
+ refusal: {
8615
+ reason: check.reason,
8616
+ message: check.message
8617
+ }
8618
+ });
8619
+ }
8620
+ return { results };
8621
+ }
8622
+ dispose() {
8623
+ this.renderer?.dispose();
8624
+ this.renderer = null;
8625
+ this.host = null;
8626
+ }
8627
+ };
8628
+ //#endregion
8013
8629
  //#region src/builtins/device-manager/device-meta-types.ts
8014
8630
  /**
8015
8631
  * Decode the raw `ctx.settings.readAddonStore()` record into {@link AddonStore}.
@@ -11958,6 +12574,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
11958
12574
  removalFence = createRemovalFence();
11959
12575
  /** Store-by-store clean-up of a removed device, with a bounded retry (D864). */
11960
12576
  removalCleanupImpl = null;
12577
+ templateActions = null;
11961
12578
  removalHooksCleanupImpl = null;
11962
12579
  /** Declared secret config paths per device, as last registered (D783). */
11963
12580
  secretConfigPaths = createSecretConfigPathRegistry();
@@ -12247,6 +12864,7 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12247
12864
  const bootRows = await deviceRows.listAll();
12248
12865
  for (const row of bootRows) idToAddonId.set(row.meta.id, row.meta.addonId);
12249
12866
  const stampIntegrationId$1 = (deviceId, integrationId) => stampIntegrationId(metaStore, this.ctx, deviceId, integrationId);
12867
+ const templates = this.makeTemplateActions();
12250
12868
  const pctx = {
12251
12869
  host: this.providerHost,
12252
12870
  metaStore,
@@ -12317,6 +12935,8 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12317
12935
  loadMeta: (input) => loadMeta(pctx, input),
12318
12936
  setName: (input) => setName(pctx, input),
12319
12937
  setAlias: (input) => setAlias(pctx, input),
12938
+ renderDeviceTemplates: (input) => templates.render(input),
12939
+ checkDeviceTemplates: (input) => templates.check(input),
12320
12940
  setLocation: (input) => setLocation(pctx, input),
12321
12941
  setType: (input) => setType(pctx, input),
12322
12942
  setIntegrationId: (input) => setIntegrationId(pctx, input),
@@ -12544,7 +13164,40 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
12544
13164
  });
12545
13165
  return this.removalHooksCleanupImpl;
12546
13166
  }
13167
+ /**
13168
+ * The template actions read device rows (alias), bindings (caps) and the
13169
+ * runtime-state slices (`device-state`) — all through what this addon already
13170
+ * owns. Built once per boot;
13171
+ */
13172
+ makeTemplateActions() {
13173
+ this.templateActions?.dispose();
13174
+ const actions = new DeviceTemplateActions(this.ctx.logger, {
13175
+ findByAlias: async (alias) => {
13176
+ const row = await this.deviceRows?.findByAlias(alias);
13177
+ if (row === void 0 || row === null) return null;
13178
+ return {
13179
+ deviceId: row.meta.id,
13180
+ addonId: row.meta.addonId,
13181
+ stableId: row.meta.stableId,
13182
+ alias
13183
+ };
13184
+ },
13185
+ capsOf: async (deviceId) => (await this.getBindings({ deviceId })).entries.map((entry) => entry.capName),
13186
+ fetchSlice: async (deviceId, cap) => {
13187
+ const api = this.ctx.api;
13188
+ if (api === void 0) throw new Error("ctx.api not ready");
13189
+ return api.deviceState.getCapSlice.query({
13190
+ deviceId,
13191
+ capName: cap
13192
+ });
13193
+ }
13194
+ });
13195
+ this.templateActions = actions;
13196
+ return actions;
13197
+ }
12547
13198
  async onShutdown() {
13199
+ this.templateActions?.dispose();
13200
+ this.templateActions = null;
12548
13201
  await this.transitions?.stop();
12549
13202
  this.transitions = null;
12550
13203
  this.removalCleanupImpl?.dispose();