@valaxyjs/devtools 1.0.0-rc.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +151 -12
  2. package/dist/client/assets/FeedbackEmptyState-6lTUwFgn.js +1 -0
  3. package/dist/client/assets/LayoutCard-ZKe9PNVY.js +1 -0
  4. package/dist/client/assets/Teleport-qWljvtqZ.js +3 -0
  5. package/dist/client/assets/VDCheckbox-BQsCYaxD.js +1 -0
  6. package/dist/client/assets/VDCodeBlock-Bt5aM9HW.js +1 -0
  7. package/dist/client/assets/VDCodeBlock-C3pmQBwJ.css +1 -0
  8. package/dist/client/assets/VDNumberField-Can2q8VD.js +1 -0
  9. package/dist/client/assets/VDPostListItem-BGlmD-N3.js +1 -0
  10. package/dist/client/assets/VDPostPanel-CFfkiijD.css +1 -0
  11. package/dist/client/assets/VDPostPanel-CjYE_B3I.js +1 -0
  12. package/dist/client/assets/VDSelect-Cozhx4qY.js +1 -0
  13. package/dist/client/assets/VDToggleGroup-Ch8jnCMN.js +1 -0
  14. package/dist/client/assets/addons-D7_qAb67.css +1 -0
  15. package/dist/client/assets/addons-wN900N6P.js +1 -0
  16. package/dist/client/assets/app-djZMc7np.js +3 -0
  17. package/dist/client/assets/archives-DrTLr9Uc.js +1 -0
  18. package/dist/client/assets/batch-edit-UNPFWmV7.css +1 -0
  19. package/dist/client/assets/batch-edit-tNwm0yaw.js +1 -0
  20. package/dist/client/assets/browser-agent-rpc-BXhoSh1z-B_H6wwYe.js +1 -0
  21. package/dist/client/assets/categories-tEHj0fN0.js +1 -0
  22. package/dist/client/assets/collections-DZuCp-05.js +1 -0
  23. package/dist/client/assets/colors-CdKJdJxa.js +1 -0
  24. package/dist/client/assets/config-Di1Ylhm8.js +1 -0
  25. package/dist/client/assets/debug-ff8JDH7M.js +1 -0
  26. package/dist/client/assets/editor-ySVA1M8V.js +1 -0
  27. package/dist/client/assets/index-fPEmPwYD.css +1 -0
  28. package/dist/client/assets/index-qslCSpK8.js +4 -0
  29. package/dist/client/assets/nanoid-Cya-tyvy.js +1 -0
  30. package/dist/client/assets/pages-VHlqQIae.js +1 -0
  31. package/dist/client/assets/posts-BePByYIU.js +1 -0
  32. package/dist/client/assets/rpc-CHB0xuhS.js +4 -0
  33. package/dist/client/assets/runtime-dom.esm-bundler-COvr_-s-.js +2 -0
  34. package/dist/client/assets/settings-DvvjModb.js +1 -0
  35. package/dist/client/assets/splitpanes.esm-CnpdH7BM.js +1 -0
  36. package/dist/client/assets/tags-KCkr8YHU.js +1 -0
  37. package/dist/client/assets/virtual_intlify-i18n-0-BOFXizJp.js +1 -0
  38. package/dist/client/assets/virtual_intlify-i18n-1-CPnPqlXp.js +1 -0
  39. package/{LICENSE → dist/client/icons/LICENSE} +1 -1
  40. package/dist/client/icons/README.md +2 -0
  41. package/dist/client/icons/archive.svg +1 -0
  42. package/dist/client/icons/article.svg +1 -0
  43. package/dist/client/icons/books.svg +1 -0
  44. package/dist/client/icons/bug.svg +1 -0
  45. package/dist/client/icons/folders.svg +1 -0
  46. package/dist/client/icons/gear-six.svg +1 -0
  47. package/dist/client/icons/hash.svg +1 -0
  48. package/dist/client/icons/pencil-simple.svg +1 -0
  49. package/dist/client/icons/puzzle-piece.svg +1 -0
  50. package/dist/client/icons/sliders-horizontal.svg +1 -0
  51. package/dist/client/icons/squares-four.svg +1 -0
  52. package/dist/client/index.html +10 -5
  53. package/dist/client-api.d.mts +19 -0
  54. package/dist/client-api.d.ts +19 -0
  55. package/dist/client-api.mjs +52 -0
  56. package/dist/index.d.mts +12 -9
  57. package/dist/index.d.ts +12 -9
  58. package/dist/index.mjs +151 -626
  59. package/dist/node/definition.d.mts +10 -0
  60. package/dist/node/definition.d.ts +10 -0
  61. package/dist/node/definition.mjs +1196 -0
  62. package/dist/node/mcp.d.mts +26 -0
  63. package/dist/node/mcp.d.ts +26 -0
  64. package/dist/node/mcp.mjs +250 -0
  65. package/dist/page.d.mts +12 -0
  66. package/dist/page.d.ts +12 -0
  67. package/dist/page.mjs +29 -0
  68. package/dist/plugin.d.mts +49 -0
  69. package/dist/plugin.d.ts +49 -0
  70. package/dist/plugin.mjs +5 -0
  71. package/dist/shared/devtools.BbttzjAw.mjs +46 -0
  72. package/dist/shared/devtools.BkRFLW7i.d.mts +58 -0
  73. package/dist/shared/devtools.BzWtXMed.mjs +3 -0
  74. package/dist/shared/devtools.CBhjeyeH.mjs +16 -0
  75. package/dist/shared/devtools.CY2Osfc0.d.ts +181 -0
  76. package/dist/shared/devtools.O-VZ9RtQ.d.mts +30 -0
  77. package/dist/shared/devtools.O-VZ9RtQ.d.ts +30 -0
  78. package/dist/shared/devtools.cHv3kjQy.d.mts +181 -0
  79. package/dist/shared/devtools.qCbHUUKc.d.ts +58 -0
  80. package/dist/shared/rpc.d.mts +169 -0
  81. package/dist/shared/rpc.d.ts +169 -0
  82. package/dist/shared/rpc.mjs +1 -0
  83. package/package.json +57 -27
  84. package/rpc.d.ts +1 -100
  85. package/dist/client/assets/VDButton-BxA3M5c6.js +0 -1
  86. package/dist/client/assets/VDCheckbox-0sYINIz1.js +0 -1
  87. package/dist/client/assets/VDInput-BUIBF6tW.js +0 -1
  88. package/dist/client/assets/VDInput-BtxYqBt3.css +0 -1
  89. package/dist/client/assets/VDNumberField-B_Uy91X1.js +0 -1
  90. package/dist/client/assets/VDPostListItem-BWod4Rd3.js +0 -1
  91. package/dist/client/assets/VDPostPanel-BQX_2a-x.js +0 -1
  92. package/dist/client/assets/VDPostPanel-Bkkd-Lkf.css +0 -1
  93. package/dist/client/assets/VDSelect-Dv55A88g.js +0 -1
  94. package/dist/client/assets/VDToggleGroup-Cn4kFzzB.js +0 -1
  95. package/dist/client/assets/archives-BsJ6lWB5.js +0 -1
  96. package/dist/client/assets/batch-edit-BUXwgmdP.js +0 -1
  97. package/dist/client/assets/batch-edit-BYL9g3v4.css +0 -1
  98. package/dist/client/assets/categories-DPzSwzgg.js +0 -1
  99. package/dist/client/assets/collections-CV7Cquhj.js +0 -1
  100. package/dist/client/assets/config-gA8k2aU6.js +0 -1
  101. package/dist/client/assets/index-DIDH_NZl.css +0 -1
  102. package/dist/client/assets/index-DYctjNWx.js +0 -6
  103. package/dist/client/assets/pages-DMZ4NY6F.js +0 -1
  104. package/dist/client/assets/posts-uQp5P0SG.js +0 -1
  105. package/dist/client/assets/settings-DcjBGHdn.js +0 -1
  106. package/dist/client/assets/splitpanes.esm-B-DN0qHF.js +0 -1
  107. package/dist/client/assets/tags-DVQEYnxm.js +0 -1
  108. package/dist/client/assets/virtual_intlify-i18n-0-C_fbdMlw.js +0 -1
  109. package/dist/client/assets/virtual_intlify-i18n-1-CjutLn3A.js +0 -1
  110. package/dist/client/assets/vue.runtime.esm-bundler-DqDZGG6R.js +0 -4
