@sixb/app 0.1.3 → 0.1.5

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/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { pathToFileURL as pathToFileURL2 } from "url";
8
8
  // src/build.ts
9
9
  import { existsSync } from "fs";
10
10
  import { copyFile, mkdir, readFile, rm, writeFile } from "fs/promises";
11
- import { basename, dirname, extname, join, resolve } from "path";
11
+ import { basename, dirname, join, resolve } from "path";
12
12
  import { promisify } from "util";
13
13
  import {
14
14
  brotliCompress as brotliCompressCallback,
@@ -145,9 +145,7 @@ function withLoadingShell(html) {
145
145
  var extensionlessSourceImportPlugin = {
146
146
  name: "sixb-extensionless-source-imports",
147
147
  setup(build) {
148
- build.onResolve({ filter: /^\.\.?\// }, (args) => {
149
- if (extname(args.path))
150
- return;
148
+ build.onResolve({ filter: /^\.\.?\/(?:.*\/)?[^/.]+$/ }, (args) => {
151
149
  const base = resolve(dirname(args.importer), args.path);
152
150
  for (const candidate of [
153
151
  `${base}.ts`,
@@ -189,7 +187,7 @@ async function precompressBuildAssets(outputs) {
189
187
 
190
188
  // src/codegen.ts
191
189
  import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
192
- import { join as join3, relative, resolve as resolve2 } from "path";
190
+ import { join as join4, relative as relative2, resolve as resolve2 } from "path";
193
191
 
194
192
  // src/manifest.ts
195
193
  function renderAppManifest(metadata) {
@@ -212,7 +210,7 @@ function renderAppManifest(metadata) {
212
210
  import { createHash } from "crypto";
213
211
  import { readFile as readFile2, stat } from "fs/promises";
214
212
  import { createRequire } from "module";
215
- import { extname as extname2, join as join2 } from "path";
213
+ import { extname, join as join2 } from "path";
216
214
  import { pathToFileURL } from "url";
217
215
  var metadataRequire = createRequire(import.meta.url);
218
216
  var metadataFields = [
@@ -321,7 +319,7 @@ function inferImageMimeType(url) {
321
319
  try {
322
320
  pathname = new URL(url, "https://sixb.invalid").pathname;
323
321
  } catch {}
324
- switch (extname2(pathname).toLowerCase()) {
322
+ switch (extname(pathname).toLowerCase()) {
325
323
  case ".svg":
326
324
  return "image/svg+xml";
327
325
  case ".png":
@@ -353,16 +351,149 @@ function renderCustomAppRuntimeScript(config) {
353
351
  return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
354
352
  }
355
353
 
354
+ // src/scanner.ts
355
+ import { readdir } from "fs/promises";
356
+ import { join as join3, relative } from "path";
357
+ var dynamicSegmentPattern = /^\[([\w-]+)\]$/;
358
+ var reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb"];
359
+ var reservedRoutePaths = new Set(["/app.webmanifest"]);
360
+ async function scanAppRoutes(appDir) {
361
+ const pages = [];
362
+ const layouts = [];
363
+ await walkDir(appDir, appDir, pages, layouts);
364
+ pages.sort(compareRouteModules);
365
+ layouts.sort(compareRouteModules);
366
+ return { pages, layouts };
367
+ }
368
+ function routePatternKey(path) {
369
+ if (path === "/")
370
+ return "/";
371
+ const segments = routeSegments(path).map((segment) => segment.startsWith(":") ? ":" : segment.toLowerCase());
372
+ return `/${segments.join("/")}`;
373
+ }
374
+ async function walkDir(dir, appDir, pages, layouts) {
375
+ const entries = await readDirectory(dir);
376
+ if (!entries)
377
+ return;
378
+ const visibleEntries = entries.filter((entry) => !String(entry.name).startsWith("_")).sort((a, b) => compareText(String(a.name), String(b.name)));
379
+ const relativeDir = normalizeRelativePath(relative(appDir, dir));
380
+ validateChildDirectories(visibleEntries, relativeDir);
381
+ const pageEntries = visibleEntries.filter((entry) => entry.isFile() && (entry.name === "page.tsx" || entry.name === "page.ts"));
382
+ if (pageEntries.length > 1) {
383
+ const modules = pageEntries.map((entry) => displayAppPath(join3(relativeDir, entry.name)));
384
+ throw new Error(`[SixbCustomApp] Conflicting page modules for route '${directoryRoutePath(relativeDir)}': ${modules.join(" and ")}. Keep exactly one of page.tsx or page.ts.`);
385
+ }
386
+ const pageEntry = pageEntries[0];
387
+ if (pageEntry) {
388
+ const relativePath = normalizeRelativePath(join3(relativeDir, pageEntry.name));
389
+ const path = directoryRoutePath(relativeDir);
390
+ assertRouteIsAvailable(path, relativePath);
391
+ pages.push({ path, filePath: join3(dir, pageEntry.name), relativePath });
392
+ }
393
+ if (relativeDir) {
394
+ const layoutEntry = visibleEntries.find((entry) => entry.isFile() && entry.name === "layout.tsx");
395
+ if (layoutEntry) {
396
+ layouts.push({
397
+ path: directoryRoutePath(relativeDir),
398
+ filePath: join3(dir, layoutEntry.name),
399
+ relativePath: normalizeRelativePath(join3(relativeDir, layoutEntry.name))
400
+ });
401
+ }
402
+ }
403
+ for (const entry of visibleEntries) {
404
+ if (!entry.isDirectory())
405
+ continue;
406
+ if (!relativeDir && entry.name === "public")
407
+ continue;
408
+ await walkDir(join3(dir, entry.name), appDir, pages, layouts);
409
+ }
410
+ }
411
+ async function readDirectory(dir) {
412
+ try {
413
+ return await readdir(dir, { withFileTypes: true });
414
+ } catch (error) {
415
+ if (isNotFoundError(error))
416
+ return null;
417
+ throw error;
418
+ }
419
+ }
420
+ function validateChildDirectories(entries, relativeDir) {
421
+ const claimedSegments = new Map;
422
+ for (const entry of entries) {
423
+ if (!entry.isDirectory())
424
+ continue;
425
+ const segment = routeSegment(entry.name, join3(relativeDir, entry.name));
426
+ const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
427
+ const existing = claimedSegments.get(key);
428
+ if (existing && existing !== entry.name) {
429
+ const parent = relativeDir ? displayAppPath(relativeDir) : "app/";
430
+ throw new Error(`[SixbCustomApp] Ambiguous route directories '${existing}' and '${entry.name}' under ${parent}. They match the same URL segment.`);
431
+ }
432
+ claimedSegments.set(key, entry.name);
433
+ }
434
+ }
435
+ function directoryRoutePath(relativeDir) {
436
+ if (!relativeDir)
437
+ return "/";
438
+ return `/${relativeDir.split("/").map((segment) => routeSegment(segment, relativeDir)).join("/")}`;
439
+ }
440
+ function routeSegment(segment, relativePath) {
441
+ const dynamic = dynamicSegmentPattern.exec(segment);
442
+ if (dynamic)
443
+ return `:${dynamic[1]}`;
444
+ if (segment.includes("[") || segment.includes("]")) {
445
+ throw new Error(`[SixbCustomApp] Invalid dynamic route directory ${displayAppPath(relativePath)}. Use one name such as '[id]'; catch-all and partial dynamic segments are not supported.`);
446
+ }
447
+ if (segment.includes("(") || segment.includes(")")) {
448
+ throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Route groups are not supported yet; use a normal directory name.`);
449
+ }
450
+ if (/[:*?]/.test(segment)) {
451
+ throw new Error(`[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Use '[name]' for a dynamic segment; ':', '*' and '?' are reserved by React Router.`);
452
+ }
453
+ return segment;
454
+ }
455
+ function assertRouteIsAvailable(path, relativePath) {
456
+ const normalizedPath = path.toLowerCase();
457
+ const reserved = reservedRoutePaths.has(normalizedPath) || reservedRoutePrefixes.some((prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`));
458
+ if (!reserved)
459
+ return;
460
+ throw new Error(`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, and /app.webmanifest.`);
461
+ }
462
+ function routeSegments(path) {
463
+ return path === "/" ? [] : path.replace(/^\/+|\/+$/g, "").split("/");
464
+ }
465
+ function normalizeRelativePath(path) {
466
+ return path.split("\\").join("/").replace(/^\.\/$/, "");
467
+ }
468
+ function displayAppPath(path) {
469
+ const normalized = normalizeRelativePath(path);
470
+ return normalized ? `app/${normalized}` : "app/";
471
+ }
472
+ function compareRouteModules(a, b) {
473
+ return compareText(a.path, b.path) || compareText(a.relativePath, b.relativePath);
474
+ }
475
+ function compareText(a, b) {
476
+ return a < b ? -1 : a > b ? 1 : 0;
477
+ }
478
+ function isNotFoundError(error) {
479
+ if (!(error instanceof Error))
480
+ return false;
481
+ const code = error.code;
482
+ return code === "ENOENT" || code === "ENOTDIR";
483
+ }
484
+
356
485
  // src/codegen.ts
357
486
  var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
358
487
  async function generateRouteManifest(routes, generatedDir, options = {}) {
359
488
  await mkdir2(generatedDir, { recursive: true });
360
- const imports = routes.map((route, index) => {
489
+ const pages = [...routes].sort(compareRouteModules2);
490
+ const pageImports = pages.map((route, index) => {
361
491
  const rel = relativeTo(generatedDir, route.filePath);
362
492
  return `import Page${index} from ${JSON.stringify(rel)}`;
363
493
  }).join(`
364
494
  `);
365
- const builtInRoutes = options.builtInRoutes ?? [];
495
+ const projectRoutePatterns = new Set(pages.map((route) => routePatternKey(route.path)));
496
+ const builtInRoutes = (options.builtInRoutes ?? []).filter((route) => !projectRoutePatterns.has(routePatternKey(route.path)));
366
497
  const builtInImports = builtInRoutes.map((route, index) => {
367
498
  if (route.exportName) {
368
499
  return `import { ${route.exportName} as BuiltInPage${index} } from ${JSON.stringify(route.moduleSpecifier)}`;
@@ -370,34 +501,167 @@ async function generateRouteManifest(routes, generatedDir, options = {}) {
370
501
  return `import BuiltInPage${index} from ${JSON.stringify(route.moduleSpecifier)}`;
371
502
  }).join(`
372
503
  `);
373
- const entries = routes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: Page${index} },`).join(`
374
- `);
375
- const builtInEntries = builtInRoutes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: BuiltInPage${index} },`).join(`
376
- `);
377
- const routeEntries = [entries, builtInEntries].filter(Boolean).join(`
504
+ const routePatterns = [...pages, ...builtInRoutes].map((route) => routePatternKey(route.path));
505
+ const layouts = [...options.layouts ?? []].filter((layout) => {
506
+ const layoutPattern = routePatternKey(layout.path);
507
+ return routePatterns.some((routePattern) => routePattern === layoutPattern || routePattern.startsWith(`${layoutPattern}/`));
508
+ }).sort(compareRouteModules2);
509
+ const layoutImports = layouts.map((layout, index) => {
510
+ const rel = relativeTo(generatedDir, layout.filePath);
511
+ return `import Layout${index} from ${JSON.stringify(rel)}`;
512
+ }).join(`
378
513
  `);
379
- const importEntries = [imports, builtInImports].filter(Boolean).join(`
514
+ const tree = createRouteTree();
515
+ for (const [index, layout] of layouts.entries()) {
516
+ insertRouteLayout(tree, layout, `Layout${index}`);
517
+ }
518
+ for (const [index, route] of pages.entries()) {
519
+ insertRoutePage(tree, route.path, `Page${index}`, route.relativePath);
520
+ }
521
+ for (const [index, route] of builtInRoutes.entries()) {
522
+ insertRoutePage(tree, route.path, `BuiltInPage${index}`, `${route.moduleSpecifier} (${route.path})`);
523
+ }
524
+ const importEntries = [
525
+ 'import { createElement } from "react"',
526
+ layouts.length > 0 ? 'import { Outlet, type RouteObject } from "react-router-dom"' : 'import type { RouteObject } from "react-router-dom"',
527
+ pageImports,
528
+ builtInImports,
529
+ layoutImports
530
+ ].filter(Boolean).join(`
380
531
  `);
532
+ const routePaths = [
533
+ ...pages.map((route) => route.path),
534
+ ...builtInRoutes.map((route) => route.path)
535
+ ];
381
536
  const content = `${importEntries}
382
537
 
538
+ export const routePaths = ${JSON.stringify(routePaths, null, 2)} as const
539
+
383
540
  export const routes = [
384
- ${routeEntries}
385
- ]
541
+ ${renderRootRouteObjects(tree)}
542
+ ] satisfies RouteObject[]
386
543
  `;
387
- const outPath = join3(generatedDir, "routes.ts");
544
+ const outPath = join4(generatedDir, "routes.ts");
388
545
  await writeFileIfChanged(outPath, content);
389
546
  return outPath;
390
547
  }
548
+ function createRouteTree(segment = "") {
549
+ return { segment, children: new Map };
550
+ }
551
+ function insertRouteLayout(root, layout, componentName) {
552
+ if (layout.path === "/") {
553
+ throw new Error(`[SixbCustomApp] Root layout ${layout.relativePath} must remain the global app wrapper.`);
554
+ }
555
+ const node = resolveRouteNode(root, layout.path, layout.relativePath);
556
+ if (node.layout) {
557
+ throw new Error(`[SixbCustomApp] Conflicting layouts '${node.layout.source}' and '${layout.relativePath}' own route '${layout.path}'.`);
558
+ }
559
+ node.layout = { componentName, source: layout.relativePath };
560
+ }
561
+ function insertRoutePage(root, path, componentName, source) {
562
+ const node = resolveRouteNode(root, path, source);
563
+ if (node.page) {
564
+ throw new Error(`[SixbCustomApp] Conflicting pages '${node.page.source}' and '${source}' match route '${path}'.`);
565
+ }
566
+ node.page = { componentName, source };
567
+ }
568
+ function resolveRouteNode(root, path, source) {
569
+ let node = root;
570
+ for (const segment of splitRoutePath(path)) {
571
+ const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
572
+ const existing = node.children.get(key);
573
+ if (existing) {
574
+ if (existing.segment.startsWith(":") && segment.startsWith(":") && existing.segment !== segment) {
575
+ throw new Error(`[SixbCustomApp] Route '${source}' uses dynamic segment '${segment}', but '${existing.segment}' already owns the same route position. Use one parameter name consistently.`);
576
+ }
577
+ node = existing;
578
+ continue;
579
+ }
580
+ const child = createRouteTree(segment);
581
+ node.children.set(key, child);
582
+ node = child;
583
+ }
584
+ return node;
585
+ }
586
+ function renderRootRouteObjects(root) {
587
+ const lines = [];
588
+ if (root.page) {
589
+ lines.push(` { path: "/", element: createElement(${root.page.componentName}) },`);
590
+ }
591
+ for (const child of sortedRenderableChildren(root)) {
592
+ lines.push(...renderRouteNode(child, 1));
593
+ }
594
+ return lines.join(`
595
+ `);
596
+ }
597
+ function renderRouteNode(node, depth) {
598
+ const indent = " ".repeat(depth);
599
+ const children = sortedRenderableChildren(node);
600
+ if (!node.layout && node.page && children.length === 0) {
601
+ return [
602
+ `${indent}{ path: ${JSON.stringify(node.segment)}, element: createElement(${node.page.componentName}) },`
603
+ ];
604
+ }
605
+ const lines = [`${indent}{`, `${indent} path: ${JSON.stringify(node.segment)},`];
606
+ if (node.layout) {
607
+ lines.push(`${indent} element: createElement(${node.layout.componentName}, { children: createElement(Outlet) }),`);
608
+ }
609
+ lines.push(`${indent} children: [`);
610
+ if (node.page) {
611
+ lines.push(`${indent} { index: true, element: createElement(${node.page.componentName}) },`);
612
+ }
613
+ for (const child of children) {
614
+ lines.push(...renderRouteNode(child, depth + 2));
615
+ }
616
+ lines.push(`${indent} ],`, `${indent}},`);
617
+ return lines;
618
+ }
619
+ function sortedRenderableChildren(node) {
620
+ return [...node.children.values()].filter(hasPageDescendant).sort((a, b) => {
621
+ const aDynamic = a.segment.startsWith(":");
622
+ const bDynamic = b.segment.startsWith(":");
623
+ if (aDynamic !== bDynamic)
624
+ return aDynamic ? 1 : -1;
625
+ return compareText2(a.segment, b.segment);
626
+ });
627
+ }
628
+ function hasPageDescendant(node) {
629
+ if (node.page)
630
+ return true;
631
+ for (const child of node.children.values()) {
632
+ if (hasPageDescendant(child))
633
+ return true;
634
+ }
635
+ return false;
636
+ }
637
+ function splitRoutePath(path) {
638
+ if (path === "/")
639
+ return [];
640
+ if (!path.startsWith("/")) {
641
+ throw new Error(`[SixbCustomApp] Route path '${path}' must start with '/'.`);
642
+ }
643
+ const segments = path.slice(1).split("/");
644
+ if (segments.some((segment) => !segment)) {
645
+ throw new Error(`[SixbCustomApp] Route path '${path}' contains an empty segment.`);
646
+ }
647
+ return segments;
648
+ }
649
+ function compareRouteModules2(a, b) {
650
+ return compareText2(a.path, b.path) || compareText2(a.relativePath, b.relativePath);
651
+ }
652
+ function compareText2(a, b) {
653
+ return a < b ? -1 : a > b ? 1 : 0;
654
+ }
391
655
  async function generateAuthExperienceEntry(projectRoot, generatedDir, options = {}) {
392
656
  await mkdir2(generatedDir, { recursive: true });
393
- const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join3(projectRoot, "app");
394
- const authPath = join3(appDir, "auth.tsx");
657
+ const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
658
+ const authPath = join4(appDir, "auth.tsx");
395
659
  if (!await fileExists2(authPath)) {
396
660
  return null;
397
661
  }
398
- const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join3(appDir, "public");
399
- const layoutPath = join3(appDir, "layout.tsx");
400
- const globalsCssPath = join3(appDir, "globals.css");
662
+ const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
663
+ const layoutPath = join4(appDir, "layout.tsx");
664
+ const globalsCssPath = join4(appDir, "globals.css");
401
665
  const metadata = await resolveAppMetadata({ layoutPath, publicDir });
402
666
  const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
403
667
  const stylesheetImport = stylesheetPath ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}` : "";
@@ -477,7 +741,7 @@ function decodeBootstrap(value: string): AuthExperienceBootstrap {
477
741
 
478
742
  createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
479
743
  `;
480
- const mainPath = join3(generatedDir, "auth-main.tsx");
744
+ const mainPath = join4(generatedDir, "auth-main.tsx");
481
745
  await writeFileIfChanged(mainPath, mainContent);
482
746
  const htmlContent = `<!DOCTYPE html>
483
747
  <html lang="en">
@@ -497,18 +761,18 @@ ${renderAuthMetadataHead(metadata)}
497
761
  </body>
498
762
  </html>
499
763
  `;
500
- const htmlPath = join3(generatedDir, "auth-index.html");
764
+ const htmlPath = join4(generatedDir, "auth-index.html");
501
765
  await writeFileIfChanged(htmlPath, htmlContent);
502
766
  return { htmlPath, mainPath };
503
767
  }
504
768
  async function generateAppEntry(projectRoot, generatedDir, options = {}) {
505
769
  await mkdir2(generatedDir, { recursive: true });
506
- const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join3(projectRoot, "app");
507
- const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join3(appDir, "public");
508
- const globalsCssPath = join3(appDir, "globals.css");
509
- const layoutPath = join3(appDir, "layout.tsx");
770
+ const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
771
+ const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join4(appDir, "public");
772
+ const globalsCssPath = join4(appDir, "globals.css");
773
+ const layoutPath = join4(appDir, "layout.tsx");
510
774
  const metadata = await resolveAppMetadata({ layoutPath, publicDir });
511
- const manifestPath = join3(generatedDir, "app.webmanifest");
775
+ const manifestPath = join4(generatedDir, "app.webmanifest");
512
776
  await writeFileIfChanged(manifestPath, renderAppManifest(metadata));
513
777
  const layoutRel = relativeTo(generatedDir, layoutPath);
514
778
  const hasLayout = await fileExists2(layoutPath);
@@ -530,7 +794,13 @@ async function generateAppEntry(projectRoot, generatedDir, options = {}) {
530
794
  const mainContent = `import React from "react"
531
795
  import { createRoot, type Root } from "react-dom/client"
532
796
  import { signOut } from "@sixb/client"
533
- import { BrowserRouter, Routes, Route, matchPath, useNavigate, useLocation } from "react-router-dom"
797
+ import {
798
+ BrowserRouter,
799
+ matchPath,
800
+ useLocation,
801
+ useNavigate,
802
+ useRoutes,
803
+ } from "react-router-dom"
534
804
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
535
805
  import {
536
806
  configureSixbBrowserClient,
@@ -538,7 +808,7 @@ import {
538
808
  readSixbBrowserRuntimeConfig,
539
809
  requireSixbBrowserAuthSession,
540
810
  } from "@sixb/client/browser"
541
- import { routes } from "./routes"
811
+ import { routePaths, routes } from "./routes"
542
812
  ${globalsCssImport}
543
813
  ${layoutImport}
544
814
 
@@ -638,7 +908,7 @@ function InternalLinkInterceptor() {
638
908
  if (isReservedPath(url.pathname)) return
639
909
  // Only intercept destinations the app actually routes; anything else may
640
910
  // be a real server resource and keeps native navigation.
641
- if (!routes.some((route) => matchPath(route.path, url.pathname))) return
911
+ if (!routePaths.some((path) => matchPath(path, url.pathname))) return
642
912
  // Same-document hash links keep native scroll behavior.
643
913
  if (
644
914
  url.hash &&
@@ -842,6 +1112,12 @@ function RoutedErrorBoundary({ children }: { children: React.ReactNode }) {
842
1112
  )
843
1113
  }
844
1114
 
1115
+ const appRoutes = [...routes, { path: "*", element: <NotFoundView /> }]
1116
+
1117
+ function AppRoutes() {
1118
+ return useRoutes(appRoutes)
1119
+ }
1120
+
845
1121
  function App() {
846
1122
  return (
847
1123
  <QueryClientProvider client={queryClient}>
@@ -849,12 +1125,7 @@ function App() {
849
1125
  <InternalLinkInterceptor />
850
1126
  <RoutedErrorBoundary>
851
1127
  ${layoutWrapperStart}
852
- <Routes>
853
- {routes.map((route) => (
854
- <Route key={route.path} path={route.path} element={<route.component />} />
855
- ))}
856
- <Route path="*" element={<NotFoundView />} />
857
- </Routes>
1128
+ <AppRoutes />
858
1129
  ${layoutWrapperEnd}
859
1130
  </RoutedErrorBoundary>
860
1131
  </BrowserRouter>
@@ -868,7 +1139,7 @@ if (canRenderApp) {
868
1139
  getRoot().render(<AccessDeniedView />)
869
1140
  }
870
1141
  `;
871
- const mainPath = join3(generatedDir, "main.tsx");
1142
+ const mainPath = join4(generatedDir, "main.tsx");
872
1143
  await writeFileIfChanged(mainPath, mainContent);
873
1144
  const metadataHead = renderMetadataHead(metadata);
874
1145
  const htmlContent = `<!DOCTYPE html>
@@ -907,7 +1178,7 @@ ${metadataHead}
907
1178
  </body>
908
1179
  </html>
909
1180
  `;
910
- const htmlPath = join3(generatedDir, "index.html");
1181
+ const htmlPath = join4(generatedDir, "index.html");
911
1182
  await writeFileIfChanged(htmlPath, htmlContent);
912
1183
  return { htmlPath, mainPath, manifestPath };
913
1184
  }
@@ -955,7 +1226,7 @@ function isFileNotFoundError(error) {
955
1226
  return error instanceof Error && "code" in error && error.code === "ENOENT";
956
1227
  }
957
1228
  function relativeTo(from, to) {
958
- let rel = relative(from, to);
1229
+ let rel = relative2(from, to);
959
1230
  if (!rel.startsWith("."))
960
1231
  rel = `./${rel}`;
961
1232
  return rel;
@@ -969,57 +1240,6 @@ async function fileExists2(path) {
969
1240
  }
970
1241
  }
971
1242
 
972
- // src/scanner.ts
973
- import { readdir } from "fs/promises";
974
- import { join as join4, relative as relative2 } from "path";
975
- async function scanPages(appDir) {
976
- const routes = [];
977
- await walkDir(appDir, appDir, routes);
978
- routes.sort((a, b) => a.path.localeCompare(b.path));
979
- return routes;
980
- }
981
- async function walkDir(dir, appDir, routes) {
982
- let entries;
983
- try {
984
- entries = await readdir(dir, { withFileTypes: true });
985
- } catch {
986
- return;
987
- }
988
- for (const entry of entries) {
989
- const name = String(entry.name);
990
- if (name.startsWith("_"))
991
- continue;
992
- const fullPath = join4(dir, name);
993
- if (entry.isDirectory()) {
994
- await walkDir(fullPath, appDir, routes);
995
- continue;
996
- }
997
- if (!entry.isFile())
998
- continue;
999
- const isPageModule = name === "page.tsx" || name === "page.ts";
1000
- if (!isPageModule)
1001
- continue;
1002
- const relativePath = relative2(appDir, fullPath);
1003
- const routePath = filePathToRoutePath(relativePath);
1004
- routes.push({
1005
- path: routePath,
1006
- filePath: fullPath,
1007
- relativePath
1008
- });
1009
- }
1010
- }
1011
- function filePathToRoutePath(filePath) {
1012
- let route = filePath.replace(/\.(tsx|ts)$/, "");
1013
- route = route.split("\\").join("/");
1014
- route = route.replace(/\[([^\]]+)\]/g, ":$1");
1015
- if (route === "page")
1016
- return "/";
1017
- route = route.replace(/\/page$/, "");
1018
- if (!route.startsWith("/"))
1019
- route = `/${route}`;
1020
- return route;
1021
- }
1022
-
1023
1243
  // src/styles.ts
1024
1244
  import { readFile as readFile4 } from "fs/promises";
1025
1245
  import { join as join6 } from "path";
@@ -1174,10 +1394,7 @@ async function createCustomApp(options) {
1174
1394
  const authEnabled = options.authEnabled ?? true;
1175
1395
  const agentRoutesEnabled = options.agentRoutes ?? true;
1176
1396
  async function scanRoutes() {
1177
- if (!await pathExists(appDir)) {
1178
- return [];
1179
- }
1180
- return await scanPages(appDir);
1397
+ return [...(await scanAppRoutes(appDir)).pages];
1181
1398
  }
1182
1399
  let tailwindCompiler = null;
1183
1400
  let tailwindCompilerKey = null;
@@ -1266,13 +1483,17 @@ async function createCustomApp(options) {
1266
1483
  return outputPath;
1267
1484
  }
1268
1485
  async function prepareGeneratedApp() {
1269
- const routes = await scanRoutes();
1486
+ const discovery = await scanAppRoutes(appDir);
1487
+ const routes = [...discovery.pages];
1270
1488
  if (routes.length === 0) {
1271
1489
  throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`);
1272
1490
  }
1273
1491
  const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : [];
1274
1492
  const stylesheets = await prepareStylesheets(builtInRoutes);
1275
- await generateRouteManifest(routes, generatedDir, { builtInRoutes });
1493
+ await generateRouteManifest(routes, generatedDir, {
1494
+ builtInRoutes,
1495
+ layouts: discovery.layouts
1496
+ });
1276
1497
  const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
1277
1498
  apiBaseUrl,
1278
1499
  audience,
@@ -1507,8 +1728,8 @@ async function pathExists(path) {
1507
1728
  }
1508
1729
  }
1509
1730
  function builtInAgentRoutesFor(routes) {
1510
- const projectRoutePaths = new Set(routes.map((route) => route.path));
1511
- return builtInAgentRoutePaths.filter((path) => !projectRoutePaths.has(path)).map((path) => ({
1731
+ const projectRoutePatterns = new Set(routes.map((route) => routePatternKey(route.path)));
1732
+ return builtInAgentRoutePaths.filter((path) => !projectRoutePatterns.has(routePatternKey(path))).map((path) => ({
1512
1733
  path,
1513
1734
  moduleSpecifier: builtInAgentRouteModule
1514
1735
  }));
@@ -1810,4 +2031,4 @@ export {
1810
2031
  createCustomApp
1811
2032
  };
1812
2033
 
1813
- //# debugId=DF164E399EBD3CA764756E2164756E21
2034
+ //# debugId=66AA128AADD55E1164756E2164756E21