@sixb/app 0.1.2 → 0.1.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/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  // @bun
2
2
  // src/createCustomApp.ts
3
3
  import { watch } from "fs";
4
- import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
4
+ import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
5
5
  import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve3 } from "path";
6
6
  import { pathToFileURL as pathToFileURL2 } from "url";
7
7
 
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,
@@ -69,6 +69,54 @@ async function buildApp(options) {
69
69
  await precompressBuildAssets(result.outputs);
70
70
  return { success: true, outdir };
71
71
  }
72
+ async function buildAuthExperience(options) {
73
+ const outdir = resolve(options.outdir);
74
+ const assetsDir = join(outdir, "assets");
75
+ await rm(outdir, { recursive: true, force: true });
76
+ await mkdir(assetsDir, { recursive: true });
77
+ const result = await Bun.build({
78
+ entrypoints: [options.scriptEntryPath],
79
+ outdir: assetsDir,
80
+ target: "browser",
81
+ conditions: ["bun"],
82
+ publicPath: "/auth/assets/",
83
+ minify: true,
84
+ splitting: true,
85
+ naming: {
86
+ entry: "auth-[hash].[ext]",
87
+ chunk: "chunk-[name]-[hash].[ext]",
88
+ asset: "asset-[name]-[hash].[ext]"
89
+ },
90
+ plugins: [extensionlessSourceImportPlugin],
91
+ define: { "process.env.NODE_ENV": '"production"' },
92
+ sourcemap: "external"
93
+ });
94
+ if (!result.success) {
95
+ return {
96
+ success: false,
97
+ outdir,
98
+ logs: result.logs.map(String)
99
+ };
100
+ }
101
+ const script = result.outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
102
+ const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"));
103
+ if (!script || stylesheets.length > 1) {
104
+ throw new Error(`[SixbCustomApp] Expected one auth entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
105
+ }
106
+ const sourceHtml = await readFile(options.entryPath, "utf-8");
107
+ const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/auth-main\.tsx["']><\/script>/;
108
+ if (!sourceEntryPattern.test(sourceHtml)) {
109
+ throw new Error("[SixbCustomApp] Generated auth shell is missing its ./auth-main.tsx entry.");
110
+ }
111
+ const assetTags = [
112
+ ...stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/auth/assets/${basename(stylesheet.path)}">`),
113
+ `<script type="module" crossorigin src="/auth/assets/${basename(script.path)}"></script>`
114
+ ].join("");
115
+ const html = sourceHtml.replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
116
+ await writeFile(join(outdir, "index.html"), html, "utf-8");
117
+ await precompressBuildAssets(result.outputs);
118
+ return { success: true, outdir };
119
+ }
72
120
  async function prepareAppHtmlBundleEntry(entryPath) {
73
121
  const html = await readFile(entryPath, "utf-8");
74
122
  const bundleHtml = html.replace(/(<link\s+rel=["'](?:manifest|icon|apple-touch-icon)["']\s+href=["'])(\/[^"']*)(["'][^>]*>)/g, `$1${STATIC_ASSET_ORIGIN}$2$3`);
@@ -97,9 +145,7 @@ function withLoadingShell(html) {
97
145
  var extensionlessSourceImportPlugin = {
98
146
  name: "sixb-extensionless-source-imports",
99
147
  setup(build) {
100
- build.onResolve({ filter: /^\.\.?\// }, (args) => {
101
- if (extname(args.path))
102
- return;
148
+ build.onResolve({ filter: /^\.\.?\/(?:.*\/)?[^/.]+$/ }, (args) => {
103
149
  const base = resolve(dirname(args.importer), args.path);
104
150
  for (const candidate of [
105
151
  `${base}.ts`,
@@ -141,7 +187,7 @@ async function precompressBuildAssets(outputs) {
141
187
 
142
188
  // src/codegen.ts
143
189
  import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
144
- import { join as join3, relative, resolve as resolve2 } from "path";
190
+ import { join as join4, relative as relative2, resolve as resolve2 } from "path";
145
191
 
146
192
  // src/manifest.ts
147
193
  function renderAppManifest(metadata) {
@@ -164,7 +210,7 @@ function renderAppManifest(metadata) {
164
210
  import { createHash } from "crypto";
165
211
  import { readFile as readFile2, stat } from "fs/promises";
166
212
  import { createRequire } from "module";
167
- import { extname as extname2, join as join2 } from "path";
213
+ import { extname, join as join2 } from "path";
168
214
  import { pathToFileURL } from "url";
169
215
  var metadataRequire = createRequire(import.meta.url);
170
216
  var metadataFields = [
@@ -273,7 +319,7 @@ function inferImageMimeType(url) {
273
319
  try {
274
320
  pathname = new URL(url, "https://sixb.invalid").pathname;
275
321
  } catch {}
276
- switch (extname2(pathname).toLowerCase()) {
322
+ switch (extname(pathname).toLowerCase()) {
277
323
  case ".svg":
278
324
  return "image/svg+xml";
279
325
  case ".png":
@@ -305,15 +351,149 @@ function renderCustomAppRuntimeScript(config) {
305
351
  return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
306
352
  }
307
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
+
308
485
  // src/codegen.ts
486
+ var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
309
487
  async function generateRouteManifest(routes, generatedDir, options = {}) {
310
488
  await mkdir2(generatedDir, { recursive: true });
311
- const imports = routes.map((route, index) => {
489
+ const pages = [...routes].sort(compareRouteModules2);
490
+ const pageImports = pages.map((route, index) => {
312
491
  const rel = relativeTo(generatedDir, route.filePath);
313
492
  return `import Page${index} from ${JSON.stringify(rel)}`;
314
493
  }).join(`
315
494
  `);
316
- 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)));
317
497
  const builtInImports = builtInRoutes.map((route, index) => {
318
498
  if (route.exportName) {
319
499
  return `import { ${route.exportName} as BuiltInPage${index} } from ${JSON.stringify(route.moduleSpecifier)}`;
@@ -321,32 +501,278 @@ async function generateRouteManifest(routes, generatedDir, options = {}) {
321
501
  return `import BuiltInPage${index} from ${JSON.stringify(route.moduleSpecifier)}`;
322
502
  }).join(`
323
503
  `);
324
- const entries = routes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: Page${index} },`).join(`
325
- `);
326
- const builtInEntries = builtInRoutes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: BuiltInPage${index} },`).join(`
327
- `);
328
- 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(`
329
513
  `);
330
- 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(`
331
531
  `);
532
+ const routePaths = [
533
+ ...pages.map((route) => route.path),
534
+ ...builtInRoutes.map((route) => route.path)
535
+ ];
332
536
  const content = `${importEntries}
333
537
 
538
+ export const routePaths = ${JSON.stringify(routePaths, null, 2)} as const
539
+
334
540
  export const routes = [
335
- ${routeEntries}
336
- ]
541
+ ${renderRootRouteObjects(tree)}
542
+ ] satisfies RouteObject[]
337
543
  `;
338
- const outPath = join3(generatedDir, "routes.ts");
544
+ const outPath = join4(generatedDir, "routes.ts");
339
545
  await writeFileIfChanged(outPath, content);
340
546
  return outPath;
341
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
+ }
655
+ async function generateAuthExperienceEntry(projectRoot, generatedDir, options = {}) {
656
+ await mkdir2(generatedDir, { recursive: true });
657
+ const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join4(projectRoot, "app");
658
+ const authPath = join4(appDir, "auth.tsx");
659
+ if (!await fileExists2(authPath)) {
660
+ return null;
661
+ }
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");
665
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir });
666
+ const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
667
+ const stylesheetImport = stylesheetPath ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}` : "";
668
+ const authRel = relativeTo(generatedDir, authPath);
669
+ const mainContent = `import React from "react"
670
+ import { createRoot } from "react-dom/client"
671
+ import type {
672
+ AuthExperienceActions,
673
+ AuthExperienceState,
674
+ } from "@sixb/app/auth"
675
+ import AuthExperience from ${JSON.stringify(authRel)}
676
+ ${stylesheetImport}
677
+
678
+ interface AuthExperienceBootstrap {
679
+ readonly state: AuthExperienceState
680
+ readonly signInUrl: string
681
+ readonly submission?: {
682
+ readonly kind: "requestMagicLink" | "confirmSignIn"
683
+ readonly action: string
684
+ readonly fields: Readonly<Record<string, string>>
685
+ }
686
+ }
687
+
688
+ const root = document.getElementById("root")
689
+ if (!root) {
690
+ throw new Error("[SixbApp] Could not find the auth experience root element.")
691
+ }
692
+
693
+ const encodedBootstrap = root.dataset.sixbAuth
694
+ if (!encodedBootstrap) {
695
+ throw new Error("[SixbApp] Auth experience bootstrap is missing.")
696
+ }
697
+
698
+ const bootstrap = decodeBootstrap(encodedBootstrap)
699
+ const actions: AuthExperienceActions = {
700
+ requestMagicLink(email) {
701
+ submit("requestMagicLink", { email })
702
+ },
703
+ confirmSignIn() {
704
+ submit("confirmSignIn")
705
+ },
706
+ restartSignIn() {
707
+ window.location.assign(bootstrap.signInUrl)
708
+ },
709
+ }
710
+
711
+ function submit(
712
+ kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
713
+ additionalFields: Readonly<Record<string, string>> = {}
714
+ ): void {
715
+ const submission = bootstrap.submission
716
+ if (!submission || submission.kind !== kind) {
717
+ throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
718
+ }
719
+
720
+ const form = document.createElement("form")
721
+ form.method = "post"
722
+ form.action = submission.action
723
+ form.hidden = true
724
+ for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
725
+ const input = document.createElement("input")
726
+ input.type = "hidden"
727
+ input.name = name
728
+ input.value = value
729
+ form.append(input)
730
+ }
731
+ document.body.append(form)
732
+ form.submit()
733
+ }
734
+
735
+ function decodeBootstrap(value: string): AuthExperienceBootstrap {
736
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
737
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
738
+ const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
739
+ return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
740
+ }
741
+
742
+ createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
743
+ `;
744
+ const mainPath = join4(generatedDir, "auth-main.tsx");
745
+ await writeFileIfChanged(mainPath, mainContent);
746
+ const htmlContent = `<!DOCTYPE html>
747
+ <html lang="en">
748
+ <head>
749
+ <meta charset="UTF-8" />
750
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
751
+ ${renderAuthMetadataHead(metadata)}
752
+ <style>
753
+ * { box-sizing: border-box; }
754
+ html, body, #root { margin: 0; min-height: 100%; }
755
+ body, #root { min-height: 100vh; min-height: 100dvh; }
756
+ </style>
757
+ </head>
758
+ <body>
759
+ <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
760
+ <script type="module" src="./auth-main.tsx"></script>
761
+ </body>
762
+ </html>
763
+ `;
764
+ const htmlPath = join4(generatedDir, "auth-index.html");
765
+ await writeFileIfChanged(htmlPath, htmlContent);
766
+ return { htmlPath, mainPath };
767
+ }
342
768
  async function generateAppEntry(projectRoot, generatedDir, options = {}) {
343
769
  await mkdir2(generatedDir, { recursive: true });
344
- const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join3(projectRoot, "app");
345
- const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join3(appDir, "public");
346
- const globalsCssPath = join3(appDir, "globals.css");
347
- 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");
348
774
  const metadata = await resolveAppMetadata({ layoutPath, publicDir });
349
- const manifestPath = join3(generatedDir, "app.webmanifest");
775
+ const manifestPath = join4(generatedDir, "app.webmanifest");
350
776
  await writeFileIfChanged(manifestPath, renderAppManifest(metadata));
351
777
  const layoutRel = relativeTo(generatedDir, layoutPath);
352
778
  const hasLayout = await fileExists2(layoutPath);
@@ -368,7 +794,13 @@ async function generateAppEntry(projectRoot, generatedDir, options = {}) {
368
794
  const mainContent = `import React from "react"
369
795
  import { createRoot, type Root } from "react-dom/client"
370
796
  import { signOut } from "@sixb/client"
371
- 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"
372
804
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
373
805
  import {
374
806
  configureSixbBrowserClient,
@@ -376,7 +808,7 @@ import {
376
808
  readSixbBrowserRuntimeConfig,
377
809
  requireSixbBrowserAuthSession,
378
810
  } from "@sixb/client/browser"
379
- import { routes } from "./routes"
811
+ import { routePaths, routes } from "./routes"
380
812
  ${globalsCssImport}
381
813
  ${layoutImport}
382
814
 
@@ -476,7 +908,7 @@ function InternalLinkInterceptor() {
476
908
  if (isReservedPath(url.pathname)) return
477
909
  // Only intercept destinations the app actually routes; anything else may
478
910
  // be a real server resource and keeps native navigation.
479
- if (!routes.some((route) => matchPath(route.path, url.pathname))) return
911
+ if (!routePaths.some((path) => matchPath(path, url.pathname))) return
480
912
  // Same-document hash links keep native scroll behavior.
481
913
  if (
482
914
  url.hash &&
@@ -680,6 +1112,12 @@ function RoutedErrorBoundary({ children }: { children: React.ReactNode }) {
680
1112
  )
681
1113
  }
682
1114
 
1115
+ const appRoutes = [...routes, { path: "*", element: <NotFoundView /> }]
1116
+
1117
+ function AppRoutes() {
1118
+ return useRoutes(appRoutes)
1119
+ }
1120
+
683
1121
  function App() {
684
1122
  return (
685
1123
  <QueryClientProvider client={queryClient}>
@@ -687,12 +1125,7 @@ function App() {
687
1125
  <InternalLinkInterceptor />
688
1126
  <RoutedErrorBoundary>
689
1127
  ${layoutWrapperStart}
690
- <Routes>
691
- {routes.map((route) => (
692
- <Route key={route.path} path={route.path} element={<route.component />} />
693
- ))}
694
- <Route path="*" element={<NotFoundView />} />
695
- </Routes>
1128
+ <AppRoutes />
696
1129
  ${layoutWrapperEnd}
697
1130
  </RoutedErrorBoundary>
698
1131
  </BrowserRouter>
@@ -706,7 +1139,7 @@ if (canRenderApp) {
706
1139
  getRoot().render(<AccessDeniedView />)
707
1140
  }
708
1141
  `;
709
- const mainPath = join3(generatedDir, "main.tsx");
1142
+ const mainPath = join4(generatedDir, "main.tsx");
710
1143
  await writeFileIfChanged(mainPath, mainContent);
711
1144
  const metadataHead = renderMetadataHead(metadata);
712
1145
  const htmlContent = `<!DOCTYPE html>
@@ -745,7 +1178,7 @@ ${metadataHead}
745
1178
  </body>
746
1179
  </html>
747
1180
  `;
748
- const htmlPath = join3(generatedDir, "index.html");
1181
+ const htmlPath = join4(generatedDir, "index.html");
749
1182
  await writeFileIfChanged(htmlPath, htmlContent);
750
1183
  return { htmlPath, mainPath, manifestPath };
751
1184
  }
@@ -761,6 +1194,16 @@ function renderMetadataHead(metadata) {
761
1194
  return tags.join(`
762
1195
  `);
763
1196
  }
1197
+ function renderAuthMetadataHead(metadata) {
1198
+ const tags = [
1199
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
1200
+ ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
1201
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
1202
+ ...metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon) ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : []
1203
+ ];
1204
+ return tags.join(`
1205
+ `);
1206
+ }
764
1207
  function escapeHtmlText(value) {
765
1208
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
766
1209
  }
@@ -783,7 +1226,7 @@ function isFileNotFoundError(error) {
783
1226
  return error instanceof Error && "code" in error && error.code === "ENOENT";
784
1227
  }
785
1228
  function relativeTo(from, to) {
786
- let rel = relative(from, to);
1229
+ let rel = relative2(from, to);
787
1230
  if (!rel.startsWith("."))
788
1231
  rel = `./${rel}`;
789
1232
  return rel;
@@ -797,57 +1240,6 @@ async function fileExists2(path) {
797
1240
  }
798
1241
  }
799
1242
 
800
- // src/scanner.ts
801
- import { readdir } from "fs/promises";
802
- import { join as join4, relative as relative2 } from "path";
803
- async function scanPages(appDir) {
804
- const routes = [];
805
- await walkDir(appDir, appDir, routes);
806
- routes.sort((a, b) => a.path.localeCompare(b.path));
807
- return routes;
808
- }
809
- async function walkDir(dir, appDir, routes) {
810
- let entries;
811
- try {
812
- entries = await readdir(dir, { withFileTypes: true });
813
- } catch {
814
- return;
815
- }
816
- for (const entry of entries) {
817
- const name = String(entry.name);
818
- if (name.startsWith("_"))
819
- continue;
820
- const fullPath = join4(dir, name);
821
- if (entry.isDirectory()) {
822
- await walkDir(fullPath, appDir, routes);
823
- continue;
824
- }
825
- if (!entry.isFile())
826
- continue;
827
- const isPageModule = name === "page.tsx" || name === "page.ts";
828
- if (!isPageModule)
829
- continue;
830
- const relativePath = relative2(appDir, fullPath);
831
- const routePath = filePathToRoutePath(relativePath);
832
- routes.push({
833
- path: routePath,
834
- filePath: fullPath,
835
- relativePath
836
- });
837
- }
838
- }
839
- function filePathToRoutePath(filePath) {
840
- let route = filePath.replace(/\.(tsx|ts)$/, "");
841
- route = route.split("\\").join("/");
842
- route = route.replace(/\[([^\]]+)\]/g, ":$1");
843
- if (route === "page")
844
- return "/";
845
- route = route.replace(/\/page$/, "");
846
- if (!route.startsWith("/"))
847
- route = `/${route}`;
848
- return route;
849
- }
850
-
851
1243
  // src/styles.ts
852
1244
  import { readFile as readFile4 } from "fs/promises";
853
1245
  import { join as join6 } from "path";
@@ -1002,13 +1394,11 @@ async function createCustomApp(options) {
1002
1394
  const authEnabled = options.authEnabled ?? true;
1003
1395
  const agentRoutesEnabled = options.agentRoutes ?? true;
1004
1396
  async function scanRoutes() {
1005
- if (!await pathExists(appDir)) {
1006
- return [];
1007
- }
1008
- return await scanPages(appDir);
1397
+ return [...(await scanAppRoutes(appDir)).pages];
1009
1398
  }
1010
1399
  let tailwindCompiler = null;
1011
1400
  let tailwindCompilerKey = null;
1401
+ let authTailwindCompiler = null;
1012
1402
  let builtInAgentCssCompiler = null;
1013
1403
  async function prepareStylesheet(stylesheet) {
1014
1404
  stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
@@ -1093,13 +1483,17 @@ async function createCustomApp(options) {
1093
1483
  return outputPath;
1094
1484
  }
1095
1485
  async function prepareGeneratedApp() {
1096
- const routes = await scanRoutes();
1486
+ const discovery = await scanAppRoutes(appDir);
1487
+ const routes = [...discovery.pages];
1097
1488
  if (routes.length === 0) {
1098
1489
  throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`);
1099
1490
  }
1100
1491
  const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : [];
1101
1492
  const stylesheets = await prepareStylesheets(builtInRoutes);
1102
- await generateRouteManifest(routes, generatedDir, { builtInRoutes });
1493
+ await generateRouteManifest(routes, generatedDir, {
1494
+ builtInRoutes,
1495
+ layouts: discovery.layouts
1496
+ });
1103
1497
  const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
1104
1498
  apiBaseUrl,
1105
1499
  audience,
@@ -1111,6 +1505,49 @@ async function createCustomApp(options) {
1111
1505
  });
1112
1506
  return { htmlPath, mainPath, manifestPath, routes };
1113
1507
  }
1508
+ async function prepareAuthExperience(authOptions = {}) {
1509
+ const outdir = authOptions.outdir ? resolve3(rootDir, authOptions.outdir) : join7(generatedDir, "auth");
1510
+ if (!await pathExists(join7(appDir, "auth.tsx"))) {
1511
+ await rm2(outdir, { recursive: true, force: true });
1512
+ return null;
1513
+ }
1514
+ const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
1515
+ let stylesheetPath;
1516
+ if (stylesheet.kind === "none") {
1517
+ stylesheetPath = null;
1518
+ } else if (stylesheet.kind === "static") {
1519
+ stylesheetPath = stylesheet.path;
1520
+ } else {
1521
+ const outputPath = join7(generatedDir, "auth.css");
1522
+ authTailwindCompiler ??= createTailwindCssCompiler({
1523
+ inputPath: stylesheet.sourcePath,
1524
+ outputPath,
1525
+ cwd: appDir,
1526
+ resolveFrom: rootDir,
1527
+ label: "[SixbCustomApp]"
1528
+ });
1529
+ await authTailwindCompiler.compile();
1530
+ stylesheetPath = outputPath;
1531
+ }
1532
+ const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
1533
+ appDir,
1534
+ publicDir,
1535
+ stylesheetPath
1536
+ });
1537
+ if (!entry) {
1538
+ return null;
1539
+ }
1540
+ const result = await buildAuthExperience({
1541
+ entryPath: entry.htmlPath,
1542
+ scriptEntryPath: entry.mainPath,
1543
+ outdir
1544
+ });
1545
+ if (!result.success) {
1546
+ throw new Error(`[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join(`
1547
+ `)}`);
1548
+ }
1549
+ return { outdir: result.outdir };
1550
+ }
1114
1551
  return {
1115
1552
  async scanRoutes() {
1116
1553
  return await scanRoutes();
@@ -1119,10 +1556,14 @@ async function createCustomApp(options) {
1119
1556
  const routes = await scanRoutes();
1120
1557
  return routes.length > 0;
1121
1558
  },
1559
+ async prepareAuthExperience(options2) {
1560
+ return await prepareAuthExperience(options2);
1561
+ },
1122
1562
  async dev(devOptions = {}) {
1123
1563
  const host = devOptions.host ?? "0.0.0.0";
1124
1564
  const port = devOptions.port ?? 3001;
1125
1565
  const { htmlPath, manifestPath } = await prepareGeneratedApp();
1566
+ await prepareAuthExperience();
1126
1567
  let htmlImportVersion = 0;
1127
1568
  let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
1128
1569
  const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
@@ -1147,6 +1588,7 @@ async function createCustomApp(options) {
1147
1588
  const enqueueRebuild = () => {
1148
1589
  rebuildChain = rebuildChain.then(async () => {
1149
1590
  const { htmlPath: nextHtmlPath } = await prepareGeneratedApp();
1591
+ await prepareAuthExperience();
1150
1592
  htmlImportVersion++;
1151
1593
  htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
1152
1594
  server.reload(serveOptions(htmlBundle));
@@ -1185,6 +1627,7 @@ async function createCustomApp(options) {
1185
1627
  watcher.close();
1186
1628
  await rebuildChain;
1187
1629
  await tailwindCompiler?.stop();
1630
+ await authTailwindCompiler?.stop();
1188
1631
  await builtInAgentCssCompiler?.stop();
1189
1632
  server.stop(true);
1190
1633
  }
@@ -1199,11 +1642,17 @@ async function createCustomApp(options) {
1199
1642
  manifestPath,
1200
1643
  outdir
1201
1644
  });
1645
+ if (result.success) {
1646
+ await prepareAuthExperience({ outdir: join7(outdir, "auth") });
1647
+ }
1202
1648
  if (result.success && await pathExists(publicDir)) {
1203
1649
  await cp(publicDir, outdir, {
1204
1650
  recursive: true,
1205
1651
  force: true,
1206
- filter: (source) => resolve3(source) !== join7(publicDir, "app.webmanifest")
1652
+ filter: (source) => {
1653
+ const resolvedSource = resolve3(source);
1654
+ return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, "auth");
1655
+ }
1207
1656
  });
1208
1657
  }
1209
1658
  return result;
@@ -1279,8 +1728,8 @@ async function pathExists(path) {
1279
1728
  }
1280
1729
  }
1281
1730
  function builtInAgentRoutesFor(routes) {
1282
- const projectRoutePaths = new Set(routes.map((route) => route.path));
1283
- 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) => ({
1284
1733
  path,
1285
1734
  moduleSpecifier: builtInAgentRouteModule
1286
1735
  }));
@@ -1582,4 +2031,4 @@ export {
1582
2031
  createCustomApp
1583
2032
  };
1584
2033
 
1585
- //# debugId=E6B6484555ADAD4D64756E2164756E21
2034
+ //# debugId=66AA128AADD55E1164756E2164756E21