/**
* What the snippet check (`snippets.mjs`) and the example check (`samples.mjs`) share: where they
* compile, each framework's compiler and options, and how a compiler's diagnostics read.
*
* Both copy their files into a run directory of their own in the system's temporary directory,
* whose `node_modules` links to the embedpdf.com site's (`website/`), which has every framework
* installed. Two checks running at the same time never touch each other's files, and nothing is
* staged under a `node_modules` path, where `svelte-check` reports nothing. Workspace packages
* resolve to their source, so nothing needs building first. Every run also compiles a canary, a
* file with known errors: a compiler that doesn't report them isn't checking, and fails the run.
*/
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { ENGINES } from '../engines.mjs';
export const contentRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export const repoRoot = path.resolve(contentRoot, '../..');
export const siteRoot = path.join(repoRoot, 'website');
export const siteRequire = createRequire(path.join(siteRoot, 'package.json'));
export const FRAMEWORKS = ['react', 'vue', 'svelte', 'angular'];
/** The viewer's docs have a plain-HTML version too: `vanilla`, a page with a script tag. */
export const VIEWER_INTEGRATIONS = ['vanilla', ...FRAMEWORKS];
export const FRAMEWORK_LABELS = {
vanilla: 'Vanilla JS',
react: 'React',
vue: 'Vue',
svelte: 'Svelte',
angular: 'Angular',
};
/**
* The viewer's CDN script, as each site's docs show it (`engines.mjs`): the only URL a plain-HTML
* page loads it from. embedpdf.com's is {@link VIEWER_CDN_URL}.
*/
export const VIEWER_CDN_URLS = Object.fromEntries(
Object.entries(ENGINES).map(([engine, { viewer }]) => [engine, viewer.cdnScript]),
);
export const VIEWER_CDN_URL = VIEWER_CDN_URLS.local;
export const toPosix = (file) => file.split(path.sep).join('/');
export function walk(directory) {
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const absolute = path.join(directory, entry.name);
return entry.isDirectory() ? walk(absolute) : [absolute];
});
}
/**
* This repository's packages, by name: the folder each is in, from the repository's root, its
* `package.json`, and whether it is published.
*/
export function workspacePackages() {
const listed = spawnSync(
'git',
['ls-files', '--cached', '--others', '--exclude-standard', '--', '*package.json'],
{
cwd: repoRoot,
encoding: 'utf8',
},
);
const packages = new Map();
for (const file of listed.stdout.split('\n').filter(Boolean)) {
try {
const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, file), 'utf8'));
if (manifest.name) {
packages.set(manifest.name, {
directory: path.posix.dirname(file),
manifest,
published: manifest.private !== true,
});
}
} catch {
// A manifest that doesn't parse names nothing.
}
}
return packages;
}
// ── options ─────────────────────────────────────────────────────────────────
export const COMPILER_OPTIONS = {
target: 'ES2022',
module: 'ESNext',
moduleResolution: 'bundler',
// Workspace packages point `development` (or a plain string) at their source.
customConditions: ['development'],
moduleDetection: 'force',
strict: true,
skipLibCheck: true,
esModuleInterop: true,
isolatedModules: true,
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
types: [],
noEmit: true,
};
/** What each framework's own projects set on top of {@link COMPILER_OPTIONS}. */
const FRAMEWORK_OPTIONS = {
react: { compilerOptions: { jsx: 'react-jsx' } },
angular: {
compilerOptions: { experimentalDecorators: true, useDefineForClassFields: false },
angularCompilerOptions: { strictTemplates: true },
},
vue: {
compilerOptions: { jsx: 'preserve' },
// Like Angular's `strictTemplates`: a component, prop, event or slot prop the adapter doesn't
// have is an error, not an unknown element or a fallthrough attribute. `data-*` attributes
// are the reader's own, on any element.
vueCompilerOptions: { strictTemplates: true, dataAttributes: ['data-*'] },
},
svelte: {
compilerOptions: {
verbatimModuleSyntax: true,
// A Svelte package names its source under the `svelte` condition.
customConditions: ['development', 'svelte'],
// SvelteKit's `$app/*` modules, which a snippet written for a SvelteKit app imports.
types: ['@sveltejs/kit'],
},
},
// A plain-HTML page's scripts, as JavaScript checked against the viewer's types. Not strict: a
// reader's JavaScript doesn't check for null or annotate its parameters. A page loads the
// viewer for its side effects (`import '…/embedpdf.js'`), so that import must resolve too.
vanilla: {
compilerOptions: {
allowJs: true,
checkJs: true,
strict: false,
noUncheckedSideEffectImports: true,
},
},
};
/**
* Bare imports the site can't resolve, or would resolve to a build: the cloud engine and the
* Angular adapter at their source, and RxJS (whose `Observable` the Angular events are) where the
* adapter gets it.
*/
export function resolvePaths() {
const angular = path.join(repoRoot, 'packages/framework/angular');
const rxjs = path.dirname(
createRequire(path.join(angular, 'package.json')).resolve('rxjs/package.json'),
);
return {
'@cloudpdf/engine': [path.join(repoRoot, 'cloudpdf/engine/src/index.ts')],
'@embedpdf/angular': [path.join(angular, 'src/public_api.ts')],
'@embedpdf/angular/*': [path.join(angular, '*/src/public_api.ts')],
rxjs: [rxjs],
'rxjs/*': [path.join(rxjs, '*')],
// SvelteKit's alias for the reader's own modules.
'$lib/*': ['./_lib/*'],
};
}
/**
* Both doors of the viewer at their source, under each name the docs import them by: `@embedpdf/viewer`'s
* entries and CDN script, and cloudpdf.com's, `@cloudpdf/viewer`, its CDN script and its framework
* packages, which the embedpdf.com site the checks resolve from doesn't install. `@embedpdf/viewer`
* names only its build, which the docs check never needs.
*/
function viewerPaths() {
const doors = path.join(repoRoot, 'packages/viewer/main/src/doors');
const cloud = path.join(repoRoot, 'cloudpdf/viewer');
return {
'@embedpdf/viewer': [path.join(doors, 'local.ts')],
'@embedpdf/viewer/portable': [path.join(doors, 'portable.ts')],
'@embedpdf/viewer/core': [path.join(doors, 'core.ts')],
'@embedpdf/viewer/snippet': [path.join(doors, 'snippet.ts')],
[VIEWER_CDN_URLS.local]: [path.join(doors, 'snippet.ts')],
'@cloudpdf/viewer': [path.join(cloud, 'main/src/index.ts')],
'@cloudpdf/viewer/snippet': [path.join(cloud, 'main/src/index.ts')],
[VIEWER_CDN_URLS.cloud]: [path.join(cloud, 'main/src/index.ts')],
...Object.fromEntries(
FRAMEWORKS.map((framework) => [
`@cloudpdf/viewer-${framework}`,
[path.join(cloud, framework, 'src/index.ts')],
]),
),
};
}
/**
* Write the tsconfig one framework's files compile with: `include` names them, and `overrides`
* changes one of the framework's option groups (`{ vueCompilerOptions: {…} }`). With `viewer`,
* the files read the viewer at its source, either door ({@link viewerPaths}), which is `.tsx`:
* JSX is on, or a program leaves those files out.
*/
export function writeTsconfig(framework, root, include, overrides = {}, { viewer = false } = {}) {
const groups = { ...FRAMEWORK_OPTIONS[framework] };
for (const [group, options] of Object.entries(overrides)) {
groups[group] = { ...groups[group], ...options };
}
const { compilerOptions, ...rest } = groups;
const tsconfig = {
compilerOptions: {
...COMPILER_OPTIONS,
...(viewer ? { jsx: 'react-jsx' } : {}),
...compilerOptions,
paths: { ...resolvePaths(), ...(viewer ? viewerPaths() : {}) },
},
include,
...rest,
};
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'tsconfig.json'), `${JSON.stringify(tsconfig, null, 2)}\n`);
}
// ── run directories ─────────────────────────────────────────────────────────
/**
* A fresh run directory for one check, outside any `node_modules`: `svelte-check` skips every
* file under one. Its `node_modules` links to the site's, so the files staged in it resolve every
* framework the site has. The caller removes it with {@link removeRunDirectory}.
*/
export function runDirectory(name) {
const parent = path.join(fs.realpathSync(os.tmpdir()), name);
fs.mkdirSync(parent, { recursive: true });
const run = fs.mkdtempSync(path.join(parent, 'run-'));
fs.symlinkSync(path.join(siteRoot, 'node_modules'), path.join(run, 'node_modules'), 'junction');
return run;
}
/** Remove a run directory: the link to the site's `node_modules` first, never what it points at. */
export function removeRunDirectory(run) {
fs.rmSync(path.join(run, 'node_modules'), { force: true });
fs.rmSync(run, { recursive: true, force: true });
}
// ── the canary ──────────────────────────────────────────────────────────────
const EXPECTED = 'error expected';
/**
* A file each framework's compiler must reject on every line marked `error expected`: a name a
* module doesn't export, a module that doesn't exist, and a template naming nothing. A compiler
* that misses one reads unresolved imports as `any`, or never looked at the file.
*/
const CANARIES = {
react: {
file: '_canary.react.tsx',
source: `// The check's canary (compile.mjs): each marked line must be an error.
import { useState, notAReactExport } from 'react'; // ${EXPECTED}
import { anything } from '@embedpdf/not-a-package'; // ${EXPECTED}
export const Canary = () =>
{notAField}
; // ${EXPECTED}
`,
},
angular: {
file: '_canary.angular.ts',
source: `// The check's canary (compile.mjs): each marked line must be an error.
import { Component, notAnAngularExport } from '@angular/core'; // ${EXPECTED}
import { anything } from '@embedpdf/not-a-package'; // ${EXPECTED}
@Component({
selector: 'canary-root',
template: '
`,
},
// A plain-HTML page's script, after the check took it out of the page: a member the viewer
// doesn't have, and an element the page names that the viewer doesn't define.
vanilla: {
file: '_canary.vanilla.js',
source: `// The check's canary (compile.mjs): each marked line must be an error.
import EmbedPDF, { notAViewerExport } from '${VIEWER_CDN_URL}'; // ${EXPECTED}
import { anything } from '@embedpdf/not-a-package'; // ${EXPECTED}
import '@embedpdf/not-a-package/loaded-for-its-side-effects'; // ${EXPECTED}
EmbedPDF.notAViewerMethod(); // ${EXPECTED}
/** @type {HTMLElementTagNameMap['epdf-not-an-element']} */ (undefined); // ${EXPECTED}
`,
},
};
/** Whether a file is a run's canary (at the root of the run, named `_canary..`). */
const isCanary = (root, file) =>
path.dirname(file) === root && path.basename(file).startsWith('_canary.');
function writeCanary(framework, root) {
const { file, source } = CANARIES[framework];
fs.mkdirSync(root, { recursive: true });
const absolute = path.join(root, file);
fs.writeFileSync(absolute, source);
const lines = source
.split('\n')
.flatMap((line, index) => (line.includes(EXPECTED) ? [index + 1] : []));
return { file: absolute, lines };
}
// ── the compilers ───────────────────────────────────────────────────────────
/** The tool a framework compiles with, from the site: `{ version, entry }`, or null when it isn't installed. */
export function findTool(name, bin) {
try {
const manifest = siteRequire.resolve(`${name}/package.json`);
const { version } = JSON.parse(fs.readFileSync(manifest, 'utf8'));
return { version, entry: bin ? path.join(path.dirname(manifest), bin) : manifest };
} catch {
return null;
}
}
export function fromTypeScript(ts, diagnostics) {
return diagnostics
.filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)
.map((diagnostic) => {
const position =
diagnostic.file && diagnostic.start !== undefined
? diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
: null;
return {
file: diagnostic.file ? path.resolve(diagnostic.file.fileName) : null,
line: position ? position.line + 1 : null,
column: position ? position.character + 1 : null,
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),
code: diagnostic.code,
};
});
}
/**
* The files of a program that the check owns: only they are checked. The packages they import are
* read for their types, not checked themselves, which keeps the check fast (and a package's own
* errors are its own check's business). `checks(file)` narrows it further, such as to one area.
*/
const checkedFiles = (program, root, checks) =>
program.getSourceFiles().filter((file) => {
const absolute = path.resolve(file.fileName);
return absolute.startsWith(`${root}${path.sep}`) && checks(absolute);
});
/**
* Compile a React (or plain TypeScript) tree with `tsc`, in this process. `ignores(ts, program,
* diagnostic)` drops the diagnostics a check doesn't report.
*/
async function compileWithTsc(root, checks, ignores = () => false) {
const tool = findTool('typescript');
if (!tool) return { tool: null, reason: "typescript isn't installed in website/" };
const ts = siteRequire('typescript');
const config = ts.getParsedCommandLineOfConfigFile(
path.join(root, 'tsconfig.json'),
{},
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} },
);
const program = ts.createProgram({ rootNames: config.fileNames, options: config.options });
const diagnostics = [
...program.getOptionsDiagnostics(),
...program.getGlobalDiagnostics(),
...checkedFiles(program, root, checks).flatMap((file) => [
...program.getSyntacticDiagnostics(file),
...program.getSemanticDiagnostics(file),
]),
].filter((diagnostic) => !ignores(ts, program, diagnostic));
return { tool: `tsc ${tool.version}`, diagnostics: fromTypeScript(ts, diagnostics) };
}
/** The deepest node of a file that holds `position`. */
function nodeAt(ts, file, position) {
let found = file;
const visit = (node) => {
if (position < node.getStart(file) || position >= node.getEnd()) return;
found = node;
ts.forEachChild(node, visit);
};
ts.forEachChild(file, visit);
return found;
}
/**
* The value a property name reads from: `element` in `element.viewer`, and in
* `const { viewer } = element`. Null for any other name.
*/
function readFrom(ts, name) {
const parent = name.parent;
if (parent && ts.isPropertyAccessExpression(parent) && parent.name === name) {
return parent.expression;
}
const declaration = parent?.parent?.parent;
if (
parent &&
ts.isBindingElement(parent) &&
(parent.propertyName ?? parent.name) === name &&
ts.isObjectBindingPattern(parent.parent) &&
declaration &&
ts.isVariableDeclaration(declaration) &&
declaration.initializer
) {
return declaration.initializer;
}
return null;
}
const PROPERTY_MISSING = new Set([
2339, // Property 'value' does not exist on type 'EventTarget'.
2551, // …Did you mean 'values'?
]);
/**
* A plain-HTML page's own DOM code: in one of its scripts, a property a browser type doesn't have
* (`event.target.value`, where the target is an `EventTarget`). Nothing checks the types of a
* reader's JavaScript, so that's fine there; a property one of our types doesn't have is still an
* error, and so is anything else. A browser type is one TypeScript's DOM library declares, even
* where a package adds to it (`@types/react` declares an empty `HTMLElement`).
*/
function isReadersDomCode(ts, program, diagnostic) {
const { file, start } = diagnostic;
if (!PROPERTY_MISSING.has(diagnostic.code) || !file || start === undefined) return false;
if (!/\.js$/.test(file.fileName)) return false;
const object = readFrom(ts, nodeAt(ts, file, start));
if (!object) return false;
const type = program.getTypeChecker().getTypeAtLocation(object);
return (type.isUnion() ? type.types : [type]).every((member) =>
((member.getSymbol() ?? member.aliasSymbol)?.declarations ?? []).some((declaration) => {
const declared = declaration.getSourceFile();
return (
program.isSourceFileDefaultLibrary(declared) &&
/^lib\.dom\b/.test(path.basename(declared.fileName))
);
}),
);
}
/** Compile a plain-HTML page's scripts, taken out of the page, as JavaScript with `tsc`. */
const compileVanilla = (root, checks) => compileWithTsc(root, checks, isReadersDomCode);
/** Compile an Angular tree with `ngc` and `strictTemplates`, in this process. */
async function compileWithNgc(root, checks) {
const tool = findTool('@angular/compiler-cli');
if (!tool) return { tool: null, reason: "@angular/compiler-cli isn't installed in website/" };
const ts = siteRequire('typescript');
const ngc = await import(pathToFileURL(siteRequire.resolve('@angular/compiler-cli')).href);
const config = ngc.readConfiguration(path.join(root, 'tsconfig.json'));
const { diagnostics } = ngc.performCompilation({
rootNames: config.rootNames,
options: { ...config.options, noEmit: true },
emitFlags: config.emitFlags,
// ngc stops at the first stage with an error, so one file's missing import would hide every
// template error in the others. Every stage, for each checked file:
gatherDiagnostics: (program) => [
...program.getTsOptionDiagnostics(),
...program.getNgOptionDiagnostics(),
...checkedFiles(program.getTsProgram(), root, checks).flatMap((file) => [
...program.getTsSyntacticDiagnostics(file),
...program.getTsSemanticDiagnostics(file),
...program.getNgSemanticDiagnostics(file.fileName),
...unexportedDeclarations(ts, file),
]),
],
});
return {
tool: `ngc ${tool.version}`,
diagnostics: fromTypeScript(ts, [...config.errors, ...diagnostics]),
};
}
const ANGULAR_DECLARATIONS = new Set(['Component', 'Directive', 'Pipe']);
const UNEXPORTED = 'ngc stops reporting template errors when';
/**
* A component, directive or pipe a file declares without exporting it, as an error. ngc can't
* type-check a template that uses one the usual way, and falls back to a mode in which it stops
* reporting template errors, in every file of the program: the check would pass while checking
* nothing.
*/
function unexportedDeclarations(ts, file) {
return file.statements.flatMap((statement) => {
if (!ts.isClassDeclaration(statement) || !statement.name) return [];
const exported = (ts.getModifiers(statement) ?? []).some(
(modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword,
);
if (exported) return [];
const decorator = (ts.getDecorators(statement) ?? [])
.map(({ expression }) =>
ts.isCallExpression(expression) ? expression.expression : expression,
)
.find((callee) => ts.isIdentifier(callee) && ANGULAR_DECLARATIONS.has(callee.text));
if (!decorator) return [];
const kind = decorator.text.toLowerCase();
return [
{
category: ts.DiagnosticCategory.Error,
code: 0,
file,
start: statement.name.getStart(file),
length: statement.name.getWidth(file),
messageText:
`The ${kind} ${statement.name.text} isn't exported. ${UNEXPORTED} a ${kind} ` +
`isn't exported; export it.`,
},
];
});
}
/**
* Run a compiler in a child process. Its output goes to files beside `cwd`, so the child never
* waits for this process to read it while this process compiles another tree.
*/
function runTool(entry, args, cwd) {
const outputs = { stdout: `${cwd}.stdout`, stderr: `${cwd}.stderr` };
const stdout = fs.openSync(outputs.stdout, 'w');
const stderr = fs.openSync(outputs.stderr, 'w');
return new Promise((resolve) => {
let finished = false;
const finish = (status, error) => {
if (finished) return;
finished = true;
fs.closeSync(stdout);
fs.closeSync(stderr);
resolve({
status,
error,
stdout: fs.readFileSync(outputs.stdout, 'utf8'),
stderr: fs.readFileSync(outputs.stderr, 'utf8'),
});
};
const child = spawn(process.execPath, [entry, ...args], {
cwd,
stdio: ['ignore', stdout, stderr],
});
child.on('error', (error) => finish(null, error));
child.on('close', (status) => finish(status));
});
}
/**
* The frameworks whose compiler runs in a child process (`vue-tsc`, `svelte-check`). `tsc` and
* `ngc` compile in this process, so only one of those runs at a time.
*/
export const CHILD_PROCESS_FRAMEWORKS = new Set(['vue', 'svelte']);
/** The first line of a tool's output that says something, for a reason it failed. */
const firstLine = (run) =>
`${run.error?.message ?? ''}\n${run.stderr ?? ''}\n${run.stdout ?? ''}`
.split('\n')
.map((line) => line.trim())
.find(Boolean) ?? `exit ${run.status}`;
/** Compile a Vue tree with `vue-tsc`, in a child process. */
async function compileWithVueTsc(root) {
const tool = findTool('vue-tsc', 'bin/vue-tsc.js');
if (!tool) return { tool: null, reason: "vue-tsc isn't installed in website/" };
const run = await runTool(
tool.entry,
['--noEmit', '--pretty', 'false', '-p', 'tsconfig.json'],
root,
);
// `file(line,column): error TS1234: message`, a message's later lines indented under it.
const diagnostics = [];
for (const line of `${run.stdout}${run.stderr}`.split('\n')) {
const match = line.match(/^(.+?)\((\d+),(\d+)\): error TS\d+: (.*)$/);
if (match) {
diagnostics.push({
file: path.resolve(root, match[1]),
line: Number(match[2]),
column: Number(match[3]),
message: match[4],
});
} else if (/^\s/.test(line) && diagnostics.length) {
diagnostics.at(-1).message += ` ${line.trim()}`;
}
}
if (run.status !== 0 && diagnostics.length === 0) {
return { tool: null, reason: `vue-tsc failed: ${firstLine(run)}` };
}
return { tool: `vue-tsc ${tool.version}`, diagnostics };
}
/** Compile a Svelte tree with `svelte-check`, in a child process. */
async function compileWithSvelteCheck(root) {
const tool = findTool('svelte-check', 'bin/svelte-check');
if (!tool) return { tool: null, reason: "svelte-check isn't installed in website/" };
const run = await runTool(
tool.entry,
[
'--workspace',
root,
'--tsconfig',
'./tsconfig.json',
'--output',
'machine-verbose',
'--threshold',
'error',
],
root,
);
// `