@cloudflare/vite-plugin 2.0.0-rc.2 → 2.0.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,6 +18,18 @@ export default defineConfig({
18
18
 
19
19
  Full documentation can be found [here](https://developers.cloudflare.com/workers/vite-plugin/).
20
20
 
21
+ ## Local Explorer allowed hosts
22
+
23
+ Local Explorer trusts loopback hostnames, including `*.localhost`, and configured Worker route and upstream hostnames. It does not inherit Vite's `allowedHosts` by default.
24
+
25
+ To also trust Vite's resolved `server.allowedHosts` (or `preview.allowedHosts` during preview), set the experimental environment variable `X_LOCAL_EXPLORER_USE_VITE_ALLOWED_HOSTS=true`. It defaults to `false`.
26
+
27
+ ```sh
28
+ X_LOCAL_EXPLORER_USE_VITE_ALLOWED_HOSTS=true pnpm exec vite
29
+ ```
30
+
31
+ This extends the Host and Origin allowlist for all `/cdn-cgi/` endpoints, including Local Explorer APIs. Enable it only when every hostname in Vite's allowed list should have access to those APIs. Exact hostnames and suffix entries such as `.example.com` are supported, including tunnel hostnames added by the plugin. Setting Vite's `allowedHosts: true` keeps Miniflare's default allowlist, even with this opt-in enabled.
32
+
21
33
  ## Features
22
34
 
23
35
  - Uses the Vite [Environment API](https://vite.dev/guide/api-environment) to integrate Vite with the Workers runtime
@@ -0,0 +1,460 @@
1
+ import { u as getLocalExplorerEnabledFromEnv } from "./misc-variables-6mf5dDi6-D3ykvtRq.mjs";
2
+ import os from "os";
3
+ import { CorePaths } from "miniflare";
4
+ import { execSync } from "child_process";
5
+ //#region ../../node_modules/.pnpm/process-ancestry@0.1.0/node_modules/process-ancestry/dist/index.js
6
+ function getProcessInfo(pid) {
7
+ try {
8
+ const output = execSync(`ps -p ${pid} -o pid=,ppid=,command=`, {
9
+ encoding: "utf8",
10
+ timeout: 5e3
11
+ }).trim();
12
+ if (!output) return null;
13
+ const [pidStr, ppidStr, ...commandParts] = output.split(/\s+/);
14
+ const parsedPid = pidStr ? parseInt(pidStr, 10) : NaN;
15
+ const parsedPpid = ppidStr ? parseInt(ppidStr, 10) : NaN;
16
+ if (isNaN(parsedPid) || isNaN(parsedPpid)) return null;
17
+ return {
18
+ pid: parsedPid,
19
+ ppid: parsedPpid,
20
+ command: commandParts.join(" ") || void 0
21
+ };
22
+ } catch (error) {
23
+ if (error instanceof Error && error.message.includes("timeout")) console.warn(`Process lookup timed out for PID ${pid}`);
24
+ return null;
25
+ }
26
+ }
27
+ function getAncestryUnix(startPid) {
28
+ const result = [];
29
+ const visited = /* @__PURE__ */ new Set();
30
+ let currentPid = startPid;
31
+ let maxDepth = 1e3;
32
+ while (currentPid && maxDepth > 0) {
33
+ if (visited.has(currentPid)) {
34
+ console.warn(`Detected cycle in process tree at PID ${currentPid}`);
35
+ break;
36
+ }
37
+ visited.add(currentPid);
38
+ const info = getProcessInfo(currentPid);
39
+ if (!info || info.ppid === 0 || info.ppid === 1) break;
40
+ result.push(info);
41
+ currentPid = info.ppid;
42
+ maxDepth--;
43
+ }
44
+ if (maxDepth === 0) console.warn(`Reached maximum depth limit while traversing process tree from PID ${startPid}`);
45
+ return result;
46
+ }
47
+ function getProcessInfo2(pid) {
48
+ try {
49
+ const output = execSync(`wmic process where (ProcessId=${pid}) get ProcessId,ParentProcessId,CommandLine /format:csv`, {
50
+ encoding: "utf8",
51
+ timeout: 1e4
52
+ });
53
+ if (!output) return null;
54
+ const fields = output.split("\n").filter((line) => line.trim() && !line.startsWith("Node")).pop()?.split(",");
55
+ if (!fields || fields.length < 4) return null;
56
+ const [_node, commandLine, parentPid, thisPid] = fields;
57
+ const parsedPid = thisPid ? parseInt(thisPid.trim(), 10) : NaN;
58
+ const parsedPpid = parentPid ? parseInt(parentPid.trim(), 10) : NaN;
59
+ if (isNaN(parsedPid) || isNaN(parsedPpid)) return null;
60
+ return {
61
+ pid: parsedPid,
62
+ ppid: parsedPpid,
63
+ command: commandLine?.trim() || void 0
64
+ };
65
+ } catch (error) {
66
+ if (error instanceof Error && error.message.includes("timeout")) console.warn(`Process lookup timed out for PID ${pid}`);
67
+ return null;
68
+ }
69
+ }
70
+ function getAncestryWindows(startPid) {
71
+ const result = [];
72
+ const visited = /* @__PURE__ */ new Set();
73
+ let currentPid = startPid;
74
+ let maxDepth = 1e3;
75
+ while (currentPid && maxDepth > 0) {
76
+ if (visited.has(currentPid)) {
77
+ console.warn(`Detected cycle in process tree at PID ${currentPid}`);
78
+ break;
79
+ }
80
+ visited.add(currentPid);
81
+ const info = getProcessInfo2(currentPid);
82
+ if (!info || info.ppid === 0 || info.ppid === 4) break;
83
+ result.push(info);
84
+ currentPid = info.ppid;
85
+ maxDepth--;
86
+ }
87
+ if (maxDepth === 0) console.warn(`Reached maximum depth limit while traversing process tree from PID ${startPid}`);
88
+ return result;
89
+ }
90
+ function getProcessAncestry(pid = process.pid) {
91
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) throw new Error("PID must be a positive integer");
92
+ if (os.platform() === "win32") return getAncestryWindows(pid);
93
+ else return getAncestryUnix(pid);
94
+ }
95
+ //#endregion
96
+ //#region ../../node_modules/.pnpm/am-i-vibing@0.5.0/node_modules/am-i-vibing/dist/detector-1yx2Hoe0.mjs
97
+ /**
98
+ * Provider configurations for major AI coding tools
99
+ */
100
+ const providers = [
101
+ {
102
+ id: "opencode",
103
+ name: "OpenCode",
104
+ type: "agent",
105
+ envVars: [{ any: [
106
+ "OPENCODE",
107
+ "OPENCODE_BIN_PATH",
108
+ "OPENCODE_SERVER",
109
+ "OPENCODE_APP_INFO",
110
+ "OPENCODE_MODES"
111
+ ] }]
112
+ },
113
+ {
114
+ id: "jules",
115
+ name: "Jules",
116
+ type: "agent",
117
+ envVars: [{ all: [["HOME", "/home/jules"], ["USER", "swebot"]] }]
118
+ },
119
+ {
120
+ id: "claude-code",
121
+ name: "Claude Code",
122
+ type: "agent",
123
+ envVars: ["CLAUDECODE"]
124
+ },
125
+ {
126
+ id: "cursor-agent",
127
+ name: "Cursor Agent",
128
+ type: "agent",
129
+ envVars: [{ all: ["CURSOR_TRACE_ID", ["PAGER", "head -n 10000 | cat"]] }]
130
+ },
131
+ {
132
+ id: "cursor",
133
+ name: "Cursor",
134
+ type: "interactive",
135
+ envVars: ["CURSOR_TRACE_ID"]
136
+ },
137
+ {
138
+ id: "antigravity",
139
+ name: "Antigravity",
140
+ type: "agent",
141
+ envVars: [{ any: ["ANTIGRAVITY_AGENT", "ANTIGRAVITY_PROJECT_ID"] }]
142
+ },
143
+ {
144
+ id: "gemini-agent",
145
+ name: "Gemini CLI",
146
+ type: "agent",
147
+ envVars: [["GEMINI_CLI", "1"]],
148
+ processChecks: ["gemini"]
149
+ },
150
+ {
151
+ id: "codex",
152
+ name: "OpenAI Codex",
153
+ type: "agent",
154
+ envVars: ["CODEX_THREAD_ID"],
155
+ processChecks: ["codex"]
156
+ },
157
+ {
158
+ id: "replit",
159
+ name: "Replit",
160
+ type: "agent",
161
+ envVars: ["REPL_ID"]
162
+ },
163
+ {
164
+ id: "aider",
165
+ name: "Aider",
166
+ type: "agent",
167
+ envVars: ["AIDER_API_KEY"],
168
+ processChecks: ["aider"]
169
+ },
170
+ {
171
+ id: "bolt-agent",
172
+ name: "Bolt.new Agent",
173
+ type: "agent",
174
+ envVars: [{ all: [["SHELL", "/bin/jsh"], "npm_config_yes"] }]
175
+ },
176
+ {
177
+ id: "bolt",
178
+ name: "Bolt.new",
179
+ type: "interactive",
180
+ envVars: [{
181
+ all: [["SHELL", "/bin/jsh"]],
182
+ none: ["npm_config_yes"]
183
+ }]
184
+ },
185
+ {
186
+ id: "zed-agent",
187
+ name: "Zed Agent",
188
+ type: "agent",
189
+ envVars: [{ all: [["TERM_PROGRAM", "zed"], ["PAGER", "cat"]] }]
190
+ },
191
+ {
192
+ id: "zed",
193
+ name: "Zed",
194
+ type: "interactive",
195
+ envVars: [{
196
+ all: [["TERM_PROGRAM", "zed"]],
197
+ none: [["PAGER", "cat"]]
198
+ }]
199
+ },
200
+ {
201
+ id: "replit-assistant",
202
+ name: "Replit Assistant",
203
+ type: "agent",
204
+ envVars: [{ all: ["REPL_ID", ["REPLIT_MODE", "assistant"]] }]
205
+ },
206
+ {
207
+ id: "replit",
208
+ name: "Replit",
209
+ type: "interactive",
210
+ envVars: [{
211
+ all: ["REPL_ID"],
212
+ none: [["REPLIT_MODE", "assistant"]]
213
+ }]
214
+ },
215
+ {
216
+ id: "windsurf",
217
+ name: "Windsurf",
218
+ type: "agent",
219
+ envVars: ["CODEIUM_EDITOR_APP_ROOT"]
220
+ },
221
+ {
222
+ id: "crush",
223
+ name: "Crush",
224
+ type: "agent",
225
+ envVars: [{ any: [
226
+ ["CRUSH", "1"],
227
+ ["AGENT", "crush"],
228
+ ["AI_AGENT", "crush"]
229
+ ] }],
230
+ processChecks: ["crush"]
231
+ },
232
+ {
233
+ id: "amp",
234
+ name: "Amp",
235
+ type: "agent",
236
+ envVars: [{ any: ["AMP_CURRENT_THREAD_ID", ["AGENT", "amp"]] }]
237
+ },
238
+ {
239
+ id: "auggie",
240
+ name: "Auggie",
241
+ type: "agent",
242
+ envVars: [["AUGMENT_AGENT", "1"]]
243
+ },
244
+ {
245
+ id: "qwen-code",
246
+ name: "Qwen Code",
247
+ type: "agent",
248
+ envVars: [["QWEN_CODE", "1"]]
249
+ },
250
+ {
251
+ id: "vscode-copilot-agent",
252
+ name: "GitHub Copilot in VS Code",
253
+ type: "agent",
254
+ envVars: [{ all: [["TERM_PROGRAM", "vscode"], ["GIT_PAGER", "cat"]] }]
255
+ },
256
+ {
257
+ id: "warp",
258
+ name: "Warp Terminal",
259
+ type: "hybrid",
260
+ envVars: [{ all: [["TERM_PROGRAM", "WarpTerminal"]] }]
261
+ },
262
+ {
263
+ id: "octofriend",
264
+ name: "Octofriend",
265
+ type: "agent",
266
+ processChecks: ["octofriend"]
267
+ },
268
+ {
269
+ id: "devin",
270
+ name: "Devin",
271
+ type: "agent",
272
+ processChecks: ["devin"]
273
+ },
274
+ {
275
+ id: "droid",
276
+ name: "Factory Droid",
277
+ type: "agent",
278
+ processChecks: ["droid"]
279
+ },
280
+ {
281
+ id: "pi",
282
+ name: "Pi",
283
+ type: "agent",
284
+ envVars: [["PI_CODING_AGENT", "true"]]
285
+ }
286
+ ];
287
+ /**
288
+ * Check if a specific environment variable exists (handles both strings and tuples)
289
+ */
290
+ function checkEnvVar(envVarDef, env = process.env) {
291
+ const [envVar, expectedValue] = typeof envVarDef === "string" ? [envVarDef, void 0] : envVarDef;
292
+ const actualValue = env[envVar];
293
+ return Boolean(actualValue && (!expectedValue || actualValue === expectedValue));
294
+ }
295
+ /**
296
+ * Check if a process is running in the process tree
297
+ */
298
+ function checkProcess(processName, processAncestry) {
299
+ for (const ancestorProcess of processAncestry) if (ancestorProcess.command?.includes(processName)) return true;
300
+ return false;
301
+ }
302
+ /**
303
+ * Check if an environment variable group matches based on its properties
304
+ */
305
+ function checkEnvVars(definition, env = process.env) {
306
+ if (typeof definition === "string" || Array.isArray(definition)) return checkEnvVar(definition, env);
307
+ const { any, all, none } = definition;
308
+ const anyResult = !any?.length || any.some((envVar) => checkEnvVar(envVar, env));
309
+ const allResult = !all?.length || all.every((envVar) => checkEnvVar(envVar, env));
310
+ const noneResult = !none?.length || !none.some((envVar) => checkEnvVar(envVar, env));
311
+ return anyResult && allResult && noneResult;
312
+ }
313
+ /**
314
+ * Run custom detectors for a provider
315
+ */
316
+ function runCustomDetectors(provider) {
317
+ return provider.customDetectors?.some((detector) => {
318
+ try {
319
+ return detector();
320
+ } catch {
321
+ return false;
322
+ }
323
+ }) ?? false;
324
+ }
325
+ /**
326
+ * Create a positive detection result
327
+ */
328
+ function createDetectedResult(provider) {
329
+ return {
330
+ isAgentic: true,
331
+ id: provider.id,
332
+ name: provider.name,
333
+ type: provider.type
334
+ };
335
+ }
336
+ /**
337
+ * Normalize the various supported argument shapes into a DetectOptions object.
338
+ *
339
+ * Supported shapes:
340
+ * - detectAgenticEnvironment()
341
+ * - detectAgenticEnvironment(options)
342
+ * - detectAgenticEnvironment(env) // legacy
343
+ * - detectAgenticEnvironment(env, processAncestry) // legacy
344
+ */
345
+ function normalizeOptions(envOrOptions, legacyAncestry) {
346
+ if (envOrOptions != null && typeof envOrOptions === "object" && ("env" in envOrOptions || "processAncestry" in envOrOptions || "checkProcesses" in envOrOptions)) {
347
+ const opts = envOrOptions;
348
+ return {
349
+ env: opts.env ?? process.env,
350
+ processAncestry: opts.processAncestry,
351
+ checkProcesses: opts.checkProcesses ?? opts.processAncestry !== void 0
352
+ };
353
+ }
354
+ return {
355
+ env: envOrOptions ?? process.env,
356
+ processAncestry: legacyAncestry,
357
+ checkProcesses: legacyAncestry !== void 0
358
+ };
359
+ }
360
+ function detectAgenticEnvironment(envOrOptions, legacyAncestry) {
361
+ const { env, processAncestry, checkProcesses } = normalizeOptions(envOrOptions, legacyAncestry);
362
+ for (const provider of providers) if (provider.envVars?.some((group) => checkEnvVars(group, env))) return createDetectedResult(provider);
363
+ for (const provider of providers) if (runCustomDetectors(provider)) return createDetectedResult(provider);
364
+ if (checkProcesses) {
365
+ let cachedAncestry = processAncestry;
366
+ const getAncestry = () => {
367
+ if (cachedAncestry === void 0) try {
368
+ cachedAncestry = getProcessAncestry();
369
+ } catch {
370
+ cachedAncestry = [];
371
+ }
372
+ return cachedAncestry;
373
+ };
374
+ for (const provider of providers) if (provider.processChecks?.some((processName) => checkProcess(processName, getAncestry()))) return createDetectedResult(provider);
375
+ }
376
+ return {
377
+ isAgentic: false,
378
+ id: null,
379
+ name: null,
380
+ type: null
381
+ };
382
+ }
383
+ //#endregion
384
+ //#region src/detect-agent.ts
385
+ const NO_PROCESS_ANCESTRY = [];
386
+ /**
387
+ * Detects whether the current process is being driven by an AI coding agent.
388
+ *
389
+ * True only when the detected type is exactly `"agent"`. Hybrid terminals (Warp,
390
+ * VS Code) embed agentic features but still have a human at the keyboard, so
391
+ * they're treated as interactive — note `isAgent()` from the library would
392
+ * report them as agents.
393
+ *
394
+ * Any error resolves to `false` rather than propagating.
395
+ */
396
+ function isAgentSession() {
397
+ try {
398
+ return detectAgenticEnvironment({
399
+ env: process.env,
400
+ processAncestry: NO_PROCESS_ANCESTRY
401
+ }).type === "agent";
402
+ } catch {
403
+ return false;
404
+ }
405
+ }
406
+ //#endregion
407
+ //#region src/plugins/agent-hint.ts
408
+ /**
409
+ * If the session is a headless AI agent with Local Explorer enabled,
410
+ * patches `server.bindCLIShortcuts` to print the explorer API hint
411
+ * after the shortcut hints have been printed.
412
+ *
413
+ * @param server - The Vite dev or preview server
414
+ * @param mode - Whether this is a "dev" or "preview" session
415
+ */
416
+ function maybeAddAgentHint(server, mode) {
417
+ if (process.stdin.isTTY || !getLocalExplorerEnabledFromEnv() || !isAgentSession()) return;
418
+ const originalBindCLIShortcuts = server.bindCLIShortcuts.bind(server);
419
+ server.bindCLIShortcuts = (options) => {
420
+ originalBindCLIShortcuts(options);
421
+ if (options?.print) printLocalExplorerAgentHint(server, mode);
422
+ };
423
+ }
424
+ /**
425
+ * Prints the Local Explorer API URL and useful routes to stdout so that
426
+ * headless AI agents can discover and call them programmatically.
427
+ *
428
+ * Keep the message in sync with:
429
+ * - packages/wrangler/src/dev/start-dev.ts (printLocalExplorerAgentHint)
430
+ * - packages/create-cloudflare/src/agents-md.ts (Local Explorer section)
431
+ *
432
+ * @param server - The Vite dev or preview server (must have `resolvedUrls` populated)
433
+ * @param mode - Whether this is a "dev" or "preview" session
434
+ */
435
+ function printLocalExplorerAgentHint(server, mode) {
436
+ const url = server.resolvedUrls?.local[0];
437
+ if (!url) return;
438
+ const explorerApiUrl = new URL(`${CorePaths.EXPLORER}/api`, url).href;
439
+ server.config.logger.info([
440
+ "",
441
+ `The Cloudflare Vite plugin detected this ${mode} session is running in an AI agent.`,
442
+ `The Local Explorer API is available at ${explorerApiUrl}`,
443
+ `Useful routes:`,
444
+ ` GET ${explorerApiUrl}/local/workers - local Workers and bindings`,
445
+ ` POST ${explorerApiUrl}/local/scheduled?worker=<name> - invoke a Worker's scheduled handler; cron is required (see the OpenAPI schema for the full request)`,
446
+ ` GET ${explorerApiUrl}/storage/kv/namespaces - KV namespaces`,
447
+ ` GET ${explorerApiUrl}/d1/database - D1 databases`,
448
+ ` GET ${explorerApiUrl}/r2/buckets - R2 buckets`,
449
+ ` GET ${explorerApiUrl}/workers/durable_objects/namespaces - Durable Object namespaces`,
450
+ ` GET ${explorerApiUrl}/workflows - Workflows`,
451
+ ` POST ${explorerApiUrl}/local/observability/query - run a read-only SQL query (SELECT/WITH only) over captured request traces and console logs. Tables: spans, logs (read attributes via json(attributes)). Example:`,
452
+ ` curl -X POST ${explorerApiUrl}/local/observability/query -H 'Content-Type: application/json' -d '{"sql":"SELECT service, name, outcome, duration_ms FROM spans WHERE parent_id IS NULL LIMIT 20"}'`,
453
+ ` POST ${explorerApiUrl}/local/observability/clear - clear all captured traces and logs`,
454
+ `If the routes above don't cover what you need, fetch the full OpenAPI schema (large - use only as a last resort):`,
455
+ ` GET ${explorerApiUrl} - OpenAPI schema`,
456
+ ""
457
+ ].join("\n"));
458
+ }
459
+ //#endregion
460
+ export { maybeAddAgentHint };