@valaxyjs/devtools 1.0.0-rc.11 → 1.0.0-rc.13

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-Rn3Nqhbz.js +3 -0
  5. package/dist/client/assets/VDCheckbox-daRKoTGK.js +1 -0
  6. package/dist/client/assets/VDCodeBlock-BtPCxwvt.js +1 -0
  7. package/dist/client/assets/VDCodeBlock-C3pmQBwJ.css +1 -0
  8. package/dist/client/assets/VDNumberField-ko0BYjUy.js +1 -0
  9. package/dist/client/assets/VDPostListItem-CHPpKGrl.js +1 -0
  10. package/dist/client/assets/VDPostPanel-CbCth8UW.css +1 -0
  11. package/dist/client/assets/VDPostPanel-TTV6v3vH.js +1 -0
  12. package/dist/client/assets/VDSelect-Cu_aXlTc.js +1 -0
  13. package/dist/client/assets/VDToggleGroup-DQu5ibPP.js +1 -0
  14. package/dist/client/assets/addons-BeZTS6wo.js +1 -0
  15. package/dist/client/assets/addons-D7_qAb67.css +1 -0
  16. package/dist/client/assets/app-djZMc7np.js +3 -0
  17. package/dist/client/assets/archives-DyxjvxXC.js +1 -0
  18. package/dist/client/assets/batch-edit-UNPFWmV7.css +1 -0
  19. package/dist/client/assets/batch-edit-e_0tefQi.js +1 -0
  20. package/dist/client/assets/browser-agent-rpc-BXhoSh1z-DKEQfrSa.js +1 -0
  21. package/dist/client/assets/categories-D8m60Fso.js +1 -0
  22. package/dist/client/assets/collections-Boilukwl.js +1 -0
  23. package/dist/client/assets/colors-CdKJdJxa.js +1 -0
  24. package/dist/client/assets/config-DoNtHUjQ.js +1 -0
  25. package/dist/client/assets/debug-x5mwtm5I.js +1 -0
  26. package/dist/client/assets/editor-CHXt0bEP.js +1 -0
  27. package/dist/client/assets/index-BkcKXtGA.js +4 -0
  28. package/dist/client/assets/index-D2Bg3cBy.css +1 -0
  29. package/dist/client/assets/nanoid-Cya-tyvy.js +1 -0
  30. package/dist/client/assets/pages-C0Hm1R05.js +1 -0
  31. package/dist/client/assets/posts-BjJqEMcb.js +1 -0
  32. package/dist/client/assets/rpc-_85YyBhb.js +4 -0
  33. package/dist/client/assets/runtime-dom.esm-bundler-COvr_-s-.js +2 -0
  34. package/dist/client/assets/settings-D1-tIv7g.js +1 -0
  35. package/dist/client/assets/splitpanes.esm-CnpdH7BM.js +1 -0
  36. package/dist/client/assets/tags-DiOGZThc.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 +11 -8
  57. package/dist/index.d.ts +11 -8
  58. package/dist/index.mjs +145 -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.BEU7Q82S.d.mts +181 -0
  72. package/dist/shared/devtools.BOLo8y6t.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.CNAj6Cjx.d.ts +58 -0
  76. package/dist/shared/devtools.D4CJIUQe.d.ts +181 -0
  77. package/dist/shared/devtools.O-VZ9RtQ.d.mts +30 -0
  78. package/dist/shared/devtools.O-VZ9RtQ.d.ts +30 -0
  79. package/dist/shared/devtools.mygDTMGI.mjs +46 -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 -26
  84. package/rpc.d.ts +1 -100
  85. package/dist/client/assets/VDButton-BxA3M5c6.js +0 -1
  86. package/dist/client/assets/VDCheckbox-BsLMqi9S.js +0 -1
  87. package/dist/client/assets/VDInput-B27GE15-.js +0 -1
  88. package/dist/client/assets/VDInput-BtxYqBt3.css +0 -1
  89. package/dist/client/assets/VDNumberField-YjWV-ued.js +0 -1
  90. package/dist/client/assets/VDPostListItem-DF0Kvz0k.js +0 -1
  91. package/dist/client/assets/VDPostPanel-Bkkd-Lkf.css +0 -1
  92. package/dist/client/assets/VDPostPanel-Dci0SDJM.js +0 -1
  93. package/dist/client/assets/VDSelect-C-luq5qS.js +0 -1
  94. package/dist/client/assets/VDToggleGroup-epojOkcK.js +0 -1
  95. package/dist/client/assets/archives-DSGEfYQX.js +0 -1
  96. package/dist/client/assets/batch-edit-BYL9g3v4.css +0 -1
  97. package/dist/client/assets/batch-edit-DUNlYX2Q.js +0 -1
  98. package/dist/client/assets/categories-O8ONgJl6.js +0 -1
  99. package/dist/client/assets/collections-Rf9R5xIW.js +0 -1
  100. package/dist/client/assets/config-B6eJg8re.js +0 -1
  101. package/dist/client/assets/index-BjYrNlmK.js +0 -6
  102. package/dist/client/assets/index-wVxzDvm5.css +0 -1
  103. package/dist/client/assets/pages-CHon8Zex.js +0 -1
  104. package/dist/client/assets/posts-B80Fz55d.js +0 -1
  105. package/dist/client/assets/settings-B9Vkun7j.js +0 -1
  106. package/dist/client/assets/splitpanes.esm-B-DN0qHF.js +0 -1
  107. package/dist/client/assets/tags-B_Je2XwK.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
