@innovatorved/code-lab 0.3.0 → 0.3.2

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 (57) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +38 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1533 -396
  7. package/dist/code-lab.js +1532 -395
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.d.ts +8 -0
  10. package/dist/extensions/cpp.esm.js +333 -10
  11. package/dist/extensions/cpp.js +333 -10
  12. package/dist/extensions/guided-lab.esm.js +1 -1
  13. package/dist/extensions/guided-lab.js +1 -1
  14. package/dist/extensions/python.esm.js +117 -104
  15. package/dist/extensions/python.js +117 -104
  16. package/dist/index.d.ts +1 -1
  17. package/dist/preview-sw.js +34 -17
  18. package/dist/runtime.esm.js +38 -31
  19. package/dist/runtime.js +38 -31
  20. package/dist/schemas.d.ts +4 -4
  21. package/dist/schemas.esm.js +1 -1
  22. package/dist/schemas.js +1 -1
  23. package/dist/scm.d.ts +13 -2
  24. package/dist/search.d.ts +5 -1
  25. package/dist/shell.esm.js +72 -16
  26. package/dist/shell.js +72 -16
  27. package/dist/terminal.esm.js +183 -54
  28. package/dist/terminal.js +183 -54
  29. package/dist/workbench/index.d.ts +1 -1
  30. package/dist/workbench/styles.d.ts +1 -1
  31. package/dist/zip.d.ts +4 -3
  32. package/package.json +1 -1
  33. package/src/code-lab.css +52 -2
  34. package/src/csp.ts +7 -10
  35. package/src/diagnostics.ts +42 -3
  36. package/src/extensions/cpp.ts +303 -9
  37. package/src/extensions/python.ts +128 -116
  38. package/src/index.ts +1 -1
  39. package/src/preview-sw.js +25 -5
  40. package/src/runtime.ts +36 -29
  41. package/src/schemas.ts +2 -2
  42. package/src/scm.ts +106 -19
  43. package/src/search.ts +71 -27
  44. package/src/shell.ts +70 -14
  45. package/src/terminal.ts +181 -52
  46. package/src/workbench/diff-editor.ts +41 -13
  47. package/src/workbench/drawer.ts +17 -8
  48. package/src/workbench/guided-pane.ts +12 -2
  49. package/src/workbench/share.ts +37 -8
  50. package/src/workbench/styles.ts +2 -1
  51. package/src/workbench/toolbar.ts +15 -4
  52. package/src/workbench.ts +484 -91
  53. package/src/zip.ts +29 -7
  54. package/dist/runtime/module-loader.d.ts +0 -11
  55. package/dist/runtime/vfs.d.ts +0 -31
  56. package/dist/runtime/wasi-host.d.ts +0 -33
  57. package/dist/shell/lexer-parser.d.ts +0 -26
package/src/scm.ts CHANGED
@@ -31,10 +31,19 @@ export interface GitState {
31
31
  branches?: string[];
32
32
  headCommit: string;
33
33
  headFiles: Record<string, string>;
34
- staged: Map<string, string | null>;
34
+ headSnapshot?: Record<string, string>;
35
+ staged: Map<string, string | null> | Set<string>;
35
36
  commits: GitCommitRecord[];
36
37
  }
37
38
 
