@tianacloud/dsh-remote 0.0.0-stage → 0.2.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 +204 -0
- package/README.md +44 -2
- package/cli.js +347 -0
- package/client.js +1501 -0
- package/cordis.patch.yml +3 -0
- package/host-main.js +628 -0
- package/icon.svg +7 -0
- package/locale/en-US.json +9 -0
- package/locale/zh-CN.json +9 -0
- package/package.json +89 -4
- package/relay-go/go.mod +3 -0
- package/relay-go/main.go +1711 -0
- package/scripts/build-web-dist.mjs +46 -0
- package/src/clipboard.js +94 -0
- package/src/connect.js +599 -0
- package/src/dsh-packages.js +46 -0
- package/src/frontend-assets.js +405 -0
- package/src/host-bridge.js +1412 -0
- package/src/local-transport.js +496 -0
- package/src/protocol.js +124 -0
- package/src/remote-api.js +433 -0
- package/src/state.js +409 -0
- package/src/tiana-cli.js +1271 -0
- package/web-src/dsh-remote-entry.mjs +2692 -0
- package/web-src/dsh-remote-sw.js +593 -0
- package/web-src/e2ee.js +460 -0
- package/web-src/frontend-loader.js +450 -0
- package/web-src/multipath.js +375 -0
- package/web-src/peer-path.js +265 -0
- package/web-src/shell-ui.js +280 -0
- package/web-src/ws-fragments.js +46 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readdirSync, readFileSync, realpathSync, statSync, existsSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { addAbortSignal } from 'node:stream';
|
|
6
|
+
import { createGzip } from 'node:zlib';
|
|
7
|
+
import { init, parse, ImportType } from 'es-module-lexer';
|
|
8
|
+
import { resolveDshPackageDir, resolveDshPackageDirs } from './dsh-packages.js';
|
|
9
|
+
|
|
10
|
+
const MAX_RESOURCE = 16 << 20;
|
|
11
|
+
const MAX_TOTAL = 64 << 20;
|
|
12
|
+
const TRANSFORM = 1;
|
|
13
|
+
const BOOTSTRAP = '@deepseek-ai/dsh-client-modules';
|
|
14
|
+
// DSH 0.2.2-rc.1 passes these singleton modules from the compiled web shell.
|
|
15
|
+
const PLATFORM_MODULES = new Set([
|
|
16
|
+
'react', 'react/jsx-runtime', 'react-dom', 'react-dom/client', '@deepseek-ai/cordis', 'zod',
|
|
17
|
+
'@tanstack/react-virtual', '@deepseek-ai/dsh-client-store', '@deepseek-ai/dsh-client-ui-slots',
|
|
18
|
+
'@deepseek-ai/dsh-client-ui-primitives', '@deepseek-ai/dsh-client-ui-dockkit',
|
|
19
|
+
]);
|
|
20
|
+
const PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u;
|
|
21
|
+
const CHUNK = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/u;
|
|
22
|
+
const MIME = {
|
|
23
|
+
'.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css',
|
|
24
|
+
'.json': 'application/json', '.webmanifest': 'application/manifest+json',
|
|
25
|
+
'.wasm': 'application/wasm', '.woff2': 'font/woff2', '.woff': 'font/woff',
|
|
26
|
+
'.ttf': 'font/ttf', '.svg': 'image/svg+xml', '.png': 'image/png',
|
|
27
|
+
'.webp': 'image/webp', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
|
|
28
|
+
'.gif': 'image/gif', '.ico': 'image/x-icon', '.avif': 'image/avif',
|
|
29
|
+
'.mp3': 'audio/mpeg', '.mp4': 'video/mp4', '.webm': 'video/webm',
|
|
30
|
+
'.pdf': 'application/pdf', '.otf': 'font/otf',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function confined(root, file) {
|
|
34
|
+
const actual = realpathSync(file);
|
|
35
|
+
const rel = relative(root, actual);
|
|
36
|
+
if (!rel || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) {
|
|
37
|
+
throw new Error('DSH resource escaped its package');
|
|
38
|
+
}
|
|
39
|
+
return actual;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readFile(file) {
|
|
43
|
+
const stat = statSync(file);
|
|
44
|
+
if (!stat.isFile() || stat.size > MAX_RESOURCE) throw new Error('Invalid DSH resource size or type');
|
|
45
|
+
const bytes = readFileSync(file);
|
|
46
|
+
if (bytes.length > MAX_RESOURCE) throw new Error('DSH resource exceeds size limit');
|
|
47
|
+
return bytes;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function localKey(source, specifier, entries) {
|
|
51
|
+
const resolved = posix.normalize(posix.join(posix.dirname(source), specifier));
|
|
52
|
+
if (!specifier.startsWith('.') || !entries.has(resolved)) {
|
|
53
|
+
throw new Error(`Unsupported core dependency: ${source} → ${specifier}`);
|
|
54
|
+
}
|
|
55
|
+
return 'core:' + resolved;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function safeExpression(ctx, expression) {
|
|
59
|
+
return String(expression).split('.').reduce((value, key) =>
|
|
60
|
+
value != null && Object.hasOwn(value, key) ? value[key] : undefined, ctx);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function coreModule(file, source, entries, isEntry) {
|
|
64
|
+
if (isEntry) {
|
|
65
|
+
const pattern = /new Function\("ctx","expr",`[\s\S]*?return eval\(expr\)[\s\S]*?`\)/gu;
|
|
66
|
+
const preloader = /(\b[$\w]+)=function\(([$\w,]+)\)\{let [$\w]+=Promise\.resolve\(\);if\([\s\S]*?new Event\("vite:preloadError"[\s\S]*?return [$\w]+\(\)\.catch\([$\w]+\)\}\)\}/gu;
|
|
67
|
+
if ([...source.matchAll(pattern)].length !== 1 || [...source.matchAll(preloader)].length !== 1) {
|
|
68
|
+
throw new Error('Unsupported DSH frontend transformation');
|
|
69
|
+
}
|
|
70
|
+
source = source.replace(pattern, '(' + safeExpression.toString() + ')')
|
|
71
|
+
.replace(preloader, '$1=(load)=>load()');
|
|
72
|
+
}
|
|
73
|
+
const edits = [];
|
|
74
|
+
const links = [];
|
|
75
|
+
let dynamicImports = 0;
|
|
76
|
+
for (const item of parse(source, file)[0]) {
|
|
77
|
+
if (item.t === ImportType.ImportMeta && source.slice(item.e, item.e + 4) === '.url') {
|
|
78
|
+
// Vite build paths only occur in the preload shim disabled above.
|
|
79
|
+
edits.push([item.s, item.e + 4, JSON.stringify('https://dsh-assets.invalid/' + file)]);
|
|
80
|
+
} else if (item.t === ImportType.Static) {
|
|
81
|
+
const key = localKey(file, item.n, entries);
|
|
82
|
+
const marker = '__DSH_CORE_LINK_' + links.length + '__';
|
|
83
|
+
links.push({ marker, key });
|
|
84
|
+
edits.push([item.s, item.e, marker]);
|
|
85
|
+
} else if (item.t === ImportType.Dynamic && item.n?.startsWith('.')) {
|
|
86
|
+
++dynamicImports;
|
|
87
|
+
edits.push([item.ss, item.se, 'globalThis.__DSH_IMPORT_CORE__(' + JSON.stringify(localKey(file, item.n, entries)) + ')']);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
|
|
91
|
+
source = source.slice(0, start) + replacement + source.slice(end);
|
|
92
|
+
}
|
|
93
|
+
return { bytes: Buffer.from(source), links, dynamicImports };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function browserExport(root, pkg) {
|
|
97
|
+
const declared = pkg.exports?.['./client'];
|
|
98
|
+
const browser = typeof declared === 'string' ? declared : declared?.default;
|
|
99
|
+
if (typeof browser !== 'string' || !browser.startsWith('./')) throw new Error('DSH client has no browser export');
|
|
100
|
+
return confined(root, resolve(root, browser));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function artifactRevision(file) {
|
|
104
|
+
const stat = statSync(file);
|
|
105
|
+
const hash = createHash('sha1').update('plugin-artifact\0');
|
|
106
|
+
for (const value of [stat.mtimeMs, stat.ctimeMs, stat.size].map(String)) {
|
|
107
|
+
hash.update(String(Buffer.byteLength(value)) + ':').update(value);
|
|
108
|
+
}
|
|
109
|
+
return hash.digest('hex').slice(0, 12);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function packageFromClient(row, clientPath) {
|
|
113
|
+
if (clientPath) {
|
|
114
|
+
const client = realpathSync(clientPath);
|
|
115
|
+
for (let root = dirname(client); dirname(root) !== root; root = dirname(root)) {
|
|
116
|
+
const metadata = join(root, 'package.json');
|
|
117
|
+
if (!existsSync(metadata)) continue;
|
|
118
|
+
const pkg = JSON.parse(readFile(metadata));
|
|
119
|
+
if (pkg.name !== row.id) continue;
|
|
120
|
+
if (client !== browserExport(root, pkg)) throw new Error('Active DSH client is not its declared export');
|
|
121
|
+
return { root, pkg, client };
|
|
122
|
+
}
|
|
123
|
+
} else {
|
|
124
|
+
// Standalone bridge gets the live revision over loopback. Locate precisely that
|
|
125
|
+
// export, even when the machine has multiple versions of the same package.
|
|
126
|
+
for (const root of resolveDshPackageDirs(row.id)) {
|
|
127
|
+
const pkg = JSON.parse(readFile(join(root, 'package.json')));
|
|
128
|
+
if (pkg.name !== row.id) continue;
|
|
129
|
+
const client = browserExport(root, pkg);
|
|
130
|
+
if (artifactRevision(client) === row.rev) return { root, pkg, client };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
throw new Error('No matching export for active DSH module: ' + row.id);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function cleanBundle(file) {
|
|
137
|
+
return Buffer.from(readFile(file).toString('utf8').replace(/\r?\n\/\/# source(?:Mapping)?URL=[^\r\n]*/gu, ''));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const BUILTIN_CLIENT_PREFIX = '@deepseek-ai/dsh-client-';
|
|
141
|
+
const SELF_CLIENT_MODULE = '@tianacloud/dsh-remote';
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Select which active DSH client modules are exposed over the remote tunnel.
|
|
145
|
+
* - `allowlist: ['*']` (or `'*'`): allow all active modules.
|
|
146
|
+
* - `allowlist: []` (default) or omitted: allow ONLY builtin DSH core modules
|
|
147
|
+
* (`@deepseek-ai/dsh-client-*`) plus `@tianacloud/dsh-remote` itself; third-party plugins are blocked.
|
|
148
|
+
* - Explicit IDs: allow builtin core + `@tianacloud/dsh-remote` + exact allowlisted active plugins.
|
|
149
|
+
*/
|
|
150
|
+
export function selectAllowedWebPlugins(modules, allowlist) {
|
|
151
|
+
const rawLimit = Array.isArray(allowlist)
|
|
152
|
+
? allowlist
|
|
153
|
+
: typeof allowlist === 'string'
|
|
154
|
+
? allowlist.split(',')
|
|
155
|
+
: [];
|
|
156
|
+
const limit = rawLimit.map((id) => String(id).trim()).filter(Boolean);
|
|
157
|
+
const allowAll = limit.includes('*');
|
|
158
|
+
|
|
159
|
+
if (allowAll) {
|
|
160
|
+
return new Set(modules.keys());
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const selected = new Set();
|
|
164
|
+
if (modules.has(BOOTSTRAP)) selected.add(BOOTSTRAP);
|
|
165
|
+
for (const id of modules.keys()) {
|
|
166
|
+
if (id.startsWith(BUILTIN_CLIENT_PREFIX) || id === SELF_CLIENT_MODULE) {
|
|
167
|
+
selected.add(id);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
for (const id of limit) {
|
|
171
|
+
if (modules.has(id)) {
|
|
172
|
+
selected.add(id);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return selected;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function compilePlugins(graph, options, add) {
|
|
179
|
+
if (!graph) return undefined;
|
|
180
|
+
if (!Array.isArray(graph.entries) || !Array.isArray(graph.batches)) {
|
|
181
|
+
throw new Error('Unsupported DSH boot manifest');
|
|
182
|
+
}
|
|
183
|
+
const modules = new Map();
|
|
184
|
+
for (const row of graph.entries) {
|
|
185
|
+
if (!PACKAGE.test(row.id) || typeof row.rev !== 'string' || modules.has(row.id)) {
|
|
186
|
+
throw new Error('Invalid DSH boot module');
|
|
187
|
+
}
|
|
188
|
+
modules.set(row.id, row);
|
|
189
|
+
}
|
|
190
|
+
const rawLimit = Array.isArray(options.allowlist)
|
|
191
|
+
? options.allowlist
|
|
192
|
+
: typeof options.allowlist === 'string'
|
|
193
|
+
? options.allowlist.split(',')
|
|
194
|
+
: [];
|
|
195
|
+
const allowAll = rawLimit.map((id) => String(id).trim()).includes('*');
|
|
196
|
+
const selected = selectAllowedWebPlugins(modules, options.allowlist);
|
|
197
|
+
if (modules.size > 0 && !modules.has(BOOTSTRAP)) {
|
|
198
|
+
throw new Error('A required DSH client module is absent: ' + BOOTSTRAP);
|
|
199
|
+
}
|
|
200
|
+
if (modules.has(BOOTSTRAP)) {
|
|
201
|
+
selected.add(BOOTSTRAP);
|
|
202
|
+
}
|
|
203
|
+
const isBuiltinOrBootstrap = (id) => id === BOOTSTRAP || id.startsWith(BUILTIN_CLIENT_PREFIX);
|
|
204
|
+
for (const id of selected) {
|
|
205
|
+
const row = modules.get(id);
|
|
206
|
+
if (!row) throw new Error('A required DSH client module is absent: ' + id);
|
|
207
|
+
for (const dependency of row.external ?? []) {
|
|
208
|
+
const name = dependency.replace(/\/client$/u, '');
|
|
209
|
+
if (selected.has(name)) continue;
|
|
210
|
+
if (modules.has(name)) {
|
|
211
|
+
if (allowAll || isBuiltinOrBootstrap(name) || name === SELF_CLIENT_MODULE) {
|
|
212
|
+
selected.add(name);
|
|
213
|
+
} else if (isBuiltinOrBootstrap(id)) {
|
|
214
|
+
continue;
|
|
215
|
+
} else {
|
|
216
|
+
throw new Error(`Required third-party DSH module is not allowlisted: ${name}`);
|
|
217
|
+
}
|
|
218
|
+
} else if (!PLATFORM_MODULES.has(dependency)) {
|
|
219
|
+
throw new Error('Required DSH module is not active: ' + dependency);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const keepDep = (dep) => PLATFORM_MODULES.has(dep) || selected.has(String(dep).replace(/\/client$/u, ''));
|
|
224
|
+
const entryOrder = graph.entries
|
|
225
|
+
.filter((row) => selected.has(row.id))
|
|
226
|
+
.map((row) => {
|
|
227
|
+
const next = { ...row };
|
|
228
|
+
if (Array.isArray(row.inject)) {
|
|
229
|
+
next.inject = row.inject.filter(keepDep);
|
|
230
|
+
}
|
|
231
|
+
if (Array.isArray(row.external)) {
|
|
232
|
+
next.external = row.external.filter(keepDep);
|
|
233
|
+
}
|
|
234
|
+
return next;
|
|
235
|
+
});
|
|
236
|
+
for (const row of entryOrder) {
|
|
237
|
+
const id = row.id;
|
|
238
|
+
const { root, pkg, client: clientFile } = packageFromClient(row, options.activeClientPath?.(id));
|
|
239
|
+
const clientDir = dirname(clientFile);
|
|
240
|
+
const route = 'plugins/??' + id + '/client.js&rev=' + encodeURIComponent(row.rev);
|
|
241
|
+
add('plugin:' + id + '/client.js', cleanBundle(clientFile), '.js', { route, owner: id, registration: id });
|
|
242
|
+
for (const item of readdirSync(clientDir, { withFileTypes: true })) {
|
|
243
|
+
if (!CHUNK.test(item.name) || /^client\.(?:node|browser)(?:\.|$)/u.test(item.name)) continue;
|
|
244
|
+
if (!item.isFile() && !item.isSymbolicLink()) continue;
|
|
245
|
+
const file = confined(root, join(clientDir, item.name));
|
|
246
|
+
add('chunk:' + id + '/' + item.name, cleanBundle(file), '.js', {
|
|
247
|
+
route: 'plugins/' + id + '/' + item.name + '?rev=' + encodeURIComponent(row.rev), owner: id,
|
|
248
|
+
registration: id, chunk: item.name,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const exportTarget = pkg.exports?.['./assets/*'];
|
|
253
|
+
if (typeof exportTarget !== 'string' || !exportTarget.endsWith('/*')) continue;
|
|
254
|
+
const exportDir = confined(root, resolve(root, exportTarget.slice(0, -2)));
|
|
255
|
+
const require = createRequire(join(root, 'package.json'));
|
|
256
|
+
for (const entry of readdirSync(exportDir, { recursive: true, withFileTypes: true })) {
|
|
257
|
+
const candidate = join(entry.parentPath, entry.name);
|
|
258
|
+
const suffix = extname(entry.name);
|
|
259
|
+
if (!MIME[suffix] || (!entry.isFile() && !entry.isSymbolicLink())) continue;
|
|
260
|
+
const path = relative(exportDir, candidate).split(sep).join('/');
|
|
261
|
+
const actual = confined(root, require.resolve(id + '/assets/' + path));
|
|
262
|
+
if (actual !== confined(root, candidate)) throw new Error('DSH asset export does not match its package');
|
|
263
|
+
const encoded = path.split('/').map(encodeURIComponent).join('/');
|
|
264
|
+
add('asset:' + id + '/' + encoded, readFile(actual), suffix, {
|
|
265
|
+
route: 'plugins/' + id + '/assets/' + encoded, owner: id,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
...graph,
|
|
271
|
+
entries: entryOrder,
|
|
272
|
+
batches: entryOrder.map((row) => ({
|
|
273
|
+
phase: row.id === BOOTSTRAP ? 'bootstrap' : 'application',
|
|
274
|
+
url: row.url, rev: row.rev, entries: [row.id],
|
|
275
|
+
})),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
export class FrontendAssets {
|
|
280
|
+
constructor(options = {}) {
|
|
281
|
+
this.options = { ...options };
|
|
282
|
+
this.snapshot = null;
|
|
283
|
+
this.serial = 0;
|
|
284
|
+
this.activeCompression = 0;
|
|
285
|
+
this.waitingCompression = [];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
setAllowlist(allowlist) {
|
|
289
|
+
const nextKey = JSON.stringify(allowlist ?? null);
|
|
290
|
+
const prevKey = JSON.stringify(this.options.allowlist ?? null);
|
|
291
|
+
if (nextKey === prevKey) return false;
|
|
292
|
+
this.options.allowlist = allowlist;
|
|
293
|
+
this.snapshot = null;
|
|
294
|
+
this.building = null;
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async prepare(rows) {
|
|
299
|
+
const graph = rows.find((row) => row.kind === 'global' && row.name === '__DSH_BOOT__')?.value;
|
|
300
|
+
const signature = JSON.stringify({ graph: graph ?? null, allowlist: this.options.allowlist ?? null });
|
|
301
|
+
if (!this.snapshot || this.snapshot.signature !== signature) {
|
|
302
|
+
const existing = this.building;
|
|
303
|
+
if (existing?.signature === signature) return existing.promise;
|
|
304
|
+
const promise = this.build(graph, signature);
|
|
305
|
+
this.building = { signature, promise };
|
|
306
|
+
try {
|
|
307
|
+
const snapshot = await promise;
|
|
308
|
+
if (this.building?.promise === promise) this.snapshot = snapshot;
|
|
309
|
+
return snapshot;
|
|
310
|
+
} finally {
|
|
311
|
+
if (this.building?.promise === promise) this.building = null;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return this.snapshot;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async build(graph, signature) {
|
|
318
|
+
await init;
|
|
319
|
+
const packageRoot = realpathSync(this.options.frontend || resolveDshPackageDir('@deepseek-ai/dsh-web-frontend'));
|
|
320
|
+
const dist = confined(packageRoot, join(packageRoot, 'dist'));
|
|
321
|
+
const html = readFile(confined(dist, join(dist, 'index.html'))).toString('utf8');
|
|
322
|
+
const entry = /<script\s+type="module"[^>]*\bsrc="\.\/([^"]+\.js)"/u.exec(html)?.[1];
|
|
323
|
+
if (!entry) throw new Error('DSH frontend has no module entry');
|
|
324
|
+
const styles = [...html.matchAll(/rel="stylesheet"[^>]*href="\.\/([^"]+\.css)"/gu)].map((m) => 'core:' + m[1]);
|
|
325
|
+
const paths = new Map();
|
|
326
|
+
for (const item of readdirSync(dist, { withFileTypes: true, recursive: true })) {
|
|
327
|
+
if (!item.isDirectory() && MIME[extname(item.name)]) {
|
|
328
|
+
const actual = confined(dist, join(item.parentPath, item.name));
|
|
329
|
+
paths.set(relative(dist, join(item.parentPath, item.name)).split(sep).join('/'), actual);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
let total = 0;
|
|
333
|
+
const resources = new Map();
|
|
334
|
+
function add(key, bytes, suffix, meta = {}) {
|
|
335
|
+
total += bytes.length;
|
|
336
|
+
if (bytes.length > MAX_RESOURCE || total > MAX_TOTAL || resources.has(key)) {
|
|
337
|
+
throw new Error('Invalid, duplicate or oversized DSH frontend resource');
|
|
338
|
+
}
|
|
339
|
+
const digest = createHash('sha256').update(bytes).digest('hex');
|
|
340
|
+
resources.set(key, { meta: { key, rev: digest, sha256: digest, byteLength: bytes.length, mimeType: MIME[suffix], ...meta }, bytes });
|
|
341
|
+
}
|
|
342
|
+
for (const [path, actual] of paths) {
|
|
343
|
+
const suffix = extname(path);
|
|
344
|
+
let bytes = readFile(actual);
|
|
345
|
+
let details = {};
|
|
346
|
+
if (suffix === '.js') ({ bytes, ...details } = coreModule(path, bytes.toString('utf8'), paths, path === entry));
|
|
347
|
+
if (suffix === '.css') {
|
|
348
|
+
const links = [];
|
|
349
|
+
bytes = Buffer.from(bytes.toString('utf8').replace(/url\(["']?(\.\.?\/[^)'"]+)["']?\)/gu, (_, ref) => {
|
|
350
|
+
const marker = '__DSH_STYLE_LINK_' + links.length + '__';
|
|
351
|
+
links.push({ marker, key: localKey(path, ref, paths) });
|
|
352
|
+
return 'url("' + marker + '")';
|
|
353
|
+
}));
|
|
354
|
+
details = { links };
|
|
355
|
+
}
|
|
356
|
+
add('core:' + path, bytes, suffix, details);
|
|
357
|
+
}
|
|
358
|
+
const boot = compilePlugins(graph, this.options, add);
|
|
359
|
+
this.serial++;
|
|
360
|
+
return {
|
|
361
|
+
signature,
|
|
362
|
+
resources,
|
|
363
|
+
manifest: {
|
|
364
|
+
transformVersion: TRANSFORM, generation: Date.now(), serial: this.serial,
|
|
365
|
+
entry: 'core:' + entry, styles, boot, resources: [...resources.values()].map((row) => row.meta),
|
|
366
|
+
},
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
async representation(asset, compressed, signal) {
|
|
371
|
+
signal.throwIfAborted();
|
|
372
|
+
if (!compressed || asset.bytes.length < 1024 || !/^(text\/|application\/(json|wasm)|image\/svg\+xml)/u.test(asset.meta.mimeType)) {
|
|
373
|
+
return { bytes: asset.bytes, encoding: 'identity' };
|
|
374
|
+
}
|
|
375
|
+
if (this.activeCompression >= 4) {
|
|
376
|
+
await new Promise((resolve, reject) => {
|
|
377
|
+
const ready = () => {
|
|
378
|
+
signal.removeEventListener('abort', abort);
|
|
379
|
+
resolve();
|
|
380
|
+
};
|
|
381
|
+
const abort = () => {
|
|
382
|
+
this.waitingCompression = this.waitingCompression.filter((entry) => entry !== ready);
|
|
383
|
+
reject(signal.reason);
|
|
384
|
+
};
|
|
385
|
+
this.waitingCompression.push(ready);
|
|
386
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
387
|
+
});
|
|
388
|
+
} else {
|
|
389
|
+
this.activeCompression++;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
signal.throwIfAborted();
|
|
393
|
+
const stream = addAbortSignal(signal, createGzip());
|
|
394
|
+
stream.end(asset.bytes);
|
|
395
|
+
const parts = [];
|
|
396
|
+
for await (const part of stream) parts.push(part);
|
|
397
|
+
signal.throwIfAborted();
|
|
398
|
+
return { bytes: Buffer.concat(parts), encoding: 'gzip' };
|
|
399
|
+
} finally {
|
|
400
|
+
const next = this.waitingCompression.shift();
|
|
401
|
+
if (next) next();
|
|
402
|
+
else this.activeCompression--;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|