@seavideo/cli 0.0.0-stage → 0.3.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 +12 -0
- package/README.md +528 -2
- package/dist/bin/seavideo.js +11 -0
- package/dist/src/atomic-write.js +14 -0
- package/dist/src/canvas/api.js +172 -0
- package/dist/src/canvas/browser.js +40 -0
- package/dist/src/canvas/chrome-binary.js +109 -0
- package/dist/src/canvas/daemon.js +264 -0
- package/dist/src/canvas/engine-install.js +46 -0
- package/dist/src/canvas/engine-log.js +9 -0
- package/dist/src/canvas/engine.js +99 -0
- package/dist/src/canvas/entry.js +16 -0
- package/dist/src/canvas/env-lock.js +164 -0
- package/dist/src/canvas/launch.js +97 -0
- package/dist/src/canvas/lifecycle.js +65 -0
- package/dist/src/canvas/names.js +61 -0
- package/dist/src/canvas/params.js +38 -0
- package/dist/src/canvas/puppeteer.js +153 -0
- package/dist/src/canvas/screenshot.js +23 -0
- package/dist/src/canvas/session-record.js +77 -0
- package/dist/src/canvas/team.js +97 -0
- package/dist/src/canvas/tool-args.js +47 -0
- package/dist/src/canvas/tool-session.js +165 -0
- package/dist/src/canvas/tool-specs.js +54 -0
- package/dist/src/canvas/url.js +38 -0
- package/dist/src/cli/args.js +16 -0
- package/dist/src/cli/commands/auth.js +51 -0
- package/dist/src/cli/commands/canvas/common.js +31 -0
- package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
- package/dist/src/cli/commands/canvas/index.js +5 -0
- package/dist/src/cli/commands/canvas/item.js +233 -0
- package/dist/src/cli/commands/canvas/list.js +168 -0
- package/dist/src/cli/commands/canvas/register.js +106 -0
- package/dist/src/cli/commands/canvas/render.js +229 -0
- package/dist/src/cli/commands/canvas/screenshot.js +52 -0
- package/dist/src/cli/commands/canvas/session.js +249 -0
- package/dist/src/cli/commands/canvas/teams.js +142 -0
- package/dist/src/cli/commands/config.js +74 -0
- package/dist/src/cli/commands/doctor.js +261 -0
- package/dist/src/cli/commands/engine.js +96 -0
- package/dist/src/cli/commands/env/create.js +160 -0
- package/dist/src/cli/commands/env/fields.js +26 -0
- package/dist/src/cli/commands/env/index.js +4 -0
- package/dist/src/cli/commands/env/list.js +44 -0
- package/dist/src/cli/commands/env/mutate.js +118 -0
- package/dist/src/cli/commands/login/flow-token.js +41 -0
- package/dist/src/cli/commands/login/index.js +12 -0
- package/dist/src/cli/commands/login/oauth.js +69 -0
- package/dist/src/cli/commands/login/save.js +26 -0
- package/dist/src/cli/commands/logout.js +92 -0
- package/dist/src/cli/commands/skill.js +185 -0
- package/dist/src/cli/commands/tool.js +279 -0
- package/dist/src/cli/commands/update.js +117 -0
- package/dist/src/cli/commands/wallet.js +69 -0
- package/dist/src/cli/commands/whoami.js +147 -0
- package/dist/src/cli/context.js +41 -0
- package/dist/src/cli/credential.js +93 -0
- package/dist/src/cli/elapsed.js +25 -0
- package/dist/src/cli/failure-screenshot.js +24 -0
- package/dist/src/cli/flags.js +1 -0
- package/dist/src/cli/hints.js +7 -0
- package/dist/src/cli/main.js +44 -0
- package/dist/src/cli/output-error.js +23 -0
- package/dist/src/cli/output.js +47 -0
- package/dist/src/cli/program.js +261 -0
- package/dist/src/cli/run.js +11 -0
- package/dist/src/cli/session.js +63 -0
- package/dist/src/config/base-url.js +26 -0
- package/dist/src/config/credential-vault.js +115 -0
- package/dist/src/config/dotenv.js +59 -0
- package/dist/src/config/envname.js +41 -0
- package/dist/src/config/paths.js +22 -0
- package/dist/src/config/preset-schema.js +67 -0
- package/dist/src/config/presets.js +132 -0
- package/dist/src/config/resolve.js +41 -0
- package/dist/src/config/secret-key.js +63 -0
- package/dist/src/config/store-schema.js +143 -0
- package/dist/src/config/store.js +273 -0
- package/dist/src/config/vault-crypto.js +44 -0
- package/dist/src/deps.js +191 -0
- package/dist/src/deps.types.js +1 -0
- package/dist/src/errors.js +24 -0
- package/dist/src/fs-retry.js +34 -0
- package/dist/src/i18n.js +1214 -0
- package/dist/src/loopback.js +134 -0
- package/dist/src/sdk/auth.js +20 -0
- package/dist/src/sdk/credential-expiry.js +67 -0
- package/dist/src/sdk/discovery.js +90 -0
- package/dist/src/sdk/http.js +98 -0
- package/dist/src/sdk/identity.js +17 -0
- package/dist/src/sdk/jwks.js +119 -0
- package/dist/src/sdk/oauth-protocol.js +226 -0
- package/dist/src/sdk/oauth.js +179 -0
- package/dist/src/sdk/provider/cn.js +34 -0
- package/dist/src/sdk/provider/index.js +16 -0
- package/dist/src/sdk/provider/oversea.js +41 -0
- package/dist/src/sdk/provider/types.js +1 -0
- package/dist/src/sdk/refresh.js +66 -0
- package/dist/src/semver.js +89 -0
- package/dist/src/skill/api.js +176 -0
- package/dist/src/text.js +3 -0
- package/dist/src/types.js +1 -0
- package/dist/src/update/check-cache.js +56 -0
- package/dist/src/update/install-layout.js +79 -0
- package/dist/src/update/notify.js +15 -0
- package/dist/src/update/npm-install.js +64 -0
- package/dist/src/update/passive.js +53 -0
- package/dist/src/update/registry.js +59 -0
- package/dist/src/wallet/api.js +107 -0
- package/package.json +67 -4
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { CANVAS_SUCCESS_CODE, requestJson } from "../sdk/http.js";
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { t } from "../i18n.js";
|
|
4
|
+
function str(v) {
|
|
5
|
+
return typeof v === 'string' && v !== '' ? v : null;
|
|
6
|
+
}
|
|
7
|
+
export function normalizeGraph(raw, envMap = process.env) {
|
|
8
|
+
const g = (raw ?? {});
|
|
9
|
+
const id = str(g['id']);
|
|
10
|
+
const name = g['name'];
|
|
11
|
+
if (id === null)
|
|
12
|
+
throw new CliError('server', t('canvas.malformed', {}, envMap));
|
|
13
|
+
return {
|
|
14
|
+
id,
|
|
15
|
+
name: typeof name === 'string' ? name : '',
|
|
16
|
+
graphType: g['graph_type'] === 'team' ? 'team' : 'personal',
|
|
17
|
+
projectId: str(g['project_id']),
|
|
18
|
+
teamId: str(g['team_id']),
|
|
19
|
+
folderId: str(g['folder_id']),
|
|
20
|
+
createdAt: str(g['createdAt']) ?? str(g['created_at']),
|
|
21
|
+
updatedAt: str(g['updatedAt']) ?? str(g['updated_at']),
|
|
22
|
+
deletedAt: str(g['deletedAt']) ?? str(g['deleted_at']),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function normalizeFolder(raw, envMap) {
|
|
26
|
+
const f = (raw ?? {});
|
|
27
|
+
const id = str(f['id']);
|
|
28
|
+
if (id === null)
|
|
29
|
+
throw new CliError('server', t('canvas.malformedFolder', {}, envMap));
|
|
30
|
+
return {
|
|
31
|
+
id,
|
|
32
|
+
name: typeof f['name'] === 'string' ? f['name'] : '',
|
|
33
|
+
createdAt: str(f['createdAt']) ?? str(f['created_at']),
|
|
34
|
+
canvasCount: numOrNull(f['graph_count']) ?? numOrNull(f['graphCount']),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function numOrNull(v) {
|
|
38
|
+
return typeof v === 'number' ? v : null;
|
|
39
|
+
}
|
|
40
|
+
function normalizeProject(raw, envMap) {
|
|
41
|
+
const p = (raw ?? {});
|
|
42
|
+
const projectId = str(p['id']);
|
|
43
|
+
if (projectId === null)
|
|
44
|
+
throw new CliError('server', t('canvas.malformedProject', {}, envMap));
|
|
45
|
+
return { id: projectId, name: str(p['name']) ?? '', teamId: str(p['team_id']) };
|
|
46
|
+
}
|
|
47
|
+
function normalizeDeleteResult(raw) {
|
|
48
|
+
const data = (raw ?? {});
|
|
49
|
+
return {
|
|
50
|
+
changed: typeof data['changed_count'] === 'number' ? data['changed_count'] : 0,
|
|
51
|
+
unchanged: typeof data['unchanged_count'] === 'number' ? data['unchanged_count'] : 0,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function listQuery(params) {
|
|
55
|
+
const q = new URLSearchParams({
|
|
56
|
+
page: String(params.page),
|
|
57
|
+
page_size: String(params.pageSize),
|
|
58
|
+
});
|
|
59
|
+
if (params.projectId !== undefined)
|
|
60
|
+
q.set('project_id', params.projectId);
|
|
61
|
+
else {
|
|
62
|
+
}
|
|
63
|
+
if (params.keyword !== undefined)
|
|
64
|
+
q.set('keyword', params.keyword);
|
|
65
|
+
else {
|
|
66
|
+
}
|
|
67
|
+
return q.toString();
|
|
68
|
+
}
|
|
69
|
+
function normalizePage(raw, envMap) {
|
|
70
|
+
const rawItems = Array.isArray(raw?.data) ? raw.data : [];
|
|
71
|
+
return {
|
|
72
|
+
total: typeof raw?.total_count === 'number' ? raw.total_count : rawItems.length,
|
|
73
|
+
items: rawItems.map((g) => normalizeGraph(g, envMap)),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function createBody(input) {
|
|
77
|
+
const body = { name: input.name };
|
|
78
|
+
if (input.projectId !== undefined)
|
|
79
|
+
body['project_id'] = input.projectId;
|
|
80
|
+
else {
|
|
81
|
+
}
|
|
82
|
+
if (input.folderId !== undefined)
|
|
83
|
+
body['folder_id'] = input.folderId;
|
|
84
|
+
else {
|
|
85
|
+
}
|
|
86
|
+
return body;
|
|
87
|
+
}
|
|
88
|
+
function apiCtx(deps, config, token) {
|
|
89
|
+
return {
|
|
90
|
+
http: { fetch: deps.fetch, env: deps.env, baseUrl: config.flowApiBaseUrl },
|
|
91
|
+
headers: { authorization: `Bearer ${token}` },
|
|
92
|
+
envMap: deps.env,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
async function pingGateway(ctx) {
|
|
96
|
+
await requestJson(ctx.http, {
|
|
97
|
+
method: 'GET',
|
|
98
|
+
path: '/api/graphs?page=1&page_size=1',
|
|
99
|
+
headers: ctx.headers,
|
|
100
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async function listCanvases(ctx, params) {
|
|
104
|
+
const data = await requestJson(ctx.http, {
|
|
105
|
+
method: 'GET',
|
|
106
|
+
path: `/api/graphs?${listQuery(params)}`,
|
|
107
|
+
headers: ctx.headers,
|
|
108
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
109
|
+
});
|
|
110
|
+
return normalizePage(data, ctx.envMap);
|
|
111
|
+
}
|
|
112
|
+
async function getCanvas(ctx, id) {
|
|
113
|
+
const data = await requestJson(ctx.http, {
|
|
114
|
+
method: 'GET',
|
|
115
|
+
path: `/api/graphs/${encodeURIComponent(id)}`,
|
|
116
|
+
headers: ctx.headers,
|
|
117
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
118
|
+
});
|
|
119
|
+
return normalizeGraph(data, ctx.envMap);
|
|
120
|
+
}
|
|
121
|
+
async function listFolders(ctx) {
|
|
122
|
+
const data = await requestJson(ctx.http, {
|
|
123
|
+
method: 'GET',
|
|
124
|
+
path: '/api/folders/options',
|
|
125
|
+
headers: ctx.headers,
|
|
126
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
127
|
+
});
|
|
128
|
+
const raw = Array.isArray(data) ? data : [];
|
|
129
|
+
return raw.map((x) => normalizeFolder(x, ctx.envMap));
|
|
130
|
+
}
|
|
131
|
+
async function getTeamProject(ctx, id) {
|
|
132
|
+
const data = await requestJson(ctx.http, {
|
|
133
|
+
method: 'GET',
|
|
134
|
+
path: `/api/team-projects/${encodeURIComponent(id)}`,
|
|
135
|
+
headers: ctx.headers,
|
|
136
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
137
|
+
});
|
|
138
|
+
return normalizeProject(data, ctx.envMap);
|
|
139
|
+
}
|
|
140
|
+
async function createCanvas(ctx, input) {
|
|
141
|
+
const data = await requestJson(ctx.http, {
|
|
142
|
+
method: 'POST',
|
|
143
|
+
path: '/api/graphs',
|
|
144
|
+
headers: ctx.headers,
|
|
145
|
+
body: createBody(input),
|
|
146
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
147
|
+
});
|
|
148
|
+
return normalizeGraph(data, ctx.envMap);
|
|
149
|
+
}
|
|
150
|
+
async function removeCanvases(ctx, ids, options) {
|
|
151
|
+
const path = options.hard ? '/api/graphs?hard_delete=true' : '/api/graphs';
|
|
152
|
+
const data = await requestJson(ctx.http, {
|
|
153
|
+
method: 'DELETE',
|
|
154
|
+
path,
|
|
155
|
+
headers: ctx.headers,
|
|
156
|
+
body: [...ids],
|
|
157
|
+
successCode: CANVAS_SUCCESS_CODE,
|
|
158
|
+
});
|
|
159
|
+
return normalizeDeleteResult(data);
|
|
160
|
+
}
|
|
161
|
+
export function createCanvasApi(deps, config, token) {
|
|
162
|
+
const ctx = apiCtx(deps, config, token);
|
|
163
|
+
return {
|
|
164
|
+
ping: () => pingGateway(ctx),
|
|
165
|
+
list: (params) => listCanvases(ctx, params),
|
|
166
|
+
get: (id) => getCanvas(ctx, id),
|
|
167
|
+
folders: () => listFolders(ctx),
|
|
168
|
+
teamProject: (id) => getTeamProject(ctx, id),
|
|
169
|
+
create: (input) => createCanvas(ctx, input),
|
|
170
|
+
remove: (ids, options) => removeCanvases(ctx, ids, options),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const LAUNCH_ARGS = [
|
|
2
|
+
'--disable-gpu',
|
|
3
|
+
'--disable-blink-features=AutomationControlled',
|
|
4
|
+
];
|
|
5
|
+
export const QUIET_STARTUP_ARGS = [
|
|
6
|
+
'--no-first-run',
|
|
7
|
+
'--no-default-browser-check',
|
|
8
|
+
'--disable-search-engine-choice-screen',
|
|
9
|
+
];
|
|
10
|
+
export const SANDBOX_ENV = 'SEAVIDEO_NO_SANDBOX';
|
|
11
|
+
export function sandboxDisabled(envMap) {
|
|
12
|
+
return envMap[SANDBOX_ENV] !== '0';
|
|
13
|
+
}
|
|
14
|
+
export const INSECURE_TLS_ENV = 'SEAVIDEO_INSECURE_TLS';
|
|
15
|
+
export const HEADFUL_ENV = 'SEAVIDEO_HEADFUL';
|
|
16
|
+
export function isHeadful(envMap) {
|
|
17
|
+
return envMap[HEADFUL_ENV] === '1';
|
|
18
|
+
}
|
|
19
|
+
export function launchArgsOf(envMap, headful = false) {
|
|
20
|
+
const args = [];
|
|
21
|
+
const wantSandboxDisabled = headful ? envMap[SANDBOX_ENV] === '1' : sandboxDisabled(envMap);
|
|
22
|
+
if (wantSandboxDisabled)
|
|
23
|
+
args.push('--no-sandbox');
|
|
24
|
+
else {
|
|
25
|
+
}
|
|
26
|
+
args.push(...LAUNCH_ARGS, ...QUIET_STARTUP_ARGS);
|
|
27
|
+
if (envMap[INSECURE_TLS_ENV] === '1')
|
|
28
|
+
args.push('--ignore-certificate-errors');
|
|
29
|
+
else {
|
|
30
|
+
}
|
|
31
|
+
return args;
|
|
32
|
+
}
|
|
33
|
+
export const DEFAULT_OPEN_TIMEOUT_MS = 90_000;
|
|
34
|
+
export const WAIT_TOOLS_EXPR = 'document.modelContext && document.modelContext.getTools().then(t => t.length > 0)';
|
|
35
|
+
export const READ_TOOLS_EXPR = `(async () => {
|
|
36
|
+
const mc = document.modelContext;
|
|
37
|
+
if (!mc) return [];
|
|
38
|
+
const tools = await mc.getTools();
|
|
39
|
+
return tools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }));
|
|
40
|
+
})()`;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { posix, win32 } from 'node:path';
|
|
2
|
+
const WINDOWS_FALLBACK_PREFIXES = [
|
|
3
|
+
'C:\\Program Files',
|
|
4
|
+
'C:\\Program Files (x86)',
|
|
5
|
+
'D:\\Program Files',
|
|
6
|
+
'D:\\Program Files (x86)',
|
|
7
|
+
];
|
|
8
|
+
export const WINDOWS_APP_PATH_KEY = 'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe';
|
|
9
|
+
const MACOS_CHROME_BUNDLE_ID = 'com.google.Chrome';
|
|
10
|
+
export async function windowsChromeCandidates(deps) {
|
|
11
|
+
const registered = await deps.readWindowsRegistry(WINDOWS_APP_PATH_KEY, '(Default)');
|
|
12
|
+
const guesses = [
|
|
13
|
+
deps.env['PROGRAMFILES'] === undefined
|
|
14
|
+
? ''
|
|
15
|
+
: win32.join(deps.env['PROGRAMFILES'], 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
16
|
+
deps.env['LOCALAPPDATA'] === undefined
|
|
17
|
+
? ''
|
|
18
|
+
: win32.join(deps.env['LOCALAPPDATA'], 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
19
|
+
deps.env['PROGRAMFILES(X86)'] === undefined
|
|
20
|
+
? ''
|
|
21
|
+
: win32.join(deps.env['PROGRAMFILES(X86)'], 'Google', 'Chrome', 'Application', 'chrome.exe'),
|
|
22
|
+
...WINDOWS_FALLBACK_PREFIXES.map((prefix) => win32.join(prefix, 'Google', 'Chrome', 'Application', 'chrome.exe')),
|
|
23
|
+
].filter((p) => p !== '');
|
|
24
|
+
return withRegistered(registered, guesses);
|
|
25
|
+
}
|
|
26
|
+
function withRegistered(registered, guesses) {
|
|
27
|
+
const ordered = registered === null ? [...guesses] : [registered, ...guesses];
|
|
28
|
+
return [...new Set(ordered)];
|
|
29
|
+
}
|
|
30
|
+
export async function macosChromeCandidates(deps) {
|
|
31
|
+
const roots = [posix.join('/Applications'), posix.join(deps.homeDir(), 'Applications')];
|
|
32
|
+
const found = [];
|
|
33
|
+
for (const root of roots) {
|
|
34
|
+
for (const name of await appNamesIn(deps, root)) {
|
|
35
|
+
if (/\.app$/iu.test(name)) {
|
|
36
|
+
const bundle = posix.join(root, name, 'Contents', 'Info.plist');
|
|
37
|
+
const binary = posix.join(root, name, 'Contents', 'MacOS', 'Google Chrome');
|
|
38
|
+
if (await hasBundleId(deps, bundle, MACOS_CHROME_BUNDLE_ID)) {
|
|
39
|
+
found.push(binary);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
async function appNamesIn(deps, root) {
|
|
51
|
+
let result;
|
|
52
|
+
try {
|
|
53
|
+
result = await deps.fs.readdir(root);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
result = [];
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
async function hasBundleId(deps, plistPath, bundleId) {
|
|
61
|
+
let result;
|
|
62
|
+
try {
|
|
63
|
+
const text = await deps.fs.readFile(plistPath, 'utf8');
|
|
64
|
+
result = text.includes(`<string>${bundleId}</string>`);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
result = false;
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
export function linuxChromeCandidates() {
|
|
72
|
+
return ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/opt/google/chrome/chrome'];
|
|
73
|
+
}
|
|
74
|
+
export async function chromeCandidates(deps) {
|
|
75
|
+
let result;
|
|
76
|
+
if (deps.platform === 'darwin') {
|
|
77
|
+
result = await macosChromeCandidates(deps);
|
|
78
|
+
}
|
|
79
|
+
else if (deps.platform === 'win32') {
|
|
80
|
+
result = await windowsChromeCandidates(deps);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
result = linuxChromeCandidates();
|
|
84
|
+
}
|
|
85
|
+
return result;
|
|
86
|
+
}
|
|
87
|
+
export async function findSystemChrome(deps) {
|
|
88
|
+
const candidates = await chromeCandidates(deps);
|
|
89
|
+
let found = null;
|
|
90
|
+
for (const candidate of candidates) {
|
|
91
|
+
if (found === null && (await isExecutable(deps, candidate))) {
|
|
92
|
+
found = candidate;
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return found;
|
|
98
|
+
}
|
|
99
|
+
async function isExecutable(deps, path) {
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
await deps.fs.stat(path);
|
|
103
|
+
result = true;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
result = false;
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { withRetry } from "../fs-retry.js";
|
|
4
|
+
import { t } from "../i18n.js";
|
|
5
|
+
import { launchArgsOf } from "./browser.js";
|
|
6
|
+
import { terminateCommand } from "../deps.js";
|
|
7
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60_000;
|
|
8
|
+
export const WATCH_INTERVAL_MS = 60_000;
|
|
9
|
+
export const DEVTOOLS_PORT_FILE = 'DevToolsActivePort';
|
|
10
|
+
export const KEEPER_BOOT_PREFIX = 'keeper-boot-';
|
|
11
|
+
export function keeperBootName() {
|
|
12
|
+
return `${KEEPER_BOOT_PREFIX}${Math.random().toString(36).slice(2, 10)}.json`;
|
|
13
|
+
}
|
|
14
|
+
export const PORT_WAIT_MS = 15_000;
|
|
15
|
+
export const PORT_POLL_MS = 100;
|
|
16
|
+
export const SESSION_BOOT_MS = 240_000;
|
|
17
|
+
export function isIdleExpired(record, now, idleMs = DEFAULT_IDLE_TIMEOUT_MS) {
|
|
18
|
+
return now.getTime() - Date.parse(record.usedAt) > idleMs;
|
|
19
|
+
}
|
|
20
|
+
export async function spawnCanvasBrowser(executablePath, profileDir, sessionFile, nodePath, deps, options = {}) {
|
|
21
|
+
const headful = options.headful === true;
|
|
22
|
+
const bootName = keeperBootName();
|
|
23
|
+
const bootFile = join(profileDir, bootName);
|
|
24
|
+
try {
|
|
25
|
+
await withRetry(deps, () => deps.fs.rm(profileDir, { recursive: true, force: true }));
|
|
26
|
+
await deps.fs.mkdir(profileDir, { recursive: true, mode: 0o700 });
|
|
27
|
+
const args = [
|
|
28
|
+
...(headful ? [] : ['--headless=shell']),
|
|
29
|
+
...launchArgsOf(deps.env, headful),
|
|
30
|
+
'--remote-debugging-port=0',
|
|
31
|
+
`--user-data-dir=${profileDir}`,
|
|
32
|
+
'about:blank',
|
|
33
|
+
];
|
|
34
|
+
startWatcher({
|
|
35
|
+
executablePath,
|
|
36
|
+
args,
|
|
37
|
+
profileDir,
|
|
38
|
+
sessionFile,
|
|
39
|
+
bootName,
|
|
40
|
+
idleMs: DEFAULT_IDLE_TIMEOUT_MS,
|
|
41
|
+
nodePath,
|
|
42
|
+
platform: deps.platform,
|
|
43
|
+
deps,
|
|
44
|
+
});
|
|
45
|
+
return await waitForBoot(bootFile, args, deps);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (err instanceof CliError)
|
|
49
|
+
throw err;
|
|
50
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
51
|
+
detail: err.code ?? (err instanceof Error ? err.name : String(err)),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function waitForBoot(bootFile, args, deps) {
|
|
56
|
+
const waited = Math.ceil(PORT_WAIT_MS / PORT_POLL_MS);
|
|
57
|
+
for (let i = 0; i < waited; i += 1) {
|
|
58
|
+
const boot = await readBootFile(bootFile, deps);
|
|
59
|
+
if (boot !== null && 'error' in boot) {
|
|
60
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
61
|
+
detail: boot.error,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (boot !== null)
|
|
65
|
+
return { pid: boot.pid, port: boot.port, args };
|
|
66
|
+
await deps.sleep(PORT_POLL_MS);
|
|
67
|
+
}
|
|
68
|
+
throw new CliError('config', t('canvas.engineStartFailed', {}, deps.env), {
|
|
69
|
+
detail: t('canvas.daemonNoPort', { ms: PORT_WAIT_MS }, deps.env),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
async function readBootFile(bootFile, deps) {
|
|
73
|
+
let result;
|
|
74
|
+
try {
|
|
75
|
+
const raw = JSON.parse(await deps.fs.readFile(bootFile, 'utf8'));
|
|
76
|
+
const pid = raw['pid'];
|
|
77
|
+
const port = raw['port'];
|
|
78
|
+
const error = raw['error'];
|
|
79
|
+
if (typeof error === 'string' && error !== '') {
|
|
80
|
+
result = { error };
|
|
81
|
+
}
|
|
82
|
+
else if (typeof pid === 'number' &&
|
|
83
|
+
Number.isInteger(pid) &&
|
|
84
|
+
pid > 0 &&
|
|
85
|
+
typeof port === 'number' &&
|
|
86
|
+
Number.isInteger(port) &&
|
|
87
|
+
port > 0) {
|
|
88
|
+
result = { pid, port };
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
result = null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
result = null;
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
export async function sessionAlive(record, deps) {
|
|
100
|
+
let result;
|
|
101
|
+
if (!deps.processAlive(record.pid)) {
|
|
102
|
+
result = false;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
try {
|
|
106
|
+
const resp = await deps.fetch(`http://127.0.0.1:${record.port}/json/version`);
|
|
107
|
+
result = resp.ok;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
result = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
export const WATCHER_SCRIPT = `
|
|
116
|
+
const fs = require('node:fs');
|
|
117
|
+
const path = require('node:path');
|
|
118
|
+
const { spawn } = require('node:child_process');
|
|
119
|
+
const cfg = JSON.parse(process.argv[1]);
|
|
120
|
+
const bootFile = path.join(cfg.profileDir, cfg.bootFile);
|
|
121
|
+
const portFile = path.join(cfg.profileDir, cfg.portFile);
|
|
122
|
+
|
|
123
|
+
// 非 detached:Windows 上 detached 会让 windowsHide 失效,每个 console 子进程
|
|
124
|
+
// 都新开一个可见窗口(实测 3 个)。父进程是看门狗,够浏览器活过 CLI 退出。
|
|
125
|
+
const child = spawn(cfg.exe, cfg.args, { windowsHide: true, stdio: 'ignore' });
|
|
126
|
+
child.unref();
|
|
127
|
+
|
|
128
|
+
// spawn 的可执行文件不存在 / 不可执行时,Node 不在同步阶段抛,而是异步 emit
|
|
129
|
+
// 'error';没有监听器会把看门狗整个打崩(stdio 是 ignore,看起来就是无声无息)。
|
|
130
|
+
// 那种情况下 CLI 会白等 PORT_WAIT_MS 才报含糊的「没等到端口」。这里把原因写进
|
|
131
|
+
// 引导文件,CLI 读到 error 字段就立刻报真因。
|
|
132
|
+
child.on('error', function (err) {
|
|
133
|
+
try { fs.writeFileSync(bootFile, JSON.stringify({ error: String(err && err.code || err) })); } catch {}
|
|
134
|
+
process.exit(1);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// 回收浏览器。看门狗现在是闲置超时 / 记录被删 / pid 被接管三条路的**主要**回收者,
|
|
138
|
+
// 所以必须连子树一起收:Windows 上 process.kill 只杀主进程,gpu / renderer 子进程
|
|
139
|
+
// 可能残留(这正是 deps.terminate 用 taskkill /T 的理由)。
|
|
140
|
+
//
|
|
141
|
+
// 平台分支不在脚本里写:内联脚本不能读 process.platform(PF001 要求平台差异只在
|
|
142
|
+
// deps.ts 判定),所以 CLi 侧用 terminateCommand() 算出「怎么杀」,经 cfg.kill 传进来。
|
|
143
|
+
function die(code) {
|
|
144
|
+
try {
|
|
145
|
+
if (cfg.kill.kind === 'command') {
|
|
146
|
+
// argsTemplate 形如 ['/PID', '{pid}', '/T', '/F']
|
|
147
|
+
const args = cfg.kill.argsTemplate.map((a) => (a === '{pid}' ? String(child.pid) : a));
|
|
148
|
+
require('node:child_process').execFileSync(cfg.kill.command, args, { stdio: 'ignore' });
|
|
149
|
+
} else {
|
|
150
|
+
process.kill(child.pid, cfg.kill.signal);
|
|
151
|
+
}
|
|
152
|
+
} catch {}
|
|
153
|
+
process.exit(code);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 等浏览器的 DevTools 端口,就绪后把 pid/port 写给 CLI。
|
|
157
|
+
// 超时就杀掉浏览器退出:CLI 那边等不到引导文件也会报错,别留半死进程。
|
|
158
|
+
const deadline = Date.now() + cfg.portWaitMs;
|
|
159
|
+
(function poll() {
|
|
160
|
+
let port = 0;
|
|
161
|
+
try {
|
|
162
|
+
port = Number(String(fs.readFileSync(portFile, 'utf8')).split('\\n')[0].trim());
|
|
163
|
+
} catch {}
|
|
164
|
+
if (Number.isInteger(port) && port > 0) {
|
|
165
|
+
try {
|
|
166
|
+
fs.writeFileSync(bootFile, JSON.stringify({ pid: child.pid, port }));
|
|
167
|
+
} catch {}
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (Date.now() > deadline) die(1);
|
|
171
|
+
else setTimeout(poll, cfg.portPollMs);
|
|
172
|
+
})();
|
|
173
|
+
|
|
174
|
+
// 浏览器自己没了(崩溃 / 被外部杀掉):看门狗跟着退,避免留下一个永远
|
|
175
|
+
// 盯着不存在的进程的僵尸。
|
|
176
|
+
//
|
|
177
|
+
// 连续失败两次才算数:spawn 之后的那一小段时间里,子进程可能还没来得及
|
|
178
|
+
// 被系统登记好,「探一次不在」会误判成崩溃,把看门狗提前打死——实测这样
|
|
179
|
+
// 引导文件永远写不出来。所以要求连续两次探不到才退出。
|
|
180
|
+
//
|
|
181
|
+
// 探活间隔比记录轮询短得多:记录轮询 60 秒是给「闲置判断」用的精度,
|
|
182
|
+
// 而「子进程已经没了」应当尽快发现——否则一次失败的 canvas use 会留下
|
|
183
|
+
// 一个空转的 node 进程。下面的 Math.min 让它最多两秒一探(连续两次才退出,
|
|
184
|
+
// 所以最坏约四秒),而不是跟着 60 秒的记录轮询一起等。
|
|
185
|
+
let missingTicks = 0;
|
|
186
|
+
const aliveTimer = setInterval(function () {
|
|
187
|
+
try {
|
|
188
|
+
process.kill(child.pid, 0);
|
|
189
|
+
missingTicks = 0;
|
|
190
|
+
} catch {
|
|
191
|
+
missingTicks += 1;
|
|
192
|
+
if (missingTicks >= 2) process.exit(0);
|
|
193
|
+
}
|
|
194
|
+
}, Math.min(cfg.intervalMs, 2000));
|
|
195
|
+
|
|
196
|
+
// 记录从「还没写」等到「等太久了」的门槛:CLI 打开页面有一个默认超时
|
|
197
|
+
// (90s),超过它还没写记录说明这条会话不会成立了,看门狗不该无限期占着浏览器。
|
|
198
|
+
let seenRecord = false;
|
|
199
|
+
const bootDeadline = Date.now() + cfg.sessionBootMs;
|
|
200
|
+
|
|
201
|
+
setInterval(function () {
|
|
202
|
+
let text;
|
|
203
|
+
try { text = fs.readFileSync(cfg.sessionFile, 'utf8'); }
|
|
204
|
+
catch {
|
|
205
|
+
// 记录还没出现是**启动中**的正常状态:看门狗先起浏览器,CLI 打开页面
|
|
206
|
+
// 成功后才写记录。只有「曾经见过记录、现在没了」才等于被显式收掉。
|
|
207
|
+
// 旧版没有这层区分,因为它是在记录写完之后才起的;现在它必须先起。
|
|
208
|
+
if (seenRecord) { clearInterval(aliveTimer); die(0); }
|
|
209
|
+
else if (Date.now() > bootDeadline) { clearInterval(aliveTimer); die(0); }
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
let rec;
|
|
213
|
+
try {
|
|
214
|
+
rec = JSON.parse(text);
|
|
215
|
+
if (typeof rec.usedAt !== 'string' || Number.isNaN(Date.parse(rec.usedAt))) throw new Error('bad');
|
|
216
|
+
} catch {
|
|
217
|
+
// 记录存在却解析不了:原子写(tmp + rename)让它本该不会发生,
|
|
218
|
+
// 但它没有别的出口——直接 return 就是「看门狗永远跑、浏览器永远不回收」。
|
|
219
|
+
// 曾经成功读过(seenRecord)说明会话已成立,现在读不出就等于记录没了;
|
|
220
|
+
// 从未读过则说明这条会话还没成立,按启动超时处理。
|
|
221
|
+
if (seenRecord || Date.now() > bootDeadline) { clearInterval(aliveTimer); die(0); }
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
seenRecord = true;
|
|
225
|
+
// 记录里的 pid 不是自己起的那个 → 新会话已接管,这个浏览器已经过时。
|
|
226
|
+
//
|
|
227
|
+
// 必须用 die() 主动杀掉子进程,不能只 process.exit(0):Windows 上父进程退出
|
|
228
|
+
// 会带走同控制台组的子进程(实测如此),但这一点**不能依赖**——从没有控制台
|
|
229
|
+
// 的环境(服务、CI)启动时并不成立,POSIX 上更是根本不会发生。只 exit 的话,
|
|
230
|
+
// 这个非 detached 的浏览器就成了永久孤儿,而下一次 canvas use 只 terminate
|
|
231
|
+
// 「当时的」记录 pid,永远不会回收它。
|
|
232
|
+
if (rec.pid !== child.pid) { clearInterval(aliveTimer); die(0); }
|
|
233
|
+
if (Date.now() - Date.parse(rec.usedAt) > cfg.idleMs) {
|
|
234
|
+
try { fs.unlinkSync(cfg.sessionFile); } catch {}
|
|
235
|
+
clearInterval(aliveTimer);
|
|
236
|
+
die(0);
|
|
237
|
+
}
|
|
238
|
+
}, cfg.intervalMs);
|
|
239
|
+
`;
|
|
240
|
+
export function startWatcher(options) {
|
|
241
|
+
const spec = terminateCommand(options.platform, 0);
|
|
242
|
+
const kill = spec.kind === 'command'
|
|
243
|
+
? {
|
|
244
|
+
kind: 'command',
|
|
245
|
+
command: spec.command,
|
|
246
|
+
argsTemplate: spec.args.map((a) => (a === '0' ? '{pid}' : a)),
|
|
247
|
+
}
|
|
248
|
+
: { kind: 'signal', signal: spec.signal };
|
|
249
|
+
const config = JSON.stringify({
|
|
250
|
+
exe: options.executablePath,
|
|
251
|
+
args: options.args,
|
|
252
|
+
profileDir: options.profileDir,
|
|
253
|
+
sessionFile: options.sessionFile,
|
|
254
|
+
bootFile: options.bootName,
|
|
255
|
+
portFile: DEVTOOLS_PORT_FILE,
|
|
256
|
+
idleMs: options.idleMs,
|
|
257
|
+
intervalMs: WATCH_INTERVAL_MS,
|
|
258
|
+
portWaitMs: PORT_WAIT_MS,
|
|
259
|
+
portPollMs: PORT_POLL_MS,
|
|
260
|
+
sessionBootMs: SESSION_BOOT_MS,
|
|
261
|
+
kill,
|
|
262
|
+
});
|
|
263
|
+
options.deps.spawnDetached(options.nodePath, ['-e', WATCHER_SCRIPT, config]);
|
|
264
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { BrowserPlatform } from '@puppeteer/browsers';
|
|
2
|
+
import { t } from "../i18n.js";
|
|
3
|
+
import { ENGINE_BROWSER, engineCacheDir } from "./engine.js";
|
|
4
|
+
export const MIRROR_BASE_URL = 'https://registry.npmmirror.com/-/binary/chrome-for-testing';
|
|
5
|
+
export const ENGINE_BUILD_ID = '156.0.8078.80';
|
|
6
|
+
export function browserPlatformOf(platform, arch) {
|
|
7
|
+
const arm = arch === 'arm64';
|
|
8
|
+
let result;
|
|
9
|
+
switch (platform) {
|
|
10
|
+
case 'darwin':
|
|
11
|
+
result = arm ? BrowserPlatform.MAC_ARM : BrowserPlatform.MAC;
|
|
12
|
+
break;
|
|
13
|
+
case 'win32':
|
|
14
|
+
result = BrowserPlatform.WIN64;
|
|
15
|
+
break;
|
|
16
|
+
default:
|
|
17
|
+
result = arm ? BrowserPlatform.LINUX_ARM : BrowserPlatform.LINUX;
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
export async function downloadCanvasEngine(deps, options = {}) {
|
|
22
|
+
const downloadOptions = {
|
|
23
|
+
browser: ENGINE_BROWSER,
|
|
24
|
+
buildId: ENGINE_BUILD_ID,
|
|
25
|
+
platform: browserPlatformOf(deps.platform, deps.arch),
|
|
26
|
+
cacheDir: engineCacheDir(deps),
|
|
27
|
+
baseUrl: options.baseUrl ?? MIRROR_BASE_URL,
|
|
28
|
+
};
|
|
29
|
+
deps.stderr(`${t('engine.downloading', { baseUrl: downloadOptions.baseUrl }, deps.env)}\n`);
|
|
30
|
+
let result;
|
|
31
|
+
try {
|
|
32
|
+
const path = await deps.download(downloadOptions);
|
|
33
|
+
result = { ok: true, path, version: ENGINE_BUILD_ID };
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
result = { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
export function makeEngineDownloader() {
|
|
41
|
+
return async (options) => {
|
|
42
|
+
const { install } = await import('@puppeteer/browsers');
|
|
43
|
+
const installed = await install(options);
|
|
44
|
+
return installed.executablePath;
|
|
45
|
+
};
|
|
46
|
+
}
|