@innovatorved/code-lab 0.1.10 → 0.1.11

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/src/shell.ts CHANGED
@@ -3019,6 +3019,12 @@
3019
3019
  if (!pkgName) continue;
3020
3020
  const subpath = spec.slice(pkgName.length).replace(/^\/+/, '');
3021
3021
  const version = resolveBareVersion(vfs, rootDir, pkgName);
3022
+ if (subpath && /\.css$/i.test(subpath)) {
3023
+ const cssHref = `${CDN_ESM_BASE}/${pkgName}@${version}/${subpath.replace(/^\/+/, '')}`;
3024
+ const loader = `if(typeof document!=='undefined'){const l=document.createElement('link');l.rel='stylesheet';l.href=${JSON.stringify(cssHref)};document.head.appendChild(l);}export default ${JSON.stringify(cssHref)};`;
3025
+ imports[spec] = `data:text/javascript;charset=utf-8,${encodeURIComponent(loader)}`;
3026
+ continue;
3027
+ }
3022
3028
  imports[spec] = cdnEsmUrl(pkgName, version, subpath || undefined);
3023
3029
  }
3024
3030
  return imports;
@@ -3039,6 +3045,7 @@
3039
3045
  let match;
3040
3046
  while ((match = re.exec(text)) !== null) {
3041
3047
  const url = match[0];
3048
+ if (url.includes('${')) continue;
3042
3049
  const pkgName = decodeURIComponent(match[1]);
3043
3050
  const rest = match[2];
3044
3051
  const pinnedVersion = rest.split(/[\/?]/)[0];
@@ -3083,6 +3090,33 @@
3083
3090
  return files;
3084
3091
  }
3085
3092
 
3093
+ function collectPreviewAssetFiles(vfs, rootDir, maxFiles = 200) {
3094
+ const files = [];
3095
+ const walk = (dir, depth) => {
3096
+ if (depth > 8 || files.length >= maxFiles) return;
3097
+ let entries = [];
3098
+ try { entries = vfs.readdirSync(dir); } catch (_) { return; }
3099
+ for (const name of entries) {
3100
+ if (name === 'node_modules' || name.startsWith('.')) continue;
3101
+ const full = PosixPath.join(dir, name);
3102
+ let st;
3103
+ try { st = vfs.statSync(full); } catch (_) { continue; }
3104
+ const dirFlag = st && (typeof st.isDirectory === 'function' ? st.isDirectory() : st.isDirectory);
3105
+ if (dirFlag) {
3106
+ walk(full, depth + 1);
3107
+ } else if (/\.(?:css|json|svg)$/i.test(name) && files.length < maxFiles) {
3108
+ try {
3109
+ const content = vfs.readFileSync(full, 'utf8');
3110
+ const rel = full.startsWith(rootDir + '/') ? full.slice(rootDir.length + 1) : name;
3111
+ files.push({ full, rel, content });
3112
+ } catch (_) {}
3113
+ }
3114
+ }
3115
+ };
3116
+ walk(rootDir, 0);
3117
+ return files;
3118
+ }
3119
+
3086
3120
  function collectPreviewScripts(vfs, rootDir, maxFiles = 200) {
3087
3121
  return collectPreviewScriptFiles(vfs, rootDir, maxFiles).map((f) => f.content);
3088
3122
  }
@@ -3165,11 +3199,31 @@
3165
3199
  return out;
3166
3200
  };
3167
3201
 
