ShtukbaseStandard
package file→ .shtukbase/packages/ontology/actions/lib/lenscommon.ts

actions/lib/lenscommon.ts

104 lines, 4.0 KB.

  1. // Shared helpers of the two generators: reading pages, templates, writing the lens, small Python-like helpers.
  2. // Bun only, no dependencies; YAML is read with Bun.YAML.
  3. import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
  4. import { dirname, join } from 'node:path';
  5. import * as lenshead from './lenshead.ts';
  6. export const HERE = import.meta.dir;
  7. // ---------------------------------------------------------------- small helpers
  8. /** Order by code point (as Python sorts strings): the same as the order of the UTF-8 bytes. */
  9. export const cmp = (a: string, b: string): number => Buffer.compare(Buffer.from(a), Buffer.from(b));
  10. /** Python truthiness: null, false, 0, '' and empty lists and maps are false. */
  11. export function truthy(v: unknown): boolean {
  12. if (v === null || v === undefined || v === false || v === 0 || v === '') return false;
  13. if (Array.isArray(v)) return v.length > 0;
  14. if (typeof v === 'object') return Object.keys(v as object).length > 0;
  15. return true;
  16. }
  17. /** `a or b or c` of Python: the first true value, else the last. */
  18. export function or(...vals: unknown[]): any {
  19. return vals.find(truthy) ?? vals[vals.length - 1];
  20. }
  21. /** `str(v)` of Python for the values a YAML header holds. */
  22. export function str(v: unknown): string {
  23. if (v === null || v === undefined) return 'None';
  24. if (v === true) return 'True';
  25. if (v === false) return 'False';
  26. return String(v);
  27. }
  28. /** html.escape(t, quote=True) */
  29. export function e(t: unknown): string {
  30. return str(t).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
  31. .replaceAll('"', '&quot;').replaceAll("'", '&#x27;');
  32. }
  33. export const isObject = (v: unknown): v is Record<string, any> => typeof v === 'object' && v !== null && !Array.isArray(v);
  34. // ---------------------------------------------------------------- reading
  35. /** A text file; line breaks are read as `\n`, as Python reads text. */
  36. export function read(path: string): string {
  37. return readFileSync(path, 'utf8').replace(/\r\n?/g, '\n');
  38. }
  39. /** (front matter text or null, body) of a markdown page. */
  40. export function splitPage(text: string): [string | null, string] {
  41. if (!text.startsWith('---\n')) return [null, text];
  42. const end = text.indexOf('\n---\n', 3);
  43. if (end !== -1) return [text.slice(4, end), text.slice(end + 5)];
  44. if (text.endsWith('\n---')) return [text.slice(4, -4), ''];
  45. return [null, text];
  46. }
  47. /** (front matter map, body) of a page; `problem` is told when the front matter does not parse (the map is then empty). */
  48. export function page(path: string, problem?: (err: string) => void): [Record<string, any>, string] {
  49. const [head, body] = splitPage(read(path));
  50. let meta: unknown = {};
  51. if (head) {
  52. try {
  53. meta = Bun.YAML.parse(head) ?? {};
  54. } catch (err) {
  55. meta = {};
  56. problem?.((err as Error).message);
  57. }
  58. }
  59. return [isObject(meta) ? meta : {}, body];
  60. }
  61. export function template(name: string): string {
  62. return read(join(HERE, 'templates', `${name}.html`));
  63. }
  64. // ---------------------------------------------------------------- writing
  65. export function write(path: string, text: string): void {
  66. mkdirSync(dirname(path), { recursive: true });
  67. writeFileSync(path, text);
  68. }
  69. /** Write the lens file: the header (with sourcesHash and outputHash) and the body. */
  70. export function build(root: string, out: string, meta: Record<string, unknown>, sources: string[], body: string): void {
  71. write(out, lenshead.make({
  72. ...meta, sources,
  73. sourcesHash: lenshead.sourcesHash(root, sources),
  74. outputHash: lenshead.outputHash(body),
  75. }, body));
  76. }
  77. /** The only option of the actions: `--out <file>` (or `--out=<file>`). Anything else is refused. */
  78. export function outOption(args: string[]): string | undefined {
  79. let out: string | undefined;
  80. for (let i = 0; i < args.length; i++) {
  81. const a = args[i];
  82. if (a === '--out' && i + 1 < args.length) out = args[++i];
  83. else if (a.startsWith('--out=')) out = a.slice(6);
  84. else throw new Error(`unknown argument ${a}; the only option is --out <file>`);
  85. }
  86. return out;
  87. }