yukari-dsh-plugin 0.0.0-stage → 0.7.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.
- package/LICENSE +21 -0
- package/README.md +17 -2
- package/client.js +8340 -0
- package/cordis.patch.yml +95 -0
- package/host/browser/index.js +397 -0
- package/host/browser/lib/browser.js +885 -0
- package/host/browser/lib/cdp.js +302 -0
- package/host/browser/lib/libraries.js +309 -0
- package/host/browser/lib/page-scripts.js +243 -0
- package/host/browser/lib/runtime.js +351 -0
- package/host/browser/lib/url-guard.js +122 -0
- package/host/browser/locale/en.json +6 -0
- package/host/browser/locale/zh.json +6 -0
- package/host/chats/index.js +254 -0
- package/host/chats/lib/admin.js +893 -0
- package/host/chats/lib/cleanup.js +272 -0
- package/host/chats/lib/paths.js +108 -0
- package/host/chats/lib/preview.js +74 -0
- package/host/chats/locale/en.json +6 -0
- package/host/chats/locale/zh.json +6 -0
- package/host/files/index.js +403 -0
- package/host/files/locale/en.json +6 -0
- package/host/files/locale/zh.json +6 -0
- package/host/github/index.js +121 -0
- package/host/github/lib/api.js +310 -0
- package/host/github/lib/atomic.js +42 -0
- package/host/github/lib/controller.js +450 -0
- package/host/github/lib/git.js +389 -0
- package/host/github/lib/redact.js +22 -0
- package/host/github/lib/signing.js +124 -0
- package/host/github/lib/store.js +181 -0
- package/host/github/locale/en.json +6 -0
- package/host/github/locale/zh.json +6 -0
- package/host/presets/index.js +450 -0
- package/host/presets/lib/definition.js +267 -0
- package/host/presets/lib/sources.js +278 -0
- package/host/presets/lib/store.js +136 -0
- package/host/presets/locale/en.json +6 -0
- package/host/presets/locale/zh.json +6 -0
- package/host/proxy/index.js +236 -0
- package/host/proxy/lib/controller.js +1151 -0
- package/host/proxy/lib/egress.js +120 -0
- package/host/proxy/lib/local-proxy.js +422 -0
- package/host/proxy/lib/shadowsocks.js +335 -0
- package/host/proxy/lib/ss-uri.js +501 -0
- package/host/proxy/lib/subscriptions.js +140 -0
- package/host/proxy/locale/en.json +6 -0
- package/host/proxy/locale/zh.json +6 -0
- package/host/purge/index.js +538 -0
- package/host/purge/lib/preset.js +140 -0
- package/host/purge/lib/prompts.js +95 -0
- package/host/purge/lib/retry-gate.js +97 -0
- package/host/purge/lib/rewriter.js +322 -0
- package/host/purge/lib/settings.js +54 -0
- package/host/purge/lib/stream-retry.js +255 -0
- package/host/purge/locale/en.json +6 -0
- package/host/purge/locale/zh.json +6 -0
- package/host/purge/presets/unrestricted/agent.cordis.yml +273 -0
- package/host/purge/presets/unrestricted/preset.json +75 -0
- package/host/purge/presets/unrestricted/preset.yml +3 -0
- package/host/rewind/index.js +127 -0
- package/host/rewind/lib/controller.js +449 -0
- package/host/rewind/lib/marker.js +53 -0
- package/host/rewind/lib/safe-path.js +47 -0
- package/host/rewind/lib/store.js +585 -0
- package/host/rewind/lib/surface.js +108 -0
- package/host/rewind/locale/en.json +6 -0
- package/host/rewind/locale/zh.json +6 -0
- package/host/rules/index.js +624 -0
- package/host/rules/lib/paths.js +87 -0
- package/host/rules/lib/render.js +92 -0
- package/host/rules/lib/scope.js +146 -0
- package/host/rules/lib/settings.js +55 -0
- package/host/rules/lib/store.js +222 -0
- package/host/rules/locale/en.json +6 -0
- package/host/rules/locale/zh.json +6 -0
- package/host/runtime/index.js +577 -0
- package/host/runtime/lib/npm.js +293 -0
- package/host/runtime/lib/restart.js +105 -0
- package/host/runtime/lib/update-guard.js +70 -0
- package/host/runtime/lib/versions.js +188 -0
- package/host/runtime/locale/en.json +6 -0
- package/host/runtime/locale/zh.json +6 -0
- package/host/shared/busy.js +40 -0
- package/host/shared/home.js +27 -0
- package/host/shared/http.js +159 -0
- package/host/shared/migrate.js +60 -0
- package/host/shared/mounted.js +54 -0
- package/host/shared/zip-writer.js +319 -0
- package/host/shared/zip.js +180 -0
- package/host/sites/index.js +258 -0
- package/host/sites/lib/sites.js +630 -0
- package/host/sites/locale/en.json +6 -0
- package/host/sites/locale/zh.json +6 -0
- package/host/skills/index.js +176 -0
- package/host/skills/lib/frontmatter.js +149 -0
- package/host/skills/lib/library.js +408 -0
- package/host/skills/lib/upload.js +115 -0
- package/host/skills/locale/en.json +6 -0
- package/host/skills/locale/zh.json +6 -0
- package/icon.png +0 -0
- package/index.js +702 -0
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +113 -4
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-page JavaScript the browser tools evaluate through `Runtime.evaluate`.
|
|
3
|
+
*
|
|
4
|
+
* Everything here is a string so it can cross the protocol boundary; the
|
|
5
|
+
* shared prelude keeps element collection, labelling, and target resolution
|
|
6
|
+
* identical between the snapshot and the action tools.
|
|
7
|
+
* @module @local/browser-control/page-scripts
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Selectors for the interactive elements a snapshot advertises. */
|
|
11
|
+
const INTERACTIVE_SELECTOR = [
|
|
12
|
+
'a[href]',
|
|
13
|
+
'area[href]',
|
|
14
|
+
'button',
|
|
15
|
+
'input:not([type="hidden"])',
|
|
16
|
+
'select',
|
|
17
|
+
'textarea',
|
|
18
|
+
'summary',
|
|
19
|
+
'label[for]',
|
|
20
|
+
'[role="button"]',
|
|
21
|
+
'[role="link"]',
|
|
22
|
+
'[role="tab"]',
|
|
23
|
+
'[role="checkbox"]',
|
|
24
|
+
'[role="radio"]',
|
|
25
|
+
'[role="switch"]',
|
|
26
|
+
'[role="combobox"]',
|
|
27
|
+
'[role="menuitem"]',
|
|
28
|
+
'[role="option"]',
|
|
29
|
+
'[role="searchbox"]',
|
|
30
|
+
'[role="textbox"]',
|
|
31
|
+
'[role="spinbutton"]',
|
|
32
|
+
'[contenteditable=""]',
|
|
33
|
+
'[contenteditable="true"]',
|
|
34
|
+
'[onclick]',
|
|
35
|
+
].join(',')
|
|
36
|
+
|
|
37
|
+
/** Helpers shared by every expression; `elementIndex` makes refs stable. */
|
|
38
|
+
const PRELUDE = `
|
|
39
|
+
const SELECTOR = ${JSON.stringify(INTERACTIVE_SELECTOR)};
|
|
40
|
+
const clean = (value) => String(value == null ? '' : value).replace(/\\s+/g, ' ').trim();
|
|
41
|
+
const isVisible = (el) => {
|
|
42
|
+
const rect = el.getBoundingClientRect();
|
|
43
|
+
if (rect.width <= 0 || rect.height <= 0) return false;
|
|
44
|
+
const style = getComputedStyle(el);
|
|
45
|
+
return style.visibility !== 'hidden' && style.display !== 'none' && style.opacity !== '0';
|
|
46
|
+
};
|
|
47
|
+
const textOf = (el) => clean(el.innerText || el.textContent || '');
|
|
48
|
+
// 密码与令牌字段的原文一旦进入快照,就会写进模型上下文和会话日志,
|
|
49
|
+
// 所以在页面里就地掩码,而不是等宿主侧再按字段名过滤一遍。
|
|
50
|
+
const SENSITIVE_FIELD = /(pass(?:word|wd|phrase)|secret|token|api[-_]?key|credential)/iu;
|
|
51
|
+
const sensitiveField = (el) => {
|
|
52
|
+
const tag = el.tagName.toLowerCase();
|
|
53
|
+
if (tag === 'input' && String(el.type || el.getAttribute('type') || '').toLowerCase() === 'password') return true;
|
|
54
|
+
const autocomplete = clean(el.getAttribute('autocomplete')).toLowerCase();
|
|
55
|
+
if (/^cc-|(^|\\s)(current-password|new-password|one-time-code)($|\\s)/u.test(autocomplete)) return true;
|
|
56
|
+
return SENSITIVE_FIELD.test(clean([el.getAttribute('name'), el.getAttribute('id')].filter(Boolean).join(' ')));
|
|
57
|
+
};
|
|
58
|
+
const displayValue = (el, value, limit) => {
|
|
59
|
+
if (!value) return undefined;
|
|
60
|
+
return sensitiveField(el) ? '••••' : value.slice(0, limit);
|
|
61
|
+
};
|
|
62
|
+
const nameOf = (el) => {
|
|
63
|
+
const tag = el.tagName.toLowerCase();
|
|
64
|
+
const labelledBy = clean(el.getAttribute('aria-labelledby'))
|
|
65
|
+
? clean(el.getAttribute('aria-labelledby')).split(/\\s+/).map((id) => {
|
|
66
|
+
const target = document.getElementById(id);
|
|
67
|
+
return target ? textOf(target) : '';
|
|
68
|
+
}).join(' ')
|
|
69
|
+
: '';
|
|
70
|
+
const candidates = [
|
|
71
|
+
clean(el.getAttribute('aria-label')),
|
|
72
|
+
labelledBy,
|
|
73
|
+
clean(el.getAttribute('placeholder')),
|
|
74
|
+
clean(el.getAttribute('title')),
|
|
75
|
+
clean(el.getAttribute('alt')),
|
|
76
|
+
tag === 'input' && /^(button|submit|reset)$/i.test(el.type || '') ? clean(el.value) : '',
|
|
77
|
+
textOf(el),
|
|
78
|
+
tag === 'input' || tag === 'textarea' ? (sensitiveField(el) ? '' : clean(el.value)) : '',
|
|
79
|
+
clean(el.getAttribute('name')),
|
|
80
|
+
];
|
|
81
|
+
for (const candidate of candidates) {
|
|
82
|
+
if (candidate) return candidate.slice(0, 140);
|
|
83
|
+
}
|
|
84
|
+
return '';
|
|
85
|
+
};
|
|
86
|
+
const collect = () => Array.from(document.querySelectorAll(SELECTOR));
|
|
87
|
+
const describe = (el, index) => {
|
|
88
|
+
const tag = el.tagName.toLowerCase();
|
|
89
|
+
const value = typeof el.value === 'string' ? el.value : '';
|
|
90
|
+
const rect = el.getBoundingClientRect();
|
|
91
|
+
return {
|
|
92
|
+
ref: 'e' + index,
|
|
93
|
+
tag,
|
|
94
|
+
role: clean(el.getAttribute('role')) || undefined,
|
|
95
|
+
type: clean(el.getAttribute('type')) || undefined,
|
|
96
|
+
name: nameOf(el),
|
|
97
|
+
value: displayValue(el, value, 120),
|
|
98
|
+
href: clean(el.getAttribute('href')) || undefined,
|
|
99
|
+
disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true',
|
|
100
|
+
checked: el.checked === true || el.getAttribute('aria-checked') === 'true' || undefined,
|
|
101
|
+
visible: isVisible(el),
|
|
102
|
+
box: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) },
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
const resolveTarget = (target) => {
|
|
106
|
+
if (!target) return null;
|
|
107
|
+
const list = collect();
|
|
108
|
+
if (target.ref) {
|
|
109
|
+
const index = Number.parseInt(String(target.ref).replace(/^e/i, ''), 10);
|
|
110
|
+
if (!Number.isInteger(index) || index < 0 || index >= list.length) return null;
|
|
111
|
+
return list[index];
|
|
112
|
+
}
|
|
113
|
+
if (target.selector) {
|
|
114
|
+
try {
|
|
115
|
+
return document.querySelector(target.selector);
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (target.text) {
|
|
121
|
+
const needle = String(target.text).toLowerCase();
|
|
122
|
+
const byText = list.find((el) => textOf(el).toLowerCase().includes(needle));
|
|
123
|
+
if (byText) return byText;
|
|
124
|
+
return list.find((el) => nameOf(el).toLowerCase().includes(needle)) || null;
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
};
|
|
128
|
+
const centerOf = (el) => {
|
|
129
|
+
el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
130
|
+
const rect = el.getBoundingClientRect();
|
|
131
|
+
return {
|
|
132
|
+
x: Math.round(rect.x + rect.width / 2),
|
|
133
|
+
y: Math.round(rect.y + rect.height / 2),
|
|
134
|
+
inside: rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || 0) && rect.right <= (window.innerWidth || 0),
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
const describeTarget = (el) => ({ tag: el.tagName.toLowerCase(), name: nameOf(el), text: textOf(el).slice(0, 80) });
|
|
138
|
+
`
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Build a report of the current page: address, readable text, and the
|
|
142
|
+
* interactive elements with stable `e<n>` refs.
|
|
143
|
+
* @param options - text and element caps.
|
|
144
|
+
* @returns an evaluable expression.
|
|
145
|
+
*/
|
|
146
|
+
export function snapshotExpression(options = {}) {
|
|
147
|
+
const maxText = options.maxText ?? 12000
|
|
148
|
+
const maxElements = options.maxElements ?? 120
|
|
149
|
+
return `(() => {
|
|
150
|
+
${PRELUDE}
|
|
151
|
+
const maxText = ${JSON.stringify(maxText)};
|
|
152
|
+
const maxElements = ${JSON.stringify(maxElements)};
|
|
153
|
+
const all = collect();
|
|
154
|
+
const elements = all.map(describe).filter((entry) => entry.visible && (entry.name || entry.tag !== 'a')).slice(0, maxElements);
|
|
155
|
+
const text = document.body ? (document.body.innerText || document.body.textContent || '') : '';
|
|
156
|
+
const normalized = clean(text);
|
|
157
|
+
const selection = window.getSelection ? clean(String(window.getSelection())) : '';
|
|
158
|
+
return {
|
|
159
|
+
url: location.href,
|
|
160
|
+
title: document.title,
|
|
161
|
+
readyState: document.readyState,
|
|
162
|
+
text: normalized.slice(0, maxText),
|
|
163
|
+
textTruncated: normalized.length > maxText,
|
|
164
|
+
textLength: normalized.length,
|
|
165
|
+
selection: selection.slice(0, 400) || undefined,
|
|
166
|
+
scroll: { y: Math.round(window.scrollY), height: Math.round(document.documentElement.scrollHeight), viewport: Math.round(window.innerHeight) },
|
|
167
|
+
elements,
|
|
168
|
+
elementCount: all.length,
|
|
169
|
+
forms: Array.from(document.querySelectorAll('input,textarea,select')).length,
|
|
170
|
+
};
|
|
171
|
+
})()`
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Resolve a target and report where to click it.
|
|
176
|
+
* @param target - `{ ref }`, `{ selector }`, or `{ text }`.
|
|
177
|
+
* @returns an evaluable expression.
|
|
178
|
+
*/
|
|
179
|
+
export function resolveExpression(target) {
|
|
180
|
+
return `(() => {
|
|
181
|
+
${PRELUDE}
|
|
182
|
+
const el = resolveTarget(${JSON.stringify(target)});
|
|
183
|
+
if (!el) return { found: false };
|
|
184
|
+
const center = centerOf(el);
|
|
185
|
+
return { found: true, ...describeTarget(el), ...center, disabled: el.disabled === true, value: displayValue(el, typeof el.value === 'string' ? el.value : '', 200) };
|
|
186
|
+
})()`
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Focus and clear a field before text is inserted by the protocol.
|
|
191
|
+
* @param target - `{ ref }`, `{ selector }`, or `{ text }`.
|
|
192
|
+
* @returns an evaluable expression.
|
|
193
|
+
*/
|
|
194
|
+
export function focusExpression(target) {
|
|
195
|
+
return `(() => {
|
|
196
|
+
${PRELUDE}
|
|
197
|
+
const el = resolveTarget(${JSON.stringify(target)});
|
|
198
|
+
if (!el) return { found: false };
|
|
199
|
+
el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
|
|
200
|
+
if (typeof el.focus === 'function') el.focus();
|
|
201
|
+
const editable = el.isContentEditable === true || /^(input|textarea)$/i.test(el.tagName);
|
|
202
|
+
if (el.isContentEditable) {
|
|
203
|
+
const range = document.createRange();
|
|
204
|
+
range.selectNodeContents(el);
|
|
205
|
+
const selection = window.getSelection();
|
|
206
|
+
selection.removeAllRanges();
|
|
207
|
+
selection.addRange(range);
|
|
208
|
+
} else if (editable) {
|
|
209
|
+
const setter = Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value');
|
|
210
|
+
if (setter && setter.set) setter.set.call(el, ''); else el.value = '';
|
|
211
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
212
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
213
|
+
}
|
|
214
|
+
return { found: true, ...describeTarget(el), editable: !!editable || el.isContentEditable === true, readOnly: el.readOnly === true || el.disabled === true };
|
|
215
|
+
})()`
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Read back the value the page currently holds for a target.
|
|
220
|
+
* @param target - `{ ref }`, `{ selector }`, or `{ text }`.
|
|
221
|
+
* @returns an evaluable expression.
|
|
222
|
+
*/
|
|
223
|
+
export function valueExpression(target) {
|
|
224
|
+
return `(() => {
|
|
225
|
+
${PRELUDE}
|
|
226
|
+
const el = resolveTarget(${JSON.stringify(target)});
|
|
227
|
+
if (!el) return { found: false };
|
|
228
|
+
const raw = typeof el.value === 'string' ? el.value : textOf(el).slice(0, 400);
|
|
229
|
+
return {
|
|
230
|
+
found: true,
|
|
231
|
+
value: sensitiveField(el) ? (raw ? '••••' : undefined) : raw,
|
|
232
|
+
checked: el.checked === true || undefined,
|
|
233
|
+
};
|
|
234
|
+
})()`
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Move the viewport by wheel deltas. */
|
|
238
|
+
export function scrollExpression() {
|
|
239
|
+
return `(() => {
|
|
240
|
+
${PRELUDE}
|
|
241
|
+
return { y: Math.round(window.scrollY), height: Math.round(document.documentElement.scrollHeight), viewport: Math.round(window.innerHeight) };
|
|
242
|
+
})()`
|
|
243
|
+
}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Automatic Chrome for Testing provisioning.
|
|
3
|
+
*
|
|
4
|
+
* Only the official Chrome metadata and storage hosts are contacted. Downloads
|
|
5
|
+
* live in DSH_HOME, are bounded and time-limited, and become visible through a
|
|
6
|
+
* same-directory rename only after extraction and executable verification.
|
|
7
|
+
*/
|
|
8
|
+
import { constants, createWriteStream } from 'node:fs'
|
|
9
|
+
import { access, chmod, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
10
|
+
import { homedir } from 'node:os'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { Readable, Transform } from 'node:stream'
|
|
13
|
+
import { pipeline } from 'node:stream/promises'
|
|
14
|
+
import { execFile } from 'node:child_process'
|
|
15
|
+
import { promisify } from 'node:util'
|
|
16
|
+
import { extractZipArchive } from '../../shared/zip.js'
|
|
17
|
+
import {
|
|
18
|
+
installCommand, installRuntimeLibraries, libraryEnvironment, missingLibraries, packagesFor,
|
|
19
|
+
} from './libraries.js'
|
|
20
|
+
|
|
21
|
+
export { installCommand, libraryEnvironment, missingLibraries, packagesFor }
|
|
22
|
+
|
|
23
|
+
export const METADATA_URL = 'https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json'
|
|
24
|
+
const MAX_METADATA_BYTES = 8 * 1024 * 1024
|
|
25
|
+
const MAX_ARCHIVE_BYTES = 512 * 1024 * 1024
|
|
26
|
+
const execFileAsync = promisify(execFile)
|
|
27
|
+
|
|
28
|
+
/** Map a Node platform/architecture pair to Chrome's archive directory. */
|
|
29
|
+
export function chromePlatform(platform = process.platform, architecture = process.arch) {
|
|
30
|
+
const key = `${platform}-${architecture}`
|
|
31
|
+
const supported = {
|
|
32
|
+
'linux-x64': 'linux64',
|
|
33
|
+
'linux-arm64': 'linux-arm64',
|
|
34
|
+
'darwin-x64': 'mac-x64',
|
|
35
|
+
'darwin-arm64': 'mac-arm64',
|
|
36
|
+
'win32-x64': 'win64',
|
|
37
|
+
}
|
|
38
|
+
if (!supported[key]) {
|
|
39
|
+
throw new Error(`Chrome for Testing has no supported ${platform}/${architecture} archive; install Chromium and set browser executablePath`)
|
|
40
|
+
}
|
|
41
|
+
return supported[key]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Compare two Chrome version strings numerically. */
|
|
45
|
+
export function compareVersions(a, b) {
|
|
46
|
+
const left = String(a).split('.').map(Number)
|
|
47
|
+
const right = String(b).split('.').map(Number)
|
|
48
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
49
|
+
const delta = (left[index] ?? 0) - (right[index] ?? 0)
|
|
50
|
+
if (delta !== 0) return delta
|
|
51
|
+
}
|
|
52
|
+
return 0
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Select the newest build carrying the required archive.
|
|
57
|
+
*
|
|
58
|
+
* The channel entry is only a hint: some metadata revisions name the stable
|
|
59
|
+
* version as a bare string, so every version is ranked explicitly instead of
|
|
60
|
+
* trusting the first match (which used to pick the oldest build).
|
|
61
|
+
* @param metadata - known-good-versions document.
|
|
62
|
+
* @param platform - Chrome archive platform id.
|
|
63
|
+
* @returns `{ version, url, revision }`.
|
|
64
|
+
*/
|
|
65
|
+
export function selectChromeBuild(metadata, platform) {
|
|
66
|
+
if (!metadata || !Array.isArray(metadata.versions)) throw new Error('Chrome for Testing metadata is malformed')
|
|
67
|
+
const stable = typeof metadata.channels?.Stable === 'string' ? metadata.channels.Stable : undefined
|
|
68
|
+
const usable = metadata.versions
|
|
69
|
+
.filter((entry) => Array.isArray(entry?.downloads?.chrome) && entry.version && (!stable || entry.version === stable))
|
|
70
|
+
.filter((entry) => entry.downloads.chrome.some((file) => file.platform === platform && /^https:\/\/storage\.googleapis\.com\//u.test(file.url)))
|
|
71
|
+
if (usable.length === 0) throw new Error(`Chrome for Testing metadata has no ${platform} download`)
|
|
72
|
+
usable.sort((a, b) => compareVersions(b.version, a.version))
|
|
73
|
+
const build = usable[0]
|
|
74
|
+
const download = build.downloads.chrome.find((file) => file.platform === platform)
|
|
75
|
+
return { version: String(build.version), url: download.url, revision: build.revision }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Location of the browser executable inside an extracted official archive. */
|
|
79
|
+
export function executableIn(directory, platform = process.platform, architecture = process.arch) {
|
|
80
|
+
if (platform === 'darwin') return path.join(directory, architecture === 'arm64' ? 'chrome-mac-arm64' : 'chrome-mac-x64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing')
|
|
81
|
+
if (platform === 'win32') return path.join(directory, 'chrome-win64', 'chrome.exe')
|
|
82
|
+
return path.join(directory, architecture === 'arm64' ? 'chrome-linux-arm64' : 'chrome-linux64', 'chrome')
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Verify that a configured or installed browser is a regular executable. */
|
|
86
|
+
export async function verifyExecutable(executablePath) {
|
|
87
|
+
try {
|
|
88
|
+
const details = await stat(executablePath)
|
|
89
|
+
if (!details.isFile()) throw new Error('not a regular file')
|
|
90
|
+
await access(executablePath, process.platform === 'win32' ? constants.F_OK : constants.X_OK)
|
|
91
|
+
return true
|
|
92
|
+
} catch (error) {
|
|
93
|
+
throw new Error(`Chromium executable is unusable at ${executablePath}: ${error instanceof Error ? error.message : String(error)}`)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Check that the installed browser actually starts.
|
|
99
|
+
*
|
|
100
|
+
* A download can complete while the host still lacks shared libraries (a slim
|
|
101
|
+
* container typically misses libglib, libnss3 and friends). Reporting that here
|
|
102
|
+
* turns a silent "ready" into a message naming the exact missing libraries.
|
|
103
|
+
* @param executablePath - the browser binary.
|
|
104
|
+
* @param options - execFile seam and timeout.
|
|
105
|
+
* @returns `{ ok, detail }`.
|
|
106
|
+
*/
|
|
107
|
+
export async function probeLaunch(executablePath, options = {}) {
|
|
108
|
+
const execute = options.execFile ?? execFileAsync
|
|
109
|
+
const env = { ...process.env, ...(options.env ?? {}) }
|
|
110
|
+
try {
|
|
111
|
+
const { stdout, stderr } = await execute(executablePath, ['--version'], { timeout: options.timeoutMs ?? 15000, windowsHide: true, env })
|
|
112
|
+
const line = String(stdout || stderr).trim().split('\n').pop() ?? ''
|
|
113
|
+
return { ok: true, detail: line }
|
|
114
|
+
} catch (error) {
|
|
115
|
+
const detail = String(error?.stderr || error?.stdout || error?.message || error).trim()
|
|
116
|
+
let missing = missingLibraries(detail)
|
|
117
|
+
// The loader stops at the first missing library; `ldd` lists them all.
|
|
118
|
+
if (process.platform === 'linux') {
|
|
119
|
+
try {
|
|
120
|
+
const { stdout } = await execute('ldd', [executablePath], { timeout: options.timeoutMs ?? 15000, env })
|
|
121
|
+
const listed = missingLibraries(stdout)
|
|
122
|
+
if (listed.length > 0) missing = listed
|
|
123
|
+
} catch { /* no ldd: keep the loader's single answer */ }
|
|
124
|
+
}
|
|
125
|
+
const packages = missing.length > 0 ? packagesFor(missing) : []
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
detail,
|
|
129
|
+
missing,
|
|
130
|
+
packages,
|
|
131
|
+
command: installCommand(packages),
|
|
132
|
+
hint: missing.length === 0
|
|
133
|
+
? ''
|
|
134
|
+
: `missing ${missing.length} runtime libraries; install them (or point browser libraryPath at them)`,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Download a URL to a file with byte and time limits. */
|
|
140
|
+
export async function downloadFile(url, destination, options = {}) {
|
|
141
|
+
const fetchImpl = options.fetch ?? globalThis.fetch
|
|
142
|
+
const timeoutMs = options.timeoutMs ?? 120000
|
|
143
|
+
const maxBytes = options.maxBytes ?? MAX_ARCHIVE_BYTES
|
|
144
|
+
const onProgress = options.onProgress ?? (() => {})
|
|
145
|
+
if (typeof fetchImpl !== 'function') throw new Error('automatic browser installation requires Node.js with fetch support')
|
|
146
|
+
const controller = new AbortController()
|
|
147
|
+
const timer = setTimeout(() => controller.abort(new Error(`download timed out after ${timeoutMs}ms`)), timeoutMs)
|
|
148
|
+
try {
|
|
149
|
+
const response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow' })
|
|
150
|
+
if (!response.ok) throw new Error(`download failed with HTTP ${response.status}`)
|
|
151
|
+
const declared = Number(response.headers.get('content-length'))
|
|
152
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw new Error(`download exceeds the ${maxBytes}-byte limit`)
|
|
153
|
+
if (!response.body) throw new Error('download response has no body')
|
|
154
|
+
// 整包读进内存会在 512MB 上限处把宿主堆打满;直接落盘,用计数流守住上限。
|
|
155
|
+
let received = 0
|
|
156
|
+
const meter = new Transform({
|
|
157
|
+
transform(chunk, _encoding, callback) {
|
|
158
|
+
received += chunk.length
|
|
159
|
+
if (received > maxBytes) {
|
|
160
|
+
callback(new Error(`download exceeded the ${maxBytes}-byte limit`))
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
onProgress({ received, total: Number.isFinite(declared) ? declared : undefined })
|
|
164
|
+
callback(null, chunk)
|
|
165
|
+
},
|
|
166
|
+
})
|
|
167
|
+
try {
|
|
168
|
+
await pipeline(Readable.from(response.body), meter, createWriteStream(destination, { flags: 'wx', mode: 0o600 }))
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// 半写的文件绝不能留到下一次安装:下一次会以为"已经下载过"。
|
|
171
|
+
await rm(destination, { force: true }).catch(() => {})
|
|
172
|
+
throw error
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
clearTimeout(timer)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Extract an official ZIP in-process.
|
|
181
|
+
*
|
|
182
|
+
* No system `unzip`, PowerShell, or npm extraction dependency is involved, so
|
|
183
|
+
* automatic installation behaves the same in a slim container and on a desktop.
|
|
184
|
+
* @param archive - the downloaded archive.
|
|
185
|
+
* @param destination - directory to unpack into.
|
|
186
|
+
*/
|
|
187
|
+
export async function extractZip(archive, destination) {
|
|
188
|
+
await extractZipArchive(archive, destination)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Shared, observable installer for one browser plugin mount. */
|
|
192
|
+
export class BrowserRuntime {
|
|
193
|
+
#config
|
|
194
|
+
#deps
|
|
195
|
+
#promise
|
|
196
|
+
#state = { status: 'idle' }
|
|
197
|
+
|
|
198
|
+
constructor(config = {}, dependencies = {}) {
|
|
199
|
+
this.#config = config
|
|
200
|
+
this.#deps = dependencies
|
|
201
|
+
if (config.executablePath) {
|
|
202
|
+
this.#state = { status: 'ready', executablePath: config.executablePath, source: 'configured' }
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
state() {
|
|
207
|
+
return { ...this.#state, ...(this.#state.progress ? { progress: { ...this.#state.progress } } : {}) }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Environment additions from the side-by-side runtime, if installed. */
|
|
211
|
+
async environment() {
|
|
212
|
+
if (this.#state.environment !== undefined) return this.#state.environment
|
|
213
|
+
const home = this.#home()
|
|
214
|
+
const env = await libraryEnvironment(home, this.#arch())
|
|
215
|
+
this.#state = { ...this.#state, environment: env }
|
|
216
|
+
return env
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
#home() {
|
|
220
|
+
return this.#deps.home ?? process.env.DSH_HOME ?? path.join(homedir(), '.dsh')
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
#arch() {
|
|
224
|
+
return this.#deps.arch ?? process.arch
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Run the launch probe through the injectable seam. */
|
|
228
|
+
async #probe(executable) {
|
|
229
|
+
return (this.#deps.probe ?? probeLaunch)(executable, { env: await this.environment() })
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* A downloaded browser still needs the libraries the image lacks. When that
|
|
234
|
+
* is the only problem, fetch them into DSH_HOME (no root required) and probe
|
|
235
|
+
* again, so the browser becomes usable without operator action.
|
|
236
|
+
*/
|
|
237
|
+
async #ensureLibraries(executable, probe) {
|
|
238
|
+
if (probe?.ok !== false || this.#config.autoLibraries === false) return probe
|
|
239
|
+
if (!Array.isArray(probe.missing) || probe.missing.length === 0) return probe
|
|
240
|
+
if (this.#arch() !== 'arm64' && this.#arch() !== 'x64') return probe
|
|
241
|
+
if (this.#deps.platform !== undefined && this.#deps.platform !== 'linux') return probe
|
|
242
|
+
try {
|
|
243
|
+
const result = await installRuntimeLibraries({
|
|
244
|
+
home: this.#home(),
|
|
245
|
+
arch: this.#arch(),
|
|
246
|
+
missing: probe.missing,
|
|
247
|
+
cjkFonts: this.#config.cjkFonts !== false,
|
|
248
|
+
fetch: this.#deps.fetch,
|
|
249
|
+
execFile: this.#deps.execFile,
|
|
250
|
+
suite: this.#config.debianSuite,
|
|
251
|
+
log: this.#deps.log,
|
|
252
|
+
})
|
|
253
|
+
this.#state = { ...this.#state, environment: result.environment, libraries: { packages: result.packages } }
|
|
254
|
+
return await this.#probe(executable)
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
257
|
+
this.#deps.log?.(`runtime libraries could not be installed: ${message}`)
|
|
258
|
+
return { ...probe, librariesError: message }
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Re-use the one in-flight installation; callers all await this promise. */
|
|
263
|
+
ensureReady() {
|
|
264
|
+
if (this.#state.status === 'ready') return Promise.resolve(this.#state.executablePath)
|
|
265
|
+
if (this.#promise) return this.#promise
|
|
266
|
+
this.#promise = this.#install()
|
|
267
|
+
return this.#promise
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Re-run the launch probe for an already installed browser. */
|
|
271
|
+
async recheck() {
|
|
272
|
+
if (this.#state.status !== 'ready' || !this.#state.executablePath) return this.retry()
|
|
273
|
+
this.#state = { ...this.#state, environment: undefined }
|
|
274
|
+
const probe = await this.#probe(this.#state.executablePath)
|
|
275
|
+
const checked = await this.#ensureLibraries(this.#state.executablePath, probe)
|
|
276
|
+
this.#state = { ...this.#state, launch: checked }
|
|
277
|
+
return this.#state.executablePath
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
retry() {
|
|
281
|
+
if (this.#state.status === 'ready') return this.recheck()
|
|
282
|
+
if (this.#state.status !== 'installing') this.#promise = undefined
|
|
283
|
+
return this.ensureReady()
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async #install() {
|
|
287
|
+
this.#state = { status: 'installing', progress: { stage: 'metadata' } }
|
|
288
|
+
const progress = (value) => {
|
|
289
|
+
this.#state = { ...this.#state, progress: { ...this.#state.progress, ...value } }
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
const platform = chromePlatform(this.#deps.platform ?? process.platform, this.#deps.arch ?? process.arch)
|
|
293
|
+
const home = this.#deps.home ?? process.env.DSH_HOME ?? path.join(homedir(), '.dsh')
|
|
294
|
+
const root = path.join(home, 'browser-runtime')
|
|
295
|
+
const metadataFile = path.join(root, `metadata-${process.pid}-${Date.now()}.json`)
|
|
296
|
+
await mkdir(root, { recursive: true })
|
|
297
|
+
try {
|
|
298
|
+
await downloadFile(METADATA_URL, metadataFile, {
|
|
299
|
+
fetch: this.#deps.fetch,
|
|
300
|
+
timeoutMs: this.#config.downloadTimeoutMs ?? 120000,
|
|
301
|
+
maxBytes: MAX_METADATA_BYTES,
|
|
302
|
+
})
|
|
303
|
+
const build = selectChromeBuild(JSON.parse(await readFile(metadataFile, 'utf8')), platform)
|
|
304
|
+
progress({ stage: 'download', version: build.version })
|
|
305
|
+
const destination = path.join(root, 'chrome', build.version, platform)
|
|
306
|
+
const executable = executableIn(destination, this.#deps.platform ?? process.platform, this.#deps.arch ?? process.arch)
|
|
307
|
+
try {
|
|
308
|
+
await verifyExecutable(executable)
|
|
309
|
+
this.#state = { status: 'ready', executablePath: executable, version: build.version, source: 'cache' }
|
|
310
|
+
const cachedLaunch = await this.#ensureLibraries(executable, await this.#probe(executable))
|
|
311
|
+
this.#state = { ...this.#state, launch: cachedLaunch }
|
|
312
|
+
return executable
|
|
313
|
+
} catch { /* install this version below */ }
|
|
314
|
+
const staging = await mkdtemp(path.join(root, '.staging-'))
|
|
315
|
+
try {
|
|
316
|
+
const archive = path.join(staging, 'chrome.zip')
|
|
317
|
+
const unpacked = path.join(staging, 'unpacked')
|
|
318
|
+
await mkdir(unpacked)
|
|
319
|
+
await downloadFile(build.url, archive, {
|
|
320
|
+
fetch: this.#deps.fetch,
|
|
321
|
+
timeoutMs: this.#config.downloadTimeoutMs ?? 300000,
|
|
322
|
+
onProgress: ({ received, total }) => progress({ stage: 'download', downloadedBytes: received, totalBytes: total, percent: total ? Math.round(received / total * 100) : undefined }),
|
|
323
|
+
})
|
|
324
|
+
progress({ stage: 'extract' })
|
|
325
|
+
await extractZip(archive, unpacked)
|
|
326
|
+
await verifyExecutable(executableIn(unpacked, this.#deps.platform ?? process.platform, this.#deps.arch ?? process.arch))
|
|
327
|
+
await mkdir(path.dirname(destination), { recursive: true })
|
|
328
|
+
try {
|
|
329
|
+
await rename(unpacked, destination)
|
|
330
|
+
} catch (error) {
|
|
331
|
+
if (error?.code !== 'EEXIST' && error?.code !== 'ENOTEMPTY') throw error
|
|
332
|
+
}
|
|
333
|
+
if (this.#deps.platform !== 'win32') await chmod(executable, 0o755).catch(() => {})
|
|
334
|
+
await verifyExecutable(executable)
|
|
335
|
+
this.#state = { status: 'ready', executablePath: executable, version: build.version, source: 'download' }
|
|
336
|
+
const freshLaunch = await this.#ensureLibraries(executable, await this.#probe(executable))
|
|
337
|
+
this.#state = { ...this.#state, launch: freshLaunch }
|
|
338
|
+
return executable
|
|
339
|
+
} finally {
|
|
340
|
+
await rm(staging, { recursive: true, force: true })
|
|
341
|
+
}
|
|
342
|
+
} finally {
|
|
343
|
+
await rm(metadataFile, { force: true })
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
347
|
+
this.#state = { status: 'error', error: `Automatic Chromium installation failed: ${message}` }
|
|
348
|
+
throw new Error(this.#state.error)
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|