@@ -0,0 +1,1196 @@
1
+ import process from 'node:process';
2
+ import { addons, normalizeRepositoryUrl } from '@valaxyjs/utils';
3
+ import { defineDevframe, defineRpcFunction } from 'devframe';
4
+ import pathe, { resolve as resolve$1 } from 'pathe';
5
+ import * as v from 'valibot';
6
+ import { a as resolveInsideRoot, r as resolvePageFile, p as pkg } from '../shared/devtools.mygDTMGI.mjs';
7
+ import { dirname, resolve } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { R as RESOURCES_STATE, c as resolveAddonBase, d as DEVTOOLS_ID, r as resolveDevtoolsBase, b as resolveDevtoolsLogo } from '../shared/devtools.CBhjeyeH.mjs';
10
+ import { randomUUID, createHash } from 'node:crypto';
11
+ import spawn from 'cross-spawn';
12
+ import fg from 'fast-glob';
13
+ import fs from 'fs-extra';
14
+ import { realpath, readFile, writeFile } from 'node:fs/promises';
15
+ import { parseModule, generateCode } from 'magicast';
16
+ import { KNOWN_EDITORS } from 'devframe/utils/launch-editor';
17
+ import dayjs from 'dayjs';
18
+ import matter from 'gray-matter';
19
+ import { dump, JSON_SCHEMA, load } from 'js-yaml';
20
+
21
+ const packageRoot = dirname(fileURLToPath(import.meta.resolve("@valaxyjs/devtools/package.json")));
22
+ const DIR_DIST = resolve(packageRoot, "dist");
23
+ const DIR_CLIENT = resolve(DIR_DIST, "client");
24
+
25
+ const pendingWrites = /* @__PURE__ */ new Map();
26
+ async function updatePageFile(file, update) {
27
+ const canonical = await realpath(file);
28
+ const previous = pendingWrites.get(canonical) || Promise.resolve();
29
+ const operation = previous.catch(() => {
30
+ }).then(async () => {
31
+ const { content, result } = update(await readFile(canonical, "utf8"));
32
+ await writeFile(canonical, content, "utf8");
33
+ return result;
34
+ });
35
+ pendingWrites.set(canonical, operation);
36
+ try {
37
+ return await operation;
38
+ } finally {
39
+ if (pendingWrites.get(canonical) === operation)
40
+ pendingWrites.delete(canonical);
41
+ }
42
+ }
43
+
44
+ function walk(node, visit) {
45
+ if (!node || typeof node !== "object")
46
+ return;
47
+ if (Array.isArray(node)) {
48
+ node.forEach((child) => walk(child, visit));
49
+ return;
50
+ }
51
+ const value = node;
52
+ if (typeof value.type !== "string")
53
+ return;
54
+ visit(value);
55
+ for (const [key, child] of Object.entries(value)) {
56
+ if (!["loc", "tokens", "comments", "original", "leadingComments", "trailingComments"].includes(key))
57
+ walk(child, visit);
58
+ }
59
+ }
60
+ function removeAddonFromConfig(source, name) {
61
+ const mod = parseModule(source);
62
+ const imports = mod.imports.$items.filter((item) => item.from === name);
63
+ const bindings = new Set(imports.map((item) => item.local));
64
+ const exported = mod.exports.default;
65
+ const value = exported?.$type === "function-call" ? exported.$args[0] : exported;
66
+ if (!value || value.$type !== "object")
67
+ throw new Error("This configuration is dynamic. Remove the addon references in your editor first.");
68
+ const entries = value.addons;
69
+ if (entries != null && entries.$type !== "array")
70
+ throw new Error("The addons list is dynamic. Remove the addon references in your editor first.");
71
+ const shortName = name.replace(/^valaxy-addon-/, "");
72
+ let changed = imports.length > 0;
73
+ if (entries) {
74
+ for (let index = entries.length - 1; index >= 0; index--) {
75
+ const item = entries[index];
76
+ const matches = typeof item === "string" ? item === name || item === shortName : item?.$type === "function-call" ? bindings.has(item.$callee) : item?.$type === "object" ? item.name === name || item.name === shortName : false;
77
+ if (matches) {
78
+ entries.splice(index, 1);
79
+ changed = true;
80
+ }
81
+ }
82
+ }
83
+ for (const item of imports)
84
+ delete mod.imports[item.local];
85
+ let remaining = false;
86
+ walk(mod.$ast, (node) => {
87
+ if (node.type === "Identifier" && bindings.has(String(node.name)))
88
+ remaining = true;
89
+ if (["StringLiteral", "Literal"].includes(String(node.type)) && typeof node.value === "string" && (node.value === name || node.value.startsWith(`${name}/`)))
90
+ remaining = true;
91
+ });
92
+ if (remaining)
93
+ throw new Error("This addon is referenced outside a simple addons entry. Remove those references in your editor first.");
94
+ return changed ? generateCode(mod).code : source;
95
+ }
96
+
97
+ const configNames = ["valaxy.config.ts", "valaxy.config.mts", "valaxy.config.js", "valaxy.config.mjs"];
98
+ const dependencyFields = ["dependencies", "devDependencies", "optionalDependencies"];
99
+ const states = /* @__PURE__ */ new Map();
100
+ const busyWorkspaces = /* @__PURE__ */ new Set();
101
+ function assertAddonName(name) {
102
+ if (!/^valaxy-addon-[a-z0-9][a-z0-9._-]*$/.test(name) || name.length > 214)
103
+ throw new Error("Expected a valaxy-addon-* npm package name.");
104
+ }
105
+ function safeUrl(value) {
106
+ if (typeof value !== "string")
107
+ return void 0;
108
+ try {
109
+ const url = new URL(normalizeRepositoryUrl(value));
110
+ return ["http:", "https:"].includes(url.protocol) ? url.href : void 0;
111
+ } catch {
112
+ return void 0;
113
+ }
114
+ }
115
+ async function fetchAddonPackage(name) {
116
+ assertAddonName(name);
117
+ const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`, {
118
+ signal: AbortSignal.timeout(1e4),
119
+ redirect: "error",
120
+ headers: { accept: "application/json" }
121
+ });
122
+ if (!response.ok)
123
+ throw new Error(`npm registry request failed (${response.status}).`);
124
+ const raw = await response.text();
125
+ if (raw.length > 1e6)
126
+ throw new Error("Package metadata is too large.");
127
+ const data = JSON.parse(raw);
128
+ if (data.name !== name || typeof data.version !== "string" || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(data.version))
129
+ throw new Error("The registry returned invalid package metadata.");
130
+ return {
131
+ name,
132
+ version: data.version,
133
+ description: typeof data.description === "string" ? data.description.slice(0, 2e3) : "",
134
+ homepage: safeUrl(data.homepage),
135
+ repository: safeUrl(typeof data.repository === "string" ? data.repository : data.repository?.url),
136
+ license: typeof data.license === "string" ? data.license : void 0,
137
+ peerDependencies: Object.fromEntries(Object.entries(data.peerDependencies || {}).filter((entry) => typeof entry[1] === "string"))
138
+ };
139
+ }
140
+ function runAddonPackageManager(root, args, onLog) {
141
+ return new Promise((resolve, reject) => {
142
+ const child = spawn("pnpm", args, { cwd: root, shell: false, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, FORCE_COLOR: "0" } });
143
+ let timedOut = false;
144
+ const timer = setTimeout(() => {
145
+ timedOut = true;
146
+ child.kill();
147
+ }, 3e5);
148
+ const stop = () => child.kill();
149
+ process.once("exit", stop);
150
+ const cleanup = () => {
151
+ clearTimeout(timer);
152
+ process.off("exit", stop);
153
+ };
154
+ child.stdout?.on("data", (data) => onLog(String(data)));
155
+ child.stderr?.on("data", (data) => onLog(String(data)));
156
+ child.once("error", (error) => {
157
+ cleanup();
158
+ reject(new Error(`Could not start pnpm: ${error.message}`));
159
+ });
160
+ child.once("close", (code) => {
161
+ cleanup();
162
+ if (timedOut)
163
+ reject(new Error("Package operation timed out. Check the project dependency files before retrying."));
164
+ else if (code !== 0)
165
+ reject(new Error(`pnpm exited with code ${code}. Check the log and project dependency files before retrying.`));
166
+ else resolve();
167
+ });
168
+ });
169
+ }
170
+ async function optionalRead(file) {
171
+ try {
172
+ return await fs.readFile(file, "utf8");
173
+ } catch (error) {
174
+ if (error.code === "ENOENT")
175
+ return void 0;
176
+ throw error;
177
+ }
178
+ }
179
+ async function workspaceRoot(root) {
180
+ let current = root;
181
+ while (true) {
182
+ if (await fs.pathExists(pathe.join(current, "pnpm-workspace.yaml")))
183
+ return current;
184
+ const parent = pathe.dirname(current);
185
+ if (parent === current)
186
+ return root;
187
+ current = parent;
188
+ }
189
+ }
190
+ async function snapshot$1(root) {
191
+ const packageFile = await resolveInsideRoot(root, "package.json");
192
+ const packageSource = await optionalRead(packageFile);
193
+ const pkg = packageSource ? JSON.parse(packageSource) : {};
194
+ const workspace = await workspaceRoot(root);
195
+ const files = /* @__PURE__ */ new Map([[packageFile, packageSource]]);
196
+ const configs = [];
197
+ for (const name of configNames) {
198
+ const file = await resolveInsideRoot(root, name);
199
+ const source = await optionalRead(file);
200
+ files.set(file, source);
201
+ if (source !== void 0)
202
+ configs.push({ path: file, source });
203
+ }
204
+ for (const name of ["pnpm-lock.yaml", "pnpm-workspace.yaml"]) {
205
+ const file = await resolveInsideRoot(workspace, name);
206
+ files.set(file, await optionalRead(file));
207
+ }
208
+ const otherLock = await Promise.all(["package-lock.json", "yarn.lock", "bun.lock", "bun.lockb"].map((name) => fs.pathExists(pathe.join(root, name))));
209
+ const declaredManager = typeof pkg.packageManager === "string" ? pkg.packageManager : "";
210
+ const managementError = !packageSource ? "This project has no package.json." : declaredManager && !declaredManager.startsWith("pnpm@") ? "This project uses another package manager. Manage its addons in your terminal." : !declaredManager && otherLock.some(Boolean) ? "A non-pnpm lockfile was found. Manage this project with its existing package manager." : configs.length > 1 ? "Multiple Valaxy configuration files were found. Keep a single configuration before managing addons." : void 0;
211
+ const revision = createHash("sha256").update(JSON.stringify([...files])).digest("hex");
212
+ return { pkg, configs, workspace, revision, managementError };
213
+ }
214
+ async function installedPackage(root, name) {
215
+ let current = root;
216
+ while (true) {
217
+ const source = await optionalRead(pathe.join(current, "node_modules", name, "package.json"));
218
+ if (source) {
219
+ const pkg = JSON.parse(source);
220
+ return pkg.name === name ? pkg : void 0;
221
+ }
222
+ const parent = pathe.dirname(current);
223
+ if (parent === current)
224
+ return void 0;
225
+ current = parent;
226
+ }
227
+ }
228
+ async function assertNoOtherReferences(root, name, configFile) {
229
+ const files = await fg("**/*.{ts,mts,cts,js,mjs,cjs,jsx,tsx,vue}", { cwd: root, absolute: true, followSymbolicLinks: false, ignore: ["**/node_modules/**", "**/dist/**", "**/.valaxy/**", "**/.output/**", "**/.nuxt/**"] });
230
+ if (files.length > 5e3)
231
+ throw new Error("This project is too large to check automatically. Remove the addon using your editor and package manager.");
232
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
233
+ const reference = new RegExp(`['"\`]${escaped}(?:/[^'"\`\\n]*)?['"\`]`);
234
+ const remaining = [];
235
+ for (const file of files) {
236
+ if (pathe.normalize(file) !== configFile && reference.test(await fs.readFile(await resolveInsideRoot(root, file), "utf8")))
237
+ remaining.push(pathe.relative(root, file));
238
+ }
239
+ if (remaining.length)
240
+ throw new Error(`Remove this addon's other source references first: ${remaining.slice(0, 10).join(", ")}`);
241
+ }
242
+ function createAddonManager(options, dependencies = {}) {
243
+ const rootPath = pathe.resolve(options.userRoot || process.cwd());
244
+ const fetchPackage = dependencies.fetchPackage || fetchAddonPackage;
245
+ const run = dependencies.run || runAddonPackageManager;
246
+ async function context() {
247
+ const root = pathe.normalize(await fs.realpath(rootPath));
248
+ let state = states.get(root);
249
+ if (!state) {
250
+ state = { plans: /* @__PURE__ */ new Map(), jobs: /* @__PURE__ */ new Map() };
251
+ states.set(root, state);
252
+ }
253
+ return { root, state };
254
+ }
255
+ async function inventory() {
256
+ const { root, state } = await context();
257
+ const current = await snapshot$1(root);
258
+ const active = options.getAddons?.() || [];
259
+ const declared = Object.assign({}, ...dependencyFields.map((field) => current.pkg[field] || {}));
260
+ const names = /* @__PURE__ */ new Set([...Object.keys(declared), ...active.map((addon) => addon.name)]);
261
+ const installed = [];
262
+ for (const name of names) {
263
+ if (!/^valaxy-addon-[a-z0-9][a-z0-9._-]*$/.test(name))
264
+ continue;
265
+ const enabled = active.find((addon) => addon.name === name);
266
+ const pkg = await installedPackage(root, name);
267
+ if (!declared[name] && !pkg && !enabled)
268
+ continue;
269
+ installed.push({ name, version: pkg?.version || enabled?.version, description: pkg?.description, specifier: declared[name], direct: Object.hasOwn(declared, name), enabled: !!enabled });
270
+ }
271
+ return { installed: installed.sort((a, b) => a.name.localeCompare(b.name)), packageManager: current.managementError ? null : "pnpm", managementError: current.managementError, configFile: current.configs[0]?.path, operation: state.operation ? structuredClone(state.operation) : void 0 };
272
+ }
273
+ async function prepare(action, name) {
274
+ assertAddonName(name);
275
+ if (action !== "install" && action !== "remove")
276
+ throw new Error("Unknown addon operation.");
277
+ const { root, state } = await context();
278
+ const current = await snapshot$1(root);
279
+ if (current.managementError)
280
+ throw new Error(current.managementError);
281
+ if (busyWorkspaces.has(current.workspace))
282
+ throw new Error("A package operation is already running in this workspace.");
283
+ const direct = dependencyFields.some((field) => Object.hasOwn(current.pkg[field] || {}, name));
284
+ if (action === "install" && direct)
285
+ throw new Error("This addon is already declared in package.json.");
286
+ if (action === "remove" && !direct)
287
+ throw new Error("Only direct dependencies of this project can be removed.");
288
+ if (action === "install" && !addons.some((addon) => addon.name === name))
289
+ throw new Error("This addon is not in the curated catalog. Install it in your terminal after reviewing it.");
290
+ const plan = { id: randomUUID(), action, name, command: "" };
291
+ let args;
292
+ if (action === "install") {
293
+ const details = await fetchPackage(name);
294
+ if (details.name !== name || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(details.version))
295
+ throw new Error("Invalid package version.");
296
+ plan.version = details.version;
297
+ args = ["add", "--save-exact", "--ignore-scripts", "--registry=https://registry.npmjs.org", `${name}@${details.version}`];
298
+ } else {
299
+ const config = current.configs[0];
300
+ await assertNoOtherReferences(root, name, config?.path);
301
+ if (config) {
302
+ const after = removeAddonFromConfig(config.source, name);
303
+ if (after !== config.source) {
304
+ plan.configFile = config.path;
305
+ plan.configBefore = config.source;
306
+ plan.configAfter = after;
307
+ } else if (options.getAddons?.().some((addon) => addon.name === name)) {
308
+ throw new Error("This addon is enabled by an inherited or dynamic configuration. Remove that reference first.");
309
+ }
310
+ }
311
+ args = ["remove", "--ignore-scripts", name];
312
+ }
313
+ if (root === current.workspace && await fs.pathExists(pathe.join(root, "pnpm-workspace.yaml")))
314
+ args.push("--workspace-root");
315
+ plan.command = `pnpm ${args.join(" ")}`;
316
+ for (const [id, entry] of state.plans) {
317
+ if (entry.expires < Date.now() || state.plans.size >= 20)
318
+ state.plans.delete(id);
319
+ }
320
+ state.plans.set(plan.id, { plan, args, revision: current.revision, expires: Date.now() + 3e5 });
321
+ return structuredClone(plan);
322
+ }
323
+ async function apply(id) {
324
+ const { root, state } = await context();
325
+ if (state.jobs.has(id))
326
+ return structuredClone(state.jobs.get(id));
327
+ const stored = state.plans.get(id);
328
+ if (!stored || stored.expires < Date.now())
329
+ throw new Error("The operation preview expired. Review a new preview before continuing.");
330
+ const current = await snapshot$1(root);
331
+ if (current.revision !== stored.revision)
332
+ throw new Error("Project configuration or dependencies changed. Review a new preview before continuing.");
333
+ if (stored.plan.action === "remove")
334
+ await assertNoOtherReferences(root, stored.plan.name, current.configs[0]?.path);
335
+ if (state.jobs.has(id))
336
+ return structuredClone(state.jobs.get(id));
337
+ if (busyWorkspaces.has(current.workspace))
338
+ throw new Error("A package operation is already running in this workspace.");
339
+ busyWorkspaces.add(current.workspace);
340
+ const operation = { ...stored.plan, status: "running", log: "" };
341
+ state.jobs.set(id, operation);
342
+ state.plans.delete(id);
343
+ state.operation = operation;
344
+ while (state.jobs.size > 20)
345
+ state.jobs.delete(state.jobs.keys().next().value);
346
+ const log = (text) => {
347
+ operation.log = (operation.log + text).slice(-2e4);
348
+ };
349
+ void (async () => {
350
+ let configChanged = false;
351
+ try {
352
+ if (operation.configFile) {
353
+ await resolveInsideRoot(root, operation.configFile);
354
+ await updatePageFile(operation.configFile, (source) => {
355
+ if (source !== operation.configBefore)
356
+ throw new Error("Configuration changed after preview. No package command was run.");
357
+ return { content: operation.configAfter, result: void 0 };
358
+ });
359
+ configChanged = true;
360
+ }
361
+ await run(root, stored.args, log);
362
+ const updated = await snapshot$1(root);
363
+ const declared = dependencyFields.some((field) => Object.hasOwn(updated.pkg[field] || {}, operation.name));
364
+ if (declared !== (operation.action === "install"))
365
+ throw new Error("pnpm finished but package.json did not reflect the requested change.");
366
+ if (operation.action === "install" && (await installedPackage(root, operation.name))?.version !== operation.version)
367
+ throw new Error("The installed addon version does not match the reviewed version. Check the project dependencies.");
368
+ operation.status = "succeeded";
369
+ } catch (error) {
370
+ operation.status = "failed";
371
+ operation.error = error instanceof Error ? error.message : String(error);
372
+ if (configChanged && operation.configFile) {
373
+ try {
374
+ const updated = await snapshot$1(root);
375
+ if (!dependencyFields.some((field) => Object.hasOwn(updated.pkg[field] || {}, operation.name)))
376
+ throw new Error("The dependency was already removed. Its configuration references remain removed; inspect the dependency files before retrying.");
377
+ await resolveInsideRoot(root, operation.configFile);
378
+ await updatePageFile(operation.configFile, (source) => {
379
+ if (source !== operation.configAfter)
380
+ throw new Error("Configuration was edited externally; it was preserved instead of restoring the preview.");
381
+ return { content: operation.configBefore, result: void 0 };
382
+ });
383
+ } catch (rollbackError) {
384
+ log(`
385
+ ${String(rollbackError)}
386
+ `);
387
+ }
388
+ }
389
+ } finally {
390
+ busyWorkspaces.delete(current.workspace);
391
+ }
392
+ })();
393
+ return structuredClone(operation);
394
+ }
395
+ return { inventory, prepare, apply, details: fetchPackage };
396
+ }
397
+
398
+ function getEditorOptions(env = process.env) {
399
+ const configured = env.LAUNCH_EDITOR || env.VISUAL || env.EDITOR;
400
+ return {
401
+ editor: KNOWN_EDITORS.find((editor) => editor === configured),
402
+ editors: [...KNOWN_EDITORS]
403
+ };
404
+ }
405
+
406
+ const DANGEROUS_FIELD_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
407
+ function validateFieldPath(fieldPath) {
408
+ const parts = fieldPath.split(".");
409
+ return parts.every((part) => part.length > 0 && !DANGEROUS_FIELD_KEYS.has(part));
410
+ }
411
+ function assertInsideRoot(root, targetFile) {
412
+ const relative = pathe.relative(root, targetFile);
413
+ if (relative.startsWith("..") || pathe.isAbsolute(relative))
414
+ throw new Error(`Config path is outside user root: ${targetFile}`);
415
+ }
416
+ function setNestedValue(obj, path, value) {
417
+ const parts = path.split(".");
418
+ let current = obj;
419
+ for (let i = 0; i < parts.length - 1; i++) {
420
+ const part = parts[i];
421
+ if (current[part] == null || typeof current[part] !== "object") {
422
+ current[part] = {};
423
+ }
424
+ current = current[part];
425
+ }
426
+ current[parts.at(-1)] = value;
427
+ }
428
+ async function parseConfigFile(filePath) {
429
+ const content = await fs.readFile(filePath, "utf-8");
430
+ const mod = parseModule(content);
431
+ return mod;
432
+ }
433
+ function serializeProxy(value) {
434
+ try {
435
+ if (value == null)
436
+ return value;
437
+ if (typeof value !== "object")
438
+ return value;
439
+ if (value.$type === "function-call") {
440
+ const callee = value.$callee ?? "";
441
+ const args = value.$args ?? [];
442
+ const serializedArgs = args.map(
443
+ (a) => typeof a === "string" ? `'${a}'` : JSON.stringify(a)
444
+ ).join(", ");
445
+ return `${callee}(${serializedArgs})`;
446
+ }
447
+ if (value.$type === "identifier") {
448
+ return String(value.$id ?? value);
449
+ }
450
+ if (value.$type && value.$type !== "object") {
451
+ return `<${value.$type}>`;
452
+ }
453
+ if (Array.isArray(value)) {
454
+ return value.map((item) => {
455
+ try {
456
+ return serializeProxy(item);
457
+ } catch {
458
+ return "<unsupported>";
459
+ }
460
+ });
461
+ }
462
+ const result = {};
463
+ for (const key of Object.keys(value)) {
464
+ if (key.startsWith("$"))
465
+ continue;
466
+ try {
467
+ result[key] = serializeProxy(value[key]);
468
+ } catch {
469
+ result[key] = "<unsupported expression>";
470
+ }
471
+ }
472
+ return result;
473
+ } catch {
474
+ return "<unsupported expression>";
475
+ }
476
+ }
477
+ async function readConfigs(userRoot) {
478
+ const siteConfigPath = pathe.resolve(userRoot, "site.config.ts");
479
+ const valaxyConfigPath = pathe.resolve(userRoot, "valaxy.config.ts");
480
+ let siteConfig = {};
481
+ let valaxyConfig = {};
482
+ let themeConfig = {};
483
+ const siteConfigExists = await fs.pathExists(siteConfigPath);
484
+ const valaxyConfigExists = await fs.pathExists(valaxyConfigPath);
485
+ if (siteConfigExists) {
486
+ try {
487
+ const mod = await parseConfigFile(siteConfigPath);
488
+ const defaultExport = mod.exports.default;
489
+ if (defaultExport && typeof defaultExport === "object") {
490
+ siteConfig = serializeProxy(defaultExport.$args?.[0] ?? defaultExport);
491
+ }
492
+ } catch (e) {
493
+ console.error("[devtools] Failed to parse site.config.ts:", e);
494
+ }
495
+ }
496
+ if (valaxyConfigExists) {
497
+ try {
498
+ const mod = await parseConfigFile(valaxyConfigPath);
499
+ const defaultExport = mod.exports.default;
500
+ if (defaultExport && typeof defaultExport === "object") {
501
+ const configObj = defaultExport.$args?.[0] ?? defaultExport;
502
+ const raw = serializeProxy(configObj);
503
+ if (raw.themeConfig) {
504
+ themeConfig = raw.themeConfig;
505
+ delete raw.themeConfig;
506
+ }
507
+ if (raw.siteConfig) {
508
+ delete raw.siteConfig;
509
+ }
510
+ valaxyConfig = raw;
511
+ }
512
+ } catch (e) {
513
+ console.error("[devtools] Failed to parse valaxy.config.ts:", e);
514
+ }
515
+ }
516
+ return {
517
+ siteConfig,
518
+ valaxyConfig,
519
+ themeConfig,
520
+ siteConfigExists,
521
+ valaxyConfigExists,
522
+ siteConfigPath,
523
+ valaxyConfigPath
524
+ };
525
+ }
526
+ const SITE_CONFIG_TEMPLATE = `import { defineSiteConfig } from 'valaxy'
527
+
528
+ export default defineSiteConfig({
529
+ })
530
+ `;
531
+ const VALAXY_CONFIG_TEMPLATE = `import { defineValaxyConfig } from 'valaxy'
532
+
533
+ export default defineValaxyConfig({
534
+ })
535
+ `;
536
+ async function writeConfigField(userRoot, configType, fieldPath, value) {
537
+ if (!validateFieldPath(fieldPath)) {
538
+ throw new Error(`Invalid field path: ${fieldPath}`);
539
+ }
540
+ const targetFile = configType === "site" ? pathe.resolve(userRoot, "site.config.ts") : pathe.resolve(userRoot, "valaxy.config.ts");
541
+ const template = configType === "site" ? SITE_CONFIG_TEMPLATE : VALAXY_CONFIG_TEMPLATE;
542
+ assertInsideRoot(userRoot, targetFile);
543
+ await resolveInsideRoot(userRoot, targetFile);
544
+ if (!await fs.pathExists(targetFile)) {
545
+ await fs.writeFile(targetFile, template, "utf-8");
546
+ }
547
+ const mod = await parseConfigFile(targetFile);
548
+ const defaultExport = mod.exports.default;
549
+ if (!defaultExport) {
550
+ throw new Error(`No default export found in ${targetFile}`);
551
+ }
552
+ const configObj = defaultExport.$args?.[0] ?? defaultExport;
553
+ if (configType === "theme") {
554
+ if (!configObj.themeConfig || typeof configObj.themeConfig !== "object") {
555
+ configObj.themeConfig = {};
556
+ }
557
+ setNestedValue(configObj.themeConfig, fieldPath, value);
558
+ } else if (configType === "valaxy") {
559
+ setNestedValue(configObj, fieldPath, value);
560
+ } else {
561
+ setNestedValue(configObj, fieldPath, value);
562
+ }
563
+ const { code } = generateCode(mod);
564
+ await fs.writeFile(targetFile, code, "utf-8");
565
+ }
566
+
567
+ const reservedFields = /* @__PURE__ */ new Set(["title", "date", "updated", "draft", "hide", "type", "tags", "categories", "excerpt", "excerpt_type", "cover", "toc", "password", "password_hint", "encryptedContent", "partiallyEncryptedContents", "layout", "path", "permalink", "abbrlink", "url", "author", "top", "sticky", "comment"]);
568
+ const identifier = /^[a-z][a-z0-9-]*$/;
569
+ async function resolveDevtoolsPlugins(options) {
570
+ const plugins = [];
571
+ const ids = /* @__PURE__ */ new Set();
572
+ const fields = /* @__PURE__ */ new Set();
573
+ for (const load of options.plugins || []) {
574
+ const loaded = typeof load === "function" ? await load() : load;
575
+ const plugin = "default" in loaded ? loaded.default : loaded;
576
+ if (plugin.apiVersion !== 1 || !identifier.test(plugin.id) || !plugin.name || ids.has(plugin.id))
577
+ throw new Error(`Invalid or duplicate Valaxy DevTools plugin: ${plugin.id}`);
578
+ ids.add(plugin.id);
579
+ const panelIds = /* @__PURE__ */ new Set();
580
+ for (const panel of plugin.panels || []) {
581
+ if (!identifier.test(panel.id) || panelIds.has(panel.id) || !panel.title)
582
+ throw new Error(`Invalid or duplicate panel: ${plugin.id}:${panel.id}`);
583
+ panelIds.add(panel.id);
584
+ if (!pathe.isAbsolute(panel.clientAssets) || !await fs.pathExists(pathe.join(panel.clientAssets, "index.html")))
585
+ throw new Error(`Panel ${plugin.id}:${panel.id} requires a built clientAssets directory with index.html`);
586
+ }
587
+ for (const field of plugin.editor?.fields || []) {
588
+ if (!/^[a-z][\w-]*$/i.test(field.key) || DANGEROUS_FIELD_KEYS.has(field.key) || reservedFields.has(field.key) || fields.has(field.key) || !field.label)
589
+ throw new Error(`Invalid or duplicate editor field: ${field.key}`);
590
+ fields.add(field.key);
591
+ if (!["text", "textarea", "boolean", "number", "select"].includes(field.type))
592
+ throw new Error(`Unsupported editor field type: ${field.key}`);
593
+ if (field.type === "select" && (!field.options.length || new Set(field.options.map((o) => o.value)).size !== field.options.length || field.options.some((o) => typeof o.value !== "string" || !o.label)))
594
+ throw new Error(`Invalid select options: ${field.key}`);
595
+ if (field.type === "number" && (field.step !== void 0 && (!Number.isFinite(field.step) || field.step <= 0) || field.min !== void 0 && !Number.isFinite(field.min) || field.max !== void 0 && !Number.isFinite(field.max) || field.min !== void 0 && field.max !== void 0 && field.min > field.max))
596
+ throw new Error(`Invalid number limits: ${field.key}`);
597
+ if ((field.type === "text" || field.type === "textarea") && field.maxLength !== void 0 && (!Number.isInteger(field.maxLength) || field.maxLength < 0))
598
+ throw new Error(`Invalid text limit: ${field.key}`);
599
+ }
600
+ const actions = /* @__PURE__ */ new Set();
601
+ for (const action of plugin.editor?.actions || []) {
602
+ if (!identifier.test(action.id) || actions.has(action.id) || !action.label || typeof action.run !== "function")
603
+ throw new Error(`Invalid or duplicate editor action: ${plugin.id}:${action.id}`);
604
+ actions.add(action.id);
605
+ }
606
+ plugins.push(plugin);
607
+ }
608
+ return plugins;
609
+ }
610
+ function validateEditorFields(plugins, frontmatter) {
611
+ for (const plugin of plugins) {
612
+ for (const field of plugin.editor?.fields || []) {
613
+ if (!Object.hasOwn(frontmatter, field.key))
614
+ continue;
615
+ const value = frontmatter[field.key];
616
+ let valid;
617
+ switch (field.type) {
618
+ case "boolean":
619
+ valid = typeof value === "boolean";
620
+ break;
621
+ case "number":
622
+ valid = typeof value === "number" && Number.isFinite(value) && (field.min === void 0 || value >= field.min) && (field.max === void 0 || value <= field.max);
623
+ break;
624
+ case "select":
625
+ valid = field.options.some((option) => option.value === value);
626
+ break;
627
+ default:
628
+ valid = typeof value === "string" && (field.maxLength === void 0 || value.length <= field.maxLength);
629
+ }
630
+ if (!valid)
631
+ throw new Error(`${plugin.name}: invalid value for ${field.label} (${field.key})`);
632
+ }
633
+ }
634
+ }
635
+ function createManifest(plugins, base) {
636
+ return {
637
+ apiVersion: 1,
638
+ plugins: plugins.map((plugin) => ({
639
+ id: plugin.id,
640
+ name: plugin.name,
641
+ panels: (plugin.panels || []).map((panel) => ({ id: `valaxy:addon:${plugin.id}:${panel.id}`, title: panel.title, icon: panel.icon || "ph:puzzle-piece", url: `${resolveAddonBase(base)}${plugin.id}/${panel.id}/` })),
642
+ fields: plugin.editor?.fields || [],
643
+ actions: (plugin.editor?.actions || []).map((action) => ({ id: `${plugin.id}:${action.id}`, label: action.label }))
644
+ }))
645
+ };
646
+ }
647
+ async function setupExtensions(ctx, plugins, manifest, data, onDispose) {
648
+ for (const [index, plugin] of plugins.entries()) {
649
+ for (const [panelIndex, panel] of (plugin.panels || []).entries()) {
650
+ const view = manifest.plugins[index].panels[panelIndex];
651
+ await ctx.host.mountConnectionMeta?.(view.url);
652
+ await ctx.host.mountStatic(view.url, panel.clientAssets);
653
+ }
654
+ await plugin.setup?.({ data, rpc: ctx.scope(`valaxy:addon:${plugin.id}`).rpc, onDispose });
655
+ }
656
+ }
657
+ function createDataApi(ctx, functions, onDispose) {
658
+ return {
659
+ ...functions,
660
+ async onChanged(listener) {
661
+ const state = await ctx.rpc.sharedState.get(RESOURCES_STATE);
662
+ const stop = state.on("updated", listener);
663
+ onDispose(stop);
664
+ return stop;
665
+ }
666
+ };
667
+ }
668
+
669
+ const matterOptions = {
670
+ engines: {
671
+ yaml: {
672
+ parse: (source) => load(source, { schema: JSON_SCHEMA }),
673
+ stringify: (data) => dump(data, { schema: JSON_SCHEMA })
674
+ }
675
+ }
676
+ };
677
+ async function migration(path, frontmatter, validateFrontmatter = () => {
678
+ }) {
679
+ if (fs.existsSync(path)) {
680
+ const rawMd = await fs.readFile(path, "utf-8");
681
+ const matterFile = matter(rawMd, matterOptions);
682
+ let mod = false;
683
+ for (const key in frontmatter) {
684
+ if (key in matterFile.data) {
685
+ matterFile.data[frontmatter[key]] = matterFile.data[key];
686
+ delete matterFile.data[key];
687
+ mod = true;
688
+ }
689
+ }
690
+ if (mod) {
691
+ validateFrontmatter(matterFile.data);
692
+ const newMd = matter.stringify(matterFile.content, matterFile.data);
693
+ await fs.writeFile(path, newMd);
694
+ }
695
+ }
696
+ }
697
+
698
+ function snapshot(content) {
699
+ return { content, revision: createHash("sha256").update(content).digest("hex") };
700
+ }
701
+ async function readPostContent(userRoot, filePath) {
702
+ const file = await resolvePageFile(userRoot, filePath);
703
+ return snapshot(matter(await readFile(file, "utf8")).content);
704
+ }
705
+ async function writePostContent(userRoot, filePath, content, revision) {
706
+ const file = await resolvePageFile(userRoot, filePath);
707
+ return updatePageFile(file, (raw) => {
708
+ const previous = matter(raw).content;
709
+ if (snapshot(previous).revision !== revision)
710
+ throw new Error("The article body changed on disk. Reload it before saving.");
711
+ return { content: raw.slice(0, raw.length - previous.length) + content, result: snapshot(content) };
712
+ });
713
+ }
714
+
715
+ function ensurePrefix(prefix, str) {
716
+ if (!str.startsWith(prefix))
717
+ return prefix + str;
718
+ return str;
719
+ }
720
+ function extractStringField(content, field) {
721
+ const regex = new RegExp(`\\b${field}\\s*:\\s*['"\`]([^'"\`]*)['"\`]`);
722
+ const match = content.match(regex);
723
+ return match?.[1] || "";
724
+ }
725
+ function extractBooleanField(content, field, defaultValue) {
726
+ const regex = new RegExp(`\\b${field}\\s*:\\s*(true|false)`);
727
+ const match = content.match(regex);
728
+ if (!match)
729
+ return defaultValue;
730
+ return match[1] === "true";
731
+ }
732
+ function extractConfigItems(content) {
733
+ const items = [];
734
+ const itemsMatch = content.match(/items\s*:\s*\[([^\]]*)\]/);
735
+ if (!itemsMatch)
736
+ return items;
737
+ const itemsContent = itemsMatch[1];
738
+ const objectRegex = /\{([^}]*)\}/g;
739
+ let objMatch;
740
+ while ((objMatch = objectRegex.exec(itemsContent)) !== null) {
741
+ const block = objMatch[1];
742
+ const keyMatch = block.match(/key\s*:\s*['"`]([^'"`]*)['"`]/);
743
+ const titleMatch = block.match(/title\s*:\s*['"`]([^'"`]*)['"`]/);
744
+ const linkMatch = block.match(/link\s*:\s*['"`]([^'"`]*)['"`]/);
745
+ items.push({
746
+ key: keyMatch?.[1],
747
+ title: titleMatch?.[1],
748
+ link: linkMatch?.[1]
749
+ });
750
+ }
751
+ return items;
752
+ }
753
+ function getFunctions(devtoolsOptions, validateFrontmatter = () => {
754
+ }) {
755
+ const userRoot = pathe.resolve(devtoolsOptions.userRoot || process.cwd());
756
+ function getRoutePath(filePath) {
757
+ const relativePath = pathe.relative(pathe.resolve(userRoot, "pages"), filePath).slice(0, -".md".length);
758
+ return ensurePrefix("/", relativePath);
759
+ }
760
+ return {
761
+ getPostContent: (filePath) => readPostContent(userRoot, filePath),
762
+ updatePostContent: (req) => writePostContent(userRoot, req.filePath, req.content, req.revision),
763
+ async getOptions() {
764
+ return {
765
+ userRoot,
766
+ siteUrl: devtoolsOptions.siteUrl?.(),
767
+ ...getEditorOptions()
768
+ };
769
+ },
770
+ async getPostList() {
771
+ const files = await fg(`${userRoot}/pages/posts/**/*.md`);
772
+ const posts = [];
773
+ for await (const file of files) {
774
+ const md = await fs.readFile(file, "utf-8");
775
+ const { data } = matter(md);
776
+ posts.push({
777
+ routePath: getRoutePath(file),
778
+ frontmatter: data,
779
+ filePath: file
780
+ });
781
+ }
782
+ return {
783
+ // sort by updated
784
+ posts: posts.sort((a, b) => {
785
+ const bDateValue = dayjs(b.frontmatter.updated || b.frontmatter.date).valueOf();
786
+ const aDateValue = dayjs(a.frontmatter.updated || a.frontmatter.date).valueOf();
787
+ return bDateValue - aDateValue;
788
+ }),
789
+ root: userRoot
790
+ };
791
+ },
792
+ async getPageData(pagePath) {
793
+ const relativePath = pagePath.startsWith("/pages/") ? pagePath.slice(1) : pagePath;
794
+ const file = await resolvePageFile(userRoot, relativePath);
795
+ const { data } = matter(await fs.readFile(file, "utf-8"));
796
+ return {
797
+ routePath: getRoutePath(file),
798
+ filePath: file,
799
+ frontmatter: data
800
+ };
801
+ },
802
+ async updateFrontmatter(req) {
803
+ const { filePath, frontmatter: newFm } = req;
804
+ const resolved = await resolvePageFile(userRoot, filePath);
805
+ for (const key of Object.keys(newFm)) {
806
+ if (DANGEROUS_FIELD_KEYS.has(key))
807
+ throw new Error("Invalid frontmatter field");
808
+ }
809
+ validateFrontmatter(newFm);
810
+ if (!fs.existsSync(resolved))
811
+ throw new Error(`File not found: ${resolved}`);
812
+ return updatePageFile(resolved, (rawMd) => {
813
+ const matterFile = matter(rawMd);
814
+ return { content: matter.stringify(matterFile.content, newFm), result: { success: true } };
815
+ });
816
+ },
817
+ async getCollectionList() {
818
+ const collectionsRoot = pathe.resolve(userRoot, "pages", "collections");
819
+ if (!await fs.pathExists(collectionsRoot))
820
+ return [];
821
+ const entries = await fs.readdir(collectionsRoot, { withFileTypes: true });
822
+ const dirs = entries.filter((f) => f.isDirectory()).map((f) => f.name);
823
+ const result = [];
824
+ for (const dir of dirs) {
825
+ const indexPath = pathe.join(collectionsRoot, dir, "index.ts");
826
+ if (!await fs.pathExists(indexPath))
827
+ continue;
828
+ const indexContent = await fs.readFile(indexPath, "utf-8");
829
+ const title = extractStringField(indexContent, "title");
830
+ const cover = extractStringField(indexContent, "cover");
831
+ const description = extractStringField(indexContent, "description");
832
+ const collapse = extractBooleanField(indexContent, "collapse", true);
833
+ const mdFiles = await fg(`${collectionsRoot}/${dir}/*.md`);
834
+ const items = [];
835
+ for (const file of mdFiles) {
836
+ const basename = pathe.basename(file, ".md");
837
+ if (basename === "index")
838
+ continue;
839
+ const md = await fs.readFile(file, "utf-8");
840
+ const { data } = matter(md);
841
+ items.push({
842
+ title: data.title || basename,
843
+ key: basename,
844
+ filePath: file,
845
+ frontmatter: data
846
+ });
847
+ }
848
+ const configItems = extractConfigItems(indexContent);
849
+ if (configItems.length > 0) {
850
+ for (const ci of configItems) {
851
+ if (ci.link && !items.some((i) => i.key === ci.key)) {
852
+ items.push({
853
+ title: ci.title || ci.link,
854
+ key: ci.key || "",
855
+ link: ci.link,
856
+ filePath: "",
857
+ frontmatter: {}
858
+ });
859
+ }
860
+ }
861
+ const orderMap = /* @__PURE__ */ new Map();
862
+ configItems.forEach((ci, i) => {
863
+ if (ci.key)
864
+ orderMap.set(`key:${ci.key}`, i);
865
+ else if (ci.link)
866
+ orderMap.set(`link:${ci.link}`, i);
867
+ });
868
+ items.sort((a, b) => {
869
+ const aIdx = (a.key ? orderMap.get(`key:${a.key}`) : orderMap.get(`link:${a.link}`)) ?? Infinity;
870
+ const bIdx = (b.key ? orderMap.get(`key:${b.key}`) : orderMap.get(`link:${b.link}`)) ?? Infinity;
871
+ if (aIdx === bIdx)
872
+ return 0;
873
+ return aIdx - bIdx;
874
+ });
875
+ } else {
876
+ items.sort((a, b) => {
877
+ const aVal = dayjs(a.frontmatter.date).valueOf();
878
+ const bVal = dayjs(b.frontmatter.date).valueOf();
879
+ const aDate = Number.isNaN(aVal) ? 0 : aVal;
880
+ const bDate = Number.isNaN(bVal) ? 0 : bVal;
881
+ return aDate - bDate;
882
+ });
883
+ }
884
+ const itemsSectionIndex = indexContent.indexOf("items:");
885
+ const topLevelArea = itemsSectionIndex === -1 ? indexContent : indexContent.slice(0, itemsSectionIndex);
886
+ const key = extractStringField(topLevelArea, "key") || dir;
887
+ result.push({
888
+ key,
889
+ title,
890
+ cover,
891
+ description,
892
+ collapse,
893
+ dirPath: pathe.join(collectionsRoot, dir),
894
+ items
895
+ });
896
+ }
897
+ return result;
898
+ },
899
+ async batchUpdateFrontmatter(filePaths, operations) {
900
+ const result = {
901
+ total: filePaths.length,
902
+ updated: 0,
903
+ errors: []
904
+ };
905
+ for (const filePath of filePaths) {
906
+ try {
907
+ const resolved = await resolvePageFile(userRoot, filePath);
908
+ if (!await fs.pathExists(resolved)) {
909
+ result.errors.push({ filePath, error: "File not found" });
910
+ continue;
911
+ }
912
+ const rawMd = await fs.readFile(resolved, "utf-8");
913
+ const matterFile = matter(rawMd);
914
+ let modified = false;
915
+ for (const op of operations) {
916
+ if (DANGEROUS_FIELD_KEYS.has(op.key) || op.type === "rename" && DANGEROUS_FIELD_KEYS.has(op.newKey))
917
+ continue;
918
+ switch (op.type) {
919
+ case "set":
920
+ matterFile.data[op.key] = op.value;
921
+ modified = true;
922
+ break;
923
+ case "delete":
924
+ if (op.key in matterFile.data) {
925
+ delete matterFile.data[op.key];
926
+ modified = true;
927
+ }
928
+ break;
929
+ case "rename":
930
+ if (op.key in matterFile.data && op.newKey) {
931
+ matterFile.data[op.newKey] = matterFile.data[op.key];
932
+ delete matterFile.data[op.key];
933
+ modified = true;
934
+ }
935
+ break;
936
+ }
937
+ }
938
+ if (modified) {
939
+ validateFrontmatter(matterFile.data);
940
+ const newMd = matter.stringify(matterFile.content, matterFile.data);
941
+ await fs.writeFile(resolved, newMd);
942
+ result.updated++;
943
+ }
944
+ } catch (e) {
945
+ result.errors.push({ filePath, error: e.message || String(e) });
946
+ }
947
+ }
948
+ return result;
949
+ },
950
+ async getConfig() {
951
+ return readConfigs(userRoot);
952
+ },
953
+ async updateConfigField(configType, fieldPath, value) {
954
+ try {
955
+ await writeConfigField(userRoot, configType, fieldPath, value);
956
+ return { success: true };
957
+ } catch (e) {
958
+ return { success: false, error: e.message || String(e) };
959
+ }
960
+ },
961
+ async runMigration(filePaths, frontmatter) {
962
+ for (const [key, value] of Object.entries(frontmatter)) {
963
+ if (DANGEROUS_FIELD_KEYS.has(key) || DANGEROUS_FIELD_KEYS.has(value))
964
+ throw new Error("Invalid migration field");
965
+ }
966
+ const paths = await Promise.all(filePaths.map((path) => resolvePageFile(userRoot, path)));
967
+ const workers = paths.map((path) => migration(path, frontmatter, validateFrontmatter));
968
+ await Promise.all(workers);
969
+ return { success: true };
970
+ },
971
+ async createPost(options) {
972
+ try {
973
+ const { title, path: customPath, tags, categories } = options;
974
+ const postsDir = pathe.resolve(userRoot, "pages", "posts");
975
+ let filePath;
976
+ if (customPath) {
977
+ const normalized = customPath.endsWith(".md") ? customPath : `${customPath}.md`;
978
+ filePath = pathe.resolve(postsDir, normalized);
979
+ const rel = pathe.relative(postsDir, filePath);
980
+ if (rel.startsWith("..") || pathe.isAbsolute(rel))
981
+ return { success: false, error: "Invalid path: must be within posts directory" };
982
+ } else {
983
+ const slug = title.toLowerCase().replace(/[\s_]+/g, "-").replace(/[^\w\u4E00-\u9FFF-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "") || `post-${Date.now()}`;
984
+ filePath = pathe.resolve(postsDir, `${slug}.md`);
985
+ }
986
+ await resolvePageFile(userRoot, filePath);
987
+ await fs.ensureDir(pathe.dirname(filePath));
988
+ const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
989
+ const frontmatter = {
990
+ title,
991
+ date: now,
992
+ updated: now,
993
+ draft: true
994
+ };
995
+ if (tags && tags.length > 0)
996
+ frontmatter.tags = tags;
997
+ if (categories && categories.length > 0)
998
+ frontmatter.categories = categories;
999
+ const content = matter.stringify("\n", frontmatter);
1000
+ const ext = pathe.extname(filePath);
1001
+ const base = filePath.slice(0, -ext.length);
1002
+ let counter = 0;
1003
+ while (true) {
1004
+ const entryExists = await fs.lstat(filePath).then(
1005
+ () => true,
1006
+ (error) => {
1007
+ if (error.code === "ENOENT")
1008
+ return false;
1009
+ throw error;
1010
+ }
1011
+ );
1012
+ if (entryExists) {
1013
+ filePath = `${base}-${++counter}${ext}`;
1014
+ continue;
1015
+ }
1016
+ try {
1017
+ await fs.writeFile(filePath, content, { encoding: "utf-8", flag: "wx" });
1018
+ break;
1019
+ } catch (error) {
1020
+ if (error.code !== "EEXIST")
1021
+ throw error;
1022
+ filePath = `${base}-${++counter}${ext}`;
1023
+ }
1024
+ }
1025
+ return { success: true, filePath };
1026
+ } catch (e) {
1027
+ return { success: false, error: e.message || String(e) };
1028
+ }
1029
+ }
1030
+ };
1031
+ }
1032
+
1033
+ const fields = v.record(v.string(), v.unknown());
1034
+ const filePaths = v.array(v.string());
1035
+ const pageData = v.object({ routePath: v.string(), filePath: v.string(), frontmatter: fields });
1036
+ const success = v.object({ success: v.boolean() });
1037
+ const postContent = v.object({ content: v.string(), revision: v.string() });
1038
+ function createRpcFunctions(functions) {
1039
+ return [
1040
+ defineRpcFunction({ name: "get-post-content", type: "query", jsonSerializable: true, args: [v.string()], returns: postContent, handler: functions.getPostContent }),
1041
+ defineRpcFunction({
1042
+ name: "update-post-content",
1043
+ type: "action",
1044
+ jsonSerializable: true,
1045
+ args: [v.object({ filePath: v.string(), content: v.pipe(v.string(), v.maxLength(2e6)), revision: v.string() })],
1046
+ returns: postContent,
1047
+ handler: functions.updatePostContent
1048
+ }),
1049
+ defineRpcFunction({ name: "get-options", type: "query", jsonSerializable: true, handler: functions.getOptions }),
1050
+ defineRpcFunction({ name: "get-post-list", type: "query", jsonSerializable: true, handler: functions.getPostList }),
1051
+ defineRpcFunction({ name: "get-page-data", type: "query", jsonSerializable: true, args: [v.string()], returns: pageData, handler: functions.getPageData }),
1052
+ defineRpcFunction({ name: "get-collection-list", type: "query", jsonSerializable: true, handler: functions.getCollectionList }),
1053
+ defineRpcFunction({ name: "get-config", type: "query", jsonSerializable: true, handler: functions.getConfig }),
1054
+ defineRpcFunction({
1055
+ name: "create-post",
1056
+ type: "action",
1057
+ jsonSerializable: true,
1058
+ args: [v.object({ title: v.pipe(v.string(), v.minLength(1)), path: v.optional(v.string()), tags: v.optional(v.array(v.string())), categories: v.optional(v.array(v.string())) })],
1059
+ returns: v.object({ success: v.boolean(), filePath: v.optional(v.string()), error: v.optional(v.string()) }),
1060
+ handler: functions.createPost
1061
+ }),
1062
+ defineRpcFunction({
1063
+ name: "update-frontmatter",
1064
+ type: "action",
1065
+ jsonSerializable: true,
1066
+ args: [v.object({ filePath: v.string(), frontmatter: fields })],
1067
+ returns: success,
1068
+ handler: functions.updateFrontmatter
1069
+ }),
1070
+ defineRpcFunction({
1071
+ name: "batch-update-frontmatter",
1072
+ type: "action",
1073
+ jsonSerializable: true,
1074
+ args: [filePaths, v.array(v.variant("type", [
1075
+ v.object({ type: v.literal("set"), key: v.string(), value: v.unknown() }),
1076
+ v.object({ type: v.literal("delete"), key: v.string() }),
1077
+ v.object({ type: v.literal("rename"), key: v.string(), newKey: v.string() })
1078
+ ]))],
1079
+ returns: v.object({ total: v.number(), updated: v.number(), errors: v.array(v.object({ filePath: v.string(), error: v.string() })) }),
1080
+ handler: functions.batchUpdateFrontmatter
1081
+ }),
1082
+ defineRpcFunction({
1083
+ name: "update-config-field",
1084
+ type: "action",
1085
+ jsonSerializable: true,
1086
+ args: [v.picklist(["site", "valaxy", "theme"]), v.string(), v.unknown()],
1087
+ returns: v.object({ success: v.boolean(), error: v.optional(v.string()) }),
1088
+ handler: functions.updateConfigField
1089
+ }),
1090
+ defineRpcFunction({
1091
+ name: "run-migration",
1092
+ type: "action",
1093
+ jsonSerializable: true,
1094
+ args: [filePaths, v.record(v.string(), v.string())],
1095
+ returns: success,
1096
+ handler: functions.runMigration
1097
+ })
1098
+ ];
1099
+ }
1100
+ function createValaxyDevframe(options = {}) {
1101
+ const cleanups = [];
1102
+ let plugins = [];
1103
+ const onDispose = (cleanup) => {
1104
+ cleanups.push(cleanup);
1105
+ };
1106
+ async function dispose() {
1107
+ const errors = [];
1108
+ for (const cleanup of cleanups.splice(0).reverse()) {
1109
+ try {
1110
+ await cleanup();
1111
+ } catch (error) {
1112
+ errors.push(error);
1113
+ }
1114
+ }
1115
+ if (errors.length)
1116
+ throw new AggregateError(errors, "Valaxy DevTools cleanup failed");
1117
+ }
1118
+ const definition = defineDevframe({
1119
+ id: DEVTOOLS_ID,
1120
+ name: "Valaxy",
1121
+ version: pkg.version,
1122
+ packageName: pkg.name,
1123
+ importMetaUrl: import.meta.url,
1124
+ homepage: normalizeRepositoryUrl(pkg.repository.url),
1125
+ description: pkg.description,
1126
+ icon: resolveDevtoolsLogo(options.base),
1127
+ basePath: resolveDevtoolsBase(options.base),
1128
+ clientAssets: DIR_CLIENT,
1129
+ capabilities: { dev: true, build: false },
1130
+ services: [
1131
+ { package: "@devframes/service-shiki", options: { langs: ["json"] } },
1132
+ { package: "@devframes/service-open", options: { editor: getEditorOptions().editor, roots: [resolve$1(options.userRoot || process.cwd())] } }
1133
+ ],
1134
+ async setup(ctx) {
1135
+ await ctx.rpc.sharedState.get(RESOURCES_STATE, { initialValue: { revision: 0 } });
1136
+ plugins = await resolveDevtoolsPlugins(options);
1137
+ const functions = getFunctions(options, (data2) => validateEditorFields(plugins, data2));
1138
+ const data = createDataApi(ctx, {
1139
+ getOptions: functions.getOptions,
1140
+ getPostList: functions.getPostList,
1141
+ getPageData: functions.getPageData,
1142
+ getCollectionList: functions.getCollectionList,
1143
+ getConfig: functions.getConfig
1144
+ }, onDispose);
1145
+ const scoped = ctx.scope(DEVTOOLS_ID);
1146
+ for (const fn of createRpcFunctions(functions))
1147
+ scoped.rpc.register(fn);
1148
+ for (const fn of createAddonRpc(createAddonManager(options)))
1149
+ scoped.rpc.register(fn);
1150
+ const manifest = createManifest(plugins, options.base);
1151
+ for (const fn of createExtensionRpc(manifest, plugins, data))
1152
+ scoped.rpc.register(fn);
1153
+ try {
1154
+ await setupExtensions(ctx, plugins, manifest, data, onDispose);
1155
+ } catch (error) {
1156
+ await dispose();
1157
+ throw error;
1158
+ }
1159
+ }
1160
+ });
1161
+ return Object.assign(definition, { dispose });
1162
+ }
1163
+ function createAddonRpc(manager) {
1164
+ const name = v.pipe(v.string(), v.maxLength(214), v.regex(/^valaxy-addon-[a-z0-9][a-z0-9._-]*$/));
1165
+ const plan = v.object({ id: v.string(), action: v.picklist(["install", "remove"]), name: v.string(), version: v.optional(v.string()), command: v.string(), configFile: v.optional(v.string()), configBefore: v.optional(v.string()), configAfter: v.optional(v.string()) });
1166
+ const operation = v.object({ ...plan.entries, status: v.picklist(["running", "succeeded", "failed"]), log: v.string(), error: v.optional(v.string()) });
1167
+ const details = v.object({ name: v.string(), version: v.string(), description: v.string(), homepage: v.optional(v.string()), repository: v.optional(v.string()), license: v.optional(v.string()), peerDependencies: v.record(v.string(), v.string()) });
1168
+ return [
1169
+ defineRpcFunction({ name: "get-addons", type: "query", jsonSerializable: true, handler: manager.inventory }),
1170
+ defineRpcFunction({ name: "get-addon-package", type: "query", jsonSerializable: true, args: [name], returns: details, handler: manager.details }),
1171
+ defineRpcFunction({ name: "prepare-addon-operation", type: "action", jsonSerializable: true, args: [v.picklist(["install", "remove"]), name], returns: plan, handler: manager.prepare }),
1172
+ defineRpcFunction({ name: "apply-addon-operation", type: "action", jsonSerializable: true, args: [v.pipe(v.string(), v.uuid())], returns: operation, handler: manager.apply })
1173
+ ];
1174
+ }
1175
+ function createExtensionRpc(manifest, plugins, data) {
1176
+ return [
1177
+ defineRpcFunction({ name: "get-extensions", type: "query", jsonSerializable: true, handler: () => manifest }),
1178
+ defineRpcFunction({
1179
+ name: "run-editor-action",
1180
+ type: "query",
1181
+ jsonSerializable: true,
1182
+ args: [v.string(), v.string(), fields],
1183
+ returns: v.object({ message: v.string(), severity: v.optional(v.picklist(["success", "warn", "error", "info"])) }),
1184
+ handler: async (id, filePath, draft) => {
1185
+ const [pluginId, actionId, extra] = id.split(":");
1186
+ const action = !extra && plugins.find((plugin) => plugin.id === pluginId)?.editor?.actions?.find((action2) => action2.id === actionId);
1187
+ if (!action)
1188
+ throw new Error(`Unknown editor action: ${id}`);
1189
+ const page = await data.getPageData(filePath);
1190
+ return action.run({ page, draft: structuredClone(draft), data });
1191
+ }
1192
+ })
1193
+ ];
1194
+ }
1195
+
1196
+ export { createRpcFunctions, createValaxyDevframe };