3202
+ const inlineLocalCssImports = (cssText, cssDir) => {
3203
+ if (!cssText) return '';
3204
+ return cssText.replace(/@import\s+(?:url\(\s*['"]?([^'")]+)['"]?\s*\)|['"]([^'"]+)['"])\s*;?/gi, (full, u1, u2) => {
3205
+ const spec = (u1 || u2 || '').trim();
3206
+ if (!spec || /^(?:https?:|data:|\/\/)/i.test(spec)) return full;
3207
+ if (spec === 'tailwindcss') return '';
3208
+ const subTarget = resolveLocalTarget(cssDir, spec);
3209
+ if (subTarget && /\.css$/i.test(subTarget)) {
3210
+ const subCss = readText(subTarget);
3211
+ if (subCss !== null) return subCss;
3212
+ }
3213
+ return '';
3214
+ });
3215
+ };
3216
+
3168
3217
  const buildHtmlPreviewResponse = (htmlBody, htmlTargetPath) => {
3169
3218
  const scriptFiles = collectPreviewScriptFiles(ctx.vfs, rootDir);
3219
+ const assetFiles = collectPreviewAssetFiles(ctx.vfs, rootDir);
3170
3220
  const specifiers = new Set();
3221
+ const compiledScripts = [];
3171
3222
  for (const f of scriptFiles) {
3172
3223
  for (const s of extractBareSpecifiers(f.content)) specifiers.add(s);
3224
+ const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3225
+ for (const s of extractBareSpecifiers(compiled)) specifiers.add(s);
3226
+ compiledScripts.push({ file: f, compiled });
3173
3227
  }
3174
3228
  // Also scan inline module scripts in HTML for bare specifiers
3175
3229
  const inlineScriptRe = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
@@ -3183,14 +3237,53 @@
3183
3237
  const importMap = buildPreviewImportMap(ctx.vfs, rootDir, specifiers);
3184
3238
  for (const f of scriptFiles) aliasPinnedCdnUrls(ctx.vfs, rootDir, f.content, importMap);
3185
3239
  aliasPinnedCdnUrls(ctx.vfs, rootDir, htmlBody, importMap);
3186
- for (const f of scriptFiles) {
3187
- const compiled = transpileAndRewriteLocalImports(f.content, f.full);
3188
- const key = toLocalImportKey(f.full);
3240
+ for (const { file, compiled } of compiledScripts) {
3241
+ const key = toLocalImportKey(file.full);
3189
3242
  importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(compiled)}`;
3190
3243
  }
3191
3244
 
3245
+ let needsTailwindBrowser = false;
3246
+ for (const af of assetFiles) {
3247
+ const key = toLocalImportKey(af.full);
3248
+ if (/\.css$/i.test(af.full)) {
3249
+ if (/@import\s+['"]tailwindcss['"]/i.test(af.content)) {
3250
+ needsTailwindBrowser = true;
3251
+ }
3252
+ const resolvedCss = inlineLocalCssImports(af.content, PosixPath.dirname(af.full));
3253
+ const cssModuleJs = `const __css=${JSON.stringify(resolvedCss)};if(typeof document!=='undefined'){const __s=document.createElement('style');__s.setAttribute('data-codelab-css',${JSON.stringify(af.rel)});__s.textContent=__css;document.head.appendChild(__s);}export default __css;`;
3254
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(cssModuleJs)}`;
3255
+ } else if (/\.json$/i.test(af.full)) {
3256
+ const jsonModuleJs = `export default ${af.content.trim() || 'null'};`;
3257
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(jsonModuleJs)}`;
3258
+ } else if (/\.svg$/i.test(af.full)) {
3259
+ const svgDataUrl = `data:image/svg+xml;utf8,${encodeURIComponent(af.content)}`;
3260
+ const svgModuleJs = `export default ${JSON.stringify(svgDataUrl)};`;
3261
+ importMap[key] = `data:text/javascript;charset=utf-8,${encodeURIComponent(svgModuleJs)}`;
3262
+ }
3263
+ }
3264
+
3192
3265
  const htmlDir = PosixPath.dirname(htmlTargetPath);
3193
- let transformedHtml = htmlBody;
3266
+ let transformedHtml = htmlBody.replace(/%PUBLIC_URL%\//g, '/').replace(/%PUBLIC_URL%/g, '');
3267
+
3268
+ // Auto-inject entry script for Create React App / bundler templates where index.html omits <script src="...">
3269
+ const hasLocalScriptTag = /<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/i.test(transformedHtml);
3270
+ if (!hasLocalScriptTag) {
3271
+ const defaultEntries = [
3272
+ '/src/main.tsx', '/src/main.jsx', '/src/main.ts', '/src/main.js',
3273
+ '/src/index.tsx', '/src/index.jsx', '/src/index.ts', '/src/index.js'
3274
+ ];
3275
+ for (const cand of defaultEntries) {
3276
+ if (isFile(PosixPath.join(rootDir, cand.slice(1)))) {
3277
+ const entryTag = `<script type="module" src="${cand}"></script>`;
3278
+ if (/<\/body>/i.test(transformedHtml)) {
3279
+ transformedHtml = transformedHtml.replace(/<\/body>/i, ` ${entryTag}\n</body>`);
3280
+ } else {
3281
+ transformedHtml += `\n${entryTag}`;
3282
+ }
3283
+ break;
3284
+ }
3285
+ }
3286
+ }
3194
3287
 
3195
3288
  // Inline local <link rel="stylesheet" href="..."> so styles work in opaque-origin / srcdoc frames
3196
3289
  transformedHtml = transformedHtml.replace(/<link\b([^>]*?)>/gi, (fullTag, attrs) => {
@@ -3201,7 +3294,11 @@
3201
3294
  if (!cssTarget || !/\.css$/i.test(cssTarget)) return fullTag;
3202
3295
  const cssContent = readText(cssTarget);
3203
3296
  if (cssContent === null) return fullTag;
3204
- return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${cssContent}\n</style>`;
3297
+ if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
3298
+ needsTailwindBrowser = true;
3299
+ }
3300
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
3301
+ return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
3205
3302
  });
