@ox-content/vite-plugin-svelte 3.1.3 → 3.1.5

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/index.cjs CHANGED
@@ -28,12 +28,6 @@ let fs = require("fs");
28
28
  fs = __toESM(fs, 1);
29
29
  let path = require("path");
30
30
  path = __toESM(path, 1);
31
- let node_path = require("node:path");
32
- node_path = __toESM(node_path, 1);
33
- let node_fs = require("node:fs");
34
- node_fs = __toESM(node_fs, 1);
35
- let node_fs_promises = require("node:fs/promises");
36
- node_fs_promises = __toESM(node_fs_promises, 1);
37
31
  //#region src/transform.ts
38
32
  const COMPONENT_REGEX = /<([A-Z][a-zA-Z0-9]*)\s*([^>]*?)\s*(?:\/>|>([\s\S]*?)<\/\1>)/g;
39
33
  const PROP_REGEX = /([a-zA-Z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|{([^}]*)}|\[([^\]]*)\]))?/g;
@@ -794,7 +788,7 @@ function findMdxIslandRanges(html) {
794
788
  let match;
795
789
  while ((match = openRe.exec(html)) !== null) {
796
790
  const tag = match[1];
797
- const name = decodeHtmlAttr$1(match[3] ?? "");
791
+ const name = decodeHtmlAttr(match[3] ?? "");
798
792
  if (!name) continue;
799
793
  const openStart = match.index;
800
794
  const openEnd = match.index + match[0].length;
@@ -849,7 +843,7 @@ function indexOfTagOpen(html, openNeedle, from) {
849
843
  }
850
844
  function matchAttr(attrs, name) {
851
845
  const match = new RegExp(`\\b${name}="([^"]*)"`, "i").exec(attrs);
852
- return match?.[1] === void 0 ? void 0 : decodeHtmlAttr$1(match[1]);
846
+ return match?.[1] === void 0 ? void 0 : decodeHtmlAttr(match[1]);
853
847
  }
854
848
  function readMdxIslandPayload(island) {
855
849
  const fromAttr = island.propsAttr ? tryParseJson(island.propsAttr) : void 0;
@@ -894,7 +888,7 @@ function tryParseJson(value) {
894
888
  return;
895
889
  }
896
890
  }
897
- function decodeHtmlAttr$1(value) {
891
+ function decodeHtmlAttr(value) {
898
892
  return value.replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
899
893
  }
900
894
  function assertSvelteComponentName(name, filePath) {
@@ -1105,248 +1099,72 @@ function toPascalCase(str) {
1105
1099
  //#endregion
1106
1100
  //#region src/html-host-default-renderer.ts
1107
1101
  const defaultRenderSvelteHtmlComponent = async (component, props, slotHtml) => {
1108
- const [{ render }, { createRawSnippet }] = await Promise.all([import("svelte/server"), import("svelte")]);
1109
- const rendered = render(component, { props: slotHtml ? {
1110
- ...props,
1111
- children: createRawSnippet(() => ({ render: () => slotHtml }))
1112
- } : props });
1113
- return rendered.html ?? rendered.body ?? "";
1102
+ return renderWithSvelteRuntime(await loadDefaultSvelteRuntime(), component, props, slotHtml);
1114
1103
  };
1115
- //#endregion
1116
- //#region src/html-host.ts
1117
- const ISLAND_JSON_SCRIPT = /^\s*<script type="application\/json">[\s\S]*?<\/script>/;
1118
- async function renderSvelteHtmlHost(input) {
1119
- const diagnostics = [];
1120
- const modules = resolveHostModules(input, diagnostics);
1121
- const byName = new Map(modules.map((module) => [module.name, module]));
1122
- const cache = /* @__PURE__ */ new Map();
1123
- const renderComponent = input.renderComponent ?? defaultRenderSvelteHtmlComponent;
1124
- return {
1125
- html: markClientModules(await (0, _ox_content_vite_plugin.applyIslandSsrHtml)(input.html, async (name, props, _filePath, slotHtml) => {
1126
- const module = byName.get(name);
1127
- if (!module) {
1128
- diagnostics.push({
1129
- code: "missing-component",
1130
- message: `Svelte island "${name}" is not registered for this document.`,
1131
- documentPath: input.documentPath,
1132
- component: name
1133
- });
1134
- return slotHtml ?? "";
1135
- }
1136
- const component = await loadComponent(input, module, cache, diagnostics);
1137
- if (!component) return slotHtml ?? "";
1138
- try {
1139
- return await renderComponent(component, props, slotHtml || void 0, {
1140
- component: name,
1141
- moduleId: module.serverModuleId,
1142
- documentPath: input.documentPath
1143
- });
1144
- } catch (error) {
1145
- diagnostics.push({
1146
- code: "ssr-failed",
1147
- message: `Svelte island "${name}" failed to render: ${errorMessage(error)}`,
1148
- documentPath: input.documentPath,
1149
- component: name,
1150
- moduleId: module.serverModuleId
1151
- });
1152
- return slotHtml ?? "";
1153
- }
1154
- }, input.documentPath, modules.map((module) => module.name)), modules),
1155
- modules,
1156
- clientModules: modules.flatMap((module) => module.clientModuleId ? [{
1157
- name: module.name,
1158
- moduleId: module.clientModuleId,
1159
- exportName: module.exportName
1160
- }] : []),
1161
- diagnostics
1104
+ function createSvelteHtmlHostComponentRenderer(loadModule) {
1105
+ let pending;
1106
+ return async (component, props, slotHtml) => {
1107
+ pending ??= loadSvelteRuntimeFromHost(loadModule);
1108
+ return renderWithSvelteRuntime(await pending, component, props, slotHtml);
1162
1109
  };
1163
1110
  }
1164
- function createSvelteHtmlHostHydrate(input) {
1165
- return (element, props) => {
1166
- const name = element.dataset.oxIsland;
1167
- if (!name) return;
1168
- const component = componentFromRegistry(input.components, name);
1169
- if (!component) return;
1170
- const slotHtml = readIslandSlotHtml(element);
1171
- element.innerHTML = "";
1172
- return input.render(component, props, element, slotHtml || void 0);
1173
- };
1174
- }
1175
- function resolveHostModules(input, diagnostics) {
1176
- const names = (0, _ox_content_vite_plugin.collectMdxIslandNamesFromHtml)(input.html);
1177
- const local = (0, _ox_content_vite_plugin.resolveDocumentComponentImports)({
1178
- imports: input.imports ?? [],
1179
- documentPath: input.documentPath,
1180
- contentRoot: input.contentRoot ?? (0, _ox_content_vite_plugin.resolveContentRootPath)(input),
1181
- srcDir: input.srcDir
1182
- });
1183
- for (const diagnostic of local.diagnostics) diagnostics.push({
1184
- ...diagnostic,
1185
- documentPath: input.documentPath
1186
- });
1187
- const localBindings = new Map(local.bindings.map((binding) => [binding.localName, binding]));
1188
- const modules = [];
1189
- for (const name of names) {
1190
- const localBinding = localBindings.get(name);
1191
- const serverModuleId = localBinding ? localBinding.resolvedPath : componentPath(input.components ?? {}, name, input.root);
1192
- if (!serverModuleId) {
1193
- diagnostics.push({
1194
- code: "missing-component",
1195
- message: `Svelte island "${name}" is not registered for this document.`,
1196
- documentPath: input.documentPath,
1197
- component: name
1198
- });
1199
- continue;
1200
- }
1201
- const module = {
1202
- name,
1203
- serverModuleId,
1204
- exportName: localBinding?.imported ?? "default",
1205
- source: localBinding ? "document" : "components"
1206
- };
1207
- const clientModuleId = input.resolveClientModule?.(module, { documentPath: input.documentPath });
1208
- modules.push(clientModuleId ? {
1209
- ...module,
1210
- clientModuleId
1211
- } : module);
1212
- }
1213
- return modules;
1214
- }
1215
- async function loadComponent(input, module, cache, diagnostics) {
1216
- let pending = cache.get(module.serverModuleId);
1217
- if (!pending) {
1218
- pending = input.loadModule(module.serverModuleId);
1219
- cache.set(module.serverModuleId, pending);
1220
- }
1221
- let exports;
1222
- try {
1223
- exports = await pending;
1224
- } catch (error) {
1225
- diagnostics.push({
1226
- code: "module-load-failed",
1227
- message: `Svelte island module "${module.serverModuleId}" failed to load: ${errorMessage(error)}`,
1228
- documentPath: input.documentPath,
1229
- component: module.name,
1230
- moduleId: module.serverModuleId
1231
- });
1232
- return;
1233
- }
1234
- const component = exportedValue(exports, module.exportName);
1235
- if (!component) diagnostics.push({
1236
- code: "missing-export",
1237
- message: `Svelte island "${module.name}" could not find export "${module.exportName}".`,
1238
- documentPath: input.documentPath,
1239
- component: module.name,
1240
- moduleId: module.serverModuleId
1241
- });
1242
- return component == null ? void 0 : component;
1243
- }
1244
- function componentPath(components, name, root = process.cwd()) {
1245
- const specifier = components[name];
1246
- if (!specifier) return;
1247
- return node_path.default.resolve(root, specifier.replace(/^\.\//, ""));
1248
- }
1249
- function exportedValue(exports, exportName) {
1250
- if (!exports || typeof exports !== "object") return;
1251
- return exports[exportName];
1252
- }
1253
- function componentFromRegistry(registry, name) {
1254
- return isReadonlyMap(registry) ? registry.get(name) : registry[name];
1255
- }
1256
- function isReadonlyMap(value) {
1257
- return typeof value.get === "function";
1258
- }
1259
- function readIslandSlotHtml(element) {
1260
- const fromAttr = element.dataset.oxContent;
1261
- if (fromAttr) return fromAttr;
1262
- if (element.dataset.oxSsr === "true") return "";
1263
- return element.innerHTML.replace(ISLAND_JSON_SCRIPT, "");
1264
- }
1265
- function markClientModules(html, modules) {
1266
- const clientModules = new Map(modules.filter((module) => module.clientModuleId).map((module) => [module.name, module]));
1267
- if (clientModules.size === 0) return html;
1268
- return html.replace(/<(div|span)\b([^>]*\bdata-ox-island="([^"]+)"[^>]*)>/gi, (openTag, _tag, _attrs, encodedName) => {
1269
- const module = clientModules.get(decodeHtmlAttr(encodedName));
1270
- if (!module?.clientModuleId) return openTag;
1271
- const attrs = [];
1272
- if (!hasAttr(openTag, "data-ox-module")) attrs.push(`data-ox-module="${escapeDoubleQuotedAttr(module.clientModuleId)}"`);
1273
- if (!hasAttr(openTag, "data-ox-export")) attrs.push(`data-ox-export="${escapeDoubleQuotedAttr(module.exportName)}"`);
1274
- return attrs.length === 0 ? openTag : openTag.replace(/>$/, ` ${attrs.join(" ")}>`);
1275
- });
1111
+ async function loadDefaultSvelteRuntime() {
1112
+ const [server, shared] = await Promise.all([import("svelte/server"), import("svelte")]);
1113
+ return resolveSvelteRuntime(server, shared);
1276
1114
  }
1277
- function escapeDoubleQuotedAttr(value) {
1278
- return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1115
+ async function loadSvelteRuntimeFromHost(loadModule) {
1116
+ const [server, shared] = await Promise.all([loadModule("svelte/server"), loadModule("svelte")]);
1117
+ return resolveSvelteRuntime(server, shared);
1279
1118
  }
1280
- function decodeHtmlAttr(value) {
1281
- return value.replaceAll("&quot;", "\"").replaceAll("&#39;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1119
+ function renderWithSvelteRuntime(runtime, component, props, slotHtml) {
1120
+ const componentProps = slotHtml ? {
1121
+ ...props,
1122
+ children: runtime.createRawSnippet(() => ({ render: () => slotHtml }))
1123
+ } : props;
1124
+ const rendered = runtime.render(component, { props: componentProps });
1125
+ return {
1126
+ html: rendered.html ?? rendered.body ?? "",
1127
+ head: rendered.head
1128
+ };
1282
1129
  }
1283
- function hasAttr(openTag, name) {
1284
- return new RegExp(`\\s${name}(?:\\s*=|\\s|>|$)`, "i").test(openTag);
1130
+ function resolveSvelteRuntime(server, shared) {
1131
+ return {
1132
+ render: runtimeFunction(server, "render", "svelte/server"),
1133
+ createRawSnippet: runtimeFunction(shared, "createRawSnippet", "svelte")
1134
+ };
1285
1135
  }
1286
- function errorMessage(error) {
1287
- return error instanceof Error ? error.message : String(error);
1136
+ function runtimeFunction(module, name, moduleId) {
1137
+ const value = module && typeof module === "object" ? module[name] : void 0;
1138
+ if (typeof value !== "function") throw new Error(`Svelte HTML host renderer could not load ${moduleId}.${name}.`);
1139
+ return value;
1288
1140
  }
1289
1141
  //#endregion
1290
- //#region src/html-host-registry-paths.ts
1291
- function toSvelteHtmlHostClientModuleId(moduleId, root = process.cwd()) {
1292
- const [pathname, suffix = ""] = splitModuleSuffix(moduleId);
1293
- if (isBareSpecifier(pathname) || pathname.startsWith("/@fs/")) return `${pathname}${suffix}`;
1294
- const rootPath = node_path.default.resolve(root);
1295
- const realRoot = existingRealpath(rootPath) ?? rootPath;
1296
- const absolute = node_path.default.isAbsolute(pathname) ? node_path.default.resolve(pathname) : node_path.default.resolve(rootPath, pathname);
1297
- const realAbsolute = existingRealpath(absolute);
1298
- const isInsideRealRoot = realAbsolute ? isInsideRoot(realAbsolute, realRoot) : false;
1299
- const isInsideLexicalRoot = isInsideRoot(absolute, rootPath);
1300
- if (node_path.default.isAbsolute(pathname) && !isInsideRealRoot && !isInsideLexicalRoot) return node_fs.default.existsSync(pathname) ? `/@fs${toPosixPath(pathname)}${suffix}` : `${toPosixPath(pathname)}${suffix}`;
1301
- const relativeRoot = isInsideRealRoot ? realRoot : rootPath;
1302
- const relativePath = isInsideRealRoot && realAbsolute ? realAbsolute : absolute;
1303
- return `/${node_path.default.relative(relativeRoot, relativePath).replace(/\\/g, "/")}${suffix}`;
1304
- }
1305
- function resolveDocumentPath(documentPath, root) {
1306
- return node_path.default.isAbsolute(documentPath) ? (0, _ox_content_vite_plugin.stripViteQuery)(documentPath) : node_path.default.resolve(root, (0, _ox_content_vite_plugin.stripViteQuery)(documentPath));
1307
- }
1308
- function resolveWatchFile(file, root) {
1309
- return node_path.default.isAbsolute(file) ? (0, _ox_content_vite_plugin.stripViteQuery)(file) : node_path.default.resolve(root, (0, _ox_content_vite_plugin.stripViteQuery)(file));
1310
- }
1311
- function shouldInvalidate(file, root, srcDir, watchFiles, extraWatchFiles) {
1312
- const changed = node_path.default.resolve(file);
1313
- if (watchFiles.some((watchFile) => changed === watchFile)) return true;
1314
- if (extraWatchFiles?.some((watchFile) => changed === resolveWatchFile(watchFile, root))) return true;
1315
- return isInsideRoot(changed, node_path.default.resolve(root, srcDir ?? "content"));
1316
- }
1317
- function splitModuleSuffix(moduleId) {
1318
- const match = /[?#]/u.exec(moduleId);
1319
- return match ? [moduleId.slice(0, match.index), moduleId.slice(match.index)] : [moduleId];
1320
- }
1321
- function isBareSpecifier(moduleId) {
1322
- return !moduleId.startsWith(".") && !moduleId.startsWith("/") && !moduleId.includes("\\");
1323
- }
1324
- function isInsideRoot(file, root) {
1325
- const relative = node_path.default.relative(node_path.default.resolve(root), node_path.default.resolve(file));
1326
- return relative === "" || !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
1327
- }
1328
- function existingRealpath(file) {
1329
- try {
1330
- return node_fs.default.realpathSync.native(file);
1331
- } catch {
1332
- return;
1333
- }
1142
+ //#region src/html-host.ts
1143
+ async function renderSvelteHtmlHost(input) {
1144
+ const resolveClientModule = input.resolveClientModule;
1145
+ return await (0, _ox_content_vite_plugin.renderHtmlHost)({
1146
+ ...input,
1147
+ frameworkName: "Svelte",
1148
+ renderComponent: input.renderComponent ?? defaultRenderSvelteHtmlComponent,
1149
+ resolveClientModule
1150
+ });
1334
1151
  }
1335
- function toPosixPath(file) {
1336
- return file.replace(/\\/g, "/");
1152
+ function createSvelteHtmlHostHydrate(input) {
1153
+ return (0, _ox_content_vite_plugin.createHtmlHostHydrate)(input);
1337
1154
  }
1338
1155
  //#endregion
1339
1156
  //#region src/html-host-renderer.ts
1340
1157
  var SvelteHtmlHostRenderError = class extends Error {
1341
1158
  diagnostics;
1342
1159
  constructor(diagnostics) {
1343
- super(formatSvelteHtmlHostDiagnostics(diagnostics));
1160
+ super((0, _ox_content_vite_plugin.formatHtmlHostDiagnostics)(diagnostics));
1344
1161
  this.name = "SvelteHtmlHostRenderError";
1345
1162
  this.diagnostics = [...diagnostics];
1346
1163
  }
1347
1164
  };
1348
1165
  function createSvelteHtmlHostRenderer(input) {
1349
1166
  const policy = input.diagnostics ?? "throw";
1167
+ const defaultRenderComponent = createSvelteHtmlHostComponentRenderer(input.loadModule);
1350
1168
  return async (html, context) => {
1351
1169
  const root = context.root ?? input.root;
1352
1170
  const result = await renderSvelteHtmlHost({
@@ -1358,288 +1176,33 @@ function createSvelteHtmlHostRenderer(input) {
1358
1176
  imports: context.imports,
1359
1177
  components: context.components ?? input.components,
1360
1178
  loadModule: input.loadModule,
1361
- renderComponent: context.renderComponent ?? input.renderComponent,
1362
- resolveClientModule: context.resolveClientModule ?? input.resolveClientModule ?? ((module) => toSvelteHtmlHostClientModuleId(module.serverModuleId, root))
1179
+ renderComponent: context.renderComponent ?? input.renderComponent ?? defaultRenderComponent,
1180
+ resolveClientModule: context.resolveClientModule ?? input.resolveClientModule ?? ((module) => (0, _ox_content_vite_plugin.toHtmlHostClientModuleId)(module.serverModuleId, root))
1363
1181
  });
1364
1182
  if (policy === "throw" && result.diagnostics.length > 0) throw new SvelteHtmlHostRenderError(result.diagnostics);
1365
1183
  return result;
1366
1184
  };
1367
1185
  }
1368
- function formatSvelteHtmlHostDiagnostics(diagnostics) {
1369
- if (diagnostics.length === 0) return "Svelte HTML host rendering failed.";
1370
- return diagnostics.map((diagnostic) => {
1371
- const details = [
1372
- diagnostic.documentPath,
1373
- diagnostic.component && `component ${diagnostic.component}`,
1374
- diagnostic.moduleId && `module ${diagnostic.moduleId}`
1375
- ].filter(Boolean);
1376
- return `${diagnostic.code}: ${diagnostic.message}${details.length > 0 ? ` (${details.join(", ")})` : ""}`;
1377
- }).join("\n");
1378
- }
1379
- //#endregion
1380
- //#region src/html-host-collection-documents.ts
1381
- function createSvelteHtmlHostCollectionDocuments(input = {}) {
1382
- return (context) => resolveSvelteHtmlHostCollectionDocuments(input, context);
1383
- }
1384
- async function resolveSvelteHtmlHostCollectionDocuments(input, context) {
1385
- const options = resolveCollectionManifestOptions((0, _ox_content_vite_plugin.customHostOxContentOptions)(input.oxContent ?? {}));
1386
- if (!options.collections.enabled) return [];
1387
- const manifest = await (0, _ox_content_vite_plugin.buildCollectionManifest)(context.root, options);
1388
- const names = resolveCollectionNames(input.collections, options.collections);
1389
- const documents = /* @__PURE__ */ new Map();
1390
- for (const name of names) for (const entry of manifest.collections[name] ?? []) {
1391
- const document = await resolveCollectionDocument(context.root, options.srcDir, name, entry);
1392
- if (!document) continue;
1393
- if (input.select && !await input.select(document, context)) continue;
1394
- documents.set(document.documentPath, document);
1395
- }
1396
- return [...documents.values()];
1397
- }
1398
- function resolveCollectionManifestOptions(oxContent) {
1399
- const collections = withoutCollectionInclude((0, _ox_content_vite_plugin.resolveCollectionsOptions)(oxContent.collections));
1400
- return {
1401
- srcDir: oxContent.srcDir ?? "content",
1402
- outDir: oxContent.outDir ?? "dist",
1403
- base: oxContent.base ?? "/",
1404
- extensions: (0, _ox_content_vite_plugin.normalizeMarkdownExtensions)(oxContent.extensions),
1405
- collections,
1406
- permalinks: (0, _ox_content_vite_plugin.resolvePermalinksOptions)(oxContent.permalinks),
1407
- cascade: (0, _ox_content_vite_plugin.resolveCascadeOptions)(oxContent.cascade),
1408
- gfm: oxContent.gfm ?? true,
1409
- mdx: oxContent.mdx,
1410
- footnotes: oxContent.footnotes ?? true,
1411
- semanticFootnotes: oxContent.semanticFootnotes ?? false,
1412
- taskLists: oxContent.taskLists ?? true,
1413
- tables: oxContent.tables ?? true,
1414
- strikethrough: oxContent.strikethrough ?? true,
1415
- autolinks: oxContent.autolinks ?? oxContent.gfm ?? true,
1416
- superscript: oxContent.superscript ?? false,
1417
- subscript: oxContent.subscript ?? false,
1418
- smartPunctuation: oxContent.smartPunctuation ?? false,
1419
- autolinkTargetBlank: oxContent.autolinkTargetBlank ?? true,
1420
- linkTargetBlank: oxContent.linkTargetBlank ?? true,
1421
- sourceSpans: oxContent.sourceSpans ?? false,
1422
- frontmatter: oxContent.frontmatter ?? true,
1423
- tocMaxDepth: oxContent.tocMaxDepth ?? 3,
1424
- cjkEmphasis: oxContent.cjkEmphasis ?? false
1425
- };
1426
- }
1427
- function withoutCollectionInclude(collections) {
1428
- return {
1429
- enabled: collections.enabled,
1430
- collections: Object.fromEntries(Object.entries(collections.collections).map(([name, collection]) => [name, {
1431
- ...collection,
1432
- include: []
1433
- }]))
1434
- };
1435
- }
1436
- function resolveCollectionNames(input, collections) {
1437
- const available = Object.keys(collections.collections);
1438
- if (!input) return available;
1439
- const selected = new Set(Array.isArray(input) ? input : [input]);
1440
- return available.filter((name) => selected.has(name));
1441
- }
1442
- async function resolveCollectionDocument(root, srcDir, collection, entry) {
1443
- const candidate = node_path.default.resolve(root, srcDir, entry.source);
1444
- let source;
1445
- try {
1446
- source = await node_fs_promises.default.readFile(candidate, "utf8");
1447
- } catch {
1448
- return;
1449
- }
1450
- return {
1451
- collection,
1452
- documentPath: candidate,
1453
- entry,
1454
- frontmatter: entry.frontmatter,
1455
- path: entry.path,
1456
- source
1457
- };
1458
- }
1459
1186
  //#endregion
1460
1187
  //#region src/html-host-registry.ts
1461
1188
  const SVELTE_HTML_HOST_MODULES_VIRTUAL_ID = "virtual:ox-content-svelte/html-host/modules";
1462
1189
  function createSvelteHtmlHostIslandRegistry(input = {}) {
1463
- const virtualModuleId = input.virtualModuleId ?? "virtual:ox-content-svelte/html-host/modules";
1464
- const resolvedVirtualModuleId = `\0${virtualModuleId}`;
1465
- let config;
1466
- let command = "build";
1467
- let components;
1468
- let cache;
1469
- let resolved = {
1470
- modules: [],
1471
- watchFiles: []
1472
- };
1473
- const context = () => ({
1474
- root: config?.root ?? input.root ?? process.cwd(),
1475
- mode: config?.mode ?? "production",
1476
- command
1190
+ return (0, _ox_content_vite_plugin.createHtmlHostIslandRegistry)({
1191
+ ...input,
1192
+ virtualModuleId: input.virtualModuleId ?? "virtual:ox-content-svelte/html-host/modules",
1193
+ pluginName: input.pluginName ?? "ox-content:svelte-html-host-island-registry"
1477
1194
  });
1478
- const resolve = async () => {
1479
- cache ??= resolveSvelteHtmlHostIslandRegistry(input, context(), components).then((next) => {
1480
- resolved = next;
1481
- return next;
1482
- });
1483
- return cache;
1484
- };
1485
- const invalidate = () => {
1486
- cache = void 0;
1487
- };
1488
- return {
1489
- plugin: {
1490
- name: "ox-content:svelte-html-host-island-registry",
1491
- config(_config, env) {
1492
- command = env.command;
1493
- },
1494
- async configResolved(resolvedConfig) {
1495
- config = resolvedConfig;
1496
- components = input.components ? await resolveComponentsGlob(input.components, resolvedConfig.root) : {};
1497
- invalidate();
1498
- },
1499
- buildStart() {
1500
- invalidate();
1501
- },
1502
- resolveId(id) {
1503
- return id === virtualModuleId ? resolvedVirtualModuleId : null;
1504
- },
1505
- async load(id) {
1506
- if (id !== resolvedVirtualModuleId) return null;
1507
- return renderModulesVirtualModule(await resolve());
1508
- },
1509
- handleHotUpdate(ctx) {
1510
- if (!shouldInvalidate(ctx.file, context().root, input.oxContent?.srcDir, resolved.watchFiles, input.watch)) return;
1511
- invalidate();
1512
- invalidateVirtualModule(ctx.server, resolvedVirtualModuleId);
1513
- ctx.server.ws.send({ type: "full-reload" });
1514
- return [];
1515
- }
1516
- },
1517
- virtualModuleId,
1518
- resolve,
1519
- resolveClientModule(module) {
1520
- return toSvelteHtmlHostClientModuleId(module.serverModuleId, context().root);
1521
- }
1522
- };
1523
1195
  }
1524
- async function resolveSvelteHtmlHostIslandRegistry(input, context, resolvedComponents) {
1525
- const components = resolvedComponents ?? (input.components ? await resolveComponentsGlob(input.components, context.root) : {});
1526
- const documents = [...await resolveMaybe(input.documents, context) ?? [], ...await resolveInputCollectionDocuments(input, context) ?? []];
1527
- const entries = await resolveMaybe(input.entries, context);
1528
- const modules = /* @__PURE__ */ new Map();
1529
- const watchFiles = /* @__PURE__ */ new Set();
1530
- for (const file of input.watch ?? []) watchFiles.add(resolveWatchFile(file, context.root));
1531
- for (const entry of entries ?? []) {
1532
- addModule(modules, {
1533
- name: entry.name ?? node_path.default.basename((0, _ox_content_vite_plugin.stripViteQuery)(entry.moduleId), node_path.default.extname(entry.moduleId)),
1534
- moduleId: toSvelteHtmlHostClientModuleId(entry.moduleId, context.root),
1535
- exportName: entry.exportName ?? "default"
1536
- });
1537
- if (entry.documentPath) watchFiles.add(resolveWatchFile(entry.documentPath, context.root));
1538
- }
1539
- const oxContent = (0, _ox_content_vite_plugin.customHostOxContentOptions)({
1540
- ...input.oxContent,
1541
- embeds: false
1542
- });
1543
- const srcDir = oxContent.srcDir ?? "content";
1544
- const contentRoot = (0, _ox_content_vite_plugin.resolveContentRootPath)({
1545
- root: context.root,
1546
- srcDir
1547
- });
1548
- for (const document of documents) {
1549
- const documentPath = resolveDocumentPath(document.documentPath, context.root);
1550
- watchFiles.add(documentPath);
1551
- for (const dependency of document.dependencies ?? []) watchFiles.add(resolveWatchFile(dependency, context.root));
1552
- const materialized = await materializeDocument(document, documentPath, oxContent);
1553
- if (!materialized) continue;
1554
- const documentComponents = document.components ?? components;
1555
- const discovered = await (0, _ox_content_vite_plugin.discoverDocumentMdxIslands)({
1556
- source: materialized.source,
1557
- html: materialized.html,
1558
- components: documentComponents,
1559
- imports: materialized.imports,
1560
- documentPath,
1561
- contentRoot,
1562
- srcDir,
1563
- root: context.root
1564
- });
1565
- const usedComponents = new Set(discovered.usedComponents);
1566
- if (materialized.html) for (const name of (0, _ox_content_vite_plugin.intersectHydratableComponentNames)((0, _ox_content_vite_plugin.collectMdxIslandNamesFromHtml)(materialized.html), documentComponents, discovered.localBindings.keys())) usedComponents.add(name);
1567
- for (const name of usedComponents) {
1568
- const local = discovered.localBindings.get(name);
1569
- const serverModuleId = local ? local.resolvedPath : resolveComponentPath(documentComponents, name, context.root);
1570
- if (!serverModuleId) continue;
1571
- addModule(modules, {
1572
- name,
1573
- moduleId: toSvelteHtmlHostClientModuleId(serverModuleId, context.root),
1574
- exportName: local?.imported ?? "default"
1575
- });
1576
- }
1577
- }
1578
- return {
1579
- modules: [...modules.values()].sort((a, b) => `${a.moduleId}\0${a.exportName}\0${a.name}`.localeCompare(`${b.moduleId}\0${b.exportName}\0${b.name}`)),
1580
- watchFiles: [...watchFiles]
1581
- };
1582
- }
1583
- function resolveInputCollectionDocuments(input, context) {
1584
- if (!input.collectionDocuments) return void 0;
1585
- return resolveSvelteHtmlHostCollectionDocuments(input.collectionDocuments.oxContent === void 0 ? {
1586
- ...input.collectionDocuments,
1587
- oxContent: input.oxContent
1588
- } : input.collectionDocuments, context);
1589
- }
1590
- function renderModulesVirtualModule(registry) {
1591
- return [
1592
- "export const modules = {",
1593
- ...[...new Set(registry.modules.map((module) => module.moduleId))].sort().map((moduleId) => ` ${JSON.stringify(moduleId)}: () => import(${JSON.stringify(moduleId)}),`),
1594
- "};",
1595
- `export const clientModules = ${JSON.stringify(registry.modules, null, 2)};`,
1596
- "export default modules;",
1597
- ""
1598
- ].join("\n");
1599
- }
1600
- async function materializeDocument(document, documentPath, oxContent) {
1601
- const source = document.source ?? await readOptional(documentPath);
1602
- if (source === void 0 && document.html === void 0) return void 0;
1603
- if (document.imports && document.html !== void 0) return {
1604
- source: source ?? "",
1605
- html: document.html,
1606
- imports: document.imports
1607
- };
1608
- if (source === void 0) return {
1609
- source: "",
1610
- html: document.html,
1611
- imports: document.imports ?? []
1612
- };
1613
- const rendered = await (0, _ox_content_vite_plugin.renderMarkdown)(source, documentPath, oxContent);
1614
- return {
1615
- source,
1616
- html: document.html ?? rendered.html,
1617
- imports: document.imports ?? rendered.imports
1618
- };
1619
- }
1620
- async function readOptional(file) {
1621
- try {
1622
- return await node_fs_promises.default.readFile(file, "utf8");
1623
- } catch {
1624
- return;
1625
- }
1196
+ function resolveSvelteHtmlHostIslandRegistry(input, context, resolvedComponents) {
1197
+ return (0, _ox_content_vite_plugin.resolveHtmlHostIslandRegistry)(input, context, resolvedComponents);
1626
1198
  }
1627
- function addModule(modules, module) {
1628
- modules.set(`${module.moduleId}\0${module.exportName}\0${module.name}`, module);
1629
- }
1630
- function resolveMaybe(value, context) {
1631
- return typeof value === "function" ? value(context) : value;
1632
- }
1633
- function resolveComponentPath(components, name, root) {
1634
- const specifier = components[name];
1635
- if (!specifier) return void 0;
1636
- if (isBareSpecifier(specifier) || specifier.startsWith("/@fs/")) return specifier;
1637
- if (specifier.startsWith("/") && !node_path.default.isAbsolute(specifier)) return specifier;
1638
- return node_path.default.isAbsolute(specifier) ? specifier : node_path.default.resolve(root, specifier);
1199
+ //#endregion
1200
+ //#region src/html-host-collection-documents.ts
1201
+ function createSvelteHtmlHostCollectionDocuments(input = {}) {
1202
+ return (context) => resolveSvelteHtmlHostCollectionDocuments(input, context);
1639
1203
  }
1640
- function invalidateVirtualModule(server, resolvedVirtualModuleId) {
1641
- const mod = server.moduleGraph.getModuleById(resolvedVirtualModuleId);
1642
- if (mod) server.moduleGraph.invalidateModule(mod);
1204
+ function resolveSvelteHtmlHostCollectionDocuments(input, context) {
1205
+ return (0, _ox_content_vite_plugin.resolveHtmlHostCollectionDocuments)(input, context);
1643
1206
  }
1644
1207
  //#endregion
1645
1208
  //#region src/index.ts
@@ -1874,4 +1437,4 @@ Object.defineProperty(exports, "renderHead", {
1874
1437
  exports.renderSvelteHtmlHost = renderSvelteHtmlHost;
1875
1438
  exports.resolveSvelteHtmlHostCollectionDocuments = resolveSvelteHtmlHostCollectionDocuments;
1876
1439
  exports.resolveSvelteHtmlHostIslandRegistry = resolveSvelteHtmlHostIslandRegistry;
1877
- exports.toSvelteHtmlHostClientModuleId = toSvelteHtmlHostClientModuleId;
1440
+ exports.toSvelteHtmlHostClientModuleId = _ox_content_vite_plugin.toHtmlHostClientModuleId;