@xyd-js/documan 0.1.0-xyd.8 → 0.1.0-xyd.85

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.js CHANGED
@@ -1,238 +1,1136 @@
1
- // src/run/build.ts
2
- import path from "node:path";
3
- import fs from "node:fs";
4
- import { fileURLToPath } from "node:url";
1
+ // src/build.ts
2
+ import path2 from "path";
3
+ import fs2 from "fs";
4
+ import { fileURLToPath as fileURLToPath2 } from "url";
5
5
  import { build as viteBuild } from "vite";
6
6
  import tsconfigPaths from "vite-tsconfig-paths";
7
- import { reactRouter } from "@xyd-js/react-router-dev/vite";
8
- import { vitePlugins as xydContentVitePlugins } from "@xyd-js/content";
9
- import { pluginZero } from "@xyd-js/plugin-zero";
7
+
8
+ // src/utils.ts
9
+ import path from "path";
10
+ import fs from "fs";
11
+ import { fileURLToPath } from "url";
12
+ import { execSync } from "child_process";
13
+ import crypto from "crypto";
14
+ import { createServer } from "vite";
15
+ import { reactRouter } from "@react-router/dev/vite";
16
+ import { IconSet } from "@iconify/tools";
17
+ import { readSettings, pluginDocs } from "@xyd-js/plugin-docs";
18
+ import { vitePlugins as xydContentVitePlugins } from "@xyd-js/content/vite";
19
+
20
+ // src/const.ts
21
+ var HOST_FOLDER_PATH = ".xyd/host";
22
+ var CACHE_FOLDER_PATH = ".xyd/.cache";
23
+ var BUILD_FOLDER_PATH = ".xyd/build";
24
+ var SUPPORTED_SETTINGS_FILES = [
25
+ "docs.json",
26
+ "docs.ts",
27
+ "docs.tsx"
28
+ ];
29
+ var SUPPORTED_CONTENT_FILES = [
30
+ ".md",
31
+ ".mdx"
32
+ ];
33
+
34
+ // src/cli.ts
35
+ import readline from "readline";
36
+ import cliSpinners from "cli-spinners";
37
+ var CLI = class {
38
+ spinner;
39
+ spinnerInterval = null;
40
+ currentFrame = 0;
41
+ currentMessage = "";
42
+ isSpinning = false;
43
+ constructor(spinnerType = "dots") {
44
+ this.spinner = cliSpinners[spinnerType];
45
+ }
46
+ startSpinner(message) {
47
+ if (this.isSpinning) {
48
+ this.stopSpinner();
49
+ }
50
+ this.currentMessage = message;
51
+ this.isSpinning = true;
52
+ this.currentFrame = 0;
53
+ this.write(`${this.spinner.frames[0]} ${this.currentMessage}`);
54
+ this.spinnerInterval = setInterval(() => {
55
+ const frame = this.spinner.frames[this.currentFrame];
56
+ this.write(`${frame} ${this.currentMessage}`);
57
+ this.currentFrame = (this.currentFrame + 1) % this.spinner.frames.length;
58
+ }, this.spinner.interval);
59
+ }
60
+ stopSpinner() {
61
+ if (this.spinnerInterval) {
62
+ clearInterval(this.spinnerInterval);
63
+ this.spinnerInterval = null;
64
+ }
65
+ this.isSpinning = false;
66
+ this.clearLine();
67
+ }
68
+ clearLine() {
69
+ readline.clearLine(process.stdout, 0);
70
+ readline.cursorTo(process.stdout, 0);
71
+ }
72
+ write(message) {
73
+ this.clearLine();
74
+ process.stdout.write(message);
75
+ }
76
+ log(message) {
77
+ if (this.isSpinning) {
78
+ this.stopSpinner();
79
+ }
80
+ console.log(message);
81
+ }
82
+ error(message) {
83
+ if (this.isSpinning) {
84
+ this.stopSpinner();
85
+ }
86
+ console.error(message);
87
+ }
88
+ updateMessage(message) {
89
+ this.currentMessage = message;
90
+ }
91
+ };
92
+ var cli = new CLI();
93
+
94
+ // src/utils.ts
10
95
  var __filename = fileURLToPath(import.meta.url);
11
96
  var __dirname = path.dirname(__filename);