3206
3303
 
3207
3304
  // Inline local <script ... src="..."></script> so entry modules & scripts execute reliably in opaque-origin / srcdoc frames
@@ -3213,11 +3310,20 @@
3213
3310
  const rawScript = readText(scriptTarget);
3214
3311
  if (rawScript === null) return fullTag;
3215
3312
  const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
3216
- const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget);
3313
+ const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
3217
3314
  const typeAttr = isMod ? ' type="module"' : '';
3218
3315
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
3219
3316
  });
3220
3317
 
3318
+ if (needsTailwindBrowser && !transformedHtml.includes('@tailwindcss/browser')) {
3319
+ const twTag = '<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>';
3320
+ if (/<head[^>]*>/i.test(transformedHtml)) {
3321
+ transformedHtml = transformedHtml.replace(/<head[^>]*>/i, (m) => `${m}\n ${twTag}`);
3322
+ } else {
3323
+ transformedHtml = twTag + '\n' + transformedHtml;
3324
+ }
3325
+ }
3326
+
3221
3327
  return injectPreviewExtras(transformedHtml, importMap);
3222
3328
  };
3223
3329
 
@@ -3229,7 +3335,9 @@
3229
3335
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
3230
3336
 
3231
3337
  if (!rel || pathname.endsWith('/') || isDir(target)) {
3232
- target = PosixPath.join(target, 'index.html');
3338
+ const rootIdx = PosixPath.join(target, 'index.html');
3339
+ const pubIdx = PosixPath.join(target, 'public', 'index.html');
3340
+ target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx;
3233
3341
  }
3234
3342
  if (!exists(target) && !hasExt) {
3235
3343
  // Resolve extensionless module specifiers (e.g. `./components/Counter`)
@@ -3243,7 +3351,9 @@
3243
3351
  for (const c of cands) { if (exists(c)) { target = c; break; } }
3244
3352
  }
3245
3353
  if (!exists(target) && !hasExt) {
3246
- target = PosixPath.join(rootDir, 'index.html'); // SPA fallback
3354
+ const rootIdx = PosixPath.join(rootDir, 'index.html');
3355
+ const pubIdx = PosixPath.join(rootDir, 'public', 'index.html');
3356
+ target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
3247
3357
  }
