@sixb/app 0.1.1 → 0.1.3

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/build.ts CHANGED
@@ -1,11 +1,23 @@
1
- import { copyFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
2
- import { basename, dirname, join } from "node:path"
1
+ import { existsSync } from "node:fs"
2
+ import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises"
3
+ import { basename, dirname, extname, join, resolve } from "node:path"
4
+ import { promisify } from "node:util"
5
+ import {
6
+ brotliCompress as brotliCompressCallback,
7
+ gzip as gzipCallback,
8
+ constants as zlibConstants,
9
+ } from "node:zlib"
3
10
 
4
11
  const STATIC_ASSET_ORIGIN = "https://sixb-static.invalid"
12
+ const brotliCompress = promisify(brotliCompressCallback)
13
+ const gzip = promisify(gzipCallback)
14
+ const PRECOMPRESSION_CONCURRENCY = 4
5
15
 
6
16
  export interface BuildAppOptions {
7
17
  /** Path to the generated index.html entry point */
8
18
  entryPath: string
19
+ /** Browser TypeScript entry generated alongside `entryPath`. */
20
+ scriptEntryPath: string
9
21
  /** Generated manifest copied to the stable `/app.webmanifest` output path. */
10
22
  manifestPath?: string
11
23
  /** Output directory, defaults to `.sixb/dist/app` */
@@ -18,9 +30,17 @@ export interface BuildAppResult {
18
30
  logs?: string[]
19
31
  }
20
32
 
33
+ export interface BuildAuthExperienceOptions {
34
+ /** Generated HTML shell containing the auth bootstrap placeholder. */
35
+ entryPath: string
36
+ /** Browser TypeScript entry generated alongside `entryPath`. */
37
+ scriptEntryPath: string
38
+ /** Directory written for the API server to mount under `/auth`. */
39
+ outdir: string
40
+ }
41
+
21
42
  /**
22
- * Builds the app using `Bun.build()` on the generated HTML entry point.
23
- * Outputs a production-ready static bundle.
43
+ * Builds the generated browser entry and writes a production-ready static shell and bundle.
24
44
  */
25
45
  export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
26
46
  const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app")
@@ -29,26 +49,31 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
29
49
  await rm(outdir, { recursive: true, force: true })
30
50
  await mkdir(outdir, { recursive: true })
31
51
 
32
- const bundleEntryPath = await prepareAppHtmlBundleEntry(options.entryPath)
33
- let result: Awaited<ReturnType<typeof Bun.build>>
34
- try {
35
- result = await Bun.build({
36
- entrypoints: [bundleEntryPath],
37
- outdir,
38
- target: "browser",
39
- conditions: ["bun"],
40
- publicPath: "/",
41
- minify: true,
42
- // React is bundled into this browser output, so without pinning NODE_ENV the production build
43
- // of a user's app ships React's development build: dev-only checks on every render, and the
44
- // warnings that go with them. This is also the only knob that selects the production JSX
45
- // runtime — an ambient NODE_ENV does not.
46
- define: { "process.env.NODE_ENV": '"production"' },
47
- sourcemap: "external",
48
- })
49
- } finally {
50
- await rm(bundleEntryPath, { force: true })
51
- }
52
+ const result = await Bun.build({
53
+ // Build the script entry directly rather than Bun's HTML entry. Bun cannot currently preserve
54
+ // a large dynamic-import graph reliably when splitting an HTML entry: one of the lazy chunks
55
+ // can be written into the shell's script tag. Building TypeScript directly also lets Shiki's
56
+ // hundreds of grammars remain off the initial custom-app path.
57
+ entrypoints: [options.scriptEntryPath],
58
+ outdir,
59
+ target: "browser",
60
+ conditions: ["bun"],
61
+ publicPath: "/",
62
+ minify: true,
63
+ splitting: true,
64
+ naming: {
65
+ entry: "app-[hash].[ext]",
66
+ chunk: "chunk-[name]-[hash].[ext]",
67
+ asset: "asset-[name]-[hash].[ext]",
68
+ },
69
+ plugins: [extensionlessSourceImportPlugin],
70
+ // React is bundled into this browser output, so without pinning NODE_ENV the production build
71
+ // of a user's app ships React's development build: dev-only checks on every render, and the
72
+ // warnings that go with them. This is also the only knob that selects the production JSX
73
+ // runtime — an ambient NODE_ENV does not.
74
+ define: { "process.env.NODE_ENV": '"production"' },
75
+ sourcemap: "external",
76
+ })
52
77
 
53
78
  if (!result.success) {
54
79
  return {
@@ -58,12 +83,106 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
58
83
  }
59
84
  }
60
85
 
61
- const bundleHtmlPath = join(outdir, basename(bundleEntryPath))
62
- await rename(bundleHtmlPath, join(outdir, "index.html"))
63
- await rewriteIndexAssetPaths(outdir)
86
+ const script = result.outputs.find(
87
+ (output) => output.kind === "entry-point" && output.type.startsWith("text/javascript")
88
+ )
89
+ const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"))
90
+ if (!script || stylesheets.length > 1) {
91
+ throw new Error(
92
+ `[SixbCustomApp] Expected one browser entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`
93
+ )
94
+ }
95
+
96
+ const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"))
97
+ const sourceEntryPattern =
98
+ /\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/
99
+ if (!sourceEntryPattern.test(sourceHtml)) {
100
+ throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.")
101
+ }
102
+
103
+ const assetTags = [
104
+ ...stylesheets.map(
105
+ (stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`
106
+ ),
107
+ `<script type="module" crossorigin src="/${basename(script.path)}"></script>`,
108
+ ].join("")
109
+ const html = withLoadingShell(sourceHtml)
110
+ .replace(sourceEntryPattern, "")
111
+ .replace("</head>", ` ${assetTags}</head>`)
112
+ await writeFile(join(outdir, "index.html"), html, "utf-8")
113
+
64
114
  if (options.manifestPath) {
65
115
  await copyFile(options.manifestPath, join(outdir, "app.webmanifest"))
66
116
  }
117
+ await precompressBuildAssets(result.outputs)
118
+
119
+ return { success: true, outdir }
120
+ }
121
+
122
+ /** Builds the optional custom auth entry as API-served static assets. */
123
+ export async function buildAuthExperience(
124
+ options: BuildAuthExperienceOptions
125
+ ): Promise<BuildAppResult> {
126
+ const outdir = resolve(options.outdir)
127
+ const assetsDir = join(outdir, "assets")
128
+ await rm(outdir, { recursive: true, force: true })
129
+ await mkdir(assetsDir, { recursive: true })
130
+
131
+ const result = await Bun.build({
132
+ entrypoints: [options.scriptEntryPath],
133
+ outdir: assetsDir,
134
+ target: "browser",
135
+ conditions: ["bun"],
136
+ publicPath: "/auth/assets/",
137
+ minify: true,
138
+ splitting: true,
139
+ naming: {
140
+ entry: "auth-[hash].[ext]",
141
+ chunk: "chunk-[name]-[hash].[ext]",
142
+ asset: "asset-[name]-[hash].[ext]",
143
+ },
144
+ plugins: [extensionlessSourceImportPlugin],
145
+ define: { "process.env.NODE_ENV": '"production"' },
146
+ sourcemap: "external",
147
+ })
148
+
149
+ if (!result.success) {
150
+ return {
151
+ success: false,
152
+ outdir,
153
+ logs: result.logs.map(String),
154
+ }
155
+ }
156
+
157
+ const script = result.outputs.find(
158
+ (output) => output.kind === "entry-point" && output.type.startsWith("text/javascript")
159
+ )
160
+ const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"))
161
+ if (!script || stylesheets.length > 1) {
162
+ throw new Error(
163
+ `[SixbCustomApp] Expected one auth entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`
164
+ )
165
+ }
166
+
167
+ const sourceHtml = await readFile(options.entryPath, "utf-8")
168
+ const sourceEntryPattern =
169
+ /\s*<script\s+type=["']module["']\s+src=["']\.\/auth-main\.tsx["']><\/script>/
170
+ if (!sourceEntryPattern.test(sourceHtml)) {
171
+ throw new Error("[SixbCustomApp] Generated auth shell is missing its ./auth-main.tsx entry.")
172
+ }
173
+
174
+ const assetTags = [
175
+ ...stylesheets.map(
176
+ (stylesheet) =>
177
+ `<link rel="stylesheet" crossorigin href="/auth/assets/${basename(stylesheet.path)}">`
178
+ ),
179
+ `<script type="module" crossorigin src="/auth/assets/${basename(script.path)}"></script>`,
180
+ ].join("")
181
+ const html = sourceHtml
182
+ .replace(sourceEntryPattern, "")
183
+ .replace("</head>", ` ${assetTags}</head>`)
184
+ await writeFile(join(outdir, "index.html"), html, "utf-8")
185
+ await precompressBuildAssets(result.outputs)
67
186
 
68
187
  return { success: true, outdir }
69
188
  }
@@ -86,20 +205,79 @@ export function restoreAppStaticUrls(html: string): string {
86
205
  return html.replaceAll(STATIC_ASSET_ORIGIN, "")
87
206
  }
88
207
 
89
- async function rewriteIndexAssetPaths(outdir: string): Promise<void> {
90
- const indexPath = join(outdir, "index.html")
91
- const originalHtml = await readFile(indexPath, "utf-8")
92
- const html = restoreAppStaticUrls(originalHtml)
208
+ function withLoadingShell(html: string): string {
209
+ const styles = `<style data-sixb-loading-shell>
210
+ .sixb-loading-shell{position:fixed;inset:0;display:grid;place-items:center;background:#fff;color:#71717a}
211
+ .sixb-loading-spinner{width:1.25rem;height:1.25rem;border:2px solid currentColor;border-right-color:transparent;border-radius:9999px;animation:sixb-loading-spin .7s linear infinite}
212
+ @media(prefers-color-scheme:dark){.sixb-loading-shell{background:#09090b;color:#a1a1aa}}
213
+ @media(prefers-reduced-motion:reduce){.sixb-loading-spinner{animation-duration:1.5s}}
214
+ @keyframes sixb-loading-spin{to{transform:rotate(360deg)}}
215
+ </style>`
216
+ const root =
217
+ '<div id="root"><div class="sixb-loading-shell" role="status" aria-label="Loading application"><span class="sixb-loading-spinner" aria-hidden="true"></span></div></div>'
93
218
 
94
- const rewritten = html.replace(
95
- /(href|src)=(["'])((?!\/|#|[a-zA-Z][a-zA-Z\d+.-]*:)(?:\.\/)?[^"'?#]+(?:[?#][^"']*)?)\2/g,
96
- (_match, attr: string, quote: string, url: string) => {
97
- const normalized = url.startsWith("./") ? url.slice(2) : url
98
- return `${attr}=${quote}/${normalized}${quote}`
99
- }
100
- )
219
+ if (!html.includes('<div id="root"></div>') || !html.includes("</head>")) {
220
+ throw new Error("[SixbCustomApp] Generated app shell is missing its root or head element.")
221
+ }
101
222
 
102
- if (rewritten !== originalHtml) {
103
- await writeFile(indexPath, rewritten, "utf-8")
223
+ return html.replace("</head>", `${styles}\n </head>`).replace('<div id="root"></div>', root)
224
+ }
225
+
226
+ const extensionlessSourceImportPlugin: Bun.BunPlugin = {
227
+ name: "sixb-extensionless-source-imports",
228
+ setup(build) {
229
+ // A direct TypeScript entry with splitting exposes a Bun 1.3 resolver edge in linked workspace
230
+ // packages: extensionless relative imports such as `../json` can fail even though `json.ts`
231
+ // exists. HTML entries masked it, but HTML splitting can point at the wrong dynamic chunk.
232
+ build.onResolve({ filter: /^\.\.?\// }, (args) => {
233
+ if (extname(args.path)) return undefined
234
+
235
+ const base = resolve(dirname(args.importer), args.path)
236
+ for (const candidate of [
237
+ `${base}.ts`,
238
+ `${base}.tsx`,
239
+ `${base}.js`,
240
+ `${base}.jsx`,
241
+ join(base, "index.ts"),
242
+ join(base, "index.tsx"),
243
+ join(base, "index.js"),
244
+ join(base, "index.jsx"),
245
+ ]) {
246
+ if (existsSync(candidate)) return { path: candidate }
247
+ }
248
+
249
+ return undefined
250
+ })
251
+ },
252
+ }
253
+
254
+ async function precompressBuildAssets(
255
+ outputs: readonly { readonly path: string; readonly type: string }[]
256
+ ): Promise<void> {
257
+ const paths = outputs
258
+ .filter(
259
+ (output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")
260
+ )
261
+ .map((output) => output.path)
262
+ let cursor = 0
263
+
264
+ const worker = async () => {
265
+ while (cursor < paths.length) {
266
+ const path = paths[cursor++]
267
+ const bytes = await Bun.file(path).arrayBuffer()
268
+ const [brotli, gzipped] = await Promise.all([
269
+ brotliCompress(bytes, {
270
+ params: {
271
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 5,
272
+ },
273
+ }),
274
+ gzip(bytes, { level: 9 }),
275
+ ])
276
+ await Promise.all([writeFile(`${path}.br`, brotli), writeFile(`${path}.gz`, gzipped)])
277
+ }
104
278
  }
279
+
280
+ await Promise.all(
281
+ Array.from({ length: Math.min(PRECOMPRESSION_CONCURRENCY, paths.length) }, worker)
282
+ )
105
283
  }
package/src/codegen.ts CHANGED
@@ -16,6 +16,8 @@ export interface GenerateRouteManifestOptions {
16
16
  readonly builtInRoutes?: readonly BuiltInRouteManifestEntry[]
17
17
  }
18
18
 
19
+ export const AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__"
20
+
19
21
  /**
20
22
  * Generates `.sixb/generated/routes.ts` with static route imports. Pages are
21
23
  * eager on purpose: project-specific apps bundle small, and a single bundle
@@ -69,6 +71,143 @@ ${routeEntries}
69
71
  return outPath
70
72
  }
71
73
 
74
+ /** Generates the optional browser entry served by the API for `/auth/*`. */
75
+ export async function generateAuthExperienceEntry(
76
+ projectRoot: string,
77
+ generatedDir: string,
78
+ options: {
79
+ readonly appDir?: string
80
+ readonly publicDir?: string
81
+ readonly stylesheetPath?: string | null
82
+ } = {}
83
+ ): Promise<{ readonly htmlPath: string; readonly mainPath: string } | null> {
84
+ await mkdir(generatedDir, { recursive: true })
85
+
86
+ const appDir = options.appDir ? resolve(projectRoot, options.appDir) : join(projectRoot, "app")
87
+ const authPath = join(appDir, "auth.tsx")
88
+ if (!(await fileExists(authPath))) {
89
+ return null
90
+ }
91
+
92
+ const publicDir = options.publicDir
93
+ ? resolve(projectRoot, options.publicDir)
94
+ : join(appDir, "public")
95
+ const layoutPath = join(appDir, "layout.tsx")
96
+ const globalsCssPath = join(appDir, "globals.css")
97
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir })
98
+ const stylesheetPath =
99
+ options.stylesheetPath !== undefined
100
+ ? options.stylesheetPath
101
+ : (await fileExists(globalsCssPath))
102
+ ? globalsCssPath
103
+ : null
104
+ const stylesheetImport = stylesheetPath
105
+ ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}`
106
+ : ""
107
+ const authRel = relativeTo(generatedDir, authPath)
108
+
109
+ const mainContent = `import React from "react"
110
+ import { createRoot } from "react-dom/client"
111
+ import type {
112
+ AuthExperienceActions,
113
+ AuthExperienceState,
114
+ } from "@sixb/app/auth"
115
+ import AuthExperience from ${JSON.stringify(authRel)}
116
+ ${stylesheetImport}
117
+
118
+ interface AuthExperienceBootstrap {
119
+ readonly state: AuthExperienceState
120
+ readonly signInUrl: string
121
+ readonly submission?: {
122
+ readonly kind: "requestMagicLink" | "confirmSignIn"
123
+ readonly action: string
124
+ readonly fields: Readonly<Record<string, string>>
125
+ }
126
+ }
127
+
128
+ const root = document.getElementById("root")
129
+ if (!root) {
130
+ throw new Error("[SixbApp] Could not find the auth experience root element.")
131
+ }
132
+
133
+ const encodedBootstrap = root.dataset.sixbAuth
134
+ if (!encodedBootstrap) {
135
+ throw new Error("[SixbApp] Auth experience bootstrap is missing.")
136
+ }
137
+
138
+ const bootstrap = decodeBootstrap(encodedBootstrap)
139
+ const actions: AuthExperienceActions = {
140
+ requestMagicLink(email) {
141
+ submit("requestMagicLink", { email })
142
+ },
143
+ confirmSignIn() {
144
+ submit("confirmSignIn")
145
+ },
146
+ restartSignIn() {
147
+ window.location.assign(bootstrap.signInUrl)
148
+ },
149
+ }
150
+
151
+ function submit(
152
+ kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
153
+ additionalFields: Readonly<Record<string, string>> = {}
154
+ ): void {
155
+ const submission = bootstrap.submission
156
+ if (!submission || submission.kind !== kind) {
157
+ throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
158
+ }
159
+
160
+ const form = document.createElement("form")
161
+ form.method = "post"
162
+ form.action = submission.action
163
+ form.hidden = true
164
+ for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
165
+ const input = document.createElement("input")
166
+ input.type = "hidden"
167
+ input.name = name
168
+ input.value = value
169
+ form.append(input)
170
+ }
171
+ document.body.append(form)
172
+ form.submit()
173
+ }
174
+
175
+ function decodeBootstrap(value: string): AuthExperienceBootstrap {
176
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
177
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
178
+ const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
179
+ return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
180
+ }
181
+
182
+ createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
183
+ `
184
+
185
+ const mainPath = join(generatedDir, "auth-main.tsx")
186
+ await writeFileIfChanged(mainPath, mainContent)
187
+
188
+ const htmlContent = `<!DOCTYPE html>
189
+ <html lang="en">
190
+ <head>
191
+ <meta charset="UTF-8" />
192
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
193
+ ${renderAuthMetadataHead(metadata)}
194
+ <style>
195
+ * { box-sizing: border-box; }
196
+ html, body, #root { margin: 0; min-height: 100%; }
197
+ body, #root { min-height: 100vh; min-height: 100dvh; }
198
+ </style>
199
+ </head>
200
+ <body>
201
+ <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
202
+ <script type="module" src="./auth-main.tsx"></script>
203
+ </body>
204
+ </html>
205
+ `
206
+ const htmlPath = join(generatedDir, "auth-index.html")
207
+ await writeFileIfChanged(htmlPath, htmlContent)
208
+ return { htmlPath, mainPath }
209
+ }
210
+
72
211
  /**
73
212
  * Generates the app entry files:
74
213
  * - `.sixb/generated/index.html` — HTML shell
@@ -540,6 +679,20 @@ function renderMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetada
540
679
  return tags.join("\n")
541
680
  }
542
681
 
682
+ function renderAuthMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetadata>>): string {
683
+ const tags = [
684
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
685
+ ...(metadata.description
686
+ ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`]
687
+ : []),
688
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
689
+ ...(metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon)
690
+ ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`]
691
+ : []),
692
+ ]
693
+ return tags.join("\n")
694
+ }
695
+
543
696
  function escapeHtmlText(value: string): string {
544
697
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
545
698
  }