12
- async function build() {
13
- const resp = await pluginZero();
14
- if (!resp) {
15
- throw new Error("PluginZero not found");
97
+ async function appInit(options) {
98
+ const readPreloadSettings = await readSettings();
99
+ if (!readPreloadSettings) {
100
+ return null;
101
+ }
102
+ const preloadSettings = typeof readPreloadSettings === "string" ? JSON.parse(readPreloadSettings) : readPreloadSettings;
103
+ {
104
+ if (!preloadSettings.integrations?.search) {
105
+ preloadSettings.integrations = {
106
+ ...preloadSettings.integrations || {},
107
+ search: {
108
+ orama: true
109
+ }
110
+ };
111
+ }
112
+ const plugins = integrationsToPlugins(preloadSettings.integrations);
113
+ if (preloadSettings.plugins) {
114
+ preloadSettings.plugins = [...plugins, ...preloadSettings.plugins];
115
+ } else {
116
+ preloadSettings.plugins = plugins;
117
+ }
16
118
  }
17
- const buildDir = path.join(process.cwd(), ".xyd/build");
119
+ let resolvedPlugins = [];
18
120
  {
19
- const packageJsonPath = path.join(buildDir, "package.json");
20
- const packageJsonContent = {
21
- type: "module",
22
- scripts: {},
23
- dependencies: {},
24
- devDependencies: {}
121
+ resolvedPlugins = await loadPlugins(preloadSettings) || [];
122
+ const userUniformVitePlugins = [];
123
+ const componentPlugins = [];
124
+ resolvedPlugins?.forEach((p) => {
125
+ if (p.uniform) {
126
+ userUniformVitePlugins.push(...p.uniform);
127
+ }
128
+ if (p.components) {
129
+ componentPlugins.push(...p.components);
130
+ }
131
+ });
132
+ globalThis.__xydUserUniformVitePlugins = userUniformVitePlugins;
133
+ globalThis.__xydUserComponents = componentPlugins;
134
+ }
135
+ const respPluginDocs = await pluginDocs(options);
136
+ if (!respPluginDocs) {
137
+ throw new Error("PluginDocs not found");
138
+ }
139
+ if (!respPluginDocs.settings) {
140
+ throw new Error("Settings not found in respPluginDocs");
141
+ }
142
+ respPluginDocs.settings.plugins = [
143
+ ...respPluginDocs.settings?.plugins || [],
144
+ ...preloadSettings.plugins || []
145
+ ];
146
+ globalThis.__xydBasePath = respPluginDocs.basePath;
147
+ globalThis.__xydSettings = respPluginDocs.settings;
148
+ globalThis.__xydPagePathMapping = respPluginDocs.pagePathMapping;
149
+ return {
150
+ respPluginDocs,
151
+ resolvedPlugins
152
+ };
153
+ }
154
+ function virtualComponentsPlugin() {
155
+ return {
156
+ name: "xyd-plugin-virtual-components",
157
+ resolveId(id) {
158
+ if (id === "virtual:xyd-user-components") {
159
+ return id + ".jsx";
160
+ }
161
+ return null;
162
+ },
163
+ async load(id) {
164
+ if (id === "virtual:xyd-user-components.jsx") {
165
+ const userComponents = globalThis.__xydUserComponents || [];
166
+ if (userComponents.length > 0 && userComponents[0]?.dist) {
167
+ const imports = userComponents.map(
168
+ (component, index) => `import Component${index} from '${component.dist}';`
169
+ ).join("\n");
170
+ const componentObjects = userComponents.map(
171
+ (component, index) => `{
172
+ component: Component${index},
173
+ name: '${component.name}',
174
+ dist: '${component.dist}'
175
+ }`
176
+ ).join(",\n ");
177
+ return `
178
+ // Pre-bundled at build time - no async loading needed
179
+ ${imports}
180
+
181
+ export const components = [
182
+ ${componentObjects}
183
+ ];
184
+ `;
185
+ }
186
+ return `
187
+ export const components = globalThis.__xydUserComponents || {}
188
+ `;
189
+ }
190
+ return null;
191
+ }
192
+ };
193
+ }
194
+ function virtualProvidersPlugin(settings) {
195
+ return {
196
+ name: "xyd-plugin-virtual-providers",
197
+ enforce: "pre",
198
+ resolveId(id) {
199
+ if (id === "virtual:xyd-analytics-providers") {
200
+ return id;
201
+ }
202
+ },
203
+ async load(id) {
204
+ if (id === "virtual:xyd-analytics-providers") {
205
+ const providers = Object.keys(settings?.integrations?.analytics || {});
206
+ const imports = providers.map(
207
+ (provider) => `import { default as ${provider}Provider } from '@pluganalytics/provider-${provider}'`
208
+ ).join("\n");
209
+ const cases = providers.map(
210
+ (provider) => `case '${provider}': return ${provider}Provider`
211
+ ).join("\n");
212
+ return `
213
+ ${imports}
214
+
215
+ export const loadProvider = async (provider) => {
216
+ switch (provider) {
217
+ ${cases}
218
+ default:
219
+ console.error(\`Provider \${provider} not found\`)
220
+ return null
221
+ }
222
+ }
223
+ `;
224
+ }
225
+ }
226
+ };
227
+ }
228
+ function commonVitePlugins(respPluginDocs, resolvedPlugins) {
229
+ const userVitePlugins = resolvedPlugins.map((p) => p.vite).flat() || [];
230
+ return [
231
+ ...xydContentVitePlugins({
232
+ toc: {
233
+ maxDepth: respPluginDocs.settings.theme?.maxTocDepth || 2
234
+ },
235
+ settings: respPluginDocs.settings
236
+ }),
237
+ ...respPluginDocs.vitePlugins,
238
+ reactRouter(),
239
+ virtualComponentsPlugin(),
240
+ virtualProvidersPlugin(respPluginDocs.settings),
241
+ pluginIconSet(respPluginDocs.settings),
242
+ ...userVitePlugins
243
+ ];
244
+ }
245
+ function pluginIconSet(settings) {
246
+ const DEFAULT_ICON_SET = "lucide";
247
+ async function fetchIconSet(name, version) {
248
+ if (name.startsWith("http://") || name.startsWith("https://")) {
249
+ try {
250
+ const iconsResp = await fetch(name);
251
+ const iconsData = await iconsResp.json();
252
+ const iconSet = new IconSet(iconsData);
253
+ return { icons: iconsData, iconSet };
254
+ } catch (error) {
255
+ console.warn(`Failed to fetch from URL ${name}:`, error);
256
+ }
257
+ }
258
+ const tryReadFile = (filePath) => {
259
+ try {
260
+ if (!fs.existsSync(filePath)) {
261
+ console.warn(`File does not exist: ${filePath}`);
262
+ return null;
263
+ }
264
+ const fileContent = fs.readFileSync(filePath, "utf-8");
265
+ try {
266
+ const iconsData = JSON.parse(fileContent);
267
+ const iconSet = new IconSet(iconsData);
268
+ return { icons: iconsData, iconSet };
269
+ } catch (parseError) {
270
+ console.warn(`Invalid JSON in file ${filePath}:`, parseError);
271
+ return null;
272
+ }
273
+ } catch (error) {
274
+ console.warn(`Failed to read file ${filePath}:`, error);
275
+ return null;
276
+ }
25
277
  };
26
- if (!fs.existsSync(buildDir)) {
27
- fs.mkdirSync(buildDir, { recursive: true });
278
+ if (path.isAbsolute(name)) {
279
+ const result = tryReadFile(name);
280
+ if (result) return result;
281
+ }
282
+ if (name.startsWith(".")) {
283
+ const fullPath = path.join(process.cwd(), name);
284
+ const result = tryReadFile(fullPath);
285
+ if (result) return result;
286
+ }
287
+ const cdnUrl = version ? `https://cdn.jsdelivr.net/npm/@iconify-json/${name}@${version}/icons.json` : `https://cdn.jsdelivr.net/npm/@iconify-json/${name}/icons.json`;
288
+ try {
289
+ const iconsResp = await fetch(cdnUrl);
290
+ const iconsData = await iconsResp.json();
291
+ const iconSet = new IconSet(iconsData);
292
+ return { icons: iconsData, iconSet };
293
+ } catch (error) {
294
+ throw new Error(`Failed to load icon set from any source (file or CDN): ${name}`);
295
+ }
296
+ }
297
+ async function processIconSet(iconSet, icons, noPrefix) {
298
+ const resp = /* @__PURE__ */ new Map();
299
+ for (const icon of Object.keys(icons.icons)) {
300
+ const svg = iconSet.toSVG(icon);
301
+ if (!svg) continue;
302
+ let prefix = noPrefix ? void 0 : iconSet.prefix;
303
+ const iconName = prefix ? `${prefix}:${icon}` : icon;
304
+ resp.set(iconName, { svg: svg.toString() });
305
+ }
306
+ return resp;
307
+ }
308
+ async function addIconsToMap(resp, name, version, noPrefix) {
309
+ const { icons, iconSet } = await fetchIconSet(name, version);
310
+ const newIcons = await processIconSet(iconSet, icons, noPrefix);
311
+ newIcons.forEach((value, key) => resp.set(key, value));
312
+ }
313
+ async function processIconLibrary(library) {
314
+ const resp = /* @__PURE__ */ new Map();
315
+ if (typeof library === "string") {
316
+ await addIconsToMap(resp, library);
317
+ } else if (Array.isArray(library)) {
318
+ for (const item of library) {
319
+ if (typeof item === "string") {
320
+ await addIconsToMap(resp, item);
321
+ } else {
322
+ const { name, version, default: isDefault, noprefix } = item;
323
+ const noPrefix = isDefault || noprefix === true;
324
+ await addIconsToMap(resp, name, version, noPrefix);
325
+ }
326
+ }
327
+ } else {
328
+ const { name, version, default: isDefault, noprefix } = library;
329
+ const noPrefix = isDefault || noprefix === true;
330
+ await addIconsToMap(resp, name, version, noPrefix);
331
+ }
332
+ return resp;
333
+ }
334
+ return {
335
+ name: "xyd-plugin-icon-set",
336
+ enforce: "pre",
337
+ resolveId(id) {
338
+ if (id === "virtual:xyd-icon-set") {
339
+ return id;
340
+ }
341
+ },
342
+ async load(id) {
343
+ if (id === "virtual:xyd-icon-set") {
344
+ let resp;
345
+ if (settings.theme?.icons?.library) {
346
+ resp = await processIconLibrary(settings.theme.icons.library);
347
+ } else {
348
+ resp = await processIconLibrary([
349
+ {
350
+ name: DEFAULT_ICON_SET,
351
+ default: true
352
+ }
353
+ ]);
354
+ }
355
+ return `
356
+ export const iconSet = ${JSON.stringify(Object.fromEntries(resp))};
357
+ `;
358
+ }
359
+ }
360
+ };
361
+ }
362
+ function getHostPath() {
363
+ if (process.env.XYD_DEV_MODE) {
364
+ if (process.env.XYD_HOST) {
365
+ return path.resolve(process.env.XYD_HOST);
366
+ }
367
+ return path.join(__dirname, "../../../", HOST_FOLDER_PATH);
368
+ }
369
+ return path.join(process.cwd(), HOST_FOLDER_PATH);
370
+ }
371
+ function getAppRoot() {
372
+ return getHostPath();
373
+ }
374
+ function getPublicPath() {
375
+ return path.join(process.cwd(), "public");
376
+ }
377
+ function getBuildPath() {
378
+ return path.join(
379
+ process.cwd(),
380
+ BUILD_FOLDER_PATH
381
+ );
382
+ }
383
+ function getDocsPluginBasePath() {
384
+ return path.join(getHostPath(), "./plugins/xyd-plugin-docs");
385
+ }
386
+ async function loadPlugins(settings) {
387
+ const resolvedPlugins = [];
388
+ for (const plugin of settings.plugins || []) {
389
+ let pluginName;
390
+ let pluginArgs = [];
391
+ if (typeof plugin === "string") {
392
+ pluginName = plugin;
393
+ pluginArgs = [];
394
+ } else if (Array.isArray(plugin)) {
395
+ pluginName = plugin[0];
396
+ pluginArgs = plugin.slice(1);
397
+ } else {
398
+ console.error(`Currently only string and array plugins are supported, got: ${plugin}`);
399
+ return [];
400
+ }
401
+ let mod;
402
+ try {
403
+ mod = await import(pluginName);
404
+ } catch (e) {
405
+ pluginName = path.join(process.cwd(), pluginName);
406
+ const pluginPreview = await createServer({
407
+ optimizeDeps: {
408
+ include: []
409
+ }
410
+ });
411
+ mod = await pluginPreview.ssrLoadModule(pluginName);
412
+ }
413
+ if (!mod.default) {
414
+ console.error(`Plugin ${plugin} has no default export`);
415
+ continue;
416
+ }
417
+ let pluginInstance = mod.default(...pluginArgs);
418
+ if (typeof pluginInstance === "function") {
419
+ const plug = pluginInstance(settings);
420
+ resolvedPlugins.push(plug);
421
+ continue;
28
422
  }
29
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContent, null, 2), "utf8");
423
+ resolvedPlugins.push(pluginInstance);
424
+ }
425
+ return resolvedPlugins;
426
+ }
427
+ function integrationsToPlugins(integrations) {
428
+ const plugins = [];
429
+ let foundSearchIntegation = 0;
430
+ if (integrations?.search?.orama) {
431
+ if (typeof integrations.search.orama === "boolean") {
432
+ plugins.push("@xyd-js/plugin-orama");
433
+ } else {
434
+ plugins.push(["@xyd-js/plugin-orama", integrations.search.orama]);
435
+ }
436
+ foundSearchIntegation++;
437
+ }
438
+ if (integrations?.search?.algolia) {
439
+ plugins.push(["@xyd-js/plugin-algolia", integrations.search.algolia]);
440
+ foundSearchIntegation++;
441
+ }
442
+ if (foundSearchIntegation > 1) {
443
+ throw new Error("Only one search integration is allowed");
444
+ }
445
+ return plugins;
446
+ }
447
+ async function preWorkspaceSetup(options = {}) {
448
+ await ensureFoldersExist();
449
+ if (!options.force) {
450
+ if (await shouldSkipHostSetup()) {
451
+ return true;
452
+ }
453
+ }
454
+ const hostTemplate = process.env.XYD_DEV_MODE ? path.resolve(__dirname, "../../xyd-host") : path.resolve(__dirname, "../../host");
455
+ const hostPath = getHostPath();
456
+ await copyHostTemplate(hostTemplate, hostPath);
457
+ let pluginDocsPath;
458
+ if (process.env.XYD_DEV_MODE) {
459
+ pluginDocsPath = path.resolve(__dirname, "../../xyd-plugin-docs");
460
+ } else {
461
+ pluginDocsPath = path.resolve(__dirname, "../../plugin-docs");
462
+ }
463
+ const pagesSourcePath = path.join(pluginDocsPath, "src/pages");
464
+ const pagesTargetPath = path.join(hostPath, "plugins/xyd-plugin-docs/src/pages");
465
+ if (fs.existsSync(pagesSourcePath)) {
466
+ await copyHostTemplate(pagesSourcePath, pagesTargetPath);
467
+ } else {
468
+ console.warn(`Pages source path does not exist: ${pagesSourcePath}`);
469
+ }
470
+ }
471
+ function calculateFolderChecksum(folderPath) {
472
+ const hash = crypto.createHash("sha256");
473
+ const ignorePatterns = [...getGitignorePatterns(folderPath), ".xydchecksum", "node_modules", "dist", ".react-router", "package-lock.json", "pnpm-lock.yaml"];
474
+ function processFile(filePath) {
475
+ const relativePath = path.relative(folderPath, filePath);
476
+ const content = fs.readFileSync(filePath);
477
+ hash.update(relativePath);
478
+ hash.update(content);
479
+ }
480
+ function processDirectory(dirPath) {
481
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
482
+ entries.sort((a, b) => a.name.localeCompare(b.name));
483
+ for (const entry of entries) {
484
+ const sourceEntry = path.join(dirPath, entry.name);
485
+ if (shouldIgnoreEntry(entry.name, ignorePatterns)) {
486
+ continue;
487
+ }
488
+ if (entry.name === ".git") {
489
+ continue;
490
+ }
491
+ if (entry.isDirectory()) {
492
+ processDirectory(sourceEntry);
493
+ } else {
494
+ processFile(sourceEntry);
495
+ }
496
+ }
497
+ }
498
+ processDirectory(folderPath);
499
+ return hash.digest("hex");
500
+ }
501
+ function getGitignorePatterns(folderPath) {
502
+ const gitignorePath = path.join(folderPath, ".gitignore");
503
+ if (fs.existsSync(gitignorePath)) {
504
+ const gitignoreContent = fs.readFileSync(gitignorePath, "utf-8");
505
+ return gitignoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
506
+ }
507
+ return [];
508
+ }
509
+ function shouldIgnoreEntry(entryName, ignorePatterns) {
510
+ return ignorePatterns.some((pattern) => {
511
+ const regex = new RegExp(pattern.replace(/\*/g, ".*"));
512
+ return regex.test(entryName);
513
+ });
514
+ }
515
+ async function copyHostTemplate(sourcePath, targetPath) {
516
+ if (!fs.existsSync(sourcePath)) {
517
+ throw new Error(`Host template source path does not exist: ${sourcePath}`);
518
+ }
519
+ if (fs.existsSync(targetPath)) {
520
+ fs.rmSync(targetPath, { recursive: true, force: true });
521
+ }
522
+ fs.mkdirSync(targetPath, { recursive: true });
523
+ const ignorePatterns = getGitignorePatterns(sourcePath);
524
+ const entries = fs.readdirSync(sourcePath, { withFileTypes: true });
525
+ for (const entry of entries) {
526
+ const sourceEntry = path.join(sourcePath, entry.name);
527
+ const targetEntry = path.join(targetPath, entry.name);
528
+ if (shouldIgnoreEntry(entry.name, ignorePatterns)) {
529
+ continue;
530
+ }
531
+ if (entry.name === ".git") {
532
+ continue;
533
+ }
534
+ if (entry.isDirectory()) {
535
+ await copyHostTemplate(sourceEntry, targetEntry);
536
+ } else {
537
+ fs.copyFileSync(sourceEntry, targetEntry);
538
+ if (entry.name === "package.json" && process.env.XYD_DEV_MODE) {
539
+ const packageJsonPath = targetEntry;
540
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
541
+ packageJson.name = "xyd-host-dev";
542
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
543
+ }
544
+ }
545
+ }
546
+ }
547
+ async function ensureFoldersExist() {
548
+ const folders = [CACHE_FOLDER_PATH];
549
+ for (const folder of folders) {
550
+ const fullPath = path.resolve(process.cwd(), folder);
551
+ if (!fs.existsSync(fullPath)) {
552
+ fs.mkdirSync(fullPath, { recursive: true });
553
+ }
554
+ }
555
+ }
556
+ async function postWorkspaceSetup(settings) {
557
+ const spinner = new CLI("dots");
558
+ try {
559
+ spinner.startSpinner("Installing xyd framework...");
560
+ const hostPath = getHostPath();
561
+ const packageJsonPath = path.join(hostPath, "package.json");
562
+ if (!fs.existsSync(packageJsonPath)) {
563
+ console.warn("No package.json found in host path");
564
+ return;
565
+ }
566
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
567
+ if (!packageJson.dependencies) {
568
+ packageJson.dependencies = {};
569
+ }
570
+ for (const plugin of settings.plugins || []) {
571
+ let pluginName;
572
+ if (typeof plugin === "string") {
573
+ pluginName = plugin;
574
+ } else if (Array.isArray(plugin)) {
575
+ pluginName = plugin[0];
576
+ } else {
577
+ continue;
578
+ }
579
+ if (pluginName.startsWith("@xyd-js/")) {
580
+ continue;
581
+ }
582
+ const isValidNpmPackage = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(pluginName);
583
+ if (isValidNpmPackage) {
584
+ const hostPackageJsonPath = path.join(hostPath, "package.json");
585
+ if (fs.existsSync(hostPackageJsonPath)) {
586
+ const hostPackageJson = JSON.parse(fs.readFileSync(hostPackageJsonPath, "utf-8"));
587
+ const deps = hostPackageJson.dependencies || {};
588
+ const matchingDep = Object.entries(deps).find(([depName]) => {
589
+ return depName === pluginName;
590
+ });
591
+ if (matchingDep) {
592
+ packageJson.dependencies[pluginName] = matchingDep[1];
593
+ } else {
594
+ console.warn(`no matching dependency found for: ${pluginName} in: ${hostPackageJsonPath}`);
595
+ }
596
+ } else {
597
+ console.warn(`no host package.json found in: ${hostPath}`);
598
+ }
599
+ } else if (!pluginName.startsWith(".") && !pluginName.startsWith("/")) {
600
+ console.warn(`invalid plugin name: ${pluginName}`);
601
+ }
602
+ }
603
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
604
+ await nodeInstallPackages(hostPath);
605
+ spinner.stopSpinner();
606
+ spinner.log("\u2714 Local xyd framework installed successfully");
607
+ } catch (error) {
608
+ spinner.stopSpinner();
609
+ spinner.error("\u274C Failed to install xyd framework");
610
+ throw error;
611
+ }
612
+ }
613
+ function nodeInstallPackages(hostPath) {
614
+ let cmd = process.env.XYD_NODE_PM ? `${process.env.XYD_NODE_PM} i` : "npm i";
615
+ if (process.env.XYD_DEV_MODE) {
616
+ cmd = "pnpm i";
617
+ }
618
+ const execOptions = {
619
+ cwd: hostPath,
620
+ env: {
621
+ ...process.env,
622
+ NODE_ENV: ""
623
+ // since 'production' does not install it well,
624
+ }
625
+ };
626
+ const customRegistry = process.env.XYD_NPM_REGISTRY || process.env.npm_config_registry;
627
+ if (customRegistry) {
628
+ if (!execOptions.env) {
629
+ execOptions.env = {};
630
+ }
631
+ execOptions.env["npm_config_registry"] = customRegistry;
632
+ }
633
+ if (process.env.XYD_VERBOSE) {
634
+ execOptions.stdio = "inherit";
635
+ }
636
+ execSync(cmd, execOptions);
637
+ }
638
+ async function shouldSkipHostSetup() {
639
+ const hostPath = getHostPath();
640
+ if (!fs.existsSync(hostPath)) {
641
+ return false;
642
+ }
643
+ const currentChecksum = calculateFolderChecksum(hostPath);
644
+ const storedChecksum = getStoredChecksum();
645
+ if (!storedChecksum || storedChecksum !== currentChecksum) {
646
+ return false;
647
+ }
648
+ return true;
649
+ }
650
+ function getStoredChecksum() {
651
+ const checksumPath = path.join(getHostPath(), ".xydchecksum");
652
+ if (!fs.existsSync(checksumPath)) {
653
+ return null;
654
+ }
655
+ try {
656
+ return fs.readFileSync(checksumPath, "utf-8").trim();
657
+ } catch (error) {
658
+ console.error("Error reading checksum file:", error);
659
+ return null;
660
+ }
661
+ }
662
+ function storeChecksum(checksum) {
663
+ const checksumPath = path.join(getHostPath(), ".xydchecksum");
664
+ try {
665
+ fs.writeFileSync(checksumPath, checksum);
666
+ } catch (error) {
667
+ console.error("Error writing checksum file:", error);
668
+ }
669
+ }
670
+
671
+ // src/build.ts
672
+ async function build() {
673
+ const skip = await preWorkspaceSetup({
674
+ force: true
675
+ });
676
+ const inited = await appInit();
677
+ if (!inited) {
678
+ return;
679
+ }
680
+ const { respPluginDocs, resolvedPlugins } = inited;
681
+ const commonRunVitePlugins = commonVitePlugins(respPluginDocs, resolvedPlugins);
682
+ const appRoot = getAppRoot();
683
+ if (!skip) {
684
+ await postWorkspaceSetup(respPluginDocs.settings);
685
+ const newChecksum = calculateFolderChecksum(getHostPath());
686
+ storeChecksum(newChecksum);
687
+ }
688
+ {
689
+ await setupInstallableEnvironmentV2();
30
690
  }
31
691
  try {
32
692
  await viteBuild({
33
- root: process.env.XYD_CLI ? __dirname : process.env.XYD_DOCUMAN_HOST || path.join(__dirname, "../host"),
34
- // @ts-ignore
693
+ mode: "production",
694
+ root: appRoot,
35
695
  plugins: [
36
- ...xydContentVitePlugins({
37
- toc: {
38
- minDepth: 2
39
- }
40
- }),
41
- reactRouter({
42
- outDir: buildDir,
43
- routes: resp.routes
44
- }),
45
- tsconfigPaths(),
46
- ...resp.vitePlugins
696
+ ...commonRunVitePlugins,
697
+ tsconfigPaths()
47
698
  ],
48
699
  optimizeDeps: {
49
700
  include: ["react/jsx-runtime"]
701
+ },
702
+ define: {
703
+ "process.env.NODE_ENV": JSON.stringify("production"),
704
+ "process.env": {}
705
+ },
706
+ resolve: {
707
+ alias: {
708
+ process: "process/browser"
709
+ }
50
710
  }
51
711
  });
52
712
  await viteBuild({
53
- root: process.env.XYD_CLI ? __dirname : process.env.XYD_DOCUMAN_HOST || path.join(__dirname, "../host"),
713
+ mode: "production",
714
+ root: appRoot,
54
715
  build: {
55
716
  ssr: true
56
717
  },
57
- // @ts-ignore
58
718
  plugins: [
59
- ...xydContentVitePlugins({
60
- toc: {
61
- minDepth: 2
62
- }
63
- }),
64
- reactRouter({
65
- outDir: buildDir,
66
- routes: resp.routes
67
- }),
68
- tsconfigPaths(),
69
- ...resp.vitePlugins
719
+ fixManifestPlugin(appRoot),
720
+ ...commonRunVitePlugins
70
721
  ],
71
722
  optimizeDeps: {
72
723
  include: ["react/jsx-runtime"]
724
+ },
725
+ define: {
726
+ "process.env.NODE_ENV": JSON.stringify("production"),
727
+ "process.env": {}
728
+ },
729
+ resolve: {
730
+ alias: {
731
+ process: "process/browser"
732
+ }
73
733
  }
74
734
  });
75
- console.log("Build completed successfully.");
76
735
  } catch (error) {
77
736
  console.error("Build failed:", error);
78
737
  }
79
738
  }
739
+ function setupInstallableEnvironmentV2() {
740
+ const buildDir = getBuildPath();
741
+ const packageJsonPath = path2.join(buildDir, "package.json");
742
+ const packageJsonContent = {
743
+ type: "module",
744
+ scripts: {},
745
+ dependencies: {},
746
+ devDependencies: {}
747
+ };
748
+ if (!fs2.existsSync(buildDir)) {
749
+ fs2.mkdirSync(buildDir, { recursive: true });
750
+ }
751
+ fs2.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContent, null, 2), "utf8");
752
+ const buildNodeModulesPath = path2.join(buildDir, "node_modules");
753
+ const dirname = path2.dirname(fileURLToPath2(import.meta.url));
754
+ let workspaceNodeModulesPath = "";
755
+ if (process.env.XYD_DEV_MODE) {
756
+ workspaceNodeModulesPath = path2.resolve(dirname, "../../../node_modules");
757
+ } else {
758
+ workspaceNodeModulesPath = path2.resolve(dirname, "../../../");
759
+ }
760
+ console.log("workspaceNodeModulesPath", workspaceNodeModulesPath);
761
+ if (fs2.existsSync(buildNodeModulesPath)) {
762
+ if (fs2.lstatSync(buildNodeModulesPath).isSymbolicLink()) {
763
+ fs2.unlinkSync(buildNodeModulesPath);
764
+ } else {
765
+ fs2.rmSync(buildNodeModulesPath, { recursive: true, force: true });
766
+ }
767
+ }
768
+ fs2.symlinkSync(workspaceNodeModulesPath, buildNodeModulesPath, "dir");
769
+ }
770
+ function fixManifestPlugin(appRoot) {
771
+ const manifestPath = path2.join(
772
+ getBuildPath(),
773
+ "./server/.vite/manifest.json"
774
+ );
775
+ return {
776
+ name: "xyd-fix-rr-manifest",
777
+ apply: "build",
778
+ // run after manifest is generated
779
+ // 2) after bundle is written, compute prefix and strip it
780
+ writeBundle(_, bundle) {
781
+ const cwdDir = process.cwd();
782
+ let prefix = path2.relative(appRoot, cwdDir).replace(/\\/g, "/");
783
+ if (prefix) prefix += "/";
784
+ const esc = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
785
+ const stripRe = new RegExp(`^${esc}`);
786
+ for (const fileName in bundle) {
787
+ const asset = bundle[fileName];
788
+ if (asset.type !== "asset") continue;
789
+ if (fileName.endsWith("manifest.json")) {
790
+ const manifest = JSON.parse(asset.source.toString());
791
+ const fixed = {};
792
+ for (const key of Object.keys(manifest)) {
793
+ const entry = manifest[key];
794
+ const newKey = key.replace(stripRe, "");
795
+ if (typeof entry.src === "string") {
796
+ entry.src = entry.src.replace(stripRe, "");
797
+ }
798
+ fixed[newKey] = entry;
799
+ }
800
+ asset.source = JSON.stringify(fixed, null, 2);
801
+ fs2.writeFileSync(manifestPath, asset.source, "utf8");
802
+ }
803
+ }
804
+ }
805
+ };
806
+ }
80
807
 
