Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
spring-raining committed Nov 25, 2024
1 parent 0d0b0b4 commit 50ffa2f
Show file tree
Hide file tree
Showing 18 changed files with 1,029 additions and 254 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,15 @@
"prettier": "^3.3.3",
"resolve-pkg": "^2.0.0",
"serve-handler": "^6.1.3",
"sirv": "^3.0.0",
"terminal-link": "^2.1.1",
"tinyglobby": "^0.2.10",
"tmp": "^0.2.1",
"upath": "^2.0.1",
"uuid": "^8.3.2",
"valibot": "^0.42.1",
"vfile": "^4.2.1",
"vite": "^5.4.11",
"w3c-xmlserializer": "^4.0.0",
"whatwg-mimetype": "^3.0.0"
},
Expand All @@ -71,6 +73,7 @@
"@types/archiver": "^5.3.2",
"@types/babel__code-frame": "^7.0.6",
"@types/command-exists": "1.2.0",
"@types/connect": "^3.4.38",
"@types/debug": "^4.1.7",
"@types/dompurify": "^3.0.5",
"@types/fs-extra": "^11.0.1",
Expand All @@ -80,6 +83,7 @@
"@types/node": "^22.5.4",
"@types/npm-package-arg": "^6.1.1",
"@types/npmcli__arborist": "^5.6.0",
"@types/picomatch": "^3.0.1",
"@types/serve-handler": "^6.1.1",
"@types/tmp": "^0.2.1",
"@types/uuid": "^8.3.1",
Expand Down
8 changes: 4 additions & 4 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ export async function getFullConfig(
cliFlags: BuildCliFlags,
): Promise<MergedConfig[]> {
const loadedConf = await collectVivliostyleConfig(cliFlags);
const { vivliostyleConfig, vivliostyleConfigPath } = loadedConf;
const { config: jsConfig } = loadedConf;
const loadedCliFlags = loadedConf.cliFlags;

const context = vivliostyleConfig
? upath.dirname(vivliostyleConfigPath)
const context = loadedCliFlags.configPath
? upath.dirname(loadedCliFlags.configPath)
: cwd;

const configEntries: MergedConfig[] = [];
for (const entry of vivliostyleConfig ?? [vivliostyleConfig]) {
for (const entry of jsConfig ?? [jsConfig]) {
const config = await mergeConfig(loadedCliFlags, entry, context);
checkUnsupportedOutputs(config);

Expand Down
155 changes: 66 additions & 89 deletions src/input/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ export type MergedConfig = {
source: string;
target: string;
}[];
cliFlags: CliFlags;
tmpPrefix: string;
size: PageSize | undefined;
cropMarks: boolean;
bleed: string | undefined;
Expand Down Expand Up @@ -421,99 +423,76 @@ function parseFileMetadata({
return { title, themes };
}

export async function collectVivliostyleConfig<T extends CliFlags>(
cliFlags: T,
): Promise<
{
cliFlags: T;
} & (
| {
vivliostyleConfig: VivliostyleConfigEntry[];
vivliostyleConfigPath: string;
}
| {
vivliostyleConfig?: undefined;
vivliostyleConfigPath?: undefined;
}
)
> {
const load = async (configPath: string) => {
let config: unknown;
let jsonRaw: string | undefined;
try {
if (upath.extname(configPath) === '.json') {
jsonRaw = fs.readFileSync(configPath, 'utf8');
config = parseJsonc(jsonRaw);
} else {
// Clear require cache to reload CJS config files
delete require.cache[require.resolve(configPath)];
const url = pathToFileURL(configPath);
// Invalidate cache for ESM config files
// https://github.com/nodejs/node/issues/49442
url.search = `version=${Date.now()}`;
config = (await import(url.href)).default;
jsonRaw = JSON.stringify(config, null, 2);
}
} catch (error) {
const thrownError = error as Error;
throw new DetailError(
`An error occurred on loading a config file: ${configPath}`,
thrownError.stack ?? thrownError.message,
);
}

const result = v.safeParse(VivliostyleConfigSchema, config);
if (result.success) {
return result.output;
export async function loadVivliostyleConfig(configPath: string) {
let config: unknown;
let jsonRaw: string | undefined;
try {
if (upath.extname(configPath) === '.json') {
jsonRaw = fs.readFileSync(configPath, 'utf8');
config = parseJsonc(jsonRaw);
} else {
const errorString = prettifySchemaError(jsonRaw, result.issues);
throw new DetailError(
`Validation of vivliostyle config failed. Please check the schema: ${configPath}`,
errorString,
);
// Clear require cache to reload CJS config files
delete require.cache[require.resolve(configPath)];
const url = pathToFileURL(configPath);
// Invalidate cache for ESM config files
// https://github.com/nodejs/node/issues/49442
url.search = `version=${Date.now()}`;
config = (await import(url.href)).default;
jsonRaw = JSON.stringify(config, null, 2);
}
};
} catch (error) {
const thrownError = error as Error;
throw new DetailError(
`An error occurred on loading a config file: ${configPath}`,
thrownError.stack ?? thrownError.message,
);
}

let configEntry:
| {
vivliostyleConfig: VivliostyleConfigEntry[];
vivliostyleConfigPath: string;
}
| {
vivliostyleConfig?: undefined;
vivliostyleConfigPath?: undefined;
} = {};
let vivliostyleConfigPath: string | undefined;
const result = v.safeParse(VivliostyleConfigSchema, config);
if (result.success) {
return result.output;
} else {
const errorString = prettifySchemaError(jsonRaw, result.issues);
throw new DetailError(
`Validation of vivliostyle config failed. Please check the schema: ${configPath}`,
errorString,
);
}
}

export async function collectVivliostyleConfig<T extends CliFlags>(
_cliFlags: T,
): Promise<{
cliFlags: T;
config?: VivliostyleConfigEntry[];
}> {
const cliFlags = { ..._cliFlags };
let config: VivliostyleConfigEntry[] | undefined;
let configPath: string | undefined;
if (cliFlags.configPath) {
vivliostyleConfigPath = upath.resolve(cwd, cliFlags.configPath);
configPath = upath.resolve(cwd, cliFlags.configPath);
} else {
vivliostyleConfigPath = ['.js', '.mjs', '.cjs']
configPath = ['.js', '.mjs', '.cjs']
.map((ext) => upath.join(cwd, `vivliostyle.config${ext}`))
.find((p) => fs.existsSync(p));
}
// let vivliostyleConfig: VivliostyleConfigSchema | undefined;
if (vivliostyleConfigPath) {
configEntry = {
vivliostyleConfigPath,
vivliostyleConfig: [await load(vivliostyleConfigPath)].flat(),
};
if (configPath) {
config = [await loadVivliostyleConfig(configPath)].flat();
cliFlags.configPath = configPath;
} else if (
cliFlags.input &&
upath.basename(cliFlags.input).startsWith('vivliostyle.config')
) {
// Load an input argument as a Vivliostyle config
try {
const inputPath = upath.resolve(cwd, cliFlags.input);
const inputConfig = await load(inputPath);
cliFlags = {
...cliFlags,
input: undefined,
};
configEntry = {
vivliostyleConfigPath: inputPath,
vivliostyleConfig: [inputConfig].flat(),
};
} catch (_err) {}
const inputConfig = await loadVivliostyleConfig(inputPath);
cliFlags.configPath = inputPath;
cliFlags.input = undefined;
config = [inputConfig].flat();
} catch (_err) {
// Ignore here because input may be a normal manuscript file
}
}

if (cliFlags.executableChromium) {
Expand Down Expand Up @@ -541,7 +520,7 @@ export async function collectVivliostyleConfig<T extends CliFlags>(
);
}

const configEntries = (configEntry.vivliostyleConfig ?? []).flat();
const configEntries = (config ?? []).flat();
if (configEntries.some((config) => config.includeAssets)) {
logWarn(
chalk.yellowBright(
Expand All @@ -558,10 +537,7 @@ export async function collectVivliostyleConfig<T extends CliFlags>(
);
}

return {
cliFlags,
...configEntry,
};
return { cliFlags, config };
}

export async function mergeConfig<T extends CliFlags>(
Expand Down Expand Up @@ -614,6 +590,7 @@ export async function mergeConfig<T extends CliFlags>(
const renderMode = cliFlags.renderMode ?? 'local';
const preflight = cliFlags.preflight ?? (pressReady ? 'press-ready' : null);
const preflightOption = cliFlags.preflightOption ?? [];
const tmpPrefix = prevConfig?.tmpPrefix || `.vs-${Date.now()}.`;

const documentProcessorFactory = config?.documentProcessor ?? VFM;

Expand Down Expand Up @@ -817,6 +794,8 @@ export async function mergeConfig<T extends CliFlags>(
outputs,
themeIndexes,
rootThemes,
cliFlags,
tmpPrefix,
size,
cropMarks,
bleed,
Expand Down Expand Up @@ -889,7 +868,6 @@ async function composeSingleInputConfig<T extends CliFlags>(
const workspaceDir = otherConfig.workspaceDir;
const entries: ParsedEntry[] = [];
const exportAliases: { source: string; target: string }[] = [];
const tmpPrefix = `.vs-${Date.now()}.`;

if (cliFlags.input && isUrlString(cliFlags.input)) {
sourcePath = cliFlags.input;
Expand Down Expand Up @@ -922,7 +900,7 @@ async function composeSingleInputConfig<T extends CliFlags>(
.resolve(
workspaceDir,
relDir,
`${tmpPrefix}${upath.basename(sourcePath)}`,
`${otherConfig.tmpPrefix}${upath.basename(sourcePath)}`,
)
.replace(/\.md$/, '.html');
await touchTmpFile(target);
Expand Down Expand Up @@ -951,7 +929,7 @@ async function composeSingleInputConfig<T extends CliFlags>(
// create temporary manifest file
const manifestPath = upath.resolve(
workspaceDir,
`${tmpPrefix}${MANIFEST_FILENAME}`,
`${otherConfig.tmpPrefix}${MANIFEST_FILENAME}`,
);
await touchTmpFile(manifestPath);
exportAliases.push({
Expand Down Expand Up @@ -1027,7 +1005,6 @@ async function composeProjectConfig<T extends CliFlags>(
debug('located package.json path', pkgJsonPath);
}
const exportAliases: { source: string; target: string }[] = [];
const tmpPrefix = `.vs-${Date.now()}.`;

const tocConfig = (() => {
const c =
Expand Down Expand Up @@ -1131,7 +1108,7 @@ async function composeProjectConfig<T extends CliFlags>(
if (inputInfo?.source && pathEquals(inputInfo.source, target)) {
const tmpPath = upath.resolve(
upath.dirname(target),
`${tmpPrefix}${upath.basename(target)}`,
`${otherConfig.tmpPrefix}${upath.basename(target)}`,
);
exportAliases.push({ source: tmpPath, target });
await touchTmpFile(tmpPath);
Expand Down Expand Up @@ -1181,7 +1158,7 @@ async function composeProjectConfig<T extends CliFlags>(
if (inputInfo?.source && pathEquals(inputInfo.source, target)) {
const tmpPath = upath.resolve(
upath.dirname(target),
`${tmpPrefix}${upath.basename(target)}`,
`${otherConfig.tmpPrefix}${upath.basename(target)}`,
);
exportAliases.push({ source: tmpPath, target });
await touchTmpFile(tmpPath);
Expand Down
1 change: 1 addition & 0 deletions src/output/webbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export function writePublicationManifest(
: (thrownError.stack ?? thrownError.message),
);
}
fs.mkdirSync(upath.dirname(output), { recursive: true });
fs.writeFileSync(output, JSON.stringify(encodedManifest, null, 2));
return publication;
}
Expand Down
Loading

0 comments on commit 50ffa2f

Please sign in to comment.