3248
3358
  if (!exists(target)) {
3249
3359
  return new Response(
package/src/workbench.ts CHANGED
@@ -1988,7 +1988,12 @@ declare module 'bun:sqlite' {
1988
1988
  const found = names.find(f => pattern.test(f));
1989
1989
  if (found) return found;
1990
1990
  if (kind === 'demo') {
1991
- return names.find(f => /\.(js|ts)$/i.test(f) && !/(^|\/)test\.(js|ts)$/i.test(f)) || null;
1991
+ const isConfigOrTest = f => /(^|\/)(test|.*\.(?:test|spec|config|d))\.(js|ts|mjs|cjs)$/i.test(f) || /(^|\/)\.[^/]+$/i.test(f);
1992
+ const hasHtmlEntry = Boolean(this.files['index.html'] || this.files['public/index.html']);
1993
+ if (hasHtmlEntry) {
1994
+ return names.find(f => /(^|\/)(server|app|demo)\.(js|ts)$/i.test(f) && !/^src\//i.test(f)) || null;
1995
+ }
1996
+ return names.find(f => /\.(js|ts)$/i.test(f) && !isConfigOrTest(f)) || null;
1992
1997
  }
1993
1998
  return null;
1994
1999
  }
@@ -4721,8 +4726,10 @@ declare module 'bun:sqlite' {
4721
4726
  return null;
4722
4727
  }
4723
4728
 
4724
- const rootDir = (this.files['public/index.html']) ? '/workspace/public'
4725
- : (this.files['site/index.html']) ? '/workspace/site'
4729
+ const hasSrcScripts = Boolean(this.files && Object.keys(this.files).some((f) => /^src\/.+\.(?:[cm]?jsx?|tsx?)$/i.test(f)));
4730
+ const rootDir = this.files['index.html'] ? '/workspace'
4731
+ : (this.files['public/index.html'] && !hasSrcScripts) ? '/workspace/public'
4732
+ : this.files['site/index.html'] ? '/workspace/site'
4726
4733
  : '/workspace';
4727
4734
 
4728
4735
  if (!this.shell || typeof this.shell.execute !== 'function') return null;
@@ -7210,6 +7217,9 @@ declare module 'bun:sqlite' {
7210
7217
  if (this.isRunning) return;
7211
7218
  const entry = this._findEntryFile('demo');
7212
7219
  if (!entry) {
7220
+ if ((this.files['index.html'] || this.files['public/index.html']) && typeof this.previewApp === 'function') {
7221
+ return this.previewApp();
7222
+ }
7213
7223
  this.terminalLogs.push({ type: 'stderr', text: 'No demo.js / demo.ts file found in this workspace.' });
7214
7224
  this.drawerTab = 'terminal';
7215
7225
  this._renderDrawerBody();
@@ -8085,7 +8095,7 @@ declare module 'bun:sqlite' {
8085
8095
  Enter any public GitHub repository URL or <code>owner/repo</code> slug. Files will be cloned directly into the in-memory Virtual Filesystem (VFS) with zero authentication required.
8086
8096
  </p>
8087
8097
  <div style="display:flex;gap:8px;">
8088
- <input id="cl-clone-repo-input" type="text" placeholder="e.g. innovatorved/code-lab or https://github.com/owner/repo" style="flex:1;height:34px;padding:0 10px;background:var(--cl-bg);border:1px solid var(--cl-border-strong);border-radius:var(--cl-radius-sm);color:var(--cl-fg);font-family:var(--cl-font-mono);font-size:12px;outline:none;" />
8098
+ <input id="cl-clone-repo-input" type="text" placeholder="e.g. mdn/todo-react or https://github.com/owner/repo" style="flex:1;height:34px;padding:0 10px;background:var(--cl-bg);border:1px solid var(--cl-border-strong);border-radius:var(--cl-radius-sm);color:var(--cl-fg);font-family:var(--cl-font-mono);font-size:12px;outline:none;" />
8089
8099
  <button type="button" class="codelab-btn codelab-btn--primary" data-cl-action="confirm-clone-repo">Clone Repo</button>
8090
8100
  </div>
8091
8101
  </div>