ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/ontology/actions/lib/lenshead.ts

actions/lib/lenshead.ts

91 líneas, 4.3 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // The header of a lens and its two hashes: what the generators of this package need, nothing more.
  2. //
  3. // A lens is an HTML file of the base. Its header is YAML in the first HTML comment of the file:
  4. //
  5. // <!--
  6. // ---
  7. // type: Lens
  8. // title: ...
  9. // sources: [base/ontology.md, "*/ontology.md"]
  10. // sourcesHash: "...64 hex..."
  11. // outputHash: "...64 hex..."
  12. // ---
  13. // -->
  14. // <!doctype html> ... <- the body: everything after `-->` and one line break
  15. //
  16. // sourcesHash is sha256 over the files the `sources` masks find: for every path (NFC, sorted) the line
  17. // `<path>\n<sha256 of the content>\n`. outputHash is sha256 of the body in UTF-8.
  18. import { createHash } from 'node:crypto';
  19. import { existsSync, readFileSync, statSync } from 'node:fs';
  20. import { join, relative } from 'node:path';
  21. import { Glob } from 'bun';
  22. import { cmp } from './lenscommon.ts';
  23. /** The header fields in the order they are written. */
  24. const FIELDS = ['type', 'title', 'icon', 'description', 'lensType', 'render',
  25. 'sources', 'generator', 'template', 'sourcesHash', 'outputHash'];
  26. const sha256 = (data: string | Uint8Array) => createHash('sha256').update(data).digest('hex');
  27. /** One value of the header: a bare word where that reads back as the same string, else JSON. */
  28. function dump(v: unknown): string {
  29. if (v === null || v === undefined) return 'null';
  30. if (typeof v === 'boolean' || typeof v === 'number') return String(v);
  31. if (Array.isArray(v)) return `[${v.map(dump).join(', ')}]`;
  32. const s = String(v);
  33. const bare = /^[A-Za-z_./][A-Za-z0-9_./*+-]*$/.test(s) && !/^[0-9a-f]{16,}$/.test(s)
  34. && !/^(true|True|TRUE|false|False|FALSE|null|Null|NULL)$/.test(s);
  35. return bare ? s : JSON.stringify(s);
  36. }
  37. /** The whole lens file: header (fields in the order above, then the others), a line break, the body. */
  38. export function make(fields: Record<string, unknown>, body: string): string {
  39. const keys = [...FIELDS.filter((k) => k in fields), ...Object.keys(fields).filter((k) => !FIELDS.includes(k))];
  40. const yaml = keys.filter((k) => fields[k] !== null && fields[k] !== undefined).map((k) => `${k}: ${dump(fields[k])}`).join('\n');
  41. return `<!--\n---\n${yaml}\n---\n-->\n${body}`;
  42. }
  43. // ---------------------------------------------------------------- sources
  44. /** Folders of the lens kit (`lib/` in the base root, the old `_lenses/`) are not sources: a mask like `**\/*.html`
  45. * would catch them and the lens would be stale for ever. A mask that names such a folder gets its files. */
  46. const SERVICE_DIRS = ['lib', '_lenses'];
  47. function dropService(rels: string[], mask: string): string[] {
  48. if (SERVICE_DIRS.some((d) => mask.split('/').includes(d))) return rels;
  49. return rels.filter((r) => !r.split('/').slice(0, -1).some((d) => SERVICE_DIRS.includes(d)));
  50. }
  51. const isFile = (p: string) => existsSync(p) && statSync(p).isFile();
  52. const isDir = (p: string) => existsSync(p) && statSync(p).isDirectory();
  53. /** Files one mask finds: a glob from the base root, `**` recursive, a leading `/` allowed; a path to a folder
  54. * means `folder/**\/*.md`. Hidden files and folders are never found by a wildcard. */
  55. function match(root: string, mask: string): string[] {
  56. mask = mask.trim().replace(/^\/+/, '');
  57. if (!mask) return [];
  58. const magic = /[*?[]/.test(mask);
  59. const full = join(root, mask);
  60. let rels: string[];
  61. if (!magic && !isDir(full)) rels = isFile(full) ? [mask] : [];
  62. else {
  63. const pattern = !magic ? `${mask.replace(/\/+$/, '')}/**/*.md` : mask;
  64. rels = [...new Glob(pattern).scanSync({ cwd: root, onlyFiles: true, followSymlinks: true })]
  65. .map((p) => relative(root, join(root, p)).split('\\').join('/'));
  66. }
  67. return dropService(rels, mask);
  68. }
  69. /** Paths of the sources, sorted, no repeats. */
  70. export function expand(root: string, sources: string[]): string[] {
  71. return [...new Set(sources.flatMap((m) => match(root, m)))].sort(cmp);
  72. }
  73. /** Git keeps names in NFC and macOS hands them out in NFD: the hash must not depend on where they were read. */
  74. export function sourcesHash(root: string, sources: string[]): string {
  75. const entries = expand(root, sources).map((rel) => [rel.normalize('NFC'), sha256(readFileSync(join(root, rel)))] as const);
  76. entries.sort((a, b) => cmp(a[0], b[0]) || cmp(a[1], b[1]));
  77. return sha256(entries.map(([rel, digest]) => `${rel}\n${digest}\n`).join(''));
  78. }
  79. export const outputHash = (body: string) => sha256(body);