Repository navigation
Expand file tree
/
Copy pathapi-docs.test.mjs
More file actions
590 lines (574 loc) · 18.5 KB
/
Copy pathapi-docs.test.mjs
File metadata and controls
590 lines (574 loc) · 18.5 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
/**
* Copyright 2026 Adobe
* All Rights Reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file in
* accordance with the terms of the Adobe license agreement accompanying
* it.
*/
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import {
mkdir,
mkdtemp,
readFile,
readdir,
rm,
writeFile
} from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { Application, TSConfigReader } from 'typedoc';
import {
ROOT,
PACKAGES,
buildSite,
generateDocs,
installRelease,
loadVersions,
writeAliases
} from './generate-api-docs.mjs';
import { versionLine } from './api-docs-manifest.mjs';
const VERSIONS = {
node: ['0.10.1', '0.9.12'],
web: ['0.16.1', '0.15.4']
};
async function fixture(t) {
const root = await mkdtemp(path.join(os.tmpdir(), 'api-docs-test-'));
t.after(() => rm(root, { recursive: true, force: true }));
await mkdir(path.join(root, 'api-docs'));
for (const [key, versions] of Object.entries(VERSIONS)) {
await writeFile(
path.join(root, `api-docs/${key}-versions.json`),
JSON.stringify({
versions,
retiredLines: [],
aliases: Object.fromEntries(versions.map((version) => [version, versionLine(version)]))
})
);
}
return root;
}
test('generated docs are ignored while docs and API source files remain trackable', () => {
const generated = [
'api-docs/index.html',
'api-docs/.nojekyll',
'api-docs/assets/main.js',
'api-docs/node/index.html',
'api-docs/web/versions/0.15.4/index.html',
'packages/c2pa-web/api-docs/index.html'
];
const sources = [
'docs/guide.md',
'packages/c2pa-web/docs/guide.md',
'api-docs/node-versions.json',
'api-docs/web-versions.json',
'api-docs/version-selector.js',
'api-docs/version-selector.css'
];
const ignored = execFileSync(
'git',
['check-ignore', '--no-index', '--stdin'],
{
cwd: ROOT,
input: [...generated, ...sources].join('\n') + '\n',
encoding: 'utf8'
}
);
assert.deepEqual(ignored.trim().split('\n'), generated);
});
test('multi-package TypeDoc output preserves API sources and other docs', async (t) => {
const root = await fixture(t);
const options = JSON.parse(
await readFile(path.join(ROOT, 'typedoc.json'), 'utf8')
);
assert.equal(options.out, 'api-docs');
assert.equal(options.cleanOutputDir, false);
const output = path.join(root, options.out);
const sources = ['node-versions.json', 'web-versions.json'];
for (const filename of ['version-selector.js', 'version-selector.css']) {
await writeFile(path.join(output, filename), '/* Source asset */');
sources.push(filename);
}
await mkdir(path.join(output, 'node'));
await writeFile(path.join(output, 'node/index.html'), 'Versioned site');
sources.push('node/index.html');
const before = await Promise.all(
sources.map((filename) => readFile(path.join(output, filename), 'utf8'))
);
await mkdir(path.join(root, 'docs'));
await writeFile(path.join(root, 'docs/guide.md'), 'Handwritten guide');
const entryPoint = path.join(root, 'index.d.ts');
await writeFile(entryPoint, 'export declare function read(): string;');
const tsconfig = path.join(root, 'tsconfig.json');
await writeFile(
tsconfig,
JSON.stringify({
compilerOptions: { skipLibCheck: true },
files: [entryPoint]
})
);
const app = await Application.bootstrap(
{
...options,
entryPoints: [entryPoint],
entryPointStrategy: 'resolve',
tsconfig,
readme: 'none',
out: output
},
[new TSConfigReader()]
);
const project = await app.convert();
assert.ok(project);
assert.equal(app.logger.hasErrors(), false);
await app.generateDocs(project, output);
assert.equal(app.logger.hasErrors(), false);
assert.match(await readFile(path.join(output, 'index.html'), 'utf8'), /read/);
for (const [index, filename] of sources.entries()) {
assert.equal(
await readFile(path.join(output, filename), 'utf8'),
before[index]
);
}
assert.equal(
await readFile(path.join(root, 'docs/guide.md'), 'utf8'),
'Handwritten guide'
);
});
test('versions preserve each configured default and order', async (t) => {
const root = await fixture(t);
for (const [key, versions] of Object.entries(VERSIONS)) {
assert.deepEqual(
await loadVersions(path.join(root, `api-docs/${key}-versions.json`)),
versions
);
}
});
test('invalid lists, ranges, tags and unsafe versions are rejected', async (t) => {
const root = await fixture(t);
const filename = path.join(root, 'api-docs/web-versions.json');
for (const value of [
null,
[],
{},
{ versions: '0.15.4' },
...[
[],
['0.15.4', '0.15.4'],
['0.15.4', '0.15.3'],
['0.14.0', '0.15.4'],
['0.15.4-rc.1'],
['latest'],
['^0.15.4'],
['../main'],
['--help'],
['v0.15.4'],
['0.15.4\n'],
['01.15.4'],
[15],
[null]
].map((versions) => ({ versions, retiredLines: [], aliases: {} }))
]) {
await writeFile(filename, JSON.stringify(value));
await assert.rejects(loadVersions(filename), /unique exact npm versions/);
}
});
test('unknown package keys are rejected before accessing files', async (t) => {
const root = await fixture(t);
for (const key of ['../web', 'constructor', '__proto__', '', undefined]) {
await assert.rejects(
buildSite(key, root),
/Choose a documentation package/
);
}
assert.deepEqual(await readdir(root), ['api-docs']);
});
for (const [key, packageInfo] of Object.entries(PACKAGES)) {
const versions = VERSIONS[key];
const version = versions[0];
test(`${key}: npm installs the exact release without lifecycle scripts`, async (t) => {
const root = await fixture(t);
const packageRoot = path.join(root, 'node_modules', packageInfo.name);
const execute = async (command, args, options) => {
assert.equal(command, 'npm');
assert.equal(options.cwd, root);
for (const flag of [
'--ignore-scripts',
'--workspaces=false',
'--package-lock=false',
'--registry=https://registry.npmjs.org'
]) {
assert.ok(args.includes(flag), flag);
}
const manifest = JSON.parse(
await readFile(path.join(root, 'package.json'))
);
assert.deepEqual(manifest.dependencies, { [packageInfo.name]: version });
await mkdir(packageRoot, { recursive: true });
await writeFile(
path.join(packageRoot, 'package.json'),
JSON.stringify({ name: packageInfo.name, version })
);
};
assert.equal(
await installRelease(packageInfo, version, root, execute),
packageRoot
);
});
test(`${key}: mismatched installed packages fail explicitly`, async (t) => {
const root = await fixture(t);
const packageRoot = path.join(root, 'node_modules', packageInfo.name);
await mkdir(packageRoot, { recursive: true });
for (const manifest of [
{ name: packageInfo.name, version: versions[1] },
{ name: 'other-package', version }
]) {
await writeFile(
path.join(packageRoot, 'package.json'),
JSON.stringify(manifest)
);
await assert.rejects(
installRelease(packageInfo, version, root, async () => undefined),
/npm installed a different package/
);
}
});
test(`${key}: builds preserve other sites and publish the first version at the package root`, async (t) => {
const root = await fixture(t);
const other = key === 'web' ? 'node' : 'web';
await mkdir(path.join(root, 'api-docs', other), { recursive: true });
await writeFile(
path.join(root, 'api-docs/index.html'),
'Multi-package site'
);
await writeFile(
path.join(root, 'api-docs', other, 'index.html'),
'Other release site'
);
await mkdir(path.join(root, 'docs'));
await writeFile(path.join(root, 'docs/guide.md'), 'Handwritten guide');
await writeFile(
path.join(root, 'api-docs/version-selector.js'),
'// Source'
);
const installed = [];
const generated = [];
const install = async (info, version, stage) => {
assert.equal(info, packageInfo);
installed.push(version);
return stage;
};
const generate = async (
root,
info,
packageRoot,
output,
version,
versions,
prefix
) => {
assert.equal(info, packageInfo);
generated.push({ version, prefix });
await mkdir(output, { recursive: true });
await writeFile(path.join(output, 'index.html'), `${version}:${prefix}`);
};
const site = await buildSite(key, root, install, generate);
assert.equal(site, path.join(root, 'api-docs', key));
assert.deepEqual(installed, versions);
assert.equal(generated.length, 3);
assert.equal(
await readFile(path.join(site, 'index.html'), 'utf8'),
`${version}:`
);
for (const version of versions) {
assert.equal(
await readFile(
path.join(site, 'versions', versionLine(version), 'index.html'),
'utf8'
),
`${version}:versions/${versionLine(version)}`
);
}
assert.equal(
await readFile(path.join(root, 'api-docs/index.html'), 'utf8'),
'Multi-package site'
);
assert.equal(
await readFile(path.join(root, 'api-docs', other, 'index.html'), 'utf8'),
'Other release site'
);
assert.equal(
await readFile(path.join(root, 'api-docs/.nojekyll'), 'utf8'),
''
);
assert.deepEqual(
await loadVersions(path.join(root, `api-docs/${key}-versions.json`)),
versions
);
assert.equal(
await readFile(path.join(root, 'api-docs/version-selector.js'), 'utf8'),
'// Source'
);
assert.equal(
await readFile(path.join(root, 'docs/guide.md'), 'utf8'),
'Handwritten guide'
);
assert.deepEqual(await readdir(path.join(root, 'docs')), ['guide.md']);
assert.deepEqual(await readdir(path.join(root, 'tmp')), []);
});
test(`${key}: failed builds preserve output and clean temporary installs`, async (t) => {
const root = await fixture(t);
const output = path.join(root, 'api-docs', key);
await mkdir(output, { recursive: true });
await writeFile(path.join(output, 'index.html'), 'Previous build');
await assert.rejects(
buildSite(key, root, async () => {
throw new Error('npm is unavailable');
}),
/npm is unavailable/
);
await assert.rejects(
buildSite(
key,
root,
async (info, version, stage) => stage,
async () => {
throw new Error('TypeDoc rendering failed');
}
),
/TypeDoc rendering failed/
);
assert.equal(
await readFile(path.join(output, 'index.html'), 'utf8'),
'Previous build'
);
assert.deepEqual(await readdir(path.join(root, 'tmp')), []);
});
test(`${key}: TypeDoc renders visible public declarations without running package code`, async (t) => {
const root = await fixture(t);
const packageRoot = path.join(root, 'node_modules', packageInfo.name);
for (const entry of packageInfo.entryPoints) {
const filename = path.join(packageRoot, entry);
await mkdir(path.dirname(filename), { recursive: true });
await writeFile(
filename,
entry.endsWith('/inline.d.ts')
? '/** Creates the inline SDK. */\nexport declare function createC2pa(): Promise<string>;\n'
: '/** Reads C2PA data. */\nexport declare class Reader { json(): string; }\n' +
'export interface C2pa {\n/** @internal */\nworker: string;\ndispose(): void;\n}\n'
);
}
const sourceReadme =
'# Published API\n\n[Prerequisites](../../README.md#prerequisites)\n\n[Versions](../../api-docs/web-versions.json)\n';
await writeFile(path.join(packageRoot, 'README.md'), sourceReadme);
await writeFile(
path.join(packageRoot, 'typedoc.mjs'),
"throw new Error('Do not execute package code');"
);
const output = path.join(root, 'rendered');
await generateDocs(
ROOT,
packageInfo,
packageRoot,
output,
version,
versions,
`versions/${version}`
);
const readerPage =
key === 'web' ? 'classes/index.Reader.html' : 'classes/Reader.html';
const dom = new JSDOM(
await readFile(path.join(output, readerPage), 'utf8')
);
assert.equal(dom.window.document.querySelector('.tsd-is-external'), null);
assert.deepEqual(
JSON.parse(
dom.window.document.querySelector('meta[name="c2pa-docs"]').content
),
{
label: packageInfo.label,
version,
versions,
prefix: `versions/${version}`
}
);
assert.equal(
dom.window.document
.querySelector('script[src$="custom.js"]')
.getAttribute('src'),
'../assets/custom.js'
);
const index = new JSDOM(
await readFile(path.join(output, 'index.html'), 'utf8')
);
assert.ok(
index.window.document.querySelector(
'a[href="https://github.com/contentauth/c2pa-js/blob/main/README.md#prerequisites"]'
)
);
assert.ok(
index.window.document.querySelector(
'a[href="https://github.com/contentauth/c2pa-js/blob/main/api-docs/web-versions.json"]'
)
);
assert.equal(
await readFile(path.join(packageRoot, 'README.md'), 'utf8'),
sourceReadme
);
if (key === 'web') {
const inline = new JSDOM(
await readFile(
path.join(output, 'functions/inline.createC2pa.html'),
'utf8'
)
);
assert.equal(
inline.window.document.querySelector('.tsd-is-external'),
null
);
assert.match(
inline.window.document.body.textContent,
/Creates the inline SDK/
);
const sdk = new JSDOM(
await readFile(path.join(output, 'interfaces/index.C2pa.html'), 'utf8')
);
assert.equal(sdk.window.document.getElementById('worker'), null);
inline.window.close();
sdk.window.close();
}
index.window.close();
dom.window.close();
});
}
const selectorSource = await readFile(
path.join(ROOT, 'api-docs/version-selector.js'),
'utf8'
);
for (const [key, packageInfo] of Object.entries(PACKAGES)) {
const versions = VERSIONS[key];
for (const base of [
`https://contentauth.github.io/c2pa-js/${key}/`,
`file:///tmp/api-docs/${key}/`
]) {
for (const prefix of [
'',
...versions.map((version) => `versions/${versionLine(version)}`)
]) {
test(`selector links and navigation: ${base}${prefix}`, () => {
const version = prefix
? versions.find((value) => versionLine(value) === prefix.split('/').pop())
: versions[0];
function element() {
return {
children: [],
appendChild(child) {
this.children.push(child);
},
setAttribute(name, value) {
this[name] = value;
},
addEventListener(event, callback) {
this[event] = callback;
}
};
}
const toolbar = element();
let destination;
vm.runInNewContext(selectorSource, {
URL,
document: {
currentScript: {
src: new URL(
(prefix ? prefix + '/' : '') + 'assets/custom.js',
base
).href
},
querySelector(selector) {
if (selector === 'meta[name="c2pa-docs"]') {
return {
content: JSON.stringify({
label: packageInfo.label,
version,
versions,
prefix
})
};
}
assert.equal(selector, '.tsd-toolbar-contents');
return toolbar;
},
createElement: element
},
window: {
location: {
assign(url) {
destination = url;
}
}
}
});
const select = toolbar.children[0].children[0];
assert.equal(
select['aria-label'],
packageInfo.label + ' API documentation version'
);
assert.equal(select.children.length, versions.length);
for (const [index, option] of select.children.entries()) {
assert.equal(
option.value,
base + 'versions/' + versionLine(versions[index]) + '/index.html'
);
assert.equal(option.textContent, versionLine(versions[index]));
assert.equal(option.title, 'Generated from ' + versions[index]);
assert.equal(option.selected, versions[index] === version);
}
select.value = select.children[1].value;
select.change();
assert.equal(
destination,
base + 'versions/' + versionLine(versions[1]) + '/index.html'
);
assert.equal(
toolbar.children[1].href,
new URL('../index.html', base).href
);
});
}
test('legacy exact-version pages redirect nested paths, query strings and fragments to their line', async (t) => {
const root = await fixture(t);
const canonical = path.join(root, 'versions/0.16');
await mkdir(path.join(canonical, 'classes'), { recursive: true });
for (const page of ['index.html', 'classes/Reader.html']) {
await writeFile(path.join(canonical, page), 'Canonical API docs');
}
await writeAliases(root, { '0.16.0': '0.16', '0.16.1': '0.16' });
for (const alias of ['0.16.0', '0.16.1']) {
for (const page of ['index.html', 'classes/Reader.html']) {
const base = `https://contentauth.github.io/c2pa-js/web/versions/${alias}/${page}`;
const dom = new JSDOM(
await readFile(path.join(root, 'versions', alias, page), 'utf8'),
{ url: base }
);
let destination;
vm.runInNewContext(dom.window.document.querySelector('script').textContent, {
location: {
search: '?example=1',
hash: '#json',
replace(value) { destination = new URL(value, base).href; }
}
});
assert.equal(destination,
`https://contentauth.github.io/c2pa-js/web/versions/0.16/${page}?example=1#json`);
assert.equal(dom.window.document.querySelector('a').href,
`https://contentauth.github.io/c2pa-js/web/versions/0.16/${page}`);
dom.window.close();
}
}
});
}
}