@devicerail/yaml-adapter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 DeviceRail contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # `@devicerail/yaml-adapter`
2
+
3
+ Optional DR-045 compatibility adapter. It parses a deliberately bounded,
4
+ JSON-shaped YAML plan and compiles it into sequential calls on an already
5
+ owned, already-negotiated `@devicerail/client` instance.
6
+
7
+ The adapter is not a workflow engine. It has no Driver, daemon, Rust, AI,
8
+ prompt, retry, branching, interpolation, or filesystem authority. YAML never
9
+ enters the DeviceRail kernel.
10
+
11
+ ```yaml
12
+ version: devicerail/v1
13
+ steps:
14
+ - id: select
15
+ method: device.select
16
+ params:
17
+ deviceId: android-emulator-5554
18
+ - id: connect
19
+ method: device.connect
20
+ params: {}
21
+ - id: tap
22
+ method: device.execute
23
+ params:
24
+ id: 11111111-1111-4111-8111-111111111111
25
+ name: tap
26
+ arguments: {x: 20, y: 40}
27
+ ```
28
+
29
+ `device.execute` requires a caller-supplied, device-aware action-protection
30
+ classifier and a fixed selected device (from `device.select` or
31
+ `initialDeviceId`). Unknown and protected actions are rejected at compile time.
32
+ Immediately before execution the adapter re-selects that device, verifies the
33
+ connection-local route through `devices.list`, and re-reads
34
+ `device.capabilities`; a missing or newly protected action fails before its
35
+ arguments are sent. The verified `device.execute` call is started in the same
36
+ JavaScript continuation as that final capability check. A client used for YAML
37
+ execution must not be shared with non-adapter calls that can race
38
+ `device.select`. The caller remains responsible for device and Session lifecycle.
39
+
40
+ Within the YAML adapter's closed method allowlist, `timeoutMs` is accepted only
41
+ for these five request-controlled methods: `device.capabilities`, `device.connect`, `device.disconnect`,
42
+ `device.execute`, and `device.observe`. An execution `AbortSignal` is passed only
43
+ to those methods; for all other methods it is observed between sequential steps,
44
+ matching the public client's cancellation contract.
45
+
46
+ Parsing uses the `js-yaml` JSON schema and then applies independent byte,
47
+ depth, node, collection, key, number, duplicate-ID, method, and timeout bounds.
48
+ Custom tags, object aliases/cycles, prototype keys, duplicate YAML keys,
49
+ unknown plan fields, `system.hello`, `events.subscribe`, and direct
50
+ `request.cancel` calls fail closed. Execution also requires the opaque,
51
+ immutable plan returned by `compileYamlPlan` rather than accepting a manually
52
+ constructed lookalike. Trust is tracked in a module-private `WeakSet`, so
53
+ copying symbols or inheriting from a valid plan does not authorize a new plan.
@@ -0,0 +1,2 @@
1
+ export { compileYamlPlan, executeYamlPlan, YAML_PLAN_VERSION, YamlPlanExecutionError, YamlPlanValidationError, } from "./plan.js";
2
+ export type { ActionProtectionContext, ActionProtectionClassifier, CompileYamlPlanOptions, ExecuteYamlPlanOptions, YamlPlan, YamlPlanClient, YamlPlanExecution, YamlPlanMethod, YamlPlanStep, YamlStepExecution, } from "./plan.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { compileYamlPlan, executeYamlPlan, YAML_PLAN_VERSION, YamlPlanExecutionError, YamlPlanValidationError, } from "./plan.js";
package/dist/plan.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { DeviceRailClient } from "@devicerail/client";
2
+ export declare const YAML_PLAN_VERSION = "devicerail/v1";
3
+ declare const PLAN_METHODS: readonly ["device.capabilities", "device.connect", "device.disconnect", "device.execute", "device.observe", "device.select", "devices.list", "events.clear", "events.list", "events.stream.open", "session.current", "session.end", "session.export", "session.start", "sessions.list", "system.describe"];
4
+ export type YamlPlanMethod = (typeof PLAN_METHODS)[number];
5
+ export interface ActionProtectionContext {
6
+ readonly actionName: string;
7
+ readonly deviceId: string;
8
+ }
9
+ export type ActionProtectionClassifier = (context: ActionProtectionContext) => "protected" | "standard" | undefined;
10
+ export interface CompileYamlPlanOptions {
11
+ /**
12
+ * Required for every `device.execute` step. Unknown and protected actions
13
+ * are rejected so secrets cannot be persisted in a YAML plan by accident.
14
+ */
15
+ readonly classifyActionProtection?: ActionProtectionClassifier;
16
+ /** Device selected before the first YAML step when the plan does not select one itself. */
17
+ readonly initialDeviceId?: string;
18
+ }
19
+ export interface YamlPlanStep {
20
+ readonly id: string;
21
+ readonly method: YamlPlanMethod;
22
+ readonly params?: Readonly<Record<string, unknown>>;
23
+ readonly timeoutMs?: number;
24
+ /** Host-derived route binding; never read from YAML or sent as action params. */
25
+ readonly boundDeviceId?: string;
26
+ }
27
+ export interface YamlPlan {
28
+ readonly steps: readonly YamlPlanStep[];
29
+ readonly version: typeof YAML_PLAN_VERSION;
30
+ }
31
+ export type YamlPlanClient = Pick<DeviceRailClient, "call">;
32
+ export interface ExecuteYamlPlanOptions {
33
+ readonly signal?: AbortSignal;
34
+ }
35
+ export interface YamlStepExecution {
36
+ readonly id: string;
37
+ readonly method: YamlPlanMethod;
38
+ readonly result: unknown;
39
+ }
40
+ export interface YamlPlanExecution {
41
+ readonly steps: readonly YamlStepExecution[];
42
+ }
43
+ export declare class YamlPlanValidationError extends Error {
44
+ readonly code: string;
45
+ readonly path: string;
46
+ constructor(code: string, path: string, message: string);
47
+ }
48
+ export declare class YamlPlanExecutionError extends Error {
49
+ readonly stepId: string;
50
+ readonly method: YamlPlanMethod;
51
+ readonly cause: unknown;
52
+ constructor(step: YamlPlanStep, cause: unknown);
53
+ }
54
+ export declare function compileYamlPlan(source: string, options?: CompileYamlPlanOptions): YamlPlan;
55
+ export declare function executeYamlPlan(client: YamlPlanClient, plan: YamlPlan, options?: ExecuteYamlPlanOptions): Promise<YamlPlanExecution>;
56
+ export {};
package/dist/plan.js ADDED
@@ -0,0 +1,350 @@
1
+ import { JSON_SCHEMA, load } from "js-yaml";
2
+ export const YAML_PLAN_VERSION = "devicerail/v1";
3
+ const MAX_SOURCE_BYTES = 256 * 1024;
4
+ const MAX_STEPS = 256;
5
+ const MAX_DEPTH = 16;
6
+ const MAX_NODES = 4_096;
7
+ const MAX_COLLECTION_ITEMS = 512;
8
+ const MAX_OBJECT_PROPERTIES = 256;
9
+ const MAX_STRING_BYTES = 64 * 1024;
10
+ const MAX_KEY_BYTES = 256;
11
+ const MAX_TIMEOUT_MS = 24 * 60 * 60 * 1_000;
12
+ const STEP_ID = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/u;
13
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
14
+ const TRUSTED_PLANS = new WeakSet();
15
+ const ACTIVE_CLIENTS = new WeakSet();
16
+ const PLAN_METHODS = [
17
+ "device.capabilities",
18
+ "device.connect",
19
+ "device.disconnect",
20
+ "device.execute",
21
+ "device.observe",
22
+ "device.select",
23
+ "devices.list",
24
+ "events.clear",
25
+ "events.list",
26
+ "events.stream.open",
27
+ "session.current",
28
+ "session.end",
29
+ "session.export",
30
+ "session.start",
31
+ "sessions.list",
32
+ "system.describe",
33
+ ];
34
+ const PLAN_METHOD_SET = new Set(PLAN_METHODS);
35
+ const CANCELLABLE_METHOD_SET = new Set([
36
+ "device.capabilities",
37
+ "device.connect",
38
+ "device.disconnect",
39
+ "device.execute",
40
+ "device.observe",
41
+ ]);
42
+ export class YamlPlanValidationError extends Error {
43
+ code;
44
+ path;
45
+ constructor(code, path, message) {
46
+ super(message);
47
+ this.name = "YamlPlanValidationError";
48
+ this.code = code;
49
+ this.path = path;
50
+ }
51
+ }
52
+ export class YamlPlanExecutionError extends Error {
53
+ stepId;
54
+ method;
55
+ cause;
56
+ constructor(step, cause) {
57
+ super(`YAML plan step ${step.id} failed`);
58
+ this.name = "YamlPlanExecutionError";
59
+ this.stepId = step.id;
60
+ this.method = step.method;
61
+ this.cause = cause;
62
+ }
63
+ }
64
+ function fail(code, path, message) {
65
+ throw new YamlPlanValidationError(code, path, message);
66
+ }
67
+ function isObject(value) {
68
+ return typeof value === "object" && value !== null && !Array.isArray(value);
69
+ }
70
+ function cloneBoundedJson(value, path, depth, budget) {
71
+ budget.nodes += 1;
72
+ if (budget.nodes > MAX_NODES) {
73
+ fail("yaml_node_limit", path, "YAML plan exceeds the node limit");
74
+ }
75
+ if (depth > MAX_DEPTH) {
76
+ fail("yaml_depth_limit", path, "YAML plan exceeds the nesting limit");
77
+ }
78
+ if (value === null || typeof value === "boolean") {
79
+ return value;
80
+ }
81
+ if (typeof value === "string") {
82
+ if (Buffer.byteLength(value, "utf8") > MAX_STRING_BYTES) {
83
+ fail("yaml_string_limit", path, "YAML string exceeds the byte limit");
84
+ }
85
+ return value;
86
+ }
87
+ if (typeof value === "number") {
88
+ if (!Number.isFinite(value) || !Number.isSafeInteger(value) && value % 1 === 0) {
89
+ fail("yaml_number_invalid", path, "YAML number is not safely representable as JSON");
90
+ }
91
+ return value;
92
+ }
93
+ if (typeof value !== "object") {
94
+ fail("yaml_type_invalid", path, "YAML contains a non-JSON value");
95
+ }
96
+ if (budget.seen.has(value)) {
97
+ fail("yaml_alias_forbidden", path, "YAML aliases and cyclic objects are not supported");
98
+ }
99
+ budget.seen.add(value);
100
+ if (Array.isArray(value)) {
101
+ if (value.length > MAX_COLLECTION_ITEMS) {
102
+ fail("yaml_collection_limit", path, "YAML sequence exceeds the item limit");
103
+ }
104
+ return Object.freeze(value.map((entry, index) => cloneBoundedJson(entry, `${path}[${index}]`, depth + 1, budget)));
105
+ }
106
+ const entries = Object.entries(value);
107
+ if (entries.length > MAX_OBJECT_PROPERTIES) {
108
+ fail("yaml_object_limit", path, "YAML mapping exceeds the property limit");
109
+ }
110
+ const clone = {};
111
+ for (const [key, entry] of entries) {
112
+ if (FORBIDDEN_KEYS.has(key)) {
113
+ fail("yaml_key_forbidden", `${path}.${key}`, "YAML mapping contains a forbidden key");
114
+ }
115
+ if (Buffer.byteLength(key, "utf8") > MAX_KEY_BYTES) {
116
+ fail("yaml_key_limit", path, "YAML mapping key exceeds the byte limit");
117
+ }
118
+ clone[key] = cloneBoundedJson(entry, `${path}.${key}`, depth + 1, budget);
119
+ }
120
+ return Object.freeze(clone);
121
+ }
122
+ function exactKeys(value, allowed, path) {
123
+ for (const key of Object.keys(value)) {
124
+ if (!allowed.has(key)) {
125
+ fail("yaml_unknown_field", `${path}.${key}`, "YAML plan contains an unknown field");
126
+ }
127
+ }
128
+ }
129
+ function positiveTimeout(value, path) {
130
+ if (value === undefined) {
131
+ return undefined;
132
+ }
133
+ if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMEOUT_MS) {
134
+ fail("yaml_timeout_invalid", path, "timeoutMs must be a positive bounded safe integer");
135
+ }
136
+ return value;
137
+ }
138
+ function requestOptions(method, timeoutMs, signal) {
139
+ if (!CANCELLABLE_METHOD_SET.has(method)) {
140
+ return undefined;
141
+ }
142
+ if (timeoutMs === undefined && signal === undefined) {
143
+ return undefined;
144
+ }
145
+ return {
146
+ ...(signal === undefined ? {} : { signal }),
147
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
148
+ };
149
+ }
150
+ function throwAbortCauseIfNeeded(signal) {
151
+ if (signal?.aborted) {
152
+ throw signal.reason;
153
+ }
154
+ }
155
+ function requireStandardAction(params, options, path, deviceId) {
156
+ const name = params?.name;
157
+ if (typeof name !== "string" || name.length === 0 || Buffer.byteLength(name, "utf8") > 128) {
158
+ fail("yaml_action_name_invalid", `${path}.params.name`, "device.execute requires a bounded action name");
159
+ }
160
+ if (deviceId === undefined) {
161
+ fail("yaml_action_device_unbound", `${path}.params.name`, "device.execute requires a fixed selected device");
162
+ }
163
+ const protection = options.classifyActionProtection?.({ actionName: name, deviceId });
164
+ if (protection === "protected") {
165
+ fail("yaml_protected_action_forbidden", `${path}.params.name`, "protected actions cannot be persisted in YAML");
166
+ }
167
+ if (protection !== "standard") {
168
+ fail("yaml_action_unknown", `${path}.params.name`, "device.execute action must be confirmed as standard");
169
+ }
170
+ return deviceId;
171
+ }
172
+ function boundedDeviceId(value, path) {
173
+ if (typeof value !== "string" ||
174
+ value.length === 0 ||
175
+ Buffer.byteLength(value, "utf8") > MAX_KEY_BYTES ||
176
+ [...value].some((character) => character <= "\u001f" || character === "\u007f")) {
177
+ fail("yaml_device_id_invalid", path, "selected device id must be a bounded printable string");
178
+ }
179
+ return value;
180
+ }
181
+ export function compileYamlPlan(source, options = {}) {
182
+ if (typeof source !== "string" || Buffer.byteLength(source, "utf8") > MAX_SOURCE_BYTES) {
183
+ fail("yaml_source_limit", "$", "YAML source exceeds the byte limit");
184
+ }
185
+ let decoded;
186
+ try {
187
+ decoded = load(source, {
188
+ filename: "devicerail-plan.yaml",
189
+ json: false,
190
+ maxDepth: MAX_DEPTH + 2,
191
+ maxTotalMergeKeys: 0,
192
+ schema: JSON_SCHEMA,
193
+ });
194
+ }
195
+ catch {
196
+ fail("yaml_parse_failed", "$", "YAML source is not valid safe YAML");
197
+ }
198
+ const cloned = cloneBoundedJson(decoded, "$", 0, { nodes: 0, seen: new WeakSet() });
199
+ if (!isObject(cloned)) {
200
+ fail("yaml_plan_invalid", "$", "YAML plan must be a mapping");
201
+ }
202
+ exactKeys(cloned, new Set(["version", "steps"]), "$");
203
+ if (cloned.version !== YAML_PLAN_VERSION) {
204
+ fail("yaml_version_unsupported", "$.version", "YAML plan version is unsupported");
205
+ }
206
+ if (!Array.isArray(cloned.steps) || cloned.steps.length === 0 || cloned.steps.length > MAX_STEPS) {
207
+ fail("yaml_steps_invalid", "$.steps", "YAML plan must contain a bounded non-empty steps sequence");
208
+ }
209
+ const ids = new Set();
210
+ let selectedDeviceId = options.initialDeviceId === undefined
211
+ ? undefined
212
+ : boundedDeviceId(options.initialDeviceId, "$.initialDeviceId");
213
+ const steps = cloned.steps.map((rawStep, index) => {
214
+ const path = `$.steps[${index}]`;
215
+ if (!isObject(rawStep)) {
216
+ fail("yaml_step_invalid", path, "YAML plan step must be a mapping");
217
+ }
218
+ exactKeys(rawStep, new Set(["id", "method", "params", "timeoutMs"]), path);
219
+ if (typeof rawStep.id !== "string" || !STEP_ID.test(rawStep.id) || ids.has(rawStep.id)) {
220
+ fail("yaml_step_id_invalid", `${path}.id`, "step id must be unique and portable");
221
+ }
222
+ ids.add(rawStep.id);
223
+ if (typeof rawStep.method !== "string" || !PLAN_METHOD_SET.has(rawStep.method)) {
224
+ fail("yaml_method_forbidden", `${path}.method`, "method is not available to YAML plans");
225
+ }
226
+ const method = rawStep.method;
227
+ const params = rawStep.params;
228
+ if (params !== undefined && !isObject(params)) {
229
+ fail("yaml_params_invalid", `${path}.params`, "params must be a JSON mapping");
230
+ }
231
+ if (method === "device.select") {
232
+ if (params === undefined) {
233
+ fail("yaml_device_select_invalid", `${path}.params`, "device.select requires params");
234
+ }
235
+ exactKeys(params, new Set(["deviceId"]), `${path}.params`);
236
+ selectedDeviceId = boundedDeviceId(params.deviceId, `${path}.params.deviceId`);
237
+ }
238
+ let boundDeviceId;
239
+ if (method === "device.execute") {
240
+ boundDeviceId = requireStandardAction(params, options, path, selectedDeviceId);
241
+ }
242
+ const timeoutMs = positiveTimeout(rawStep.timeoutMs, `${path}.timeoutMs`);
243
+ if (timeoutMs !== undefined && !CANCELLABLE_METHOD_SET.has(method)) {
244
+ fail("yaml_timeout_unsupported", `${path}.timeoutMs`, `${method} does not support timeoutMs`);
245
+ }
246
+ return Object.freeze({
247
+ id: rawStep.id,
248
+ method,
249
+ ...(params === undefined ? {} : { params }),
250
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
251
+ ...(boundDeviceId === undefined ? {} : { boundDeviceId }),
252
+ });
253
+ });
254
+ const plan = Object.freeze({
255
+ version: YAML_PLAN_VERSION,
256
+ steps: Object.freeze(steps),
257
+ });
258
+ TRUSTED_PLANS.add(plan);
259
+ return plan;
260
+ }
261
+ function validateTrustedPlan(plan) {
262
+ if (!TRUSTED_PLANS.has(plan)) {
263
+ fail("yaml_plan_untrusted", "$", "YAML plan must be produced by compileYamlPlan");
264
+ }
265
+ if (plan.version !== YAML_PLAN_VERSION ||
266
+ !Object.isFrozen(plan) ||
267
+ !Object.isFrozen(plan.steps) ||
268
+ plan.steps.length === 0 ||
269
+ plan.steps.length > MAX_STEPS) {
270
+ fail("yaml_plan_corrupt", "$", "compiled YAML plan integrity check failed");
271
+ }
272
+ const ids = new Set();
273
+ for (const [index, step] of plan.steps.entries()) {
274
+ const path = `$.steps[${index}]`;
275
+ if (!Object.isFrozen(step) ||
276
+ !STEP_ID.test(step.id) ||
277
+ ids.has(step.id) ||
278
+ !PLAN_METHOD_SET.has(step.method)) {
279
+ fail("yaml_plan_corrupt", path, "compiled YAML plan integrity check failed");
280
+ }
281
+ ids.add(step.id);
282
+ if (step.method === "device.execute" && step.boundDeviceId === undefined) {
283
+ fail("yaml_plan_corrupt", path, "compiled action route binding is missing");
284
+ }
285
+ }
286
+ }
287
+ function actionName(step) {
288
+ const name = step.params?.name;
289
+ if (typeof name !== "string") {
290
+ fail("yaml_plan_corrupt", `$.steps.${step.id}`, "compiled action name is missing");
291
+ }
292
+ return name;
293
+ }
294
+ async function executeVerifiedAction(call, step, signal) {
295
+ const deviceId = step.boundDeviceId;
296
+ if (deviceId === undefined) {
297
+ fail("yaml_plan_corrupt", `$.steps.${step.id}`, "compiled action route binding is missing");
298
+ }
299
+ // Re-select and then re-read the public capability immediately before the
300
+ // action. This catches route drift and a standard -> protected transition.
301
+ await call("device.select", { deviceId });
302
+ throwAbortCauseIfNeeded(signal);
303
+ const inventory = await call("devices.list");
304
+ if (!isObject(inventory) || inventory.selectedDeviceId !== deviceId) {
305
+ fail("yaml_action_route_changed", `$.steps.${step.id}`, "selected device route changed");
306
+ }
307
+ throwAbortCauseIfNeeded(signal);
308
+ const capabilities = await call("device.capabilities", undefined, requestOptions("device.capabilities", step.timeoutMs, signal));
309
+ const name = actionName(step);
310
+ const definition = Array.isArray(capabilities)
311
+ ? capabilities.find((candidate) => isObject(candidate) && candidate.name === name)
312
+ : undefined;
313
+ if (!isObject(definition) || (definition.protection ?? "standard") !== "standard") {
314
+ fail("yaml_action_runtime_forbidden", `$.steps.${step.id}`, "action is missing or protected on the selected device");
315
+ }
316
+ throwAbortCauseIfNeeded(signal);
317
+ // Start the action in this same continuation. Returning to executeYamlPlan
318
+ // here would introduce a microtask window in which another caller could
319
+ // change the connection-local route after the capability check.
320
+ return await call("device.execute", step.params, requestOptions("device.execute", step.timeoutMs, signal));
321
+ }
322
+ export async function executeYamlPlan(client, plan, options = {}) {
323
+ validateTrustedPlan(plan);
324
+ if (ACTIVE_CLIENTS.has(client)) {
325
+ fail("yaml_client_busy", "$", "this client is already executing a YAML plan");
326
+ }
327
+ ACTIVE_CLIENTS.add(client);
328
+ const completed = [];
329
+ try {
330
+ const call = client.call.bind(client);
331
+ for (const step of plan.steps) {
332
+ if (options.signal?.aborted) {
333
+ throw new YamlPlanExecutionError(step, options.signal.reason);
334
+ }
335
+ try {
336
+ const result = step.method === "device.execute"
337
+ ? await executeVerifiedAction(call, step, options.signal)
338
+ : await call(step.method, step.params, requestOptions(step.method, step.timeoutMs, options.signal));
339
+ completed.push(Object.freeze({ id: step.id, method: step.method, result }));
340
+ }
341
+ catch (cause) {
342
+ throw new YamlPlanExecutionError(step, cause);
343
+ }
344
+ }
345
+ return Object.freeze({ steps: Object.freeze(completed) });
346
+ }
347
+ finally {
348
+ ACTIVE_CLIENTS.delete(client);
349
+ }
350
+ }
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@devicerail/yaml-adapter",
3
+ "version": "0.1.0",
4
+ "description": "Optional bounded YAML plan adapter for DeviceRail public RPC calls",
5
+ "license": "Apache-2.0",
6
+ "keywords": [
7
+ "device-automation",
8
+ "test-automation",
9
+ "yaml",
10
+ "workflow"
11
+ ],
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=22"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org/"
19
+ },
20
+ "main": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md"
31
+ ],
32
+ "dependencies": {
33
+ "js-yaml": "5.2.1",
34
+ "@devicerail/client": "0.1.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "26.1.1",
38
+ "typescript": "7.0.2"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/wangweiwei/device-rail.git",
43
+ "directory": "packages/yaml-adapter"
44
+ },
45
+ "homepage": "https://github.com/wangweiwei/device-rail#readme",
46
+ "bugs": {
47
+ "url": "https://github.com/wangweiwei/device-rail/issues"
48
+ },
49
+ "scripts": {
50
+ "typecheck": "tsc -p tsconfig.json --noEmit",
51
+ "build": "node scripts/clean.mjs dist && tsc -p tsconfig.build.json && tsc -p tsconfig.package-exports.json && node scripts/check-package-exports.mjs",
52
+ "test": "node scripts/clean.mjs .test-dist && tsc -p tsconfig.test.json && node scripts/run-tests.mjs"
53
+ }
54
+ }