mechanica 2.0.3 → 2.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/chunks/{editor-JV0Nhfw4.js → editor-MStotuaz.js} +276 -106
  2. package/dist/chunks/node-adapter-4eD9p0iP.js +699 -0
  3. package/dist/chunks/page-assets-DsJXmoDs.js +70 -0
  4. package/dist/chunks/{page-assets-CM_MCuoa.js → rich-text-codec--Nssj0Nn.js} +71 -117
  5. package/dist/chunks/site-DR_X2rzc.js +62 -0
  6. package/dist/cli.js +59 -23
  7. package/dist/composer.js +16 -65
  8. package/dist/editor.css +112 -112
  9. package/dist/editor.js +69 -123
  10. package/dist/export.js +8 -5
  11. package/dist/plugin.js +69 -656
  12. package/dist/server.js +4 -0
  13. package/dist/types/cli/build.d.ts +3 -1
  14. package/dist/types/editor/lib/backend.d.ts +90 -0
  15. package/dist/types/editor/lib/page-list.d.ts +5 -20
  16. package/dist/types/{vite/dev → server}/assets-store.d.ts +2 -2
  17. package/dist/types/server/editor-page.d.ts +23 -0
  18. package/dist/types/server/index.d.ts +11 -0
  19. package/dist/types/server/node-adapter.d.ts +11 -0
  20. package/dist/types/{vite/dev → server}/pages-store.d.ts +5 -5
  21. package/dist/types/{vite → server}/rich-text-codec.d.ts +6 -0
  22. package/dist/types/server/service.d.ts +53 -0
  23. package/dist/types/server/site.d.ts +29 -0
  24. package/dist/types/vite/dev/middleware.d.ts +6 -28
  25. package/package.json +6 -2
  26. /package/dist/types/{vite/dev → server}/composed-store.d.ts +0 -0
  27. /package/dist/types/{vite/dev → server}/data-store.d.ts +0 -0
  28. /package/dist/types/{vite/dev → server}/fs-utils.d.ts +0 -0
  29. /package/dist/types/{vite/dev → server}/image-preview.d.ts +0 -0
  30. /package/dist/types/{vite/dev → server}/page-state.d.ts +0 -0
  31. /package/dist/types/{vite/dev → server}/query-dev.d.ts +0 -0
@@ -0,0 +1,70 @@
1
+ //#region src/cli/page-assets.ts
2
+ /**
3
+ * Resolve which built files a page needs for its blocks, from the client
4
+ * build's Vite manifest (`dist/.vite/manifest.json`) plus the plugin-emitted
5
+ * block map (`dist/mechanica-blocks.json`, block id → source file + the
6
+ * output chunk that contains it).
7
+ *
8
+ * Blocks are code-split out of the client entry, so without help the browser
9
+ * would discover a page's block chunks only after the entry runs (a round
10
+ * trip) and their CSS only at hydrate time (a flash of unstyled blocks). The
11
+ * export injects `<link rel="stylesheet">` + `<link rel="modulepreload">` per
12
+ * page instead, computed here.
13
+ *
14
+ * Blocks are located in the manifest by their chunk **file** (not a source
15
+ * key): with `blockChunks: 'bundled'` many blocks share one chunk, which has
16
+ * no per-block manifest entries — the chunk file is the stable join point.
17
+ */
18
+ /**
19
+ * Where the plugin writes the block map in the client build's outDir
20
+ * (`generateBundle` in `src/vite/plugin.ts`).
21
+ */
22
+ var BLOCKS_MANIFEST_FILE = "mechanica-blocks.json";
23
+ /**
24
+ * Collect a manifest entry's chunk, its CSS, and everything its static
25
+ * imports pull in (transitively) — the full set the browser will fetch when
26
+ * that module is imported.
27
+ */
28
+ function resolveChunkAssets(manifest, key, into = {
29
+ js: [],
30
+ css: []
31
+ }, seen = /* @__PURE__ */ new Set()) {
32
+ if (seen.has(key)) return into;
33
+ seen.add(key);
34
+ const chunk = manifest[key];
35
+ if (!chunk) return into;
36
+ if (!into.js.includes(chunk.file)) into.js.push(chunk.file);
37
+ for (const css of chunk.css ?? []) if (!into.css.includes(css)) into.css.push(css);
38
+ for (const imported of chunk.imports ?? []) resolveChunkAssets(manifest, imported, into, seen);
39
+ return into;
40
+ }
41
+ /**
42
+ * Build the `<link>` tags for one page: stylesheets first (they must apply
43
+ * before first paint — the server-rendered blocks are already in the HTML),
44
+ * then `modulepreload` for the block chunks and their shared imports.
45
+ *
46
+ * Every tag carries `crossorigin`, like the ones Vite writes into the built
47
+ * index: a later `import()` of the same chunk always fetches in CORS mode, and
48
+ * on a cross-origin CDN a copy cached by a no-CORS hint has no
49
+ * `Access-Control-Allow-Origin`, so the browser would block the import. The
50
+ * attribute is a no-op for same-origin builds.
51
+ */
52
+ function blockAssetLinks(options) {
53
+ const keyByFile = /* @__PURE__ */ new Map();
54
+ for (const [key, entry] of Object.entries(options.manifest)) keyByFile.set(entry.file, key);
55
+ const assets = {
56
+ js: [],
57
+ css: []
58
+ };
59
+ const seen = /* @__PURE__ */ new Set();
60
+ for (const blockId of options.blockIds) {
61
+ const ref = options.blockFiles[blockId];
62
+ const key = ref && keyByFile.get(ref.chunk);
63
+ if (key) resolveChunkAssets(options.manifest, key, assets, seen);
64
+ }
65
+ const wanted = (file) => !options.alreadyLinked?.(file);
66
+ const href = (file) => `${options.base ?? ""}/${file}`;
67
+ return [...assets.css.filter(wanted).map((file) => `<link rel="stylesheet" crossorigin href="${href(file)}">`), ...assets.js.filter(wanted).map((file) => `<link rel="modulepreload" crossorigin href="${href(file)}">`)];
68
+ }
69
+ //#endregion
70
+ export { blockAssetLinks as n, BLOCKS_MANIFEST_FILE as t };
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
- import { basename, dirname, join, parse, relative } from "node:path";
3
- import { diffTranslation, migrateContent, passDefaultValue, walkSchema, walkTree } from "mechanica-shared";
2
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
3
+ import { UPLOADS_PREFIX, diffTranslation, migrateContent, passDefaultValue, walkSchema, walkTree } from "mechanica-shared";
4
4
  import { createHash } from "node:crypto";
