包文件→ .shtukbase/packages/ontology/actions/lib/lenshead.ts
actions/lib/lenshead.ts
91 行, 4.3 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // The header of a lens and its two hashes: what the generators of this package need, nothing more.
- //
- // A lens is an HTML file of the base. Its header is YAML in the first HTML comment of the file:
- //
- // <!--
- // ---
- // type: Lens
- // title: ...
- // sources: [base/ontology.md, "*/ontology.md"]
- // sourcesHash: "...64 hex..."
- // outputHash: "...64 hex..."
- // ---
- // -->
- // <!doctype html> ... <- the body: everything after `-->` and one line break
- //
- // sourcesHash is sha256 over the files the `sources` masks find: for every path (NFC, sorted) the line
- // `<path>\n<sha256 of the content>\n`. outputHash is sha256 of the body in UTF-8.
- import { createHash } from 'node:crypto';
- import { existsSync, readFileSync, statSync } from 'node:fs';
- import { join, relative } from 'node:path';
- import { Glob } from 'bun';
- import { cmp } from './lenscommon.ts';
- /** The header fields in the order they are written. */
- const FIELDS = ['type', 'title', 'icon', 'description', 'lensType', 'render',
- 'sources', 'generator', 'template', 'sourcesHash', 'outputHash'];
- const sha256 = (data: string | Uint8Array) => createHash('sha256').update(data).digest('hex');
- /** One value of the header: a bare word where that reads back as the same string, else JSON. */
- function dump(v: unknown): string {
- if (v === null || v === undefined) return 'null';
- if (typeof v === 'boolean' || typeof v === 'number') return String(v);
- if (Array.isArray(v)) return `[${v.map(dump).join(', ')}]`;
- const s = String(v);
- const bare = /^[A-Za-z_./][A-Za-z0-9_./*+-]*$/.test(s) && !/^[0-9a-f]{16,}$/.test(s)
- && !/^(true|True|TRUE|false|False|FALSE|null|Null|NULL)$/.test(s);
- return bare ? s : JSON.stringify(s);
- }
- /** The whole lens file: header (fields in the order above, then the others), a line break, the body. */
- export function make(fields: Record<string, unknown>, body: string): string {
- const keys = [...FIELDS.filter((k) => k in fields), ...Object.keys(fields).filter((k) => !FIELDS.includes(k))];
- const yaml = keys.filter((k) => fields[k] !== null && fields[k] !== undefined).map((k) => `${k}: ${dump(fields[k])}`).join('\n');
- return `<!--\n---\n${yaml}\n---\n-->\n${body}`;
- }
- // ---------------------------------------------------------------- sources
- /** Folders of the lens kit (`lib/` in the base root, the old `_lenses/`) are not sources: a mask like `**\/*.html`
- * would catch them and the lens would be stale for ever. A mask that names such a folder gets its files. */
- const SERVICE_DIRS = ['lib', '_lenses'];
- function dropService(rels: string[], mask: string): string[] {
- if (SERVICE_DIRS.some((d) => mask.split('/').includes(d))) return rels;
- return rels.filter((r) => !r.split('/').slice(0, -1).some((d) => SERVICE_DIRS.includes(d)));
- }
- const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
- const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
- /** Files one mask finds: a glob from the base root, `**` recursive, a leading `/` allowed; a path to a folder
- * means `folder/**\/*.md`. Hidden files and folders are never found by a wildcard. */
- function match(root: string, mask: string): string[] {
- mask = mask.trim().replace(/^\/+/, '');
- if (!mask) return [];
- const magic = /[*?[]/.test(mask);
- const full = join(root, mask);
- let rels: string[];
- if (!magic && !isDir(full)) rels = isFile(full) ? [mask] : [];
- else {
- const pattern = !magic ? `${mask.replace(/\/+$/, '')}/**/*.md` : mask;
- rels = [...new Glob(pattern).scanSync({ cwd: root, onlyFiles: true, followSymlinks: true })]
- .map((p) => relative(root, join(root, p)).split('\\').join('/'));
- }
- return dropService(rels, mask);
- }
- /** Paths of the sources, sorted, no repeats. */
- export function expand(root: string, sources: string[]): string[] {
- return [...new Set(sources.flatMap((m) => match(root, m)))].sort(cmp);
- }
- /** Git keeps names in NFC and macOS hands them out in NFD: the hash must not depend on where they were read. */
- export function sourcesHash(root: string, sources: string[]): string {
- const entries = expand(root, sources).map((rel) => [rel.normalize('NFC'), sha256(readFileSync(join(root, rel)))] as const);
- entries.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
- return sha256(entries.map(([rel, digest]) => `${rel}\n${digest}\n`).join(''));
- }
- export const outputHash = (body: string) => sha256(body);