statum-mkpstm.vala 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. using Xml;
  2. using Html;
  3. using Astralis;
  4. using Invercargill;
  5. using Invercargill.DataStructures;
  6. namespace Statum.Tools {
  7. /**
  8. * `statum-mkpstm` — the build-time Statum pre-rendering pipeline.
  9. *
  10. * Turns an app HTML page (plus its templates/fragments) into a Vala
  11. * {@link Statum.StatumPage} subclass: a static, precompressed document whose
  12. * route comes from its `<pstm-uri>`. Composition (templates, fragments,
  13. * `pstm-res` rewriting) is applied, then the result is precompressed with
  14. * identity/gzip/zstd/br.
  15. */
  16. public class Mkpstm : Object {
  17. private static string? output_file = null;
  18. private static string? namespace_name = null;
  19. private static string? class_name_override = null;
  20. private static string? route_override = null;
  21. private static List<string> template_dirs = new List<string>();
  22. private Dictionary<string, Xml.Doc*> templates_by_name = new Dictionary<string, Xml.Doc*>();
  23. private Dictionary<string, Xml.Doc*> fragments_by_name = new Dictionary<string, Xml.Doc*>();
  24. /**
  25. * The Statum client ships as four modules with a strict load order
  26. * (core first: every later module registers into the seams core
  27. * installs). A legacy single-file `pstm-res-src="statum.js"` reference
  28. * expands at build time into exactly these four tags.
  29. */
  30. private const string[] CLIENT_MODULE_ORDER = {
  31. "statum-core.js", "statum-document.js", "statum-markdown.js", "statum-forms.js"
  32. };
  33. private const OptionEntry[] options = {
  34. { "output", 'o', 0, OptionArg.FILENAME, ref output_file, "Output Vala file name", "FILE" },
  35. { "ns", '\0', 0, OptionArg.STRING, ref namespace_name, "Namespace for the generated class", "NAMESPACE" },
  36. { "name", 'n', 0, OptionArg.STRING, ref class_name_override, "Generated class name (default: <InputName>Page)", "NAME" },
  37. { "route", 'r', 0, OptionArg.STRING, ref route_override, "Page route (default: from <pstm-uri>)", "ROUTE" },
  38. { "template-dir", 't', 0, OptionArg.FILENAME_ARRAY, ref template_dirs, "Directory to search for templates/fragments (repeatable)", "DIR" },
  39. { null }
  40. };
  41. public static int main(string[] args) {
  42. try {
  43. var opt = new OptionContext("PAGE_FILE - Generate a Statum StatumPage");
  44. opt.add_main_entries(options, null);
  45. opt.parse(ref args);
  46. } catch (OptionError e) {
  47. stderr.printf("Error: %s\n", e.message);
  48. return 1;
  49. }
  50. string? page_file = null;
  51. if (args.length > 1) {
  52. page_file = args[1];
  53. }
  54. if (page_file == null) {
  55. stderr.printf("Error: No page file specified.\n");
  56. return 1;
  57. }
  58. try {
  59. var tool = new Mkpstm();
  60. var generated = tool.run((!)page_file);
  61. var out_path = tool.output_file ?? (make_pascal_case((!)page_file) + "Page.vala");
  62. write_file(out_path, generated);
  63. stdout.printf("Generated: %s\n", out_path);
  64. return 0;
  65. } catch (GLib.Error e) {
  66. stderr.printf("Error: %s\n", e.message);
  67. return 1;
  68. }
  69. }
  70. public string run(string page_file) throws GLib.Error {
  71. if (template_dirs.length() == 0) {
  72. var parent = File.new_for_path(page_file).get_parent();
  73. template_dirs.append(parent != null ? ((!)parent).get_path() : ".");
  74. }
  75. load_templates_and_fragments(page_file);
  76. var doc = parse_html_file(page_file);
  77. validate_document(doc, page_file);
  78. validate_head_directives(doc, page_file);
  79. // Capture the page's routes before composition (the <pstm-uri>
  80. // directive is dropped while merging templates).
  81. var routes = read_routes(doc);
  82. doc = compose_templates(doc);
  83. inline_fragments(doc);
  84. expand_legacy_client(doc, page_file);
  85. rewrite_resources(doc);
  86. var variant = build_variant(doc);
  87. var class_name = class_name_override ?? (make_pascal_case(page_file) + "Page");
  88. var route = route_override ?? (routes.length > 0 ? routes[0] : "");
  89. return emit(class_name, route, variant);
  90. }
  91. // ------------------------------------------------------------------
  92. // Template/fragment loading
  93. // ------------------------------------------------------------------
  94. private void load_templates_and_fragments(string page_file) throws GLib.Error {
  95. foreach (var dir in template_dirs) {
  96. var dir_file = File.new_for_path(dir);
  97. if (!dir_file.query_exists()) {
  98. continue;
  99. }
  100. var enumerator = dir_file.enumerate_children("standard::name", 0);
  101. FileInfo info;
  102. while ((info = enumerator.next_file()) != null) {
  103. var name = info.get_name();
  104. if (!name.has_suffix(".html") || name.has_prefix(".")) {
  105. continue;
  106. }
  107. var path = Path.build_filename(dir, name);
  108. if (path == page_file) {
  109. continue;
  110. }
  111. var tdoc = parse_html_file(path);
  112. var source = Path.build_filename(dir, name);
  113. validate_document(tdoc, source);
  114. validate_head_directives(tdoc, source);
  115. var tname = read_pstm_name(tdoc);
  116. if (tname == null) {
  117. continue;
  118. }
  119. if (find_first_element(tdoc->get_root_element(), "pstm-content") != null) {
  120. templates_by_name.set((!)tname, tdoc);
  121. } else {
  122. fragments_by_name.set((!)tname, tdoc);
  123. }
  124. }
  125. }
  126. }
  127. // ------------------------------------------------------------------
  128. // Composition
  129. // ------------------------------------------------------------------
  130. private Xml.Doc* compose_templates(Xml.Doc* doc) throws GLib.Error {
  131. Xml.Doc* current_doc = doc;
  132. string merged_title = read_directive_in_doc(current_doc, "pstm-title") ?? "";
  133. // Guard against cyclic template chains (A templates B templates A).
  134. var visited = new HashSet<string>();
  135. while (true) {
  136. var parent_name = read_directive_in_doc(current_doc, "pstm-template");
  137. if (parent_name == null || parent_name.length == 0) {
  138. break;
  139. }
  140. if (visited.contains((!)parent_name)) {
  141. break;
  142. }
  143. visited.add((!)parent_name);
  144. Xml.Doc* parent_doc;
  145. if (!templates_by_name.try_get((!)parent_name, out parent_doc)) {
  146. throw new IOError.FAILED(@"Unknown template \"$((!)parent_name)\"");
  147. }
  148. // Merge this document's <head> into the parent's <head> (so
  149. // pages, templates and nested components can all declare head
  150. // tags), then splice its <body> into the parent's content outlet.
  151. merge_head(current_doc, parent_doc);
  152. splice_body(current_doc, parent_doc);
  153. var parent_title = read_directive_in_doc(parent_doc, "pstm-title");
  154. if (parent_title != null && parent_title.length > 0) {
  155. merged_title = merged_title + (!)parent_title;
  156. }
  157. current_doc = parent_doc;
  158. }
  159. apply_title(current_doc, merged_title);
  160. return current_doc;
  161. }
  162. /**
  163. * Copies the children of `child_doc`'s <head> into `parent_doc`'s <head>,
  164. * skipping the consumed structural directives (pstm-template/name/title/
  165. * uri) which are page-level metadata and must not be carried up.
  166. */
  167. private void merge_head(Xml.Doc* child_doc, Xml.Doc* parent_doc) {
  168. var child_head = find_head(child_doc);
  169. var parent_head = find_head(parent_doc);
  170. if (child_head == null || parent_head == null) {
  171. return;
  172. }
  173. for (var child = child_head->children; child != null; child = child->next) {
  174. if (!is_element(child)) {
  175. continue;
  176. }
  177. var name = (string) child->name;
  178. if (name == "pstm-template" || name == "pstm-name" || name == "pstm-title" || name == "pstm-uri") {
  179. continue;
  180. }
  181. var copied = child->doc_copy(parent_doc, 1);
  182. if (copied != null) {
  183. parent_head->add_child(copied);
  184. }
  185. }
  186. }
  187. /**
  188. * Splices `child_doc`'s <body> into `parent_doc`'s <pstm-content> outlet
  189. * (or appends to the parent's <body> when there is no outlet). When the
  190. * child <body> carries `pstm-materialise-as`, it is wrapped in an element
  191. * of that tag (carrying the body's non-pstm attributes); otherwise its
  192. * children are spliced directly.
  193. */
  194. private void splice_body(Xml.Doc* child_doc, Xml.Doc* parent_doc) {
  195. var child_body = find_body(child_doc);
  196. var parent_body = find_body(parent_doc);
  197. if (child_body == null || parent_body == null) {
  198. return;
  199. }
  200. var outlet = find_first_element(parent_body, "pstm-content");
  201. var materialise_as = child_body->get_prop("pstm-materialise-as");
  202. if (materialise_as != null) {
  203. var wrapper = parent_body->new_child(null, (!)materialise_as, null);
  204. wrapper->unlink();
  205. copy_non_pstm_attrs(child_body, wrapper);
  206. for (var child = child_body->children; child != null; child = child->next) {
  207. if (is_structural_directive(child)) {
  208. continue;
  209. }
  210. var copied = child->doc_copy(parent_doc, 1);
  211. if (copied != null) {
  212. wrapper->add_child(copied);
  213. }
  214. }
  215. if (outlet != null) {
  216. outlet->add_prev_sibling(wrapper);
  217. } else {
  218. parent_body->add_child(wrapper);
  219. }
  220. } else {
  221. for (var child = child_body->children; child != null; child = child->next) {
  222. if (is_structural_directive(child)) {
  223. continue;
  224. }
  225. var copied = child->doc_copy(parent_doc, 1);
  226. if (copied == null) {
  227. continue;
  228. }
  229. if (outlet != null) {
  230. outlet->add_prev_sibling(copied);
  231. } else {
  232. parent_body->add_child(copied);
  233. }
  234. }
  235. }
  236. if (outlet != null) {
  237. outlet->unlink();
  238. }
  239. }
  240. /** Copies an element's non-`pstm-*` attributes onto another element. */
  241. private static void copy_non_pstm_attrs(Xml.Node* src, Xml.Node* dst) {
  242. for (var attr = src->properties; attr != null; attr = attr->next) {
  243. var attr_name = (string) attr->name;
  244. if (attr_name.has_prefix("pstm-")) {
  245. continue;
  246. }
  247. var value = src->get_prop(attr_name);
  248. if (value != null) {
  249. dst->set_prop(attr_name, (!)value);
  250. }
  251. }
  252. }
  253. private static string? read_directive_in_doc(Xml.Doc* doc, string name) {
  254. var root = doc->get_root_element();
  255. if (root == null) {
  256. return null;
  257. }
  258. return read_directive_text(root, name);
  259. }
  260. private static bool is_structural_directive(Xml.Node* node) {
  261. if (!is_element(node)) {
  262. return false;
  263. }
  264. var name = (string) node->name;
  265. return name == "pstm-template" || name == "pstm-name" || name == "pstm-title" || name == "pstm-uri" || name == "pstm-content";
  266. }
  267. /** Fragment-body metadata elements skipped when inlining (e.g. pstm-input). */
  268. private static bool is_fragment_metadata(Xml.Node* node) {
  269. if (!is_element(node)) {
  270. return false;
  271. }
  272. var name = (string) node->name;
  273. return name == "pstm-input" || name.has_prefix("pstm-");
  274. }
  275. private void inline_fragments(Xml.Doc* doc) {
  276. bool changed = true;
  277. while (changed) {
  278. changed = false;
  279. var includes = find_all_elements(doc, "pstm-fragment");
  280. foreach (var include in includes) {
  281. if (inline_one_fragment(doc, include)) {
  282. changed = true;
  283. }
  284. }
  285. }
  286. }
  287. private bool inline_one_fragment(Xml.Doc* doc, Xml.Node* include) {
  288. var name = include->get_prop("name");
  289. if (name == null) {
  290. return false;
  291. }
  292. Xml.Doc* fragment_doc;
  293. if (!fragments_by_name.try_get((!)name, out fragment_doc)) {
  294. return false;
  295. }
  296. var fragment_body = find_body(fragment_doc);
  297. if (fragment_body == null) {
  298. return false;
  299. }
  300. // Merge the fragment's <head> into the document's <head>.
  301. merge_head(fragment_doc, doc);
  302. var inputs = collect_input_names(fragment_body);
  303. var include_materialise = include->get_prop("pstm-materialise-as");
  304. var fragment_materialise = fragment_body->get_prop("pstm-materialise-as");
  305. var materialise_as = include_materialise ?? fragment_materialise;
  306. bool wrap = (materialise_as != null) || inputs.length > 0;
  307. string tag = materialise_as ?? "div";
  308. if (wrap) {
  309. var parent = include->parent;
  310. if (parent == null) {
  311. return false;
  312. }
  313. var wrapper = parent->new_child(null, tag, null);
  314. wrapper->unlink();
  315. include->add_prev_sibling(wrapper);
  316. // Carry the fragment <body>'s attributes when it supplied the tag.
  317. if (include_materialise == null && fragment_materialise != null) {
  318. copy_non_pstm_attrs(fragment_body, wrapper);
  319. }
  320. for (var child = fragment_body->children; child != null; child = child->next) {
  321. if (is_fragment_metadata(child)) {
  322. continue;
  323. }
  324. var copied = child->doc_copy(doc, 1);
  325. if (copied != null) {
  326. wrapper->add_child(copied);
  327. }
  328. }
  329. foreach (var input_name in inputs) {
  330. var expr = include->get_prop(input_name);
  331. if (expr != null) {
  332. wrapper->set_prop(@"stm-def-$input_name-as", (!)expr);
  333. }
  334. }
  335. } else {
  336. for (var child = fragment_body->children; child != null; child = child->next) {
  337. if (is_fragment_metadata(child)) {
  338. continue;
  339. }
  340. var copied = child->doc_copy(doc, 1);
  341. if (copied != null) {
  342. include->add_prev_sibling(copied);
  343. }
  344. }
  345. }
  346. include->unlink();
  347. return true;
  348. }
  349. private string[] collect_input_names(Xml.Node* fragment_body) {
  350. var names = new string[0];
  351. for (var n = fragment_body->children; n != null; n = n->next) {
  352. if (is_element(n) && (string) n->name == "pstm-input") {
  353. var input_name = n->get_prop("name");
  354. if (input_name != null) {
  355. names += (!)input_name;
  356. }
  357. }
  358. }
  359. return names;
  360. }
  361. private void rewrite_resources(Xml.Doc* doc) {
  362. var root = doc->get_root_element();
  363. if (root != null) {
  364. rewrite_resources_in(root);
  365. }
  366. }
  367. /**
  368. * Expands a legacy single-file client reference into the four ordered
  369. * module tags.
  370. *
  371. * `<script pstm-res-src="statum.js">` (the pre-split client, no longer
  372. * an embedded resource) becomes one `<script src="/_statum/resource/
  373. * statum-<mod>.js">` tag per module, in canonical load order. Later
  374. * duplicate `statum.js` references on the same page are dropped, and
  375. * explicit `pstm-res-src="statum-<mod>.js"` references the expansion
  376. * already covers are removed (subsumed) so every module appears exactly
  377. * once. Pages referencing only module files (or only plain `src="…"`
  378. * scripts, which are already final) are left entirely alone.
  379. *
  380. * Runs on the composed document before {@link rewrite_resources}: the
  381. * inserted tags use plain `src` attributes, so the generic rewrite and
  382. * `strip_pstm` both leave them alone.
  383. */
  384. private void expand_legacy_client(Xml.Doc* doc, string page_file) {
  385. var root = doc->get_root_element();
  386. if (root == null) {
  387. return;
  388. }
  389. Xml.Node* legacy = null;
  390. var refs = new ClientRefs();
  391. collect_client_refs(root, refs);
  392. legacy = refs.legacy;
  393. if (legacy == null) {
  394. return;
  395. }
  396. var parent = legacy->parent;
  397. if (parent == null) {
  398. return;
  399. }
  400. foreach (var module in CLIENT_MODULE_ORDER) {
  401. var tag = ((!)parent)->new_child(null, "script", null);
  402. tag->unlink();
  403. // Script tags carrying pstm-res-src carry no other attributes
  404. // today; copy any extras onto all four for good measure.
  405. copy_non_pstm_attrs(legacy, tag);
  406. tag->set_prop("src", @"/_statum/resource/$module");
  407. legacy->add_prev_sibling(tag);
  408. }
  409. string[] subsumed = new string[0];
  410. foreach (var node in refs.modules) {
  411. var name = node->get_prop("pstm-res-src");
  412. if (name != null) {
  413. subsumed += (!)name;
  414. }
  415. node->unlink();
  416. }
  417. legacy->unlink();
  418. // Exactly one build warning per page, naming the page and the
  419. // expansion.
  420. var page = page_name(page_file);
  421. stderr.printf("warning: %s: expanding legacy pstm-res-src=\"statum.js\" into %s",
  422. page, string.joinv(", ", CLIENT_MODULE_ORDER));
  423. if (subsumed.length > 0) {
  424. stderr.printf("; subsumed explicit module tag(s): %s", string.joinv(", ", subsumed));
  425. }
  426. if (refs.duplicates > 0) {
  427. stderr.printf("; dropped %d duplicate statum.js reference(s)", refs.duplicates);
  428. }
  429. stderr.printf("\n");
  430. }
  431. /**
  432. * Collects the client script references of a composed document: the
  433. * first `<script pstm-res-src="statum.js">` (if any), every explicit
  434. * module `pstm-res-src="statum-<mod>.js"` reference, and the count of
  435. * further `statum.js` duplicates.
  436. */
  437. private void collect_client_refs(Xml.Node* node, ClientRefs refs) {
  438. if (!is_element(node)) {
  439. return;
  440. }
  441. if ((string) node->name == "script") {
  442. var res = node->get_prop("pstm-res-src");
  443. if (res != null) {
  444. if ((!)res == "statum.js") {
  445. if (refs.legacy == null) {
  446. refs.legacy = node;
  447. } else {
  448. refs.duplicates++;
  449. }
  450. } else if (is_client_module((!)res)) {
  451. refs.modules += node;
  452. }
  453. }
  454. }
  455. for (var child = node->children; child != null; child = child->next) {
  456. collect_client_refs(child, refs);
  457. }
  458. }
  459. /** The page's short name, as warnings name it (e.g. `home`). */
  460. private static string page_name(string page_file) {
  461. var page = Path.get_basename(page_file);
  462. var dot = page.last_index_of(".");
  463. if (dot > 0) {
  464. page = page.substring(0, dot);
  465. }
  466. return page;
  467. }
  468. private static bool is_client_module(string name) {
  469. foreach (var module in CLIENT_MODULE_ORDER) {
  470. if (name == module) {
  471. return true;
  472. }
  473. }
  474. return false;
  475. }
  476. private void rewrite_resources_in(Xml.Node* node) {
  477. if (!is_element(node)) {
  478. return;
  479. }
  480. string[] to_add_attr = new string[0];
  481. string[] to_add_val = new string[0];
  482. string[] to_remove = new string[0];
  483. for (var attr = node->properties; attr != null; attr = attr->next) {
  484. var attr_name = (string) attr->name;
  485. if (attr_name.has_prefix("pstm-res-")) {
  486. var target_attr = attr_name.substring("pstm-res-".length);
  487. var value = node->get_prop(attr_name);
  488. if (value != null) {
  489. to_add_attr += target_attr;
  490. to_add_val += @"/_statum/resource/$((!)value)";
  491. }
  492. to_remove += attr_name;
  493. }
  494. }
  495. for (int i = 0; i < to_add_attr.length; i++) {
  496. node->set_prop(to_add_attr[i], to_add_val[i]);
  497. }
  498. foreach (var attr_name in to_remove) {
  499. node->unset_prop(attr_name);
  500. }
  501. for (var child = node->children; child != null; child = child->next) {
  502. rewrite_resources_in(child);
  503. }
  504. }
  505. // ------------------------------------------------------------------
  506. // Variant rendering
  507. // ------------------------------------------------------------------
  508. /**
  509. * Renders the composed document to its single HTML form (stripping every
  510. * `pstm-*` directive) and precompresses it. Pages no longer have
  511. * variants: a page is a static, precompressed document, so there is
  512. * exactly one.
  513. */
  514. private VariantData build_variant(Xml.Doc* doc) throws GLib.Error {
  515. strip_pstm(doc);
  516. var html = serialize(doc);
  517. return compress_variant(html);
  518. }
  519. private VariantData compress_variant(string html) throws GLib.Error {
  520. var data = new VariantData();
  521. data.identity = html.data;
  522. var buffer = new ByteBuffer.from_byte_array(html.data);
  523. var gzip = new GzipCompressor(9).compress_buffer(buffer, null).to_array();
  524. var zstd = new ZstdCompressor(19).compress_buffer(buffer, null).to_array();
  525. var br = new BrotliCompressor(11).compress_buffer(buffer, null).to_array();
  526. data.has_gzip = gzip.length < html.length;
  527. data.has_zstd = zstd.length < html.length;
  528. data.has_br = br.length < html.length;
  529. data.gzip = data.has_gzip ? gzip : null;
  530. data.zstd = data.has_zstd ? zstd : null;
  531. data.br = data.has_br ? br : null;
  532. return data;
  533. }
  534. /** Remove every `pstm-*` attribute and `pstm-*` element from the tree. */
  535. private void strip_pstm(Xml.Doc* doc) {
  536. var root = doc->get_root_element();
  537. if (root != null) {
  538. strip_pstm_from(root);
  539. }
  540. }
  541. private void strip_pstm_from(Xml.Node* node) {
  542. string[] to_remove = new string[0];
  543. for (var attr = node->properties; attr != null; attr = attr->next) {
  544. var attr_name = (string) attr->name;
  545. if (attr_name.has_prefix("pstm-")) {
  546. to_remove += attr_name;
  547. }
  548. }
  549. foreach (var attr_name in to_remove) {
  550. node->unset_prop(attr_name);
  551. }
  552. var child = node->children;
  553. while (child != null) {
  554. var next = child->next;
  555. if (is_element(child) && ((string) child->name).has_prefix("pstm-")) {
  556. child->unlink();
  557. } else if (is_element(child)) {
  558. strip_pstm_from(child);
  559. }
  560. child = next;
  561. }
  562. }
  563. // ------------------------------------------------------------------
  564. // Code generation
  565. // ------------------------------------------------------------------
  566. private string emit(string class_name, string route, VariantData variant) throws GLib.Error {
  567. var page_hash = compute_hash(variant.identity);
  568. var b = new StringBuilder();
  569. string i1 = namespace_name != null ? " " : "";
  570. string i2 = namespace_name != null ? " " : " ";
  571. string i3 = namespace_name != null ? " " : " ";
  572. b.append("using Statum;\n");
  573. b.append("using Invercargill;\n");
  574. b.append("using Invercargill.DataStructures;\n");
  575. b.append("using Astralis;\n\n");
  576. if (namespace_name != null) {
  577. b.append_printf("namespace %s {\n\n", namespace_name);
  578. }
  579. b.append_printf("%s// Generated by statum-mkpstm\n", i1);
  580. b.append_printf("%spublic class %s : StatumPage {\n\n", i1, class_name);
  581. b.append_printf("%spublic override string route { get { return \"%s\"; } }\n", i2, escape(route));
  582. b.append_printf("%spublic override string content_type { get { return \"text/html; charset=utf-8\"; } }\n\n", i2);
  583. // get_best_encoding: smallest available supported encoding.
  584. b.append_printf("%spublic override string get_best_encoding(Set<string> supported) {\n", i2);
  585. if (variant.has_br) {
  586. b.append_printf("%sif (supported.has(\"br\")) return \"br\";\n", i3);
  587. }
  588. if (variant.has_zstd) {
  589. b.append_printf("%sif (supported.has(\"zstd\")) return \"zstd\";\n", i3);
  590. }
  591. if (variant.has_gzip) {
  592. b.append_printf("%sif (supported.has(\"gzip\")) return \"gzip\";\n", i3);
  593. }
  594. b.append_printf("%sreturn \"identity\";\n", i3);
  595. b.append_printf("%s}\n\n", i2);
  596. // get_encoding
  597. b.append_printf("%spublic override unowned uint8[] get_encoding(string encoding) {\n", i2);
  598. b.append_printf("%sswitch (encoding) {\n", i3);
  599. b.append_printf("%scase \"identity\": return IDENTITY;\n", i3);
  600. if (variant.has_gzip && variant.gzip != null) {
  601. b.append_printf("%scase \"gzip\": return GZIP;\n", i3);
  602. }
  603. if (variant.has_zstd && variant.zstd != null) {
  604. b.append_printf("%scase \"zstd\": return ZSTD;\n", i3);
  605. }
  606. if (variant.has_br && variant.br != null) {
  607. b.append_printf("%scase \"br\": return BR;\n", i3);
  608. }
  609. b.append_printf("%sdefault: return IDENTITY;\n", i3);
  610. b.append_printf("%s}\n", i3);
  611. b.append_printf("%s}\n\n", i2);
  612. // get_etag_for (ETag = "<page-hash>-<encoding>")
  613. b.append_printf("%spublic override string get_etag_for(string encoding) {\n", i2);
  614. b.append_printf("%sreturn \"\\\"%s-%%s\\\"\".printf(encoding);\n", i3, page_hash);
  615. b.append_printf("%s}\n\n", i2);
  616. // Byte arrays.
  617. emit_one_array(b, i2, i3, "IDENTITY", variant.identity);
  618. if (variant.has_gzip && variant.gzip != null) {
  619. emit_one_array(b, i2, i3, "GZIP", (!)variant.gzip);
  620. }
  621. if (variant.has_zstd && variant.zstd != null) {
  622. emit_one_array(b, i2, i3, "ZSTD", (!)variant.zstd);
  623. }
  624. if (variant.has_br && variant.br != null) {
  625. emit_one_array(b, i2, i3, "BR", (!)variant.br);
  626. }
  627. b.append_printf("%s}\n", i1);
  628. if (namespace_name != null) {
  629. b.append("}\n");
  630. }
  631. return b.str;
  632. }
  633. private void emit_one_array(StringBuilder b, string i2, string i3, string name, uint8[] data) {
  634. b.append_printf("%sprivate const uint8[] %s = {\n", i2, name);
  635. for (int i = 0; i < data.length; i++) {
  636. if (i == 0) {
  637. b.append(i3);
  638. } else if (i % 16 == 0) {
  639. b.append(",\n").append(i3);
  640. } else {
  641. b.append(", ");
  642. }
  643. b.append_printf("0x%02x", data[i]);
  644. }
  645. b.append_printf("\n%s};\n\n", i2);
  646. }
  647. // ------------------------------------------------------------------
  648. // DOM helpers
  649. // ------------------------------------------------------------------
  650. private Xml.Doc* parse_html_file(string path) throws GLib.Error {
  651. var file = File.new_for_path(path);
  652. if (!file.query_exists()) {
  653. throw new IOError.NOT_FOUND(@"Page file '$path' does not exist");
  654. }
  655. uint8[] contents;
  656. string etag_out;
  657. file.load_contents(null, out contents, out etag_out);
  658. // Parse with libxml2's HTML parser (mirrors Astralis' MarkupDocument)
  659. // so the tree has HTML semantics and serializes as HTML, not XML.
  660. int opts = (int)(Html.ParserOption.RECOVER |
  661. Html.ParserOption.NOERROR |
  662. Html.ParserOption.NOWARNING |
  663. Html.ParserOption.NOBLANKS |
  664. Html.ParserOption.NONET);
  665. char[] buffer = ((string) contents).to_utf8();
  666. var doc = Html.Doc.read_memory(buffer, buffer.length, path, "utf-8", opts);
  667. if (doc == null) {
  668. throw new IOError.FAILED(@"Failed to parse HTML file '$path'");
  669. }
  670. return doc;
  671. }
  672. private static Xml.Node* find_body(Xml.Doc* doc) {
  673. var root = doc->get_root_element();
  674. if (root == null) {
  675. return null;
  676. }
  677. return find_first_element(root, "body");
  678. }
  679. private static Xml.Node* find_head(Xml.Doc* doc) {
  680. var root = doc->get_root_element();
  681. if (root == null) {
  682. return null;
  683. }
  684. return find_first_element(root, "head");
  685. }
  686. /**
  687. * Validates that `doc` has both a <head> and a <body> element, which every
  688. * Statum HTML input (pages, templates and fragments) must declare.
  689. */
  690. private void validate_document(Xml.Doc* doc, string source) throws GLib.Error {
  691. if (find_head(doc) == null) {
  692. throw new IOError.FAILED(@"\"$source\" has no <head> element (a <head> and <body> are required)");
  693. }
  694. if (find_body(doc) == null) {
  695. throw new IOError.FAILED(@"\"$source\" has no <body> element (a <head> and <body> are required)");
  696. }
  697. }
  698. /**
  699. * Validates that the structural directives <pstm-title>, <pstm-template>
  700. * and <pstm-name> appear only inside <head>.
  701. */
  702. private void validate_head_directives(Xml.Doc* doc, string source) throws GLib.Error {
  703. var root = doc->get_root_element();
  704. if (root == null) {
  705. return;
  706. }
  707. string[] names = { "pstm-title", "pstm-template", "pstm-name", "pstm-uri" };
  708. foreach (var name in names) {
  709. var nodes = new Series<Xml.Node*>();
  710. find_all_from(root, name, nodes);
  711. foreach (var node in nodes) {
  712. if (!is_descendant_of_head(node)) {
  713. throw new IOError.FAILED(@"\"$source\": <$name> must appear inside <head>");
  714. }
  715. }
  716. }
  717. }
  718. /** Walks the ancestor chain to determine whether `node` is within <head>. */
  719. private static bool is_descendant_of_head(Xml.Node* node) {
  720. for (var p = node->parent; p != null; p = p->parent) {
  721. if (is_element(p) && ((string) p->name).down() == "head") {
  722. return true;
  723. }
  724. }
  725. return false;
  726. }
  727. private static Xml.Node* find_first_element(Xml.Node* root, string name) {
  728. if (!is_element(root)) {
  729. return null;
  730. }
  731. if (((string) root->name).down() == name.down()) {
  732. return root;
  733. }
  734. for (var child = root->children; child != null; child = child->next) {
  735. var found = find_first_element(child, name);
  736. if (found != null) {
  737. return found;
  738. }
  739. }
  740. return null;
  741. }
  742. private static Xml.Node*[] find_all_elements(Xml.Doc* doc, string name) {
  743. var collected = new Series<Xml.Node*>();
  744. var root = doc->get_root_element();
  745. if (root != null) {
  746. find_all_from(root, name, collected);
  747. }
  748. return collected.to_array();
  749. }
  750. private static void find_all_from(Xml.Node* node, string name, Series<Xml.Node*> result) {
  751. if (is_element(node) && ((string) node->name).down() == name.down()) {
  752. result.add(node);
  753. }
  754. if (is_element(node)) {
  755. for (var child = node->children; child != null; child = child->next) {
  756. find_all_from(child, name, result);
  757. }
  758. }
  759. }
  760. private static string? read_directive_text(Xml.Node* body, string directive) {
  761. var node = find_first_element(body, directive);
  762. if (node == null) {
  763. return null;
  764. }
  765. var text = element_text(node);
  766. return text.strip().length > 0 ? text.strip() : null;
  767. }
  768. private static string? read_pstm_name(Xml.Doc* doc) {
  769. var node = find_first_element(doc->get_root_element(), "pstm-name");
  770. if (node == null) {
  771. return null;
  772. }
  773. return element_text(node).strip();
  774. }
  775. private static string[] read_routes(Xml.Doc* doc) {
  776. string[] routes = new string[0];
  777. var nodes = find_all_elements(doc, "pstm-uri");
  778. foreach (var node in nodes) {
  779. var text = element_text(node).strip();
  780. if (text.length > 0) {
  781. routes += text;
  782. }
  783. }
  784. return routes;
  785. }
  786. private static string element_text(Xml.Node* node) {
  787. var b = new StringBuilder();
  788. for (var child = node->children; child != null; child = child->next) {
  789. if (child->type == ElementType.TEXT_NODE && child->content != null) {
  790. b.append((string) child->content);
  791. } else if (is_element(child)) {
  792. b.append(element_text(child));
  793. }
  794. }
  795. return b.str;
  796. }
  797. private static void apply_title(Xml.Doc* doc, string? title) {
  798. if (title == null || title.length == 0) {
  799. return;
  800. }
  801. var head = find_first_element(doc->get_root_element(), "head");
  802. if (head == null) {
  803. return;
  804. }
  805. var title_node = find_first_element(head, "title");
  806. if (title_node == null) {
  807. title_node = head->new_child(null, "title", null);
  808. }
  809. for (var child = title_node->children; child != null; child = child->next) {
  810. child->unlink();
  811. }
  812. title_node->add_content(title);
  813. }
  814. private static string serialize(Xml.Doc* doc) {
  815. // Serialize with libxml2's HTML serializer (htmlDocDumpMemory) so the
  816. // output is valid HTML: no <?xml?> prolog, no self-closing
  817. // `<script/>`, and correct void/non-void element handling. The doc was
  818. // produced by the HTML parser, so it carries HTML structure.
  819. string mem;
  820. int len;
  821. ((Html.Doc*) doc)->dump_memory(out mem, out len);
  822. return len > 0 ? mem.substring(0, len) : mem;
  823. }
  824. private static bool is_element(Xml.Node* node) {
  825. return node != null && node->type == ElementType.ELEMENT_NODE;
  826. }
  827. private static string compute_hash(uint8[] data) {
  828. var checksum = new Checksum(ChecksumType.SHA512);
  829. checksum.update(data, data.length);
  830. return checksum.get_string();
  831. }
  832. private static string escape(string s) {
  833. return s.replace("\\", "\\\\").replace("\"", "\\\"");
  834. }
  835. private static void write_file(string path, string contents) throws GLib.Error {
  836. var file = File.new_for_path(path);
  837. var stream = new DataOutputStream(file.replace(null, false, FileCreateFlags.NONE));
  838. stream.put_string(contents);
  839. stream.close();
  840. }
  841. private static string make_pascal_case(string input) {
  842. var basename = Path.get_basename(input);
  843. var dot = basename.last_index_of(".");
  844. if (dot > 0) {
  845. basename = basename.substring(0, dot);
  846. }
  847. var result = new StringBuilder();
  848. var capitalize_next = true;
  849. foreach (var c in basename.data) {
  850. if (c == '-' || c == '_' || c == ' ' || c == '.') {
  851. capitalize_next = true;
  852. } else {
  853. if (capitalize_next) {
  854. result.append_printf("%c", c >= 'a' && c <= 'z' ? c - 32 : c);
  855. capitalize_next = false;
  856. } else {
  857. result.append_printf("%c", c);
  858. }
  859. }
  860. }
  861. return result.str;
  862. }
  863. // ------------------------------------------------------------------
  864. // Model
  865. // ------------------------------------------------------------------
  866. /** Scratch state for {@link collect_client_refs}. */
  867. private class ClientRefs : Object {
  868. public Xml.Node* legacy = null;
  869. public Xml.Node*[] modules = new Xml.Node*[0];
  870. public int duplicates = 0;
  871. }
  872. private class VariantData : Object {
  873. public uint8[] identity;
  874. public uint8[]? gzip;
  875. public uint8[]? zstd;
  876. public uint8[]? br;
  877. public bool has_gzip;
  878. public bool has_zstd;
  879. public bool has_br;
  880. }
  881. }
  882. }