@nulib/canopy 0.0.0 → 2.0.1
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/bin/canopy.js +16 -0
- package/lib/AGENTS.md +107 -0
- package/lib/base-path.js +67 -0
- package/lib/build/appearance.js +76 -0
- package/lib/build/assets.js +30 -0
- package/lib/build/build.js +350 -0
- package/lib/build/dev.js +1355 -0
- package/lib/build/devtoast.config.json +6 -0
- package/lib/build/devtoast.css +14 -0
- package/lib/build/facets.js +19 -0
- package/lib/build/fonts.js +105 -0
- package/lib/build/iiif.js +2990 -0
- package/lib/build/log.js +31 -0
- package/lib/build/mdx.js +1967 -0
- package/lib/build/package-names.js +111 -0
- package/lib/build/pages.js +420 -0
- package/lib/build/rehype-task-list-labels.js +54 -0
- package/lib/build/runtimes.js +141 -0
- package/lib/build/search-index.js +55 -0
- package/lib/build/search-text.js +160 -0
- package/lib/build/search-workflow.js +72 -0
- package/lib/build/search.js +302 -0
- package/lib/build/sitemap.js +197 -0
- package/lib/build/styles.js +140 -0
- package/lib/build/theme-tokens.js +78 -0
- package/lib/build/ui-styles.js +25 -0
- package/lib/build/upgrade-notices.js +121 -0
- package/lib/cli.js +64 -0
- package/lib/common.js +580 -0
- package/lib/components/bibliography.js +197 -0
- package/lib/components/featured.js +237 -0
- package/lib/components/hero-slider-runtime.js +215 -0
- package/lib/components/image-story-runtime-entry.js +249 -0
- package/lib/components/map-runtime.js +114 -0
- package/lib/components/metadata-index.js +32 -0
- package/lib/components/nav-place.js +227 -0
- package/lib/components/navigation.js +381 -0
- package/lib/components/referenced.js +217 -0
- package/lib/components/slider-runtime-entry.js +106 -0
- package/lib/components/timeline-runtime.js +80 -0
- package/lib/components/viewer-runtime-entry.js +88 -0
- package/lib/config-path.js +78 -0
- package/lib/default-locale.js +113 -0
- package/lib/discovery/browser-loader.js +107 -0
- package/lib/discovery/browser.js +115 -0
- package/lib/discovery/config.js +25 -0
- package/lib/discovery/envelope.js +124 -0
- package/lib/discovery/export.js +226 -0
- package/lib/discovery/ingestion.js +62 -0
- package/lib/discovery/pagination.js +66 -0
- package/lib/discovery/provenance.js +79 -0
- package/lib/discovery/search.js +81 -0
- package/lib/discovery/tools.js +155 -0
- package/lib/discovery/validation.js +121 -0
- package/lib/head.js +154 -0
- package/lib/iiif/thumbnail.js +402 -0
- package/lib/index.js +9 -0
- package/lib/locale-runtime.js +69 -0
- package/lib/locales.js +203 -0
- package/lib/orchestrator.js +231 -0
- package/lib/page-context.js +24 -0
- package/lib/search/bundle.js +25 -0
- package/lib/search/data.js +202 -0
- package/lib/search/engine.js +86 -0
- package/lib/search/index-cache.js +95 -0
- package/lib/search/search-app.jsx +835 -0
- package/lib/search/search-engine-runtime.js +44 -0
- package/lib/search/search-form-runtime.js +462 -0
- package/lib/search/search.js +676 -0
- package/package.json +109 -3
- package/types/base-path.d.ts +4 -0
- package/types/orchestrator.d.ts +17 -0
- package/ui/dist/index.mjs +7358 -0
- package/ui/dist/index.mjs.map +7 -0
- package/ui/dist/server.mjs +12731 -0
- package/ui/dist/server.mjs.map +7 -0
- package/ui/fonts/OFL.txt +98 -0
- package/ui/fonts/google-sans-flex-latin-ext.woff2 +0 -0
- package/ui/fonts/google-sans-flex-latin.woff2 +0 -0
- package/ui/fonts/source-serif-4-italic-latin-ext.woff2 +0 -0
- package/ui/fonts/source-serif-4-italic-latin.woff2 +0 -0
- package/ui/fonts/source-serif-4-latin-ext.woff2 +0 -0
- package/ui/fonts/source-serif-4-latin.woff2 +0 -0
- package/ui/styles/base/_common.scss +97 -0
- package/ui/styles/base/_heading.scss +61 -0
- package/ui/styles/base/_markdown.scss +188 -0
- package/ui/styles/base/_type.scss +51 -0
- package/ui/styles/base/_utilities.scss +7 -0
- package/ui/styles/base/index.scss +5 -0
- package/ui/styles/components/_article-card.scss +108 -0
- package/ui/styles/components/_band.scss +104 -0
- package/ui/styles/components/_bibliography.scss +88 -0
- package/ui/styles/components/_buttons.scss +143 -0
- package/ui/styles/components/_card.scss +109 -0
- package/ui/styles/components/_diagram.scss +76 -0
- package/ui/styles/components/_feature.scss +66 -0
- package/ui/styles/components/_footer.scss +136 -0
- package/ui/styles/components/_gallery.scss +476 -0
- package/ui/styles/components/_image-story.scss +56 -0
- package/ui/styles/components/_interstitial-hero.scss +625 -0
- package/ui/styles/components/_layout.scss +83 -0
- package/ui/styles/components/_map.scss +296 -0
- package/ui/styles/components/_metadata-index.scss +68 -0
- package/ui/styles/components/_nav-tree.scss +80 -0
- package/ui/styles/components/_referenced-items.scss +69 -0
- package/ui/styles/components/_sub-navigation.scss +208 -0
- package/ui/styles/components/_swoosh.scss +50 -0
- package/ui/styles/components/_timeline.scss +350 -0
- package/ui/styles/components/_work.scss +71 -0
- package/ui/styles/components/header/_header.scss +294 -0
- package/ui/styles/components/header/_logo.scss +99 -0
- package/ui/styles/components/header/_navbar.scss +143 -0
- package/ui/styles/components/header/index.scss +3 -0
- package/ui/styles/components/iiif/_image.scss +32 -0
- package/ui/styles/components/iiif/_slider.scss +5 -0
- package/ui/styles/components/iiif/index.scss +2 -0
- package/ui/styles/components/index.scss +25 -0
- package/ui/styles/components/modal/_modal.scss +130 -0
- package/ui/styles/components/modal/index.scss +1 -0
- package/ui/styles/components/search/_filters.scss +259 -0
- package/ui/styles/components/search/_form.scss +187 -0
- package/ui/styles/components/search/_panel.scss +7 -0
- package/ui/styles/components/search/_results.scss +241 -0
- package/ui/styles/components/search/_tabs.scss +60 -0
- package/ui/styles/components/search/index.scss +4 -0
- package/ui/styles/index.css +5007 -0
- package/ui/styles/index.scss +11 -0
- package/ui/styles/settings/_breakpoints.scss +7 -0
- package/ui/styles/settings/_focus.scss +15 -0
- package/ui/styles/settings/_tokens.scss +170 -0
- package/ui/styles/settings/_type.scss +126 -0
- package/ui/styles/version-parity.css +116 -0
- package/ui/tailwind-canopy-iiif-plugin.js +39 -0
- package/ui/tailwind-canopy-iiif-preset.js +32 -0
- package/ui/tailwind-config.d.ts +29 -0
- package/ui/tailwind-config.js +159 -0
- package/ui/tailwind-default.config.mjs +4 -0
- package/ui/theme-color.js +130 -0
- package/ui/theme-palette.js +337 -0
- package/ui/theme.js +153 -0
- package/README.md +0 -3
package/lib/build/mdx.js
ADDED
|
@@ -0,0 +1,1967 @@
|
|
|
1
|
+
const React = require("react");
|
|
2
|
+
const ReactDOMServer = require("react-dom/server");
|
|
3
|
+
const {pathToFileURL} = require("url");
|
|
4
|
+
const crypto = require("crypto");
|
|
5
|
+
const {
|
|
6
|
+
fs,
|
|
7
|
+
fsp,
|
|
8
|
+
path,
|
|
9
|
+
CONTENT_DIR,
|
|
10
|
+
OUT_DIR,
|
|
11
|
+
CACHE_DIR,
|
|
12
|
+
ensureDirSync,
|
|
13
|
+
withBase,
|
|
14
|
+
readSiteMetadata,
|
|
15
|
+
readPrimaryNavigation,
|
|
16
|
+
getLocaleRouteConfig,
|
|
17
|
+
getDefaultLocaleCode,
|
|
18
|
+
} = require("../common");
|
|
19
|
+
const globalRoot = typeof globalThis !== "undefined" ? globalThis : global;
|
|
20
|
+
if (globalRoot && typeof globalRoot.__canopyRequire !== "function") {
|
|
21
|
+
globalRoot.__canopyRequire = typeof require === "function" ? require : null;
|
|
22
|
+
}
|
|
23
|
+
const {readCanopyLocalesWithMessages, readLocaleMessages} = require("../locales");
|
|
24
|
+
|
|
25
|
+
function getSiteLanguageToggle() {
|
|
26
|
+
try {
|
|
27
|
+
const data = readCanopyLocalesWithMessages();
|
|
28
|
+
if (
|
|
29
|
+
data &&
|
|
30
|
+
Array.isArray(data.locales) &&
|
|
31
|
+
data.locales.length
|
|
32
|
+
) {
|
|
33
|
+
return {
|
|
34
|
+
locales: data.locales,
|
|
35
|
+
messages: data.messages || {},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
} catch (_) {}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const rehypeTaskListLabels = require("./rehype-task-list-labels");
|
|
42
|
+
let remarkGfm = null;
|
|
43
|
+
try {
|
|
44
|
+
const mod = require("remark-gfm");
|
|
45
|
+
const plugin = mod && (typeof mod === "function" ? mod : mod.default);
|
|
46
|
+
remarkGfm = typeof plugin === "function" ? plugin : null;
|
|
47
|
+
} catch (_) {
|
|
48
|
+
remarkGfm = null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const EXTRA_REMARK_PLUGINS = (() => {
|
|
52
|
+
try {
|
|
53
|
+
const absPath = path.resolve(
|
|
54
|
+
process.cwd(),
|
|
55
|
+
"packages/helpers/docs/remark-code-meta.js"
|
|
56
|
+
);
|
|
57
|
+
if (fs.existsSync(absPath)) {
|
|
58
|
+
const plugin = require(absPath);
|
|
59
|
+
if (typeof plugin === "function") return [plugin];
|
|
60
|
+
}
|
|
61
|
+
} catch (_) {}
|
|
62
|
+
return [];
|
|
63
|
+
})();
|
|
64
|
+
|
|
65
|
+
function buildCompileOptions(overrides = {}) {
|
|
66
|
+
const base = {
|
|
67
|
+
jsx: false,
|
|
68
|
+
development: false,
|
|
69
|
+
providerImportSource: "@mdx-js/react",
|
|
70
|
+
jsxImportSource: "react",
|
|
71
|
+
format: "mdx",
|
|
72
|
+
};
|
|
73
|
+
const remarkPlugins = [];
|
|
74
|
+
if (remarkGfm) {
|
|
75
|
+
remarkPlugins.push(remarkGfm);
|
|
76
|
+
}
|
|
77
|
+
if (overrides && Array.isArray(overrides.remarkPlugins)) {
|
|
78
|
+
remarkPlugins.push(...overrides.remarkPlugins);
|
|
79
|
+
}
|
|
80
|
+
if (EXTRA_REMARK_PLUGINS.length) {
|
|
81
|
+
remarkPlugins.push(...EXTRA_REMARK_PLUGINS);
|
|
82
|
+
}
|
|
83
|
+
if (remarkPlugins.length) {
|
|
84
|
+
base.remarkPlugins = remarkPlugins;
|
|
85
|
+
}
|
|
86
|
+
// Names Markdown task lists' checkboxes (WCAG 4.1.2; ACCESSIBILITY.md C15).
|
|
87
|
+
base.rehypePlugins = [rehypeTaskListLabels];
|
|
88
|
+
if (overrides && Array.isArray(overrides.rehypePlugins)) {
|
|
89
|
+
base.rehypePlugins.push(...overrides.rehypePlugins);
|
|
90
|
+
}
|
|
91
|
+
// The page's imports of this package, by either name; `server: true` for a page that
|
|
92
|
+
// renders on the server, where its UI imports take the SSR-safe entry (`ui/server`).
|
|
93
|
+
base.recmaPlugins = [
|
|
94
|
+
[recmaPackageImports, {server: Boolean(overrides && overrides.server)}],
|
|
95
|
+
];
|
|
96
|
+
if (overrides && Array.isArray(overrides.recmaPlugins)) {
|
|
97
|
+
base.recmaPlugins.push(...overrides.recmaPlugins);
|
|
98
|
+
}
|
|
99
|
+
if (overrides && typeof overrides === "object") {
|
|
100
|
+
const {
|
|
101
|
+
remarkPlugins: _omit,
|
|
102
|
+
rehypePlugins: _omitRehype,
|
|
103
|
+
recmaPlugins: _omitRecma,
|
|
104
|
+
server: _omitServer,
|
|
105
|
+
...rest
|
|
106
|
+
} = overrides;
|
|
107
|
+
Object.assign(base, rest);
|
|
108
|
+
}
|
|
109
|
+
return base;
|
|
110
|
+
}
|
|
111
|
+
const yaml = require("js-yaml");
|
|
112
|
+
const {getPageContext} = require("../page-context");
|
|
113
|
+
|
|
114
|
+
// An import of this package by its name or its 1.x name (`@canopy-iiif/app`), read as
|
|
115
|
+
// this package wherever a site's code is compiled or bundled (`package-names.js`).
|
|
116
|
+
const {
|
|
117
|
+
PACKAGE_NAME,
|
|
118
|
+
recmaPackageImports,
|
|
119
|
+
esbuildPackageNames,
|
|
120
|
+
esbuildServerPackageNames,
|
|
121
|
+
} = require("./package-names");
|
|
122
|
+
|
|
123
|
+
function parseFrontmatter(src) {
|
|
124
|
+
let input = String(src || "");
|
|
125
|
+
// Strip UTF-8 BOM if present
|
|
126
|
+
if (input.charCodeAt(0) === 0xfeff) input = input.slice(1);
|
|
127
|
+
// Allow a few leading blank lines before frontmatter
|
|
128
|
+
const m = input.match(/^(?:\s*\r?\n)*---\s*\r?\n([\s\S]*?)\r?\n---\s*\r?\n?/);
|
|
129
|
+
if (!m) return {data: null, content: input};
|
|
130
|
+
let data = null;
|
|
131
|
+
try {
|
|
132
|
+
data = yaml.load(m[1]) || null;
|
|
133
|
+
} catch (_) {
|
|
134
|
+
data = null;
|
|
135
|
+
}
|
|
136
|
+
const content = input.slice(m[0].length);
|
|
137
|
+
return {data, content};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ESM-only in v3; load dynamically from CJS
|
|
141
|
+
let MDXProviderCached = null;
|
|
142
|
+
async function getMdxProvider() {
|
|
143
|
+
if (MDXProviderCached) return MDXProviderCached;
|
|
144
|
+
try {
|
|
145
|
+
const mod = await import("@mdx-js/react");
|
|
146
|
+
MDXProviderCached = mod.MDXProvider || mod.default;
|
|
147
|
+
} catch (_) {
|
|
148
|
+
MDXProviderCached = null;
|
|
149
|
+
}
|
|
150
|
+
return MDXProviderCached;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Lazily load UI components from the workspace package and cache them.
|
|
154
|
+
// Re-import when the built UI server bundle changes on disk.
|
|
155
|
+
let UI_COMPONENTS = null;
|
|
156
|
+
let UI_COMPONENTS_PATH = "";
|
|
157
|
+
let UI_COMPONENTS_MTIME = 0;
|
|
158
|
+
let MERGED_UI_COMPONENTS = null;
|
|
159
|
+
let MERGED_UI_KEY = "";
|
|
160
|
+
const DEBUG =
|
|
161
|
+
process.env.CANOPY_DEBUG === "1" || process.env.CANOPY_DEBUG === "true";
|
|
162
|
+
const APP_COMPONENTS_DIR = path.join(process.cwd(), "app", "components");
|
|
163
|
+
const CUSTOM_COMPONENT_ENTRY_CANDIDATES = [
|
|
164
|
+
"mdx.tsx",
|
|
165
|
+
"mdx.ts",
|
|
166
|
+
"mdx.mts",
|
|
167
|
+
"mdx.cts",
|
|
168
|
+
"mdx.jsx",
|
|
169
|
+
"mdx.js",
|
|
170
|
+
"mdx.mjs",
|
|
171
|
+
"mdx.cjs",
|
|
172
|
+
"mdx-components.tsx",
|
|
173
|
+
"mdx-components.ts",
|
|
174
|
+
"mdx-components.mts",
|
|
175
|
+
"mdx-components.cts",
|
|
176
|
+
"mdx-components.jsx",
|
|
177
|
+
"mdx-components.js",
|
|
178
|
+
"mdx-components.mjs",
|
|
179
|
+
"mdx-components.cjs",
|
|
180
|
+
];
|
|
181
|
+
const CUSTOM_COMPONENT_EXTENSIONS = new Set(
|
|
182
|
+
[".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts"].map(
|
|
183
|
+
(ext) => ext.toLowerCase()
|
|
184
|
+
)
|
|
185
|
+
);
|
|
186
|
+
let CUSTOM_MDX_COMPONENTS = null;
|
|
187
|
+
let CUSTOM_MDX_SIGNATURE = "";
|
|
188
|
+
let CUSTOM_CLIENT_COMPONENT_ENTRIES = [];
|
|
189
|
+
let CUSTOM_CLIENT_COMPONENT_PLACEHOLDERS = new Map();
|
|
190
|
+
let SERVER_COMPONENT_CACHE = new Map();
|
|
191
|
+
|
|
192
|
+
function isPlainObject(val) {
|
|
193
|
+
if (!val || typeof val !== "object") return false;
|
|
194
|
+
const proto = Object.getPrototypeOf(val);
|
|
195
|
+
return !proto || proto === Object.prototype;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function serializeClientValue(value, depth = 0) {
|
|
199
|
+
if (value == null) return null;
|
|
200
|
+
if (depth > 4) return null;
|
|
201
|
+
const type = typeof value;
|
|
202
|
+
if (type === "string" || type === "number" || type === "boolean") {
|
|
203
|
+
return value;
|
|
204
|
+
}
|
|
205
|
+
if (Array.isArray(value)) {
|
|
206
|
+
const items = value
|
|
207
|
+
.map((entry) => serializeClientValue(entry, depth + 1))
|
|
208
|
+
.filter((entry) => typeof entry !== "undefined" && entry !== null);
|
|
209
|
+
return items;
|
|
210
|
+
}
|
|
211
|
+
if (React.isValidElement && React.isValidElement(value)) {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
if (isPlainObject(value)) {
|
|
215
|
+
const out = {};
|
|
216
|
+
Object.keys(value).forEach((key) => {
|
|
217
|
+
const result = serializeClientValue(value[key], depth + 1);
|
|
218
|
+
if (typeof result !== "undefined" && result !== null) {
|
|
219
|
+
out[key] = result;
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function serializeClientProps(props) {
|
|
228
|
+
if (!props || typeof props !== "object") return {};
|
|
229
|
+
const out = {};
|
|
230
|
+
Object.keys(props).forEach((key) => {
|
|
231
|
+
if (key === "children") {
|
|
232
|
+
const child = props[key];
|
|
233
|
+
if (
|
|
234
|
+
typeof child === "string" ||
|
|
235
|
+
typeof child === "number" ||
|
|
236
|
+
typeof child === "boolean"
|
|
237
|
+
) {
|
|
238
|
+
out[key] = child;
|
|
239
|
+
}
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
const serialized = serializeClientValue(props[key]);
|
|
243
|
+
if (typeof serialized !== "undefined" && serialized !== null) {
|
|
244
|
+
out[key] = serialized;
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function createClientComponentPlaceholder(name) {
|
|
251
|
+
const safeName = String(name || "");
|
|
252
|
+
return function ClientComponentPlaceholder(props = {}) {
|
|
253
|
+
let payload = {};
|
|
254
|
+
try {
|
|
255
|
+
payload = serializeClientProps(props);
|
|
256
|
+
} catch (_) {
|
|
257
|
+
payload = {};
|
|
258
|
+
}
|
|
259
|
+
let json = "{}";
|
|
260
|
+
try {
|
|
261
|
+
json = JSON.stringify(payload || {});
|
|
262
|
+
} catch (_) {
|
|
263
|
+
json = "{}";
|
|
264
|
+
}
|
|
265
|
+
return React.createElement(
|
|
266
|
+
"div",
|
|
267
|
+
{
|
|
268
|
+
"data-canopy-client-component": safeName,
|
|
269
|
+
},
|
|
270
|
+
React.createElement("script", {type: "application/json"}, json)
|
|
271
|
+
);
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function getClientComponentPlaceholder(name) {
|
|
276
|
+
const cached = CUSTOM_CLIENT_COMPONENT_PLACEHOLDERS.get(name);
|
|
277
|
+
if (cached) return cached;
|
|
278
|
+
const placeholder = createClientComponentPlaceholder(name);
|
|
279
|
+
CUSTOM_CLIENT_COMPONENT_PLACEHOLDERS.set(name, placeholder);
|
|
280
|
+
return placeholder;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function loadServerComponentFromPath(name, spec) {
|
|
284
|
+
if (!spec || typeof spec !== "string") return null;
|
|
285
|
+
const esbuild = resolveEsbuild();
|
|
286
|
+
if (!esbuild)
|
|
287
|
+
throw new Error(
|
|
288
|
+
"Custom MDX components require esbuild. Install dependencies before building."
|
|
289
|
+
);
|
|
290
|
+
let resolved = spec;
|
|
291
|
+
if (!path.isAbsolute(resolved)) {
|
|
292
|
+
resolved = path.resolve(APP_COMPONENTS_DIR, spec);
|
|
293
|
+
}
|
|
294
|
+
if (!fs.existsSync(resolved)) {
|
|
295
|
+
throw new Error(
|
|
296
|
+
'[canopy][mdx] Component "' + String(name) + '" not found at ' + String(spec) + '. Ensure the file exists under app/components.'
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
let mtime = 0;
|
|
300
|
+
try {
|
|
301
|
+
const st = fs.statSync(resolved);
|
|
302
|
+
mtime = Math.floor(st.mtimeMs || 0);
|
|
303
|
+
} catch (_) {}
|
|
304
|
+
const cacheKey = resolved;
|
|
305
|
+
const cached = SERVER_COMPONENT_CACHE.get(cacheKey);
|
|
306
|
+
if (cached && cached.mtime === mtime && cached.component) {
|
|
307
|
+
return cached.component;
|
|
308
|
+
}
|
|
309
|
+
ensureDirSync(CACHE_DIR);
|
|
310
|
+
const hash = crypto.createHash("sha1").update(resolved).digest("hex");
|
|
311
|
+
const outFile = path.join(CACHE_DIR, "server-comp-" + hash + ".mjs");
|
|
312
|
+
await esbuild.build({
|
|
313
|
+
entryPoints: [resolved],
|
|
314
|
+
outfile: outFile,
|
|
315
|
+
bundle: true,
|
|
316
|
+
platform: "node",
|
|
317
|
+
target: "node18",
|
|
318
|
+
format: "esm",
|
|
319
|
+
jsx: "automatic",
|
|
320
|
+
jsxImportSource: "react",
|
|
321
|
+
sourcemap: false,
|
|
322
|
+
logLevel: "silent",
|
|
323
|
+
external: [
|
|
324
|
+
"react",
|
|
325
|
+
"react-dom",
|
|
326
|
+
"react-dom/server",
|
|
327
|
+
"react-dom/client",
|
|
328
|
+
],
|
|
329
|
+
// As in 1.x, a component loaded by its own path keeps the UI entry it imports.
|
|
330
|
+
plugins: [esbuildServerPackageNames({server: false})],
|
|
331
|
+
allowOverwrite: true,
|
|
332
|
+
});
|
|
333
|
+
const bust = mtime || Date.now();
|
|
334
|
+
const mod = await import(pathToFileURL(outFile).href + "?v=" + bust);
|
|
335
|
+
let component = null;
|
|
336
|
+
if (mod && typeof mod === "object") {
|
|
337
|
+
component = mod.default || mod[name] || null;
|
|
338
|
+
if (!isComponentLike(component)) {
|
|
339
|
+
component = Object.keys(mod)
|
|
340
|
+
.map((key) => mod[key])
|
|
341
|
+
.find((value) => isComponentLike(value));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (!isComponentLike(component)) {
|
|
345
|
+
throw new Error(
|
|
346
|
+
'[canopy][mdx] Component "' +
|
|
347
|
+
String(name) +
|
|
348
|
+
'" from ' +
|
|
349
|
+
String(spec) +
|
|
350
|
+
' did not export a valid React component. Ensure the module exports a default component or named export matching the key.'
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
SERVER_COMPONENT_CACHE.set(cacheKey, {mtime, component});
|
|
354
|
+
return component;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function resolveServerComponentMap(source) {
|
|
358
|
+
const entries = Object.entries(source || {});
|
|
359
|
+
if (!entries.length) return {};
|
|
360
|
+
const resolved = {};
|
|
361
|
+
for (const [key, value] of entries) {
|
|
362
|
+
if (value == null) continue;
|
|
363
|
+
if (typeof value === "string") {
|
|
364
|
+
const component = await loadServerComponentFromPath(key, value);
|
|
365
|
+
if (component) resolved[key] = component;
|
|
366
|
+
} else {
|
|
367
|
+
resolved[key] = value;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return resolved;
|
|
371
|
+
}
|
|
372
|
+
async function loadCoreUiComponents() {
|
|
373
|
+
// Do not rely on a cached mapping; re-import each time to avoid transient races.
|
|
374
|
+
try {
|
|
375
|
+
// Prefer the workspace dist path during dev to avoid export-map resolution issues
|
|
376
|
+
let resolved = null;
|
|
377
|
+
try {
|
|
378
|
+
const wsDist = path.join(
|
|
379
|
+
process.cwd(),
|
|
380
|
+
"packages",
|
|
381
|
+
"app",
|
|
382
|
+
"ui",
|
|
383
|
+
"dist",
|
|
384
|
+
"server.mjs"
|
|
385
|
+
);
|
|
386
|
+
if (fs.existsSync(wsDist)) resolved = wsDist;
|
|
387
|
+
} catch (_) {}
|
|
388
|
+
// This package's own dist, beside this file, then its export.
|
|
389
|
+
if (!resolved) {
|
|
390
|
+
const own = path.join(__dirname, "..", "..", "ui", "dist", "server.mjs");
|
|
391
|
+
if (fs.existsSync(own)) {
|
|
392
|
+
resolved = own;
|
|
393
|
+
} else {
|
|
394
|
+
try {
|
|
395
|
+
resolved = require.resolve(`${PACKAGE_NAME}/ui/server`);
|
|
396
|
+
} catch (_) {
|
|
397
|
+
resolved = null;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
// Determine current mtime for change detection
|
|
402
|
+
let currentPath = resolved || "";
|
|
403
|
+
let currentMtime = 0;
|
|
404
|
+
if (currentPath) {
|
|
405
|
+
try {
|
|
406
|
+
const st = fs.statSync(currentPath);
|
|
407
|
+
currentMtime = Math.floor(st.mtimeMs || 0);
|
|
408
|
+
} catch (_) {
|
|
409
|
+
currentMtime = 0;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
// If we have a cached module and the path/mtime have not changed, return cached
|
|
413
|
+
if (
|
|
414
|
+
UI_COMPONENTS &&
|
|
415
|
+
UI_COMPONENTS_PATH === currentPath &&
|
|
416
|
+
UI_COMPONENTS_MTIME === currentMtime
|
|
417
|
+
) {
|
|
418
|
+
if (DEBUG) {
|
|
419
|
+
try {
|
|
420
|
+
console.log("[canopy][mdx] UI components cache hit:", {
|
|
421
|
+
path: UI_COMPONENTS_PATH,
|
|
422
|
+
mtime: UI_COMPONENTS_MTIME,
|
|
423
|
+
});
|
|
424
|
+
} catch (_) {}
|
|
425
|
+
}
|
|
426
|
+
return UI_COMPONENTS;
|
|
427
|
+
}
|
|
428
|
+
let mod = null;
|
|
429
|
+
let importErr = null;
|
|
430
|
+
if (resolved) {
|
|
431
|
+
const {pathToFileURL} = require("url");
|
|
432
|
+
const fileUrl = pathToFileURL(resolved).href;
|
|
433
|
+
const attempts = 5;
|
|
434
|
+
for (let i = 0; i < attempts && !mod; i++) {
|
|
435
|
+
const bustVal = currentMtime
|
|
436
|
+
? String(currentMtime) + '-' + String(i)
|
|
437
|
+
: String(Date.now()) + '-' + String(i);
|
|
438
|
+
try {
|
|
439
|
+
mod = await import(fileUrl + '?v=' + bustVal);
|
|
440
|
+
} catch (e) {
|
|
441
|
+
importErr = e;
|
|
442
|
+
if (DEBUG) {
|
|
443
|
+
try {
|
|
444
|
+
console.warn(
|
|
445
|
+
"[canopy][mdx] ESM import failed for",
|
|
446
|
+
resolved,
|
|
447
|
+
"(attempt",
|
|
448
|
+
i + 1,
|
|
449
|
+
"of",
|
|
450
|
+
attempts + ")\n",
|
|
451
|
+
e && (e.stack || e.message || String(e))
|
|
452
|
+
);
|
|
453
|
+
} catch (_) {}
|
|
454
|
+
}
|
|
455
|
+
// Small delay to avoid watch-write race
|
|
456
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (DEBUG) {
|
|
460
|
+
try {
|
|
461
|
+
console.log("[canopy][mdx] UI components resolved", {
|
|
462
|
+
path: resolved,
|
|
463
|
+
mtime: currentMtime,
|
|
464
|
+
loaded: !!mod,
|
|
465
|
+
});
|
|
466
|
+
} catch (_) {}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
if (!mod) {
|
|
470
|
+
// Try package subpath as a secondary resolution path to avoid export-map issues
|
|
471
|
+
try {
|
|
472
|
+
mod = await import(`${PACKAGE_NAME}/ui/server`);
|
|
473
|
+
} catch (e2) {
|
|
474
|
+
const msgA = importErr && (importErr.stack || importErr.message);
|
|
475
|
+
const msgB = e2 && (e2.stack || e2.message);
|
|
476
|
+
throw new Error(
|
|
477
|
+
`Failed to load ${PACKAGE_NAME}/ui/server. Ensure the UI package is built.\nPath import error: ` +
|
|
478
|
+
(msgA || "") +
|
|
479
|
+
"\nExport-map import error: " +
|
|
480
|
+
(msgB || "")
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
let comp = mod && typeof mod === "object" ? mod : {};
|
|
485
|
+
// Hard-require core exports; do not inject fallbacks
|
|
486
|
+
const required = [
|
|
487
|
+
"SearchPanel",
|
|
488
|
+
"SearchFormModal",
|
|
489
|
+
"SearchResults",
|
|
490
|
+
"SearchSummary",
|
|
491
|
+
"SearchTabs",
|
|
492
|
+
"Viewer",
|
|
493
|
+
"Slider",
|
|
494
|
+
"RelatedItems",
|
|
495
|
+
"Interstitials",
|
|
496
|
+
];
|
|
497
|
+
const missing = required.filter((k) => !comp || !comp[k]);
|
|
498
|
+
if (missing.length) {
|
|
499
|
+
throw new Error(
|
|
500
|
+
"[canopy][mdx] Missing UI exports: " + missing.join(", ")
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
if (DEBUG) {
|
|
504
|
+
try {
|
|
505
|
+
console.log("[canopy][mdx] UI component sources", {
|
|
506
|
+
path: currentPath,
|
|
507
|
+
mtime: currentMtime,
|
|
508
|
+
hasServerExport: !!mod,
|
|
509
|
+
hasWorkspace: typeof comp !== "undefined",
|
|
510
|
+
SearchFormModal: !!comp.SearchFormModal,
|
|
511
|
+
Viewer: !!comp.Viewer,
|
|
512
|
+
Slider: !!comp.Slider,
|
|
513
|
+
});
|
|
514
|
+
} catch (_) {}
|
|
515
|
+
}
|
|
516
|
+
UI_COMPONENTS = comp;
|
|
517
|
+
UI_COMPONENTS_PATH = currentPath;
|
|
518
|
+
UI_COMPONENTS_MTIME = currentMtime;
|
|
519
|
+
} catch (e) {
|
|
520
|
+
const msg = (e && (e.stack || e.message || String(e))) || "unknown error";
|
|
521
|
+
throw new Error(
|
|
522
|
+
"[canopy][mdx] Failed to load UI components (no fallbacks): " + msg
|
|
523
|
+
);
|
|
524
|
+
}
|
|
525
|
+
return UI_COMPONENTS;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function resolveCustomComponentsEntry() {
|
|
529
|
+
const baseDir = APP_COMPONENTS_DIR;
|
|
530
|
+
if (!baseDir) return null;
|
|
531
|
+
try {
|
|
532
|
+
if (!fs.existsSync(baseDir)) return null;
|
|
533
|
+
} catch (_) {
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
for (const candidate of CUSTOM_COMPONENT_ENTRY_CANDIDATES) {
|
|
537
|
+
const full = path.join(baseDir, candidate);
|
|
538
|
+
try {
|
|
539
|
+
const st = fs.statSync(full);
|
|
540
|
+
if (st && st.isFile()) return full;
|
|
541
|
+
} catch (_) {}
|
|
542
|
+
}
|
|
543
|
+
return null;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function computeCustomComponentsSignature(entryPath) {
|
|
547
|
+
const baseDir = fs.existsSync(APP_COMPONENTS_DIR)
|
|
548
|
+
? APP_COMPONENTS_DIR
|
|
549
|
+
: path.dirname(entryPath);
|
|
550
|
+
let newest = 0;
|
|
551
|
+
const stack = [];
|
|
552
|
+
if (baseDir && fs.existsSync(baseDir)) stack.push(baseDir);
|
|
553
|
+
while (stack.length) {
|
|
554
|
+
const dir = stack.pop();
|
|
555
|
+
let entries = [];
|
|
556
|
+
try {
|
|
557
|
+
entries = fs.readdirSync(dir, {withFileTypes: true});
|
|
558
|
+
} catch (_) {
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
for (const entry of entries) {
|
|
562
|
+
const full = path.join(dir, entry.name);
|
|
563
|
+
if (entry.isDirectory()) {
|
|
564
|
+
stack.push(full);
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
const ext = path.extname(full).toLowerCase();
|
|
568
|
+
if (!CUSTOM_COMPONENT_EXTENSIONS.has(ext)) continue;
|
|
569
|
+
try {
|
|
570
|
+
const st = fs.statSync(full);
|
|
571
|
+
const mtime = st && st.mtimeMs ? Math.floor(st.mtimeMs) : 0;
|
|
572
|
+
if (mtime > newest) newest = mtime;
|
|
573
|
+
} catch (_) {}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const entryKey = (() => {
|
|
577
|
+
try {
|
|
578
|
+
return path.resolve(entryPath);
|
|
579
|
+
} catch (_) {
|
|
580
|
+
return entryPath;
|
|
581
|
+
}
|
|
582
|
+
})();
|
|
583
|
+
return String(entryKey) + ':' + String(newest);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async function compileCustomComponentModule(entryPath, signature) {
|
|
587
|
+
const esbuild = resolveEsbuild();
|
|
588
|
+
if (!esbuild)
|
|
589
|
+
throw new Error(
|
|
590
|
+
"Custom MDX components require esbuild. Install dependencies before building."
|
|
591
|
+
);
|
|
592
|
+
ensureDirSync(CACHE_DIR);
|
|
593
|
+
const rel = (() => {
|
|
594
|
+
try {
|
|
595
|
+
return path
|
|
596
|
+
.relative(process.cwd(), entryPath)
|
|
597
|
+
.split(path.sep)
|
|
598
|
+
.join("/");
|
|
599
|
+
} catch (_) {
|
|
600
|
+
return entryPath;
|
|
601
|
+
}
|
|
602
|
+
})();
|
|
603
|
+
const tmpFile = path.join(CACHE_DIR, "custom-mdx-components.mjs");
|
|
604
|
+
try {
|
|
605
|
+
await esbuild.build({
|
|
606
|
+
entryPoints: [entryPath],
|
|
607
|
+
outfile: tmpFile,
|
|
608
|
+
bundle: true,
|
|
609
|
+
platform: "node",
|
|
610
|
+
target: "node18",
|
|
611
|
+
format: "esm",
|
|
612
|
+
sourcemap: false,
|
|
613
|
+
logLevel: "silent",
|
|
614
|
+
jsx: "automatic",
|
|
615
|
+
jsxImportSource: "react",
|
|
616
|
+
external: [
|
|
617
|
+
"react",
|
|
618
|
+
"react-dom",
|
|
619
|
+
"react-dom/server",
|
|
620
|
+
"react-dom/client",
|
|
621
|
+
],
|
|
622
|
+
plugins: [esbuildServerPackageNames()],
|
|
623
|
+
allowOverwrite: true,
|
|
624
|
+
});
|
|
625
|
+
} catch (err) {
|
|
626
|
+
const msg = err && (err.message || err.stack) ? err.message || err.stack : err;
|
|
627
|
+
throw new Error(
|
|
628
|
+
'Failed to compile custom MDX components (' +
|
|
629
|
+
rel +
|
|
630
|
+
').\n' +
|
|
631
|
+
(msg || 'Unknown error')
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
const cacheBust = signature || String(Date.now());
|
|
635
|
+
return import(pathToFileURL(tmpFile).href + '?custom=' + cacheBust);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function isComponentLike(value) {
|
|
639
|
+
if (value == null) return false;
|
|
640
|
+
if (typeof value === "function") return true;
|
|
641
|
+
if (typeof value === "object") {
|
|
642
|
+
if (value.$$typeof) return true;
|
|
643
|
+
if (value.render && typeof value.render === "function") return true;
|
|
644
|
+
}
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function cloneComponentMap(source) {
|
|
649
|
+
const out = {};
|
|
650
|
+
Object.keys(source || {}).forEach((key) => {
|
|
651
|
+
const value = source[key];
|
|
652
|
+
if (typeof value === "undefined" || value === null) return;
|
|
653
|
+
out[key] = value;
|
|
654
|
+
});
|
|
655
|
+
return out;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async function normalizeCustomComponentExports(mod) {
|
|
659
|
+
if (!mod || typeof mod !== "object") return {components: {}, clientEntries: []};
|
|
660
|
+
const candidateKeys = ["components", "mdxComponents", "MDXComponents"];
|
|
661
|
+
let components = {};
|
|
662
|
+
for (const key of candidateKeys) {
|
|
663
|
+
if (mod[key] && typeof mod[key] === "object") {
|
|
664
|
+
const cloned = cloneComponentMap(mod[key]);
|
|
665
|
+
if (Object.keys(cloned).length) {
|
|
666
|
+
components = cloned;
|
|
667
|
+
break;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
if (!Object.keys(components).length && mod.default && typeof mod.default === "object") {
|
|
672
|
+
const cloned = cloneComponentMap(mod.default);
|
|
673
|
+
if (Object.keys(cloned).length) components = cloned;
|
|
674
|
+
}
|
|
675
|
+
if (!Object.keys(components).length) {
|
|
676
|
+
const fallback = {};
|
|
677
|
+
Object.keys(mod).forEach((key) => {
|
|
678
|
+
if (key === "default" || key === "__esModule") return;
|
|
679
|
+
const value = mod[key];
|
|
680
|
+
if (!isComponentLike(value)) return;
|
|
681
|
+
fallback[key] = value;
|
|
682
|
+
});
|
|
683
|
+
components = fallback;
|
|
684
|
+
}
|
|
685
|
+
if (Object.keys(components).length) {
|
|
686
|
+
components = await resolveServerComponentMap(components);
|
|
687
|
+
}
|
|
688
|
+
const clientEntries = [];
|
|
689
|
+
const rawClient = mod && typeof mod === "object" ? mod.clientComponents : null;
|
|
690
|
+
if (rawClient && typeof rawClient === "object") {
|
|
691
|
+
Object.keys(rawClient).forEach((key) => {
|
|
692
|
+
const spec = rawClient[key];
|
|
693
|
+
if (typeof spec !== "string" || !spec.trim()) return;
|
|
694
|
+
let resolved = spec.trim();
|
|
695
|
+
if (!path.isAbsolute(resolved)) {
|
|
696
|
+
resolved = path.resolve(APP_COMPONENTS_DIR, resolved);
|
|
697
|
+
}
|
|
698
|
+
if (!fs.existsSync(resolved)) {
|
|
699
|
+
throw new Error(
|
|
700
|
+
`[canopy][mdx] Client component "${key}" not found at ${spec}. Ensure the file exists under app/components.`
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
clientEntries.push({
|
|
704
|
+
name: String(key),
|
|
705
|
+
source: spec,
|
|
706
|
+
path: resolved,
|
|
707
|
+
});
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
if (clientEntries.length) {
|
|
711
|
+
clientEntries.forEach((entry) => {
|
|
712
|
+
components[entry.name] = getClientComponentPlaceholder(entry.name);
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
return {components, clientEntries};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
async function loadCustomMdxComponents() {
|
|
719
|
+
const entry = resolveCustomComponentsEntry();
|
|
720
|
+
if (!entry) {
|
|
721
|
+
CUSTOM_MDX_COMPONENTS = null;
|
|
722
|
+
CUSTOM_MDX_SIGNATURE = "";
|
|
723
|
+
CUSTOM_CLIENT_COMPONENT_ENTRIES = [];
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
const signature = computeCustomComponentsSignature(entry);
|
|
727
|
+
if (
|
|
728
|
+
CUSTOM_MDX_COMPONENTS &&
|
|
729
|
+
CUSTOM_MDX_SIGNATURE &&
|
|
730
|
+
CUSTOM_MDX_SIGNATURE === signature
|
|
731
|
+
) {
|
|
732
|
+
return {
|
|
733
|
+
components: CUSTOM_MDX_COMPONENTS,
|
|
734
|
+
signature,
|
|
735
|
+
clientEntries: CUSTOM_CLIENT_COMPONENT_ENTRIES.slice(),
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
const mod = await compileCustomComponentModule(entry, signature);
|
|
739
|
+
const {components, clientEntries} = await normalizeCustomComponentExports(mod);
|
|
740
|
+
CUSTOM_MDX_COMPONENTS = components;
|
|
741
|
+
CUSTOM_MDX_SIGNATURE = signature;
|
|
742
|
+
CUSTOM_CLIENT_COMPONENT_ENTRIES = Array.isArray(clientEntries)
|
|
743
|
+
? clientEntries.slice()
|
|
744
|
+
: [];
|
|
745
|
+
return {components, signature, clientEntries: CUSTOM_CLIENT_COMPONENT_ENTRIES};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async function loadUiComponents() {
|
|
749
|
+
const baseComponents = await loadCoreUiComponents();
|
|
750
|
+
const custom = await loadCustomMdxComponents();
|
|
751
|
+
const customKey = custom && custom.signature ? custom.signature : "";
|
|
752
|
+
const compositeKey = `${UI_COMPONENTS_PATH || ""}:${
|
|
753
|
+
UI_COMPONENTS_MTIME || 0
|
|
754
|
+
}:${customKey}`;
|
|
755
|
+
if (MERGED_UI_COMPONENTS && MERGED_UI_KEY === compositeKey) {
|
|
756
|
+
return MERGED_UI_COMPONENTS;
|
|
757
|
+
}
|
|
758
|
+
const merged =
|
|
759
|
+
custom &&
|
|
760
|
+
custom.components &&
|
|
761
|
+
Object.keys(custom.components).length > 0
|
|
762
|
+
? {...baseComponents, ...custom.components}
|
|
763
|
+
: baseComponents;
|
|
764
|
+
MERGED_UI_COMPONENTS = merged;
|
|
765
|
+
MERGED_UI_KEY = compositeKey;
|
|
766
|
+
return MERGED_UI_COMPONENTS;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function slugifyHeading(text) {
|
|
770
|
+
try {
|
|
771
|
+
return String(text || "")
|
|
772
|
+
.toLowerCase()
|
|
773
|
+
.trim()
|
|
774
|
+
.replace(/[^a-z0-9\s-]/g, "")
|
|
775
|
+
.replace(/\s+/g, "-");
|
|
776
|
+
} catch (_) {
|
|
777
|
+
return "";
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function extractHeadings(mdxSource) {
|
|
782
|
+
const {content} = parseFrontmatter(String(mdxSource || ""));
|
|
783
|
+
const cleaned = content.replace(/```[\s\S]*?```/g, "");
|
|
784
|
+
const headingRegex = /^ {0,3}(#{1,6})\s+(.+?)\s*$/gm;
|
|
785
|
+
const seen = new Map();
|
|
786
|
+
const headings = [];
|
|
787
|
+
let match;
|
|
788
|
+
while ((match = headingRegex.exec(cleaned))) {
|
|
789
|
+
const hashes = match[1] || "";
|
|
790
|
+
const depth = hashes.length;
|
|
791
|
+
let raw = match[2] || "";
|
|
792
|
+
let explicitId = null;
|
|
793
|
+
const idMatch = raw.match(/\s*\{#([A-Za-z0-9_-]+)\}\s*$/);
|
|
794
|
+
if (idMatch) {
|
|
795
|
+
explicitId = idMatch[1];
|
|
796
|
+
raw = raw.slice(0, raw.length - idMatch[0].length);
|
|
797
|
+
}
|
|
798
|
+
const title = raw
|
|
799
|
+
.replace(/\<[^>]*\>/g, "")
|
|
800
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
|
|
801
|
+
.trim();
|
|
802
|
+
if (!title) continue;
|
|
803
|
+
const baseId =
|
|
804
|
+
explicitId || slugifyHeading(title) || `section-${headings.length + 1}`;
|
|
805
|
+
const count = seen.get(baseId) || 0;
|
|
806
|
+
seen.set(baseId, count + 1);
|
|
807
|
+
const id = count === 0 ? baseId : `${baseId}-${count + 1}`;
|
|
808
|
+
headings.push({
|
|
809
|
+
id,
|
|
810
|
+
title,
|
|
811
|
+
depth,
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
return headings;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function extractPlainText(mdxSource) {
|
|
818
|
+
let {content} = parseFrontmatter(String(mdxSource || ""));
|
|
819
|
+
if (!content) return "";
|
|
820
|
+
content = content.replace(/```[\s\S]*?```/g, " ");
|
|
821
|
+
content = content.replace(/`{1,3}([^`]+)`{1,3}/g, "$1");
|
|
822
|
+
content = content.replace(/!\[[^\]]*\]\([^)]*\)/g, " ");
|
|
823
|
+
content = content.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
824
|
+
content = content.replace(/<[^>]+>/g, " ");
|
|
825
|
+
content = content.replace(/\{#([^}]+)\}/g, " ");
|
|
826
|
+
content = content.replace(/\{\/[A-Za-z0-9_.-]+\}/g, " ");
|
|
827
|
+
content = content.replace(/\{[^{}]*\}/g, " ");
|
|
828
|
+
content = content.replace(/[#>*~_\-]+/g, " ");
|
|
829
|
+
content = content.replace(/\n+/g, " ");
|
|
830
|
+
content = content.replace(/\s+/g, " ").trim();
|
|
831
|
+
return content;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function extractMarkdownSummary(mdxSource) {
|
|
835
|
+
let {content} = parseFrontmatter(String(mdxSource || ""));
|
|
836
|
+
if (!content) return "";
|
|
837
|
+
content = content.replace(/^import[^\n]+$/gm, " ");
|
|
838
|
+
content = content.replace(/^export[^\n]+$/gm, " ");
|
|
839
|
+
content = content.replace(/```[\s\S]*?```/g, " ");
|
|
840
|
+
content = content.replace(/<[A-Za-z][^>]*?>[\s\S]*?<\/[A-Za-z][^>]*?>/g, " ");
|
|
841
|
+
content = content.replace(/<[A-Za-z][^>]*?\/>/g, " ");
|
|
842
|
+
content = content.replace(/\{\/[A-Za-z0-9_.-]+\}/g, " ");
|
|
843
|
+
content = content.replace(/\{[^{}]*\}/g, " ");
|
|
844
|
+
content = content.replace(/^#{1,6}\s+.*$/gm, " ");
|
|
845
|
+
content = content.replace(/\s+/g, " ").trim();
|
|
846
|
+
return content;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// A page's words: { text } it is found by, { excerpt } its prose without headings (a meta
|
|
850
|
+
// description where the page gives none) and { markdown } its result's excerpt is drawn
|
|
851
|
+
// from, read with the MDX parser (`search-text.js`), or the patterns above where it cannot.
|
|
852
|
+
function extractSearchText(mdxSource) {
|
|
853
|
+
const {content} = parseFrontmatter(String(mdxSource || ""));
|
|
854
|
+
if (!content) return {text: "", excerpt: "", markdown: ""};
|
|
855
|
+
const parsed = require("./search-text").searchTextFromMdx(content);
|
|
856
|
+
if (parsed) return parsed;
|
|
857
|
+
const text = extractPlainText(mdxSource);
|
|
858
|
+
return {text, excerpt: text, markdown: extractMarkdownSummary(mdxSource)};
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function extractTitle(mdxSource) {
|
|
862
|
+
const {data, content} = parseFrontmatter(String(mdxSource || ""));
|
|
863
|
+
if (data && typeof data.title === "string" && data.title.trim()) {
|
|
864
|
+
return data.title.trim();
|
|
865
|
+
}
|
|
866
|
+
const m = content.match(/^\s*#{1,6}\s+(.+?)\s*$/m);
|
|
867
|
+
return m ? m[1].trim() : "Untitled";
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function isReservedFile(p) {
|
|
871
|
+
const base = path.basename(p);
|
|
872
|
+
return base.startsWith("_");
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
// Cache for directory-scoped layouts
|
|
876
|
+
const DIR_LAYOUTS = new Map();
|
|
877
|
+
async function getNearestDirLayout(filePath) {
|
|
878
|
+
const dirStart = path.dirname(filePath);
|
|
879
|
+
let dir = dirStart;
|
|
880
|
+
while (dir && dir.startsWith(CONTENT_DIR)) {
|
|
881
|
+
const key = path.resolve(dir);
|
|
882
|
+
if (DIR_LAYOUTS.has(key)) {
|
|
883
|
+
const cached = DIR_LAYOUTS.get(key);
|
|
884
|
+
if (cached) return cached;
|
|
885
|
+
}
|
|
886
|
+
const candidate = path.join(dir, "_layout.mdx");
|
|
887
|
+
if (fs.existsSync(candidate)) {
|
|
888
|
+
try {
|
|
889
|
+
const Comp = await compileMdxToComponent(candidate);
|
|
890
|
+
DIR_LAYOUTS.set(key, Comp);
|
|
891
|
+
return Comp;
|
|
892
|
+
} catch (_) {
|
|
893
|
+
DIR_LAYOUTS.set(key, null);
|
|
894
|
+
}
|
|
895
|
+
} else {
|
|
896
|
+
DIR_LAYOUTS.set(key, null);
|
|
897
|
+
}
|
|
898
|
+
const parent = path.dirname(dir);
|
|
899
|
+
if (parent === dir) break;
|
|
900
|
+
dir = parent;
|
|
901
|
+
}
|
|
902
|
+
return null;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
let APP_WRAPPER = null; // { App, Head } or null
|
|
906
|
+
async function loadAppWrapper() {
|
|
907
|
+
if (APP_WRAPPER !== null) return APP_WRAPPER;
|
|
908
|
+
const appPath = path.join(CONTENT_DIR, "_app.mdx");
|
|
909
|
+
if (!fs.existsSync(appPath)) {
|
|
910
|
+
// Keep missing _app as a build-time error as specified
|
|
911
|
+
throw new Error("Missing required file: content/_app.mdx");
|
|
912
|
+
}
|
|
913
|
+
const {compile} = await import("@mdx-js/mdx");
|
|
914
|
+
const raw = await fsp.readFile(appPath, "utf8");
|
|
915
|
+
const {content: source} = parseFrontmatter(raw);
|
|
916
|
+
let code = String(await compile(source, buildCompileOptions({server: true})));
|
|
917
|
+
// MDX v3 default export (MDXContent) does not forward external children.
|
|
918
|
+
// When present, expose the underlying layout function as __MDXLayout for wrapping.
|
|
919
|
+
if (
|
|
920
|
+
/\bconst\s+MDXLayout\b/.test(code) &&
|
|
921
|
+
!/export\s+const\s+__MDXLayout\b/.test(code)
|
|
922
|
+
) {
|
|
923
|
+
code += "\nexport const __MDXLayout = MDXLayout;\n";
|
|
924
|
+
}
|
|
925
|
+
ensureDirSync(CACHE_DIR);
|
|
926
|
+
const tmpFile = path.join(CACHE_DIR, "_app.mjs");
|
|
927
|
+
await fsp.writeFile(tmpFile, code, "utf8");
|
|
928
|
+
const mod = await import(pathToFileURL(tmpFile).href + `?v=${Date.now()}`);
|
|
929
|
+
let App = mod.App || mod.__MDXLayout || mod.default || null;
|
|
930
|
+
const Head = mod.Head || null;
|
|
931
|
+
// Prefer a component that renders its children, but do not hard-fail if probe fails.
|
|
932
|
+
let ok = false;
|
|
933
|
+
try {
|
|
934
|
+
// Try to render the probe inside an MDXProvider with UI server components
|
|
935
|
+
const components = await loadUiComponents();
|
|
936
|
+
const MDXProvider = await getMdxProvider();
|
|
937
|
+
const probeChild = React.createElement("span", {"data-canopy-probe": "1"});
|
|
938
|
+
const probeTree = React.createElement(
|
|
939
|
+
App || (() => null),
|
|
940
|
+
null,
|
|
941
|
+
probeChild
|
|
942
|
+
);
|
|
943
|
+
const probe = MDXProvider
|
|
944
|
+
? React.createElement(MDXProvider, {components}, probeTree)
|
|
945
|
+
: probeTree;
|
|
946
|
+
const out = ReactDOMServer.renderToStaticMarkup(probe);
|
|
947
|
+
ok = !!(out && out.indexOf("data-canopy-probe") !== -1);
|
|
948
|
+
} catch (_) {
|
|
949
|
+
ok = false;
|
|
950
|
+
}
|
|
951
|
+
if (!ok) {
|
|
952
|
+
throw new Error(
|
|
953
|
+
"content/_app.mdx must render {children}. Update the layout so downstream pages receive their content."
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
APP_WRAPPER = {App, Head};
|
|
957
|
+
return APP_WRAPPER;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
async function compileMdxFile(filePath, outPath, Layout, extraProps = {}) {
|
|
961
|
+
const {compile} = await import("@mdx-js/mdx");
|
|
962
|
+
const raw = await fsp.readFile(filePath, "utf8");
|
|
963
|
+
const {content: source} = parseFrontmatter(raw);
|
|
964
|
+
const compiled = await compile(source, buildCompileOptions({server: true}));
|
|
965
|
+
const code = String(compiled);
|
|
966
|
+
ensureDirSync(CACHE_DIR);
|
|
967
|
+
const relCacheName =
|
|
968
|
+
path
|
|
969
|
+
.relative(CONTENT_DIR, filePath)
|
|
970
|
+
.replace(/[\\/]/g, "_")
|
|
971
|
+
.replace(/\.mdx$/i, "") + ".mjs";
|
|
972
|
+
const tmpFile = path.join(CACHE_DIR, relCacheName);
|
|
973
|
+
await fsp.writeFile(tmpFile, code, "utf8");
|
|
974
|
+
// Bust ESM module cache using source mtime
|
|
975
|
+
let bust = "";
|
|
976
|
+
try {
|
|
977
|
+
const st = fs.statSync(filePath);
|
|
978
|
+
bust = `?v=${Math.floor(st.mtimeMs)}`;
|
|
979
|
+
} catch (_) {}
|
|
980
|
+
const mod = await import(pathToFileURL(tmpFile).href + bust);
|
|
981
|
+
const MDXContent = mod.default || mod.MDXContent || mod;
|
|
982
|
+
const components = await loadUiComponents();
|
|
983
|
+
const markdownTableComponent =
|
|
984
|
+
components &&
|
|
985
|
+
(components.MarkdownTable ||
|
|
986
|
+
components.DocsMarkdownTable ||
|
|
987
|
+
components.MarkdownTables ||
|
|
988
|
+
components.MDXMarkdownTable);
|
|
989
|
+
const codeBlockComponent =
|
|
990
|
+
components &&
|
|
991
|
+
(components.DocsCodeBlock ||
|
|
992
|
+
components.CodeBlock ||
|
|
993
|
+
components.MarkdownCodeBlock ||
|
|
994
|
+
components.MDXCodeBlock);
|
|
995
|
+
const rawHeadings = Array.isArray(
|
|
996
|
+
extraProps && extraProps.page && extraProps.page.headings
|
|
997
|
+
)
|
|
998
|
+
? extraProps.page.headings
|
|
999
|
+
.map((heading) => (heading ? {...heading} : heading))
|
|
1000
|
+
.filter(Boolean)
|
|
1001
|
+
: [];
|
|
1002
|
+
const headingQueue = rawHeadings.slice();
|
|
1003
|
+
const headingIdCounts = new Map();
|
|
1004
|
+
headingQueue.forEach((heading) => {
|
|
1005
|
+
if (heading && heading.id) {
|
|
1006
|
+
const key = String(heading.id);
|
|
1007
|
+
headingIdCounts.set(key, (headingIdCounts.get(key) || 0) + 1);
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
|
|
1011
|
+
function reserveHeadingId(base) {
|
|
1012
|
+
const fallback = base || "section";
|
|
1013
|
+
let candidate = fallback;
|
|
1014
|
+
let attempt = 1;
|
|
1015
|
+
while (headingIdCounts.has(candidate)) {
|
|
1016
|
+
attempt += 1;
|
|
1017
|
+
candidate = `${fallback}-${attempt}`;
|
|
1018
|
+
}
|
|
1019
|
+
headingIdCounts.set(candidate, 1);
|
|
1020
|
+
return candidate;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function extractTextFromChildren(children) {
|
|
1024
|
+
if (children == null) return "";
|
|
1025
|
+
if (typeof children === "string" || typeof children === "number")
|
|
1026
|
+
return String(children);
|
|
1027
|
+
if (Array.isArray(children))
|
|
1028
|
+
return children.map((child) => extractTextFromChildren(child)).join("");
|
|
1029
|
+
if (React.isValidElement(children))
|
|
1030
|
+
return extractTextFromChildren(children.props && children.props.children);
|
|
1031
|
+
return "";
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
function takeHeading(level, children) {
|
|
1035
|
+
if (!headingQueue.length) return null;
|
|
1036
|
+
const idx = headingQueue.findIndex((item) => {
|
|
1037
|
+
if (!item || typeof item !== "object") return false;
|
|
1038
|
+
const depth = typeof item.depth === "number" ? item.depth : item.level;
|
|
1039
|
+
return depth === level;
|
|
1040
|
+
});
|
|
1041
|
+
if (idx === -1) return null;
|
|
1042
|
+
const [heading] = headingQueue.splice(idx, 1);
|
|
1043
|
+
if (!heading.id) {
|
|
1044
|
+
const text = heading.title || extractTextFromChildren(children);
|
|
1045
|
+
const baseId = slugifyHeading(text);
|
|
1046
|
+
heading.id = reserveHeadingId(baseId);
|
|
1047
|
+
}
|
|
1048
|
+
if (!heading.title) {
|
|
1049
|
+
heading.title = extractTextFromChildren(children);
|
|
1050
|
+
}
|
|
1051
|
+
return heading;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
function createHeadingComponent(level) {
|
|
1055
|
+
const tag = `h${level}`;
|
|
1056
|
+
const Base = components && components[tag] ? components[tag] : tag;
|
|
1057
|
+
return function HeadingComponent(props) {
|
|
1058
|
+
const heading = takeHeading(level, props && props.children);
|
|
1059
|
+
const id = props && props.id ? props.id : heading && heading.id;
|
|
1060
|
+
const finalProps = id ? {...props, id} : props;
|
|
1061
|
+
return React.createElement(Base, finalProps, props && props.children);
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
const levelsPresent = Array.from(
|
|
1066
|
+
new Set(
|
|
1067
|
+
headingQueue
|
|
1068
|
+
.map((heading) => (heading ? heading.depth || heading.level : null))
|
|
1069
|
+
.filter(
|
|
1070
|
+
(level) => typeof level === "number" && level >= 1 && level <= 6
|
|
1071
|
+
)
|
|
1072
|
+
)
|
|
1073
|
+
);
|
|
1074
|
+
const headingComponents = levelsPresent.length
|
|
1075
|
+
? levelsPresent.reduce((acc, level) => {
|
|
1076
|
+
acc[`h${level}`] = createHeadingComponent(level);
|
|
1077
|
+
return acc;
|
|
1078
|
+
}, {})
|
|
1079
|
+
: {};
|
|
1080
|
+
const MDXProvider = await getMdxProvider();
|
|
1081
|
+
// Base path support for anchors
|
|
1082
|
+
const Anchor = function A(props) {
|
|
1083
|
+
let {href = "", ...rest} = props || {};
|
|
1084
|
+
href = withBase(href);
|
|
1085
|
+
return React.createElement("a", {href, ...rest}, props.children);
|
|
1086
|
+
};
|
|
1087
|
+
const app = await loadAppWrapper();
|
|
1088
|
+
const dirLayout = await getNearestDirLayout(filePath);
|
|
1089
|
+
const contentNode = React.createElement(MDXContent, extraProps);
|
|
1090
|
+
const layoutProps = dirLayout ? {...extraProps} : null;
|
|
1091
|
+
const withLayout = dirLayout
|
|
1092
|
+
? React.createElement(dirLayout, layoutProps, contentNode)
|
|
1093
|
+
: contentNode;
|
|
1094
|
+
const withApp = React.createElement(app.App, null, withLayout);
|
|
1095
|
+
const PageContext = getPageContext();
|
|
1096
|
+
const siteMeta = readSiteMetadata();
|
|
1097
|
+
const pageLocale =
|
|
1098
|
+
extraProps && extraProps.page && typeof extraProps.page.locale === "string"
|
|
1099
|
+
? extraProps.page.locale
|
|
1100
|
+
: undefined;
|
|
1101
|
+
const primaryNav = readPrimaryNavigation(pageLocale);
|
|
1102
|
+
const siteLanguageToggle = getSiteLanguageToggle();
|
|
1103
|
+
const siteContext = siteMeta ? {...siteMeta} : {};
|
|
1104
|
+
if (siteLanguageToggle) {
|
|
1105
|
+
siteContext.languageToggle = siteLanguageToggle;
|
|
1106
|
+
}
|
|
1107
|
+
try {
|
|
1108
|
+
const localeMessages = readLocaleMessages(pageLocale);
|
|
1109
|
+
if (localeMessages) siteContext.localeMessages = localeMessages;
|
|
1110
|
+
} catch (_) {}
|
|
1111
|
+
try {
|
|
1112
|
+
const localeRoutes = getLocaleRouteConfig(pageLocale);
|
|
1113
|
+
if (localeRoutes) siteContext.routes = localeRoutes;
|
|
1114
|
+
} catch (_) {}
|
|
1115
|
+
try {
|
|
1116
|
+
const defaultRoutes = getLocaleRouteConfig(getDefaultLocaleCode());
|
|
1117
|
+
if (defaultRoutes) siteContext.routesDefault = defaultRoutes;
|
|
1118
|
+
} catch (_) {}
|
|
1119
|
+
const contextValue = {
|
|
1120
|
+
navigation:
|
|
1121
|
+
extraProps && extraProps.navigation ? extraProps.navigation : null,
|
|
1122
|
+
page: extraProps && extraProps.page ? extraProps.page : null,
|
|
1123
|
+
site: siteContext && Object.keys(siteContext).length ? siteContext : null,
|
|
1124
|
+
primaryNavigation: Array.isArray(primaryNav) ? primaryNav : [],
|
|
1125
|
+
};
|
|
1126
|
+
const withContext = PageContext
|
|
1127
|
+
? React.createElement(PageContext.Provider, {value: contextValue}, withApp)
|
|
1128
|
+
: withApp;
|
|
1129
|
+
const compMap = {...components, ...headingComponents, a: Anchor};
|
|
1130
|
+
if (markdownTableComponent && !compMap.table) {
|
|
1131
|
+
compMap.table = markdownTableComponent;
|
|
1132
|
+
}
|
|
1133
|
+
if (codeBlockComponent && !compMap.pre) {
|
|
1134
|
+
compMap.pre = codeBlockComponent;
|
|
1135
|
+
}
|
|
1136
|
+
const page = MDXProvider
|
|
1137
|
+
? React.createElement(MDXProvider, {components: compMap}, withContext)
|
|
1138
|
+
: withContext;
|
|
1139
|
+
const body = ReactDOMServer.renderToStaticMarkup(page);
|
|
1140
|
+
let head = "";
|
|
1141
|
+
if (app && app.Head) {
|
|
1142
|
+
const headElement = React.createElement(app.Head, {
|
|
1143
|
+
page: contextValue.page,
|
|
1144
|
+
navigation: contextValue.navigation,
|
|
1145
|
+
});
|
|
1146
|
+
const wrappedHead = PageContext
|
|
1147
|
+
? React.createElement(
|
|
1148
|
+
PageContext.Provider,
|
|
1149
|
+
{value: contextValue},
|
|
1150
|
+
headElement
|
|
1151
|
+
)
|
|
1152
|
+
: headElement;
|
|
1153
|
+
head = ReactDOMServer.renderToStaticMarkup(wrappedHead);
|
|
1154
|
+
}
|
|
1155
|
+
return {body, head};
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
async function compileMdxToComponent(filePath) {
|
|
1159
|
+
const {compile} = await import("@mdx-js/mdx");
|
|
1160
|
+
const raw = await fsp.readFile(filePath, "utf8");
|
|
1161
|
+
const {content: source} = parseFrontmatter(raw);
|
|
1162
|
+
const compiled = await compile(source, buildCompileOptions());
|
|
1163
|
+
const code = String(compiled);
|
|
1164
|
+
ensureDirSync(CACHE_DIR);
|
|
1165
|
+
const relCacheName =
|
|
1166
|
+
path
|
|
1167
|
+
.relative(CONTENT_DIR, filePath)
|
|
1168
|
+
.replace(/[\\/]/g, "_")
|
|
1169
|
+
.replace(/\.mdx$/i, "") + ".mjs";
|
|
1170
|
+
const tmpFile = path.join(CACHE_DIR, relCacheName);
|
|
1171
|
+
await fsp.writeFile(tmpFile, code, "utf8");
|
|
1172
|
+
let bust = "";
|
|
1173
|
+
try {
|
|
1174
|
+
const st = fs.statSync(filePath);
|
|
1175
|
+
bust = `?v=${Math.floor(st.mtimeMs)}`;
|
|
1176
|
+
} catch (_) {}
|
|
1177
|
+
const mod = await import(pathToFileURL(tmpFile).href + bust);
|
|
1178
|
+
return mod.default || mod.MDXContent || mod;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
async function loadCustomLayout(defaultLayout) {
|
|
1182
|
+
// Deprecated: directory-scoped layouts handled per-page via getNearestDirLayout
|
|
1183
|
+
return defaultLayout;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* A module that reads React from `window.React` (`react-globals.js`), for the runtimes
|
|
1188
|
+
* that hydrate beside the page's React, exporting every name React exports. Clover 4
|
|
1189
|
+
* imports `lazy` and `Suspense` too; a list kept by hand missed them, and every runtime
|
|
1190
|
+
* that reaches Clover then failed to bundle, the timeline's and map's among them, as
|
|
1191
|
+
* esbuild parses the targets of the UI bundle's dynamic imports.
|
|
1192
|
+
*/
|
|
1193
|
+
function reactGlobalShim() {
|
|
1194
|
+
return (
|
|
1195
|
+
"const React = (typeof window !== 'undefined' && window.React) || {};\n" +
|
|
1196
|
+
"export default React;\n" +
|
|
1197
|
+
Object.keys(require("react"))
|
|
1198
|
+
.filter((name) => name !== "default" && /^[A-Za-z_$][\w$]*$/.test(name))
|
|
1199
|
+
.map((name) => `export const ${name} = React.${name};`)
|
|
1200
|
+
.join("\n") +
|
|
1201
|
+
"\n"
|
|
1202
|
+
);
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function resolveEsbuild() {
|
|
1206
|
+
try {
|
|
1207
|
+
return require("../../ui/node_modules/esbuild");
|
|
1208
|
+
} catch (_) {
|
|
1209
|
+
try {
|
|
1210
|
+
return require("esbuild");
|
|
1211
|
+
} catch (_) {
|
|
1212
|
+
return null;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function createReactShimPlugin() {
|
|
1218
|
+
const reactShim = reactGlobalShim();
|
|
1219
|
+
const rdomShim = `
|
|
1220
|
+
const ReactDOM = (typeof window !== 'undefined' && window.ReactDOM) || {};
|
|
1221
|
+
export default ReactDOM;
|
|
1222
|
+
export const render = ReactDOM.render;
|
|
1223
|
+
export const hydrate = ReactDOM.hydrate;
|
|
1224
|
+
export const findDOMNode = ReactDOM.findDOMNode;
|
|
1225
|
+
export const unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
|
|
1226
|
+
export const createPortal = ReactDOM.createPortal;
|
|
1227
|
+
export const flushSync = ReactDOM.flushSync;
|
|
1228
|
+
export const unstable_batchedUpdates = ReactDOM.unstable_batchedUpdates;
|
|
1229
|
+
export const unstable_renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer;
|
|
1230
|
+
`;
|
|
1231
|
+
const rdomClientShim = `
|
|
1232
|
+
const RDC = (typeof window !== 'undefined' && window.ReactDOMClient) || {};
|
|
1233
|
+
export const createRoot = RDC.createRoot;
|
|
1234
|
+
export const hydrateRoot = RDC.hydrateRoot;
|
|
1235
|
+
`;
|
|
1236
|
+
return {
|
|
1237
|
+
name: "canopy-react-shims",
|
|
1238
|
+
setup(build) {
|
|
1239
|
+
const ns = "canopy-shim";
|
|
1240
|
+
build.onResolve({ filter: /^react$/ }, () => ({ path: "react", namespace: ns }));
|
|
1241
|
+
build.onResolve({ filter: /^react-dom$/ }, () => ({ path: "react-dom", namespace: ns }));
|
|
1242
|
+
build.onResolve({ filter: /^react-dom\/client$/ }, () => ({ path: "react-dom-client", namespace: ns }));
|
|
1243
|
+
build.onLoad({ filter: /^react$/, namespace: ns }, () => ({ contents: reactShim, loader: "js" }));
|
|
1244
|
+
build.onLoad({ filter: /^react-dom$/, namespace: ns }, () => ({ contents: rdomShim, loader: "js" }));
|
|
1245
|
+
build.onLoad({ filter: /^react-dom-client$/, namespace: ns }, () => ({ contents: rdomClientShim, loader: "js" }));
|
|
1246
|
+
},
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
function createSliderCssInlinePlugin() {
|
|
1251
|
+
return {
|
|
1252
|
+
name: "canopy-inline-slider-css",
|
|
1253
|
+
setup(build) {
|
|
1254
|
+
build.onLoad({ filter: /\.css$/ }, (args) => {
|
|
1255
|
+
const fs = require("fs");
|
|
1256
|
+
let css = "";
|
|
1257
|
+
try {
|
|
1258
|
+
css = fs.readFileSync(args.path, "utf8");
|
|
1259
|
+
} catch (_) {
|
|
1260
|
+
css = "";
|
|
1261
|
+
}
|
|
1262
|
+
const js = [
|
|
1263
|
+
`var css = ${JSON.stringify(css)};`,
|
|
1264
|
+
`(function(){ try { var s = document.createElement('style'); s.setAttribute('data-canopy-slider-css',''); s.textContent = css; document.head.appendChild(s); } catch (e) {} })();`,
|
|
1265
|
+
`export default css;`,
|
|
1266
|
+
].join("\n");
|
|
1267
|
+
return { contents: js, loader: "js" };
|
|
1268
|
+
});
|
|
1269
|
+
},
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
let cloverRuntimePromise = null;
|
|
1274
|
+
|
|
1275
|
+
function renameAnonymousChunks(scriptsDir) {
|
|
1276
|
+
try {
|
|
1277
|
+
const entries = fs
|
|
1278
|
+
.readdirSync(scriptsDir)
|
|
1279
|
+
.filter((name) => name.startsWith('canopy-chunk-') && name.endsWith('.js'));
|
|
1280
|
+
if (!entries.length) return;
|
|
1281
|
+
const replacements = [];
|
|
1282
|
+
for (const oldName of entries) {
|
|
1283
|
+
const newName = `canopy-shared-${oldName.slice('canopy-chunk-'.length)}`;
|
|
1284
|
+
if (newName === oldName) continue;
|
|
1285
|
+
const fromPath = path.join(scriptsDir, oldName);
|
|
1286
|
+
const toPath = path.join(scriptsDir, newName);
|
|
1287
|
+
try {
|
|
1288
|
+
fs.renameSync(fromPath, toPath);
|
|
1289
|
+
replacements.push({ from: oldName, to: newName });
|
|
1290
|
+
} catch (_) {}
|
|
1291
|
+
}
|
|
1292
|
+
if (!replacements.length) return;
|
|
1293
|
+
const targetFiles = fs
|
|
1294
|
+
.readdirSync(scriptsDir)
|
|
1295
|
+
.filter((name) => name.endsWith('.js'));
|
|
1296
|
+
for (const filename of targetFiles) {
|
|
1297
|
+
const filePath = path.join(scriptsDir, filename);
|
|
1298
|
+
let contents = '';
|
|
1299
|
+
try {
|
|
1300
|
+
contents = fs.readFileSync(filePath, 'utf8');
|
|
1301
|
+
} catch (_) {
|
|
1302
|
+
continue;
|
|
1303
|
+
}
|
|
1304
|
+
let changed = false;
|
|
1305
|
+
replacements.forEach(({ from, to }) => {
|
|
1306
|
+
if (contents.includes(from)) {
|
|
1307
|
+
contents = contents.split(from).join(to);
|
|
1308
|
+
changed = true;
|
|
1309
|
+
}
|
|
1310
|
+
});
|
|
1311
|
+
if (changed) {
|
|
1312
|
+
try {
|
|
1313
|
+
fs.writeFileSync(filePath, contents, 'utf8');
|
|
1314
|
+
} catch (_) {}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
} catch (_) {}
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// Clover dependencies use native BigInt literals, requiring ES2020 or newer.
|
|
1321
|
+
async function buildCloverHydrationRuntimes() {
|
|
1322
|
+
const esbuild = resolveEsbuild();
|
|
1323
|
+
if (!esbuild)
|
|
1324
|
+
throw new Error(
|
|
1325
|
+
"Clover hydration runtimes require esbuild. Install dependencies before building."
|
|
1326
|
+
);
|
|
1327
|
+
ensureDirSync(OUT_DIR);
|
|
1328
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1329
|
+
ensureDirSync(scriptsDir);
|
|
1330
|
+
const entryPoints = {
|
|
1331
|
+
viewer: path.join(__dirname, "../components/viewer-runtime-entry.js"),
|
|
1332
|
+
slider: path.join(__dirname, "../components/slider-runtime-entry.js"),
|
|
1333
|
+
"image-story": path.join(
|
|
1334
|
+
__dirname,
|
|
1335
|
+
"../components/image-story-runtime-entry.js",
|
|
1336
|
+
),
|
|
1337
|
+
};
|
|
1338
|
+
await esbuild.build({
|
|
1339
|
+
entryPoints,
|
|
1340
|
+
outdir: scriptsDir,
|
|
1341
|
+
entryNames: "canopy-[name]",
|
|
1342
|
+
chunkNames: "canopy-[name]-[hash]",
|
|
1343
|
+
bundle: true,
|
|
1344
|
+
platform: "browser",
|
|
1345
|
+
format: "esm",
|
|
1346
|
+
splitting: true,
|
|
1347
|
+
sourcemap: false,
|
|
1348
|
+
target: ["es2020"],
|
|
1349
|
+
logLevel: "silent",
|
|
1350
|
+
minify: true,
|
|
1351
|
+
define: { "process.env.NODE_ENV": '"production"' },
|
|
1352
|
+
plugins: [createReactShimPlugin(), createSliderCssInlinePlugin()],
|
|
1353
|
+
});
|
|
1354
|
+
renameAnonymousChunks(scriptsDir);
|
|
1355
|
+
try {
|
|
1356
|
+
const { logLine } = require("./log");
|
|
1357
|
+
const runtimeLabels = {
|
|
1358
|
+
viewer: "Viewer, Scroll, and Image runtime",
|
|
1359
|
+
slider: "Slider runtime",
|
|
1360
|
+
"image-story": "ImageStory runtime",
|
|
1361
|
+
};
|
|
1362
|
+
Object.keys(entryPoints).forEach((key) => {
|
|
1363
|
+
const file = `canopy-${key}.js`;
|
|
1364
|
+
try {
|
|
1365
|
+
const abs = path.join(scriptsDir, file);
|
|
1366
|
+
const st = fs.statSync(abs);
|
|
1367
|
+
const size = st && st.size ? st.size : 0;
|
|
1368
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1369
|
+
const rel = path.relative(process.cwd(), abs).split(path.sep).join("/");
|
|
1370
|
+
const label = runtimeLabels[key] ? ` – ${runtimeLabels[key]}` : "";
|
|
1371
|
+
logLine(`✓ Wrote ${rel}${kb}${label}`, "cyan");
|
|
1372
|
+
} catch (_) {}
|
|
1373
|
+
});
|
|
1374
|
+
} catch (_) {}
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
async function ensureClientRuntime() {
|
|
1378
|
+
if (!cloverRuntimePromise) {
|
|
1379
|
+
cloverRuntimePromise = buildCloverHydrationRuntimes();
|
|
1380
|
+
}
|
|
1381
|
+
return cloverRuntimePromise;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
function getCustomClientComponentEntries() {
|
|
1385
|
+
return Array.isArray(CUSTOM_CLIENT_COMPONENT_ENTRIES)
|
|
1386
|
+
? CUSTOM_CLIENT_COMPONENT_ENTRIES.slice()
|
|
1387
|
+
: [];
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
let customClientRuntimePromise = null;
|
|
1391
|
+
let customClientRuntimeSignature = "";
|
|
1392
|
+
|
|
1393
|
+
function computeClientRuntimeSignature(entries) {
|
|
1394
|
+
if (!entries || !entries.length) return "";
|
|
1395
|
+
const parts = entries
|
|
1396
|
+
.map((entry) => {
|
|
1397
|
+
const abs = entry && entry.path ? entry.path : "";
|
|
1398
|
+
let mtime = 0;
|
|
1399
|
+
if (abs) {
|
|
1400
|
+
try {
|
|
1401
|
+
const st = fs.statSync(abs);
|
|
1402
|
+
mtime = Math.floor(st.mtimeMs || 0);
|
|
1403
|
+
} catch (_) {}
|
|
1404
|
+
}
|
|
1405
|
+
return `${entry.name || ""}:${abs}:${mtime}`;
|
|
1406
|
+
})
|
|
1407
|
+
.sort();
|
|
1408
|
+
return parts.join("|");
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
async function buildCustomClientRuntime(entries) {
|
|
1412
|
+
const esbuild = resolveEsbuild();
|
|
1413
|
+
if (!esbuild) {
|
|
1414
|
+
throw new Error(
|
|
1415
|
+
"Custom client component hydration requires esbuild. Install dependencies before building."
|
|
1416
|
+
);
|
|
1417
|
+
}
|
|
1418
|
+
ensureDirSync(OUT_DIR);
|
|
1419
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1420
|
+
ensureDirSync(scriptsDir);
|
|
1421
|
+
const outFile = path.join(scriptsDir, "canopy-custom-components.js");
|
|
1422
|
+
const imports = entries
|
|
1423
|
+
.map((entry, index) => {
|
|
1424
|
+
const ident = `Component${index}`;
|
|
1425
|
+
return `import ${ident} from ${JSON.stringify(entry.path)}; registry.set(${JSON.stringify(
|
|
1426
|
+
entry.name
|
|
1427
|
+
)}, ${ident});`;
|
|
1428
|
+
})
|
|
1429
|
+
.join("\n");
|
|
1430
|
+
const runtimeSource = `
|
|
1431
|
+
import React from 'react';
|
|
1432
|
+
import { createRoot } from 'react-dom/client';
|
|
1433
|
+
const registry = new Map();
|
|
1434
|
+
${imports}
|
|
1435
|
+
function ready(fn){ if(document.readyState==='loading'){ document.addEventListener('DOMContentLoaded', fn, { once: true }); } else { fn(); } }
|
|
1436
|
+
function parseProps(node){ try { const script = node.querySelector('script[type="application/json"]'); if (!script) return {}; const text = script.textContent || '{}'; const data = JSON.parse(text); if (script.parentNode) { script.parentNode.removeChild(script); } return (data && typeof data === 'object') ? data : {}; } catch (_) { return {}; } }
|
|
1437
|
+
const roots = new WeakMap();
|
|
1438
|
+
function mount(node, Component){ if(!node || !Component) return; const props = parseProps(node); let root = roots.get(node); if(!root){ root = createRoot(node); roots.set(node, root); } root.render(React.createElement(Component, props)); }
|
|
1439
|
+
function hydrateAll(){
|
|
1440
|
+
const nodes = document.querySelectorAll('[data-canopy-client-component]');
|
|
1441
|
+
nodes.forEach((node) => {
|
|
1442
|
+
if (!node || node.__canopyClientMounted) return;
|
|
1443
|
+
const name = node.getAttribute('data-canopy-client-component');
|
|
1444
|
+
const Component = registry.get(name);
|
|
1445
|
+
if (!Component) return;
|
|
1446
|
+
mount(node, Component);
|
|
1447
|
+
node.__canopyClientMounted = true;
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
ready(hydrateAll);
|
|
1451
|
+
`;
|
|
1452
|
+
await esbuild.build({
|
|
1453
|
+
stdin: {
|
|
1454
|
+
contents: runtimeSource,
|
|
1455
|
+
resolveDir: process.cwd(),
|
|
1456
|
+
sourcefile: "canopy-custom-client-runtime.js",
|
|
1457
|
+
loader: "js",
|
|
1458
|
+
},
|
|
1459
|
+
outfile: outFile,
|
|
1460
|
+
bundle: true,
|
|
1461
|
+
platform: "browser",
|
|
1462
|
+
target: ["es2020"],
|
|
1463
|
+
format: "esm",
|
|
1464
|
+
sourcemap: false,
|
|
1465
|
+
minify: true,
|
|
1466
|
+
logLevel: "silent",
|
|
1467
|
+
// A site's client components may import this package by its 1.x name.
|
|
1468
|
+
plugins: [esbuildPackageNames(), createReactShimPlugin()],
|
|
1469
|
+
});
|
|
1470
|
+
try {
|
|
1471
|
+
const {logLine} = require("./log");
|
|
1472
|
+
let size = 0;
|
|
1473
|
+
try {
|
|
1474
|
+
const st = fs.statSync(outFile);
|
|
1475
|
+
size = st && st.size ? st.size : 0;
|
|
1476
|
+
} catch (_) {}
|
|
1477
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1478
|
+
const rel = path.relative(process.cwd(), outFile).split(path.sep).join("/");
|
|
1479
|
+
logLine(`✓ Wrote ${rel}${kb}`, "cyan");
|
|
1480
|
+
} catch (_) {}
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
async function ensureCustomClientRuntime() {
|
|
1484
|
+
const entries = getCustomClientComponentEntries();
|
|
1485
|
+
if (!entries.length) return null;
|
|
1486
|
+
const signature = computeClientRuntimeSignature(entries);
|
|
1487
|
+
if (customClientRuntimePromise && customClientRuntimeSignature === signature) {
|
|
1488
|
+
return customClientRuntimePromise;
|
|
1489
|
+
}
|
|
1490
|
+
customClientRuntimeSignature = signature;
|
|
1491
|
+
customClientRuntimePromise = buildCustomClientRuntime(entries);
|
|
1492
|
+
return customClientRuntimePromise;
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// Facets runtime: fetches /api/search/facets.json, picks a value per label (random from top 3),
|
|
1496
|
+
// and renders a Slider for each.
|
|
1497
|
+
async function ensureFacetsRuntime() {
|
|
1498
|
+
let esbuild = null;
|
|
1499
|
+
try {
|
|
1500
|
+
esbuild = require("../../ui/node_modules/esbuild");
|
|
1501
|
+
} catch (_) {
|
|
1502
|
+
try {
|
|
1503
|
+
esbuild = require("esbuild");
|
|
1504
|
+
} catch (_) {}
|
|
1505
|
+
}
|
|
1506
|
+
if (!esbuild) {
|
|
1507
|
+
throw new Error(
|
|
1508
|
+
"RelatedItems runtime bundling requires esbuild. Install dependencies before building."
|
|
1509
|
+
);
|
|
1510
|
+
}
|
|
1511
|
+
ensureDirSync(OUT_DIR);
|
|
1512
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1513
|
+
ensureDirSync(scriptsDir);
|
|
1514
|
+
const outFile = path.join(scriptsDir, "canopy-related-items.js");
|
|
1515
|
+
const entry = `
|
|
1516
|
+
function ready(fn){ if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',fn,{once:true}); else fn(); }
|
|
1517
|
+
function parseProps(el){ try{ const s=el.querySelector('script[type="application/json"]'); if(s) return JSON.parse(s.textContent||'{}'); }catch(_){ } return {}; }
|
|
1518
|
+
function buildSliderProps(iiifContent, options){
|
|
1519
|
+
const props = { iiifContent };
|
|
1520
|
+
if (options && typeof options === 'object') props.options = options;
|
|
1521
|
+
return props;
|
|
1522
|
+
}
|
|
1523
|
+
function rootBase(){
|
|
1524
|
+
try {
|
|
1525
|
+
var bp = (window && window.CANOPY_BASE_PATH) ? String(window.CANOPY_BASE_PATH) : '';
|
|
1526
|
+
if (bp && bp.charAt(bp.length - 1) === '/') return bp.slice(0, -1);
|
|
1527
|
+
return bp;
|
|
1528
|
+
} catch(_){ return ''; }
|
|
1529
|
+
}
|
|
1530
|
+
function pickRandomTop(values, topN){ const arr=(values||[]).slice().sort((a,b)=> (b.doc_count||0)-(a.doc_count||0) || String(a.value).localeCompare(String(b.value))); const n=Math.min(topN||3, arr.length); if(!n) return null; const i=Math.floor(Math.random()*n); return arr[i]; }
|
|
1531
|
+
function makeSliderPlaceholder(props){ try{ const el=document.createElement('div'); el.setAttribute('data-canopy-slider','1'); const s=document.createElement('script'); s.type='application/json'; s.textContent=JSON.stringify(props||{}); el.appendChild(s); return el; }catch(_){ return null; } }
|
|
1532
|
+
function slugify(s){ try{ return String(s||'').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,''); }catch(_){ return ''; } }
|
|
1533
|
+
function firstI18nString(x){ if(!x) return ''; if(typeof x==='string') return x; try{ const keys=Object.keys(x||{}); if(!keys.length) return ''; const arr=x[keys[0]]; if(Array.isArray(arr)&&arr.length) return String(arr[0]); }catch(_){ } return ''; }
|
|
1534
|
+
async function fetchManifestValues(iiif){ try{ const res = await fetch(iiif, { headers: { 'Accept': 'application/json' } }).catch(()=>null); if(!res||!res.ok) return null; const m = await res.json().catch(()=>null); if(!m) return null; const meta = Array.isArray(m.metadata)? m.metadata : []; const out = []; for (const entry of meta){ if(!entry) continue; const label = firstI18nString(entry.label); if(!label) continue; const vals = []; try { if (typeof entry.value === 'string') vals.push(entry.value); else { const obj = entry.value || {}; for (const k of Object.keys(obj)) { const arr = Array.isArray(obj[k]) ? obj[k] : []; for (const v of arr) if (v) vals.push(String(v)); } } } catch(_){} if (vals.length) out.push({ label, values: vals.map((v)=>({ value: v, valueSlug: slugify(v) })) }); }
|
|
1535
|
+
return out; } catch(_){ return null; } }
|
|
1536
|
+
async function getApiVersion(){
|
|
1537
|
+
try {
|
|
1538
|
+
const u = rootBase() + '/api/index.json';
|
|
1539
|
+
const res = await fetch(u).catch(()=>null);
|
|
1540
|
+
const j = res && res.ok ? await res.json().catch(()=>null) : null;
|
|
1541
|
+
return (j && typeof j.version === 'string') ? j.version : '';
|
|
1542
|
+
} catch(_) { return ''; }
|
|
1543
|
+
}
|
|
1544
|
+
ready(function(){
|
|
1545
|
+
const nodes = document.querySelectorAll('[data-canopy-related-items]');
|
|
1546
|
+
nodes.forEach(async (el) => {
|
|
1547
|
+
try {
|
|
1548
|
+
const props = parseProps(el) || {};
|
|
1549
|
+
const labelsFilter = Array.isArray(props.labels) ? props.labels.map(String) : null;
|
|
1550
|
+
const topN = Number(props.top || 3) || 3;
|
|
1551
|
+
const ver = await getApiVersion();
|
|
1552
|
+
const verQ = ver ? ('?v=' + encodeURIComponent(ver)) : '';
|
|
1553
|
+
const sliderOptions = (props && typeof props.sliderOptions === 'object') ? props.sliderOptions : null;
|
|
1554
|
+
const res = await fetch(rootBase() + '/api/search/facets.json' + verQ).catch(()=>null);
|
|
1555
|
+
if(!res || !res.ok) return;
|
|
1556
|
+
const json = await res.json().catch(()=>null);
|
|
1557
|
+
if(!Array.isArray(json)) return;
|
|
1558
|
+
// Build lookup for allowed labels and value slugs
|
|
1559
|
+
const allowedLabels = new Map(); // label -> { slug, values: Set(valueSlug) }
|
|
1560
|
+
json.forEach((f)=>{ if(!f||!f.label||!Array.isArray(f.values)) return; if(labelsFilter && !labelsFilter.includes(String(f.label))) return; const vs = new Set((f.values||[]).map((v)=> String((v && v.slug) || slugify(v && v.value)))); allowedLabels.set(String(f.label), { slug: f.slug || slugify(f.label), values: vs }); });
|
|
1561
|
+
|
|
1562
|
+
const manifestIiif = props.iiifContent && String(props.iiifContent);
|
|
1563
|
+
if (manifestIiif) {
|
|
1564
|
+
const mv = await fetchManifestValues(manifestIiif);
|
|
1565
|
+
if (!mv || !mv.length) return;
|
|
1566
|
+
// For each label present on the manifest, choose ONE value at random (from values also present in the index)
|
|
1567
|
+
mv.forEach((entry) => {
|
|
1568
|
+
const allow = allowedLabels.get(String(entry.label));
|
|
1569
|
+
if (!allow) return; // skip labels not indexed
|
|
1570
|
+
const candidates = (entry.values || []).filter((vv) => allow.values.has(vv.valueSlug));
|
|
1571
|
+
if (!candidates.length) return;
|
|
1572
|
+
const pick = candidates[Math.floor(Math.random() * candidates.length)];
|
|
1573
|
+
const wrap = document.createElement('div');
|
|
1574
|
+
wrap.setAttribute('data-facet-label', entry.label);
|
|
1575
|
+
wrap.setAttribute('class', 'canopy-slider');
|
|
1576
|
+
const ph = makeSliderPlaceholder(buildSliderProps(rootBase() + '/api/facet/' + (allow.slug) + '/' + pick.valueSlug + '.json' + verQ, sliderOptions));
|
|
1577
|
+
if (ph) wrap.appendChild(ph);
|
|
1578
|
+
el.appendChild(wrap);
|
|
1579
|
+
});
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
// Homepage/default mode: pick a random top value per allowed label
|
|
1584
|
+
const selected = [];
|
|
1585
|
+
json.forEach((f) => { if(!f || !f.label || !Array.isArray(f.values)) return; if(labelsFilter && !labelsFilter.includes(String(f.label))) return; const pick = pickRandomTop(f.values, topN); if(pick) selected.push({ label: f.label, labelSlug: f.slug || slugify(f.label), value: pick.value, valueSlug: (pick.slug) || slugify(pick.value) }); });
|
|
1586
|
+
selected.forEach((s) => {
|
|
1587
|
+
const wrap = document.createElement('div');
|
|
1588
|
+
wrap.setAttribute('data-facet-label', s.label);
|
|
1589
|
+
wrap.setAttribute('class', 'canopy-slider');
|
|
1590
|
+
const ph = makeSliderPlaceholder(buildSliderProps(rootBase() + '/api/facet/' + s.labelSlug + '/' + s.valueSlug + '.json' + verQ, sliderOptions));
|
|
1591
|
+
if (ph) wrap.appendChild(ph);
|
|
1592
|
+
el.appendChild(wrap);
|
|
1593
|
+
});
|
|
1594
|
+
} catch(_) { }
|
|
1595
|
+
});
|
|
1596
|
+
});
|
|
1597
|
+
`;
|
|
1598
|
+
const shim = {name: "facets-vanilla", setup() {}};
|
|
1599
|
+
try {
|
|
1600
|
+
await esbuild.build({
|
|
1601
|
+
stdin: {
|
|
1602
|
+
contents: entry,
|
|
1603
|
+
resolveDir: process.cwd(),
|
|
1604
|
+
sourcefile: "canopy-facets-entry.js",
|
|
1605
|
+
loader: "js",
|
|
1606
|
+
},
|
|
1607
|
+
outfile: outFile,
|
|
1608
|
+
platform: "browser",
|
|
1609
|
+
format: "iife",
|
|
1610
|
+
bundle: true,
|
|
1611
|
+
sourcemap: false,
|
|
1612
|
+
target: ["es2020"],
|
|
1613
|
+
logLevel: "silent",
|
|
1614
|
+
minify: true,
|
|
1615
|
+
plugins: [shim],
|
|
1616
|
+
});
|
|
1617
|
+
} catch (e) {
|
|
1618
|
+
const message = e && e.message ? e.message : e;
|
|
1619
|
+
throw new Error(`RelatedItems runtime build failed: ${message}`);
|
|
1620
|
+
}
|
|
1621
|
+
try {
|
|
1622
|
+
const {logLine} = require("./log");
|
|
1623
|
+
let size = 0;
|
|
1624
|
+
try {
|
|
1625
|
+
const st = fs.statSync(outFile);
|
|
1626
|
+
size = (st && st.size) || 0;
|
|
1627
|
+
} catch (_) {}
|
|
1628
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1629
|
+
const rel = path.relative(process.cwd(), outFile).split(path.sep).join("/");
|
|
1630
|
+
logLine(`✓ Wrote ${rel}${kb}`, "cyan");
|
|
1631
|
+
} catch (_) {}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
async function ensureSliderRuntime() {
|
|
1635
|
+
return ensureClientRuntime();
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
// Build a small React globals vendor for client-side React pages.
|
|
1639
|
+
async function ensureReactGlobals() {
|
|
1640
|
+
let esbuild = null;
|
|
1641
|
+
try {
|
|
1642
|
+
esbuild = require("../../ui/node_modules/esbuild");
|
|
1643
|
+
} catch (_) {
|
|
1644
|
+
try {
|
|
1645
|
+
esbuild = require("esbuild");
|
|
1646
|
+
} catch (_) {}
|
|
1647
|
+
}
|
|
1648
|
+
if (!esbuild)
|
|
1649
|
+
throw new Error(
|
|
1650
|
+
"React globals bundling requires esbuild. Install dependencies before building."
|
|
1651
|
+
);
|
|
1652
|
+
const {path} = require("../common");
|
|
1653
|
+
ensureDirSync(OUT_DIR);
|
|
1654
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1655
|
+
ensureDirSync(scriptsDir);
|
|
1656
|
+
const vendorFile = path.join(scriptsDir, "react-globals.js");
|
|
1657
|
+
const globalsEntry = `
|
|
1658
|
+
import * as React from 'react';
|
|
1659
|
+
import * as ReactDOM from 'react-dom';
|
|
1660
|
+
import * as ReactDOMClient from 'react-dom/client';
|
|
1661
|
+
(function(){ try{ window.React = React; window.ReactDOM = ReactDOM; window.ReactDOMClient = ReactDOMClient; }catch(e){} })();
|
|
1662
|
+
`;
|
|
1663
|
+
await esbuild.build({
|
|
1664
|
+
stdin: {
|
|
1665
|
+
contents: globalsEntry,
|
|
1666
|
+
resolveDir: process.cwd(),
|
|
1667
|
+
loader: "js",
|
|
1668
|
+
sourcefile: "react-globals-entry.js",
|
|
1669
|
+
},
|
|
1670
|
+
outfile: vendorFile,
|
|
1671
|
+
platform: "browser",
|
|
1672
|
+
format: "iife",
|
|
1673
|
+
bundle: true,
|
|
1674
|
+
sourcemap: false,
|
|
1675
|
+
target: ["es2020"],
|
|
1676
|
+
logLevel: "silent",
|
|
1677
|
+
minify: true,
|
|
1678
|
+
define: {"process.env.NODE_ENV": '"production"'},
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
async function ensureHeroRuntime() {
|
|
1683
|
+
let esbuild = null;
|
|
1684
|
+
try {
|
|
1685
|
+
esbuild = require("../ui/node_modules/esbuild");
|
|
1686
|
+
} catch (_) {
|
|
1687
|
+
try {
|
|
1688
|
+
esbuild = require("esbuild");
|
|
1689
|
+
} catch (_) {}
|
|
1690
|
+
}
|
|
1691
|
+
if (!esbuild)
|
|
1692
|
+
throw new Error(
|
|
1693
|
+
"Hero slider runtime bundling requires esbuild. Install dependencies before building."
|
|
1694
|
+
);
|
|
1695
|
+
ensureDirSync(OUT_DIR);
|
|
1696
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1697
|
+
ensureDirSync(scriptsDir);
|
|
1698
|
+
const outFile = path.join(scriptsDir, "canopy-hero-slider.js");
|
|
1699
|
+
const entryFile = path.join(
|
|
1700
|
+
__dirname,
|
|
1701
|
+
"..",
|
|
1702
|
+
"components",
|
|
1703
|
+
"hero-slider-runtime.js"
|
|
1704
|
+
);
|
|
1705
|
+
await esbuild.build({
|
|
1706
|
+
entryPoints: [entryFile],
|
|
1707
|
+
outfile: outFile,
|
|
1708
|
+
platform: "browser",
|
|
1709
|
+
format: "iife",
|
|
1710
|
+
bundle: true,
|
|
1711
|
+
sourcemap: false,
|
|
1712
|
+
target: ["es2020"],
|
|
1713
|
+
logLevel: "silent",
|
|
1714
|
+
minify: true,
|
|
1715
|
+
});
|
|
1716
|
+
try {
|
|
1717
|
+
const {logLine} = require("./log");
|
|
1718
|
+
let size = 0;
|
|
1719
|
+
try {
|
|
1720
|
+
const st = fs.statSync(outFile);
|
|
1721
|
+
size = (st && st.size) || 0;
|
|
1722
|
+
} catch (_) {}
|
|
1723
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1724
|
+
const rel = path.relative(process.cwd(), outFile).split(path.sep).join("/");
|
|
1725
|
+
logLine(`✓ Wrote ${rel}${kb}`, "cyan");
|
|
1726
|
+
} catch (_) {}
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
async function ensureTimelineRuntime() {
|
|
1730
|
+
let esbuild = null;
|
|
1731
|
+
try {
|
|
1732
|
+
esbuild = require("../ui/node_modules/esbuild");
|
|
1733
|
+
} catch (_) {
|
|
1734
|
+
try {
|
|
1735
|
+
esbuild = require("esbuild");
|
|
1736
|
+
} catch (_) {}
|
|
1737
|
+
}
|
|
1738
|
+
if (!esbuild)
|
|
1739
|
+
throw new Error(
|
|
1740
|
+
"Timeline runtime bundling requires esbuild. Install dependencies before building."
|
|
1741
|
+
);
|
|
1742
|
+
ensureDirSync(OUT_DIR);
|
|
1743
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1744
|
+
ensureDirSync(scriptsDir);
|
|
1745
|
+
const outFile = path.join(scriptsDir, "canopy-timeline.js");
|
|
1746
|
+
const entryFile = path.join(
|
|
1747
|
+
__dirname,
|
|
1748
|
+
"..",
|
|
1749
|
+
"components",
|
|
1750
|
+
"timeline-runtime.js"
|
|
1751
|
+
);
|
|
1752
|
+
const reactShim = reactGlobalShim();
|
|
1753
|
+
const rdomShim = `
|
|
1754
|
+
const ReactDOM = (typeof window !== 'undefined' && window.ReactDOM) || {};
|
|
1755
|
+
export default ReactDOM;
|
|
1756
|
+
export const render = ReactDOM.render;
|
|
1757
|
+
export const hydrate = ReactDOM.hydrate;
|
|
1758
|
+
export const findDOMNode = ReactDOM.findDOMNode;
|
|
1759
|
+
export const unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
|
|
1760
|
+
export const createPortal = ReactDOM.createPortal;
|
|
1761
|
+
export const flushSync = ReactDOM.flushSync;
|
|
1762
|
+
export const unstable_batchedUpdates = ReactDOM.unstable_batchedUpdates;
|
|
1763
|
+
export const unstable_renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer;
|
|
1764
|
+
`;
|
|
1765
|
+
const rdomClientShim = `
|
|
1766
|
+
const RDC = (typeof window !== 'undefined' && window.ReactDOMClient) || {};
|
|
1767
|
+
export const createRoot = RDC.createRoot;
|
|
1768
|
+
export const hydrateRoot = RDC.hydrateRoot;
|
|
1769
|
+
`;
|
|
1770
|
+
const plugin = {
|
|
1771
|
+
name: "canopy-react-shims-timeline",
|
|
1772
|
+
setup(build) {
|
|
1773
|
+
const ns = "canopy-timeline-shim";
|
|
1774
|
+
build.onResolve({filter: /^react$/}, () => ({path: "react", namespace: ns}));
|
|
1775
|
+
build.onResolve({filter: /^react-dom$/}, () => ({path: "react-dom", namespace: ns}));
|
|
1776
|
+
build.onResolve({filter: /^react-dom\/client$/}, () => ({
|
|
1777
|
+
path: "react-dom-client",
|
|
1778
|
+
namespace: ns,
|
|
1779
|
+
}));
|
|
1780
|
+
build.onLoad({filter: /^react$/, namespace: ns}, () => ({
|
|
1781
|
+
contents: reactShim,
|
|
1782
|
+
loader: "js",
|
|
1783
|
+
}));
|
|
1784
|
+
build.onLoad({filter: /^react-dom$/, namespace: ns}, () => ({
|
|
1785
|
+
contents: rdomShim,
|
|
1786
|
+
loader: "js",
|
|
1787
|
+
}));
|
|
1788
|
+
build.onLoad({filter: /^react-dom-client$/, namespace: ns}, () => ({
|
|
1789
|
+
contents: rdomClientShim,
|
|
1790
|
+
loader: "js",
|
|
1791
|
+
}));
|
|
1792
|
+
},
|
|
1793
|
+
};
|
|
1794
|
+
await esbuild.build({
|
|
1795
|
+
entryPoints: [entryFile],
|
|
1796
|
+
outfile: outFile,
|
|
1797
|
+
platform: "browser",
|
|
1798
|
+
format: "iife",
|
|
1799
|
+
bundle: true,
|
|
1800
|
+
sourcemap: false,
|
|
1801
|
+
target: ["es2020"],
|
|
1802
|
+
logLevel: "silent",
|
|
1803
|
+
minify: true,
|
|
1804
|
+
plugins: [plugin],
|
|
1805
|
+
loader: {
|
|
1806
|
+
".png": "dataurl",
|
|
1807
|
+
".svg": "dataurl",
|
|
1808
|
+
".gif": "dataurl",
|
|
1809
|
+
},
|
|
1810
|
+
});
|
|
1811
|
+
try {
|
|
1812
|
+
const {logLine} = require("./log");
|
|
1813
|
+
let size = 0;
|
|
1814
|
+
try {
|
|
1815
|
+
const st = fs.statSync(outFile);
|
|
1816
|
+
size = (st && st.size) || 0;
|
|
1817
|
+
} catch (_) {}
|
|
1818
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1819
|
+
const rel = path.relative(process.cwd(), outFile).split(path.sep).join("/");
|
|
1820
|
+
logLine(`✓ Wrote ${rel}${kb}`, "cyan");
|
|
1821
|
+
} catch (_) {}
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
async function ensureMapRuntime() {
|
|
1825
|
+
let esbuild = null;
|
|
1826
|
+
try {
|
|
1827
|
+
esbuild = require("../ui/node_modules/esbuild");
|
|
1828
|
+
} catch (_) {
|
|
1829
|
+
try {
|
|
1830
|
+
esbuild = require("esbuild");
|
|
1831
|
+
} catch (_) {}
|
|
1832
|
+
}
|
|
1833
|
+
if (!esbuild)
|
|
1834
|
+
throw new Error(
|
|
1835
|
+
"Map runtime bundling requires esbuild. Install dependencies before building."
|
|
1836
|
+
);
|
|
1837
|
+
ensureDirSync(OUT_DIR);
|
|
1838
|
+
const scriptsDir = path.join(OUT_DIR, "scripts");
|
|
1839
|
+
ensureDirSync(scriptsDir);
|
|
1840
|
+
const outFile = path.join(scriptsDir, "canopy-map.js");
|
|
1841
|
+
const entryFile = path.join(
|
|
1842
|
+
__dirname,
|
|
1843
|
+
"..",
|
|
1844
|
+
"components",
|
|
1845
|
+
"map-runtime.js"
|
|
1846
|
+
);
|
|
1847
|
+
const reactShim = reactGlobalShim();
|
|
1848
|
+
const rdomShim = `
|
|
1849
|
+
const ReactDOM = (typeof window !== 'undefined' && window.ReactDOM) || {};
|
|
1850
|
+
export default ReactDOM;
|
|
1851
|
+
export const render = ReactDOM.render;
|
|
1852
|
+
export const hydrate = ReactDOM.hydrate;
|
|
1853
|
+
export const findDOMNode = ReactDOM.findDOMNode;
|
|
1854
|
+
export const unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
|
|
1855
|
+
export const createPortal = ReactDOM.createPortal;
|
|
1856
|
+
export const flushSync = ReactDOM.flushSync;
|
|
1857
|
+
export const unstable_batchedUpdates = ReactDOM.unstable_batchedUpdates;
|
|
1858
|
+
export const unstable_renderSubtreeIntoContainer = ReactDOM.unstable_renderSubtreeIntoContainer;
|
|
1859
|
+
`;
|
|
1860
|
+
const rdomClientShim = `
|
|
1861
|
+
const RDC = (typeof window !== 'undefined' && window.ReactDOMClient) || {};
|
|
1862
|
+
export const createRoot = RDC.createRoot;
|
|
1863
|
+
export const hydrateRoot = RDC.hydrateRoot;
|
|
1864
|
+
`;
|
|
1865
|
+
const plugin = {
|
|
1866
|
+
name: "canopy-react-shims-map",
|
|
1867
|
+
setup(build) {
|
|
1868
|
+
const ns = "canopy-map-shim";
|
|
1869
|
+
build.onResolve({filter: /^react$/}, () => ({path: "react", namespace: ns}));
|
|
1870
|
+
build.onResolve({filter: /^react-dom$/}, () => ({path: "react-dom", namespace: ns}));
|
|
1871
|
+
build.onResolve({filter: /^react-dom\/client$/}, () => ({
|
|
1872
|
+
path: "react-dom-client",
|
|
1873
|
+
namespace: ns,
|
|
1874
|
+
}));
|
|
1875
|
+
build.onLoad({filter: /^react$/, namespace: ns}, () => ({
|
|
1876
|
+
contents: reactShim,
|
|
1877
|
+
loader: "js",
|
|
1878
|
+
}));
|
|
1879
|
+
build.onLoad({filter: /^react-dom$/, namespace: ns}, () => ({
|
|
1880
|
+
contents: rdomShim,
|
|
1881
|
+
loader: "js",
|
|
1882
|
+
}));
|
|
1883
|
+
build.onLoad({filter: /^react-dom-client$/, namespace: ns}, () => ({
|
|
1884
|
+
contents: rdomClientShim,
|
|
1885
|
+
loader: "js",
|
|
1886
|
+
}));
|
|
1887
|
+
},
|
|
1888
|
+
};
|
|
1889
|
+
await esbuild.build({
|
|
1890
|
+
entryPoints: [entryFile],
|
|
1891
|
+
outfile: outFile,
|
|
1892
|
+
platform: "browser",
|
|
1893
|
+
format: "iife",
|
|
1894
|
+
bundle: true,
|
|
1895
|
+
sourcemap: false,
|
|
1896
|
+
target: ["es2020"],
|
|
1897
|
+
logLevel: "silent",
|
|
1898
|
+
minify: true,
|
|
1899
|
+
plugins: [plugin],
|
|
1900
|
+
loader: {
|
|
1901
|
+
".png": "dataurl",
|
|
1902
|
+
".svg": "dataurl",
|
|
1903
|
+
".gif": "dataurl",
|
|
1904
|
+
},
|
|
1905
|
+
});
|
|
1906
|
+
try {
|
|
1907
|
+
const {logLine} = require("./log");
|
|
1908
|
+
let size = 0;
|
|
1909
|
+
try {
|
|
1910
|
+
const st = fs.statSync(outFile);
|
|
1911
|
+
size = (st && st.size) || 0;
|
|
1912
|
+
} catch (_) {}
|
|
1913
|
+
const kb = size ? ` (${(size / 1024).toFixed(1)} KB)` : "";
|
|
1914
|
+
const rel = path.relative(process.cwd(), outFile).split(path.sep).join("/");
|
|
1915
|
+
logLine(`✓ Wrote ${rel}${kb}`, "cyan");
|
|
1916
|
+
} catch (_) {}
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
module.exports = {
|
|
1920
|
+
extractTitle,
|
|
1921
|
+
extractHeadings,
|
|
1922
|
+
extractPlainText,
|
|
1923
|
+
extractMarkdownSummary,
|
|
1924
|
+
extractSearchText,
|
|
1925
|
+
isReservedFile,
|
|
1926
|
+
parseFrontmatter,
|
|
1927
|
+
compileMdxFile,
|
|
1928
|
+
compileMdxToComponent,
|
|
1929
|
+
loadCustomLayout,
|
|
1930
|
+
loadAppWrapper,
|
|
1931
|
+
loadUiComponents,
|
|
1932
|
+
ensureClientRuntime,
|
|
1933
|
+
ensureSliderRuntime,
|
|
1934
|
+
ensureTimelineRuntime,
|
|
1935
|
+
ensureMapRuntime,
|
|
1936
|
+
ensureHeroRuntime,
|
|
1937
|
+
ensureFacetsRuntime,
|
|
1938
|
+
ensureReactGlobals,
|
|
1939
|
+
ensureCustomClientRuntime,
|
|
1940
|
+
resetMdxCaches: function () {
|
|
1941
|
+
try {
|
|
1942
|
+
DIR_LAYOUTS.clear();
|
|
1943
|
+
} catch (_) {}
|
|
1944
|
+
APP_WRAPPER = null;
|
|
1945
|
+
UI_COMPONENTS = null;
|
|
1946
|
+
UI_COMPONENTS_PATH = "";
|
|
1947
|
+
UI_COMPONENTS_MTIME = 0;
|
|
1948
|
+
MERGED_UI_COMPONENTS = null;
|
|
1949
|
+
MERGED_UI_KEY = "";
|
|
1950
|
+
CUSTOM_MDX_COMPONENTS = null;
|
|
1951
|
+
CUSTOM_MDX_SIGNATURE = "";
|
|
1952
|
+
CUSTOM_CLIENT_COMPONENT_ENTRIES = [];
|
|
1953
|
+
try {
|
|
1954
|
+
CUSTOM_CLIENT_COMPONENT_PLACEHOLDERS.clear();
|
|
1955
|
+
} catch (_) {
|
|
1956
|
+
CUSTOM_CLIENT_COMPONENT_PLACEHOLDERS = new Map();
|
|
1957
|
+
}
|
|
1958
|
+
try {
|
|
1959
|
+
SERVER_COMPONENT_CACHE.clear();
|
|
1960
|
+
} catch (_) {
|
|
1961
|
+
SERVER_COMPONENT_CACHE = new Map();
|
|
1962
|
+
}
|
|
1963
|
+
customClientRuntimePromise = null;
|
|
1964
|
+
customClientRuntimeSignature = "";
|
|
1965
|
+
cloverRuntimePromise = null;
|
|
1966
|
+
},
|
|
1967
|
+
};
|