5
5
  import { parsePage, serializePage } from "mechanica-shared/page-format";
6
6
  import { createRequire } from "node:module";
@@ -59,7 +59,7 @@ async function analyzeImageBuffer(buffer) {
59
59
  }
60
60
  }
61
61
  //#endregion
62
- //#region src/vite/dev/fs-utils.ts
62
+ //#region src/server/fs-utils.ts
63
63
  /**
64
64
  * Filesystem helpers for the `.mech` store: atomic writes (temp file + rename,
65
65
  * so a crash mid-save never leaves a half-written page) and a registry of our
@@ -93,7 +93,7 @@ function writeFileAtomic(file, content) {
93
93
  markMutated(file);
94
94
  }
95
95
  //#endregion
96
- //#region src/vite/dev/assets-store.ts
96
+ //#region src/server/assets-store.ts
97
97
  /** Find a non-colliding filename in `dir`, suffixing `_1`, `_2`, … as needed. */
98
98
  function getUniqueName(dir, fileName) {
99
99
  const existing = fs.existsSync(dir) ? fs.readdirSync(dir) : [];
@@ -107,8 +107,6 @@ function getUniqueName(dir, fileName) {
107
107
  return candidate;
108
108
  }
109
109
  var assetsDir = (mechDir) => join(mechDir, "assets");
110
- /** The URL prefix uploaded assets are referenced by in page data. */
111
- var UPLOADS_PREFIX = "/@mechanica/assets/";
112
110
  /** Public URL the dev server serves an asset under. */
113
111
  var assetUrl = (fileName) => `${UPLOADS_PREFIX}${fileName}`;
114
112
  /**
@@ -125,8 +123,8 @@ function isDerivedAsset(fileName) {
125
123
  }
126
124
  /** The asset filename an uploaded-asset src refers to, or null for other URLs. */
127
125
  function assetFileOf(src) {
128
- if (typeof src !== "string" || !src.startsWith("/@mechanica/assets/")) return null;
129
- const file = src.slice(19);
126
+ if (typeof src !== "string" || !src.startsWith(UPLOADS_PREFIX)) return null;
127
+ const file = src.slice(UPLOADS_PREFIX.length);
130
128
  try {
131
129
  return decodeURIComponent(file);
132
130
  } catch {
@@ -252,7 +250,7 @@ function listImages(mechDir) {
252
250
  }));
253
251
  }
254
252
  //#endregion
255
- //#region src/vite/dev/pages-store.ts
253
+ //#region src/server/pages-store.ts
256
254
  /** File extension for page documents under `<mech>/pages`. */
257
255
  var EXT = ".page.md";