package/dist/index.mjs CHANGED
@@ -1,652 +1,177 @@
1
- import { colors } from 'consola/utils';
2
- import sirv from 'sirv';
3
- import { dirname, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import bodyParser from 'body-parser';
1
+ import { createPluginFromDevframe } from '@vitejs/devtools-kit/node';
2
+ import { initDevframe } from 'devframe/initiate';
3
+ import { buildOtpAuthUrl } from 'devframe/node/auth';
4
+ import { serveStaticNodeMiddleware } from 'devframe/utils/serve-static';
5
+ import { R as RESOURCES_STATE, r as resolveDevtoolsBase, a as DEVTOOLS_FRAME_ID, b as resolveDevtoolsLogo } from './shared/devtools.CBhjeyeH.mjs';
6
+ import { createValaxyDevframe } from './node/definition.mjs';
6
7
  import process from 'node:process';
7
- import dayjs from 'dayjs';
8
- import fg from 'fast-glob';
9
- import fs from 'fs-extra';
10
- import matter from 'gray-matter';
11
8
  import pathe from 'pathe';
12
- import { generateCode, parseModule } from 'magicast';
13
- import { JSON_SCHEMA } from 'js-yaml';
9
+ import { addons } from '@valaxyjs/utils';
10
+ import 'devframe';
11
+ import 'valibot';
12
+ import './shared/devtools.BbttzjAw.mjs';
13
+ import 'fs-extra';
14
+ import 'node:path';
15
+ import 'node:url';
16
+ import 'node:crypto';
17
+ import 'cross-spawn';
18
+ import 'tinyglobby';
19
+ import 'node:fs/promises';
20
+ import 'magicast';
21
+ import 'devframe/utils/launch-editor';
22
+ import 'dayjs';
23
+ import 'gray-matter';
24
+ import 'js-yaml';
14
25
 
15
26
  const NAMESPACE = "valaxy:devtools";
16
27
 
17
- const DIR_DIST = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
18
- const DEVTOOLS_CLIENT_FOLDER = resolve(DIR_DIST, "../dist/client");
19
- const DIR_CLIENT = DEVTOOLS_CLIENT_FOLDER;
20
-
21
- const DANGEROUS_FIELD_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
22
- function validateFieldPath(fieldPath) {
23
- const parts = fieldPath.split(".");
24
- return parts.every((part) => part.length > 0 && !DANGEROUS_FIELD_KEYS.has(part));
25
- }
26
- function assertInsideRoot(root, targetFile) {
27
- const relative = pathe.relative(root, targetFile);
28
- if (relative.startsWith("..") || pathe.isAbsolute(relative))
29
- throw new Error(`Config path is outside user root: ${targetFile}`);
30
- }
31
- function setNestedValue(obj, path, value) {
32
- const parts = path.split(".");
33
- let current = obj;
34
- for (let i = 0; i < parts.length - 1; i++) {
35
- const part = parts[i];
36
- if (current[part] == null || typeof current[part] !== "object") {
37
- current[part] = {};
38
- }
39
- current = current[part];
40
- }
41
- current[parts.at(-1)] = value;
42
- }
43
- async function parseConfigFile(filePath) {
44
- const content = await fs.readFile(filePath, "utf-8");
45
- const mod = parseModule(content);
46
- return mod;
47
- }
48
- function serializeProxy(value) {
49
- try {
50
- if (value == null)
51
- return value;
52
- if (typeof value !== "object")
53
- return value;
54
- if (value.$type === "function-call") {
55
- const callee = value.$callee ?? "";
56
- const args = value.$args ?? [];
57
- const serializedArgs = args.map(
58
- (a) => typeof a === "string" ? `'${a}'` : JSON.stringify(a)
59
- ).join(", ");
60
- return `${callee}(${serializedArgs})`;
61
- }
62
- if (value.$type === "identifier") {
63
- return String(value.$id ?? value);
64
- }
65
- if (value.$type && value.$type !== "object") {
66
- return `<${value.$type}>`;
67
- }
68
- if (Array.isArray(value)) {
69
- return value.map((item) => {
70
- try {
71
- return serializeProxy(item);
72
- } catch {
73
- return "<unsupported>";
74
- }
75
- });
76
- }
77
- const result = {};
78
- for (const key of Object.keys(value)) {
79
- if (key.startsWith("$"))
80
- continue;
81
- try {
82
- result[key] = serializeProxy(value[key]);
83
- } catch {
84
- result[key] = "<unsupported expression>";
85
- }
86
- }
87
- return result;
88
- } catch {
89
- return "<unsupported expression>";
90
- }
91
- }
92
- async function readConfigs(userRoot) {
93
- const siteConfigPath = pathe.resolve(userRoot, "site.config.ts");
94
- const valaxyConfigPath = pathe.resolve(userRoot, "valaxy.config.ts");
95
- let siteConfig = {};
96
- let valaxyConfig = {};
97
- let themeConfig = {};
98
- const siteConfigExists = await fs.pathExists(siteConfigPath);
99
- const valaxyConfigExists = await fs.pathExists(valaxyConfigPath);
100
- if (siteConfigExists) {
101
- try {
102
- const mod = await parseConfigFile(siteConfigPath);
103
- const defaultExport = mod.exports.default;
104
- if (defaultExport && typeof defaultExport === "object") {
105
- siteConfig = serializeProxy(defaultExport.$args?.[0] ?? defaultExport);
106
- }
107
- } catch (e) {
108
- console.error("[devtools] Failed to parse site.config.ts:", e);
109
- }
110
- }
111
- if (valaxyConfigExists) {
112
- try {
113
- const mod = await parseConfigFile(valaxyConfigPath);
114
- const defaultExport = mod.exports.default;
115
- if (defaultExport && typeof defaultExport === "object") {
116
- const configObj = defaultExport.$args?.[0] ?? defaultExport;
117
- const raw = serializeProxy(configObj);
118
- if (raw.themeConfig) {
119
- themeConfig = raw.themeConfig;
120
- delete raw.themeConfig;
121
- }
122
- if (raw.siteConfig) {
123
- delete raw.siteConfig;
124
- }
125
- valaxyConfig = raw;
126
- }
127
- } catch (e) {
128
- console.error("[devtools] Failed to parse valaxy.config.ts:", e);
129
- }
130
- }
131
- return {
132
- siteConfig,
133
- valaxyConfig,
134
- themeConfig,
135
- siteConfigExists,
136
- valaxyConfigExists,
137
- siteConfigPath,
138
- valaxyConfigPath
28
+ async function watchResources(server, ctx, options) {
29
+ const state = await ctx.rpc.sharedState.get(RESOURCES_STATE);
30
+ const root = pathe.resolve(options.userRoot || process.cwd());
31
+ let timer;
32
+ const changed = (_event, file) => {
33
+ const relative = pathe.relative(root, file);
34
+ if (!relative.startsWith("pages/") && !["site.config.ts", "valaxy.config.ts", "valaxy.config.mts", "valaxy.config.js", "valaxy.config.mjs", "package.json", "pnpm-lock.yaml"].includes(relative))
35
+ return;
36
+ clearTimeout(timer);
37
+ timer = setTimeout(() => state.mutate((value) => {
38
+ value.revision++;
39
+ }), 100);
40
+ };
41
+ server.watcher.add(["pages", "site.config.ts", "valaxy.config.ts", "valaxy.config.mts", "valaxy.config.js", "valaxy.config.mjs", "package.json", "pnpm-lock.yaml"].map((file) => pathe.join(root, file)));
42
+ server.watcher.on("all", changed);
43
+ return () => {
44
+ clearTimeout(timer);
45
+ server.watcher.off("all", changed);
139
46
  };
140
- }
141
- const SITE_CONFIG_TEMPLATE = `import { defineSiteConfig } from 'valaxy'
142
-
143
- export default defineSiteConfig({
144
- })
145
- `;
146
- const VALAXY_CONFIG_TEMPLATE = `import { defineValaxyConfig } from 'valaxy'
147
-
148
- export default defineValaxyConfig({
149
- })
150
- `;
151
- async function writeConfigField(userRoot, configType, fieldPath, value) {
152
- if (!validateFieldPath(fieldPath)) {
153
- throw new Error(`Invalid field path: ${fieldPath}`);
154
- }
155
- const targetFile = configType === "site" ? pathe.resolve(userRoot, "site.config.ts") : pathe.resolve(userRoot, "valaxy.config.ts");
156
- const template = configType === "site" ? SITE_CONFIG_TEMPLATE : VALAXY_CONFIG_TEMPLATE;
157
- assertInsideRoot(userRoot, targetFile);
158
- if (!await fs.pathExists(targetFile)) {
159
- await fs.writeFile(targetFile, template, "utf-8");
160
- }
161
- const mod = await parseConfigFile(targetFile);
162
- const defaultExport = mod.exports.default;
163
- if (!defaultExport) {
164
- throw new Error(`No default export found in ${targetFile}`);
165
- }
166
- const configObj = defaultExport.$args?.[0] ?? defaultExport;
167
- if (configType === "theme") {
168
- if (!configObj.themeConfig || typeof configObj.themeConfig !== "object") {
169
- configObj.themeConfig = {};
170
- }
171
- setNestedValue(configObj.themeConfig, fieldPath, value);
172
- } else if (configType === "valaxy") {
173
- setNestedValue(configObj, fieldPath, value);
174
- } else {
175
- setNestedValue(configObj, fieldPath, value);
176
- }
177
- const { code } = generateCode(mod);
178
- await fs.writeFile(targetFile, code, "utf-8");
179
- }
180
-
181
- async function migration(path, frontmatter) {
182
- if (fs.existsSync(path)) {
183
- const rawMd = await fs.readFile(path, "utf-8");
184
- const matterFile = matter(rawMd, { schema: JSON_SCHEMA });
185
- let mod = false;
186
- for (const key in frontmatter) {
187
- if (key in matterFile.data) {
188
- matterFile.data[frontmatter[key]] = matterFile.data[key];
189
- delete matterFile.data[key];
190
- mod = true;
191
- }
192
- }
193
- if (mod) {
194
- const newMd = matter.stringify(matterFile.content, matterFile.data);
195
- await fs.writeFile(path, newMd);
196
- }
197
- }
198
47
  }
199
48
 
200
- function ensurePrefix(prefix, str) {
201
- if (!str.startsWith(prefix))
202
- return prefix + str;
203
- return str;
204
- }
205
- function extractStringField(content, field) {
206
- const regex = new RegExp(`\\b${field}\\s*:\\s*['"\`]([^'"\`]*)['"\`]`);
207
- const match = content.match(regex);
208
- return match?.[1] || "";
209
- }
210
- function extractBooleanField(content, field, defaultValue) {
211
- const regex = new RegExp(`\\b${field}\\s*:\\s*(true|false)`);
212
- const match = content.match(regex);
213
- if (!match)
214
- return defaultValue;
215
- return match[1] === "true";
216
- }
217
- function extractConfigItems(content) {
218
- const items = [];
219
- const itemsMatch = content.match(/items\s*:\s*\[([^\]]*)\]/);
220
- if (!itemsMatch)
221
- return items;
222
- const itemsContent = itemsMatch[1];
223
- const objectRegex = /\{([^}]*)\}/g;
224
- let objMatch;
225
- while ((objMatch = objectRegex.exec(itemsContent)) !== null) {
226
- const block = objMatch[1];
227
- const keyMatch = block.match(/key\s*:\s*['"`]([^'"`]*)['"`]/);
228
- const titleMatch = block.match(/title\s*:\s*['"`]([^'"`]*)['"`]/);
229
- const linkMatch = block.match(/link\s*:\s*['"`]([^'"`]*)['"`]/);
230
- items.push({
231
- key: keyMatch?.[1],
232
- title: titleMatch?.[1],
233
- link: linkMatch?.[1]
234
- });
235
- }
236
- return items;
237
- }
238
- function getFunctions(server, devtoolsOptions) {
239
- const userRoot = (devtoolsOptions.userRoot || process.cwd()).replace(/\\/g, "/");
240
- function getRoutePath(filePath) {
241
- const relativePath = pathe.relative(pathe.resolve(userRoot, "pages"), filePath).slice(0, -".md".length);
242
- return ensurePrefix("/", relativePath);
49
+ function ValaxyDevtools(options = {}) {
50
+ let stopWatching;
51
+ let standalone;
52
+ let definition;
53
+ let openPath;
54
+ function resolveOptions(server, base = "/") {
55
+ return {
56
+ ...options,
57
+ base: options.base ?? base,
58
+ siteUrl: options.siteUrl ?? (() => server?.resolvedUrls?.local[0] || "")
59
+ };
243
60
  }
244
61
  return {
245
- async getOptions() {
246
- return {
247
- userRoot
248
- };
249
- },
250
- async getPostList() {
251
- const files = await fg(`${userRoot}/pages/posts/**/*.md`);
252
- const posts = [];
253
- for await (const file of files) {
254
- const md = await fs.readFile(file, "utf-8");
255
- const { data } = matter(md);
256
- posts.push({
257
- routePath: getRoutePath(file),
258
- frontmatter: data,
259
- filePath: file
260
- });
62
+ name: NAMESPACE,
63
+ apply: "serve",
64
+ api: {
65
+ /** Public browser entry; authentication remains owned by Devframe. */
66
+ getOpenPath: () => openPath,
67
+ /** Pair a local host through Devframe's expiring fragment-based link. */
68
+ getStandaloneOpenUrl(origin) {
69
+ const url = new URL(origin);
70
+ if (!standalone || url.protocol !== "http:" || url.hostname !== "127.0.0.1")
71
+ return void 0;
72
+ return buildOtpAuthUrl(new URL(standalone.base, url).href);
261
73
  }
262
- return {
263
- // sort by updated
264
- posts: posts.sort((a, b) => {
265
- const bDateValue = dayjs(b.frontmatter.updated || b.frontmatter.date).valueOf();
266
- const aDateValue = dayjs(a.frontmatter.updated || a.frontmatter.date).valueOf();
267
- return bDateValue - aDateValue;
268
- }),
269
- root: userRoot
270
- };
271
74
  },
272
- async getPageData(pagePath) {
273
- const relativePath = pagePath.startsWith("/") ? pagePath.slice(1) : pagePath;
274
- const file = pathe.resolve(userRoot, relativePath);
275
- const { data } = matter(file);
276
- return {
277
- routePath: getRoutePath(file),
278
- filePath: file,
279
- frontmatter: data
280
- };
281
- },
282
- async updateFrontmatter(req) {
283
- const { filePath, frontmatter: newFm } = req;
284
- const pagesDir = pathe.resolve(userRoot, "pages");
285
- const resolved = pathe.resolve(filePath);
286
- const rel = pathe.relative(pagesDir, resolved);
287
- if (rel.startsWith("..") || pathe.isAbsolute(rel) || !resolved.endsWith(".md"))
288
- throw new Error("Invalid file path: must be within pages directory and end with .md");
289
- if (!fs.existsSync(resolved))
290
- throw new Error(`File not found: ${resolved}`);
291
- const rawMd = await fs.readFile(resolved, "utf-8");
292
- const matterFile = matter(rawMd);
293
- matterFile.data = newFm;
294
- const newMd = matter.stringify(matterFile.content, matterFile.data);
295
- await fs.writeFile(resolved, newMd);
296
- return { success: true };
297
- },
298
- async getCollectionList() {
299
- const collectionsRoot = pathe.resolve(userRoot, "pages", "collections");
300
- if (!await fs.pathExists(collectionsRoot))
301
- return [];
302
- const entries = await fs.readdir(collectionsRoot, { withFileTypes: true });
303
- const dirs = entries.filter((f) => f.isDirectory()).map((f) => f.name);
304
- const result = [];
305
- for (const dir of dirs) {
306
- const indexPath = pathe.join(collectionsRoot, dir, "index.ts");
307
- if (!await fs.pathExists(indexPath))
308
- continue;
309
- const indexContent = await fs.readFile(indexPath, "utf-8");
310
- const title = extractStringField(indexContent, "title");
311
- const cover = extractStringField(indexContent, "cover");
312
- const description = extractStringField(indexContent, "description");
313
- const collapse = extractBooleanField(indexContent, "collapse", true);
314
- const mdFiles = await fg(`${collectionsRoot}/${dir}/*.md`);
315
- const items = [];
316
- for (const file of mdFiles) {
317
- const basename = pathe.basename(file, ".md");
318
- if (basename === "index")
319
- continue;
320
- const md = await fs.readFile(file, "utf-8");
321
- const { data } = matter(md);
322
- items.push({
323
- title: data.title || basename,
324
- key: basename,
325
- filePath: file,
326
- frontmatter: data
327
- });
328
- }
329
- const configItems = extractConfigItems(indexContent);
330
- if (configItems.length > 0) {
331
- for (const ci of configItems) {
332
- if (ci.link && !items.some((i) => i.key === ci.key)) {
333
- items.push({
334
- title: ci.title || ci.link,
335
- key: ci.key || "",
336
- link: ci.link,
337
- filePath: "",
338
- frontmatter: {}
339
- });
340
- }
75
+ devtools: {
76
+ capabilities: { build: false },
77
+ async setup(ctx) {
78
+ const resolved = resolveOptions(ctx.viteServer, ctx.viteConfig.base);
79
+ definition = createValaxyDevframe(resolved);
80
+ const plugin = createPluginFromDevframe(definition, {
81
+ base: resolveDevtoolsBase(resolved.base),
82
+ dock: {
83
+ category: "framework",
84
+ groupId: "valaxy:tools",
85
+ frameId: DEVTOOLS_FRAME_ID,
86
+ subTabs: { protocol: "postmessage" },
87
+ visibility: "false"
341
88
  }
342
- const orderMap = /* @__PURE__ */ new Map();
343
- configItems.forEach((ci, i) => {
344
- if (ci.key)
345
- orderMap.set(`key:${ci.key}`, i);
346
- else if (ci.link)
347
- orderMap.set(`link:${ci.link}`, i);
348
- });
349
- items.sort((a, b) => {
350
- const aIdx = (a.key ? orderMap.get(`key:${a.key}`) : orderMap.get(`link:${a.link}`)) ?? Infinity;
351
- const bIdx = (b.key ? orderMap.get(`key:${b.key}`) : orderMap.get(`link:${b.link}`)) ?? Infinity;
352
- if (aIdx === bIdx)
353
- return 0;
354
- return aIdx - bIdx;
355
- });
356
- } else {
357
- items.sort((a, b) => {
358
- const aVal = dayjs(a.frontmatter.date).valueOf();
359
- const bVal = dayjs(b.frontmatter.date).valueOf();
360
- const aDate = Number.isNaN(aVal) ? 0 : aVal;
361
- const bDate = Number.isNaN(bVal) ? 0 : bVal;
362
- return aDate - bDate;
363
- });
364
- }
365
- const itemsSectionIndex = indexContent.indexOf("items:");
366
- const topLevelArea = itemsSectionIndex === -1 ? indexContent : indexContent.slice(0, itemsSectionIndex);
367
- const key = extractStringField(topLevelArea, "key") || dir;
368
- result.push({
369
- key,
370
- title,
371
- cover,
372
- description,
373
- collapse,
374
- dirPath: pathe.join(collectionsRoot, dir),
375
- items
376
89
  });
377
- }
378
- return result;
379
- },
380
- async batchUpdateFrontmatter(filePaths, operations) {
381
- const pagesDir = pathe.resolve(userRoot, "pages");
382
- const result = {
383
- total: filePaths.length,
384
- updated: 0,
385
- errors: []
386
- };
387
- for (const filePath of filePaths) {
388
- try {
389
- const resolved = pathe.resolve(filePath);
390
- const rel = pathe.relative(pagesDir, resolved);
391
- if (rel.startsWith("..") || pathe.isAbsolute(rel) || !resolved.endsWith(".md")) {
392
- result.errors.push({ filePath, error: "Invalid file path: must be within pages directory and end with .md" });
393
- continue;
394
- }
395
- if (!await fs.pathExists(resolved)) {
396
- result.errors.push({ filePath, error: "File not found" });
397
- continue;
398
- }
399
- const rawMd = await fs.readFile(resolved, "utf-8");
400
- const matterFile = matter(rawMd);
401
- let modified = false;
402
- for (const op of operations) {
403
- if (DANGEROUS_FIELD_KEYS.has(op.key) || op.newKey && DANGEROUS_FIELD_KEYS.has(op.newKey))
404
- continue;
405
- switch (op.type) {
406
- case "set":
407
- matterFile.data[op.key] = op.value;
408
- modified = true;
409
- break;
410
- case "delete":
411
- if (op.key in matterFile.data) {
412
- delete matterFile.data[op.key];
413
- modified = true;
414
- }
415
- break;
416
- case "rename":
417
- if (op.key in matterFile.data && op.newKey) {
418
- matterFile.data[op.newKey] = matterFile.data[op.key];
419
- delete matterFile.data[op.key];
420
- modified = true;
421
- }
422
- break;
423
- }
424
- }
425
- if (modified) {
426
- const newMd = matter.stringify(matterFile.content, matterFile.data);
427
- await fs.writeFile(resolved, newMd);
428
- result.updated++;
429
- }
430
- } catch (e) {
431
- result.errors.push({ filePath, error: e.message || String(e) });
90
+ ctx.docks.register({ id: "valaxy:tools", type: "group", title: "Valaxy", icon: resolveDevtoolsLogo(resolved.base), category: "framework", defaultChildId: "valaxy" });
91
+ await plugin.devtools.setup(ctx);
92
+ openPath = resolveDevtoolsBase(resolved.base);
93
+ const manifest = await ctx.rpc.invokeLocal("valaxy:get-extensions");
94
+ for (const extension of manifest.plugins) {
95
+ for (const panel of extension.panels)
96
+ ctx.docks.register({ ...panel, type: "iframe", groupId: "valaxy:tools", category: "app" });
432
97
  }
98
+ if (ctx.viteServer)
99
+ stopWatching = await watchResources(ctx.viteServer, ctx, resolved);
433
100
  }
434
- return result;
435
101
  },
436
- async getConfig() {
437
- return readConfigs(userRoot);
438
- },
439
- async updateConfigField(configType, fieldPath, value) {
440
- try {
441
- await writeConfigField(userRoot, configType, fieldPath, value);
442
- return { success: true };
443
- } catch (e) {
444
- return { success: false, error: e.message || String(e) };
445
- }
446
- },
447
- async runMigration(filePaths, frontmatter) {
448
- const workers = filePaths.map((path) => migration(path, frontmatter));
449
- await Promise.all(workers);
450
- return { success: true };
102
+ async configureServer(server) {
103
+ if (server.config.devtools && server.config.devtools.enabled)
104
+ return;
105
+ const resolved = resolveOptions(server, server.config.base);
106
+ const httpServer = server.httpServer && "headersTimeout" in server.httpServer ? server.httpServer : void 0;
107
+ definition = createValaxyDevframe(resolved);
108
+ const frame = definition;
109
+ standalone = initDevframe({
110
+ ...frame,
111
+ async setup(ctx, info) {
112
+ const mountStatic = ctx.host.mountStatic;
113
+ ctx.host.mountStatic = (base, source) => {
114
+ if (typeof source === "string")
115
+ server.middlewares.use(base, serveStaticNodeMiddleware(source));
116
+ else return mountStatic(base, source);
117
+ };
118
+ await frame.setup(ctx, info);
119
+ }
120
+ }, {
121
+ base: resolveDevtoolsBase(resolved.base),
122
+ server: httpServer,
123
+ ws: httpServer ? void 0 : false,
124
+ mcp: false
125
+ });
126
+ server.middlewares.use(standalone.nodeMiddleware);
127
+ openPath = standalone.base;
128
+ stopWatching = await watchResources(server, await standalone.context, resolved);
451
129
  },
452
- async createPost(options) {
130
+ async closeBundle() {
131
+ openPath = void 0;
132
+ stopWatching?.();
133
+ stopWatching = void 0;
453
134
  try {
454
- const { title, path: customPath, tags, categories } = options;
455
- const postsDir = pathe.resolve(userRoot, "pages", "posts");
456
- let filePath;
457
- if (customPath) {
458
- const normalized = customPath.endsWith(".md") ? customPath : `${customPath}.md`;
459
- filePath = pathe.resolve(postsDir, normalized);
460
- const rel = pathe.relative(postsDir, filePath);
461
- if (rel.startsWith("..") || pathe.isAbsolute(rel))
462
- return { success: false, error: "Invalid path: must be within posts directory" };
463
- } else {
464
- const slug = title.toLowerCase().replace(/[\s_]+/g, "-").replace(/[^\w\u4E00-\u9FFF-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "") || `post-${Date.now()}`;
465
- filePath = pathe.resolve(postsDir, `${slug}.md`);
466
- }
467
- await fs.ensureDir(pathe.dirname(filePath));
468
- if (await fs.pathExists(filePath)) {
469
- const ext = pathe.extname(filePath);
470
- const base = filePath.slice(0, -ext.length);
471
- let counter = 1;
472
- while (await fs.pathExists(filePath)) {
473
- filePath = `${base}-${counter}${ext}`;
474
- counter++;
475
- }
476
- }
477
- const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
478
- const frontmatter = {
479
- title,
480
- date: now,
481
- updated: now,
482
- draft: true
483
- };
484
- if (tags && tags.length > 0)
485
- frontmatter.tags = tags;
486
- if (categories && categories.length > 0)
487
- frontmatter.categories = categories;
488
- const content = matter.stringify("\n", frontmatter);
489
- await fs.writeFile(filePath, content, "utf-8");
490
- return { success: true, filePath };
491
- } catch (e) {
492
- return { success: false, error: e.message || String(e) };
135
+ await definition?.dispose();
136
+ } finally {
137
+ await standalone?.close();
138
+ standalone = void 0;
139
+ definition = void 0;
493
140
  }
494
141
  }
495
142
  };
496
143
  }
497
144
 
498
- const prefix = "/valaxy-devtools-api";
499
- function isExactRouteRequest(req) {
500
- const pathname = new URL(req.url || "/", "http://localhost").pathname;
501
- return pathname === "/" || pathname === "";
502
- }
503
- function sendJson(res, data) {
504
- res.setHeader("Content-Type", "application/json");
505
- res.end(JSON.stringify(data));
506
- }
507
- function sendError(res, statusCode, error) {
508
- res.statusCode = statusCode;
509
- sendJson(res, { error });
510
- }
511
- function createRoute(handlers) {
512
- return async (req, res, next) => {
513
- if (!isExactRouteRequest(req)) {
514
- next?.();
515
- return;
516
- }
517
- const method = req.method?.toUpperCase();
518
- const handler = handlers[method];
519
- if (!handler) {
520
- next?.();
521
- return;
522
- }
523
- try {
524
- const data = await handler(req, res);
525
- if (!res.writableEnded)
526
- sendJson(res, data);
527
- } catch (e) {
528
- sendError(res, 500, e?.message || String(e));
529
- }
530
- };
531
- }
532
- function registerApi(server, _viteConfig, options = {}) {
533
- const app = server.middlewares;
534
- app.use(bodyParser.json());
535
- const functions = getFunctions(server, options);
536
- app.use(`${prefix}/options`, createRoute({
537
- GET: () => functions.getOptions()
538
- }));
539
- app.use(`${prefix}/posts`, createRoute({
540
- GET: () => functions.getPostList(),
541
- POST: async (req, res) => {
542
- const body = req.body;
543
- if (!body?.title) {
544
- sendError(res, 400, "Missing title");
545
- return;
546
- }
547
- return functions.createPost(body);
548
- }
549
- }));
550
- app.use(`${prefix}/pages`, createRoute({
551
- GET: async (req, res) => {
552
- const url = new URL(req.url || "", "http://localhost");
553
- const pagePath = url.searchParams.get("path");
554
- if (!pagePath) {
555
- sendError(res, 400, 'Missing "path" query parameter');
556
- return;
557
- }
558
- return functions.getPageData(pagePath);
559
- }
560
- }));
561
- app.use(`${prefix}/collections`, createRoute({
562
- GET: () => functions.getCollectionList()
563
- }));
564
- app.use(`${prefix}/frontmatter/batch`, createRoute({
565
- POST: async (req, res) => {
566
- const body = req.body;
567
- const { filePaths, operations } = body;
568
- if (!Array.isArray(filePaths) || !Array.isArray(operations)) {
569
- sendError(res, 400, "Invalid request: filePaths and operations must be arrays");
570
- return;
571
- }
572
- for (const op of operations) {
573
- if (!op || typeof op.type !== "string" || typeof op.key !== "string") {
574
- sendError(res, 400, "Invalid operation: each operation must have type and key");
575
- return;
576
- }
577
- }
578
- return functions.batchUpdateFrontmatter(filePaths, operations);
579
- }
580
- }));
581
- app.use(`${prefix}/frontmatter`, createRoute({
582
- POST: async (req) => {
583
- return functions.updateFrontmatter(req.body);
584
- }
585
- }));
586
- app.use(`${prefix}/migration`, createRoute({
587
- POST: async (req) => {
588
- const { filePaths, frontmatter } = req.body;
589
- return functions.runMigration(filePaths, frontmatter);
590
- }
591
- }));
592
- app.use(`${prefix}/config`, createRoute({
593
- GET: () => functions.getConfig(),
594
- PUT: async (req, res) => {
595
- const body = req.body;
596
- const { configType, fieldPath, value } = body;
597
- if (!configType || !fieldPath) {
598
- sendError(res, 400, "Missing configType or fieldPath");
599
- return;
600
- }
601
- return functions.updateConfigField(configType, fieldPath, value);
602
- }
603
- }));
604
- }
605
-
606
- function ValaxyDevtools(options = {}) {
607
- let config;
608
- const isDevDevtools = import.meta.env?.VITE_VALAXY_DEVTOOLS_DEV === "true";
609
- function configureServer(server) {
610
- const _print = server.printUrls;
611
- const base = (options.base ?? server.config.base) || "/";
612
- const devtoolsUrl = `${base}__valaxy_devtools__/`;
613
- if (!isDevDevtools) {
614
- server.middlewares.use(devtoolsUrl, sirv(DIR_CLIENT, {
615
- single: true,
616
- dev: true
617
- }));
618
- }
619
- server.printUrls = () => {
620
- let host = `${config.server.https ? "https" : "http"}://localhost:${config.server.port || "80"}`;
621
- const url = server.resolvedUrls?.local[0];
622
- if (url) {
623
- try {
624
- const u = new URL(url);
625
- host = `${u.protocol}//${u.host}`;
626
- } catch (error) {
627
- console.warn("Parse resolved url failed:", error);
628
- }
629
- }
630
- _print();
631
- const colorUrl = (url2) => colors.green(url2.replace(/:(\d+)\//, (_, port) => `:${colors.bold(port)}/`));
632
- console.log(` ${colors.green("\u279C")} ${colors.bold("Inspect")}: ${colorUrl(`${host}${base}__inspect/`)}`);
633
- };
634
- registerApi(server, config, options);
635
- }
636
- const plugin = {
637
- name: NAMESPACE,
638
- enforce: "pre",
639
- // config: () => { },
640
- configResolved(_config) {
641
- config = _config;
642
- },
643
- configureServer(server) {
644
- configureServer(server);
645
- }
646
- };
647
- return plugin;
648
- }
145
+ const editorPresentations = [
146
+ { commands: ["code"], name: "Visual Studio Code", icon: "i-vscode-icons:file-type-vscode" },
147
+ { commands: ["code-insiders"], name: "VS Code Insiders", icon: "i-vscode-icons:file-type-vscode-insiders" },
148
+ { commands: ["cursor"], name: "Cursor", icon: "i-simple-icons:cursor" },
149
+ { commands: ["zed"], name: "Zed", icon: "i-simple-icons:zedindustries" },
150
+ { commands: ["webstorm", "wstorm"], name: "WebStorm", icon: "i-simple-icons:webstorm" },
151
+ { commands: ["codium", "vscodium"], name: "VSCodium", icon: "i-simple-icons:vscodium" },
152
+ { commands: ["subl", "sublime", "sublime_text"], name: "Sublime Text", icon: "i-simple-icons:sublimetext" },
153
+ { commands: ["idea"], name: "IntelliJ IDEA", icon: "i-simple-icons:intellijidea" },
154
+ { commands: ["trae"], name: "Trae", icon: "i-simple-icons:trae" },
155
+ { commands: ["atom"], name: "Atom", icon: "i-simple-icons:atom" },
156
+ { commands: ["pycharm", "charm"], name: "PyCharm", icon: "i-simple-icons:pycharm" },
157
+ { commands: ["phpstorm"], name: "PhpStorm", icon: "i-simple-icons:phpstorm" },
158
+ { commands: ["rubymine"], name: "RubyMine", icon: "i-simple-icons:rubymine" },
159
+ { commands: ["clion"], name: "CLion", icon: "i-simple-icons:clion" },
160
+ { commands: ["goland"], name: "GoLand", icon: "i-simple-icons:goland" },
161
+ { commands: ["rider"], name: "Rider", icon: "i-simple-icons:rider" },
162
+ { commands: ["notepad++"], name: "Notepad++", icon: "i-simple-icons:notepadplusplus" },
163
+ { commands: ["vim"], name: "Vim", icon: "i-simple-icons:vim" },
164
+ { commands: ["mvim"], name: "MacVim", icon: "i-simple-icons:vim" },
165
+ { commands: ["gvim"], name: "gVim", icon: "i-simple-icons:vim" },
166
+ { commands: ["emacs"], name: "Emacs", icon: "i-simple-icons:gnuemacs" },
167
+ { commands: ["emacsclient"], name: "Emacs Client", icon: "i-simple-icons:gnuemacs" },
168
+ { commands: ["mate"], name: "TextMate", icon: "i-ph:code" },
169
+ { commands: ["rmate"], name: "Remote TextMate", icon: "i-ph:code" },
170
+ { commands: ["antigravity"], name: "Antigravity", icon: "i-ph:code" },
171
+ { commands: ["appcode"], name: "AppCode", icon: "i-ph:code" },
172
+ { commands: ["joe"], name: "JOE", icon: "i-ph:terminal" }
173
+ ];
649
174
 
650
- const safelist = [];
175
+ const safelist = [...addons.map((addon) => addon.icon), ...editorPresentations.map((editor) => editor.icon)];
651
176
 
652
- export { ValaxyDevtools, ValaxyDevtools as default, safelist };
177
+ export { ValaxyDevtools, createValaxyDevframe, ValaxyDevtools as default, safelist };