Repository navigation
Expand file tree
/
Copy pathtest-packed-consumer.mjs
More file actions
652 lines (615 loc) · 20.7 KB
/
Copy pathtest-packed-consumer.mjs
File metadata and controls
652 lines (615 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import {spawn, spawnSync} from 'node:child_process';
import {rmSync} from 'node:fs';
import {
cp,
mkdir,
mkdtemp,
readFile,
readdir,
realpath,
rm,
writeFile,
} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {dirname, join, relative, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {chromium} from '@playwright/test';
import {requireWasmArtifacts, wasmArtifacts} from './wasm-artifacts.mjs';
import {getPackageDocumentation} from './package-documentation.mjs';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const fixture = resolve(root, 'test/consumers/vite');
const generatedRoot = await mkdtemp(
join(tmpdir(), 'tinyjoin-packed-consumer-'),
);
const packageTestEnvironment = {
...process.env,
npm_config_cache: resolve(generatedRoot, 'npm-cache'),
npm_config_update_notifier: 'false',
};
const packageDirectory = resolve(generatedRoot, 'package');
const appDirectory = resolve(generatedRoot, 'app');
const port = 43_117;
const baseUrl = `http://127.0.0.1:${port}`;
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const arguments_ = process.argv.slice(2);
if (arguments_.some((argument) => argument !== '--built')) {
throw new Error(`Unknown packed-consumer option: ${arguments_.join(' ')}`);
}
const useBuiltPackage = arguments_.includes('--built');
const cleanupGeneratedRoot = () =>
rmSync(generatedRoot, {force: true, recursive: true});
process.once('exit', cleanupGeneratedRoot);
await mkdir(packageDirectory, {recursive: true});
// Pack the same clean dist directory that is published to npm. Release checks
// pass --built so their one already-verified WASM build is reused.
if (useBuiltPackage) {
await requireWasmArtifacts(resolve(root, 'dist'));
} else {
run(npm, ['run', 'build'], root);
}
await assertBuildLibRejectsMissingWasmArtifacts();
const packOutput = run(
npm,
[
'pack',
'./dist',
'--ignore-scripts',
'--json',
'--pack-destination',
packageDirectory,
],
root,
);
const packed = parsePackOutput(packOutput);
const packageDocumentation = await getPackageDocumentation(root);
assertPackedFiles(packed, Object.keys(packageDocumentation));
const tarball = resolve(packageDirectory, packed.filename);
await cp(fixture, appDirectory, {recursive: true});
await cp(resolve(root, 'test/consumers/node'), resolve(appDirectory, 'node'), {
recursive: true,
});
const manifestPath = resolve(appDirectory, 'package.json');
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
manifest.dependencies.tinyjoin = `file:${tarball}`;
await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
run(npm, ['install', '--no-audit', '--no-fund'], appDirectory);
const installedPackage = resolve(appDirectory, 'node_modules/tinyjoin');
const installedRealPath = await realpath(installedPackage);
const nodeModulesRealPath = await realpath(
resolve(appDirectory, 'node_modules'),
);
if (installedRealPath !== resolve(nodeModulesRealPath, 'tinyjoin')) {
throw new Error(
`Expected a packed install under node_modules, received ${installedRealPath}`,
);
}
const installedManifest = JSON.parse(
await readFile(resolve(installedPackage, 'package.json'), 'utf8'),
);
if (installedManifest.name !== 'tinyjoin') {
throw new Error('The installed tarball is not the tinyjoin package');
}
if (installedManifest.types !== './@types/index.d.ts') {
throw new Error(
`The installed tarball has unexpected declarations: ${installedManifest.types}`,
);
}
for (const developmentField of ['private', 'scripts', 'devDependencies']) {
if (developmentField in installedManifest) {
throw new Error(
`Published TinyJoin manifest contains development field ${developmentField}`,
);
}
}
if (
installedManifest.dependencies &&
Object.keys(installedManifest.dependencies).length > 0
) {
throw new Error(
`Published TinyJoin unexpectedly has runtime dependencies: ${Object.keys(installedManifest.dependencies).join(', ')}`,
);
}
await assertInstalledOpfsLoader(installedPackage);
// Reading the installed contracts uses only the tarball's files, without a
// website request. Also reject stale content and broken local guide links.
for (const [path, expected] of Object.entries(packageDocumentation)) {
const contents = await readFile(resolve(installedPackage, path), 'utf8');
if (contents !== expected) {
throw new Error(`Installed documentation is stale: ${path}`);
}
for (const [, href] of contents.matchAll(/\]\(([^)]+\.md(?:#[^)]*)?)\)/g)) {
if (/^https?:/.test(href)) continue;
await readFile(resolve(installedPackage, dirname(path), href.split('#')[0]));
}
}
console.log('PACKAGE_LOCAL_GUIDES_OK');
const ssrOutput = run(
process.execPath,
[
'--input-type=module',
'--eval',
"const pkg = await import('tinyjoin'); if (typeof pkg.create !== 'function') throw new Error('missing create export'); console.log('SSR_IMPORT_OK');",
],
appDirectory,
);
if (!ssrOutput.includes('SSR_IMPORT_OK')) {
throw new Error(`SSR-safe import did not complete:\n${ssrOutput}`);
}
await exerciseNodeConsumer();
run(npm, ['run', 'typecheck'], appDirectory);
run(npm, ['run', 'build'], appDirectory);
const builtFiles = await listFiles(resolve(appDirectory, 'dist'));
await assertConsumerPrivateRuntimeBoundary(builtFiles);
if (!builtFiles.some((file) => file.endsWith('.wasm'))) {
throw new Error(
`The consumer build emitted no WASM asset:\n${builtFiles.join('\n')}`,
);
}
let server;
let serverOutput = '';
let browser;
let completed = false;
try {
// Own the Vite process directly. On Linux, terminating an npm wrapper can
// leave Vite alive with inherited output pipes, preventing this test exiting.
server = spawn(
process.execPath,
[
resolve(appDirectory, 'node_modules/vite/bin/vite.js'),
'preview',
'--host',
'127.0.0.1',
'--port',
String(port),
'--strictPort',
],
{
cwd: appDirectory,
env: packageTestEnvironment,
stdio: ['ignore', 'pipe', 'pipe'],
},
);
server.stdout.on('data', (chunk) => {
serverOutput += String(chunk);
});
server.stderr.on('data', (chunk) => {
serverOutput += String(chunk);
});
await waitForServer(server, baseUrl, () => serverOutput);
browser = await chromium.launch({headless: true});
const page = await browser.newPage();
// Routing disables Chromium's HTTP cache. Every lazy module/WASM load is
// therefore observable on the exact navigation that requested it.
await page.route('**/*', (route) => route.continue());
const runtimeRequests = [];
page.on('request', (request) => runtimeRequests.push(request.url()));
const appLocal = await exerciseMemory(
page,
`${baseUrl}/?worker=app-local`,
runtimeRequests,
);
console.log(`APP_LOCAL_WORKER_OK ${JSON.stringify(appLocal)}`);
const packageDefault = await exerciseMemory(
page,
`${baseUrl}/?worker=default`,
runtimeRequests,
);
console.log(`PACKAGE_DEFAULT_WORKER_OK ${JSON.stringify(packageDefault)}`);
for (const workerMode of ['app-local', 'default']) {
const freshDatabaseName = `packed-fresh-${workerMode}-${Date.now()}`;
const freshParameters = new URLSearchParams({
worker: workerMode,
database: freshDatabaseName,
});
const written = await exerciseFreshOpfs(
page,
`${baseUrl}/?${freshParameters}&persistence=write`,
runtimeRequests,
);
const restored = await exercisePersistedOpfs(
page,
`${baseUrl}/?${freshParameters}&persistence=read`,
runtimeRequests,
);
console.log(
`OPFS_FRESH_${workerMode.toUpperCase().replace('-', '_')}_WORKER_OK ${JSON.stringify({written, restored})}`,
);
}
completed = true;
} finally {
const cleanup = await Promise.allSettled([
browser?.close(),
server ? stopServer(server) : undefined,
]);
if (completed) {
const failure = cleanup.find((result) => result.status === 'rejected');
if (failure?.status === 'rejected') {
throw failure.reason;
}
}
}
console.log(`PACKED_TARBALL ${relative(root, tarball)}`);
console.log(`PACKED_INSTALL ${relative(root, installedRealPath)}`);
console.log('SSR_IMPORT_OK');
console.log(`VITE_BUILD_OK ${builtFiles.length} files`);
await rm(generatedRoot, {force: true, recursive: true});
process.removeListener('exit', cleanupGeneratedRoot);
console.log('PACKED_CONSUMER_CLEANUP_OK');
function run(command, args, cwd, options = {}) {
const result = spawnSync(command, args, {
cwd,
encoding: 'utf8',
env: packageTestEnvironment,
maxBuffer: 20 * 1024 * 1024,
...options,
});
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`;
if (result.status !== 0) {
throw new Error(
`${command} ${args.join(' ')} failed with ${result.error?.message ?? result.status}:\n${output}`,
);
}
return output;
}
async function exerciseNodeConsumer() {
for (const project of ['node/tsconfig.json', 'node/tsconfig.drizzle.json']) {
run(
process.execPath,
['node_modules/typescript/bin/tsc', '--project', project],
appDirectory,
{timeout: 30_000},
);
}
for (const args of [
['node/main.mjs'],
['--input-type=module', '--eval', "await import('./node/main.mjs')"],
]) {
const output = run(process.execPath, args, appDirectory, {timeout: 30_000});
if (!output.includes('NODE_MEMORY_CONSUMER_OK')) {
throw new Error(`Node packed consumer did not complete:\n${output}`);
}
}
// The Drizzle driver resolves the application's own drizzle-orm.
const drizzleOutput = run(process.execPath, ['node/drizzle.mjs'], appDirectory, {
timeout: 30_000,
});
if (!drizzleOutput.includes('NODE_DRIZZLE_CONSUMER_OK')) {
throw new Error(`Drizzle packed consumer did not complete:\n${drizzleOutput}`);
}
// So does the Kysely dialect, the application's own kysely.
const kyselyOutput = run(process.execPath, ['node/kysely.mjs'], appDirectory, {
timeout: 30_000,
});
if (!kyselyOutput.includes('NODE_KYSELY_CONSUMER_OK')) {
throw new Error(`Kysely packed consumer did not complete:\n${kyselyOutput}`);
}
// A damaged install must reject create() and stop its Worker. Keep the
// installed browser consumer and the repository's build artifacts intact.
const damagedApp = resolve(generatedRoot, 'node-missing-wasm');
const damagedPackage = resolve(damagedApp, 'node_modules/tinyjoin');
await mkdir(dirname(damagedPackage), {recursive: true});
await cp(installedPackage, damagedPackage, {recursive: true});
await rm(resolve(damagedPackage, 'wasm/tinyjoin_wasm_bg.wasm'));
await cp(
resolve(root, 'test/consumers/node/missing-wasm.mjs'),
resolve(damagedApp, 'main.mjs'),
);
const output = run(process.execPath, ['main.mjs'], damagedApp, {
timeout: 30_000,
});
if (!output.includes('NODE_MISSING_WASM_REJECTED')) {
throw new Error(`Node missing-WASM consumer did not complete:\n${output}`);
}
console.log('NODE_DECLARATIONS_OK');
console.log('NODE_MEMORY_CONSUMER_OK');
console.log('NODE_DRIZZLE_CONSUMER_OK');
console.log('NODE_KYSELY_CONSUMER_OK');
console.log('NODE_MISSING_WASM_REJECTED');
}
async function assertBuildLibRejectsMissingWasmArtifacts() {
for (const missing of wasmArtifacts) {
const fixture = resolve(
generatedRoot,
`missing-${missing.replaceAll('/', '-')}`,
);
await Promise.all(
wasmArtifacts
.filter((artifact) => artifact !== missing)
.map(async (artifact) => {
const path = resolve(fixture, artifact);
await mkdir(dirname(path), {recursive: true});
await writeFile(path, 'fixture');
}),
);
try {
await requireWasmArtifacts(fixture);
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Missing TinyJoin WASM artifacts')
) {
continue;
}
throw error;
}
throw new Error(`Build precondition accepted missing artifact ${missing}`);
}
}
function parsePackOutput(output) {
let parsed;
try {
parsed = JSON.parse(output);
} catch {
throw new Error(`Could not parse npm pack output:\n${output}`);
}
const entry = Array.isArray(parsed) ? parsed[0] : undefined;
if (!entry || typeof entry.filename !== 'string') {
throw new Error(`npm pack did not report a tarball filename:\n${output}`);
}
return entry;
}
function assertPackedFiles(packed, documentationFiles) {
const files = Array.isArray(packed.files)
? packed.files.map((file) => file.path).sort()
: [];
const expected = [
'@types/index.d.ts',
'@types/node/index.d.ts',
'@types/worker/index.d.ts',
'@types/vite/index.d.ts',
'@types/drizzle/index.d.ts',
'@types/kysely/index.d.ts',
'LICENSE',
'README.md',
'RUST_STANDARD_LIBRARY_NOTICES.html',
'THIRD_PARTY_NOTICES.txt',
...documentationFiles,
'package.json',
'index.js',
'node/index.js',
'node/worker-entry.js',
'protocol.js',
'releases.md',
'wasm/tinyjoin_wasm.js',
'wasm/tinyjoin_wasm_bg.wasm',
'worker-opfs/tinyjoin_opfs_runtime.js',
'worker/default-entry.js',
'worker/index.js',
'vite/index.js',
'drizzle/index.js',
'kysely/index.js',
].sort();
const missing = expected.filter((file) => !files.includes(file));
const unexpected = files.filter((file) => !expected.includes(file));
if (missing.length > 0 || unexpected.length > 0) {
throw new Error(
`Packed TinyJoin file inventory changed:\nmissing: ${missing.join(', ') || '(none)'}\nunexpected: ${unexpected.join(', ') || '(none)'}`,
);
}
}
async function assertInstalledOpfsLoader(packageDirectory) {
// The Worker bundle carries the loader, and its quoting is the minifier's
// choice. An application's own bundler still has to find the ignore hints.
const path = resolve(packageDirectory, 'worker/default-entry.js');
const source = await readFile(path, 'utf8');
for (const marker of [
/(['"])\.\.\/worker-opfs\/tinyjoin_opfs_runtime\.js\1/,
/@vite-ignore/,
/webpackIgnore:\s*true/,
]) {
if (!marker.test(source)) {
throw new Error(`Packed OPFS loader is missing ${marker.source}: ${path}`);
}
}
}
async function assertConsumerPrivateRuntimeBoundary(files) {
const javascript = files.filter((file) => file.endsWith('.js'));
const wasm = files.filter((file) => file.endsWith('.wasm'));
const opfsRuntime = javascript.filter((file) =>
/tinyjoin_opfs_runtime(?:-[^/]*)?\.js$/.test(file),
);
const pageWasm = wasm.filter((file) =>
/tinyjoin_wasm_bg(?:-[^/]*)?\.wasm$/.test(file),
);
if (opfsRuntime.length !== 1 || pageWasm.length !== 1 || wasm.length !== 1) {
throw new Error(
`Consumer build did not emit exactly one OPFS runtime and one page WASM:\n${files.join('\n')}`,
);
}
const opfsImplementationMarkers = [
'createOpfsWasmEngine',
'Another TinyJoin worker already has this OPFS database open',
];
const privateOpfsImplementationMarkers = [
'Another TinyJoin worker already has this OPFS database open',
];
const opfsRuntimeSource = await readFile(opfsRuntime[0], 'utf8');
if (Buffer.byteLength(opfsRuntimeSource) > 96 * 1024) {
throw new Error(
`Consumer OPFS runtime exceeds its 96 KiB raw gate: ${opfsRuntime[0]}`,
);
}
for (const marker of opfsImplementationMarkers) {
if (!opfsRuntimeSource.includes(marker)) {
throw new Error(
`OPFS runtime is missing expected implementation marker: ${marker}`,
);
}
}
for (const [pattern, description] of [
[/\bimport\s*\(/, 'a dynamic import'],
[/\bnew URL\s*\(/, 'an unresolved asset URL'],
[
/data:(?:application\/wasm|text\/javascript)/i,
'an inlined runtime or WASM data URL',
],
[/tinyjoin_wasm(?:_bg)?/i, 'default WASM glue'],
[
/WASM returned an invalid structured response envelope/,
'the structured WASM adapter',
],
]) {
if (pattern.test(opfsRuntimeSource)) {
throw new Error(
`OPFS runtime eagerly contains ${description}: ${opfsRuntime[0]}`,
);
}
}
for (const file of javascript) {
if (opfsRuntime.includes(file)) {
continue;
}
const source = await readFile(file, 'utf8');
const leaked = privateOpfsImplementationMarkers.find((marker) =>
source.includes(marker),
);
if (leaked) {
throw new Error(
`Consumer JavaScript eagerly contains OPFS implementation code (${leaked}): ${file}`,
);
}
}
}
async function listFiles(directory) {
const entries = await readdir(directory, {withFileTypes: true});
const files = [];
for (const entry of entries) {
const path = resolve(directory, entry.name);
if (entry.isDirectory()) {
files.push(...(await listFiles(path)));
} else {
files.push(path);
}
}
return files;
}
async function waitForServer(child, url, output) {
const timeoutAt = Date.now() + 30_000;
while (Date.now() < timeoutAt) {
if (child.exitCode !== null) {
throw new Error(`Vite preview exited early:\n${output()}`);
}
try {
const response = await fetch(url);
if (response.ok) {
return;
}
} catch {
// The preview server has not bound its port yet.
}
await new Promise((resolvePromise) => setTimeout(resolvePromise, 100));
}
throw new Error(`Timed out waiting for Vite preview:\n${output()}`);
}
async function exercise(page, url) {
await page.goto(url);
const text = await waitForConsumerResult(page, 'packed consumer');
const result = JSON.parse(text ?? 'null');
if (
result.preparedClosed !== true ||
result.initialRevision !== 2 ||
result.initialTitle !== 'from packed insert' ||
result.changedRevision !== 3 ||
result.changedTitle !== 'from packed update'
) {
throw new Error(`Unexpected packed-consumer result: ${text}`);
}
return result;
}
async function exerciseMemory(page, url, requests) {
return captureLazyRequests(requests, {opfs: false}, () =>
exercise(page, url),
);
}
async function exerciseFreshOpfs(page, url, requests) {
return captureLazyRequests(requests, {opfs: true}, () => exercise(page, url));
}
async function exercisePersisted(page, url) {
await page.goto(url);
const text = await waitForConsumerResult(page, 'packed OPFS restart');
const result = JSON.parse(text ?? 'null');
if (
result.preparedClosed !== true ||
result.revision !== 3 ||
result.title !== 'from packed update'
) {
throw new Error(`Unexpected packed OPFS restart result: ${text}`);
}
return result;
}
async function exercisePersistedOpfs(page, url, requests) {
return captureLazyRequests(requests, {opfs: true}, () =>
exercisePersisted(page, url),
);
}
async function waitForConsumerResult(page, description) {
await page
.locator(
'body[data-status="passed"][data-closed="true"], body[data-status="failed"]',
)
.waitFor({timeout: 30_000});
const [status, text] = await Promise.all([
page.locator('body').getAttribute('data-status'),
page.locator('#result').textContent(),
]);
if (status === 'failed') {
throw new Error(
`${description} failed: ${text ?? 'unknown browser error'}`,
);
}
return text;
}
async function captureLazyRequests(requests, expected, exerciseRuntime) {
const firstRequest = requests.length;
const result = await exerciseRuntime();
const capturedRequests = requests.slice(firstRequest);
const opfsRequests = capturedRequests.filter((url) =>
isOpfsRuntimeRequest(url),
);
if (expected.opfs && opfsRequests.length !== 1) {
throw new Error(
`Packed OPFS runtime did not lazily load exactly one runtime chunk: ${capturedRequests.join(', ')}`,
);
}
if (!expected.opfs && opfsRequests.length > 0) {
throw new Error(
`Memory packed runtime unexpectedly loaded OPFS code: ${opfsRequests.join(', ')}`,
);
}
return result;
}
function isOpfsRuntimeRequest(url) {
return url.includes('tinyjoin_opfs_runtime') || url.includes('/worker-opfs/');
}
async function stopServer(child) {
if (
(child.exitCode !== null || child.signalCode !== null) &&
child.stdout.destroyed &&
child.stderr.destroyed
) {
return;
}
await new Promise((resolvePromise, reject) => {
const forceStop = setTimeout(() => {
child.kill('SIGKILL');
}, 5_000);
const deadline = setTimeout(() => {
child.stdout.destroy();
child.stderr.destroy();
finish(new Error('Packed consumer preview did not close within 10 seconds'));
}, 10_000);
const finish = (error) => {
clearTimeout(forceStop);
clearTimeout(deadline);
child.removeListener('close', onClose);
child.removeListener('error', finish);
if (error) reject(error);
else resolvePromise();
};
const onClose = () => finish();
// "exit" only covers the process; "close" also covers its output pipes.
child.once('close', onClose);
child.once('error', finish);
child.kill('SIGTERM');
});
}