258
256
  /**
@@ -298,16 +296,24 @@ function translationsOf(mechDir, urlPath, config) {
298
296
  for (const { locale } of variantFilesOf(mechDir, urlPath)) if (config.all.includes(locale)) present.add(locale);
299
297
  return config.all.filter((code) => present.has(code));
300
298
  }
301
- var richTextCodec;
302
- /** Configure the codec used to (de)serialize rich-text fields. Dev server only. */
303
- function setPageCodec(codec) {
304
- richTextCodec = codec;
299
+ var sites = /* @__PURE__ */ new Map();
300
+ var siteOf = (mechDir) => {
301
+ const key = resolve(mechDir);
302
+ let site = sites.get(key);
303
+ if (!site) sites.set(key, site = {});
304
+ return site;
305
+ };
306
+ /** Configure the codec used to (de)serialize a site's rich-text fields. */
307
+ function setPageCodec(mechDir, codec) {
308
+ siteOf(mechDir).codec = codec;
305
309
  }
306
- var codecOptions = () => richTextCodec ? { richText: richTextCodec } : void 0;
307
- var blocksMeta;
308
- /** Configure block metadata used to migrate page data on read. Dev server only. */
309
- function setPageBlocks(blocks) {
310
- blocksMeta = blocks ? new Map(blocks.map((block) => [block.id, block])) : void 0;
310
+ var codecOptions = (mechDir) => {
311
+ const codec = siteOf(mechDir).codec;
312
+ return codec ? { richText: codec } : void 0;
313
+ };
314
+ /** Configure the block metadata a site's pages are read and written with. */
315
+ function setPageBlocks(mechDir, blocks) {
316
+ siteOf(mechDir).blocks = blocks ? new Map(blocks.map((block) => [block.id, block])) : void 0;
311
317
  }
312
318
  /**
313
319
  * Fill schema defaults into placed block data, in place — the same pass
@@ -315,7 +321,8 @@ function setPageBlocks(blocks) {
315
321
  * defaulted prop renders identically in dev and in the exported site.
316
322
  * A no-op until {@link setPageBlocks} has run.
317
323
  */
318
- function fillContentDefaults(content) {
324
+ function fillContentDefaults(mechDir, content) {
325
+ const blocksMeta = siteOf(mechDir).blocks;
319
326
  if (!blocksMeta) return;
320
327
  walkTree(content, (block) => {
321
328
  const meta = blocksMeta.get(block.blockId);
@@ -329,6 +336,7 @@ function fillContentDefaults(content) {
329
336
  * runtime state is complete. A no-op until {@link setPageBlocks} has run.
330
337
  */
331
338
  function fillImageMeta(mechDir, content) {
339
+ const blocksMeta = siteOf(mechDir).blocks;
332
340
  if (!blocksMeta) return;
333
341
  applyImageManifest(content, blocksMeta, readImageManifest(mechDir));
334
342
  }
@@ -345,9 +353,9 @@ var emptyPage = () => ({
345
353
  content: [],
346
354
  data: {}
347
355
  });
348
- var readFile = (file) => parsePage(fs.readFileSync(file, "utf-8"), codecOptions());
349
- var writeFile = (file, page) => {
350
- writeFileAtomic(file, serializePage(page, codecOptions()));
356
+ var readFile = (mechDir, file) => parsePage(fs.readFileSync(file, "utf-8"), codecOptions(mechDir));
357
+ var writeFile = (mechDir, file, page) => {
358
+ writeFileAtomic(file, serializePage(page, codecOptions(mechDir)));
351
359
  };
352
360
  /**
353
361
  * Resolve a URL path to its page file under `<mechDir>/pages`. A `locale`
@@ -364,7 +372,8 @@ function getPagePath(mechDir, urlPath, locale) {
364
372
  function readPage(mechDir, urlPath, locale) {
365
373
  const file = getPagePath(mechDir, urlPath, locale);
366
374
  if (!fs.existsSync(file)) return emptyPage();
367
- const page = readFile(file);
375
+ const page = readFile(mechDir, file);
376
+ const blocksMeta = siteOf(mechDir).blocks;
368
377
  if (blocksMeta && page.content) migrateContent(page.content, blocksMeta);
369
378
  return page;
370
379
  }
@@ -408,7 +417,7 @@ function createPage(mechDir, input) {
408
417
  name: input.name,
409
418
  path: input.path
410
419
  };
411
- writeFile(file, page);
420
+ writeFile(mechDir, file, page);
412
421
  return {
413
422
  ...page,
414
423
  path: folderPrefix + input.path.trim()
@@ -429,10 +438,10 @@ function duplicatePage(mechDir, sourcePath, input) {
429
438
  path: input.path,
430
439
  ...source.draft ? { draft: true } : {}
431
440
  };
432
- writeFile(file, page);
441
+ writeFile(mechDir, file, page);
433
442
  for (const { locale, file: variantFile } of variantFilesOf(mechDir, sourcePath)) {
434
- const variant = readFile(variantFile);
435
- writeFile(getPagePath(mechDir, targetPath, locale), {
443
+ const variant = readFile(mechDir, variantFile);
444
+ writeFile(mechDir, getPagePath(mechDir, targetPath, locale), {
436
445
  content: variant.content ?? [],
437
446
  data: variant.data ?? {},
438
447
  meta: variant.meta,
@@ -484,7 +493,7 @@ function createTranslation(mechDir, urlPath, locale) {
484
493
  path: source.path,
485
494
  ...source.draft ? { draft: true } : {}
486
495
  };
487
- writeFile(target, page);
496
+ writeFile(mechDir, target, page);
488
497
  return page;
489
498
  }
490
499
  /** Delete a single translation of a page. Returns whether it existed. */
@@ -507,13 +516,13 @@ function movePage(mechDir, fromPath, toPath) {
507
516
  const target = getPagePath(mechDir, cleaned);
508
517
  if (target !== file && fs.existsSync(target)) throw new PageExistsError(cleaned);
509
518
  const variants = variantFilesOf(mechDir, fromPath);
510
- const page = readFile(file);
519
+ const page = readFile(mechDir, file);
511
520
  page.path = cleaned;
512
- writeFile(target, page);
521
+ writeFile(mechDir, target, page);
513
522
  for (const { locale, file: variantFile } of variants) {
514
- const variant = readFile(variantFile);
523
+ const variant = readFile(mechDir, variantFile);
515
524
  variant.path = cleaned;
516
- writeFile(getPagePath(mechDir, cleaned, locale), variant);
525
+ writeFile(mechDir, getPagePath(mechDir, cleaned, locale), variant);
517
526
  }
518
527
  if (target !== file) {
519
528
  fs.rmSync(file);
@@ -534,18 +543,19 @@ function movePage(mechDir, fromPath, toPath) {
534
543
  */
535
544
  function savePage(mechDir, urlPath, patch, locale) {
536
545
  const file = getPagePath(mechDir, urlPath, locale);
537
- const page = fs.existsSync(file) ? readFile(file) : emptyPage();
546
+ const page = fs.existsSync(file) ? readFile(mechDir, file) : emptyPage();
538
547
  if (patch.content !== void 0) page.content = patch.content;
539
548
  if (patch.data !== void 0) page.data = patch.data;
540
549
  if (patch.layout !== void 0 && !locale) {
541
550
  if (patch.layout) page.layout = patch.layout;
542
551
  else delete page.layout;
543
552
  }
553
+ const blocksMeta = siteOf(mechDir).blocks;
544
554
  if (blocksMeta && page.content) updateImageManifest(mechDir, harvestImageMeta(page.content, blocksMeta));
545
555
  if (locale && pageVersion(mechDir, urlPath) != null) {
546
556
  const base = readPage(mechDir, urlPath);
547
557
  if (blocksMeta && base.content) {
548
- fillContentDefaults(base.content);
558
+ fillContentDefaults(mechDir, base.content);
549
559
  fillImageMeta(mechDir, base.content);
550
560
  harvestImageMeta(base.content, blocksMeta);
551
561
  }
@@ -559,7 +569,7 @@ function savePage(mechDir, urlPath, patch, locale) {
559
569
  page.content = sparse.content;
560
570
  page.data = sparse.data;
561
571
  }
562
- writeFile(file, page);
572
+ writeFile(mechDir, file, page);
563
573
  return pageVersion(mechDir, urlPath, locale);
564
574
  }
565
575
  /**
@@ -574,12 +584,12 @@ function renamePage(mechDir, urlPath, name) {
574
584
  let wrote = false;
575
585
  for (const target of files) {
576
586
  if (!fs.existsSync(target)) continue;
577
- const page = readFile(target);
587
+ const page = readFile(mechDir, target);
578
588
  page.name = name;
579
- writeFile(target, page);
589
+ writeFile(mechDir, target, page);
580
590
  wrote = true;
581
591
  }
582
- if (!wrote) writeFile(file, {
592
+ if (!wrote) writeFile(mechDir, file, {
583
593
  ...emptyPage(),
584
594
  name
585
595
  });
@@ -591,10 +601,10 @@ function renamePage(mechDir, urlPath, name) {
591
601
  function setPageDraft(mechDir, urlPath, draft, locale) {
592
602
  const file = getPagePath(mechDir, urlPath, locale);
593
603
  if (!fs.existsSync(file)) return;
594
- const page = readFile(file);
604
+ const page = readFile(mechDir, file);
595
605
  if (draft) page.draft = true;
596
606
  else delete page.draft;
597
- writeFile(file, page);
607
+ writeFile(mechDir, file, page);
598
608
  }
599
609
  /** List folders (top-level directories) under `<mechDir>/pages`. */
600
610
  function listFolders(mechDir) {
@@ -640,12 +650,12 @@ function listPages(mechDir, options = {}) {
640
650
  }
641
651
  const items = [];
642
652
  for (const entry of bases) {
643
- const page = readFile(join(pagesDir, entry.relative));
653
+ const page = readFile(mechDir, join(pagesDir, entry.relative));
644
654
  let source = page;
645
655
  if (options.locale) {
646
656
  const variantFile = getPagePath(mechDir, entry.path, options.locale);
647
657
  if (!fs.existsSync(variantFile)) continue;
648
- source = readFile(variantFile);
658
+ source = readFile(mechDir, variantFile);
649
659
  }
650
660
  const embedded = {};
651
661
  for (const dataEntry of options.data ?? []) embedded[dataEntry.id] = source.data?.[dataEntry.id] ?? {};
@@ -712,7 +722,7 @@ function comparePages(a, b) {
712
722
  return a.folderPath.localeCompare(b.folderPath);
713
723
  }
714
724
  //#endregion
715
- //#region src/vite/dev/data-store.ts
725
+ //#region src/server/data-store.ts
716
726
  /** Site-wide data lives in a single file alongside the pages directory. */
717
727
  var SITE_DATA_FILE = "data.json";
718
728
  /** Folder-scoped data for every folder lives in one file, keyed by folder path. */
@@ -896,7 +906,7 @@ function composedBlockMeta(def) {
896
906
  };
897
907
  }
898
908
  //#endregion
899
- //#region src/vite/rich-text-codec.ts
909
+ //#region src/server/rich-text-codec.ts
900
910
  /**
901
911
  * Build a {@link RichTextCodec} from compiled block components: it maps each
902
912
  * block's `richText` props (so the page codec knows which fields to store as
@@ -919,85 +929,29 @@ function buildRichTextCodec(blocks) {
919
929
  };
920
930
  }
921
931
  /**
922
- * Top-level props whose (compact) schema is the `richText` alias — either the
923
- * shorthand string `'richText'` or an expanded node with `format: 'richText'`.
932
+ * The same codec from block **metadata** (a site manifest's `blocks`, whose
933
+ * `props` are unfolded JSON schemas) — for hosts that have no components.
934
+ */
935
+ function richTextCodecFromBlocks(blocks) {
936
+ return buildRichTextCodec([...blocks].map((block) => ({
937
+ blockId: block.id,
938
+ blockSchema: { props: block.props }
939
+ })));
940
+ }
941
+ /**
942
+ * Top-level props whose schema is the `richText` alias — either the shorthand
943
+ * string `'richText'` or an expanded node with `format: 'richText'`. Takes a
944
+ * compact props map or an unfolded object schema (`{ type, properties }`).
924
945
  */
925
946
  function findRichTextProps(props) {
926
947
  const found = /* @__PURE__ */ new Set();
927
948
  if (props && typeof props === "object") {
928
- for (const [key, value] of Object.entries(props)) if (value === "richText") found.add(key);
949
+ const unfolded = props;
950
+ const fields = unfolded.type === "object" && unfolded.properties && typeof unfolded.properties === "object" ? unfolded.properties : props;
951
+ for (const [key, value] of Object.entries(fields)) if (value === "richText") found.add(key);
929
952
  else if (value && typeof value === "object" && value.format === "richText") found.add(key);
930
953
  }
931
954
  return found;
932
955
  }
933
956
  //#endregion
934
- //#region src/cli/page-assets.ts
935
- /**
936
- * Resolve which built files a page needs for its blocks, from the client
937
- * build's Vite manifest (`dist/.vite/manifest.json`) plus the plugin-emitted
938
- * block map (`dist/mechanica-blocks.json`, block id → source file + the
939
- * output chunk that contains it).
940
- *
941
- * Blocks are code-split out of the client entry, so without help the browser
942
- * would discover a page's block chunks only after the entry runs (a round
943
- * trip) and their CSS only at hydrate time (a flash of unstyled blocks). The
944
- * export injects `<link rel="stylesheet">` + `<link rel="modulepreload">` per
945
- * page instead, computed here.
946
- *
947
- * Blocks are located in the manifest by their chunk **file** (not a source
948
- * key): with `blockChunks: 'bundled'` many blocks share one chunk, which has
949
- * no per-block manifest entries — the chunk file is the stable join point.
950
- */
951
- /**
952
- * Where the plugin writes the block map in the client build's outDir
953
- * (`generateBundle` in `src/vite/plugin.ts`).
954
- */
955
- var BLOCKS_MANIFEST_FILE = "mechanica-blocks.json";
956
- /**
957
- * Collect a manifest entry's chunk, its CSS, and everything its static
958
- * imports pull in (transitively) — the full set the browser will fetch when
959
- * that module is imported.
960
- */
961
- function resolveChunkAssets(manifest, key, into = {
962
- js: [],
963
- css: []
964
- }, seen = /* @__PURE__ */ new Set()) {
965
- if (seen.has(key)) return into;
966
- seen.add(key);
967
- const chunk = manifest[key];
968
- if (!chunk) return into;
969
- if (!into.js.includes(chunk.file)) into.js.push(chunk.file);
970
- for (const css of chunk.css ?? []) if (!into.css.includes(css)) into.css.push(css);
971
- for (const imported of chunk.imports ?? []) resolveChunkAssets(manifest, imported, into, seen);
972
- return into;
973
- }
974
- /**
975
- * Build the `<link>` tags for one page: stylesheets first (they must apply
976
- * before first paint — the server-rendered blocks are already in the HTML),
977
- * then `modulepreload` for the block chunks and their shared imports.
978
- *
979
- * Every tag carries `crossorigin`, like the ones Vite writes into the built
980
- * index: a later `import()` of the same chunk always fetches in CORS mode, and
981
- * on a cross-origin CDN a copy cached by a no-CORS hint has no
982
- * `Access-Control-Allow-Origin`, so the browser would block the import. The
983
- * attribute is a no-op for same-origin builds.
984
- */
985
- function blockAssetLinks(options) {
986
- const keyByFile = /* @__PURE__ */ new Map();
987
- for (const [key, entry] of Object.entries(options.manifest)) keyByFile.set(entry.file, key);
988
- const assets = {
989
- js: [],
990
- css: []
991
- };
992
- const seen = /* @__PURE__ */ new Set();
993
- for (const blockId of options.blockIds) {
994
- const ref = options.blockFiles[blockId];
995
- const key = ref && keyByFile.get(ref.chunk);
996
- if (key) resolveChunkAssets(options.manifest, key, assets, seen);
997
- }
998
- const wanted = (file) => !options.alreadyLinked?.(file);
999
- const href = (file) => `${options.base ?? ""}/${file}`;
1000
- return [...assets.css.filter(wanted).map((file) => `<link rel="stylesheet" crossorigin href="${href(file)}">`), ...assets.js.filter(wanted).map((file) => `<link rel="modulepreload" crossorigin href="${href(file)}">`)];
1001
- }
1002
- //#endregion
1003
- export { renamePage as A, readImageManifest as B, getPagePath as C, pageUrlOf as D, movePage as E, translationsOf as F, wasRecentlyMutated as G, saveUpload as H, UPLOADS_PREFIX as I, hasSharp as J, writeFileAtomic as K, assetFileOf as L, setPageBlocks as M, setPageCodec as N, pageVersion as O, setPageDraft as P, isDerivedAsset as R, fillImageMeta as S, listPages as T, updateImageManifest as U, saveDerivedAsset as V, markMutated as W, isRasterImage as Y, createTranslation as _, toBlockMeta as a, duplicatePage as b, mergeLocaleFolderData as c, readFolderData as d, readFoldersData as f, createPage as g, PageExistsError as h, composedBlockMeta as i, savePage as j, readPage as k, mergeLocaleSiteData as l, readSiteLocaleOverride as m, blockAssetLinks as n, folderOf as o, readSiteData as p, analyzeImageBuffer as q, buildRichTextCodec as r, mergeFolderData as s, BLOCKS_MANIFEST_FILE as t, mergeSiteData as u, deletePage as v, listFolders as w, fillContentDefaults as x, deleteTranslation as y, listImages as z };
957
+ export { savePage as A, saveDerivedAsset as B, listFolders as C, pageVersion as D, pageUrlOf as E, UPLOADS_PREFIX as F, writeFileAtomic as G, updateImageManifest as H, assetFileOf as I, isRasterImage as J, analyzeImageBuffer as K, isDerivedAsset as L, setPageCodec as M, setPageDraft as N, readPage as O, translationsOf as P, listImages as R, getPagePath as S, movePage as T, markMutated as U, saveUpload as V, wasRecentlyMutated as W, deletePage as _, folderOf as a, fillContentDefaults as b, mergeLocaleSiteData as c, readFoldersData as d, readSiteData as f, createTranslation as g, createPage as h, toBlockMeta as i, setPageBlocks as j, renamePage as k, mergeSiteData as l, PageExistsError as m, richTextCodecFromBlocks as n, mergeFolderData as o, readSiteLocaleOverride as p, hasSharp as q, composedBlockMeta as r, mergeLocaleFolderData as s, buildRichTextCodec as t, readFolderData as u, deleteTranslation as v, listPages as w, fillImageMeta as x, duplicatePage as y, readImageManifest as z };
@@ -0,0 +1,62 @@
1
+ import { M as setPageCodec, i as toBlockMeta, j as setPageBlocks, n as richTextCodecFromBlocks, r as composedBlockMeta } from "./rich-text-codec--Nssj0Nn.js";
2
+ import fs from "node:fs";
3
+ import { join } from "node:path";
4
+ import { SITE_MANIFEST_FILE, areFieldSchemasRegistered, localePath, registerFieldSchemas } from "mechanica-shared";
5
+ //#region src/vite/generate-pages.ts
6
+ /** Run every provider's `list` once and flatten the results. */
7
+ async function collectGeneratedPages(providers, ctx) {
8
+ if (!providers?.length) return [];
9
+ return (await Promise.all(providers.map((p) => (typeof p === "function" ? p : p.list)(ctx)))).flat();
10
+ }
11
+ /** The served (locale-prefixed) URL a generated page renders at. */
12
+ function generatedServedPath(page, config) {
13
+ if (!config || !page.locale || page.locale === config.default) return page.path;
14
+ return localePath(page.path, page.locale, config);
15
+ }
16
+ //#endregion
17
+ //#region src/server/site.ts
18
+ /** Describe a site's code as data — see {@link SiteManifest}. */
19
+ function buildSiteManifest(input) {
20
+ if (!areFieldSchemasRegistered()) registerFieldSchemas();
21
+ return {
22
+ format: 1,
23
+ ...input.engine ? { engine: input.engine } : {},
24
+ blocks: [...[...input.components].map(toBlockMeta), ...(input.composed ?? []).map(composedBlockMeta)],
25
+ ...input.site?.url || input.site?.name ? { site: input.site } : {},
26
+ locales: input.locales ?? null,
27
+ generated: input.generated ?? []
28
+ };
29
+ }
30
+ /** Read the manifest a build left in `distDir`, or null when there is none. */
31
+ function readSiteManifest(distDir) {
32
+ const file = join(distDir, SITE_MANIFEST_FILE);
33
+ if (!fs.existsSync(file)) return null;
34
+ const manifest = JSON.parse(fs.readFileSync(file, "utf-8"));
35
+ if (manifest.format !== 1) throw new Error(`Unsupported site manifest format: ${String(manifest.format)}`);
36
+ return manifest;
37
+ }
38
+ /**
39
+ * Tell the stores what the code behind a `.mech` directory looks like: the
40
+ * rich-text codec and the block metadata every page read and write of that
41
+ * site goes through. Keyed by directory, so one process can serve many sites.
42
+ */
43
+ function configureSite(mechDir, manifest) {
44
+ if (!areFieldSchemasRegistered()) registerFieldSchemas();
45
+ setPageCodec(mechDir, richTextCodecFromBlocks(manifest.blocks));
46
+ setPageBlocks(mechDir, manifest.blocks);
47
+ }
48
+ function indexGeneratedPages(manifest) {
49
+ const byServed = /* @__PURE__ */ new Map();
50
+ const logical = /* @__PURE__ */ new Set();
51
+ for (const page of manifest.generated) {
52
+ byServed.set(generatedServedPath(page, manifest.locales), page);
53
+ logical.add(page.path);
54
+ }
55
+ return {
56
+ pages: manifest.generated,
57
+ byServed,
58
+ logical
59
+ };
60
+ }
61
+ //#endregion
62
+ export { collectGeneratedPages as a, readSiteManifest as i, configureSite as n, indexGeneratedPages as r, buildSiteManifest as t };
package/dist/cli.js CHANGED
@@ -1,10 +1,12 @@
1
- import { B as readImageManifest, J as hasSharp, R as isDerivedAsset, U as updateImageManifest, Y as isRasterImage, q as analyzeImageBuffer } from "./chunks/page-assets-CM_MCuoa.js";
1
+ import { t as buildSiteManifest } from "./chunks/site-DR_X2rzc.js";
2
+ import { H as updateImageManifest, J as isRasterImage, K as analyzeImageBuffer, L as isDerivedAsset, q as hasSharp, z as readImageManifest } from "./chunks/rich-text-codec--Nssj0Nn.js";
2
3
  import { exportBuilt } from "./export.js";
3
4
  import fs, { readFileSync } from "node:fs";
4
5
  import { dirname, join } from "node:path";
6
+ import { EDITOR_DIST_DIR, SITE_MANIFEST_FILE } from "mechanica-shared";
5
7
  import { chmod, mkdir, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
9
  import { build } from "vite";
7
- import { fileURLToPath } from "node:url";
8
10
  import os from "node:os";
9
11
  import { spawn } from "node:child_process";
10
12
  import readline from "node:readline";
@@ -34,6 +36,24 @@ function parseArgs(argv) {
34
36
  };
35
37
  }
36
38
  //#endregion
39
+ //#region src/cli/platform/engine-version.ts
40
+ /**
41
+ * This package's version, read from its own `package.json` — found by walking
42
+ * up from this module, which sits at a different depth in `src/` and in the
43
+ * built `dist/` (and its chunks).
44
+ */
45
+ function engineVersion() {
46
+ let dir = dirname(fileURLToPath(import.meta.url));
47
+ for (let depth = 0; depth < 6; depth++) {
48
+ try {
49
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
50
+ if (pkg.name === "mechanica" && typeof pkg.version === "string") return pkg.version;
51
+ } catch {}
52
+ dir = dirname(dir);
53
+ }
54
+ throw new Error("Could not determine the mechanica version");
55
+ }
56
+ //#endregion
37
57
  //#region src/cli/build.ts
38
58
  /**
39
59
  * Produce the client and SSR bundles into `dist/`. Uses the project's
@@ -44,7 +64,7 @@ function parseArgs(argv) {
44
64
  * SSR module — the plugin generates the actual entry, so its options (user
45
65
  * entry, site url/name) all ride the bundle without duplication here.
46
66
  */
47
- async function runBuild() {
67
+ async function runBuild(options = {}) {
48
68
  console.info("Building client bundle…");
49
69
  await build({ build: {
50
70
  outDir: "dist",
@@ -71,8 +91,39 @@ async function runBuild() {
71
91
  } finally {
72
92
  await rm(ssrEntryPath, { force: true });
73
93
  }
94
+ await writeSiteManifest(join(process.cwd(), "dist"));
95
+ if (options.editor) {
96
+ console.info("Building editor bundle…");
97
+ process.env.MECHANICA_EDITOR_BUILD = "1";
98
+ try {
99
+ await build({ build: {
100
+ outDir: join("dist", EDITOR_DIST_DIR),
101
+ emptyOutDir: true
102
+ } });
103
+ } finally {
104
+ delete process.env.MECHANICA_EDITOR_BUILD;
105
+ }
106
+ }
74
107
  console.info("Build complete → dist/");
75
108
  }
109
+ /**
110
+ * Describe the site's code as data (`dist/mechanica-site.json`): block
111
+ * schemas, locales, generated pages — read off the SSR bundle just built. A
112
+ * host that serves the editor for this bundle reads the file instead of
113
+ * running the bundle.
114
+ */
115
+ async function writeSiteManifest(distDir) {
116
+ const ssr = await import(`${pathToFileURL(join(distDir, "ssr.js")).href}?t=${Date.now()}`);
117
+ const manifest = buildSiteManifest({
118
+ components: ssr.blocksList ?? [],
119
+ composed: ssr.composedList ?? [],
120
+ locales: ssr.locales ?? null,
121
+ generated: ssr.generatedPages ?? [],
122
+ site: ssr.site,
123
+ engine: engineVersion()
124
+ });
125
+ await writeFile(join(distDir, SITE_MANIFEST_FILE), JSON.stringify(manifest));
126
+ }
76
127
  //#endregion
77
128
  //#region src/cli/run-export.ts
78
129
  /**
@@ -433,24 +484,6 @@ async function packBundle(distDir, meta) {
433
484
  }))));
434
485
  }
435
486
  //#endregion
436
- //#region src/cli/platform/engine-version.ts
437
- /**
438
- * This package's version, read from its own `package.json` — found by walking
439
- * up from this module, which sits at a different depth in `src/` and in the
440
- * built `dist/` (and its chunks).
441
- */
442
- function engineVersion() {
443
- let dir = dirname(fileURLToPath(import.meta.url));
444
- for (let depth = 0; depth < 6; depth++) {
445
- try {
446
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
447
- if (pkg.name === "mechanica" && typeof pkg.version === "string") return pkg.version;
448
- } catch {}
449
- dir = dirname(dir);
450
- }
451
- throw new Error("Could not determine the mechanica version");
452
- }
453
- //#endregion
454
487
  //#region src/cli/platform/push.ts
455
488
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
456
489
  var POLL_MS = 1e3;
@@ -518,7 +551,7 @@ async function runPush() {
518
551
  let status = await request(link.origin, "GET", statusPath, { token });
519
552
  let deployId = null;
520
553
  if (status.needsBundle) {
521
- await runBuild();
554
+ await runBuild({ editor: true });
522
555
  const body = await packBundle(join(cwd, "dist"), {
523
556
  commit: head,
524
557
  engine: engineVersion()
@@ -1225,6 +1258,9 @@ var HELP = `mechanica — build Vue 3 sites with a visual block editor
1225
1258
 
1226
1259
  Usage:
1227
1260
  mechanica build Build the client + SSR bundles into dist/
1261
+ (--editor also builds dist/mechanica-editor/: the
1262
+ site with the editor overlay, for a host that
1263
+ serves editing without the dev server)
1228
1264
  mechanica export Build, then statically render every page into export/
1229
1265
  (a site url — the plugin's siteUrl option or
1230
1266
  --site-url <origin> — also turns on the automatic
@@ -1259,7 +1295,7 @@ async function run(argv) {
1259
1295
  const { command, args, flags } = parseArgs(argv);
1260
1296
  const str = (value) => typeof value === "string" ? value : void 0;
1261
1297
  switch (command) {
1262
- case "build": return runBuild();
1298
+ case "build": return runBuild({ editor: flags.editor === true });
1263
1299
  case "export": return runExport({
1264
1300
  siteUrl: str(flags["site-url"]),
1265
1301
  siteName: str(flags["site-name"]),