@burdenoff/ui-engine 0.0.0-stage → 2026.1127.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +97 -2
  3. package/dist/capture.d.ts +118 -0
  4. package/dist/capture.js +14 -0
  5. package/dist/index-3v887c75.js +52 -0
  6. package/dist/index-c6pmt2rg.js +213 -0
  7. package/dist/index-n5amgh31.js +210 -0
  8. package/dist/index-phd8yhyg.js +224 -0
  9. package/dist/index-tqffkt91.js +1986 -0
  10. package/dist/index.d.ts +11 -0
  11. package/dist/index.js +234 -0
  12. package/dist/recording.d.ts +214 -0
  13. package/dist/recording.js +28 -0
  14. package/dist/redact-credentials.d.ts +39 -0
  15. package/dist/replay.d.ts +144 -0
  16. package/dist/replay.js +20 -0
  17. package/dist/resolve.d.ts +43 -0
  18. package/dist/resolve.js +10 -0
  19. package/dist/script/adapters/browser-action-contract.d.ts +22 -0
  20. package/dist/script/adapters/from-browser-action.d.ts +7 -0
  21. package/dist/script/adapters/from-remote-browser.d.ts +7 -0
  22. package/dist/script/adapters/recording.d.ts +25 -0
  23. package/dist/script/adapters/to-browser-action.d.ts +8 -0
  24. package/dist/script/canonical.d.ts +6 -0
  25. package/dist/script/capabilities.d.ts +29 -0
  26. package/dist/script/describe.d.ts +83 -0
  27. package/dist/script/fingerprint.d.ts +9 -0
  28. package/dist/script/hash.d.ts +3 -0
  29. package/dist/script/index.d.ts +22 -0
  30. package/dist/script/json-schema.d.ts +4 -0
  31. package/dist/script/limits.d.ts +61 -0
  32. package/dist/script/parse.d.ts +31 -0
  33. package/dist/script/schema.d.ts +87 -0
  34. package/dist/script/types.d.ts +489 -0
  35. package/dist/script/walk.d.ts +29 -0
  36. package/dist/script.d.ts +2 -0
  37. package/dist/script.js +175 -0
  38. package/package.json +101 -4
  39. package/schema/ui-script-v1.schema.json +8199 -0
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
4
+ Algoshred Technologies Private Limited,
5
+ and all its sister companies.
6
+
7
+ Maintainer: Vignesh T.V <https://github.com/tvvignesh>
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is furnished
14
+ to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # @burdenoff/ui-engine
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The shared, browser-safe UI automation engine behind FluidGrids RPA ("Use Browser") and BotManor Stewards teach mode. It holds the recorded-step format, capture-time masking, target resolution and the replay planner, and it runs unchanged in a browser extension (MV3), a bundled web app, Bun and Node.
4
+
5
+ FluidGrids owns this package; changes that touch the recording format, masking or fingerprints also need a Stewards reviewer.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add @burdenoff/ui-engine zod
11
+ ```
12
+
13
+ `zod` (`^4.6.6`) is a peer dependency, so an app that already uses zod 4 ships a single copy. The only runtime dependency is `@noble/hashes` (pure JavaScript sha256).
14
+
15
+ ## Modules
16
+
17
+ Each module is a subpath export, and the root entry re-exports all of them.
18
+
19
+ | Import | What it holds |
20
+ |---|---|
21
+ | `@burdenoff/ui-engine/recording` | Recording v1 schema (`recordingSchema`, `recordedStepSchema`, `recordedTargetSchema`), `targetFingerprint`, `parseRecording`, `RecordingError`, `sha256Hex` |
22
+ | `@burdenoff/ui-engine/capture` | `captureRecording` (turns recorder events into a masked recording), `maskUrl`, `redactCredentials`, `REDACTED` |
23
+ | `@burdenoff/ui-engine/resolve` | `readSnapshotNodes` (array, `{ nodes }` or `{ elements }` snapshots), `resolveTarget` (exact role and label match, `nth` among equals) |
24
+ | `@burdenoff/ui-engine/replay` | The pure replay planner: `replayStateFrom`, `planReplay`, `afterReplayCall`, `finishFallback`, `markFallbackAsked`, `replayReasons`, `readReplayState` |
25
+ | `@burdenoff/ui-engine/script` | UI script v1: types, `uiScriptSchema`, `parseUiScript`, `UI_SCRIPT_SCHEMA_HASH`, `requiredCapabilities`, the adapters and `describeStep` (see below) |
26
+ | `@burdenoff/ui-engine/schema/ui-script-v1.schema.json` | The JSON Schema (draft 2020-12) of UI script v1 |
27
+
28
+ ## UI script v1
29
+
30
+ A UI script is the portable form of a UI sequence that a desk runs: a paired browser (the FluidGrids extension), a remote browser driven over CDP by the workers, and later a robot. It is the contract FluidGrids RPA builds on (spec `fluidgrids-specs/product/specs/rpa/03-ARCHITECTURE.md` section 5 and `05-UI_AUTOMATION.md`; plan package P0-04, BOFF-17115).
31
+
32
+ **Shape.** `{ scriptVersion: 1, name?, application?, settings?, inputs?, outputs?, variables?, elements?, steps, cleanup? }`.
33
+
34
+ - A **target** is an ordered list of methods: `role` (accessible role and name, the n-th match; a superset of the Stewards saved-step target), `css`, `testId`, `xpath`, `fuzzy`, `anchor` and `text`, each with an on or off switch, plus an optional frame and shadow-root chain. A step names an inline target or a pinned library element (`{ element: key }`).
35
+ - **Steps** carry an `id` (unique across the script), an action and its fields, and the common options: `intent`, `note`, `saveAs`, `disabled`, `breakpoint`, `timeoutMs`, `retry`, `onError`, `verify`, `screenshot`, `inputMethod`, `safeToRepeat`, `screenshotRef` and `fingerprint`.
36
+ - **Actions.** Web: `navigate`, `goBack`, `reload`, `closeTab`, `click`, `doubleClick`, `hover`, `type`, `typeSecret`, `clear`, `select`, `check`, `pressKey`, `scroll`, `waitFor`, `extract`, `extractList`, `getText`, `getValue`, `getAttribute`, `elementExists`, `getPageText`, `getPageHtml`, `screenshot`, `login`. Desktop (from Stewards recordings): `focusWindow`. Flow: `if`, `forEach`, `while` (a limit is mandatory), `retryScope`, `set`, `log`, `call` (a shared sequence pinned by version; inlined when the worker compiles the script).
37
+ - **Expressions** are JSON trees, never text to evaluate: literals, `{ input }`, `{ var }` (each with an optional `path`), `{ list }`, `{ object }` and `{ op, args }` over a fixed operator list (`UI_EXPRESSION_OPS`, arities in `UI_EXPRESSION_ARITY`).
38
+ - **Secrets** never appear in a script: `typeSecret` holds a reference, and `parseUiScript` refuses credential-shaped text in values, intents, notes, URLs, target texts and selectors, window names, element names and script descriptions.
39
+ - **Fingerprints** cover every target a step holds. A step a Stewards saved step can express is fingerprinted exactly as Stewards does.
40
+ - Optional fields have no zod defaults, so a parsed script is exactly the stored one; each type documents the default an interpreter applies.
41
+
42
+ **Limits** (`limits.ts`): 500 steps including nested and clean-up steps, 1 MiB serialised, flow blocks 8 deep, expressions 16 deep, 8 methods per target, 500 pinned elements, 100 inputs, outputs and variables each.
43
+
44
+ **Parsing.** `parseUiScript(value, { resolved? })` accepts an object or its JSON text and throws `UiScriptError` with a `code` (`INVALID_SCRIPT`, `SCRIPT_TOO_LARGE`, `TOO_MANY_STEPS`, `DUPLICATE_STEP_ID`, `UNKNOWN_ELEMENT`, `UNKNOWN_INPUT`, `FINGERPRINT_MISMATCH`, `CREDENTIAL_IN_SCRIPT`, `UNRESOLVED`) and a `path`. `resolved: true` also requires every pinned element to carry its target and every `call` to be inlined. `safeParseUiScript` returns the result instead of throwing.
45
+
46
+ **Schema hash.** `UI_SCRIPT_SCHEMA_HASH` is the SHA-256 of the canonical JSON of `schema/ui-script-v1.schema.json`. The service returns the hashes it accepts, and a worker refuses to park a script whose hash the service does not accept. After changing `src/script/schema.ts`, run `bun run schema:write` and copy the printed hash into `src/script/hash.ts`; a test fails until both match.
47
+
48
+ **Capabilities.** `requiredCapabilities(script)` returns the sorted ids a desk must support (`script:1`, `action:<action>`, `target:<kind>`, `target:frame`, `step:verify`, `step:retry`, `step:breakpoint`, `input:direct`, `input:hardware`); `CAPABILITY_IDS` lists them all and `missingCapabilities(script, supported)` reports the gap.
49
+
50
+ **Adapters.**
51
+
52
+ | Function | From and to | Notes |
53
+ |---|---|---|
54
+ | `fromRecording`, `toRecording` | Stewards saved-step recording v1 | Lossless both ways, fingerprints included; `toRecording` returns null for a script a recording cannot express |
55
+ | `fromBrowserActionSteps` | Run in Browser steps (`internal:browser-action`) | Keeps every field a 0.3.0 extension reads |
56
+ | `toBrowserActionSteps` | Lowering to Run in Browser steps | Null unless the script fits the legacy contract: at most 100 steps and 256 KB, only the 14 legacy actions, one CSS selector per target (or one text for click and wait), literal or supplied input values, no script wait or screenshot settings beyond the defaults, and no flow steps, verification, retries or breakpoints |
57
+ | `fromRemoteBrowserSteps` | Remote Browser `runSteps` (`store/remotebrowser` 1.0.0) | Playwright `css=`, `text=`, `xpath=`, `id=` and `data-testid=` selectors; other engines are refused |
58
+
59
+ **Descriptions.** `describeStep(step, elements)` returns `{ key, vars, fallback }`, with keys under `fluidgrids.uiScript.step.*` for `tr(key, vars)` and an English fallback; `UI_SCRIPT_STEP_MESSAGES` holds every English template.
60
+
61
+ ## Compatibility with Stewards
62
+
63
+ The modules were copied from `wspace-botmanor-svc` `src/modules/stewards/teach/` at commit `6558d8b` (BOFF-16873). The differences are:
64
+
65
+ - sha256 comes from `@noble/hashes` instead of `node:crypto`, with byte-identical output;
66
+ - `canAuthorSavedSteps` stays in Stewards, because it is an access rule of that service;
67
+ - the replay tool-call and chat-message types are local structural copies, and `planReplay`, `afterReplayCall` take optional `ReplayOptions` (tool names and call-id prefix) whose defaults reproduce the Stewards calls exactly;
68
+ - `readSnapshotNodes` also reads the `{ elements }` snapshot that the browser desk returns.
69
+ - `captureRecording` trims labels before taking the fingerprint (the schema trims them on parse, so an untrimmed label used to fail its own fingerprint check), and removes every value it masked from the recording's other text: intents, labels, window titles and plain typed text (a plain typed text that contains one becomes a masked step). Values shorter than four characters are not searched for.
70
+
71
+ - A navigation URL that holds a value masked elsewhere in the same demonstration, as written or percent-encoded, loses its query and fragment, or its path when the value is in the path.
72
+ - `maskUrl` also cuts a reset-style link after its reset segment (`/reset/<token>` becomes `/reset`) and drops a path or fragment that holds a recognisable credential. The sensitive values a URL loses (user info, the values of secret-looking parameters, every query value of a reset-style link, and the path segments cut from it) are masked in the rest of the recording too, so a code from a verification link does not survive in an intent or a label.
73
+ - `parseRecording` refuses a recording whose stored text (intent, target labels, typed text, URL, window app and title) still holds a recognisable credential, with `RecordingError` code `CREDENTIAL_IN_RECORDING`. The Stewards copy documented this check but did not perform it.
74
+
75
+ Recordings that capture produces, in either copy, still parse here, and the golden fingerprints are unchanged.
76
+
77
+ `tests/golden/stewards-6558d8b.json` was generated by running the Stewards code itself. The golden tests prove the fingerprints and a captured recording are identical, so a recording saved by either side parses on the other.
78
+
79
+ ## Browser safety
80
+
81
+ Nothing under `src/` may import a Node built-in. ESLint enforces this, `tests/browser-safe.test.ts` checks every source file, and `bun run check:browser-safe` (a `boff sanity` extra step) checks the built `dist/` for Node built-ins and for any bare import other than `zod` and `@noble/hashes`.
82
+
83
+ ## Development
84
+
85
+ ```bash
86
+ bun install
87
+ bun run sanity # format, lint, typecheck, build, tests with the coverage gate, browser-safety check
88
+ bun test # unit tests only
89
+ bun run build # dist/ (ESM, browser target) and .d.ts files
90
+ ```
91
+
92
+ ## Release
93
+
94
+ Every push to `main` publishes the next CalVer version (`YYYY.MDD.PATCH`) to npm through `.github/workflows/release.yml`, which calls the shared `node-lib-release.yml` from `algoshred/ci-workflows`. A pushed CalVer tag publishes exactly that version. Pull requests must pass the `PR Gate` check.
95
+
96
+ ## Licence
97
+
98
+ MIT. See `LICENSE`.
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Teach-mode capture with masking (BOFF-16214, plan 5.7).
3
+ *
4
+ * Copied from wspace-botmanor-svc `src/modules/stewards/teach/capture.ts` at
5
+ * 6558d8b (BOFF-16873). This module also re-exports `redactCredentials` and
6
+ * `REDACTED`. Changes from that file, none of which alters a recording
7
+ * the Stewards copy accepts:
8
+ *
9
+ * - labels are trimmed before the fingerprint is taken. The recording schema
10
+ * trims them when it parses, so an untrimmed label used to fail its own
11
+ * fingerprint check and the whole demonstration was refused;
12
+ * - every value masked at capture is also removed from the other text the
13
+ * recording keeps (intents, labels, window titles, plain typed text and
14
+ * navigation URLs), because `redactCredentials` cannot recognise an
15
+ * arbitrary password or a bare one-time code by its shape.
16
+ * - a reset-style link loses the path after its reset segment (`/reset/<token>`
17
+ * kept `<token>` before), and a path holding a recognisable credential is
18
+ * dropped.
19
+ *
20
+ * The recorder (Track C, BOFF-16146 C4) sends the events of a person's
21
+ * demonstration. This turns them into saved steps and masks at capture time,
22
+ * so nothing secret ever reaches storage:
23
+ *
24
+ * - text typed into a password, one-time-code, card or similar field is never
25
+ * kept. With a vault reference the step becomes `secret_fill`; without one it
26
+ * is kept as a masked `type` step that always falls back to the model;
27
+ * - typed text that looks like a credential or a one-time code is masked too;
28
+ * - a URL that carries a token, code, signature or reset link loses its query
29
+ * and fragment, a reset link also loses the path after its reset segment,
30
+ * and a path holding a recognisable credential is dropped; the sensitive
31
+ * values it lost are masked in the rest of the recording too;
32
+ * - credential-like fragments in labels and intents are replaced, and so is
33
+ * any value masked elsewhere in the same demonstration; a navigation URL
34
+ * that holds such a value loses its query and fragment, or its path;
35
+ * - a screenshot is referenced only when the recorder masked it.
36
+ *
37
+ * `capturedSecrets` lists every raw value that was masked, so a caller (and
38
+ * the tests) can assert none of them appears in the stored recording.
39
+ */
40
+ import { REDACTED, redactCredentials } from './redact-credentials.js';
41
+ import { type Recording } from './recording.js';
42
+ export { REDACTED, redactCredentials };
43
+ /** The element a recorder event acted on, as the accessibility tree described it. */
44
+ export interface RecorderElement {
45
+ app?: string;
46
+ window?: string;
47
+ role: string;
48
+ name: string;
49
+ nth?: number;
50
+ /** The HTML input type or native field kind, when known (`password`, `text`, …). */
51
+ inputType?: string;
52
+ /** The HTML autocomplete hint, when known (`one-time-code`, `current-password`, `cc-number`, …). */
53
+ autocomplete?: string;
54
+ }
55
+ export interface RecorderScreenshot {
56
+ ref: string;
57
+ /** The recorder boxed out secret fields before uploading. Unmasked screenshots are never referenced. */
58
+ masked: boolean;
59
+ }
60
+ export type RecorderEvent = {
61
+ type: 'click';
62
+ element: RecorderElement;
63
+ button?: 'left' | 'right';
64
+ count?: 1 | 2;
65
+ intent?: string;
66
+ screenshot?: RecorderScreenshot;
67
+ } | {
68
+ type: 'type';
69
+ element?: RecorderElement;
70
+ text: string;
71
+ /** The vault entry the person chose for this field, when it is a secret field. */
72
+ secretRef?: string;
73
+ /** The page origin the secret belongs to (required with `secretRef`). */
74
+ origin?: string;
75
+ intent?: string;
76
+ screenshot?: RecorderScreenshot;
77
+ } | {
78
+ type: 'key';
79
+ keys: string[];
80
+ intent?: string;
81
+ screenshot?: RecorderScreenshot;
82
+ } | {
83
+ type: 'scroll';
84
+ element?: RecorderElement;
85
+ dx: number;
86
+ dy: number;
87
+ intent?: string;
88
+ screenshot?: RecorderScreenshot;
89
+ } | {
90
+ type: 'navigate';
91
+ url: string;
92
+ intent?: string;
93
+ screenshot?: RecorderScreenshot;
94
+ } | {
95
+ type: 'focus_window';
96
+ app: string;
97
+ title?: string;
98
+ intent?: string;
99
+ screenshot?: RecorderScreenshot;
100
+ };
101
+ export interface CaptureResult {
102
+ recording: Recording;
103
+ /** Steps whose typed value was masked and that will always fall back to the model. */
104
+ maskedStepIds: string[];
105
+ /** Raw values that were masked (kept in memory only, for checks; never store this). */
106
+ capturedSecrets: string[];
107
+ }
108
+ /**
109
+ * Drop the query and fragment of a URL that carries a secret or is a
110
+ * reset-style link. A reset-style link also loses the path after its reset
111
+ * segment, and a path that holds a recognisable credential is dropped whole.
112
+ */
113
+ export declare function maskUrl(raw: string): {
114
+ url: string;
115
+ masked: boolean;
116
+ };
117
+ /** Build saved steps from a demonstration, masking at capture. Throws RecordingError on an unusable result. */
118
+ export declare function captureRecording(events: readonly RecorderEvent[]): CaptureResult;
@@ -0,0 +1,14 @@
1
+ import {
2
+ maskUrl2,
3
+ captureRecording2
4
+ } from "./index-phd8yhyg.js";
5
+ import {
6
+ REDACTED2,
7
+ redactCredentials2
8
+ } from "./index-c6pmt2rg.js";
9
+ export {
10
+ REDACTED2 as REDACTED,
11
+ captureRecording2 as captureRecording,
12
+ maskUrl2 as maskUrl,
13
+ redactCredentials2 as redactCredentials
14
+ };
@@ -0,0 +1,52 @@
1
+ // src/resolve.ts
2
+ var MAX_SNAPSHOT_NODES2 = 2000;
3
+ var MAX_FIELD = 512;
4
+ function text(value) {
5
+ return typeof value === "string" && value.length > 0 ? value.slice(0, MAX_FIELD) : undefined;
6
+ }
7
+ function snapshotList(snapshot) {
8
+ if (Array.isArray(snapshot))
9
+ return snapshot;
10
+ if (!snapshot || typeof snapshot !== "object")
11
+ return [];
12
+ if ("nodes" in snapshot && Array.isArray(snapshot.nodes))
13
+ return snapshot.nodes;
14
+ if ("elements" in snapshot && Array.isArray(snapshot.elements))
15
+ return snapshot.elements;
16
+ return [];
17
+ }
18
+ function readSnapshotNodes2(snapshot) {
19
+ const list = snapshotList(snapshot);
20
+ const nodes = [];
21
+ for (const item of list) {
22
+ if (nodes.length >= MAX_SNAPSHOT_NODES2)
23
+ break;
24
+ if (!item || typeof item !== "object")
25
+ continue;
26
+ const record = item;
27
+ const ref = text(record.ref);
28
+ const role = text(record.role);
29
+ const name = typeof record.name === "string" ? record.name.slice(0, MAX_FIELD) : undefined;
30
+ if (!ref || !role || name === undefined)
31
+ continue;
32
+ const app = text(record.app);
33
+ const window = text(record.window);
34
+ nodes.push({ ref, role, name, ...app ? { app } : {}, ...window ? { window } : {} });
35
+ }
36
+ return nodes;
37
+ }
38
+ function same(a, b) {
39
+ const norm = (value) => value.normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
40
+ return norm(a ?? "") === norm(b ?? "");
41
+ }
42
+ function resolveTarget2(target, nodes) {
43
+ if (!nodes)
44
+ return { resolved: false, reason: "no-snapshot" };
45
+ const matches = nodes.filter((node) => same(node.role, target.role) && same(node.name, target.name) && (target.app === undefined || same(node.app, target.app)) && (target.window === undefined || same(node.window, target.window)));
46
+ if (matches.length === 0)
47
+ return { resolved: false, reason: "not-found" };
48
+ const match = matches[target.nth];
49
+ return match ? { resolved: true, ref: match.ref } : { resolved: false, reason: "fewer-matches" };
50
+ }
51
+
52
+ export { MAX_SNAPSHOT_NODES2, readSnapshotNodes2, resolveTarget2 };
@@ -0,0 +1,213 @@
1
+ // src/recording.ts
2
+ import { sha256 as nobleSha256 } from "@noble/hashes/sha2.js";
3
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
4
+ import { z } from "zod";
5
+
6
+ // src/redact-credentials.ts
7
+ var REDACTED2 = "[REDACTED]";
8
+ var CREDENTIAL_PATTERNS = [
9
+ /\b(?:Bearer|Basic)\s+[^\s"'`,;)\]}]+/gi,
10
+ /\b(?:sk|pk|rk|xai)-[^\s"'`,;)\]}]+/gi,
11
+ /\b(?:gsk|hf|ghp|gho|ghs|ghu|glpat)_[^\s"'`,;)\]}]+/gi,
12
+ /\bAIza[\w-]{10,}/g,
13
+ /\b(?:AKIA|ASIA)[0-9A-Z]{12,}/g
14
+ ];
15
+ var SEPARATORS = /([\s"'`,;:=()[\]{}]+)/;
16
+ var SECRET_KEY = /^(?:api[_-]?key|access[_-]?key|secret|secret[_-]?key|client[_-]?secret|token|password)$/i;
17
+ function isMaskedFragment(word) {
18
+ const ellipsis = word.indexOf("…");
19
+ return word.includes("***") || ellipsis !== -1 && ellipsis < word.length - 1;
20
+ }
21
+ function redactWords(text) {
22
+ const parts = text.split(SEPARATORS);
23
+ for (let index = 0;index < parts.length; index += 2) {
24
+ const word = parts[index] ?? "";
25
+ if (word && word !== REDACTED2 && isMaskedFragment(word))
26
+ parts[index] = REDACTED2;
27
+ const separator = parts[index + 1] ?? "";
28
+ const next = parts[index + 2];
29
+ if (next && SECRET_KEY.test(word) && /[:=]/.test(separator))
30
+ parts[index + 2] = REDACTED2;
31
+ }
32
+ return parts.join("");
33
+ }
34
+ function redactCredentials2(text) {
35
+ if (!text)
36
+ return text;
37
+ let redacted = text;
38
+ for (const pattern of CREDENTIAL_PATTERNS) {
39
+ redacted = redacted.replace(pattern, REDACTED2);
40
+ }
41
+ redacted = redactWords(redacted);
42
+ return redacted.replace(/(?:\[REDACTED\]){2,}/g, REDACTED2);
43
+ }
44
+ var MARKER_PROBE = "";
45
+ function containsCredential(text) {
46
+ if (!text)
47
+ return false;
48
+ const probe = text.replaceAll(REDACTED2, MARKER_PROBE);
49
+ return redactCredentials2(probe).replaceAll(MARKER_PROBE, REDACTED2) !== text;
50
+ }
51
+ function decodeUriText(text) {
52
+ try {
53
+ return decodeURIComponent(text.replaceAll("+", " "));
54
+ } catch {
55
+ return text;
56
+ }
57
+ }
58
+ function containsCredentialInUrl(text) {
59
+ return containsCredential(decodeUriText(text).replace(/[/?&#]/g, " "));
60
+ }
61
+
62
+ // src/recording.ts
63
+ function sha256Hex2(text) {
64
+ return bytesToHex(nobleSha256(utf8ToBytes(text)));
65
+ }
66
+ var RECORDING_VERSION2 = 1;
67
+ var MAX_RECORDED_STEPS2 = 200;
68
+ var MAX_LABEL = 512;
69
+ var MAX_TEXT = 4000;
70
+ var MAX_INTENT = 500;
71
+ var SAVED_STEP_AUTHORS2 = ["PERSON", "TEACH_MODE", "IMPORT"];
72
+ var REPLAYABLE_ACTIONS2 = [
73
+ "click",
74
+ "type",
75
+ "secret_fill",
76
+ "key",
77
+ "scroll",
78
+ "navigate",
79
+ "focus_window"
80
+ ];
81
+ var label = z.string().trim().min(1).max(MAX_LABEL);
82
+ var recordedTargetSchema2 = z.strictObject({
83
+ app: label.optional(),
84
+ window: label.optional(),
85
+ role: label,
86
+ name: label,
87
+ nth: z.int().min(0).max(50).default(0)
88
+ });
89
+ var stepBase = {
90
+ id: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),
91
+ intent: z.string().trim().min(1).max(MAX_INTENT),
92
+ screenshotRef: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9:/._-]{0,511}$/).optional(),
93
+ fingerprint: z.string().regex(/^[0-9a-f]{64}$/)
94
+ };
95
+ var targeted = { ...stepBase, target: recordedTargetSchema2 };
96
+ var recordedStepSchema2 = z.discriminatedUnion("action", [
97
+ z.strictObject({
98
+ ...targeted,
99
+ action: z.literal("click"),
100
+ button: z.enum(["left", "right"]).default("left"),
101
+ count: z.union([z.literal(1), z.literal(2)]).default(1)
102
+ }),
103
+ z.strictObject({
104
+ ...stepBase,
105
+ action: z.literal("type"),
106
+ target: recordedTargetSchema2.optional(),
107
+ text: z.string().max(MAX_TEXT).optional(),
108
+ masked: z.boolean().default(false)
109
+ }),
110
+ z.strictObject({
111
+ ...targeted,
112
+ action: z.literal("secret_fill"),
113
+ secretRef: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9:/._-]{0,254}$/),
114
+ expectedOrigin: z.url({ protocol: /^https?$/ })
115
+ }),
116
+ z.strictObject({ ...stepBase, action: z.literal("key"), keys: z.array(z.string().min(1).max(32)).min(1).max(8) }),
117
+ z.strictObject({
118
+ ...stepBase,
119
+ action: z.literal("scroll"),
120
+ target: recordedTargetSchema2.optional(),
121
+ dx: z.int().min(-1e4).max(1e4),
122
+ dy: z.int().min(-1e4).max(1e4)
123
+ }),
124
+ z.strictObject({ ...stepBase, action: z.literal("navigate"), url: z.url({ protocol: /^https?$/ }).max(2048) }),
125
+ z.strictObject({
126
+ ...stepBase,
127
+ action: z.literal("focus_window"),
128
+ app: label,
129
+ title: label.optional()
130
+ })
131
+ ]);
132
+ var recordingSchema2 = z.strictObject({
133
+ version: z.literal(RECORDING_VERSION2),
134
+ steps: z.array(recordedStepSchema2).min(1).max(MAX_RECORDED_STEPS2)
135
+ });
136
+ function targetFingerprint2(step) {
137
+ const target = "target" in step && step.target ? step.target : undefined;
138
+ return sha256Hex2(JSON.stringify([
139
+ step.action,
140
+ target?.app ?? null,
141
+ target?.window ?? null,
142
+ target?.role ?? null,
143
+ target?.name ?? null,
144
+ target?.nth ?? 0,
145
+ "url" in step ? step.url ?? null : null,
146
+ "app" in step ? step.app ?? null : null,
147
+ "title" in step ? step.title ?? null : null
148
+ ]));
149
+ }
150
+
151
+ class RecordingError2 extends Error {
152
+ code;
153
+ constructor(code, message) {
154
+ super(message);
155
+ this.code = code;
156
+ this.name = "RecordingError";
157
+ }
158
+ }
159
+ function parseRecording2(value) {
160
+ const parsed = recordingSchema2.safeParse(value);
161
+ if (!parsed.success) {
162
+ const issue = parsed.error.issues[0];
163
+ const where = issue?.path.map(String).join(".") ?? "";
164
+ throw new RecordingError2("INVALID_RECORDING", `Recording is not valid at ${where || "the top"}: ${issue?.message}`);
165
+ }
166
+ const ids = new Set;
167
+ for (const step of parsed.data.steps) {
168
+ if (ids.has(step.id))
169
+ throw new RecordingError2("DUPLICATE_STEP_ID", `Step id ${step.id} is used twice.`);
170
+ ids.add(step.id);
171
+ if (targetFingerprint2(step) !== step.fingerprint) {
172
+ throw new RecordingError2("FINGERPRINT_MISMATCH", `Step ${step.id} was changed after it was recorded.`);
173
+ }
174
+ const field = credentialField(step);
175
+ if (field) {
176
+ throw new RecordingError2("CREDENTIAL_IN_RECORDING", `Step ${step.id} holds a credential in its ${field}.`);
177
+ }
178
+ }
179
+ return parsed.data;
180
+ }
181
+ function storedText(step) {
182
+ const target = "target" in step ? step.target : undefined;
183
+ const fields = [
184
+ ["intent", step.intent],
185
+ ["target app", target?.app],
186
+ ["target window", target?.window],
187
+ ["target role", target?.role],
188
+ ["target name", target?.name]
189
+ ];
190
+ switch (step.action) {
191
+ case "type":
192
+ return [...fields, ["text", step.text]];
193
+ case "navigate":
194
+ return fields;
195
+ case "focus_window":
196
+ return [...fields, ["app", step.app], ["title", step.title]];
197
+ default:
198
+ return fields;
199
+ }
200
+ }
201
+ function credentialField(step) {
202
+ if (step.action === "navigate") {
203
+ const url = new URL(step.url);
204
+ if (url.username || url.password || containsCredentialInUrl(step.url))
205
+ return "url";
206
+ }
207
+ return storedText(step).find(([, value]) => value !== undefined && containsCredential(value))?.[0];
208
+ }
209
+ function isSavedStepAuthor2(value) {
210
+ return typeof value === "string" && SAVED_STEP_AUTHORS2.includes(value);
211
+ }
212
+
213
+ export { REDACTED2, redactCredentials2, containsCredential, decodeUriText, containsCredentialInUrl, sha256Hex2, RECORDING_VERSION2, MAX_RECORDED_STEPS2, SAVED_STEP_AUTHORS2, REPLAYABLE_ACTIONS2, recordedTargetSchema2, recordedStepSchema2, recordingSchema2, targetFingerprint2, RecordingError2, parseRecording2, isSavedStepAuthor2 };