39
+ export interface GitStatusEntry {
40
+ path: string;
41
+ status: GitFileChangeType;
42
+ staged: boolean;
43
+ index: string;
44
+ worktree: string;
45
+ }
46
+
38
47
  export interface GitStatusResult {
39
48
  branch: string;
40
49
  headCommit: string;
@@ -43,6 +52,7 @@ export interface GitStatusResult {
43
52
  deleted: GitFileStatus[];
44
53
  staged: GitFileStatus[];
45
54
  unstaged: GitFileStatus[];
55
+ entries: GitStatusEntry[];
46
56
  hasChanges: boolean;
47
57
  isClean: boolean;
48
58
  }
@@ -92,15 +102,41 @@ export function createGitState(
92
102
 
93
103
  /**
94
104
  * Computes working-tree and staging-area Git status against `gitState`.
105
+ * Supports both `computeGitStatus(vfsFiles, repoRoot, gitState)` and
106
+ * `computeGitStatus(gitState, vfsFiles)` calling conventions.
95
107
  */
96
108
  export function computeGitStatus(
97
- vfsFiles: Record<string, string>,
98
- _repoRoot = '/workspace',
109
+ arg1: Record<string, string> | GitState,
110
+ arg2: string | Record<string, string> = '/workspace',
99
111
  gitState?: GitState
100
112
  ): GitStatusResult {
101
- const state = gitState || createGitState({});
102
- const headFiles = state.headFiles || {};
103
- const currentStaged = state.staged instanceof Map ? state.staged : new Map<string, string | null>();
113
+ let vfsFiles: Record<string, string>;
114
+ let state: GitState;
115
+
116
+ if (
117
+ arg1 &&
118
+ typeof arg1 === 'object' &&
119
+ ('headFiles' in arg1 || 'headSnapshot' in arg1 || 'staged' in arg1 || 'commits' in arg1)
120
+ ) {
121
+ state = arg1 as GitState;
122
+ vfsFiles = (arg2 && typeof arg2 === 'object' ? arg2 : {}) as Record<string, string>;
123
+ } else {
124
+ vfsFiles = (arg1 && typeof arg1 === 'object' ? arg1 : {}) as Record<string, string>;
125
+ state = gitState || createGitState({});
126
+ }
127
+
128
+ const headFiles: Record<string, string> = state.headFiles || state.headSnapshot || {};
129
+ const currentStaged = new Map<string, string | null>();
130
+ if (state.staged instanceof Map) {
131
+ for (const [k, v] of state.staged.entries()) {
132
+ currentStaged.set(k, v);
133
+ }
134
+ } else if (state.staged instanceof Set) {
135
+ for (const k of state.staged.values()) {
136
+ const existsInVfs = Object.prototype.hasOwnProperty.call(vfsFiles, k);
137
+ currentStaged.set(k, existsInVfs ? vfsFiles[k] : null);
138
+ }
139
+ }
104
140
 
105
141
  const untracked: GitFileStatus[] = [];
106
142
  const modified: GitFileStatus[] = [];
@@ -110,12 +146,14 @@ export function computeGitStatus(
110
146
  for (const [filePath, stagedContent] of currentStaged.entries()) {
111
147
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
112
148
  if (stagedContent === null) {
113
- staged.push({
114
- path: filePath,
115
- status: 'deleted',
116
- staged: true,
117
- oldContent: headFiles[filePath]
118
- });
149
+ if (inHead) {
150
+ staged.push({
151
+ path: filePath,
152
+ status: 'deleted',
153
+ staged: true,
154
+ oldContent: headFiles[filePath]
155
+ });
156
+ }
119
157
  } else {
120
158
  staged.push({
121
159
  path: filePath,
@@ -174,6 +212,36 @@ export function computeGitStatus(
174
212
  }
175
213
 
176
214
  const unstaged: GitFileStatus[] = [...modified, ...deleted];
215
+ const entries: GitStatusEntry[] = [
216
+ ...staged.map((s) => ({
217
+ path: s.path,
218
+ status: s.status,
219
+ staged: true,
220
+ index: s.status === 'added' ? 'A' : s.status === 'deleted' ? 'D' : 'M',
221
+ worktree: ' '
222
+ })),
223
+ ...modified.map((m) => ({
224
+ path: m.path,
225
+ status: m.status,
226
+ staged: false,
227
+ index: ' ',
228
+ worktree: 'M'
229
+ })),
230
+ ...deleted.map((d) => ({
231
+ path: d.path,
232
+ status: d.status,
233
+ staged: false,
234
+ index: ' ',
235
+ worktree: 'D'
236
+ })),
237
+ ...untracked.map((u) => ({
238
+ path: u.path,
239
+ status: u.status,
240
+ staged: false,
241
+ index: '?',
242
+ worktree: '?'
243
+ }))
244
+ ];
177
245
  const isClean =
178
246
  untracked.length === 0 &&
179
247
  modified.length === 0 &&
@@ -188,6 +256,7 @@ export function computeGitStatus(
188
256
  deleted,
189
257
  staged,
190
258
  unstaged,
259
+ entries,
191
260
  hasChanges: !isClean,
192
261
  isClean
193
262
  };
@@ -205,15 +274,28 @@ export function stageFile(
205
274
  if (!(gitState.staged instanceof Map)) {
206
275
  gitState.staged = new Map<string, string | null>();
207
276
  }
208
- gitState.staged.set(relativePath, currentContent === undefined ? null : currentContent);
277
+ const normalizedContent = currentContent === undefined ? null : currentContent;
278
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
279
+ if (
280
+ normalizedContent === null &&
281
+ !Object.prototype.hasOwnProperty.call(headFiles, relativePath) &&
282
+ !gitState.staged.has(relativePath)
283
+ ) {
284
+ return;
285
+ }
286
+ gitState.staged.set(relativePath, normalizedContent);
209
287
  }
210
288
 
211
289
  /**
212
290
  * Removes a file from the staging index.
213
291
  */
214
292
  export function unstageFile(gitState: GitState, relativePath: string): void {
215
- if (!gitState || !(gitState.staged instanceof Map)) return;
216
- gitState.staged.delete(relativePath);
293
+ if (!gitState) return;
294
+ if (gitState.staged instanceof Map) {
295
+ gitState.staged.delete(relativePath);
296
+ } else if (gitState.staged instanceof Set) {
297
+ gitState.staged.delete(relativePath);
298
+ }
217
299
  }
218
300
 
219
301
  /**
@@ -229,8 +311,10 @@ export function commitChanges(gitState: GitState, message: string): string {
229
311
  throw new Error('Nothing to commit (staging area is empty)');
230
312
  }
231
313
 
232
- const newHeadFiles: Record<string, string> = { ...(gitState.headFiles || {}) };
314
+ const newHeadFiles: Record<string, string> = { ...(gitState.headFiles || gitState.headSnapshot || {}) };
315
+ const diffSummaryParts: string[] = [];
233
316
  for (const [filePath, content] of gitState.staged.entries()) {
317
+ diffSummaryParts.push(`${filePath}:${content === null ? '<DEL>' : content}`);
234
318
  if (content === null) {
235
319
  delete newHeadFiles[filePath];
236
320
  } else {
@@ -239,12 +323,15 @@ export function commitChanges(gitState: GitState, message: string): string {
239
323
  }
240
324
 
241
325
  const timestamp = Date.now();
242
- const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
326
+ const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
327
+ const hash = computeShortCommitHash(
328
+ `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join('|')}`
329
+ );
243
330
  const commit: GitCommitRecord = {
244
331
  hash,
245
332
  message: trimmed,
246
333
  timestamp,
247
- files: newHeadFiles
334
+ files: { ...newHeadFiles }
248
335
  };
249
336
 
250
337
  if (!Array.isArray(gitState.commits)) {
@@ -252,7 +339,7 @@ export function commitChanges(gitState: GitState, message: string): string {
252
339
  }
253
340
  gitState.commits.push(commit);
254
341
  gitState.headCommit = hash;
255
- gitState.headFiles = newHeadFiles;
342
+ gitState.headFiles = { ...newHeadFiles };
256
343
  gitState.staged.clear();
257
344
 
258
345
  return hash;
package/src/search.ts CHANGED
@@ -10,6 +10,7 @@
10
10
 
11
11
  export interface SearchOptions {
12
12
  query?: string;
13
+ replacement?: string;
13
14
  caseSensitive?: boolean;
14
15
  wholeWord?: boolean;
15
16
  regex?: boolean;
@@ -55,8 +56,10 @@ export interface SearchResult extends Array<SearchMatchGroup> {
55
56
 
56
57
  export interface ReplaceResult {
57
58
  updatedFiles: Record<string, string>;
59
+ files: Record<string, string>;
58
60
  replacedCount: number;
59
61
  filesAffected: string[];
62
+ filesModified: number;
60
63
  }
61
64
 
62
65
  /**
@@ -82,11 +85,22 @@ export function normalizeSearchPath(filePath: string): string {
82
85
 
83
86
  /**
84
87
  * Matches a file path against a glob or literal substring filter.
88
+ * Supports comma-separated patterns (e.g. `*.ts, *.js`).
85
89
  */
86
90
  export function matchesGlob(filePath: string, pattern: string): boolean {
87
91
  if (!pattern || pattern === '*' || pattern === '**') return true;
92
+ if (pattern.includes(',')) {
93
+ const subPatterns = pattern
94
+ .split(',')
95
+ .map((s) => s.trim())
96
+ .filter(Boolean);
97
+ if (subPatterns.length > 1) {
98
+ return subPatterns.some((sub) => matchesGlob(filePath, sub));
99
+ }
100
+ }
101
+
88
102
  const normPath = normalizeSearchPath(filePath);
89
- const normPattern = normalizeSearchPath(pattern);
103
+ const normPattern = normalizeSearchPath(pattern.trim());
90
104
 
91
105
  if (normPattern === normPath) return true;
92
106
 
@@ -102,10 +116,13 @@ export function matchesGlob(filePath: string, pattern: string): boolean {
102
116
  const c = normPattern[i];
103
117
  if (c === '*') {
104
118
  if (normPattern[i + 1] === '*') {
105
- regexStr += '.*';
106
119
  i += 2;
107
120
  if (normPattern[i] === '/') {
121
+ // `/**/` or leading `**/` matches zero or more directory segments
122
+ regexStr += '(?:.*/)?';
108
123
  i++;
124
+ } else {
125
+ regexStr += '.*';
109
126
  }
110
127
  continue;
111
128
  } else {
@@ -130,7 +147,13 @@ export function matchesGlob(filePath: string, pattern: string): boolean {
130
147
 
131
148
  try {
132
149
  const re = new RegExp(regexStr);
133
- return re.test(normPath);
150
+ if (re.test(normPath)) return true;
151
+ // Also allow basename match when pattern has no directory separator (e.g. `*.ts` matching `src/app.ts`)
152
+ if (!normPattern.includes('/')) {
153
+ const baseName = normPath.split('/').pop() || normPath;
154
+ if (re.test(baseName)) return true;
155
+ }
156
+ return false;
134
157
  } catch (err) {
135
158
  void err;
136
159
  return normPath.includes(normPattern.replace(/[*?]/g, ''));
@@ -286,11 +309,11 @@ export function searchInFiles(
286
309
  export function replaceInFiles(
287
310
  files: Record<string, string>,
288
311
  arg2: string | SearchOptions,
289
- arg3: string,
312
+ arg3?: string,
290
313
  arg4?: SearchOptions | string[]
291
314
  ): ReplaceResult {
292
315
  let query = '';
293
- const replacement = typeof arg3 === 'string' ? arg3 : '';
316
+ let replacement = typeof arg3 === 'string' ? arg3 : '';
294
317
  let opts: SearchOptions = {};
295
318
  let targetFiles: string[] | undefined = undefined;
296
319
 
@@ -305,6 +328,9 @@ export function replaceInFiles(
305
328
  } else if (arg2 && typeof arg2 === 'object') {
306
329
  opts = arg2;
307
330
  query = opts.query || '';
331
+ if (typeof arg3 !== 'string' && typeof opts.replacement === 'string') {
332
+ replacement = opts.replacement;
333
+ }
308
334
  if (Array.isArray(arg4)) {
309
335
  targetFiles = arg4;
310
336
  } else {
@@ -313,10 +339,13 @@ export function replaceInFiles(
313
339
  }
314
340
 
315
341
  if (!query) {
342
+ const copy = { ...files };
316
343
  return {
317
- updatedFiles: { ...files },
344
+ updatedFiles: copy,
345
+ files: copy,
318
346
  replacedCount: 0,
319
- filesAffected: []
347
+ filesAffected: [],
348
+ filesModified: 0
320
349
  };
321
350
  }
322
351
 
@@ -337,10 +366,13 @@ export function replaceInFiles(
337
366
  regex = new RegExp(patternStr, isCaseSensitive ? 'g' : 'gi');
338
367
  } catch (err) {
339
368
  void err;
369
+ const copy = { ...files };
340
370
  return {
341
- updatedFiles: { ...files },
371
+ updatedFiles: copy,
372
+ files: copy,
342
373
  replacedCount: 0,
343
- filesAffected: []
374
+ filesAffected: [],
375
+ filesModified: 0
344
376
  };
345
377
  }
346
378
 
@@ -353,29 +385,39 @@ export function replaceInFiles(
353
385
  if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
354
386
  if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
355
387
 
356
- // Count matches safely
357
- regex.lastIndex = 0;
388
+ const lines = content.split('\n');
358
389
  let countInFile = 0;
359
- let m: RegExpExecArray | null;
360
- while ((m = regex.exec(content)) !== null) {
361
- countInFile++;
362
- if (m[0].length === 0) {
363
- regex.lastIndex++;
364
- if (regex.lastIndex > content.length) {
365
- break;
390
+ const newLines: string[] = [];
391
+
392
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
393
+ const lineText = lines[lineIdx];
394
+ regex.lastIndex = 0;
395
+ let lineMatches = 0;
396
+ let m: RegExpExecArray | null;
397
+ while ((m = regex.exec(lineText)) !== null) {
398
+ lineMatches++;
399
+ if (m[0].length === 0) {
400
+ regex.lastIndex++;
401
+ if (regex.lastIndex > lineText.length) {
402
+ break;
403
+ }
404
+ }
405
+ }
406
+ if (lineMatches > 0) {
407
+ countInFile += lineMatches;
408
+ regex.lastIndex = 0;
409
+ if (isRegex) {
410
+ newLines.push(lineText.replace(regex, replacement));
411
+ } else {
412
+ newLines.push(lineText.replace(regex, () => replacement));
366
413
  }
414
+ } else {
415
+ newLines.push(lineText);
367
416
  }
368
417
  }
369
418
 
370
419
  if (countInFile > 0) {
371
- regex.lastIndex = 0;
372
- let newContent: string;
373
- if (isRegex) {
374
- newContent = content.replace(regex, replacement);
375
- } else {
376
- newContent = content.replace(regex, () => replacement);
377
- }
378
- updatedFiles[filePath] = newContent;
420
+ updatedFiles[filePath] = newLines.join('\n');
379
421
  filesAffected.push(filePath);
380
422
  replacedCount += countInFile;
381
423
  }
@@ -383,7 +425,9 @@ export function replaceInFiles(
383
425
 
384
426
  return {
385
427
  updatedFiles,
428
+ files: updatedFiles,
386
429
  replacedCount,
387
- filesAffected
430
+ filesAffected,
431
+ filesModified: filesAffected.length
388
432
  };
389
433
  }
package/src/shell.ts CHANGED
@@ -2902,6 +2902,13 @@
2902
2902
  return out;
2903
2903
  }
2904
2904
 
2905
+ function quoteShellArg(arg) {
2906
+ const s = String(arg ?? '');
2907
+ if (s.length === 0) return "''";
2908
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
2909
+ return "'" + s.replace(/'/g, "'\\''") + "'";
2910
+ }
2911
+
2905
2912
  async function runPackageScript(scriptName, scriptArgs, ctx) {
2906
2913
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
2907
2914
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -2909,7 +2916,7 @@
2909
2916
  }
2910
2917
  let cmd = pkgData.scripts[scriptName];
2911
2918
  if (scriptArgs && scriptArgs.length > 0) {
2912
- cmd += ' ' + scriptArgs.join(' ');
2919
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
2913
2920
  }
2914
2921
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
2915
2922
  if (fallback) return fallback;
@@ -3162,6 +3169,11 @@
3162
3169
  const isFile = (p) => exists(p) && !isDir(p);
3163
3170
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
3164
3171
 
3172
+ const isWithinRoot = (p) => {
3173
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
3174
+ return p === rootDir || p.startsWith(rootPrefix);
3175
+ };
3176
+
3165
3177
  const resolveLocalTarget = (baseDir, rawSpec) => {
3166
3178
  if (!rawSpec || typeof rawSpec !== 'string') return null;
3167
3179
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -3169,6 +3181,7 @@
3169
3181
  const candidateBase = clean.startsWith('/')
3170
3182
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
3171
3183
  : PosixPath.join(baseDir, clean);
3184
+ if (!isWithinRoot(candidateBase)) return null;
3172
3185
  if (isFile(candidateBase)) return candidateBase;
3173
3186
  const cands = [
3174
3187
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -3177,7 +3190,7 @@
3177
3190
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
3178
3191
  ];
3179
3192
  for (const c of cands) {
3180
- if (isFile(c)) return c;
3193
+ if (isWithinRoot(c) && isFile(c)) return c;
3181
3194
  }
3182
3195
  return null;
3183
3196
  };
@@ -3306,7 +3319,7 @@
3306
3319
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3307
3320
  needsTailwindBrowser = true;
3308
3321
  }
3309
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3322
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
3310
3323
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3311
3324
  });
3312
3325
 
@@ -3318,7 +3331,7 @@
3318
3331
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
3319
3332
  const rawScript = readText(scriptTarget);
3320
3333
  if (rawScript === null) return fullTag;
3321
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3334
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
3322
3335
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3323
3336
  const typeAttr = isMod ? ' type="module"' : '';
3324
3337
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -3341,6 +3354,12 @@
3341
3354
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
3342
3355
  const rel = pathname.replace(/^\/+/, '');
3343
3356
  let target = PosixPath.join(rootDir, rel);
3357
+ if (!isWithinRoot(target)) {
3358
+ return new Response(
3359
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
3360
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
3361
+ );
3362
+ }
3344
3363
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3345
3364
 
3346
3365
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -3365,8 +3384,13 @@
3365
3384
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3366
3385
  }
3367
3386
  if (!exists(target)) {
3387
+ const safePath = String(pathname)
3388
+ .replace(/&/g, '&amp;')
3389
+ .replace(/</g, '&lt;')
3390
+ .replace(/>/g, '&gt;')
3391
+ .replace(/"/g, '&quot;');
3368
3392
  return new Response(
3369
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
3393
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
3370
3394
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
3371
3395
  );
3372
3396
  }
@@ -5517,13 +5541,17 @@
5517
5541
 
5518
5542
  const count = Math.max(1, result.filesWritten);
5519
5543
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
5544
+ if (!enumeratedEmitted) {
5545
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
5546
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
5547
+ }
5520
5548
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
5521
5549
  const stdout =
5522
5550
  `Cloning into '${dirDisplayName}'...\n` +
5523
5551
  `remote: Enumerating objects: ${count}, done.\n` +
5524
5552
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
5525
5553
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
5526
- return { code: 0, stdout, stderr: '' };
5554
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
5527
5555
  } catch (err) {
5528
5556
  if (ctx.signal && ctx.signal.aborted) {
5529
5557
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -6586,7 +6614,8 @@
6586
6614
  if (ctx.vfs.existsSync(binPath)) {
6587
6615
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
6588
6616
  }
6589
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
6617
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
6618
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6590
6619
  },
6591
6620
 
6592
6621
  async bunx(args, ctx) {
@@ -6657,7 +6686,8 @@
6657
6686
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
6658
6687
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
6659
6688
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
6660
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
6689
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
6690
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
6661
6691
  }
6662
6692
 
6663
6693
  if (sub === 'dlx') {
@@ -7840,18 +7870,27 @@
7840
7870
  if (item.background) {
7841
7871
  const pid = this.nextPid++;
7842
7872
  const jobId = this.nextJobId++;
7873
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
7843
7874
  const job = {
7844
7875
  id: jobId,
7845
7876
  pid,
7846
7877
  command: trimmed,
7847
7878
  status: 'Running',
7848
- startTime: Date.now()
7879
+ startTime: Date.now(),
7880
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
7849
7881
  };
7850
7882
  this.jobs.set(jobId, job);
7851
7883
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
7852
7884
 
7853
- // Run in background promise
7854
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
7885
+ // Run in background promise with its own independent AbortSignal
7886
+ this._executeAstNode(item.node, {
7887
+ ...execOptions,
7888
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
7889
+ env: Object.assign({}, this.env, currentEnv),
7890
+ cwd: this.cwd,
7891
+ pid,
7892
+ isBackground: true
7893
+ })
7855
7894
  .then(res => {
7856
7895
  if (job.status !== 'Terminated') {
7857
7896
  job.status = 'Done';
@@ -8005,17 +8044,24 @@
8005
8044
  if (item.background) {
8006
8045
  const pid = this.nextPid++;
8007
8046
  const jobId = this.nextJobId++;
8047
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
8008
8048
  const job = {
8009
8049
  id: jobId,
8010
8050
  pid,
8011
8051
  command: 'background',
8012
8052
  status: 'Running',
8013
- startTime: Date.now()
8053
+ startTime: Date.now(),
8054
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
8014
8055
  };
8015
8056
  this.jobs.set(jobId, job);
8016
8057
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
8017
8058
 
8018
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
8059
+ this._executeAstNode(item.node, {
8060
+ ...context,
8061
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
8062
+ pid,
8063
+ isBackground: true
8064
+ })
8019
8065
  .then(res => {
8020
8066
  if (job.status !== 'Terminated') {
8021
8067
  job.status = 'Done';
@@ -8131,7 +8177,11 @@
8131
8177
  wordItems.push(...(innerCtx.positionalArgs || []));
8132
8178
  }
8133
8179
 
8180
+ let loopIter = 0;
8134
8181
  for (const val of wordItems) {
8182
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8183
+ await new Promise((r) => setTimeout(r, 0));
8184
+ }
8135
8185
  if (innerCtx.signal && innerCtx.signal.aborted) {
8136
8186
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8137
8187
  }
@@ -8176,7 +8226,11 @@
8176
8226
  let combinedStderr = '';
8177
8227
  let lastCode = 0;
8178
8228
 
8229
+ let loopIter = 0;
8179
8230
  while (true) {
8231
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
8232
+ await new Promise((r) => setTimeout(r, 0));
8233
+ }
8180
8234
  if (innerCtx.signal && innerCtx.signal.aborted) {
8181
8235
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
8182
8236
  }
@@ -8643,7 +8697,9 @@
8643
8697
 
8644
8698
  // Route any remaining unstreamed output
8645
8699
  if (res.stdout) {
8646
- if (streamedStdoutBytes > 0) {
8700
+ if (res.alreadyStreamed) {
8701
+ stdoutOut = res.stdout;
8702
+ } else if (streamedStdoutBytes > 0) {
8647
8703
  if (res.stdout.length > streamedStdoutBytes) {
8648
8704
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
8649
8705
  }