@camstack/server 1.2.929 → 1.2.930
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/CHANGELOG.md +6 -0
- package/package.json +9 -11
- package/system/dist/builtins/alerts/alerts.addon.js +1 -1
- package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
- package/system/dist/builtins/composer/composer.addon.js +3 -3
- package/system/dist/builtins/composer/composer.addon.mjs +3 -3
- package/system/dist/builtins/core-blocks/actions-service.d.ts +18 -1
- package/system/dist/builtins/core-blocks/core-blocks.addon.js +986 -208
- package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +985 -208
- package/system/dist/builtins/core-blocks/tcp-connect.d.ts +3 -0
- package/system/dist/builtins/core-notifier/core-notifier.addon.js +6 -487
- package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +3 -484
- package/system/dist/builtins/device-manager/device-manager.addon.js +3 -3
- package/system/dist/builtins/device-manager/device-manager.addon.mjs +3 -3
- package/system/dist/{composition-sources-Caqv7O7z.mjs → composition-sources-BEUWn2s_.mjs} +1 -1
- package/system/dist/{composition-sources-CgnHjm8Q.js → composition-sources-acfR4hDq.js} +1 -1
- package/system/dist/{core-blocks.cap-LEMqVwxO.js → core-blocks.cap-BMeMCBrx.js} +37 -9
- package/system/dist/{core-blocks.cap-C6iKAZ-x.mjs → core-blocks.cap-BRPsLAij.mjs} +32 -10
- package/system/dist/index.js +2 -2
- package/system/dist/index.mjs +2 -2
- package/system/dist/{notification-rules.cap-B__YBgnG.js → notification-rules.cap-BDh0LDhV.js} +6 -0
- package/system/dist/{notification-rules.cap-D9ArZlwx.mjs → notification-rules.cap-DUmiMBQB.mjs} +1 -1
- package/system/dist/notification-targets-CRH-9Dy5.js +509 -0
- package/system/dist/notification-targets-DaNE-pIt.mjs +486 -0
- package/system/dist/{prefix-walk-DC0ljmbB.js → prefix-walk-BkMxoXpL.js} +1 -1
- package/system/dist/{prefix-walk-B4b2-9aK.mjs → prefix-walk-ifwg_ukx.mjs} +1 -1
- package/system/dist/{rename-composition-block-CcWLwVhG.js → rename-composition-block-BJsL58Ih.js} +121 -15
- package/system/dist/{rename-composition-block-7WIICIDq.mjs → rename-composition-block-OAtErZgq.mjs} +121 -15
- package/system/package.json +1 -1
|
@@ -3,8 +3,9 @@ const require_chunk = require("../../chunk-Cek0wNdY.js");
|
|
|
3
3
|
const require_stream_catalog_cap = require("../../stream-catalog.cap-D3uwePiA.js");
|
|
4
4
|
const require_base_addon = require("../../base-addon-DD5dIfcZ.js");
|
|
5
5
|
const require_scoped_settings = require("../../scoped-settings-CylSSq_8.js");
|
|
6
|
-
const require_rename_composition_block = require("../../rename-composition-block-
|
|
7
|
-
const
|
|
6
|
+
const require_rename_composition_block = require("../../rename-composition-block-BJsL58Ih.js");
|
|
7
|
+
const require_notification_targets = require("../../notification-targets-CRH-9Dy5.js");
|
|
8
|
+
const require_notification_rules_cap = require("../../notification-rules.cap-BDh0LDhV.js");
|
|
8
9
|
const require_record_kind = require("../../record-kind-DoBfYHCs.js");
|
|
9
10
|
const require_entry_kind = require("../../entry-kind-cq90c--V.js");
|
|
10
11
|
const require_device_manager_cap = require("../../device-manager.cap-2abwVLCM.js");
|
|
@@ -13,13 +14,13 @@ const require_quantity = require("../../quantity-lY1KiTSZ.js");
|
|
|
13
14
|
const require_tag = require("../../tag-BxLazvVb.js");
|
|
14
15
|
const require_device_type = require("../../device-type-CbQsnFdC.js");
|
|
15
16
|
const require_device_kind = require("../../device-kind-CsSiv_YF.js");
|
|
16
|
-
const require_core_blocks_cap = require("../../core-blocks.cap-
|
|
17
|
+
const require_core_blocks_cap = require("../../core-blocks.cap-BMeMCBrx.js");
|
|
17
18
|
const require_error_cap = require("../../error.cap-DBhgPeWK.js");
|
|
18
|
-
const require_prefix_walk = require("../../prefix-walk-
|
|
19
|
+
const require_prefix_walk = require("../../prefix-walk-BkMxoXpL.js");
|
|
19
20
|
const require_l10n = require("../../l10n-CGMvp7NF.js");
|
|
20
21
|
const require_integration_instances_cap = require("../../integration-instances.cap-dJIxg2_s.js");
|
|
21
22
|
const require_cap_call_context = require("../../cap-call-context-Bd76CbOW.js");
|
|
22
|
-
const require_composition_sources = require("../../composition-sources-
|
|
23
|
+
const require_composition_sources = require("../../composition-sources-acfR4hDq.js");
|
|
23
24
|
const require_declared_device = require("../../declared-device-BWphj9WE.js");
|
|
24
25
|
const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
|
|
25
26
|
const require_capture_engine = require("../../capture-engine-DZ0LIUqA.js");
|
|
@@ -28,6 +29,8 @@ const require_cap_call_scope = require("../../cap-call-scope-8eiugfLl.js");
|
|
|
28
29
|
let zod = require("zod");
|
|
29
30
|
let node_crypto = require("node:crypto");
|
|
30
31
|
let _camstack_types_node = require("@camstack/types/node");
|
|
32
|
+
let node_net = require("node:net");
|
|
33
|
+
node_net = require_chunk.__toESM(node_net);
|
|
31
34
|
let node_path = require("node:path");
|
|
32
35
|
node_path = require_chunk.__toESM(node_path);
|
|
33
36
|
let _camstack_types_addon = require("@camstack/types/addon");
|
|
@@ -93,6 +96,26 @@ async function readGuard(guard) {
|
|
|
93
96
|
};
|
|
94
97
|
}
|
|
95
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* What a loop's condition says about going on. A `while` goes on while it
|
|
101
|
+
* reads true, an `until` goes on while it reads false; `unknown` ends either,
|
|
102
|
+
* with the reason (D49): a loop never runs on a value it could not read.
|
|
103
|
+
*/
|
|
104
|
+
function repeatCheck(by, verdict) {
|
|
105
|
+
if (verdict.result === "unknown") return {
|
|
106
|
+
go: false,
|
|
107
|
+
reason: `the condition could not be read: ${verdict.reason}`,
|
|
108
|
+
unknown: true
|
|
109
|
+
};
|
|
110
|
+
if (by === "while") return verdict.result === "true" ? { go: true } : {
|
|
111
|
+
go: false,
|
|
112
|
+
reason: "the condition is no longer true"
|
|
113
|
+
};
|
|
114
|
+
return verdict.result === "true" ? {
|
|
115
|
+
go: false,
|
|
116
|
+
reason: "the condition is true"
|
|
117
|
+
} : { go: true };
|
|
118
|
+
}
|
|
96
119
|
/** A loop condition that throws ends the loop as unreadable, never a crash of the run. */
|
|
97
120
|
async function readRepeatCheck(check, iteration) {
|
|
98
121
|
if (check === void 0) return { go: true };
|
|
@@ -654,10 +677,6 @@ function commandStepMeta(target, actionId) {
|
|
|
654
677
|
...target.kind === "devices" && target.ids.length === 1 ? { deviceId: target.ids[0] } : {}
|
|
655
678
|
};
|
|
656
679
|
}
|
|
657
|
-
function stepMetaOfAction(step) {
|
|
658
|
-
if (step.kind === "wait") return { kind: "wait" };
|
|
659
|
-
return commandStepMeta(step.target, step.actionId);
|
|
660
|
-
}
|
|
661
680
|
function isPlainRecord$2(value) {
|
|
662
681
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
663
682
|
}
|
|
@@ -695,75 +714,6 @@ async function runForDevices(deviceIds, scope, work, concurrency = 4) {
|
|
|
695
714
|
const failed = outcomes.filter((o) => o.outcome === "error");
|
|
696
715
|
if (failed.length > 0) throw new Error(`${failed.length} of ${outcomes.length} devices failed: ` + failed.slice(0, 3).map((f) => `${f.deviceId}: ${f.message ?? "failed"}`).join("; "));
|
|
697
716
|
}
|
|
698
|
-
/**
|
|
699
|
-
* The runnable form of an internal Action's steps, bound to one run's
|
|
700
|
-
* variables. Variables are substituted per step, at the moment it runs, so a
|
|
701
|
-
* missing one fails THAT step (traced) and leaves the later ones not-run.
|
|
702
|
-
*/
|
|
703
|
-
/** The guard and the else list of a step, bound to the run (#472); `{}` for an unguarded step. */
|
|
704
|
-
function guardOf(step, vars, deps) {
|
|
705
|
-
const when = step.if;
|
|
706
|
-
if (when === void 0) return {};
|
|
707
|
-
const evaluate = deps.evaluateCondition;
|
|
708
|
-
return {
|
|
709
|
-
guard: async () => evaluate === void 0 ? {
|
|
710
|
-
result: "unknown",
|
|
711
|
-
reason: "this consumer has no condition evaluator"
|
|
712
|
-
} : evaluate(when),
|
|
713
|
-
...step.else === void 0 ? {} : { otherwise: buildActionSteps(step.else, vars, deps) }
|
|
714
|
-
};
|
|
715
|
-
}
|
|
716
|
-
function buildActionSteps(steps, vars, deps) {
|
|
717
|
-
return steps.map((step) => {
|
|
718
|
-
const guarded = {
|
|
719
|
-
...guardOf(step, vars, deps),
|
|
720
|
-
...step.enabled === false ? { disabled: true } : {}
|
|
721
|
-
};
|
|
722
|
-
const meta = stepMetaOfAction(step);
|
|
723
|
-
if (step.kind === "wait") return {
|
|
724
|
-
meta,
|
|
725
|
-
...guarded,
|
|
726
|
-
run: () => deps.sleep(step.seconds * 1e3)
|
|
727
|
-
};
|
|
728
|
-
return {
|
|
729
|
-
meta,
|
|
730
|
-
...guarded,
|
|
731
|
-
run: async (scope) => {
|
|
732
|
-
require_core_blocks_cap.vocabCall(step.actionId, void 0);
|
|
733
|
-
const templated = await resolveStepArgsWithTemplates(step.args ?? {}, vars, deps.onMissingVar, deps.renderTemplates);
|
|
734
|
-
if (templated.notes.length > 0) scope.setTemplateNotes(templated.notes);
|
|
735
|
-
const args = isPlainRecord$2(templated.value) ? templated.value : {};
|
|
736
|
-
const target = await deps.resolveTarget(step.target, step.actionId, vars, {
|
|
737
|
-
actionId: step.actionId,
|
|
738
|
-
owner: deps.owner
|
|
739
|
-
});
|
|
740
|
-
if (target.deviceIds.length === 0) {
|
|
741
|
-
scope.markEmpty(target.emptyReason ?? "the target matched no device");
|
|
742
|
-
return;
|
|
743
|
-
}
|
|
744
|
-
const call = require_core_blocks_cap.vocabCall(step.actionId, args);
|
|
745
|
-
scope.setArgs(args);
|
|
746
|
-
const [only] = target.deviceIds;
|
|
747
|
-
if (target.deviceIds.length === 1 && only !== void 0) {
|
|
748
|
-
scope.setDeviceId(only);
|
|
749
|
-
await deps.invokeCap({
|
|
750
|
-
deviceId: only,
|
|
751
|
-
cap: call.cap,
|
|
752
|
-
method: call.method,
|
|
753
|
-
args: call.args
|
|
754
|
-
});
|
|
755
|
-
return;
|
|
756
|
-
}
|
|
757
|
-
await runForDevices(target.deviceIds, scope, (deviceId) => deps.invokeCap({
|
|
758
|
-
deviceId,
|
|
759
|
-
cap: call.cap,
|
|
760
|
-
method: call.method,
|
|
761
|
-
args: call.args
|
|
762
|
-
}));
|
|
763
|
-
}
|
|
764
|
-
};
|
|
765
|
-
});
|
|
766
|
-
}
|
|
767
717
|
//#endregion
|
|
768
718
|
//#region ../types/dist/esm/automation/recipe-literal.mjs
|
|
769
719
|
/**
|
|
@@ -934,7 +884,7 @@ function triggerLeafVariables(kind) {
|
|
|
934
884
|
* (D8: an event WAKES the evaluation, the reconcile guarantees it). */
|
|
935
885
|
var RECONCILE_MS = 15e3;
|
|
936
886
|
/** What a step trace shows before the step runs. */
|
|
937
|
-
function stepMetaOf(action) {
|
|
887
|
+
function stepMetaOf$1(action) {
|
|
938
888
|
switch (action.kind) {
|
|
939
889
|
case "wait": return { kind: "wait" };
|
|
940
890
|
case "code": return { kind: "code" };
|
|
@@ -1246,66 +1196,35 @@ function emitStepBody(action) {
|
|
|
1246
1196
|
case "wait": return ` await sleep(${j(action.seconds * 1e3)})`;
|
|
1247
1197
|
case "command": return ` await actuateTarget(scope, ${j(action.target)}, ${j(action.actionId)}, ${j(action.args ?? {})}, vars)`;
|
|
1248
1198
|
case "action": return ` // an Action run, awaited: the step takes THAT run's outcome
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1199
|
+
await runActionBody(${j(action)}, {
|
|
1200
|
+
...env,
|
|
1201
|
+
run: (input) =>
|
|
1202
|
+
ctx.api.actions.run.mutate({
|
|
1203
|
+
actionId: input.actionId,
|
|
1204
|
+
variables: input.variables,
|
|
1205
|
+
wait: true,
|
|
1206
|
+
origin: { blockId: BLOCK_ID ?? undefined },
|
|
1207
|
+
}),
|
|
1208
|
+
})`;
|
|
1258
1209
|
case "notify": return ` // a notification through one target: the one send path the exporters use
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
if (sent.status === 'failed') throw new Error('notification failed: ' + sent.message)`;
|
|
1210
|
+
await runNotifyBody(${j(action)}, {
|
|
1211
|
+
...env,
|
|
1212
|
+
send: (input) =>
|
|
1213
|
+
sendToExportedTarget(ctx.api, ctx.logger, {
|
|
1214
|
+
exporter: 'automation',
|
|
1215
|
+
targetId: input.targetId,
|
|
1216
|
+
notification: { body: input.body, ...(input.title === undefined ? {} : { title: input.title }) },
|
|
1217
|
+
}),
|
|
1218
|
+
})`;
|
|
1269
1219
|
case "probe": return ` // a TCP reachability probe: one measurement, an expectation, an optional retry window
|
|
1270
|
-
|
|
1271
|
-
{ connect: tcpConnect, now: () => Date.now(), sleep, isAborted: () => token.aborted },
|
|
1272
|
-
{
|
|
1273
|
-
host: String(substitute(${j(action.host)}, vars)),
|
|
1274
|
-
port: ${j(action.port)},
|
|
1275
|
-
timeoutSeconds: ${j(action.timeoutSeconds)},
|
|
1276
|
-
${action.expect === void 0 ? "" : `expect: ${j(action.expect)},`}
|
|
1277
|
-
${action.retryUntilSeconds === void 0 ? "" : `retryUntilSeconds: ${j(action.retryUntilSeconds)},`}
|
|
1278
|
-
},
|
|
1279
|
-
)
|
|
1280
|
-
${action.saveAs === void 0 ? "" : `Object.assign(vars, reachVars(${j(action.saveAs)}, probed.result))`}
|
|
1281
|
-
scope.setAttempts(probed.attempts, probed.message)
|
|
1282
|
-
ctx.logger.info('probe finished', { host: String(substitute(${j(action.host)}, vars)), port: ${j(action.port)}, met: probed.met, attempts: probed.attempts, rttMs: probed.result.rttMs })
|
|
1283
|
-
if (!probed.met) throw new Error('probe: ' + probed.message)`;
|
|
1220
|
+
await runProbeBody(${j(action)}, scope, { ...env, connect: tcpConnect })`;
|
|
1284
1221
|
case "http-request": return ` // an HTTP request: one measurement, an expectation, an optional retry window.
|
|
1285
1222
|
// Header values and the body are never logged or traced.
|
|
1286
|
-
|
|
1287
|
-
scope.setArgs({ method: ${j(action.method)}, url: redactUrl(httpUrl) })
|
|
1288
|
-
const startedHttp = Date.now()
|
|
1289
|
-
const requested = await runHttpStep(
|
|
1290
|
-
{ fetch: globalThis.fetch, now: () => Date.now(), sleep, isAborted: () => token.aborted },
|
|
1291
|
-
{
|
|
1292
|
-
method: ${j(action.method)},
|
|
1293
|
-
url: httpUrl,
|
|
1294
|
-
timeoutSeconds: ${j(action.timeoutSeconds)},
|
|
1295
|
-
${action.headers === void 0 ? "" : `headers: substituteStrings(${j(action.headers)}, vars),`}
|
|
1296
|
-
${action.body === void 0 ? "" : `body: String(substitute(${j(action.body)}, vars)),`}
|
|
1297
|
-
${action.expect === void 0 ? "" : `expect: ${j(action.expect)},`}
|
|
1298
|
-
${action.retryUntilSeconds === void 0 ? "" : `retryUntilSeconds: ${j(action.retryUntilSeconds)},`}
|
|
1299
|
-
},
|
|
1300
|
-
)
|
|
1301
|
-
${action.saveAs === void 0 ? "" : `Object.assign(vars, reachVars(${j(action.saveAs)}, requested.result))`}
|
|
1302
|
-
scope.setAttempts(requested.attempts, requested.message)
|
|
1303
|
-
ctx.logger.info('http request finished', { method: ${j(action.method)}, url: redactUrl(httpUrl), status: requested.result.status, met: requested.met, attempts: requested.attempts, durationMs: Date.now() - startedHttp })
|
|
1304
|
-
if (!requested.met) throw new Error('http request: ' + requested.message)`;
|
|
1223
|
+
await runHttpBody(${j(action)}, scope, { ...env, fetch: globalThis.fetch })`;
|
|
1305
1224
|
case "stop": return ` // end the run here, on purpose: the steps after it are not-run with this reason
|
|
1306
1225
|
scope.stop(String(substitute(${j(action.reason)}, vars)), ${j(action.outcome)})`;
|
|
1307
1226
|
case "set": return ` // write the run's own bag, for the steps after this one — substitution only
|
|
1308
|
-
|
|
1227
|
+
runSetBody(${j(action)}, env)`;
|
|
1309
1228
|
case "code": return ` // inline code action — a fragment of THIS block, bundled by esbuild
|
|
1310
1229
|
await (async () => {
|
|
1311
1230
|
${action.code.split("\n").map((line) => ` ${line}`).join("\n")}
|
|
@@ -1322,7 +1241,7 @@ function isNestedSite(site) {
|
|
|
1322
1241
|
/** A list of steps under `path` (a branch, an else list, the steps of a repeat or a parallel). */
|
|
1323
1242
|
function emitList(steps, path) {
|
|
1324
1243
|
return steps.map((step, at) => emitStep(step, {
|
|
1325
|
-
meta: j(stepMetaOf(step)),
|
|
1244
|
+
meta: j(stepMetaOf$1(step)),
|
|
1326
1245
|
path: `${path}.${at}`
|
|
1327
1246
|
})).join("\n");
|
|
1328
1247
|
}
|
|
@@ -1365,52 +1284,22 @@ function wakeDevicesOf(when) {
|
|
|
1365
1284
|
}
|
|
1366
1285
|
/** A `wait-until` step: read the condition, wait for a wake, read again, until the timeout. */
|
|
1367
1286
|
function emitWaitUntil(action, site) {
|
|
1368
|
-
const onTimeout = action.onTimeout === "stop" ? `scope.stop(message, 'failed')` : "scope.markTimedOut(message)";
|
|
1369
1287
|
return ` {
|
|
1370
1288
|
meta: ${site.meta},
|
|
1371
1289
|
run: async (scope) => {
|
|
1372
1290
|
// woken by a report of one of its devices, by the reconcile tick, or by a restart
|
|
1373
|
-
|
|
1291
|
+
await runWaitUntilBody(${j(action)}, scope, {
|
|
1292
|
+
...env,
|
|
1374
1293
|
read: () => evaluateCondition(${j(action.when)}, ${j(`${site.path}.when`)}, vars),
|
|
1375
|
-
timeoutMs: ${j(action.timeoutS * 1e3)},
|
|
1376
|
-
now: () => Date.now(),
|
|
1377
|
-
isAborted: () => token.aborted,
|
|
1378
1294
|
nextWake: (ms) => waitForWake(ms, token, ${j(wakeDevicesOf(action.when))}),
|
|
1379
|
-
})
|
|
1380
|
-
if (waited.result === 'timed-out') {
|
|
1381
|
-
const message = waitTimedOutMessage(${j(action.timeoutS)}, waited.lastReason)
|
|
1382
|
-
ctx.logger.info('wait-until timed out', { step: ${j(site.path)}, onTimeout: ${j(action.onTimeout)}, reason: waited.lastReason })
|
|
1383
|
-
${onTimeout}
|
|
1384
|
-
}
|
|
1295
|
+
}, ${j(site.path)})
|
|
1385
1296
|
},
|
|
1386
1297
|
},`;
|
|
1387
1298
|
}
|
|
1388
|
-
/** How a `repeat` decides its iterations, as the fields of a RunnableRepeat
|
|
1299
|
+
/** How a `repeat` decides its iterations, as the fields of a RunnableRepeat: the shared `repeatLoopFields`. */
|
|
1389
1300
|
function emitRepeatLoop(loop, site) {
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
case "forEach": return `// once per device: the device id is in vars.${require_core_blocks_cap.REPEAT_ITEM_VAR} for the steps of that iteration
|
|
1393
|
-
limit: ${j(loop.target.ids.length)}, limitIsTimeout: false,
|
|
1394
|
-
...(() => {
|
|
1395
|
-
const ids = ${j(loop.target.ids)}
|
|
1396
|
-
let outer: unknown
|
|
1397
|
-
return {
|
|
1398
|
-
before: async (iteration) => {
|
|
1399
|
-
if (iteration === 0) outer = vars[${j(require_core_blocks_cap.REPEAT_ITEM_VAR)}]
|
|
1400
|
-
if (iteration < ids.length) vars[${j(require_core_blocks_cap.REPEAT_ITEM_VAR)}] = ids[iteration]
|
|
1401
|
-
else if (${j(isNestedSite(site))} && outer !== undefined) vars[${j(require_core_blocks_cap.REPEAT_ITEM_VAR)}] = outer
|
|
1402
|
-
return { go: true }
|
|
1403
|
-
},
|
|
1404
|
-
}
|
|
1405
|
-
})(),`;
|
|
1406
|
-
case "while":
|
|
1407
|
-
case "until": {
|
|
1408
|
-
const read = `repeatCheck(${j(loop.by)}, await evaluateCondition(${j(loop.when)}, ${j(`${site.path}.loop.when`)}, vars))`;
|
|
1409
|
-
const pause = loop.waitS === void 0 ? "" : `\n between: () => sleep(${j(loop.waitS * 1e3)}),`;
|
|
1410
|
-
return `limit: ${j(loop.maxIterations)}, limitIsTimeout: true,
|
|
1411
|
-
${loop.by === "while" ? "before" : "after"}: async () => ${read},${pause}`;
|
|
1412
|
-
}
|
|
1413
|
-
}
|
|
1301
|
+
const read = loop.by === "while" || loop.by === "until" ? `read: (when) => evaluateCondition(when, ${j(`${site.path}.loop.when`)}, vars)` : "read: async () => ({ result: 'unknown', reason: 'no condition' })";
|
|
1302
|
+
return `...repeatLoopFields(${j(loop)}, { ...env, ${read} }, ${j(isNestedSite(site))}),`;
|
|
1414
1303
|
}
|
|
1415
1304
|
/** One step, wherever it sits: a block step emits its own steps one level down, under its path. */
|
|
1416
1305
|
function emitStep(action, site) {
|
|
@@ -1500,7 +1389,7 @@ function renderAutomationBlock(input) {
|
|
|
1500
1389
|
if (boundsError !== null) throw new Error(`cannot generate an automation from an invalid recipe: ${boundsError}`);
|
|
1501
1390
|
const { name, recipe } = input;
|
|
1502
1391
|
const runMode = recipe.runMode ?? { mode: "single" };
|
|
1503
|
-
const stepMeta = recipe.actions.map(stepMetaOf);
|
|
1392
|
+
const stepMeta = recipe.actions.map(stepMetaOf$1);
|
|
1504
1393
|
const elseSteps = (a) => a.kind === "wait" || a.kind === "command" ? a.else ?? [] : [];
|
|
1505
1394
|
const hasDomainTarget = recipe.actions.flatMap((a) => [
|
|
1506
1395
|
a,
|
|
@@ -1528,6 +1417,7 @@ function renderAutomationBlock(input) {
|
|
|
1528
1417
|
AutomationRunVerdict,
|
|
1529
1418
|
AutomationWhen,
|
|
1530
1419
|
AutomationStepTrace,
|
|
1420
|
+
BodyEnv,
|
|
1531
1421
|
RunnableStep,
|
|
1532
1422
|
StepScope,
|
|
1533
1423
|
TimeSite,
|
|
@@ -1566,13 +1456,13 @@ import {
|
|
|
1566
1456
|
vocabCall,
|
|
1567
1457
|
evaluateStepCondition,
|
|
1568
1458
|
runSteps,
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1459
|
+
runProbeBody,
|
|
1460
|
+
runHttpBody,
|
|
1461
|
+
runActionBody,
|
|
1462
|
+
runNotifyBody,
|
|
1463
|
+
runSetBody,
|
|
1464
|
+
runWaitUntilBody,
|
|
1465
|
+
repeatLoopFields,
|
|
1576
1466
|
siteFor,
|
|
1577
1467
|
validateTimeSpecForSite,
|
|
1578
1468
|
zoneOnlySite,
|
|
@@ -1996,14 +1886,6 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
|
|
|
1996
1886
|
return resolveStepArgs(value, vars, warnMissingVar)
|
|
1997
1887
|
}
|
|
1998
1888
|
|
|
1999
|
-
/** Header values, substituted: the values are text, and are never logged. */
|
|
2000
|
-
function substituteStrings(
|
|
2001
|
-
raw: Record<string, string>,
|
|
2002
|
-
vars: Record<string, unknown>,
|
|
2003
|
-
): Record<string, string> {
|
|
2004
|
-
return Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, String(substitute(value, vars))]))
|
|
2005
|
-
}
|
|
2006
|
-
|
|
2007
1889
|
/** Open a TCP connection and close it again: resolves when the port answered. */
|
|
2008
1890
|
async function tcpConnect(host: string, port: number, timeoutMs: number): Promise<void> {
|
|
2009
1891
|
const net = await import('node:net')
|
|
@@ -2020,21 +1902,6 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
|
|
|
2020
1902
|
})
|
|
2021
1903
|
}
|
|
2022
1904
|
|
|
2023
|
-
/** The variables handed to an Action step, substituted and kept to primitives. */
|
|
2024
|
-
function substituteVariables(
|
|
2025
|
-
raw: Record<string, string | number | boolean>,
|
|
2026
|
-
vars: Record<string, unknown>,
|
|
2027
|
-
): Record<string, string | number | boolean> {
|
|
2028
|
-
const out: Record<string, string | number | boolean> = {}
|
|
2029
|
-
for (const [key, value] of Object.entries(raw)) {
|
|
2030
|
-
const resolved = substitute(value, vars)
|
|
2031
|
-
if (typeof resolved === 'string' || typeof resolved === 'number' || typeof resolved === 'boolean') {
|
|
2032
|
-
out[key] = resolved
|
|
2033
|
-
}
|
|
2034
|
-
}
|
|
2035
|
-
return out
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
1905
|
async function actuate(
|
|
2039
1906
|
scope: StepScope,
|
|
2040
1907
|
deviceId: number,
|
|
@@ -2082,6 +1949,15 @@ ${hasTime ? ` // a time-is leaf changes sides at a boundary with no device ev
|
|
|
2082
1949
|
token: RunToken,
|
|
2083
1950
|
): Promise<{ steps: readonly AutomationStepTrace[]; failed: boolean }> {
|
|
2084
1951
|
const sleep = (ms: number): Promise<void> => abortableSleep(ms, token)
|
|
1952
|
+
// what a step does when it runs is shared with an Action's runner (step-bodies.ts)
|
|
1953
|
+
const env: BodyEnv = {
|
|
1954
|
+
vars,
|
|
1955
|
+
substitute: (value) => substitute(value, vars),
|
|
1956
|
+
sleep,
|
|
1957
|
+
now: () => Date.now(),
|
|
1958
|
+
isAborted: () => token.aborted,
|
|
1959
|
+
info: (message, meta) => ctx.logger.info(message, meta),
|
|
1960
|
+
}
|
|
2085
1961
|
const steps: RunnableStep[] = [
|
|
2086
1962
|
${recipe.actions.map((a, i) => emitAction(a, i)).join("\n")}
|
|
2087
1963
|
]
|
|
@@ -2369,7 +2245,7 @@ ${eventLeaves.map(({ leaf, path }) => emitLeaf(leaf, path)).join("\n\n")}
|
|
|
2369
2245
|
* named devices' binding maps, never the fleet-wide capability list.
|
|
2370
2246
|
*/
|
|
2371
2247
|
/** The steps directly under this one: its `else`, a block's body, every branch. */
|
|
2372
|
-
function childrenOf(step) {
|
|
2248
|
+
function childrenOf$1(step) {
|
|
2373
2249
|
switch (step.kind) {
|
|
2374
2250
|
case "wait":
|
|
2375
2251
|
case "command": return "else" in step ? step.else ?? [] : [];
|
|
@@ -2384,7 +2260,7 @@ function commandsIn(step) {
|
|
|
2384
2260
|
return [...step.kind === "command" && step.target.kind === "devices" ? [{
|
|
2385
2261
|
actionId: step.actionId,
|
|
2386
2262
|
ids: step.target.ids
|
|
2387
|
-
}] : [], ...childrenOf(step).flatMap(commandsIn)];
|
|
2263
|
+
}] : [], ...childrenOf$1(step).flatMap(commandsIn)];
|
|
2388
2264
|
}
|
|
2389
2265
|
/**
|
|
2390
2266
|
* Refuse a step list naming a device that does not offer the step's action.
|
|
@@ -2428,6 +2304,738 @@ async function evaluateStepCondition(when, fetchers, now = Date.now, history, si
|
|
|
2428
2304
|
};
|
|
2429
2305
|
}
|
|
2430
2306
|
//#endregion
|
|
2307
|
+
//#region ../types/dist/esm/automation/reach-steps.mjs
|
|
2308
|
+
/** Read at most `cap` bytes of a body, then cancel the stream: a huge answer is never held. */
|
|
2309
|
+
async function readCappedBody(response, cap) {
|
|
2310
|
+
if (response.body === void 0 || response.body === null) {
|
|
2311
|
+
const full = await response.text();
|
|
2312
|
+
return full.length > cap ? {
|
|
2313
|
+
text: full.slice(0, cap),
|
|
2314
|
+
truncated: true
|
|
2315
|
+
} : {
|
|
2316
|
+
text: full,
|
|
2317
|
+
truncated: false
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
const reader = response.body.getReader();
|
|
2321
|
+
const chunks = [];
|
|
2322
|
+
let total = 0;
|
|
2323
|
+
let truncated = false;
|
|
2324
|
+
for (;;) {
|
|
2325
|
+
const { done, value } = await reader.read();
|
|
2326
|
+
if (done) break;
|
|
2327
|
+
if (value === void 0) continue;
|
|
2328
|
+
const room = cap - total;
|
|
2329
|
+
if (value.length > room) {
|
|
2330
|
+
chunks.push(value.subarray(0, room));
|
|
2331
|
+
total += room;
|
|
2332
|
+
truncated = true;
|
|
2333
|
+
await reader.cancel();
|
|
2334
|
+
break;
|
|
2335
|
+
}
|
|
2336
|
+
chunks.push(value);
|
|
2337
|
+
total += value.length;
|
|
2338
|
+
}
|
|
2339
|
+
const bytes = new Uint8Array(total);
|
|
2340
|
+
let at = 0;
|
|
2341
|
+
for (const chunk of chunks) {
|
|
2342
|
+
bytes.set(chunk, at);
|
|
2343
|
+
at += chunk.length;
|
|
2344
|
+
}
|
|
2345
|
+
return {
|
|
2346
|
+
text: new TextDecoder().decode(bytes),
|
|
2347
|
+
truncated
|
|
2348
|
+
};
|
|
2349
|
+
}
|
|
2350
|
+
/**
|
|
2351
|
+
* A URL as it may be logged or traced: the userinfo and every query value are
|
|
2352
|
+
* replaced by `***` (the keys stay). Text that is not a URL is returned as `***`.
|
|
2353
|
+
*/
|
|
2354
|
+
function redactUrl(raw) {
|
|
2355
|
+
try {
|
|
2356
|
+
const u = new URL(raw);
|
|
2357
|
+
if (u.username !== "") u.username = "***";
|
|
2358
|
+
if (u.password !== "") u.password = "***";
|
|
2359
|
+
for (const key of [...u.searchParams.keys()]) u.searchParams.set(key, "***");
|
|
2360
|
+
return u.toString().replace(/%2A%2A%2A/g, "***");
|
|
2361
|
+
} catch {
|
|
2362
|
+
return "***";
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
function errorText$5(err) {
|
|
2366
|
+
return err instanceof Error ? err.message : String(err);
|
|
2367
|
+
}
|
|
2368
|
+
/** A transport error names the URL it was given: show the redacted one, and no userinfo at all. */
|
|
2369
|
+
function scrubbedError(err, url) {
|
|
2370
|
+
return errorText$5(err).split(url).join(redactUrl(url)).replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]*@/gi, "$1***@");
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* Try, and while the expectation does not hold and the window is open, pause
|
|
2374
|
+
* {@link REACH_RETRY_INTERVAL_S} s and try again. Bounded twice: the window is
|
|
2375
|
+
* clamped to {@link REACH_RETRY_MAX_S}, and the pause is a constant.
|
|
2376
|
+
*/
|
|
2377
|
+
async function retryUntilMet(clock, input) {
|
|
2378
|
+
const windowMs = Math.min(input.windowSeconds ?? 0, 600) * 1e3;
|
|
2379
|
+
const deadline = clock.now() + windowMs;
|
|
2380
|
+
const interval = 5 * 1e3;
|
|
2381
|
+
let attempts = 0;
|
|
2382
|
+
for (;;) {
|
|
2383
|
+
const result = await input.attempt();
|
|
2384
|
+
attempts += 1;
|
|
2385
|
+
const met = input.met(result);
|
|
2386
|
+
if (met || clock.isAborted()) return {
|
|
2387
|
+
result,
|
|
2388
|
+
met,
|
|
2389
|
+
attempts
|
|
2390
|
+
};
|
|
2391
|
+
const left = deadline - clock.now();
|
|
2392
|
+
if (left <= 0) return {
|
|
2393
|
+
result,
|
|
2394
|
+
met,
|
|
2395
|
+
attempts
|
|
2396
|
+
};
|
|
2397
|
+
await clock.sleep(Math.min(interval, left));
|
|
2398
|
+
if (clock.isAborted()) return {
|
|
2399
|
+
result,
|
|
2400
|
+
met,
|
|
2401
|
+
attempts
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
async function probeOnce(deps, input) {
|
|
2406
|
+
const startedAt = deps.now();
|
|
2407
|
+
try {
|
|
2408
|
+
await deps.connect(input.host, input.port, input.timeoutSeconds * 1e3);
|
|
2409
|
+
return {
|
|
2410
|
+
reachable: true,
|
|
2411
|
+
rttMs: Math.max(0, deps.now() - startedAt),
|
|
2412
|
+
error: null
|
|
2413
|
+
};
|
|
2414
|
+
} catch (err) {
|
|
2415
|
+
return {
|
|
2416
|
+
reachable: false,
|
|
2417
|
+
rttMs: null,
|
|
2418
|
+
error: errorText$5(err)
|
|
2419
|
+
};
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
async function runProbeStep(deps, input) {
|
|
2423
|
+
const want = input.expect ?? "reachable";
|
|
2424
|
+
const run = await retryUntilMet(deps, {
|
|
2425
|
+
attempt: () => probeOnce(deps, input),
|
|
2426
|
+
met: (result) => result.reachable === (want === "reachable"),
|
|
2427
|
+
windowSeconds: input.retryUntilSeconds
|
|
2428
|
+
});
|
|
2429
|
+
const seen = run.result.reachable ? `reachable in ${String(run.result.rttMs)} ms` : `unreachable (${run.result.error ?? "no answer"})`;
|
|
2430
|
+
return {
|
|
2431
|
+
...run,
|
|
2432
|
+
message: `${run.met ? "expected" : "wanted"} ${want}; after ${String(run.attempts)} attempt(s) ${seen}`
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
function parseJson(text, truncated) {
|
|
2436
|
+
if (truncated) return null;
|
|
2437
|
+
try {
|
|
2438
|
+
return JSON.parse(text);
|
|
2439
|
+
} catch {
|
|
2440
|
+
return null;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
async function httpOnce(deps, input) {
|
|
2444
|
+
const controller = new AbortController();
|
|
2445
|
+
const timer = setTimeout(() => controller.abort(), input.timeoutSeconds * 1e3);
|
|
2446
|
+
try {
|
|
2447
|
+
const response = await deps.fetch(input.url, {
|
|
2448
|
+
method: input.method,
|
|
2449
|
+
...input.headers === void 0 ? {} : { headers: { ...input.headers } },
|
|
2450
|
+
...input.body === void 0 ? {} : { body: input.body },
|
|
2451
|
+
signal: controller.signal
|
|
2452
|
+
});
|
|
2453
|
+
const body = await readCappedBody(response, require_core_blocks_cap.HTTP_TEXT_CAP);
|
|
2454
|
+
return {
|
|
2455
|
+
status: response.status,
|
|
2456
|
+
ok: response.status >= 200 && response.status < 300,
|
|
2457
|
+
json: parseJson(body.text, body.truncated),
|
|
2458
|
+
text: body.text,
|
|
2459
|
+
error: null
|
|
2460
|
+
};
|
|
2461
|
+
} catch (err) {
|
|
2462
|
+
return {
|
|
2463
|
+
status: null,
|
|
2464
|
+
ok: false,
|
|
2465
|
+
json: null,
|
|
2466
|
+
text: null,
|
|
2467
|
+
error: controller.signal.aborted ? `timed out after ${String(input.timeoutSeconds)} s` : scrubbedError(err, input.url)
|
|
2468
|
+
};
|
|
2469
|
+
} finally {
|
|
2470
|
+
clearTimeout(timer);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
/** The value at a dotted path of a parsed body; `undefined` when any step of the path is missing. */
|
|
2474
|
+
function readPath(root, path) {
|
|
2475
|
+
let at = root;
|
|
2476
|
+
for (const key of path.split(".")) {
|
|
2477
|
+
if (at === null || typeof at !== "object") return void 0;
|
|
2478
|
+
at = Reflect.get(at, key);
|
|
2479
|
+
}
|
|
2480
|
+
return at;
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* Whether the answer is what the step wanted. No expectation: a 2xx. A field
|
|
2484
|
+
* that is not there is never "met" — not even for `ne` — because "absent" is
|
|
2485
|
+
* not an answer the operator compared against (D49).
|
|
2486
|
+
*/
|
|
2487
|
+
function httpExpectationMet(result, expect) {
|
|
2488
|
+
if (result.status === null) return false;
|
|
2489
|
+
if (expect === void 0) return result.ok;
|
|
2490
|
+
if (expect.on === "status") return require_core_blocks_cap.compareValues(result.status, expect.operator, expect.value);
|
|
2491
|
+
if (expect.fieldPath === void 0) return false;
|
|
2492
|
+
const actual = readPath(result.json, expect.fieldPath);
|
|
2493
|
+
if (actual === void 0) return false;
|
|
2494
|
+
return require_core_blocks_cap.compareValues(actual, expect.operator, expect.value);
|
|
2495
|
+
}
|
|
2496
|
+
async function runHttpStep(deps, input) {
|
|
2497
|
+
const run = await retryUntilMet(deps, {
|
|
2498
|
+
attempt: () => httpOnce(deps, input),
|
|
2499
|
+
met: (result) => httpExpectationMet(result, input.expect),
|
|
2500
|
+
windowSeconds: input.retryUntilSeconds
|
|
2501
|
+
});
|
|
2502
|
+
const seen = run.result.status === null ? `no answer (${run.result.error ?? "unknown"})` : `status ${String(run.result.status)}`;
|
|
2503
|
+
return {
|
|
2504
|
+
...run,
|
|
2505
|
+
message: `${run.met ? "expectation met" : "expectation not met"}; after ${String(run.attempts)} attempt(s) ${seen}`
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
2508
|
+
var FLAT_DEPTH_MAX = 4;
|
|
2509
|
+
var FLAT_KEYS_MAX = 60;
|
|
2510
|
+
function flatten(prefix, value, depth, out) {
|
|
2511
|
+
if (Object.keys(out).length >= FLAT_KEYS_MAX) return;
|
|
2512
|
+
if (value === null || value === void 0) out[prefix] = "";
|
|
2513
|
+
else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") out[prefix] = value;
|
|
2514
|
+
else if (typeof value === "object" && !Array.isArray(value) && depth < FLAT_DEPTH_MAX) for (const [key, inner] of Object.entries(value)) flatten(`${prefix}.${key}`, inner, depth + 1, out);
|
|
2515
|
+
}
|
|
2516
|
+
/**
|
|
2517
|
+
* What a step writes into the run's bag under `saveAs`: the result itself, and
|
|
2518
|
+
* its scalar fields flat (`ccu.reachable`, `r.json.sysInfo.addr`), because a
|
|
2519
|
+
* `{{vars.x.y}}` slot reads the flat key. A `null` reads as empty text there.
|
|
2520
|
+
*/
|
|
2521
|
+
function reachVars(name, result) {
|
|
2522
|
+
const flat = {};
|
|
2523
|
+
for (const [key, value] of Object.entries(result)) {
|
|
2524
|
+
if (key === "text") continue;
|
|
2525
|
+
flatten(`${name}.${key}`, value, 0, flat);
|
|
2526
|
+
}
|
|
2527
|
+
return {
|
|
2528
|
+
[name]: result,
|
|
2529
|
+
...flat
|
|
2530
|
+
};
|
|
2531
|
+
}
|
|
2532
|
+
//#endregion
|
|
2533
|
+
//#region ../types/dist/esm/automation/wait-until.mjs
|
|
2534
|
+
async function readSafely(read) {
|
|
2535
|
+
try {
|
|
2536
|
+
return await read();
|
|
2537
|
+
} catch (err) {
|
|
2538
|
+
return {
|
|
2539
|
+
result: "unknown",
|
|
2540
|
+
reason: err instanceof Error ? err.message : String(err)
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
async function waitUntil(input) {
|
|
2545
|
+
const startedAt = input.now();
|
|
2546
|
+
const deadline = startedAt + input.timeoutMs;
|
|
2547
|
+
for (;;) {
|
|
2548
|
+
const verdict = await readSafely(input.read);
|
|
2549
|
+
const waitedMs = input.now() - startedAt;
|
|
2550
|
+
if (input.isAborted()) return {
|
|
2551
|
+
result: "aborted",
|
|
2552
|
+
waitedMs
|
|
2553
|
+
};
|
|
2554
|
+
if (verdict.result === "true") return {
|
|
2555
|
+
result: "met",
|
|
2556
|
+
waitedMs
|
|
2557
|
+
};
|
|
2558
|
+
const remaining = deadline - input.now();
|
|
2559
|
+
if (remaining <= 0) return {
|
|
2560
|
+
result: "timed-out",
|
|
2561
|
+
waitedMs,
|
|
2562
|
+
lastReason: verdict.reason
|
|
2563
|
+
};
|
|
2564
|
+
await input.nextWake(remaining);
|
|
2565
|
+
if (input.isAborted()) return {
|
|
2566
|
+
result: "aborted",
|
|
2567
|
+
waitedMs: input.now() - startedAt
|
|
2568
|
+
};
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
/** What the run trace says of a wait that ran out. */
|
|
2572
|
+
function waitTimedOutMessage(timeoutS, lastReason) {
|
|
2573
|
+
return `timed out after ${timeoutS} s: ${lastReason}`;
|
|
2574
|
+
}
|
|
2575
|
+
//#endregion
|
|
2576
|
+
//#region ../types/dist/esm/automation/step-bodies.mjs
|
|
2577
|
+
/**
|
|
2578
|
+
* What a plain step DOES when it runs — the semantics of probe, http-request,
|
|
2579
|
+
* wait-until, set, notify and action, in ONE place. Two consumers call them:
|
|
2580
|
+
* the runner of an Action (`buildActionSteps`) and the block an automation
|
|
2581
|
+
* compiles to (`emitStepBody` emits a call to the same function), so a step
|
|
2582
|
+
* kind cannot behave one way in an Action and another in an automation.
|
|
2583
|
+
*
|
|
2584
|
+
* Pure: everything impure (clock, fetch, a TCP connect, the log) arrives in
|
|
2585
|
+
* {@link BodyEnv}.
|
|
2586
|
+
*/
|
|
2587
|
+
function textOf(env, value) {
|
|
2588
|
+
return String(env.substitute(value));
|
|
2589
|
+
}
|
|
2590
|
+
/** Header values, substituted: the values are text, and are never logged. */
|
|
2591
|
+
function substituteTexts(env, raw) {
|
|
2592
|
+
return Object.fromEntries(Object.entries(raw).map(([key, value]) => [key, textOf(env, value)]));
|
|
2593
|
+
}
|
|
2594
|
+
/** The variables handed to an Action step, substituted and kept to primitives. */
|
|
2595
|
+
function substituteRunVariables(env, raw) {
|
|
2596
|
+
const out = {};
|
|
2597
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
2598
|
+
const resolved = env.substitute(value);
|
|
2599
|
+
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") out[key] = resolved;
|
|
2600
|
+
}
|
|
2601
|
+
return out;
|
|
2602
|
+
}
|
|
2603
|
+
/** A TCP reachability probe: one measurement, an expectation, an optional retry window. */
|
|
2604
|
+
async function runProbeBody(step, scope, env) {
|
|
2605
|
+
const host = textOf(env, step.host);
|
|
2606
|
+
const probed = await runProbeStep({
|
|
2607
|
+
connect: env.connect,
|
|
2608
|
+
now: env.now,
|
|
2609
|
+
sleep: env.sleep,
|
|
2610
|
+
isAborted: env.isAborted
|
|
2611
|
+
}, {
|
|
2612
|
+
host,
|
|
2613
|
+
port: step.port,
|
|
2614
|
+
timeoutSeconds: step.timeoutSeconds,
|
|
2615
|
+
...step.expect === void 0 ? {} : { expect: step.expect },
|
|
2616
|
+
...step.retryUntilSeconds === void 0 ? {} : { retryUntilSeconds: step.retryUntilSeconds }
|
|
2617
|
+
});
|
|
2618
|
+
if (step.saveAs !== void 0) Object.assign(env.vars, reachVars(step.saveAs, probed.result));
|
|
2619
|
+
scope.setAttempts(probed.attempts, probed.message);
|
|
2620
|
+
env.info("probe finished", {
|
|
2621
|
+
host,
|
|
2622
|
+
port: step.port,
|
|
2623
|
+
met: probed.met,
|
|
2624
|
+
attempts: probed.attempts,
|
|
2625
|
+
rttMs: probed.result.rttMs
|
|
2626
|
+
});
|
|
2627
|
+
if (!probed.met) throw new Error(`probe: ${probed.message}`);
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* An HTTP request: one measurement, an expectation, an optional retry window.
|
|
2631
|
+
* Header values and the body are never logged or traced.
|
|
2632
|
+
*/
|
|
2633
|
+
async function runHttpBody(step, scope, env) {
|
|
2634
|
+
const url = textOf(env, step.url);
|
|
2635
|
+
scope.setArgs({
|
|
2636
|
+
method: step.method,
|
|
2637
|
+
url: redactUrl(url)
|
|
2638
|
+
});
|
|
2639
|
+
const startedAt = env.now();
|
|
2640
|
+
const requested = await runHttpStep({
|
|
2641
|
+
fetch: env.fetch,
|
|
2642
|
+
now: env.now,
|
|
2643
|
+
sleep: env.sleep,
|
|
2644
|
+
isAborted: env.isAborted
|
|
2645
|
+
}, {
|
|
2646
|
+
method: step.method,
|
|
2647
|
+
url,
|
|
2648
|
+
timeoutSeconds: step.timeoutSeconds,
|
|
2649
|
+
...step.headers === void 0 ? {} : { headers: substituteTexts(env, step.headers) },
|
|
2650
|
+
...step.body === void 0 ? {} : { body: textOf(env, step.body) },
|
|
2651
|
+
...step.expect === void 0 ? {} : { expect: step.expect },
|
|
2652
|
+
...step.retryUntilSeconds === void 0 ? {} : { retryUntilSeconds: step.retryUntilSeconds }
|
|
2653
|
+
});
|
|
2654
|
+
if (step.saveAs !== void 0) Object.assign(env.vars, reachVars(step.saveAs, requested.result));
|
|
2655
|
+
scope.setAttempts(requested.attempts, requested.message);
|
|
2656
|
+
env.info("http request finished", {
|
|
2657
|
+
method: step.method,
|
|
2658
|
+
url: redactUrl(url),
|
|
2659
|
+
status: requested.result.status,
|
|
2660
|
+
met: requested.met,
|
|
2661
|
+
attempts: requested.attempts,
|
|
2662
|
+
durationMs: env.now() - startedAt
|
|
2663
|
+
});
|
|
2664
|
+
if (!requested.met) throw new Error(`http request: ${requested.message}`);
|
|
2665
|
+
}
|
|
2666
|
+
/** Write the run's own bag, for the steps after this one — substitution only, never evaluation. */
|
|
2667
|
+
function runSetBody(step, env) {
|
|
2668
|
+
Object.assign(env.vars, substituteRunVariables(env, step.vars));
|
|
2669
|
+
}
|
|
2670
|
+
/** Pause until the condition is true; at the timeout, `continue` marks the step timed out, `stop` ends the run as a failure. */
|
|
2671
|
+
async function runWaitUntilBody(step, scope, env, path) {
|
|
2672
|
+
const waited = await waitUntil({
|
|
2673
|
+
read: env.read,
|
|
2674
|
+
timeoutMs: step.timeoutS * 1e3,
|
|
2675
|
+
now: env.now,
|
|
2676
|
+
isAborted: env.isAborted,
|
|
2677
|
+
nextWake: env.nextWake
|
|
2678
|
+
});
|
|
2679
|
+
if (waited.result !== "timed-out") return;
|
|
2680
|
+
const message = waitTimedOutMessage(step.timeoutS, waited.lastReason);
|
|
2681
|
+
env.info("wait-until timed out", {
|
|
2682
|
+
step: path,
|
|
2683
|
+
onTimeout: step.onTimeout,
|
|
2684
|
+
reason: waited.lastReason
|
|
2685
|
+
});
|
|
2686
|
+
if (step.onTimeout === "stop") scope.stop(message, "failed");
|
|
2687
|
+
else scope.markTimedOut(message);
|
|
2688
|
+
}
|
|
2689
|
+
/** A notification through one target: the one send path the exporters use. */
|
|
2690
|
+
async function runNotifyBody(step, env) {
|
|
2691
|
+
const sent = await env.send({
|
|
2692
|
+
targetId: step.targetId,
|
|
2693
|
+
body: textOf(env, step.body),
|
|
2694
|
+
...step.title === void 0 ? {} : { title: textOf(env, step.title) }
|
|
2695
|
+
});
|
|
2696
|
+
if (sent.status === "refused") throw new Error(`notification target ${sent.reason}`);
|
|
2697
|
+
if (sent.status === "failed") throw new Error(`notification failed: ${sent.message}`);
|
|
2698
|
+
}
|
|
2699
|
+
/** An Action run, awaited: the step takes THAT run's outcome. */
|
|
2700
|
+
async function runActionBody(step, env) {
|
|
2701
|
+
const result = await env.run({
|
|
2702
|
+
actionId: step.actionId,
|
|
2703
|
+
variables: substituteRunVariables(env, step.variables ?? {})
|
|
2704
|
+
});
|
|
2705
|
+
if (result.outcome !== "ran") throw new Error(`action ${step.actionId} ${result.outcome}${result.message === void 0 ? "" : `: ${result.message}`}`);
|
|
2706
|
+
}
|
|
2707
|
+
/**
|
|
2708
|
+
* `nested` is whether the loop sits inside a block step: a `forEach` one level
|
|
2709
|
+
* down gives back the device of the loop around it, when there is one; any
|
|
2710
|
+
* other loop leaves its last device in place.
|
|
2711
|
+
*/
|
|
2712
|
+
function repeatLoopFields(loop, env, nested) {
|
|
2713
|
+
switch (loop.by) {
|
|
2714
|
+
case "count": return {
|
|
2715
|
+
limit: loop.count,
|
|
2716
|
+
limitIsTimeout: false
|
|
2717
|
+
};
|
|
2718
|
+
case "forEach": {
|
|
2719
|
+
const ids = loop.target.ids;
|
|
2720
|
+
let outer;
|
|
2721
|
+
return {
|
|
2722
|
+
limit: ids.length,
|
|
2723
|
+
limitIsTimeout: false,
|
|
2724
|
+
before: async (iteration) => {
|
|
2725
|
+
if (iteration === 0) outer = env.vars[require_core_blocks_cap.REPEAT_ITEM_VAR];
|
|
2726
|
+
const id = ids[iteration];
|
|
2727
|
+
if (id !== void 0) env.vars[require_core_blocks_cap.REPEAT_ITEM_VAR] = id;
|
|
2728
|
+
else if (nested && outer !== void 0) env.vars[require_core_blocks_cap.REPEAT_ITEM_VAR] = outer;
|
|
2729
|
+
return { go: true };
|
|
2730
|
+
}
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
case "while":
|
|
2734
|
+
case "until": {
|
|
2735
|
+
const check = async () => repeatCheck(loop.by, await env.read(loop.when));
|
|
2736
|
+
const waitS = loop.waitS;
|
|
2737
|
+
return {
|
|
2738
|
+
limit: loop.maxIterations,
|
|
2739
|
+
limitIsTimeout: true,
|
|
2740
|
+
...loop.by === "while" ? { before: check } : { after: check },
|
|
2741
|
+
...waitS === void 0 ? {} : { between: () => env.sleep(waitS * 1e3) }
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
//#endregion
|
|
2747
|
+
//#region ../types/dist/esm/automation/action-steps.mjs
|
|
2748
|
+
var NO_EVALUATOR = {
|
|
2749
|
+
result: "unknown",
|
|
2750
|
+
reason: "this consumer has no condition evaluator"
|
|
2751
|
+
};
|
|
2752
|
+
function stepMetaOf(step) {
|
|
2753
|
+
switch (step.kind) {
|
|
2754
|
+
case "command": return commandStepMeta(step.target, step.actionId);
|
|
2755
|
+
case "wait":
|
|
2756
|
+
case "action":
|
|
2757
|
+
case "notify":
|
|
2758
|
+
case "probe":
|
|
2759
|
+
case "http-request":
|
|
2760
|
+
case "wait-until":
|
|
2761
|
+
case "set":
|
|
2762
|
+
case "stop":
|
|
2763
|
+
case "choose":
|
|
2764
|
+
case "parallel":
|
|
2765
|
+
case "repeat": return { kind: step.kind };
|
|
2766
|
+
default: return assertNever(step);
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
function assertNever(step) {
|
|
2770
|
+
throw new Error(`step kind not handled by the Action runner: ${JSON.stringify(step)}`);
|
|
2771
|
+
}
|
|
2772
|
+
/** The step needs an effect this consumer did not provide: it fails when it RUNS, with the name of what is missing. */
|
|
2773
|
+
function missing(kind, what) {
|
|
2774
|
+
return /* @__PURE__ */ new Error(`this consumer cannot run a ${kind} step: it has no ${what}`);
|
|
2775
|
+
}
|
|
2776
|
+
function bodyEnv(ctx) {
|
|
2777
|
+
const { deps, bag } = ctx;
|
|
2778
|
+
return {
|
|
2779
|
+
vars: bag,
|
|
2780
|
+
substitute: (value) => resolveStepArgs(value, bag, (name) => deps.onMissingVar(name)),
|
|
2781
|
+
sleep: (ms) => deps.sleep(ms),
|
|
2782
|
+
now: deps.now ?? Date.now,
|
|
2783
|
+
isAborted: deps.isAborted ?? (() => false),
|
|
2784
|
+
info: (message, meta) => deps.info?.(message, meta)
|
|
2785
|
+
};
|
|
2786
|
+
}
|
|
2787
|
+
function readerOf(ctx) {
|
|
2788
|
+
const evaluate = ctx.deps.evaluateCondition;
|
|
2789
|
+
return async (when) => evaluate === void 0 ? NO_EVALUATOR : evaluate(when);
|
|
2790
|
+
}
|
|
2791
|
+
/** The guard and the else list of a step (#472), bound to the run; `{}` for an unguarded step. */
|
|
2792
|
+
function guardOf(step, ctx) {
|
|
2793
|
+
const when = "if" in step ? step.if : void 0;
|
|
2794
|
+
if (when === void 0) return {};
|
|
2795
|
+
const read = readerOf(ctx);
|
|
2796
|
+
const otherwise = "else" in step ? step.else : void 0;
|
|
2797
|
+
return {
|
|
2798
|
+
guard: () => read(when),
|
|
2799
|
+
...otherwise === void 0 ? {} : { otherwise: buildList(otherwise, ctx) }
|
|
2800
|
+
};
|
|
2801
|
+
}
|
|
2802
|
+
/** A device command: resolve the target, substitute the args, dispatch one call per device. */
|
|
2803
|
+
async function runCommand(step, scope, ctx) {
|
|
2804
|
+
const { deps, bag } = ctx;
|
|
2805
|
+
require_core_blocks_cap.vocabCall(step.actionId, void 0);
|
|
2806
|
+
const templated = await resolveStepArgsWithTemplates(step.args ?? {}, bag, (name) => deps.onMissingVar(name), deps.renderTemplates);
|
|
2807
|
+
if (templated.notes.length > 0) scope.setTemplateNotes(templated.notes);
|
|
2808
|
+
const args = isPlainRecord$2(templated.value) ? templated.value : {};
|
|
2809
|
+
const target = await deps.resolveTarget(step.target, step.actionId, bag, {
|
|
2810
|
+
actionId: step.actionId,
|
|
2811
|
+
owner: deps.owner
|
|
2812
|
+
});
|
|
2813
|
+
if (target.deviceIds.length === 0) {
|
|
2814
|
+
scope.markEmpty(target.emptyReason ?? "the target matched no device");
|
|
2815
|
+
return;
|
|
2816
|
+
}
|
|
2817
|
+
const call = require_core_blocks_cap.vocabCall(step.actionId, args);
|
|
2818
|
+
scope.setArgs(args);
|
|
2819
|
+
const [only] = target.deviceIds;
|
|
2820
|
+
if (target.deviceIds.length === 1 && only !== void 0) {
|
|
2821
|
+
scope.setDeviceId(only);
|
|
2822
|
+
await deps.invokeCap({
|
|
2823
|
+
deviceId: only,
|
|
2824
|
+
cap: call.cap,
|
|
2825
|
+
method: call.method,
|
|
2826
|
+
args: call.args
|
|
2827
|
+
});
|
|
2828
|
+
return;
|
|
2829
|
+
}
|
|
2830
|
+
await runForDevices(target.deviceIds, scope, (deviceId) => deps.invokeCap({
|
|
2831
|
+
deviceId,
|
|
2832
|
+
cap: call.cap,
|
|
2833
|
+
method: call.method,
|
|
2834
|
+
args: call.args
|
|
2835
|
+
}));
|
|
2836
|
+
}
|
|
2837
|
+
function buildStep(step, ctx, path) {
|
|
2838
|
+
const { deps } = ctx;
|
|
2839
|
+
const env = bodyEnv(ctx);
|
|
2840
|
+
const read = readerOf(ctx);
|
|
2841
|
+
const common = {
|
|
2842
|
+
meta: stepMetaOf(step),
|
|
2843
|
+
...guardOf(step, ctx),
|
|
2844
|
+
...step.enabled === false ? { disabled: true } : {},
|
|
2845
|
+
..."continueOnError" in step && step.continueOnError === true ? { continueOnError: true } : {}
|
|
2846
|
+
};
|
|
2847
|
+
const inside = {
|
|
2848
|
+
...ctx,
|
|
2849
|
+
nested: true
|
|
2850
|
+
};
|
|
2851
|
+
switch (step.kind) {
|
|
2852
|
+
case "wait": return {
|
|
2853
|
+
...common,
|
|
2854
|
+
run: () => deps.sleep(step.seconds * 1e3)
|
|
2855
|
+
};
|
|
2856
|
+
case "command": return {
|
|
2857
|
+
...common,
|
|
2858
|
+
run: (scope) => runCommand(step, scope, ctx)
|
|
2859
|
+
};
|
|
2860
|
+
case "action": {
|
|
2861
|
+
const run = deps.runAction;
|
|
2862
|
+
return {
|
|
2863
|
+
...common,
|
|
2864
|
+
run: async () => {
|
|
2865
|
+
if (run === void 0) throw missing("action", "way to run another action");
|
|
2866
|
+
await runActionBody(step, {
|
|
2867
|
+
...env,
|
|
2868
|
+
run
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
};
|
|
2872
|
+
}
|
|
2873
|
+
case "notify": {
|
|
2874
|
+
const send = deps.sendNotification;
|
|
2875
|
+
return {
|
|
2876
|
+
...common,
|
|
2877
|
+
run: async () => {
|
|
2878
|
+
if (send === void 0) throw missing("notify", "notification sender");
|
|
2879
|
+
await runNotifyBody(step, {
|
|
2880
|
+
...env,
|
|
2881
|
+
send
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
case "probe": {
|
|
2887
|
+
const connect = deps.connect;
|
|
2888
|
+
return {
|
|
2889
|
+
...common,
|
|
2890
|
+
run: async (scope) => {
|
|
2891
|
+
if (connect === void 0) throw missing("probe", "network access");
|
|
2892
|
+
await runProbeBody(step, scope, {
|
|
2893
|
+
...env,
|
|
2894
|
+
connect
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
};
|
|
2898
|
+
}
|
|
2899
|
+
case "http-request": {
|
|
2900
|
+
const fetchFn = deps.fetch;
|
|
2901
|
+
return {
|
|
2902
|
+
...common,
|
|
2903
|
+
run: async (scope) => {
|
|
2904
|
+
if (fetchFn === void 0) throw missing("http-request", "network access");
|
|
2905
|
+
await runHttpBody(step, scope, {
|
|
2906
|
+
...env,
|
|
2907
|
+
fetch: fetchFn
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
2910
|
+
};
|
|
2911
|
+
}
|
|
2912
|
+
case "wait-until": {
|
|
2913
|
+
const poll = deps.waitPollMs ?? 5e3;
|
|
2914
|
+
return {
|
|
2915
|
+
...common,
|
|
2916
|
+
run: (scope) => runWaitUntilBody(step, scope, {
|
|
2917
|
+
...env,
|
|
2918
|
+
read: () => read(step.when),
|
|
2919
|
+
nextWake: (ms) => deps.sleep(Math.min(ms, poll))
|
|
2920
|
+
}, path)
|
|
2921
|
+
};
|
|
2922
|
+
}
|
|
2923
|
+
case "set": return {
|
|
2924
|
+
...common,
|
|
2925
|
+
run: async () => runSetBody(step, env)
|
|
2926
|
+
};
|
|
2927
|
+
case "stop": return {
|
|
2928
|
+
...common,
|
|
2929
|
+
run: async (scope) => {
|
|
2930
|
+
scope.stop(String(env.substitute(step.reason)), step.outcome);
|
|
2931
|
+
}
|
|
2932
|
+
};
|
|
2933
|
+
case "choose": return {
|
|
2934
|
+
...common,
|
|
2935
|
+
run: async () => {},
|
|
2936
|
+
choose: {
|
|
2937
|
+
branches: step.branches.map((branch, at) => ({
|
|
2938
|
+
guard: () => read(branch.if),
|
|
2939
|
+
steps: buildList(branch.steps, inside, `${path}.branches.${at}.steps`)
|
|
2940
|
+
})),
|
|
2941
|
+
...step.else === void 0 ? {} : { otherwise: buildList(step.else, inside, `${path}.else`) }
|
|
2942
|
+
}
|
|
2943
|
+
};
|
|
2944
|
+
case "parallel": return {
|
|
2945
|
+
...common,
|
|
2946
|
+
run: async () => {},
|
|
2947
|
+
parallel: buildList(step.steps, inside, `${path}.steps`)
|
|
2948
|
+
};
|
|
2949
|
+
case "repeat": {
|
|
2950
|
+
const repeatEnv = {
|
|
2951
|
+
...env,
|
|
2952
|
+
read
|
|
2953
|
+
};
|
|
2954
|
+
return {
|
|
2955
|
+
...common,
|
|
2956
|
+
run: async () => {},
|
|
2957
|
+
repeat: {
|
|
2958
|
+
steps: buildList(step.steps, inside, `${path}.steps`),
|
|
2959
|
+
...repeatLoopFields(step.loop, repeatEnv, ctx.nested)
|
|
2960
|
+
}
|
|
2961
|
+
};
|
|
2962
|
+
}
|
|
2963
|
+
default: return assertNever(step);
|
|
2964
|
+
}
|
|
2965
|
+
}
|
|
2966
|
+
function buildList(steps, ctx, path = "steps") {
|
|
2967
|
+
return steps.map((step, at) => buildStep(step, ctx, `${path}.${at}`));
|
|
2968
|
+
}
|
|
2969
|
+
/**
|
|
2970
|
+
* The runnable form of an Action's steps, bound to one run's variables. The
|
|
2971
|
+
* bag is copied: `set`, `probe` and `http-request` write to THIS run's copy.
|
|
2972
|
+
*/
|
|
2973
|
+
function buildActionSteps(steps, vars, deps) {
|
|
2974
|
+
return buildList(steps, {
|
|
2975
|
+
bag: { ...vars },
|
|
2976
|
+
deps,
|
|
2977
|
+
nested: false
|
|
2978
|
+
});
|
|
2979
|
+
}
|
|
2980
|
+
//#endregion
|
|
2981
|
+
//#region ../types/dist/esm/automation/action-graph.mjs
|
|
2982
|
+
function childrenOf(step) {
|
|
2983
|
+
switch (step.kind) {
|
|
2984
|
+
case "wait":
|
|
2985
|
+
case "command": return "else" in step ? step.else ?? [] : [];
|
|
2986
|
+
case "parallel":
|
|
2987
|
+
case "repeat": return step.steps;
|
|
2988
|
+
case "choose": return [...step.branches.flatMap((branch) => branch.steps), ...step.else ?? []];
|
|
2989
|
+
default: return [];
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
/** The ids of the Actions a step list runs, at any depth, each once, in the order they are written. */
|
|
2993
|
+
function actionIdsCalledBy(steps) {
|
|
2994
|
+
const ids = [];
|
|
2995
|
+
const visit = (step) => {
|
|
2996
|
+
if (step.kind === "action" && !ids.includes(step.actionId)) ids.push(step.actionId);
|
|
2997
|
+
for (const child of childrenOf(step)) visit(child);
|
|
2998
|
+
};
|
|
2999
|
+
for (const step of steps) visit(step);
|
|
3000
|
+
return ids;
|
|
3001
|
+
}
|
|
3002
|
+
/**
|
|
3003
|
+
* The cycle a save would close, as the ids along it (`[a, b, a]`), or `null`.
|
|
3004
|
+
* `rootId` is the Action being saved and `rootSteps` the steps it is saved with:
|
|
3005
|
+
* the stored copy of `rootId` is never read, only the new one.
|
|
3006
|
+
*/
|
|
3007
|
+
async function findActionCycle(rootId, rootSteps, stepsOf) {
|
|
3008
|
+
const cleared = /* @__PURE__ */ new Set();
|
|
3009
|
+
const walk = async (id, steps, path) => {
|
|
3010
|
+
for (const called of actionIdsCalledBy(steps)) {
|
|
3011
|
+
if (called === rootId) return [
|
|
3012
|
+
...path,
|
|
3013
|
+
id,
|
|
3014
|
+
called
|
|
3015
|
+
];
|
|
3016
|
+
if (cleared.has(called) || path.includes(called)) continue;
|
|
3017
|
+
const next = await stepsOf(called);
|
|
3018
|
+
if (next === void 0) continue;
|
|
3019
|
+
const found = await walk(called, next, [...path, id]);
|
|
3020
|
+
if (found !== null) return found;
|
|
3021
|
+
cleared.add(called);
|
|
3022
|
+
}
|
|
3023
|
+
return null;
|
|
3024
|
+
};
|
|
3025
|
+
return walk(rootId, rootSteps, []);
|
|
3026
|
+
}
|
|
3027
|
+
var NO_RUN_CHAIN = { ids: [] };
|
|
3028
|
+
/** Why a run may not start under this chain, or `null` when it may. */
|
|
3029
|
+
function refuseRunUnder(chain, actionId) {
|
|
3030
|
+
if (chain.ids.includes(actionId)) return `action cycle: ${[...chain.ids, actionId].join(" -> ")}`;
|
|
3031
|
+
if (chain.ids.length >= 8) return `actions call actions more than 8 deep: ${[...chain.ids, actionId].join(" -> ")}`;
|
|
3032
|
+
return null;
|
|
3033
|
+
}
|
|
3034
|
+
/** The chain of a run of `actionId` started under `chain`. */
|
|
3035
|
+
function chainWith(chain, actionId) {
|
|
3036
|
+
return { ids: [...chain.ids, actionId] };
|
|
3037
|
+
}
|
|
3038
|
+
//#endregion
|
|
2431
3039
|
//#region ../types/dist/esm/automation/prepare-units.mjs
|
|
2432
3040
|
/**
|
|
2433
3041
|
* The save boundary for numbers tied to a quantity (D972), as a pure function
|
|
@@ -2509,6 +3117,68 @@ function prepareRecipeUnits(recipe, resolver) {
|
|
|
2509
3117
|
}
|
|
2510
3118
|
}
|
|
2511
3119
|
//#endregion
|
|
3120
|
+
//#region ../types/dist/esm/automation/export-entities.mjs
|
|
3121
|
+
function errorText$4(err) {
|
|
3122
|
+
return err instanceof Error ? err.message : String(err);
|
|
3123
|
+
}
|
|
3124
|
+
/** Send through one CamStack notification target on behalf of an exporter. */
|
|
3125
|
+
async function sendToExportedTarget(api, log, input) {
|
|
3126
|
+
const { exporter, targetId } = input;
|
|
3127
|
+
const tags = { targetId };
|
|
3128
|
+
try {
|
|
3129
|
+
const { targets, unreadable } = await require_notification_targets.listNotificationTargets(api);
|
|
3130
|
+
const target = targets.find((t) => t.id === targetId);
|
|
3131
|
+
if (target === void 0 && unreadable.length > 0) throw new Error(`notification targets unreadable from ${unreadable.map((u) => u.addonId).join(", ")}`);
|
|
3132
|
+
if (target === void 0) {
|
|
3133
|
+
log.warn(`${exporter}: exported notifier not used — target-gone`, {
|
|
3134
|
+
tags,
|
|
3135
|
+
meta: { reason: "target-gone" }
|
|
3136
|
+
});
|
|
3137
|
+
return {
|
|
3138
|
+
status: "refused",
|
|
3139
|
+
reason: "target-gone"
|
|
3140
|
+
};
|
|
3141
|
+
}
|
|
3142
|
+
if (!target.enabled) {
|
|
3143
|
+
log.warn(`${exporter}: exported notifier not used — target-disabled`, {
|
|
3144
|
+
tags,
|
|
3145
|
+
meta: { reason: "target-disabled" }
|
|
3146
|
+
});
|
|
3147
|
+
return {
|
|
3148
|
+
status: "refused",
|
|
3149
|
+
reason: "target-disabled"
|
|
3150
|
+
};
|
|
3151
|
+
}
|
|
3152
|
+
const result = await api.notificationOutput.send.mutate({
|
|
3153
|
+
targetId,
|
|
3154
|
+
addonId: target.addonId,
|
|
3155
|
+
notification: require_notification_rules_cap.NotificationSchema.parse(input.notification)
|
|
3156
|
+
});
|
|
3157
|
+
if (!result.success) {
|
|
3158
|
+
const message = result.error ?? "send failed";
|
|
3159
|
+
log.warn(`${exporter}: exported notifier send failed`, {
|
|
3160
|
+
tags,
|
|
3161
|
+
meta: { message }
|
|
3162
|
+
});
|
|
3163
|
+
return {
|
|
3164
|
+
status: "failed",
|
|
3165
|
+
message
|
|
3166
|
+
};
|
|
3167
|
+
}
|
|
3168
|
+
return { status: "sent" };
|
|
3169
|
+
} catch (err) {
|
|
3170
|
+
const message = errorText$4(err);
|
|
3171
|
+
log.warn(`${exporter}: exported notifier send failed`, {
|
|
3172
|
+
tags,
|
|
3173
|
+
meta: { message }
|
|
3174
|
+
});
|
|
3175
|
+
return {
|
|
3176
|
+
status: "failed",
|
|
3177
|
+
message
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
//#endregion
|
|
2512
3182
|
//#region ../types/dist/esm/remote/remote-builtin-components.mjs
|
|
2513
3183
|
var btn = (idSuffix, row, col, init) => ({
|
|
2514
3184
|
idSuffix,
|
|
@@ -10760,9 +11430,22 @@ var RunToken = class {
|
|
|
10760
11430
|
this.wakers.add(wake);
|
|
10761
11431
|
});
|
|
10762
11432
|
}
|
|
11433
|
+
children = /* @__PURE__ */ new Set();
|
|
11434
|
+
/**
|
|
11435
|
+
* An Action this run started from an `action` step ends with it: stopping the parent, or its
|
|
11436
|
+
* time limit, stops the child. Returns the unlink to call once the child has ended.
|
|
11437
|
+
*/
|
|
11438
|
+
link(child) {
|
|
11439
|
+
this.children.add(child);
|
|
11440
|
+
if (this.aborted) child.abort();
|
|
11441
|
+
return () => {
|
|
11442
|
+
this.children.delete(child);
|
|
11443
|
+
};
|
|
11444
|
+
}
|
|
10763
11445
|
abort() {
|
|
10764
11446
|
this.aborted = true;
|
|
10765
11447
|
for (const wake of [...this.wakers]) wake();
|
|
11448
|
+
for (const child of [...this.children]) child.abort();
|
|
10766
11449
|
}
|
|
10767
11450
|
};
|
|
10768
11451
|
function errorMessage$2(err) {
|
|
@@ -10784,6 +11467,7 @@ var ActionsService = class {
|
|
|
10784
11467
|
targets;
|
|
10785
11468
|
templates;
|
|
10786
11469
|
conditions;
|
|
11470
|
+
effects;
|
|
10787
11471
|
running = /* @__PURE__ */ new Map();
|
|
10788
11472
|
/** Last run START per action — the throttle's memory. */
|
|
10789
11473
|
lastStartedAt = /* @__PURE__ */ new Map();
|
|
@@ -10806,6 +11490,7 @@ var ActionsService = class {
|
|
|
10806
11490
|
this.targets = new require_core_blocks_cap.ActionTargetResolver(deps.directory, deps.logger);
|
|
10807
11491
|
this.templates = deps.templates;
|
|
10808
11492
|
this.conditions = deps.conditions;
|
|
11493
|
+
this.effects = deps.effects;
|
|
10809
11494
|
}
|
|
10810
11495
|
/** A device was added, removed, moved or re-bound: forget the cached domains. */
|
|
10811
11496
|
invalidateTargets() {
|
|
@@ -10904,7 +11589,26 @@ var ActionsService = class {
|
|
|
10904
11589
|
});
|
|
10905
11590
|
throw new require_rename_composition_block.ActionError("template-scope", reason);
|
|
10906
11591
|
}
|
|
10907
|
-
|
|
11592
|
+
run(input) {
|
|
11593
|
+
return this.runUnder(input, NO_RUN_CHAIN);
|
|
11594
|
+
}
|
|
11595
|
+
/**
|
|
11596
|
+
* One run, under the chain of Actions that started it (an `action` step runs
|
|
11597
|
+
* an Action from inside a run): an Action already in the chain, or a chain
|
|
11598
|
+
* past the depth bound, is refused — logged with the action id, never hung.
|
|
11599
|
+
*/
|
|
11600
|
+
async runUnder(input, chain, parent) {
|
|
11601
|
+
const refusal = refuseRunUnder(chain, input.actionId);
|
|
11602
|
+
if (refusal !== null) {
|
|
11603
|
+
this.logger.warn(`action run refused — ${refusal}`, {
|
|
11604
|
+
...input.deviceId === void 0 ? {} : { tags: { deviceId: input.deviceId } },
|
|
11605
|
+
meta: {
|
|
11606
|
+
actionId: input.actionId,
|
|
11607
|
+
chain: chain.ids
|
|
11608
|
+
}
|
|
11609
|
+
});
|
|
11610
|
+
throw new require_rename_composition_block.ActionError("cycle", refusal);
|
|
11611
|
+
}
|
|
10908
11612
|
await this.authorize(input.caller, input.actionId, input.deviceId, "run");
|
|
10909
11613
|
const entry = await this.find(input.actionId);
|
|
10910
11614
|
if (entry === null) throw new require_rename_composition_block.ActionError("not-found", `no action "${input.actionId}"`);
|
|
@@ -10973,6 +11677,7 @@ var ActionsService = class {
|
|
|
10973
11677
|
}
|
|
10974
11678
|
this.lastStartedAt.set(entry.id, startedAt);
|
|
10975
11679
|
const token = new RunToken();
|
|
11680
|
+
const unlink = parent === void 0 ? void 0 : parent.link(token);
|
|
10976
11681
|
this.running.set(entry.id, {
|
|
10977
11682
|
runId,
|
|
10978
11683
|
token,
|
|
@@ -10986,7 +11691,8 @@ var ActionsService = class {
|
|
|
10986
11691
|
lastRunAt: startedAt,
|
|
10987
11692
|
lastError: null
|
|
10988
11693
|
});
|
|
10989
|
-
const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token, readable);
|
|
11694
|
+
const done = this.execute(entry, resolved.values, runId, startedAt, trigger, token, readable, chainWith(chain, entry.id), input);
|
|
11695
|
+
if (unlink !== void 0) done.finally(unlink);
|
|
10990
11696
|
if (input.wait === true) return done;
|
|
10991
11697
|
return {
|
|
10992
11698
|
runId,
|
|
@@ -11021,13 +11727,13 @@ var ActionsService = class {
|
|
|
11021
11727
|
};
|
|
11022
11728
|
}
|
|
11023
11729
|
/** Never rejects: a run's failure is its outcome. */
|
|
11024
|
-
async execute(entry, values, runId, startedAt, trigger, token, readable) {
|
|
11730
|
+
async execute(entry, values, runId, startedAt, trigger, token, readable, chain, started) {
|
|
11025
11731
|
let outcome = "failed";
|
|
11026
11732
|
let steps = [];
|
|
11027
11733
|
let message;
|
|
11028
11734
|
const deadline = this.armDeadline(entry.id, runId, token);
|
|
11029
11735
|
try {
|
|
11030
|
-
const running = runSteps(this.runnableFor(entry, values, token, runId, readable), {
|
|
11736
|
+
const running = runSteps(this.runnableFor(entry, values, token, runId, readable, chain, started), {
|
|
11031
11737
|
pathPrefix: "steps",
|
|
11032
11738
|
isAborted: () => token.aborted,
|
|
11033
11739
|
abortReason: "the run was stopped",
|
|
@@ -11143,7 +11849,7 @@ var ActionsService = class {
|
|
|
11143
11849
|
}
|
|
11144
11850
|
};
|
|
11145
11851
|
}
|
|
11146
|
-
runnableFor(entry, values, token, runId, readable) {
|
|
11852
|
+
runnableFor(entry, values, token, runId, readable, chain, started) {
|
|
11147
11853
|
if (entry.source === "internal") {
|
|
11148
11854
|
const ruleFire = require_command_origin_claim.ruleFireOfClaim(require_cap_call_scope.readCurrentCommandOrigin());
|
|
11149
11855
|
return buildActionSteps(entry.steps ?? [], values, {
|
|
@@ -11164,7 +11870,30 @@ var ActionsService = class {
|
|
|
11164
11870
|
onMissingVar: (name) => this.logger.warn("action template referenced a variable that was never set", { meta: {
|
|
11165
11871
|
actionId: entry.id,
|
|
11166
11872
|
variable: name
|
|
11167
|
-
} })
|
|
11873
|
+
} }),
|
|
11874
|
+
now: this.now,
|
|
11875
|
+
isAborted: () => token.aborted,
|
|
11876
|
+
info: (message, meta) => this.logger.info(message, { meta: {
|
|
11877
|
+
actionId: entry.id,
|
|
11878
|
+
runId,
|
|
11879
|
+
...meta
|
|
11880
|
+
} }),
|
|
11881
|
+
runAction: async ({ actionId, variables }) => {
|
|
11882
|
+
const result = await this.runUnder({
|
|
11883
|
+
caller: started.caller,
|
|
11884
|
+
actionId,
|
|
11885
|
+
variables,
|
|
11886
|
+
wait: true,
|
|
11887
|
+
...started.deviceId === void 0 ? {} : { deviceId: started.deviceId }
|
|
11888
|
+
}, chain, token);
|
|
11889
|
+
return {
|
|
11890
|
+
outcome: result.outcome,
|
|
11891
|
+
message: result.message
|
|
11892
|
+
};
|
|
11893
|
+
},
|
|
11894
|
+
...this.effects?.fetch === void 0 ? {} : { fetch: this.effects.fetch },
|
|
11895
|
+
...this.effects?.connect === void 0 ? {} : { connect: this.effects.connect },
|
|
11896
|
+
...this.effects?.sendNotification === void 0 ? {} : { sendNotification: this.effects.sendNotification }
|
|
11168
11897
|
});
|
|
11169
11898
|
}
|
|
11170
11899
|
return [{
|
|
@@ -11228,6 +11957,7 @@ var ActionsService = class {
|
|
|
11228
11957
|
if (patch.steps !== void 0) this.requireWithinCeiling(patch.steps, patch.name ?? existing.name);
|
|
11229
11958
|
if (patch.steps !== void 0) await this.requireOffered(patch.steps, patch.name ?? existing.name);
|
|
11230
11959
|
const { steps, warnings } = this.normalizeSteps(patch.steps ?? existing.steps ?? [], patch.name ?? existing.name);
|
|
11960
|
+
await this.requireNoCycle(input.actionId, steps, patch.name ?? existing.name);
|
|
11231
11961
|
const action = await this.store.update(input.actionId, {
|
|
11232
11962
|
name: patch.name ?? existing.name,
|
|
11233
11963
|
steps,
|
|
@@ -11282,6 +12012,18 @@ var ActionsService = class {
|
|
|
11282
12012
|
throw err;
|
|
11283
12013
|
}
|
|
11284
12014
|
}
|
|
12015
|
+
/** An Action that would run itself, directly or through others, is refused at save and names the cycle. */
|
|
12016
|
+
async requireNoCycle(actionId, steps, actionName) {
|
|
12017
|
+
const cycle = await findActionCycle(actionId, steps, async (id) => require_rename_composition_block.isInternalActionId(id) ? (await this.store.get(id))?.steps : void 0);
|
|
12018
|
+
if (cycle === null) return;
|
|
12019
|
+
const message = `action cycle: ${cycle.join(" -> ")}`;
|
|
12020
|
+
this.logger.warn("action save refused — it would run itself", { meta: {
|
|
12021
|
+
action: actionName,
|
|
12022
|
+
actionId,
|
|
12023
|
+
cycle
|
|
12024
|
+
} });
|
|
12025
|
+
throw new require_rename_composition_block.ActionError("cycle", message);
|
|
12026
|
+
}
|
|
11285
12027
|
/** An action whose waits alone exceed the run ceiling could never finish: refuse the save. */
|
|
11286
12028
|
requireWithinCeiling(steps, actionName) {
|
|
11287
12029
|
const total = require_rename_composition_block.actionWaitTotalMs(steps);
|
|
@@ -11563,6 +12305,23 @@ function withCanonicalStepTargets(data) {
|
|
|
11563
12305
|
};
|
|
11564
12306
|
}
|
|
11565
12307
|
//#endregion
|
|
12308
|
+
//#region src/builtins/core-blocks/tcp-connect.ts
|
|
12309
|
+
/** Open a TCP connection and close it again: resolves when the port answered, rejects with the reason. */
|
|
12310
|
+
var tcpConnect = (host, port, timeoutMs) => new Promise((resolve, reject) => {
|
|
12311
|
+
const socket = node_net.connect({
|
|
12312
|
+
host,
|
|
12313
|
+
port
|
|
12314
|
+
});
|
|
12315
|
+
const done = (err) => {
|
|
12316
|
+
socket.destroy();
|
|
12317
|
+
if (err === void 0) resolve();
|
|
12318
|
+
else reject(err);
|
|
12319
|
+
};
|
|
12320
|
+
socket.setTimeout(timeoutMs, () => done(/* @__PURE__ */ new Error(`timed out after ${timeoutMs / 1e3} s`)));
|
|
12321
|
+
socket.once("connect", () => done());
|
|
12322
|
+
socket.once("error", (err) => done(err));
|
|
12323
|
+
});
|
|
12324
|
+
//#endregion
|
|
11566
12325
|
//#region src/builtins/core-blocks/runs-api.ts
|
|
11567
12326
|
/**
|
|
11568
12327
|
* The three `core-blocks` methods that front the runs ledger.
|
|
@@ -11734,6 +12493,25 @@ function buildActionsRuntime(deps) {
|
|
|
11734
12493
|
invokeCap: invokeCapOver(deps.api),
|
|
11735
12494
|
templates: templateDoorOver(deps.api),
|
|
11736
12495
|
conditions: conditionDoorOver(deps.api),
|
|
12496
|
+
effects: {
|
|
12497
|
+
fetch: globalThis.fetch,
|
|
12498
|
+
connect: tcpConnect,
|
|
12499
|
+
sendNotification: async ({ targetId, title, body }) => {
|
|
12500
|
+
const current = deps.api();
|
|
12501
|
+
if (current === void 0) return {
|
|
12502
|
+
status: "failed",
|
|
12503
|
+
message: "no ctx.api on this node — the notification cannot be sent"
|
|
12504
|
+
};
|
|
12505
|
+
return sendToExportedTarget(current, deps.logger.child("actions"), {
|
|
12506
|
+
exporter: "actions",
|
|
12507
|
+
targetId,
|
|
12508
|
+
notification: {
|
|
12509
|
+
body,
|
|
12510
|
+
...title === void 0 ? {} : { title }
|
|
12511
|
+
}
|
|
12512
|
+
});
|
|
12513
|
+
}
|
|
12514
|
+
},
|
|
11737
12515
|
emit: (event) => deps.eventBus.emit({
|
|
11738
12516
|
id: (0, node_crypto.randomUUID)(),
|
|
11739
12517
|
timestamp: /* @__PURE__ */ new Date(),
|