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.
- package/dist/chunks/{editor-JV0Nhfw4.js → editor-MStotuaz.js} +276 -106
- package/dist/chunks/node-adapter-4eD9p0iP.js +699 -0
- package/dist/chunks/page-assets-DsJXmoDs.js +70 -0
- package/dist/chunks/{page-assets-CM_MCuoa.js → rich-text-codec--Nssj0Nn.js} +71 -117
- package/dist/chunks/site-DR_X2rzc.js +62 -0
- package/dist/cli.js +59 -23
- package/dist/composer.js +16 -65
- package/dist/editor.css +112 -112
- package/dist/editor.js +69 -123
- package/dist/export.js +8 -5
- package/dist/plugin.js +69 -656
- package/dist/server.js +4 -0
- package/dist/types/cli/build.d.ts +3 -1
- package/dist/types/editor/lib/backend.d.ts +90 -0
- package/dist/types/editor/lib/page-list.d.ts +5 -20
- package/dist/types/{vite/dev → server}/assets-store.d.ts +2 -2
- package/dist/types/server/editor-page.d.ts +23 -0
- package/dist/types/server/index.d.ts +11 -0
- package/dist/types/server/node-adapter.d.ts +11 -0
- package/dist/types/{vite/dev → server}/pages-store.d.ts +5 -5
- package/dist/types/{vite → server}/rich-text-codec.d.ts +6 -0
- package/dist/types/server/service.d.ts +53 -0
- package/dist/types/server/site.d.ts +29 -0
- package/dist/types/vite/dev/middleware.d.ts +6 -28
- package/package.json +6 -2
- /package/dist/types/{vite/dev → server}/composed-store.d.ts +0 -0
- /package/dist/types/{vite/dev → server}/data-store.d.ts +0 -0
- /package/dist/types/{vite/dev → server}/fs-utils.d.ts +0 -0
- /package/dist/types/{vite/dev → server}/image-preview.d.ts +0 -0
- /package/dist/types/{vite/dev → server}/page-state.d.ts +0 -0
- /package/dist/types/{vite/dev → server}/query-dev.d.ts +0 -0
package/dist/plugin.js
CHANGED
|
@@ -1,27 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import { a as collectGeneratedPages, n as configureSite, r as indexGeneratedPages, t as buildSiteManifest } from "./chunks/site-DR_X2rzc.js";
|
|
2
|
+
import { a as buildGeneratedState, c as collectComposed, i as renderEditablePage, l as loadComposedDefinitions, n as createEditorService, o as buildPageState, t as toNodeMiddleware } from "./chunks/node-adapter-4eD9p0iP.js";
|
|
3
|
+
import { E as pageUrlOf, W as wasRecentlyMutated } from "./chunks/rich-text-codec--Nssj0Nn.js";
|
|
4
|
+
import { t as BLOCKS_MANIFEST_FILE } from "./chunks/page-assets-DsJXmoDs.js";
|
|
5
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
6
|
+
import { join, relative } from "node:path";
|
|
4
7
|
import { parseVueRequest } from "@vitejs/plugin-vue";
|
|
5
|
-
import { areFieldSchemasRegistered,
|
|
8
|
+
import { areFieldSchemasRegistered, normalizeLocales, registerFieldSchemas, serializeState } from "mechanica-shared";
|
|
6
9
|
import { babelParse, parse as parse$1 } from "@vue/compiler-sfc";
|
|
7
10
|
import { walk } from "estree-walker";
|
|
8
11
|
import MagicString from "magic-string";
|
|
9
|
-
import { parseComposedBlock, serializeComposedBlock } from "mechanica-shared/block-format";
|
|
10
|
-
import { createHash } from "node:crypto";
|
|
11
12
|
import { promises } from "fs";
|
|
12
13
|
import path from "path";
|
|
13
|
-
//#region src/vite/generate-pages.ts
|
|
14
|
-
/** Run every provider's `list` once and flatten the results. */
|
|
15
|
-
async function collectGeneratedPages(providers, ctx) {
|
|
16
|
-
if (!providers?.length) return [];
|
|
17
|
-
return (await Promise.all(providers.map((p) => (typeof p === "function" ? p : p.list)(ctx)))).flat();
|
|
18
|
-
}
|
|
19
|
-
/** The served (locale-prefixed) URL a generated page renders at. */
|
|
20
|
-
function generatedServedPath(page, config) {
|
|
21
|
-
if (!config || !page.locale || page.locale === config.default) return page.path;
|
|
22
|
-
return localePath(page.path, page.locale, config);
|
|
23
|
-
}
|
|
24
|
-
//#endregion
|
|
25
14
|
//#region src/compiler/compile-block.ts
|
|
26
15
|
/**
|
|
27
16
|
* The macro name authors call inside a block's `<script setup>`.
|
|
@@ -607,41 +596,6 @@ async function collectWidgets(widgetsDir, resolve) {
|
|
|
607
596
|
].join("\n");
|
|
608
597
|
}
|
|
609
598
|
//#endregion
|
|
610
|
-
//#region src/vite/collect-composed.ts
|
|
611
|
-
/** Filename suffix for composed-block documents under `<mech>/blocks`. */
|
|
612
|
-
var COMPOSED_EXT = ".block.yml";
|
|
613
|
-
/** List `*.block.yml` files directly under `dir`, in stable (sorted) order. */
|
|
614
|
-
function listComposedFiles(dir) {
|
|
615
|
-
try {
|
|
616
|
-
return readdirSync(dir).filter((name) => name.endsWith(COMPOSED_EXT)).sort().map((name) => join(dir, name));
|
|
617
|
-
} catch {
|
|
618
|
-
return [];
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* Read and parse every composed-block definition under `dir`
|
|
623
|
-
* (`<mech>/blocks`). A malformed file is skipped (reported via `onError`) so one
|
|
624
|
-
* bad block never breaks the whole set. The id defaults to the filename base.
|
|
625
|
-
*/
|
|
626
|
-
function loadComposedDefinitions(dir, onError) {
|
|
627
|
-
const defs = [];
|
|
628
|
-
for (const file of listComposedFiles(dir)) try {
|
|
629
|
-
defs.push(parseComposedBlock(readFileSync(file, "utf-8"), basename(file, COMPOSED_EXT)));
|
|
630
|
-
} catch (error) {
|
|
631
|
-
onError?.(file, error);
|
|
632
|
-
}
|
|
633
|
-
return defs;
|
|
634
|
-
}
|
|
635
|
-
/**
|
|
636
|
-
* Generate the `virtual:mechanica/composed` module source: the parsed
|
|
637
|
-
* definitions baked in as a JSON literal (they are data, never imports). Loaded
|
|
638
|
-
* by the client/SSR/preview entries, which register them into the block set.
|
|
639
|
-
*/
|
|
640
|
-
function collectComposed(dir, onError) {
|
|
641
|
-
const defs = loadComposedDefinitions(dir, onError);
|
|
642
|
-
return `export const composedList = ${JSON.stringify(defs)}\n`;
|
|
643
|
-
}
|
|
644
|
-
//#endregion
|
|
645
599
|
//#region src/vite/collect-components.ts
|
|
646
600
|
/**
|
|
647
601
|
* Generate the `virtual:mechanica/components` module — the site's design-system
|
|
@@ -842,548 +796,15 @@ function generateSsrEntry(options) {
|
|
|
842
796
|
].join("\n");
|
|
843
797
|
}
|
|
844
798
|
//#endregion
|
|
845
|
-
//#region src/vite/dev/query-dev.ts
|
|
846
|
-
/**
|
|
847
|
-
* The dev server's {@link QuerySource}: pages come live from the `.mech`
|
|
848
|
-
* store; `useFetch` URLs are fetched server-side (no CORS, matching how the
|
|
849
|
-
* export resolves them at build time). `generated` pages (plugin `generatePages`)
|
|
850
|
-
* are merged into the page listing so `usePages()` sees them, like the export.
|
|
851
|
-
*/
|
|
852
|
-
function devQuerySource(mechDir, generated) {
|
|
853
|
-
return {
|
|
854
|
-
listPages: (options) => listPages(mechDir, {
|
|
855
|
-
...options,
|
|
856
|
-
generated
|
|
857
|
-
}),
|
|
858
|
-
fetchJson: async ({ url, ...init }) => {
|
|
859
|
-
const res = await fetch(url, init);
|
|
860
|
-
if (!res.ok) throw new Error(`${url} responded ${res.status}`);
|
|
861
|
-
return res.json();
|
|
862
|
-
}
|
|
863
|
-
};
|
|
864
|
-
}
|
|
865
|
-
/**
|
|
866
|
-
* Resolve a dev-mode query key against the local `.mech` store. Keys are of the
|
|
867
|
-
* form `"<type>.<json-args>"` (the same encoding the runtime composables use);
|
|
868
|
-
* `context.page` selects the chunk of a paginated query.
|
|
869
|
-
*/
|
|
870
|
-
function resolveDevQuery(mechDir, key, context = {}, generated) {
|
|
871
|
-
return resolveQueryKey(devQuerySource(mechDir, generated), key, context);
|
|
872
|
-
}
|
|
873
|
-
//#endregion
|
|
874
|
-
//#region src/vite/dev/page-state.ts
|
|
875
|
-
/**
|
|
876
|
-
* Recognize a paginated variant URL (`/blog/2`): no page file of its own, a
|
|
877
|
-
* numeric tail ≥ 2, and an existing base page. Returns the base path + number.
|
|
878
|
-
* Checked against the default-locale (base) files — pagination structure is
|
|
879
|
-
* defined by the logical page, and variant URLs never have their own file.
|
|
880
|
-
*/
|
|
881
|
-
function paginatedVariantOf(mechDir, urlPath) {
|
|
882
|
-
const match = urlPath.match(/^(.*)\/(\d+)$/);
|
|
883
|
-
if (!match) return null;
|
|
884
|
-
const page = Number(match[2]);
|
|
885
|
-
if (page < 2) return null;
|
|
886
|
-
if (pageVersion(mechDir, urlPath) != null) return null;
|
|
887
|
-
const basePath = match[1] || "/";
|
|
888
|
-
if (pageVersion(mechDir, basePath) == null) return null;
|
|
889
|
-
return {
|
|
890
|
-
basePath,
|
|
891
|
-
page
|
|
892
|
-
};
|
|
893
|
-
}
|
|
894
|
-
/**
|
|
895
|
-
* The dev state for a page: effective data resolved site < folder < page, plus
|
|
896
|
-
* the scope buckets the editor edits, and the page's on-disk version for
|
|
897
|
-
* optimistic-concurrency saves. Injected as `window.state` on page load and
|
|
898
|
-
* served by `GET /@mechanica/state` when the editor refreshes after an
|
|
899
|
-
* external change.
|
|
900
|
-
*
|
|
901
|
-
* A paginated variant URL (`/blog/2`) serves its base page's state with
|
|
902
|
-
* `page.pagination` set — `page.path` stays the base path, so editing the
|
|
903
|
-
* variant edits (and saves to) the real page.
|
|
904
|
-
*
|
|
905
|
-
* A locale-prefixed URL (`/ru/about`) serves that page's translation: the
|
|
906
|
-
* prefix is stripped to the logical path, `page.locale`/`page.locales` are set,
|
|
907
|
-
* and the version targets the translation file. When no translation exists the
|
|
908
|
-
* default-locale content renders as a fallback (`page.localeFallback`).
|
|
909
|
-
*/
|
|
910
|
-
function buildPageState(mechDir, urlPath, config) {
|
|
911
|
-
const { locale, path: localePathStripped } = parseLocalePath(urlPath, config);
|
|
912
|
-
const variant = paginatedVariantOf(mechDir, localePathStripped);
|
|
913
|
-
const pagePath = variant?.basePath ?? localePathStripped;
|
|
914
|
-
const localeCode = !config || locale === config.default ? void 0 : locale;
|
|
915
|
-
let fallback = false;
|
|
916
|
-
let page = readPage(mechDir, pagePath, localeCode);
|
|
917
|
-
let layout = page.layout;
|
|
918
|
-
if (localeCode) {
|
|
919
|
-
const hasTranslation = pageVersion(mechDir, pagePath, localeCode) != null;
|
|
920
|
-
const hasBase = pageVersion(mechDir, pagePath) != null;
|
|
921
|
-
if (!hasTranslation) {
|
|
922
|
-
page = readPage(mechDir, pagePath);
|
|
923
|
-
fallback = true;
|
|
924
|
-
layout = page.layout;
|
|
925
|
-
} else if (hasBase) {
|
|
926
|
-
const base = readPage(mechDir, pagePath);
|
|
927
|
-
layout = base.layout;
|
|
928
|
-
const merged = mergeTranslation({
|
|
929
|
-
content: base.content ?? [],
|
|
930
|
-
data: base.data ?? {},
|
|
931
|
-
meta: base.meta ?? {}
|
|
932
|
-
}, {
|
|
933
|
-
content: page.content ?? [],
|
|
934
|
-
data: page.data ?? {},
|
|
935
|
-
meta: page.meta ?? {}
|
|
936
|
-
});
|
|
937
|
-
page = {
|
|
938
|
-
...page,
|
|
939
|
-
content: merged.content,
|
|
940
|
-
data: merged.data,
|
|
941
|
-
meta: merged.meta
|
|
942
|
-
};
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
const content = page.content ?? [];
|
|
946
|
-
fillContentDefaults(content);
|
|
947
|
-
fillImageMeta(mechDir, content);
|
|
948
|
-
let baseContent;
|
|
949
|
-
if (localeCode && pageVersion(mechDir, pagePath) != null) {
|
|
950
|
-
const base = readPage(mechDir, pagePath).content ?? [];
|
|
951
|
-
fillContentDefaults(base);
|
|
952
|
-
fillImageMeta(mechDir, base);
|
|
953
|
-
baseContent = base;
|
|
954
|
-
}
|
|
955
|
-
const folder = folderOf(mechDir, pagePath);
|
|
956
|
-
const siteData = readSiteData(mechDir, localeCode);
|
|
957
|
-
const folderData = readFolderData(mechDir, folder, localeCode);
|
|
958
|
-
const pageData = page.data ?? {};
|
|
959
|
-
const pageMeta = {
|
|
960
|
-
path: pagePath,
|
|
961
|
-
meta: page.meta ?? {}
|
|
962
|
-
};
|
|
963
|
-
if (layout) pageMeta.layout = layout;
|
|
964
|
-
if (variant) pageMeta.pagination = { page: variant.page };
|
|
965
|
-
if (config) {
|
|
966
|
-
pageMeta.locale = locale;
|
|
967
|
-
pageMeta.locales = translationsOf(mechDir, pagePath, config);
|
|
968
|
-
if (fallback) pageMeta.localeFallback = true;
|
|
969
|
-
}
|
|
970
|
-
return {
|
|
971
|
-
content,
|
|
972
|
-
data: {
|
|
973
|
-
...siteData,
|
|
974
|
-
...folderData,
|
|
975
|
-
...pageData
|
|
976
|
-
},
|
|
977
|
-
siteData,
|
|
978
|
-
folderData,
|
|
979
|
-
pageData,
|
|
980
|
-
folder,
|
|
981
|
-
page: pageMeta,
|
|
982
|
-
version: pageVersion(mechDir, pagePath, localeCode),
|
|
983
|
-
...config ? { locales: config } : {},
|
|
984
|
-
...baseContent ? { baseContent } : {}
|
|
985
|
-
};
|
|
986
|
-
}
|
|
987
|
-
/**
|
|
988
|
-
* The dev state for a programmatically generated page ({@link VirtualPage}) —
|
|
989
|
-
* the file-free counterpart of {@link buildPageState}. It replicates the same
|
|
990
|
-
* shape (content with block-prop defaults + image meta filled, the
|
|
991
|
-
* site‹folder‹page data merge, and `page.locale`/`page.locales`), but reads its
|
|
992
|
-
* content/data/meta from the baked page rather than a `.page.md`. `version` is
|
|
993
|
-
* null and `generated` is set, so the editor treats it as read-only and never
|
|
994
|
-
* queues a save against a file that doesn't exist.
|
|
995
|
-
*/
|
|
996
|
-
function buildGeneratedState(mechDir, vp, config) {
|
|
997
|
-
const content = vp.content ?? [];
|
|
998
|
-
fillContentDefaults(content);
|
|
999
|
-
fillImageMeta(mechDir, content);
|
|
1000
|
-
const localeCode = !config || !vp.locale || vp.locale === config.default ? void 0 : vp.locale;
|
|
1001
|
-
const folder = folderOf(mechDir, vp.path);
|
|
1002
|
-
const siteData = readSiteData(mechDir, localeCode);
|
|
1003
|
-
const folderData = readFolderData(mechDir, folder, localeCode);
|
|
1004
|
-
const pageData = vp.data ?? {};
|
|
1005
|
-
const pageMeta = {
|
|
1006
|
-
path: vp.path,
|
|
1007
|
-
meta: vp.meta ?? {}
|
|
1008
|
-
};
|
|
1009
|
-
if (vp.layout) pageMeta.layout = vp.layout;
|
|
1010
|
-
if (config) {
|
|
1011
|
-
pageMeta.locale = vp.locale ?? config.default;
|
|
1012
|
-
pageMeta.locales = vp.locales ?? [config.default];
|
|
1013
|
-
}
|
|
1014
|
-
return {
|
|
1015
|
-
content,
|
|
1016
|
-
data: {
|
|
1017
|
-
...siteData,
|
|
1018
|
-
...folderData,
|
|
1019
|
-
...pageData
|
|
1020
|
-
},
|
|
1021
|
-
siteData,
|
|
1022
|
-
folderData,
|
|
1023
|
-
pageData,
|
|
1024
|
-
folder,
|
|
1025
|
-
page: pageMeta,
|
|
1026
|
-
version: null,
|
|
1027
|
-
generated: true,
|
|
1028
|
-
...config ? { locales: config } : {}
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
//#endregion
|
|
1032
|
-
//#region src/vite/dev/composed-store.ts
|
|
1033
|
-
/**
|
|
1034
|
-
* CRUD for composed blocks under `<mech>/blocks/<id>.block.yml`. Mirrors
|
|
1035
|
-
* `pages-store`: atomic writes, own-write marking (so the watcher tells the
|
|
1036
|
-
* composer's own saves from external edits), and content-hash versioning for
|
|
1037
|
-
* optimistic-concurrency saves (a 409 when the file changed under the editor).
|
|
1038
|
-
* See PLAN.md § 5.1.
|
|
1039
|
-
*/
|
|
1040
|
-
/** The directory composed blocks live in. */
|
|
1041
|
-
function composedDirOf(mechDir) {
|
|
1042
|
-
return join(mechDir, "blocks");
|
|
1043
|
-
}
|
|
1044
|
-
var fileOf = (mechDir, id) => join(composedDirOf(mechDir), `${id}${COMPOSED_EXT}`);
|
|
1045
|
-
var hash = (text) => createHash("sha1").update(text).digest("hex").slice(0, 16);
|
|
1046
|
-
/** Thrown by {@link createComposedBlock} when the id is already taken. */
|
|
1047
|
-
var ComposedBlockExistsError = class ComposedBlockExistsError extends Error {
|
|
1048
|
-
id;
|
|
1049
|
-
constructor(id) {
|
|
1050
|
-
super(`Composed block already exists: ${id}`);
|
|
1051
|
-
this.id = id;
|
|
1052
|
-
this.name = "ComposedBlockExistsError";
|
|
1053
|
-
Object.setPrototypeOf(this, ComposedBlockExistsError.prototype);
|
|
1054
|
-
}
|
|
1055
|
-
};
|
|
1056
|
-
/** List every composed block (summaries), skipping malformed files. */
|
|
1057
|
-
function listComposedBlocks(mechDir) {
|
|
1058
|
-
return loadComposedDefinitions(composedDirOf(mechDir)).map((def) => ({
|
|
1059
|
-
id: def.id,
|
|
1060
|
-
name: def.name,
|
|
1061
|
-
icon: def.icon,
|
|
1062
|
-
category: def.category
|
|
1063
|
-
}));
|
|
1064
|
-
}
|
|
1065
|
-
/** Read one composed block plus its on-disk version, or `null` when absent. */
|
|
1066
|
-
function readComposedBlock(mechDir, id) {
|
|
1067
|
-
const file = fileOf(mechDir, id);
|
|
1068
|
-
if (!fs.existsSync(file)) return null;
|
|
1069
|
-
const text = fs.readFileSync(file, "utf-8");
|
|
1070
|
-
return {
|
|
1071
|
-
def: parseComposedBlock(text, id),
|
|
1072
|
-
version: hash(text)
|
|
1073
|
-
};
|
|
1074
|
-
}
|
|
1075
|
-
/** A composed block's current on-disk version (content hash), or `null`. */
|
|
1076
|
-
function composedVersion(mechDir, id) {
|
|
1077
|
-
const file = fileOf(mechDir, id);
|
|
1078
|
-
if (!fs.existsSync(file)) return null;
|
|
1079
|
-
return hash(fs.readFileSync(file, "utf-8"));
|
|
1080
|
-
}
|
|
1081
|
-
var writeDef = (mechDir, id, def) => {
|
|
1082
|
-
const file = fileOf(mechDir, id);
|
|
1083
|
-
writeFileAtomic(file, serializeComposedBlock({
|
|
1084
|
-
...def,
|
|
1085
|
-
id
|
|
1086
|
-
}));
|
|
1087
|
-
return hash(fs.readFileSync(file, "utf-8"));
|
|
1088
|
-
};
|
|
1089
|
-
/** Create a new composed block; throws {@link ComposedBlockExistsError} if taken. */
|
|
1090
|
-
function createComposedBlock(mechDir, def) {
|
|
1091
|
-
if (fs.existsSync(fileOf(mechDir, def.id))) throw new ComposedBlockExistsError(def.id);
|
|
1092
|
-
return { version: writeDef(mechDir, def.id, def) };
|
|
1093
|
-
}
|
|
1094
|
-
/** Overwrite a composed block's definition; returns the new on-disk version. */
|
|
1095
|
-
function saveComposedBlock(mechDir, id, def) {
|
|
1096
|
-
return { version: writeDef(mechDir, id, def) };
|
|
1097
|
-
}
|
|
1098
|
-
/** Delete a composed block. Returns whether it existed. */
|
|
1099
|
-
function deleteComposedBlock(mechDir, id) {
|
|
1100
|
-
const file = fileOf(mechDir, id);
|
|
1101
|
-
if (!fs.existsSync(file)) return false;
|
|
1102
|
-
fs.rmSync(file);
|
|
1103
|
-
markMutated(file);
|
|
1104
|
-
return true;
|
|
1105
|
-
}
|
|
1106
|
-
//#endregion
|
|
1107
799
|
//#region src/vite/dev/middleware.ts
|
|
1108
800
|
/**
|
|
1109
|
-
* The `/@mechanica` dev middleware:
|
|
1110
|
-
*
|
|
801
|
+
* The `/@mechanica` dev middleware: the site's editor API (`src/server` —
|
|
802
|
+
* page CRUD, asset upload/serve, folder list, query resolution) over the local
|
|
803
|
+
* `.mech` store, mounted on Vite's connect stack. Mounted under the
|
|
1111
804
|
* `/@mechanica` prefix, so `req.url` here is already prefix-stripped.
|
|
1112
805
|
*/
|
|
1113
806
|
function createDevMiddleware(mechDir, options = {}) {
|
|
1114
|
-
|
|
1115
|
-
/** Resolve a `locale` query param to a variant code (undefined = base/default). */
|
|
1116
|
-
const variantCode = (raw) => config && raw && raw !== config.default && config.all.includes(raw) ? raw : void 0;
|
|
1117
|
-
return async (req, res, next) => {
|
|
1118
|
-
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1119
|
-
const { pathname } = url;
|
|
1120
|
-
const query = url.searchParams;
|
|
1121
|
-
const json = (data, status = 200) => {
|
|
1122
|
-
res.statusCode = status;
|
|
1123
|
-
res.setHeader("content-type", "application/json");
|
|
1124
|
-
res.end(JSON.stringify(data));
|
|
1125
|
-
};
|
|
1126
|
-
/**
|
|
1127
|
-
* Stream a file from a directory under `.mech`, containing the resolved
|
|
1128
|
-
* path so an encoded `..` (or an absolute path) cannot escape it.
|
|
1129
|
-
*/
|
|
1130
|
-
const serveFrom = (dirName, prefix) => {
|
|
1131
|
-
const dir = resolve(mechDir, dirName);
|
|
1132
|
-
const file = resolve(dir, decodeURIComponent(pathname.slice(prefix.length)));
|
|
1133
|
-
if (file !== dir && !file.startsWith(dir + sep)) {
|
|
1134
|
-
res.statusCode = 403;
|
|
1135
|
-
return res.end("Forbidden");
|
|
1136
|
-
}
|
|
1137
|
-
if (!fs.existsSync(file)) {
|
|
1138
|
-
res.statusCode = 404;
|
|
1139
|
-
return res.end("Not found");
|
|
1140
|
-
}
|
|
1141
|
-
return fs.createReadStream(file).pipe(res);
|
|
1142
|
-
};
|
|
1143
|
-
try {
|
|
1144
|
-
const gen = options.generated ? await options.generated() : null;
|
|
1145
|
-
/** Reject a mutation targeting a file-less generated page. */
|
|
1146
|
-
const blockGenerated = (path) => {
|
|
1147
|
-
if (path && gen?.logical.has(path)) {
|
|
1148
|
-
json({ error: "This page is generated and read-only" }, 409);
|
|
1149
|
-
return true;
|
|
1150
|
-
}
|
|
1151
|
-
return false;
|
|
1152
|
-
};
|
|
1153
|
-
if (pathname.startsWith("/assets/")) return serveFrom("assets", "/assets/");
|
|
1154
|
-
if (pathname.startsWith("/thumbs/")) {
|
|
1155
|
-
res.setHeader("cache-control", "no-cache");
|
|
1156
|
-
return serveFrom("thumbs", "/thumbs/");
|
|
1157
|
-
}
|
|
1158
|
-
if (pathname === "/images" && req.method === "GET") return json(listImages(mechDir));
|
|
1159
|
-
if (pathname === "/folders" && req.method === "GET") return json(listFolders(mechDir));
|
|
1160
|
-
if (pathname === "/query" && req.method === "GET") {
|
|
1161
|
-
const key = query.get("q");
|
|
1162
|
-
if (!key) return json({ error: "Missing query key" }, 400);
|
|
1163
|
-
return json(await resolveDevQuery(mechDir, key, {
|
|
1164
|
-
page: Number(query.get("page") ?? "") || void 0,
|
|
1165
|
-
locale: variantCode(query.get("locale"))
|
|
1166
|
-
}, gen?.pages));
|
|
1167
|
-
}
|
|
1168
|
-
if (pathname === "/upload" && req.method === "POST") {
|
|
1169
|
-
const body = await readBody(req);
|
|
1170
|
-
const header = req.headers["x-file-name"] ?? "file";
|
|
1171
|
-
let name = header;
|
|
1172
|
-
try {
|
|
1173
|
-
name = decodeURIComponent(header);
|
|
1174
|
-
} catch {}
|
|
1175
|
-
if (req.headers["x-derived-asset"]) return json(await saveDerivedAsset(mechDir, name, body));
|
|
1176
|
-
return json(await saveUpload(mechDir, name, body));
|
|
1177
|
-
}
|
|
1178
|
-
if (pathname === "/state" && req.method === "GET") {
|
|
1179
|
-
const pathParam = query.get("path");
|
|
1180
|
-
if (!pathParam) return json({ error: "Missing path" }, 400);
|
|
1181
|
-
await options.ready?.();
|
|
1182
|
-
const generated = gen?.byServed.get(pathParam);
|
|
1183
|
-
if (generated) return json(buildGeneratedState(mechDir, generated, config));
|
|
1184
|
-
return json(buildPageState(mechDir, pathParam, config));
|
|
1185
|
-
}
|
|
1186
|
-
if (pathname === "/pages" && req.method === "GET") return json(listPages(mechDir, {
|
|
1187
|
-
...config ? { locales: config } : {},
|
|
1188
|
-
generated: gen?.pages
|
|
1189
|
-
}));
|
|
1190
|
-
if (pathname === "/blocks" && req.method === "GET") {
|
|
1191
|
-
if (!options.blocks) return json({ error: "Block listing unavailable" }, 503);
|
|
1192
|
-
return json(await options.blocks());
|
|
1193
|
-
}
|
|
1194
|
-
if (pathname === "/pages" && req.method === "DELETE") {
|
|
1195
|
-
const pathParam = query.get("path");
|
|
1196
|
-
if (!pathParam) return json({ error: "Missing path" }, 400);
|
|
1197
|
-
if (blockGenerated(pathParam)) return;
|
|
1198
|
-
return json({ success: deletePage(mechDir, pathParam) });
|
|
1199
|
-
}
|
|
1200
|
-
if (pathname === "/pages/draft" && req.method === "POST") {
|
|
1201
|
-
const pathParam = query.get("path");
|
|
1202
|
-
if (!pathParam) return json({ error: "Missing path" }, 400);
|
|
1203
|
-
if (blockGenerated(pathParam)) return;
|
|
1204
|
-
const body = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1205
|
-
setPageDraft(mechDir, pathParam, body.draft === true, variantCode(query.get("locale")));
|
|
1206
|
-
return json({
|
|
1207
|
-
success: true,
|
|
1208
|
-
draft: body.draft === true
|
|
1209
|
-
});
|
|
1210
|
-
}
|
|
1211
|
-
if (pathname === "/pages/translation" && req.method === "POST") {
|
|
1212
|
-
const pathParam = query.get("path");
|
|
1213
|
-
const locale = query.get("locale");
|
|
1214
|
-
if (!pathParam || !locale) return json({ error: "Missing path or locale" }, 400);
|
|
1215
|
-
if (blockGenerated(pathParam)) return;
|
|
1216
|
-
if (!config || locale === config.default || !config.all.includes(locale)) return json({ error: "Unknown locale" }, 400);
|
|
1217
|
-
try {
|
|
1218
|
-
createTranslation(mechDir, pathParam, locale);
|
|
1219
|
-
return json({ success: true });
|
|
1220
|
-
} catch (error) {
|
|
1221
|
-
if (error instanceof PageExistsError) return json({ error: "Translation already exists" }, 400);
|
|
1222
|
-
throw error;
|
|
1223
|
-
}
|
|
1224
|
-
}
|
|
1225
|
-
if (pathname === "/pages/translation" && req.method === "DELETE") {
|
|
1226
|
-
const pathParam = query.get("path");
|
|
1227
|
-
const locale = query.get("locale");
|
|
1228
|
-
if (!pathParam || !locale) return json({ error: "Missing path or locale" }, 400);
|
|
1229
|
-
if (blockGenerated(pathParam)) return;
|
|
1230
|
-
return json({ success: deleteTranslation(mechDir, pathParam, locale) });
|
|
1231
|
-
}
|
|
1232
|
-
if (pathname === "/pages/duplicate" && req.method === "POST") {
|
|
1233
|
-
const pathParam = query.get("path");
|
|
1234
|
-
if (!pathParam) return json({ error: "Missing path" }, 400);
|
|
1235
|
-
if (blockGenerated(pathParam)) return;
|
|
1236
|
-
const body = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1237
|
-
if (!body.path || !body.name) return json({ error: "path and name are required" }, 400);
|
|
1238
|
-
try {
|
|
1239
|
-
return json(duplicatePage(mechDir, pathParam, body));
|
|
1240
|
-
} catch (error) {
|
|
1241
|
-
if (error instanceof PageExistsError) return json({ error: { path: "Page already exists" } }, 400);
|
|
1242
|
-
throw error;
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
if (pathname === "/pages" && req.method === "POST") {
|
|
1246
|
-
const body = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1247
|
-
const pathParam = query.get("path");
|
|
1248
|
-
if (pathParam) {
|
|
1249
|
-
if (blockGenerated(pathParam)) return;
|
|
1250
|
-
try {
|
|
1251
|
-
const path = typeof body.path === "string" && body.path.trim() && body.path.trim() !== pathParam ? movePage(mechDir, pathParam, body.path).path : pathParam;
|
|
1252
|
-
if (body.name) renamePage(mechDir, path, body.name);
|
|
1253
|
-
return json({
|
|
1254
|
-
success: true,
|
|
1255
|
-
path
|
|
1256
|
-
});
|
|
1257
|
-
} catch (error) {
|
|
1258
|
-
if (error instanceof PageExistsError) return json({ error: { path: "Page already exists" } }, 400);
|
|
1259
|
-
throw error;
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
if (!body.path || !body.name) return json({ error: "path and name are required" }, 400);
|
|
1263
|
-
if (config) {
|
|
1264
|
-
const first = `${typeof body.folderId === "string" ? `${body.folderId}/` : ""}${String(body.path).trim()}`.replace(/^\/+/, "").split("/")[0];
|
|
1265
|
-
if (first && first !== config.default && config.all.includes(first)) return json({ error: { path: `"/${first}" is reserved for the ${first} locale` } }, 400);
|
|
1266
|
-
}
|
|
1267
|
-
try {
|
|
1268
|
-
return json(createPage(mechDir, body));
|
|
1269
|
-
} catch (error) {
|
|
1270
|
-
if (error instanceof PageExistsError) return json({ error: { path: "Page already exists" } }, 400);
|
|
1271
|
-
throw error;
|
|
1272
|
-
}
|
|
1273
|
-
}
|
|
1274
|
-
if (pathname === "/save" && req.method === "POST") {
|
|
1275
|
-
const pathParam = query.get("path");
|
|
1276
|
-
if (!pathParam) return json({ error: "Missing path" }, 400);
|
|
1277
|
-
if (blockGenerated(pathParam)) return;
|
|
1278
|
-
const locale = variantCode(query.get("locale"));
|
|
1279
|
-
const body = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1280
|
-
if (!body.force && typeof body.version === "string") {
|
|
1281
|
-
const current = pageVersion(mechDir, pathParam, locale);
|
|
1282
|
-
if (current != null && current !== body.version) return json({
|
|
1283
|
-
error: "conflict",
|
|
1284
|
-
version: current
|
|
1285
|
-
}, 409);
|
|
1286
|
-
}
|
|
1287
|
-
const folder = folderOf(mechDir, pathParam);
|
|
1288
|
-
const version = savePage(mechDir, pathParam, {
|
|
1289
|
-
content: body.content,
|
|
1290
|
-
data: body.pageData ?? {},
|
|
1291
|
-
layout: body.layout
|
|
1292
|
-
}, locale);
|
|
1293
|
-
const siteI18n = body.siteDataI18n ?? {};
|
|
1294
|
-
const folderI18n = body.folderDataI18n ?? {};
|
|
1295
|
-
if (locale) {
|
|
1296
|
-
mergeSiteData(mechDir, body.siteData ?? {});
|
|
1297
|
-
mergeFolderData(mechDir, folder, body.folderData ?? {});
|
|
1298
|
-
mergeLocaleSiteData(mechDir, locale, siteI18n);
|
|
1299
|
-
mergeLocaleFolderData(mechDir, locale, folder, folderI18n);
|
|
1300
|
-
} else {
|
|
1301
|
-
mergeSiteData(mechDir, {
|
|
1302
|
-
...body.siteData ?? {},
|
|
1303
|
-
...siteI18n
|
|
1304
|
-
});
|
|
1305
|
-
mergeFolderData(mechDir, folder, {
|
|
1306
|
-
...body.folderData ?? {},
|
|
1307
|
-
...folderI18n
|
|
1308
|
-
});
|
|
1309
|
-
}
|
|
1310
|
-
return json({
|
|
1311
|
-
success: true,
|
|
1312
|
-
version
|
|
1313
|
-
});
|
|
1314
|
-
}
|
|
1315
|
-
if (pathname === "/composed" && req.method === "GET") return json(listComposedBlocks(mechDir));
|
|
1316
|
-
if (pathname === "/composed/get" && req.method === "GET") {
|
|
1317
|
-
const id = query.get("id");
|
|
1318
|
-
if (!id || !isValidId(id)) return json({ error: "Missing or invalid id" }, 400);
|
|
1319
|
-
const result = readComposedBlock(mechDir, id);
|
|
1320
|
-
if (!result) return json({ error: "not found" }, 404);
|
|
1321
|
-
return json(result);
|
|
1322
|
-
}
|
|
1323
|
-
if (pathname === "/composed/create" && req.method === "POST") {
|
|
1324
|
-
const def = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1325
|
-
const invalid = validateComposed(def);
|
|
1326
|
-
if (invalid) return json({ error: invalid }, 400);
|
|
1327
|
-
if ((await Promise.resolve().then(() => options.blocks?.()).catch(() => []) ?? []).some((block) => block.id === def.id)) return json({ error: { id: "A block with this id already exists" } }, 400);
|
|
1328
|
-
try {
|
|
1329
|
-
return json({
|
|
1330
|
-
success: true,
|
|
1331
|
-
...createComposedBlock(mechDir, def)
|
|
1332
|
-
});
|
|
1333
|
-
} catch (error) {
|
|
1334
|
-
if (error instanceof ComposedBlockExistsError) return json({ error: { id: "A block with this id already exists" } }, 400);
|
|
1335
|
-
throw error;
|
|
1336
|
-
}
|
|
1337
|
-
}
|
|
1338
|
-
if (pathname === "/composed/save" && req.method === "POST") {
|
|
1339
|
-
const id = query.get("id");
|
|
1340
|
-
if (!id || !isValidId(id)) return json({ error: "Missing or invalid id" }, 400);
|
|
1341
|
-
const body = JSON.parse((await readBody(req)).toString("utf-8"));
|
|
1342
|
-
const invalid = validateComposed(body.def);
|
|
1343
|
-
if (invalid) return json({ error: invalid }, 400);
|
|
1344
|
-
if (!body.force && typeof body.version === "string") {
|
|
1345
|
-
const current = composedVersion(mechDir, id);
|
|
1346
|
-
if (current != null && current !== body.version) return json({
|
|
1347
|
-
error: "conflict",
|
|
1348
|
-
version: current
|
|
1349
|
-
}, 409);
|
|
1350
|
-
}
|
|
1351
|
-
return json({
|
|
1352
|
-
success: true,
|
|
1353
|
-
...saveComposedBlock(mechDir, id, body.def)
|
|
1354
|
-
});
|
|
1355
|
-
}
|
|
1356
|
-
if (pathname === "/composed/delete" && req.method === "POST") {
|
|
1357
|
-
const id = query.get("id");
|
|
1358
|
-
if (!id || !isValidId(id)) return json({ error: "Missing or invalid id" }, 400);
|
|
1359
|
-
return json({ success: deleteComposedBlock(mechDir, id) });
|
|
1360
|
-
}
|
|
1361
|
-
next();
|
|
1362
|
-
} catch (error) {
|
|
1363
|
-
json({ error: String(error) }, 500);
|
|
1364
|
-
}
|
|
1365
|
-
};
|
|
1366
|
-
}
|
|
1367
|
-
function readBody(req) {
|
|
1368
|
-
return new Promise((resolve, reject) => {
|
|
1369
|
-
const chunks = [];
|
|
1370
|
-
req.on("data", (chunk) => chunks.push(chunk));
|
|
1371
|
-
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
1372
|
-
req.on("error", reject);
|
|
1373
|
-
});
|
|
1374
|
-
}
|
|
1375
|
-
/** A safe composed-block id — a filename component, never a path (no traversal). */
|
|
1376
|
-
function isValidId(id) {
|
|
1377
|
-
return /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(id);
|
|
1378
|
-
}
|
|
1379
|
-
/** Validate an incoming composed-block definition; returns a field-error map or null. */
|
|
1380
|
-
function validateComposed(def) {
|
|
1381
|
-
if (!def || typeof def !== "object") return { def: "Invalid definition" };
|
|
1382
|
-
const d = def;
|
|
1383
|
-
if (typeof d.id !== "string" || !isValidId(d.id)) return { id: "A valid id is required" };
|
|
1384
|
-
if (typeof d.name !== "string" || d.name === "") return { name: "A name is required" };
|
|
1385
|
-
if (d.template !== void 0 && !Array.isArray(d.template)) return { template: "template must be a list" };
|
|
1386
|
-
return null;
|
|
807
|
+
return toNodeMiddleware(createEditorService(mechDir, options));
|
|
1387
808
|
}
|
|
1388
809
|
//#endregion
|
|
1389
810
|
//#region src/vite/dev/preview.ts
|
|
@@ -1554,6 +975,7 @@ function mechanica(options = {}) {
|
|
|
1554
975
|
let isDev = false;
|
|
1555
976
|
let locales = null;
|
|
1556
977
|
let isClientBuild = false;
|
|
978
|
+
let isEditorBuild = false;
|
|
1557
979
|
let lazyBlockFiles = null;
|
|
1558
980
|
let generatedPagesCache = null;
|
|
1559
981
|
const loadGeneratedPages = () => {
|
|
@@ -1569,19 +991,12 @@ function mechanica(options = {}) {
|
|
|
1569
991
|
};
|
|
1570
992
|
let generatedIndexCache = null;
|
|
1571
993
|
const loadGeneratedIndex = () => {
|
|
1572
|
-
if (!generatedIndexCache) generatedIndexCache = loadGeneratedPages().then((pages) => {
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
}
|
|
1579
|
-
return {
|
|
1580
|
-
pages,
|
|
1581
|
-
byServed,
|
|
1582
|
-
logical
|
|
1583
|
-
};
|
|
1584
|
-
});
|
|
994
|
+
if (!generatedIndexCache) generatedIndexCache = loadGeneratedPages().then((pages) => indexGeneratedPages({
|
|
995
|
+
format: 1,
|
|
996
|
+
blocks: [],
|
|
997
|
+
locales,
|
|
998
|
+
generated: pages
|
|
999
|
+
}));
|
|
1585
1000
|
return generatedIndexCache;
|
|
1586
1001
|
};
|
|
1587
1002
|
const blockSchemas = /* @__PURE__ */ new Map();
|
|
@@ -1640,24 +1055,43 @@ function mechanica(options = {}) {
|
|
|
1640
1055
|
const isBlockFile = (file) => file.endsWith(".vue") && slash(file).startsWith(slash(blocksDir) + "/");
|
|
1641
1056
|
const isWidgetFile = (file) => /\.(ts|js|mts|mjs)$/.test(file) && slash(file).startsWith(slash(widgetsDir) + "/");
|
|
1642
1057
|
const isComposedFile = (file) => file.endsWith(".block.yml") && slash(file).startsWith(slash(composedDir) + "/");
|
|
1643
|
-
let
|
|
1644
|
-
const
|
|
1645
|
-
if (!
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1058
|
+
let siteReady = null;
|
|
1059
|
+
const loadSite = (server) => {
|
|
1060
|
+
if (!siteReady) {
|
|
1061
|
+
const attempt = Promise.all([server.ssrLoadModule(BLOCKS_MODULE_ID), loadGeneratedPages()]).then(([mod, generated]) => {
|
|
1062
|
+
const composed = loadComposedDefinitions(composedDir, (file, error) => server.config.logger.warn(`[mechanica] skipped ${slash(file)}: ${error}`));
|
|
1063
|
+
const manifest = buildSiteManifest({
|
|
1064
|
+
components: mod.blocksList ?? [],
|
|
1065
|
+
composed,
|
|
1066
|
+
site: {
|
|
1067
|
+
url: options.siteUrl,
|
|
1068
|
+
name: options.siteName
|
|
1069
|
+
},
|
|
1070
|
+
locales,
|
|
1071
|
+
generated
|
|
1072
|
+
});
|
|
1073
|
+
configureSite(mechDir, manifest);
|
|
1074
|
+
return manifest;
|
|
1075
|
+
}).catch((error) => {
|
|
1076
|
+
server.config.logger.warn(`[mechanica] block schemas unavailable: ${error}`);
|
|
1077
|
+
if (siteReady === attempt) siteReady = null;
|
|
1078
|
+
return {
|
|
1079
|
+
format: 1,
|
|
1080
|
+
blocks: [],
|
|
1081
|
+
locales,
|
|
1082
|
+
generated: []
|
|
1083
|
+
};
|
|
1084
|
+
});
|
|
1085
|
+
siteReady = attempt;
|
|
1086
|
+
}
|
|
1087
|
+
return siteReady;
|
|
1654
1088
|
};
|
|
1655
1089
|
const invalidateBlocks = (server) => {
|
|
1656
|
-
|
|
1090
|
+
siteReady = null;
|
|
1657
1091
|
const mod = server.moduleGraph.getModuleById(RESOLVED_BLOCKS_ID);
|
|
1658
1092
|
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
1659
1093
|
server.ws.send({ type: "full-reload" });
|
|
1660
|
-
|
|
1094
|
+
loadSite(server);
|
|
1661
1095
|
};
|
|
1662
1096
|
const invalidateWidgets = (server) => {
|
|
1663
1097
|
const mod = server.moduleGraph.getModuleById(RESOLVED_WIDGETS_ID);
|
|
@@ -1665,11 +1099,11 @@ function mechanica(options = {}) {
|
|
|
1665
1099
|
server.ws.send({ type: "full-reload" });
|
|
1666
1100
|
};
|
|
1667
1101
|
const invalidateComposed = (server) => {
|
|
1668
|
-
|
|
1102
|
+
siteReady = null;
|
|
1669
1103
|
const mod = server.moduleGraph.getModuleById(RESOLVED_COMPOSED_ID);
|
|
1670
1104
|
if (mod) server.moduleGraph.invalidateModule(mod);
|
|
1671
1105
|
server.ws.send({ type: "full-reload" });
|
|
1672
|
-
|
|
1106
|
+
loadSite(server);
|
|
1673
1107
|
};
|
|
1674
1108
|
const invalidateManifest = (server) => {
|
|
1675
1109
|
for (const id of [
|
|
@@ -1687,6 +1121,7 @@ function mechanica(options = {}) {
|
|
|
1687
1121
|
enforce: "pre",
|
|
1688
1122
|
config(_config, env) {
|
|
1689
1123
|
if (env.command !== "build" || env.isSsrBuild) return;
|
|
1124
|
+
if (process.env.MECHANICA_EDITOR_BUILD) return;
|
|
1690
1125
|
return { build: { rollupOptions: { output: { codeSplitting: {
|
|
1691
1126
|
includeDependenciesRecursively: false,
|
|
1692
1127
|
groups: [{
|
|
@@ -1713,7 +1148,8 @@ function mechanica(options = {}) {
|
|
|
1713
1148
|
root = config.root;
|
|
1714
1149
|
locales = normalizeLocales(options.locales);
|
|
1715
1150
|
isDev = config.command === "serve";
|
|
1716
|
-
|
|
1151
|
+
isEditorBuild = config.command === "build" && !config.build?.ssr && !!process.env.MECHANICA_EDITOR_BUILD;
|
|
1152
|
+
isClientBuild = config.command === "build" && !config.build?.ssr && !isEditorBuild;
|
|
1717
1153
|
const vueApi = (config.plugins?.find((plugin) => plugin.name === "vite:vue"))?.api;
|
|
1718
1154
|
if (vueApi?.options && !vueApi.options.features?.componentIdGenerator) vueApi.options = {
|
|
1719
1155
|
...vueApi.options,
|
|
@@ -1763,7 +1199,7 @@ function mechanica(options = {}) {
|
|
|
1763
1199
|
if (id === RESOLVED_CLIENT_ID) return generateClientEntry({
|
|
1764
1200
|
userEntry,
|
|
1765
1201
|
mount,
|
|
1766
|
-
mode: isDev ? "dev" : "client",
|
|
1202
|
+
mode: isDev || isEditorBuild ? "dev" : "client",
|
|
1767
1203
|
lazy: isClientBuild
|
|
1768
1204
|
});
|
|
1769
1205
|
if (id === RESOLVED_SSR_ID) return generateSsrEntry({
|
|
@@ -1806,29 +1242,9 @@ function mechanica(options = {}) {
|
|
|
1806
1242
|
configureServer(server) {
|
|
1807
1243
|
server.middlewares.use("/@mechanica/preview", createPreviewMiddleware());
|
|
1808
1244
|
server.middlewares.use("/@mechanica/composer", createComposerMiddleware());
|
|
1809
|
-
server.middlewares.use("/@mechanica", createDevMiddleware(mechDir, {
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
ready: () => ensurePageCodec(server),
|
|
1813
|
-
blocks: async () => {
|
|
1814
|
-
const compiled = ((await server.ssrLoadModule("virtual:mechanica/blocks")).blocksList ?? []).map((component) => {
|
|
1815
|
-
const meta = toBlockMeta(component);
|
|
1816
|
-
return {
|
|
1817
|
-
id: meta.id,
|
|
1818
|
-
name: meta.name,
|
|
1819
|
-
hidden: meta.hidden
|
|
1820
|
-
};
|
|
1821
|
-
});
|
|
1822
|
-
const composed = loadComposedDefinitions(composedDir).map((def) => ({
|
|
1823
|
-
id: def.id,
|
|
1824
|
-
name: def.name,
|
|
1825
|
-
hidden: def.hidden
|
|
1826
|
-
}));
|
|
1827
|
-
return [...compiled, ...composed];
|
|
1828
|
-
}
|
|
1829
|
-
}));
|
|
1830
|
-
if (server.httpServer && !server.httpServer.listening) server.httpServer.once("listening", () => void ensurePageCodec(server));
|
|
1831
|
-
else ensurePageCodec(server);
|
|
1245
|
+
server.middlewares.use("/@mechanica", createDevMiddleware(mechDir, { site: () => loadSite(server) }));
|
|
1246
|
+
if (server.httpServer && !server.httpServer.listening) server.httpServer.once("listening", () => void loadSite(server));
|
|
1247
|
+
else loadSite(server);
|
|
1832
1248
|
const isComposerFile = (file) => slash(file) === slash(composerFilePath);
|
|
1833
1249
|
server.watcher.on("add", (file) => {
|
|
1834
1250
|
if (isBlockFile(file)) invalidateBlocks(server);
|
|
@@ -1891,31 +1307,28 @@ function mechanica(options = {}) {
|
|
|
1891
1307
|
order: "pre",
|
|
1892
1308
|
async handler(html, ctx) {
|
|
1893
1309
|
if (!isDev) {
|
|
1894
|
-
const clientScript = `<script type="module"
|
|
1310
|
+
const clientScript = `<script type="module">${isEditorBuild ? `import ${JSON.stringify(CLIENT_MODULE_ID)}\nimport 'mechanica/editor'\n` : `import ${JSON.stringify(CLIENT_MODULE_ID)}`}<\/script>`;
|
|
1895
1311
|
return html.replace("</body>", `${clientScript}\n</body>`);
|
|
1896
1312
|
}
|
|
1897
1313
|
const url = new URL(ctx.originalUrl ?? "/", "http://localhost");
|
|
1898
1314
|
const urlPath = url.pathname;
|
|
1899
1315
|
if (/\.\w+$/.test(urlPath)) return html;
|
|
1900
1316
|
const withEditor = !url.searchParams.has("mechanica-shot");
|
|
1901
|
-
if (ctx.server) await
|
|
1317
|
+
if (ctx.server) await loadSite(ctx.server);
|
|
1902
1318
|
const generated = (await loadGeneratedIndex()).byServed.get(urlPath);
|
|
1903
1319
|
const state = generated ? buildGeneratedState(mechDir, generated, locales) : buildPageState(mechDir, urlPath, locales);
|
|
1904
|
-
|
|
1905
|
-
`<script>window.state=${serializeState(state)}<\/script>`,
|
|
1906
|
-
`<script type="module">`,
|
|
1907
|
-
`import ${JSON.stringify(CLIENT_MODULE_ID)}`,
|
|
1908
|
-
...withEditor ? [`import 'mechanica/editor'`] : [],
|
|
1909
|
-
`<\/script>`
|
|
1910
|
-
].join("\n");
|
|
1911
|
-
return passDataToHTML(html, {
|
|
1912
|
-
...state.data,
|
|
1320
|
+
return renderEditablePage(html, state, {
|
|
1913
1321
|
site: {
|
|
1914
1322
|
url: options.siteUrl,
|
|
1915
1323
|
name: options.siteName
|
|
1916
1324
|
},
|
|
1917
|
-
|
|
1918
|
-
|
|
1325
|
+
scripts: [
|
|
1326
|
+
`<script type="module">`,
|
|
1327
|
+
`import ${JSON.stringify(CLIENT_MODULE_ID)}`,
|
|
1328
|
+
...withEditor ? [`import 'mechanica/editor'`] : [],
|
|
1329
|
+
`<\/script>`
|
|
1330
|
+
].join("\n")
|
|
1331
|
+
});
|
|
1919
1332
|
}
|
|
1920
1333
|
}
|
|
1921
1334
|
};
|