@extension-use/host 0.0.0-stage → 0.2.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/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,192 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ GROUP_NAMES,
4
+ withExtensionUse
5
+ } from "./chunk-4SALFB5W.js";
6
+ import "./chunk-QYMPEWZP.js";
7
+ import "./chunk-5X4QMMKA.js";
8
+
9
+ // src/cli.ts
10
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
11
+ import { createRequire } from "module";
12
+ import { dirname, join, relative, resolve } from "path";
13
+ import { fileURLToPath } from "url";
14
+
15
+ // src/codegen.ts
16
+ import { coreActionSchemas } from "@extension-use/protocol/schemas";
17
+ var IDENT = /^[A-Za-z_$][\w$]*$/;
18
+ var key = (k) => IDENT.test(k) ? k : JSON.stringify(k);
19
+ function jsonSchemaToTs(schema, indent = "") {
20
+ if (schema === true || schema === void 0) return "unknown";
21
+ if (schema === false) return "never";
22
+ if (schema.$ref) return "unknown";
23
+ if (schema.const !== void 0) return JSON.stringify(schema.const);
24
+ if (schema.enum) return schema.enum.map((e) => JSON.stringify(e)).join(" | ");
25
+ const union = schema.anyOf ?? schema.oneOf;
26
+ if (union) return union.map((s) => wrap(jsonSchemaToTs(s, indent))).join(" | ");
27
+ if (schema.allOf) return schema.allOf.map((s) => wrap(jsonSchemaToTs(s, indent))).join(" & ");
28
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
29
+ if (types.length > 1) return types.map((t) => jsonSchemaToTs({ ...schema, type: t }, indent)).join(" | ");
30
+ switch (types[0]) {
31
+ case "string":
32
+ return "string";
33
+ case "number":
34
+ case "integer":
35
+ return "number";
36
+ case "boolean":
37
+ return "boolean";
38
+ case "null":
39
+ return "null";
40
+ case "array":
41
+ return `${wrap(jsonSchemaToTs(schema.items, indent))}[]`;
42
+ case "object":
43
+ case void 0: {
44
+ if (!schema.properties && types[0] === void 0) return "unknown";
45
+ const props = Object.entries(schema.properties ?? {});
46
+ const extra = schema.additionalProperties;
47
+ if (!props.length) return extra && extra !== true ? `Record<string, ${jsonSchemaToTs(extra, indent)}>` : "Record<string, unknown>";
48
+ const inner = indent + " ";
49
+ const lines = props.map(([k, v]) => {
50
+ const doc = v.description ? `${inner}/** ${v.description.replace(/\*\//g, "*\\/")} */
51
+ ` : "";
52
+ return `${doc}${inner}${key(k)}${(schema.required ?? []).includes(k) ? "" : "?"}: ${jsonSchemaToTs(v, inner)};`;
53
+ });
54
+ return `{
55
+ ${lines.join("\n")}
56
+ ${indent}}`;
57
+ }
58
+ default:
59
+ return "unknown";
60
+ }
61
+ }
62
+ function wrap(t) {
63
+ return / [|&] /.test(t) && !t.startsWith("{") ? `(${t})` : t;
64
+ }
65
+ function generateTypes(describe, options = {}) {
66
+ const typeName = options.typeName ?? "HostActions";
67
+ const actions = describe.actions.filter((a) => options.all || !(a.name in coreActionSchemas)).sort((a, b) => a.name.localeCompare(b.name));
68
+ const body = actions.map((a) => {
69
+ const doc = a.description ? ` /** ${a.description.replace(/\*\//g, "*\\/")} */
70
+ ` : "";
71
+ return `${doc} ${JSON.stringify(a.name)}: {
72
+ input: ${jsonSchemaToTs(a.input, " ")};
73
+ output: ${jsonSchemaToTs(a.output, " ")};
74
+ };`;
75
+ }).join("\n");
76
+ const host = describe.host.name ? `${describe.host.name} (${describe.host.id})` : describe.host.id;
77
+ return `// Generated by \`extension-use codegen\` from ${host}${describe.host.version ? ` ${describe.host.version}` : ""}. Do not edit.
78
+ // Use it with: connect<CoreActions & ${typeName}>(transport)
79
+
80
+ export type ${typeName} = {
81
+ ${body}
82
+ };
83
+ `;
84
+ }
85
+
86
+ // src/cli.ts
87
+ var argv = process.argv.slice(2);
88
+ var command = argv[0];
89
+ var flag = (name) => {
90
+ const i = argv.indexOf(`--${name}`);
91
+ return i >= 0 ? argv[i + 1] : void 0;
92
+ };
93
+ var list = (v) => v ? v.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
94
+ var HELP = `Usage:
95
+ extension-use manifest [options] Print or write the manifest fields Extension-use needs
96
+ --groups <list> Action groups the host enables (default: all but the opt-in ones: tabCapture, downloads, bookmarks, history, cookies). Known: ${GROUP_NAMES.join(", ")}
97
+ --origins <list> Web app origins allowed to connect from a tab (externally_connectable)
98
+ --matches <list> Pages the content runtime runs on (default <all_urls>)
99
+ --no-side-panel Don't add the "sidePanel" permission
100
+ --remote Remote control through a relay (adds "storage" and "alarms")
101
+ --write <file> Merge into manifest.json, or into the "manifest" key of package.json
102
+
103
+ extension-use codegen [options] Write TypeScript types for your extension's own actions
104
+ --relay <url> Ask a running browser through a relay (token: EXTENSION_USE_TOKEN or --token)
105
+ --device <id> Device to ask (default "default")
106
+ --from <file> Or read saved runtime.describe output (JSON)
107
+ --out <file> Where to write (default extension-actions.ts)
108
+ --all Include the built-in actions too
109
+
110
+ extension-use vendor [options] Copy the no-build bundles into your project
111
+ --extension <dir> Where to put the extension bundles (default extension/vendor)
112
+ --web <dir> Where to put the web app client (default web/vendor; needs @extension-use/client installed)`;
113
+ function manifest() {
114
+ const options = {
115
+ ...list(flag("groups")) ? { groups: list(flag("groups")) } : {},
116
+ ...list(flag("origins")) ? { controllerOrigins: list(flag("origins")) } : {},
117
+ ...list(flag("matches")) ? { matches: list(flag("matches")) } : {},
118
+ sidePanel: !argv.includes("--no-side-panel"),
119
+ remote: argv.includes("--remote")
120
+ };
121
+ const file = flag("write");
122
+ if (!file) {
123
+ console.log(JSON.stringify(withExtensionUse({}, options), null, 2));
124
+ return;
125
+ }
126
+ const json = JSON.parse(readFileSync(file, "utf8"));
127
+ const isPackageJson = /package\.json$/i.test(file);
128
+ const current = isPackageJson ? json.manifest ?? {} : json;
129
+ const merged = withExtensionUse(current, options);
130
+ writeFileSync(file, JSON.stringify(isPackageJson ? { ...json, manifest: merged } : merged, null, 2) + "\n");
131
+ console.log(`Updated ${file}${isPackageJson ? ' ("manifest")' : ""}: ${[...merged.permissions ?? [], ...merged.host_permissions ?? []].join(", ")}`);
132
+ }
133
+ function vendor() {
134
+ const here = dirname(fileURLToPath(import.meta.url));
135
+ const hostDir = join(here, "standalone");
136
+ const extDir = resolve(flag("extension") ?? "extension/vendor");
137
+ const webDir = resolve(flag("web") ?? "web/vendor");
138
+ const copied = [];
139
+ mkdirSync(extDir, { recursive: true });
140
+ for (const f of ["extension-use-background.js", "extension-use-content.js", "extension-use-frame.js", "extension-use-ui.js", "extension-use-offscreen.js"]) {
141
+ const src = join(hostDir, f);
142
+ if (!existsSync(src)) throw new Error(`Missing ${src}. Is @extension-use/host built?`);
143
+ copyFileSync(src, join(extDir, f));
144
+ copied.push(relative(process.cwd(), join(extDir, f)));
145
+ }
146
+ try {
147
+ const require2 = createRequire(join(process.cwd(), "package.json"));
148
+ const client = require2.resolve("@extension-use/client/standalone/extension-use-client.js");
149
+ mkdirSync(webDir, { recursive: true });
150
+ copyFileSync(client, join(webDir, "extension-use-client.js"));
151
+ copied.push(relative(process.cwd(), join(webDir, "extension-use-client.js")));
152
+ } catch {
153
+ console.warn("Skipped the web client: install @extension-use/client to vendor it.");
154
+ }
155
+ console.log(`Copied:
156
+ ${copied.join("\n ")}`);
157
+ }
158
+ async function codegen() {
159
+ let describe;
160
+ const from = flag("from");
161
+ if (from) {
162
+ describe = JSON.parse(readFileSync(from, "utf8"));
163
+ } else {
164
+ const relay = flag("relay");
165
+ const token = process.env.EXTENSION_USE_TOKEN ?? flag("token");
166
+ if (!relay || !token) throw new Error("Give --relay and a token (EXTENSION_USE_TOKEN), or --from <describe.json>");
167
+ const res = await fetch(`${relay.replace(/\/+$/, "")}/v1/devices/${encodeURIComponent(flag("device") ?? "default")}/calls`, {
168
+ method: "POST",
169
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
170
+ body: JSON.stringify({ action: "runtime.describe" })
171
+ });
172
+ const json = await res.json();
173
+ if (!json.ok || !json.output) throw new Error(`${json.error?.code}: ${json.error?.message}`);
174
+ describe = json.output;
175
+ }
176
+ if (!Array.isArray(describe?.actions)) throw new Error("Not runtime.describe output");
177
+ const out = flag("out") ?? "extension-actions.ts";
178
+ writeFileSync(out, generateTypes(describe, { all: argv.includes("--all") }));
179
+ console.log(`Wrote ${out} (${describe.actions.length} actions from ${describe.host.name ?? describe.host.id})`);
180
+ }
181
+ try {
182
+ if (command === "manifest") manifest();
183
+ else if (command === "codegen") await codegen();
184
+ else if (command === "vendor") vendor();
185
+ else {
186
+ console.log(HELP);
187
+ process.exit(command === "--help" || command === "help" ? 0 : 1);
188
+ }
189
+ } catch (err) {
190
+ console.error(`\u2716 ${err.message}`);
191
+ process.exit(1);
192
+ }
@@ -0,0 +1,62 @@
1
+ import { Locator } from '@extension-use/protocol';
2
+ export { ExtensionUseError } from '@extension-use/protocol';
3
+ import { ElementInfo } from '@extension-use/protocol/schemas';
4
+
5
+ interface ContentContext {
6
+ signal: AbortSignal;
7
+ timeoutMs: number;
8
+ policy: {
9
+ sensitiveFields: "refuse" | "allow";
10
+ };
11
+ emit(name: string, payload: unknown): void;
12
+ }
13
+ type ContentHandler = (input: any, ctx: ContentContext) => unknown | Promise<unknown>;
14
+ interface ContentGroup {
15
+ name: string;
16
+ handlers: Record<string, ContentHandler>;
17
+ }
18
+
19
+ declare function roleOf(el: Element): string;
20
+ declare function nameOf(el: Element): string;
21
+ declare function isVisible(el: Element): boolean;
22
+
23
+ declare function refFor(el: Element): string;
24
+ declare function findAll(locator: Locator, root?: ParentNode): Element[];
25
+ interface ResolveOptions {
26
+ timeoutMs: number;
27
+ signal?: AbortSignal;
28
+ /** Require the element to be visible. Default true. */
29
+ visible?: boolean;
30
+ root?: ParentNode;
31
+ }
32
+ /** Find one element, waiting for it up to `timeoutMs`. */
33
+ declare function resolve(locator: Locator, opts: ResolveOptions): Promise<Element>;
34
+ declare function describe(el: Element, textMaxLength?: number): ElementInfo;
35
+ /** A short, reasonably stable CSS selector for an element. */
36
+ declare function cssPath(el: Element): string;
37
+
38
+ declare const contentGroups: {
39
+ readonly page: ContentGroup;
40
+ readonly dom: {
41
+ name: string;
42
+ handlers: {
43
+ [x: string]: ContentHandler;
44
+ };
45
+ };
46
+ readonly edit: ContentGroup;
47
+ readonly wait: ContentGroup;
48
+ readonly overlay: ContentGroup;
49
+ readonly picker: ContentGroup;
50
+ };
51
+ declare const allContentGroups: ContentGroup[];
52
+ interface ContentRuntimeOptions {
53
+ /** Default: all built-in content groups. */
54
+ groups?: ContentGroup[];
55
+ /** Host-defined content actions. */
56
+ handlers?: Record<string, ContentHandler>;
57
+ /** Show "Controlled by …" on the page during remote and website control. Default true. */
58
+ indicator?: boolean;
59
+ }
60
+ declare function startContentRuntime(options?: ContentRuntimeOptions): void;
61
+
62
+ export { type ContentContext, type ContentGroup, type ContentHandler, type ContentRuntimeOptions, allContentGroups, contentGroups, cssPath, describe, findAll, isVisible, nameOf, refFor, resolve as resolveLocator, roleOf, startContentRuntime };