@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.
@@ -1,17 +1,23 @@
1
1
  import { watch } from "node:fs"
2
- import { access, cp, mkdir, readFile, writeFile } from "node:fs/promises"
2
+ import { access, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"
3
3
  import { dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"
4
4
  import { pathToFileURL } from "node:url"
5
5
  import type { AuthSessionAudience } from "@sixb/core"
6
6
  import {
7
7
  type BuildAppResult,
8
8
  buildApp,
9
+ buildAuthExperience,
9
10
  prepareAppHtmlBundleEntry,
10
11
  restoreAppStaticUrls,
11
12
  } from "./build"
12
- import { type BuiltInRouteManifestEntry, generateAppEntry, generateRouteManifest } from "./codegen"
13
+ import {
14
+ type BuiltInRouteManifestEntry,
15
+ generateAppEntry,
16
+ generateAuthExperienceEntry,
17
+ generateRouteManifest,
18
+ } from "./codegen"
13
19
  import { renderCustomAppRuntimeScript } from "./runtime"
14
- import { type PageRoute, scanPages } from "./scanner"
20
+ import { type PageRoute, routePatternKey, scanAppRoutes } from "./scanner"
15
21
  import { type CustomAppStylesheet, resolveCustomAppStylesheet } from "./styles"
16
22
  import { createTailwindCssCompiler, type TailwindCssCompiler } from "./tailwind"
17
23
 
@@ -35,6 +41,14 @@ export interface CustomAppBuildOptions {
35
41
  outdir?: string
36
42
  }
37
43
 
44
+ export interface CustomAuthExperienceBuildOptions {
45
+ outdir?: string
46
+ }
47
+
48
+ export interface CustomAuthExperienceBuildResult {
49
+ readonly outdir: string
50
+ }
51
+
38
52
  export interface CustomAppStartOptions {
39
53
  host?: string
40
54
  port?: number
@@ -54,6 +68,9 @@ export interface CustomAppDevServer {
54
68
  export interface CustomAppInstance {
55
69
  scanRoutes(): Promise<PageRoute[]>
56
70
  hasRoutes(): Promise<boolean>
71
+ prepareAuthExperience(
72
+ options?: CustomAuthExperienceBuildOptions
73
+ ): Promise<CustomAuthExperienceBuildResult | null>
57
74
  dev(options?: CustomAppDevOptions): Promise<CustomAppDevServer>
58
75
  build(options?: CustomAppBuildOptions): Promise<BuildAppResult>
59
76
  start(options?: CustomAppStartOptions): Promise<CustomAppDevServer>
@@ -81,15 +98,12 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
81
98
  const agentRoutesEnabled = options.agentRoutes ?? true
82
99
 
83
100
  async function scanRoutes(): Promise<PageRoute[]> {
84
- if (!(await pathExists(appDir))) {
85
- return []
86
- }
87
-
88
- return await scanPages(appDir)
101
+ return [...(await scanAppRoutes(appDir)).pages]
89
102
  }
90
103
 
91
104
  let tailwindCompiler: TailwindCssCompiler | null = null
92
105
  let tailwindCompilerKey: string | null = null
106
+ let authTailwindCompiler: TailwindCssCompiler | null = null
93
107
  let builtInAgentCssCompiler: TailwindCssCompiler | null = null
94
108
 
95
109
  // `app/globals.css` is source. When it uses Tailwind, compile it to
@@ -218,14 +232,18 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
218
232
  manifestPath: string
219
233
  routes: PageRoute[]
220
234
  }> {
221
- const routes = await scanRoutes()
235
+ const discovery = await scanAppRoutes(appDir)
236
+ const routes = [...discovery.pages]
222
237
  if (routes.length === 0) {
223
238
  throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`)
224
239
  }
225
240
 
226
241
  const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : []
227
242
  const stylesheets = await prepareStylesheets(builtInRoutes)
228
- await generateRouteManifest(routes, generatedDir, { builtInRoutes })
243
+ await generateRouteManifest(routes, generatedDir, {
244
+ builtInRoutes,
245
+ layouts: discovery.layouts,
246
+ })
229
247
  const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
230
248
  apiBaseUrl,
231
249
  audience,
@@ -238,6 +256,58 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
238
256
  return { htmlPath, mainPath, manifestPath, routes }
239
257
  }
240
258
 
259
+ async function prepareAuthExperience(
260
+ authOptions: CustomAuthExperienceBuildOptions = {}
261
+ ): Promise<CustomAuthExperienceBuildResult | null> {
262
+ const outdir = authOptions.outdir
263
+ ? resolve(rootDir, authOptions.outdir)
264
+ : join(generatedDir, "auth")
265
+ if (!(await pathExists(join(appDir, "auth.tsx")))) {
266
+ await rm(outdir, { recursive: true, force: true })
267
+ return null
268
+ }
269
+
270
+ const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir })
271
+ let stylesheetPath: string | null
272
+ if (stylesheet.kind === "none") {
273
+ stylesheetPath = null
274
+ } else if (stylesheet.kind === "static") {
275
+ stylesheetPath = stylesheet.path
276
+ } else {
277
+ const outputPath = join(generatedDir, "auth.css")
278
+ authTailwindCompiler ??= createTailwindCssCompiler({
279
+ inputPath: stylesheet.sourcePath,
280
+ outputPath,
281
+ cwd: appDir,
282
+ resolveFrom: rootDir,
283
+ label: "[SixbCustomApp]",
284
+ })
285
+ await authTailwindCompiler.compile()
286
+ stylesheetPath = outputPath
287
+ }
288
+
289
+ const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
290
+ appDir,
291
+ publicDir,
292
+ stylesheetPath,
293
+ })
294
+ if (!entry) {
295
+ return null
296
+ }
297
+
298
+ const result = await buildAuthExperience({
299
+ entryPath: entry.htmlPath,
300
+ scriptEntryPath: entry.mainPath,
301
+ outdir,
302
+ })
303
+ if (!result.success) {
304
+ throw new Error(
305
+ `[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join("\n")}`
306
+ )
307
+ }
308
+ return { outdir: result.outdir }
309
+ }
310
+
241
311
  return {
242
312
  async scanRoutes() {
243
313
  return await scanRoutes()
@@ -248,10 +318,15 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
248
318
  return routes.length > 0
249
319
  },
250
320
 
321
+ async prepareAuthExperience(options) {
322
+ return await prepareAuthExperience(options)
323
+ },
324
+
251
325
  async dev(devOptions: CustomAppDevOptions = {}) {
252
326
  const host = devOptions.host ?? "0.0.0.0"
253
327
  const port = devOptions.port ?? 3001
254
328
  const { htmlPath, manifestPath } = await prepareGeneratedApp()
329
+ await prepareAuthExperience()
255
330
  let htmlImportVersion = 0
256
331
  let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion)
257
332
  const publicRoutes = (await pathExists(publicDir)) ? await createPublicRoutes(publicDir) : {}
@@ -282,6 +357,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
282
357
  rebuildChain = rebuildChain
283
358
  .then(async () => {
284
359
  const { htmlPath: nextHtmlPath } = await prepareGeneratedApp()
360
+ await prepareAuthExperience()
285
361
  htmlImportVersion++
286
362
  htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion)
287
363
  server.reload(serveOptions(htmlBundle))
@@ -331,6 +407,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
331
407
  watcher.close()
332
408
  await rebuildChain
333
409
  await tailwindCompiler?.stop()
410
+ await authTailwindCompiler?.stop()
334
411
  await builtInAgentCssCompiler?.stop()
335
412
  server.stop(true)
336
413
  },
@@ -347,11 +424,21 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
347
424
  outdir,
348
425
  })
349
426
 
427
+ if (result.success) {
428
+ await prepareAuthExperience({ outdir: join(outdir, "auth") })
429
+ }
430
+
350
431
  if (result.success && (await pathExists(publicDir))) {
351
432
  await cp(publicDir, outdir, {
352
433
  recursive: true,
353
434
  force: true,
354
- filter: (source) => resolve(source) !== join(publicDir, "app.webmanifest"),
435
+ filter: (source) => {
436
+ const resolvedSource = resolve(source)
437
+ return (
438
+ resolvedSource !== join(publicDir, "app.webmanifest") &&
439
+ resolvedSource !== join(publicDir, "auth")
440
+ )
441
+ },
355
442
  })
356
443
  }
357
444
 
@@ -443,10 +530,10 @@ async function pathExists(path: string): Promise<boolean> {
443
530
  }
444
531
 
445
532
  function builtInAgentRoutesFor(routes: readonly PageRoute[]): BuiltInRouteManifestEntry[] {
446
- const projectRoutePaths = new Set(routes.map((route) => route.path))
533
+ const projectRoutePatterns = new Set(routes.map((route) => routePatternKey(route.path)))
447
534
 
448
535
  return builtInAgentRoutePaths
449
- .filter((path) => !projectRoutePaths.has(path))
536
+ .filter((path) => !projectRoutePatterns.has(routePatternKey(path)))
450
537
  .map((path) => ({
451
538
  path,
452
539
  moduleSpecifier: builtInAgentRouteModule,
package/src/index.ts CHANGED
@@ -5,6 +5,8 @@ export {
5
5
  type CustomAppDevServer,
6
6
  type CustomAppInstance,
7
7
  type CustomAppStartOptions,
8
+ type CustomAuthExperienceBuildOptions,
9
+ type CustomAuthExperienceBuildResult,
8
10
  createCustomApp,
9
11
  } from "./createCustomApp"
10
12
  export type { AppMetadata } from "./metadata"
package/src/scanner.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { readdir } from "node:fs/promises"
2
2
  import { join, relative } from "node:path"
3
3
 
4
+ const dynamicSegmentPattern = /^\[([\w-]+)\]$/
5
+ const reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb"] as const
6
+ const reservedRoutePaths = new Set(["/app.webmanifest"])
7
+
4
8
  export interface PageRoute {
5
9
  /** React Router path, e.g. "/" or "/remote/:id" */
6
10
  path: string
@@ -10,72 +14,213 @@ export interface PageRoute {
10
14
  relativePath: string
11
15
  }
12
16
 
17
+ export interface AppRouteLayout {
18
+ /** React Router prefix owned by this layout, e.g. "/remote/:id". */
19
+ path: string
20
+ /** Absolute file path. */
21
+ filePath: string
22
+ /** Relative path from the app directory, e.g. "remote/[id]/layout.tsx". */
23
+ relativePath: string
24
+ }
25
+
26
+ export interface AppRouteDiscovery {
27
+ readonly pages: readonly PageRoute[]
28
+ /** Descendant layouts only. The root layout remains the global app wrapper. */
29
+ readonly layouts: readonly AppRouteLayout[]
30
+ }
31
+
13
32
  /**
14
- * Recursively scans an `app/` directory for `page.tsx`/`page.ts` files and
15
- * converts them to React Router route paths.
33
+ * Recursively scans an `app/` directory for page modules and descendant layouts.
16
34
  *
17
- * - `app/page.tsx` -> `/`
18
- * - `app/about/page.tsx` -> `/about`
19
- * - `app/remote/[id]/page.tsx` -> `/remote/:id`
20
- * - Files starting with `_` are skipped.
35
+ * - `app/page.tsx` -> page `/`
36
+ * - `app/about/page.tsx` -> page `/about`
37
+ * - `app/remote/[id]/page.tsx` -> page `/remote/:id`
38
+ * - `app/remote/[id]/layout.tsx` -> layout `/remote/:id/**`
39
+ * - `app/layout.tsx` remains the global wrapper and is not returned as a route layout.
40
+ * - Files and folders starting with `_` are skipped.
21
41
  */
42
+ export async function scanAppRoutes(appDir: string): Promise<AppRouteDiscovery> {
43
+ const pages: PageRoute[] = []
44
+ const layouts: AppRouteLayout[] = []
45
+ await walkDir(appDir, appDir, pages, layouts)
46
+ pages.sort(compareRouteModules)
47
+ layouts.sort(compareRouteModules)
48
+ return { pages, layouts }
49
+ }
50
+
51
+ /** Preserve the existing flat inspection contract while route generation uses the richer scan. */
22
52
  export async function scanPages(appDir: string): Promise<PageRoute[]> {
23
- const routes: PageRoute[] = []
24
- await walkDir(appDir, appDir, routes)
25
- routes.sort((a, b) => a.path.localeCompare(b.path))
26
- return routes
53
+ return [...(await scanAppRoutes(appDir)).pages]
27
54
  }
28
55
 
29
- async function walkDir(dir: string, appDir: string, routes: PageRoute[]): Promise<void> {
30
- let entries: import("node:fs").Dirent[]
31
- try {
32
- entries = (await readdir(dir, { withFileTypes: true })) as import("node:fs").Dirent[]
33
- } catch {
34
- return
56
+ /** Treat parameter names as labels when comparing route ownership and overrides. */
57
+ export function routePatternKey(path: string): string {
58
+ if (path === "/") return "/"
59
+ const segments = routeSegments(path).map((segment) =>
60
+ segment.startsWith(":") ? ":" : segment.toLowerCase()
61
+ )
62
+ return `/${segments.join("/")}`
63
+ }
64
+
65
+ async function walkDir(
66
+ dir: string,
67
+ appDir: string,
68
+ pages: PageRoute[],
69
+ layouts: AppRouteLayout[]
70
+ ): Promise<void> {
71
+ const entries = await readDirectory(dir)
72
+ if (!entries) return
73
+
74
+ const visibleEntries = entries
75
+ .filter((entry) => !String(entry.name).startsWith("_"))
76
+ .sort((a, b) => compareText(String(a.name), String(b.name)))
77
+ const relativeDir = normalizeRelativePath(relative(appDir, dir))
78
+
79
+ validateChildDirectories(visibleEntries, relativeDir)
80
+
81
+ const pageEntries = visibleEntries.filter(
82
+ (entry) => entry.isFile() && (entry.name === "page.tsx" || entry.name === "page.ts")
83
+ )
84
+ if (pageEntries.length > 1) {
85
+ const modules = pageEntries.map((entry) => displayAppPath(join(relativeDir, entry.name)))
86
+ throw new Error(
87
+ `[SixbCustomApp] Conflicting page modules for route '${directoryRoutePath(relativeDir)}': ${modules.join(" and ")}. Keep exactly one of page.tsx or page.ts.`
88
+ )
35
89
  }
36
90
 
37
- for (const entry of entries) {
38
- const name = String(entry.name)
39
- if (name.startsWith("_")) continue
91
+ const pageEntry = pageEntries[0]
92
+ if (pageEntry) {
93
+ const relativePath = normalizeRelativePath(join(relativeDir, pageEntry.name))
94
+ const path = directoryRoutePath(relativeDir)
95
+ assertRouteIsAvailable(path, relativePath)
96
+ pages.push({ path, filePath: join(dir, pageEntry.name), relativePath })
97
+ }
40
98
 
41
- const fullPath = join(dir, name)
99
+ if (relativeDir) {
100
+ const layoutEntry = visibleEntries.find(
101
+ (entry) => entry.isFile() && entry.name === "layout.tsx"
102
+ )
103
+ if (layoutEntry) {
104
+ layouts.push({
105
+ path: directoryRoutePath(relativeDir),
106
+ filePath: join(dir, layoutEntry.name),
107
+ relativePath: normalizeRelativePath(join(relativeDir, layoutEntry.name)),
108
+ })
109
+ }
110
+ }
42
111
 
43
- if (entry.isDirectory()) {
44
- await walkDir(fullPath, appDir, routes)
45
- continue
112
+ for (const entry of visibleEntries) {
113
+ if (!entry.isDirectory()) continue
114
+ // `app/public/` is the static asset root, never part of the file router.
115
+ if (!relativeDir && entry.name === "public") continue
116
+ await walkDir(join(dir, entry.name), appDir, pages, layouts)
117
+ }
118
+ }
119
+
120
+ async function readDirectory(dir: string): Promise<import("node:fs").Dirent[] | null> {
121
+ try {
122
+ return (await readdir(dir, { withFileTypes: true })) as import("node:fs").Dirent[]
123
+ } catch (error) {
124
+ if (isNotFoundError(error)) return null
125
+ throw error
126
+ }
127
+ }
128
+
129
+ function validateChildDirectories(
130
+ entries: readonly import("node:fs").Dirent[],
131
+ relativeDir: string
132
+ ): void {
133
+ const claimedSegments = new Map<string, string>()
134
+
135
+ for (const entry of entries) {
136
+ if (!entry.isDirectory()) continue
137
+ const segment = routeSegment(entry.name, join(relativeDir, entry.name))
138
+ const key = segment.startsWith(":") ? ":" : segment.toLowerCase()
139
+ const existing = claimedSegments.get(key)
140
+ if (existing && existing !== entry.name) {
141
+ const parent = relativeDir ? displayAppPath(relativeDir) : "app/"
142
+ throw new Error(
143
+ `[SixbCustomApp] Ambiguous route directories '${existing}' and '${entry.name}' under ${parent}. They match the same URL segment.`
144
+ )
46
145
  }
146
+ claimedSegments.set(key, entry.name)
147
+ }
148
+ }
47
149
 
48
- if (!entry.isFile()) continue
49
- const isPageModule = name === "page.tsx" || name === "page.ts"
50
- if (!isPageModule) continue
150
+ function directoryRoutePath(relativeDir: string): string {
151
+ if (!relativeDir) return "/"
152
+ return `/${relativeDir
153
+ .split("/")
154
+ .map((segment) => routeSegment(segment, relativeDir))
155
+ .join("/")}`
156
+ }
51
157
 
52
- const relativePath = relative(appDir, fullPath)
53
- const routePath = filePathToRoutePath(relativePath)
158
+ function routeSegment(segment: string, relativePath: string): string {
159
+ const dynamic = dynamicSegmentPattern.exec(segment)
160
+ if (dynamic) return `:${dynamic[1]}`
54
161
 
55
- routes.push({
56
- path: routePath,
57
- filePath: fullPath,
58
- relativePath,
59
- })
162
+ if (segment.includes("[") || segment.includes("]")) {
163
+ throw new Error(
164
+ `[SixbCustomApp] Invalid dynamic route directory ${displayAppPath(relativePath)}. Use one name such as '[id]'; catch-all and partial dynamic segments are not supported.`
165
+ )
166
+ }
167
+ if (segment.includes("(") || segment.includes(")")) {
168
+ throw new Error(
169
+ `[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Route groups are not supported yet; use a normal directory name.`
170
+ )
60
171
  }
172
+ if (/[:*?]/.test(segment)) {
173
+ throw new Error(
174
+ `[SixbCustomApp] Invalid route directory ${displayAppPath(relativePath)}. Use '[name]' for a dynamic segment; ':', '*' and '?' are reserved by React Router.`
175
+ )
176
+ }
177
+
178
+ return segment
179
+ }
180
+
181
+ function assertRouteIsAvailable(path: string, relativePath: string): void {
182
+ const normalizedPath = path.toLowerCase()
183
+ const reserved =
184
+ reservedRoutePaths.has(normalizedPath) ||
185
+ reservedRoutePrefixes.some(
186
+ (prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)
187
+ )
188
+ if (!reserved) return
189
+
190
+ throw new Error(
191
+ `[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, and /app.webmanifest.`
192
+ )
61
193
  }
62
194
 
63
- function filePathToRoutePath(filePath: string): string {
64
- // Remove extension
65
- let route = filePath.replace(/\.(tsx|ts)$/, "")
195
+ function routeSegments(path: string): string[] {
196
+ return path === "/" ? [] : path.replace(/^\/+|\/+$/g, "").split("/")
197
+ }
66
198
 
67
- // Normalize path separators
68
- route = route.split("\\").join("/")
199
+ function normalizeRelativePath(path: string): string {
200
+ return path
201
+ .split("\\")
202
+ .join("/")
203
+ .replace(/^\.\/$/, "")
204
+ }
69
205
 
70
- // Convert [param] to :param
71
- route = route.replace(/\[([^\]]+)\]/g, ":$1")
206
+ function displayAppPath(path: string): string {
207
+ const normalized = normalizeRelativePath(path)
208
+ return normalized ? `app/${normalized}` : "app/"
209
+ }
72
210
 
73
- // Remove trailing /page
74
- if (route === "page") return "/"
75
- route = route.replace(/\/page$/, "")
211
+ function compareRouteModules(
212
+ a: Pick<PageRoute, "path" | "relativePath">,
213
+ b: Pick<PageRoute, "path" | "relativePath">
214
+ ): number {
215
+ return compareText(a.path, b.path) || compareText(a.relativePath, b.relativePath)
216
+ }
76
217
 
77
- // Ensure leading slash
78
- if (!route.startsWith("/")) route = `/${route}`
218
+ function compareText(a: string, b: string): number {
219
+ return a < b ? -1 : a > b ? 1 : 0
220
+ }
79
221
 
80
- return route
222
+ function isNotFoundError(error: unknown): boolean {
223
+ if (!(error instanceof Error)) return false
224
+ const code = (error as NodeJS.ErrnoException).code
225
+ return code === "ENOENT" || code === "ENOTDIR"
81
226
  }