81
- // src/run/dev.ts
82
- import path2 from "node:path";
83
- import { fileURLToPath as fileURLToPath2 } from "node:url";
84
- import { createServer, searchForWorkspaceRoot } from "vite";
85
- import { reactRouter as reactRouter2 } from "@xyd-js/react-router-dev/vite";
86
- import { vitePlugins as xydContentVitePlugins2 } from "@xyd-js/content";
87
- import { pluginZero as pluginZero2 } from "@xyd-js/plugin-zero";
88
- var __filename2 = fileURLToPath2(import.meta.url);
89
- var __dirname2 = path2.dirname(__filename2);
90
- var port = process.env.XYD_PORT ? parseInt(process.env.XYD_PORT) : 5175;
91
- async function dev() {
92
- const resp = await pluginZero2();
93
- if (!resp) {
94
- throw new Error("PluginZero not found");
808
+ // src/dev.ts
809
+ import path3 from "path";
810
+ import fs3 from "fs";
811
+ import { createServer as createServer2, searchForWorkspaceRoot } from "vite";
812
+ import { readSettings as readSettings2 } from "@xyd-js/plugin-docs";
813
+ if (!process.env.ENABLE_TIMERS) {
814
+ ["time", "timeLog", "timeEnd"].forEach((method) => {
815
+ console[method] = () => {
816
+ };
817
+ });
818
+ }
819
+ var RELOADING = false;
820
+ async function dev(options) {
821
+ const spinner = new CLI("dots");
822
+ spinner.startSpinner("Preparing local xyd instance...");
823
+ const skip = await preWorkspaceSetup();
824
+ const inited = await appInit();
825
+ if (!inited) {
826
+ return;
95
827
  }
828
+ const { respPluginDocs, resolvedPlugins } = inited;
96
829
  const allowCwd = searchForWorkspaceRoot(process.cwd());
97
- const preview = await createServer({
98
- // any valid user config options, plus `mode` and `configFile`
99
- // configFile: path.join(__dirname, "../src/vite/empty-config.ts"), // TODO: bundler??
100
- // configFile: path.join(__dirname, "../"), // TODO: bundler??
101
- // root: path.join(__dirname, "../"), // TODO: bundler?
102
- root: process.env.XYD_CLI ? __dirname2 : process.env.XYD_DOCUMAN_HOST || path2.join(__dirname2, "../host"),
103
- // TODO: bundler?
830
+ const appRoot = getAppRoot();
831
+ const commonRunVitePlugins = commonVitePlugins(respPluginDocs, resolvedPlugins);
832
+ spinner.stopSpinner();
833
+ if (!skip) {
834
+ await postWorkspaceSetup(respPluginDocs.settings);
835
+ const newChecksum = calculateFolderChecksum(getHostPath());
836
+ storeChecksum(newChecksum);
837
+ }
838
+ spinner.log("\u2714 Local xyd instance is ready");
839
+ let server = null;
840
+ const port = options?.port ?? parseInt(process.env.XYD_PORT ?? "5175");
841
+ let USE_CONTEXT_ISSUE_PACKAGES = [];
842
+ {
843
+ if (process.env.XYD_DEV_MODE) {
844
+ USE_CONTEXT_ISSUE_PACKAGES = [
845
+ "react-github-btn",
846
+ "radix-ui",
847
+ "@code-hike/lighter",
848
+ "lucide-react",
849
+ "openux-js",
850
+ "pluganalytics"
851
+ ];
852
+ } else {
853
+ USE_CONTEXT_ISSUE_PACKAGES = [
854
+ "@xyd-js/theme-cosmo",
855
+ "@xyd-js/theme-opener",
856
+ "@xyd-js/theme-picasso",
857
+ "@xyd-js/theme-poetry"
858
+ ];
859
+ }
860
+ }
861
+ const preview = await createServer2({
862
+ root: appRoot,
863
+ publicDir: "/public",
104
864
  server: {
865
+ allowedHosts: [],
105
866
  port,
106
867
  fs: {
107
868
  allow: [
108
869
  allowCwd,
109
- process.env.XYD_CLI ? path2.join(__dirname2, "../../") : ""
110
- // path.join(__dirname, "../node_modules") // Ensure node_modules from xyd-documan is included
870
+ appRoot
111
871
  ]
112
872
  }
113
873
  },
874
+ define: {
875
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
876
+ "process.env": {}
877
+ },
878
+ resolve: {
879
+ alias: {
880
+ process: "process/browser"
881
+ }
882
+ // preserveSymlinks: true
883
+ },
114
884
  build: {
115
885
  rollupOptions: {
116
- // Exclude package `B` from the client-side bundle
117
- external: ["@xyd-js/uniform", "@xyd-js/uniform/content", "@xyd-js/plugin-zero"]
886
+ external: []
118
887
  }
119
888
  },
120
889
  ssr: {
121
- external: ["@xyd-js/uniform", "@xyd-js/uniform/content", "@xyd-js/plugin-zero"]
122
- // noExternal: [
123
- // "@xyd-js/uniform",
124
- // "@xyd-js/uniform/content",
125
- // "@xyd-js/plugin-zero"
126
- // ],
890
+ external: []
127
891
  },
128
892
  optimizeDeps: {
129
- include: ["react/jsx-runtime"]
893
+ include: [
894
+ "react/jsx-runtime",
895
+ ...USE_CONTEXT_ISSUE_PACKAGES
896
+ ]
897
+ // exclude: ["react", "react-dom"]
130
898
  },
131
- // @ts-ignore
132
899
  plugins: [
133
- // TODO: fix plugin ts
134
- ...xydContentVitePlugins2({
135
- toc: {
136
- minDepth: 2
900
+ ...commonRunVitePlugins,
901
+ {
902
+ name: "xyd-configureServer",
903
+ configureServer(s) {
904
+ server = s;
137
905
  }
138
- }),
139
- reactRouter2({
140
- routes: resp.routes
141
- }),
142
- ...resp.vitePlugins
906
+ }
143
907
  ]
144
908
  });
909
+ const watcher = fs3.watch(allowCwd, { recursive: true }, async (eventType, filename) => {
910
+ if (RELOADING) {
911
+ return;
912
+ }
913
+ if (!filename) {
914
+ console.log("[xyd:dev-watcher] Received empty filename");
915
+ return;
916
+ }
917
+ if (!server) {
918
+ console.log("[xyd:dev-watcher] Server not ready");
919
+ return;
920
+ }
921
+ const filePath = path3.join(allowCwd, filename);
922
+ if (filePath.includes(CACHE_FOLDER_PATH)) {
923
+ return;
924
+ }
925
+ const publicPathReload = filePath.includes(getPublicPath());
926
+ if (publicPathReload) {
927
+ const relativePath = path3.relative(allowCwd, filePath);
928
+ const urlPath = "/" + relativePath.replace(/\\/g, "/");
929
+ preview.ws.send({
930
+ type: "full-reload",
931
+ path: urlPath
932
+ });
933
+ return;
934
+ }
935
+ let apiPaths = {};
936
+ if (respPluginDocs?.settings?.api) {
937
+ apiPaths = resolveApiFilePaths(process.cwd(), respPluginDocs.settings.api);
938
+ }
939
+ const apiChanged = !!apiPaths[filePath];
940
+ const isSettingsFile = SUPPORTED_SETTINGS_FILES.some((ext) => filePath.endsWith(ext));
941
+ const isContentFile = SUPPORTED_CONTENT_FILES.some((ext) => filePath.endsWith(ext));
942
+ const isWatchFile = isSettingsFile || isContentFile || apiChanged;
943
+ if (!isWatchFile) {
944
+ return;
945
+ }
946
+ if (isContentFile && eventType !== "rename") {
947
+ console.log("\u{1F504} Content file changed, refresh...", eventType);
948
+ invalidateSettings(server);
949
+ await touchLayoutPage();
950
+ return;
951
+ }
952
+ const renameContentFile = isContentFile && eventType === "rename";
953
+ if (isSettingsFile || renameContentFile) {
954
+ if (renameContentFile) {
955
+ console.log("\u{1F504} Content file renamed, refresh...");
956
+ } else {
957
+ console.log("\u{1F504} Settings file changed, refresh...");
958
+ }
959
+ if (respPluginDocs?.settings.engine?.uniform?.store) {
960
+ await appInit({
961
+ disableFSWrite: true
962
+ });
963
+ } else {
964
+ await appInit();
965
+ }
966
+ const newSettings = await readSettings2();
967
+ if (typeof newSettings !== "object") {
968
+ console.log("[xyd:dev-watcher] Settings is not an object");
969
+ return;
970
+ }
971
+ invalidateSettings(server);
972
+ await touchReactRouterConfig();
973
+ await touchLayoutPage();
974
+ server.ws.send({ type: "full-reload" });
975
+ }
976
+ });
977
+ watcher.on("error", (error) => {
978
+ console.error("[xyd:dev] File watcher error:", error);
979
+ });
145
980
  await preview.listen(port);
981
+ if (respPluginDocs.settings.navigation) {
982
+ await optimizeDepsFix(port, respPluginDocs.settings.navigation);
983
+ }
146
984
  preview.printUrls();
147
985
  preview.bindCLIShortcuts({ print: true });
986
+ preview.httpServer?.once("close", () => {
987
+ watcher.close();
988
+ });
148
989
  }
149
-
150
- // src/run/serve.ts
151
- import fs2 from "node:fs";
152
- import os from "node:os";
153
- import path3 from "node:path";
154
- import url from "node:url";
155
- import { createRequestHandler } from "@react-router/express";
156
- import compression from "compression";
157
- import express from "express";
158
- import morgan from "morgan";
159
- import sourceMapSupport from "source-map-support";
160
- import getPort from "get-port";
161
- function parseNumber(raw) {
162
- if (raw === void 0) return void 0;
163
- let maybe = Number(raw);
164
- if (Number.isNaN(maybe)) return void 0;
165
- return maybe;
166
- }
167
- async function serve() {
168
- process.env.NODE_ENV = process.env.NODE_ENV ?? "production";
169
- sourceMapSupport.install({
170
- retrieveSourceMap: function(source) {
171
- let match = source.startsWith("file://");
172
- if (match) {
173
- let filePath = url.fileURLToPath(source);
174
- let sourceMapPath = `${filePath}.map`;
175
- if (fs2.existsSync(sourceMapPath)) {
176
- return {
177
- url: source,
178
- map: fs2.readFileSync(sourceMapPath, "utf8")
179
- };
990
+ function resolveApiFilePaths(basePath, api) {
991
+ const result = {};
992
+ const apis = [api.openapi, api.graphql, api.sources].filter((s) => s !== void 0);
993
+ apis.forEach((section) => {
994
+ flattenApiFile(section).forEach((p) => {
995
+ const apiAbsPath = path3.resolve(basePath, p);
996
+ result[apiAbsPath] = true;
997
+ });
998
+ });
999
+ return result;
1000
+ }
1001
+ function flattenApiFile(file) {
1002
+ if (!file) return [];
1003
+ if (typeof file === "string") {
1004
+ return [file];
1005
+ }
1006
+ if (Array.isArray(file)) {
1007
+ return file.flatMap(flattenApiFile);
1008
+ }
1009
+ if (typeof file === "object") {
1010
+ const obj = file;
1011
+ if (typeof obj.source === "string") {
1012
+ return [obj.source];
1013
+ }
1014
+ return Object.values(obj).flatMap(flattenApiFile);
1015
+ }
1016
+ return [];
1017
+ }
1018
+ function getFirstPageFromNavigation(navigation) {
1019
+ if (!navigation?.sidebar?.length) {
1020
+ return null;
1021
+ }
1022
+ function extractFirstPage(pages) {
1023
+ for (const page of pages) {
1024
+ if (typeof page === "string") {
1025
+ return normalizePagePath(page);
1026
+ }
1027
+ if (typeof page === "object") {
1028
+ if ("route" in page && page.pages) {
1029
+ const firstPage = extractFirstPage(page.pages);
1030
+ if (firstPage) return firstPage;
1031
+ }
1032
+ if ("pages" in page && page.pages) {
1033
+ const firstPage = extractFirstPage(page.pages);
1034
+ if (firstPage) return firstPage;
1035
+ }
1036
+ if ("page" in page && typeof page.page === "string") {
1037
+ return normalizePagePath(page.page);
180
1038
  }
181
1039
  }
182
- return null;
183
1040
  }
184
- });
185
- let port2 = parseNumber(process.env.PORT) ?? await getPort({ port: 3e3 });
186
- let buildPathArg = path3.join(process.cwd(), ".xyd/build/server/index.js");
187
- if (!buildPathArg) {
188
- console.error(`
189
- Usage: react-router-serve <server-build-path> - e.g. react-router-serve build/server/index.js`);
190
- process.exit(1);
191
- }
192
- let buildPath = path3.resolve(buildPathArg);
193
- let build2 = await import(url.pathToFileURL(buildPath).href);
194
- let onListen = () => {
195
- let address = process.env.HOST || Object.values(os.networkInterfaces()).flat().find((ip) => String(ip?.family).includes("4") && !ip?.internal)?.address;
196
- if (!address) {
197
- console.log(`[xyd-serve] http://localhost:${port2}`);
198
- } else {
199
- console.log(
200
- `[xyd-serve] http://localhost:${port2} (http://${address}:${port2})`
201
- );
1041
+ return null;
1042
+ }
1043
+ return extractFirstPage(navigation.sidebar);
1044
+ }
1045
+ function normalizePagePath(pagePath) {
1046
+ let normalized = pagePath.replace(/\.(md|mdx)$/, "");
1047
+ if (normalized.endsWith("/index") || normalized === "index") {
1048
+ normalized = normalized.replace(/\/?index$/, "");
1049
+ }
1050
+ if (normalized.startsWith("/")) {
1051
+ normalized = normalized.slice(1);
1052
+ }
1053
+ return normalized;
1054
+ }
1055
+ async function fetchFirstPage(firstPage, port) {
1056
+ const urlsToTry = [
1057
+ `http://localhost:${port}/${firstPage}`,
1058
+ `http://localhost:${port}/${firstPage}/`,
1059
+ `http://localhost:${port}/${firstPage}.html`,
1060
+ `http://localhost:${port}/${firstPage}/index.html`
1061
+ ];
1062
+ for (const url of urlsToTry) {
1063
+ try {
1064
+ const response = await fetch(url);
1065
+ if (response.ok) {
1066
+ return;
1067
+ }
1068
+ } catch (error) {
1069
+ continue;
202
1070
  }
203
- };
204
- build2 = {
205
- ...build2,
206
- assetsBuildDirectory: path3.join(process.cwd(), ".xyd/build/client")
207
- };
208
- let app = express();
209
- app.disable("x-powered-by");
210
- app.use(compression());
211
- app.use(
212
- path3.posix.join(build2.publicPath, "assets"),
213
- express.static(path3.join(build2.assetsBuildDirectory, "assets"), {
214
- immutable: true,
215
- maxAge: "1y"
216
- })
217
- );
218
- app.use(build2.publicPath, express.static(build2.assetsBuildDirectory));
219
- app.use(express.static("public", { maxAge: "1h" }));
220
- app.use(morgan("tiny"));
221
- app.all(
222
- "*",
223
- createRequestHandler({
224
- build: build2,
225
- mode: process.env.NODE_ENV
226
- })
227
- );
228
- let server = process.env.HOST ? app.listen(port2, process.env.HOST, onListen) : app.listen(port2, onListen);
229
- ["SIGTERM", "SIGINT"].forEach((signal) => {
230
- process.once(signal, () => server?.close(console.error));
1071
+ }
1072
+ }
1073
+ function invalidateSettings(server) {
1074
+ const virtualId = "virtual:xyd-settings";
1075
+ const resolvedId = virtualId + ".jsx";
1076
+ const mod = server.moduleGraph.getModuleById(resolvedId);
1077
+ if (!mod) {
1078
+ console.log("[xyd:dev-watcher] Settings module not found");
1079
+ return;
1080
+ }
1081
+ server.moduleGraph.invalidateModule(mod);
1082
+ server.ws.send({
1083
+ type: "update",
1084
+ updates: [
1085
+ {
1086
+ type: "js-update",
1087
+ path: `/@id/${resolvedId}`,
1088
+ acceptedPath: `/@id/${resolvedId}`,
1089
+ timestamp: Date.now()
1090
+ }
1091
+ ]
1092
+ });
1093
+ }
1094
+ async function touchReactRouterConfig() {
1095
+ const hostPath = getHostPath();
1096
+ const hostReactRouterConfig = path3.join(hostPath, "react-router.config.ts");
1097
+ await fs3.promises.utimes(hostReactRouterConfig, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
1098
+ }
1099
+ async function touchLayoutPage() {
1100
+ const docsPluginBasePath = getDocsPluginBasePath();
1101
+ const layoutPath = path3.join(docsPluginBasePath, "./src/pages/layout.tsx");
1102
+ await fs3.promises.utimes(layoutPath, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
1103
+ }
1104
+ async function optimizeDepsFix(port, navigation) {
1105
+ const firstPage = getFirstPageFromNavigation(navigation);
1106
+ if (firstPage) {
1107
+ await fetchFirstPage(firstPage, port);
1108
+ }
1109
+ }
1110
+
1111
+ // src/install.ts
1112
+ import fs4 from "fs";
1113
+ import { readSettings as readSettings3 } from "@xyd-js/plugin-docs";
1114
+ async function install() {
1115
+ const settings = await readSettings3();
1116
+ if (!settings) {
1117
+ throw new Error("cannot preload settings");
1118
+ }
1119
+ if (typeof settings === "string") {
1120
+ throw new Error("install does not support string settings");
1121
+ }
1122
+ const hostPath = getHostPath();
1123
+ if (fs4.existsSync(hostPath)) {
1124
+ fs4.rmSync(hostPath, { recursive: true, force: true });
1125
+ }
1126
+ await preWorkspaceSetup({
1127
+ force: true
231
1128
  });
1129
+ await postWorkspaceSetup(settings);
232
1130
  }
233
1131
  export {
234
1132
  build,
235
1133
  dev,
236
- serve
1134
+ install
237
1135
  };
238
1136
  //# sourceMappingURL=index.js.map