@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/dist/index.js CHANGED
@@ -1,34 +1,45 @@
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";
5
- import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve2 } from "path";
4
+ import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
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
- import { copyFile, mkdir, readFile, rename, rm, writeFile } from "fs/promises";
10
- import { basename, dirname, join } from "path";
9
+ import { existsSync } from "fs";
10
+ import { copyFile, mkdir, readFile, rm, writeFile } from "fs/promises";
11
+ import { basename, dirname, extname, join, resolve } from "path";
12
+ import { promisify } from "util";
13
+ import {
14
+ brotliCompress as brotliCompressCallback,
15
+ gzip as gzipCallback,
16
+ constants as zlibConstants
17
+ } from "zlib";
11
18
  var STATIC_ASSET_ORIGIN = "https://sixb-static.invalid";
19
+ var brotliCompress = promisify(brotliCompressCallback);
20
+ var gzip = promisify(gzipCallback);
21
+ var PRECOMPRESSION_CONCURRENCY = 4;
12
22
  async function buildApp(options) {
13
23
  const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app");
14
24
  await rm(outdir, { recursive: true, force: true });
15
25
  await mkdir(outdir, { recursive: true });
16
- const bundleEntryPath = await prepareAppHtmlBundleEntry(options.entryPath);
17
- let result;
18
- try {
19
- result = await Bun.build({
20
- entrypoints: [bundleEntryPath],
21
- outdir,
22
- target: "browser",
23
- conditions: ["bun"],
24
- publicPath: "/",
25
- minify: true,
26
- define: { "process.env.NODE_ENV": '"production"' },
27
- sourcemap: "external"
28
- });
29
- } finally {
30
- await rm(bundleEntryPath, { force: true });
31
- }
26
+ const result = await Bun.build({
27
+ entrypoints: [options.scriptEntryPath],
28
+ outdir,
29
+ target: "browser",
30
+ conditions: ["bun"],
31
+ publicPath: "/",
32
+ minify: true,
33
+ splitting: true,
34
+ naming: {
35
+ entry: "app-[hash].[ext]",
36
+ chunk: "chunk-[name]-[hash].[ext]",
37
+ asset: "asset-[name]-[hash].[ext]"
38
+ },
39
+ plugins: [extensionlessSourceImportPlugin],
40
+ define: { "process.env.NODE_ENV": '"production"' },
41
+ sourcemap: "external"
42
+ });
32
43
  if (!result.success) {
33
44
  return {
34
45
  success: false,
@@ -36,12 +47,74 @@ async function buildApp(options) {
36
47
  logs: result.logs.map(String)
37
48
  };
38
49
  }
39
- const bundleHtmlPath = join(outdir, basename(bundleEntryPath));
40
- await rename(bundleHtmlPath, join(outdir, "index.html"));
41
- await rewriteIndexAssetPaths(outdir);
50
+ const script = result.outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
51
+ const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"));
52
+ if (!script || stylesheets.length > 1) {
53
+ throw new Error(`[SixbCustomApp] Expected one browser entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
54
+ }
55
+ const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"));
56
+ const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/;
57
+ if (!sourceEntryPattern.test(sourceHtml)) {
58
+ throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.");
59
+ }
60
+ const assetTags = [
61
+ ...stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`),
62
+ `<script type="module" crossorigin src="/${basename(script.path)}"></script>`
63
+ ].join("");
64
+ const html = withLoadingShell(sourceHtml).replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
65
+ await writeFile(join(outdir, "index.html"), html, "utf-8");
42
66
  if (options.manifestPath) {
43
67
  await copyFile(options.manifestPath, join(outdir, "app.webmanifest"));
44
68
  }
69
+ await precompressBuildAssets(result.outputs);
70
+ return { success: true, outdir };
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);
45
118
  return { success: true, outdir };
46
119
  }
47
120
  async function prepareAppHtmlBundleEntry(entryPath) {
@@ -54,22 +127,69 @@ async function prepareAppHtmlBundleEntry(entryPath) {
54
127
  function restoreAppStaticUrls(html) {
55
128
  return html.replaceAll(STATIC_ASSET_ORIGIN, "");
56
129
  }
57
- async function rewriteIndexAssetPaths(outdir) {
58
- const indexPath = join(outdir, "index.html");
59
- const originalHtml = await readFile(indexPath, "utf-8");
60
- const html = restoreAppStaticUrls(originalHtml);
61
- const rewritten = html.replace(/(href|src)=(["'])((?!\/|#|[a-zA-Z][a-zA-Z\d+.-]*:)(?:\.\/)?[^"'?#]+(?:[?#][^"']*)?)\2/g, (_match, attr, quote, url) => {
62
- const normalized = url.startsWith("./") ? url.slice(2) : url;
63
- return `${attr}=${quote}/${normalized}${quote}`;
64
- });
65
- if (rewritten !== originalHtml) {
66
- await writeFile(indexPath, rewritten, "utf-8");
130
+ function withLoadingShell(html) {
131
+ const styles = `<style data-sixb-loading-shell>
132
+ .sixb-loading-shell{position:fixed;inset:0;display:grid;place-items:center;background:#fff;color:#71717a}
133
+ .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}
134
+ @media(prefers-color-scheme:dark){.sixb-loading-shell{background:#09090b;color:#a1a1aa}}
135
+ @media(prefers-reduced-motion:reduce){.sixb-loading-spinner{animation-duration:1.5s}}
136
+ @keyframes sixb-loading-spin{to{transform:rotate(360deg)}}
137
+ </style>`;
138
+ const root = '<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>';
139
+ if (!html.includes('<div id="root"></div>') || !html.includes("</head>")) {
140
+ throw new Error("[SixbCustomApp] Generated app shell is missing its root or head element.");
141
+ }
142
+ return html.replace("</head>", `${styles}
143
+ </head>`).replace('<div id="root"></div>', root);
144
+ }
145
+ var extensionlessSourceImportPlugin = {
146
+ name: "sixb-extensionless-source-imports",
147
+ setup(build) {
148
+ build.onResolve({ filter: /^\.\.?\// }, (args) => {
149
+ if (extname(args.path))
150
+ return;
151
+ const base = resolve(dirname(args.importer), args.path);
152
+ for (const candidate of [
153
+ `${base}.ts`,
154
+ `${base}.tsx`,
155
+ `${base}.js`,
156
+ `${base}.jsx`,
157
+ join(base, "index.ts"),
158
+ join(base, "index.tsx"),
159
+ join(base, "index.js"),
160
+ join(base, "index.jsx")
161
+ ]) {
162
+ if (existsSync(candidate))
163
+ return { path: candidate };
164
+ }
165
+ return;
166
+ });
67
167
  }
168
+ };
169
+ async function precompressBuildAssets(outputs) {
170
+ const paths = outputs.filter((output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")).map((output) => output.path);
171
+ let cursor = 0;
172
+ const worker = async () => {
173
+ while (cursor < paths.length) {
174
+ const path = paths[cursor++];
175
+ const bytes = await Bun.file(path).arrayBuffer();
176
+ const [brotli, gzipped] = await Promise.all([
177
+ brotliCompress(bytes, {
178
+ params: {
179
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 5
180
+ }
181
+ }),
182
+ gzip(bytes, { level: 9 })
183
+ ]);
184
+ await Promise.all([writeFile(`${path}.br`, brotli), writeFile(`${path}.gz`, gzipped)]);
185
+ }
186
+ };
187
+ await Promise.all(Array.from({ length: Math.min(PRECOMPRESSION_CONCURRENCY, paths.length) }, worker));
68
188
  }
69
189
 
70
190
  // src/codegen.ts
71
191
  import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
72
- import { join as join3, relative, resolve } from "path";
192
+ import { join as join3, relative, resolve as resolve2 } from "path";
73
193
 
74
194
  // src/manifest.ts
75
195
  function renderAppManifest(metadata) {
@@ -92,7 +212,7 @@ function renderAppManifest(metadata) {
92
212
  import { createHash } from "crypto";
93
213
  import { readFile as readFile2, stat } from "fs/promises";
94
214
  import { createRequire } from "module";
95
- import { extname, join as join2 } from "path";
215
+ import { extname as extname2, join as join2 } from "path";
96
216
  import { pathToFileURL } from "url";
97
217
  var metadataRequire = createRequire(import.meta.url);
98
218
  var metadataFields = [
@@ -201,7 +321,7 @@ function inferImageMimeType(url) {
201
321
  try {
202
322
  pathname = new URL(url, "https://sixb.invalid").pathname;
203
323
  } catch {}
204
- switch (extname(pathname).toLowerCase()) {
324
+ switch (extname2(pathname).toLowerCase()) {
205
325
  case ".svg":
206
326
  return "image/svg+xml";
207
327
  case ".png":
@@ -234,6 +354,7 @@ function renderCustomAppRuntimeScript(config) {
234
354
  }
235
355
 
236
356
  // src/codegen.ts
357
+ var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
237
358
  async function generateRouteManifest(routes, generatedDir, options = {}) {
238
359
  await mkdir2(generatedDir, { recursive: true });
239
360
  const imports = routes.map((route, index) => {
@@ -267,10 +388,123 @@ ${routeEntries}
267
388
  await writeFileIfChanged(outPath, content);
268
389
  return outPath;
269
390
  }
391
+ async function generateAuthExperienceEntry(projectRoot, generatedDir, options = {}) {
392
+ await mkdir2(generatedDir, { recursive: true });
393
+ const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join3(projectRoot, "app");
394
+ const authPath = join3(appDir, "auth.tsx");
395
+ if (!await fileExists2(authPath)) {
396
+ return null;
397
+ }
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");
401
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir });
402
+ const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
403
+ const stylesheetImport = stylesheetPath ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}` : "";
404
+ const authRel = relativeTo(generatedDir, authPath);
405
+ const mainContent = `import React from "react"
406
+ import { createRoot } from "react-dom/client"
407
+ import type {
408
+ AuthExperienceActions,
409
+ AuthExperienceState,
410
+ } from "@sixb/app/auth"
411
+ import AuthExperience from ${JSON.stringify(authRel)}
412
+ ${stylesheetImport}
413
+
414
+ interface AuthExperienceBootstrap {
415
+ readonly state: AuthExperienceState
416
+ readonly signInUrl: string
417
+ readonly submission?: {
418
+ readonly kind: "requestMagicLink" | "confirmSignIn"
419
+ readonly action: string
420
+ readonly fields: Readonly<Record<string, string>>
421
+ }
422
+ }
423
+
424
+ const root = document.getElementById("root")
425
+ if (!root) {
426
+ throw new Error("[SixbApp] Could not find the auth experience root element.")
427
+ }
428
+
429
+ const encodedBootstrap = root.dataset.sixbAuth
430
+ if (!encodedBootstrap) {
431
+ throw new Error("[SixbApp] Auth experience bootstrap is missing.")
432
+ }
433
+
434
+ const bootstrap = decodeBootstrap(encodedBootstrap)
435
+ const actions: AuthExperienceActions = {
436
+ requestMagicLink(email) {
437
+ submit("requestMagicLink", { email })
438
+ },
439
+ confirmSignIn() {
440
+ submit("confirmSignIn")
441
+ },
442
+ restartSignIn() {
443
+ window.location.assign(bootstrap.signInUrl)
444
+ },
445
+ }
446
+
447
+ function submit(
448
+ kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
449
+ additionalFields: Readonly<Record<string, string>> = {}
450
+ ): void {
451
+ const submission = bootstrap.submission
452
+ if (!submission || submission.kind !== kind) {
453
+ throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
454
+ }
455
+
456
+ const form = document.createElement("form")
457
+ form.method = "post"
458
+ form.action = submission.action
459
+ form.hidden = true
460
+ for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
461
+ const input = document.createElement("input")
462
+ input.type = "hidden"
463
+ input.name = name
464
+ input.value = value
465
+ form.append(input)
466
+ }
467
+ document.body.append(form)
468
+ form.submit()
469
+ }
470
+
471
+ function decodeBootstrap(value: string): AuthExperienceBootstrap {
472
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
473
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
474
+ const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
475
+ return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
476
+ }
477
+
478
+ createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
479
+ `;
480
+ const mainPath = join3(generatedDir, "auth-main.tsx");
481
+ await writeFileIfChanged(mainPath, mainContent);
482
+ const htmlContent = `<!DOCTYPE html>
483
+ <html lang="en">
484
+ <head>
485
+ <meta charset="UTF-8" />
486
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
487
+ ${renderAuthMetadataHead(metadata)}
488
+ <style>
489
+ * { box-sizing: border-box; }
490
+ html, body, #root { margin: 0; min-height: 100%; }
491
+ body, #root { min-height: 100vh; min-height: 100dvh; }
492
+ </style>
493
+ </head>
494
+ <body>
495
+ <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
496
+ <script type="module" src="./auth-main.tsx"></script>
497
+ </body>
498
+ </html>
499
+ `;
500
+ const htmlPath = join3(generatedDir, "auth-index.html");
501
+ await writeFileIfChanged(htmlPath, htmlContent);
502
+ return { htmlPath, mainPath };
503
+ }
270
504
  async function generateAppEntry(projectRoot, generatedDir, options = {}) {
271
505
  await mkdir2(generatedDir, { recursive: true });
272
- const appDir = options.appDir ? resolve(projectRoot, options.appDir) : join3(projectRoot, "app");
273
- const publicDir = options.publicDir ? resolve(projectRoot, options.publicDir) : join3(appDir, "public");
506
+ const appDir = options.appDir ? resolve2(projectRoot, options.appDir) : join3(projectRoot, "app");
507
+ const publicDir = options.publicDir ? resolve2(projectRoot, options.publicDir) : join3(appDir, "public");
274
508
  const globalsCssPath = join3(appDir, "globals.css");
275
509
  const layoutPath = join3(appDir, "layout.tsx");
276
510
  const metadata = await resolveAppMetadata({ layoutPath, publicDir });
@@ -689,6 +923,16 @@ function renderMetadataHead(metadata) {
689
923
  return tags.join(`
690
924
  `);
691
925
  }
926
+ function renderAuthMetadataHead(metadata) {
927
+ const tags = [
928
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
929
+ ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
930
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
931
+ ...metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon) ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : []
932
+ ];
933
+ return tags.join(`
934
+ `);
935
+ }
692
936
  function escapeHtmlText(value) {
693
937
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
694
938
  }
@@ -824,8 +1068,8 @@ function createTailwindCssCompiler(options) {
824
1068
  activeProcess = proc;
825
1069
  const stderr = new Response(proc.stderr).text().catch(() => "");
826
1070
  let timeout;
827
- const timedOut = new Promise((resolve2) => {
828
- timeout = setTimeout(() => resolve2("timeout"), timeoutMs);
1071
+ const timedOut = new Promise((resolve3) => {
1072
+ timeout = setTimeout(() => resolve3("timeout"), timeoutMs);
829
1073
  });
830
1074
  try {
831
1075
  const outcome = await Promise.race([proc.exited, timedOut]);
@@ -914,17 +1158,17 @@ function usesTailwind(css) {
914
1158
  }
915
1159
 
916
1160
  // src/createCustomApp.ts
917
- var packageRoot = resolve2(import.meta.dir, "..");
1161
+ var packageRoot = resolve3(import.meta.dir, "..");
918
1162
  var builtInAgentRouteModule = "@sixb/app/agents";
919
1163
  var builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threadId"];
920
1164
  var builtInAgentRouteSourcePath = join7(packageRoot, "src", "agents.ts");
921
1165
  var customAppManifestRoute = "/app.webmanifest";
922
1166
  var internalAppShellRoute = "/__sixb/generated/app-shell";
923
1167
  async function createCustomApp(options) {
924
- const rootDir = resolve2(options.rootDir);
925
- const appDir = options.appDir ? resolve2(rootDir, options.appDir) : resolve2(rootDir, "app");
926
- const generatedDir = resolve2(rootDir, options.generatedDir ?? join7(".sixb", "generated"));
927
- const publicDir = options.publicDir ? resolve2(rootDir, options.publicDir) : resolve2(appDir, "public");
1168
+ const rootDir = resolve3(options.rootDir);
1169
+ const appDir = options.appDir ? resolve3(rootDir, options.appDir) : resolve3(rootDir, "app");
1170
+ const generatedDir = resolve3(rootDir, options.generatedDir ?? join7(".sixb", "generated"));
1171
+ const publicDir = options.publicDir ? resolve3(rootDir, options.publicDir) : resolve3(appDir, "public");
928
1172
  const apiBaseUrl = options.apiBaseUrl;
929
1173
  const audience = options.audience ?? "app";
930
1174
  const authEnabled = options.authEnabled ?? true;
@@ -937,6 +1181,7 @@ async function createCustomApp(options) {
937
1181
  }
938
1182
  let tailwindCompiler = null;
939
1183
  let tailwindCompilerKey = null;
1184
+ let authTailwindCompiler = null;
940
1185
  let builtInAgentCssCompiler = null;
941
1186
  async function prepareStylesheet(stylesheet) {
942
1187
  stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
@@ -1028,7 +1273,7 @@ async function createCustomApp(options) {
1028
1273
  const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : [];
1029
1274
  const stylesheets = await prepareStylesheets(builtInRoutes);
1030
1275
  await generateRouteManifest(routes, generatedDir, { builtInRoutes });
1031
- const { htmlPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
1276
+ const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
1032
1277
  apiBaseUrl,
1033
1278
  audience,
1034
1279
  authEnabled,
@@ -1037,7 +1282,50 @@ async function createCustomApp(options) {
1037
1282
  frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
1038
1283
  stylesheetPath: stylesheets.stylesheetPath
1039
1284
  });
1040
- return { htmlPath, manifestPath, routes };
1285
+ return { htmlPath, mainPath, manifestPath, routes };
1286
+ }
1287
+ async function prepareAuthExperience(authOptions = {}) {
1288
+ const outdir = authOptions.outdir ? resolve3(rootDir, authOptions.outdir) : join7(generatedDir, "auth");
1289
+ if (!await pathExists(join7(appDir, "auth.tsx"))) {
1290
+ await rm2(outdir, { recursive: true, force: true });
1291
+ return null;
1292
+ }
1293
+ const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
1294
+ let stylesheetPath;
1295
+ if (stylesheet.kind === "none") {
1296
+ stylesheetPath = null;
1297
+ } else if (stylesheet.kind === "static") {
1298
+ stylesheetPath = stylesheet.path;
1299
+ } else {
1300
+ const outputPath = join7(generatedDir, "auth.css");
1301
+ authTailwindCompiler ??= createTailwindCssCompiler({
1302
+ inputPath: stylesheet.sourcePath,
1303
+ outputPath,
1304
+ cwd: appDir,
1305
+ resolveFrom: rootDir,
1306
+ label: "[SixbCustomApp]"
1307
+ });
1308
+ await authTailwindCompiler.compile();
1309
+ stylesheetPath = outputPath;
1310
+ }
1311
+ const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
1312
+ appDir,
1313
+ publicDir,
1314
+ stylesheetPath
1315
+ });
1316
+ if (!entry) {
1317
+ return null;
1318
+ }
1319
+ const result = await buildAuthExperience({
1320
+ entryPath: entry.htmlPath,
1321
+ scriptEntryPath: entry.mainPath,
1322
+ outdir
1323
+ });
1324
+ if (!result.success) {
1325
+ throw new Error(`[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join(`
1326
+ `)}`);
1327
+ }
1328
+ return { outdir: result.outdir };
1041
1329
  }
1042
1330
  return {
1043
1331
  async scanRoutes() {
@@ -1047,10 +1335,14 @@ async function createCustomApp(options) {
1047
1335
  const routes = await scanRoutes();
1048
1336
  return routes.length > 0;
1049
1337
  },
1338
+ async prepareAuthExperience(options2) {
1339
+ return await prepareAuthExperience(options2);
1340
+ },
1050
1341
  async dev(devOptions = {}) {
1051
1342
  const host = devOptions.host ?? "0.0.0.0";
1052
1343
  const port = devOptions.port ?? 3001;
1053
1344
  const { htmlPath, manifestPath } = await prepareGeneratedApp();
1345
+ await prepareAuthExperience();
1054
1346
  let htmlImportVersion = 0;
1055
1347
  let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
1056
1348
  const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
@@ -1075,6 +1367,7 @@ async function createCustomApp(options) {
1075
1367
  const enqueueRebuild = () => {
1076
1368
  rebuildChain = rebuildChain.then(async () => {
1077
1369
  const { htmlPath: nextHtmlPath } = await prepareGeneratedApp();
1370
+ await prepareAuthExperience();
1078
1371
  htmlImportVersion++;
1079
1372
  htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
1080
1373
  server.reload(serveOptions(htmlBundle));
@@ -1113,24 +1406,32 @@ async function createCustomApp(options) {
1113
1406
  watcher.close();
1114
1407
  await rebuildChain;
1115
1408
  await tailwindCompiler?.stop();
1409
+ await authTailwindCompiler?.stop();
1116
1410
  await builtInAgentCssCompiler?.stop();
1117
1411
  server.stop(true);
1118
1412
  }
1119
1413
  };
1120
1414
  },
1121
1415
  async build(buildOptions = {}) {
1122
- const outdir = resolve2(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
1123
- const { htmlPath, manifestPath } = await prepareGeneratedApp();
1416
+ const outdir = resolve3(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
1417
+ const { htmlPath, mainPath, manifestPath } = await prepareGeneratedApp();
1124
1418
  const result = await buildApp({
1125
1419
  entryPath: htmlPath,
1420
+ scriptEntryPath: mainPath,
1126
1421
  manifestPath,
1127
1422
  outdir
1128
1423
  });
1424
+ if (result.success) {
1425
+ await prepareAuthExperience({ outdir: join7(outdir, "auth") });
1426
+ }
1129
1427
  if (result.success && await pathExists(publicDir)) {
1130
1428
  await cp(publicDir, outdir, {
1131
1429
  recursive: true,
1132
1430
  force: true,
1133
- filter: (source) => resolve2(source) !== join7(publicDir, "app.webmanifest")
1431
+ filter: (source) => {
1432
+ const resolvedSource = resolve3(source);
1433
+ return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, "auth");
1434
+ }
1134
1435
  });
1135
1436
  }
1136
1437
  return result;
@@ -1138,7 +1439,7 @@ async function createCustomApp(options) {
1138
1439
  async start(startOptions = {}) {
1139
1440
  const host = startOptions.host ?? "0.0.0.0";
1140
1441
  const port = startOptions.port ?? 3001;
1141
- const outdir = resolve2(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
1442
+ const outdir = resolve3(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
1142
1443
  const indexPath = join7(outdir, "index.html");
1143
1444
  if (!await pathExists(indexPath)) {
1144
1445
  throw new Error(`[SixbCustomApp] No built app found in ${outdir}`);
@@ -1169,7 +1470,7 @@ async function createCustomApp(options) {
1169
1470
  }
1170
1471
  const directFile = Bun.file(resolvedPath);
1171
1472
  if (await directFile.exists()) {
1172
- return fileResponse(req, directFile, staticAssetHeaders(url.pathname));
1473
+ return staticFileResponse(req, resolvedPath, staticAssetHeaders(url.pathname));
1173
1474
  }
1174
1475
  if (isAssetRequest(url.pathname)) {
1175
1476
  return notFoundResponse();
@@ -1316,7 +1617,7 @@ function resolveStaticPath(appRoot, pathname) {
1316
1617
  if (segments.includes(".."))
1317
1618
  return null;
1318
1619
  const normalizedPath = normalize(decodedPath).replace(/^[\\/]+/, "");
1319
- const resolvedPath = resolve2(appRoot, normalizedPath);
1620
+ const resolvedPath = resolve3(appRoot, normalizedPath);
1320
1621
  const rel = relative3(appRoot, resolvedPath);
1321
1622
  if (rel.startsWith("..") || isAbsolute(rel))
1322
1623
  return null;
@@ -1349,7 +1650,7 @@ function htmlResponse(request, html) {
1349
1650
  }
1350
1651
  });
1351
1652
  }
1352
- var IMMUTABLE_ASSET_PATTERN = /^chunk-[a-z0-9]+\.(js|css|js\.map|css\.map)$/;
1653
+ var IMMUTABLE_ASSET_PATTERN = /^(?:(?:app|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/;
1353
1654
  function staticAssetHeaders(pathname) {
1354
1655
  if (pathname === customAppManifestRoute) {
1355
1656
  return {
@@ -1363,6 +1664,54 @@ function staticAssetHeaders(pathname) {
1363
1664
  }
1364
1665
  return { "cache-control": "public, max-age=31536000, immutable" };
1365
1666
  }
1667
+ async function staticFileResponse(request, path, headers) {
1668
+ const responseHeaders = new Headers(headers);
1669
+ const originalFile = Bun.file(path);
1670
+ let responseFile = originalFile;
1671
+ if (isPrecompressedAsset(path)) {
1672
+ responseHeaders.append("vary", "Accept-Encoding");
1673
+ if (!request.headers.has("range")) {
1674
+ for (const encoding of acceptedPrecompressedEncodings(request)) {
1675
+ const candidate = Bun.file(`${path}.${encoding === "br" ? "br" : "gz"}`);
1676
+ if (!await candidate.exists())
1677
+ continue;
1678
+ responseFile = candidate;
1679
+ responseHeaders.set("content-encoding", encoding);
1680
+ responseHeaders.set("content-type", originalFile.type);
1681
+ break;
1682
+ }
1683
+ }
1684
+ }
1685
+ return new Response(request.method === "HEAD" ? null : responseFile, {
1686
+ headers: responseHeaders
1687
+ });
1688
+ }
1689
+ function isPrecompressedAsset(path) {
1690
+ return path.endsWith(".js") || path.endsWith(".css");
1691
+ }
1692
+ function acceptedPrecompressedEncodings(request) {
1693
+ const header = request.headers.get("accept-encoding");
1694
+ if (!header)
1695
+ return [];
1696
+ const qualities = new Map;
1697
+ for (const item of header.split(",")) {
1698
+ const [rawName, ...parameters] = item.trim().split(";");
1699
+ const name = rawName.toLowerCase();
1700
+ let quality = 1;
1701
+ for (const parameter of parameters) {
1702
+ const match = parameter.trim().match(/^q=(0(?:\.\d+)?|1(?:\.0+)?)$/);
1703
+ if (match)
1704
+ quality = Number(match[1]);
1705
+ }
1706
+ qualities.set(name, quality);
1707
+ }
1708
+ const wildcard = qualities.get("*") ?? 0;
1709
+ return ["br", "gzip"].map((encoding, preference) => ({
1710
+ encoding,
1711
+ preference,
1712
+ quality: qualities.get(encoding) ?? wildcard
1713
+ })).filter((candidate) => candidate.quality > 0).sort((left, right) => right.quality - left.quality || left.preference - right.preference).map((candidate) => candidate.encoding);
1714
+ }
1366
1715
  function fileResponse(request, file, headers = {}) {
1367
1716
  return new Response(request.method === "HEAD" ? null : file, { headers });
1368
1717
  }
@@ -1461,4 +1810,4 @@ export {
1461
1810
  createCustomApp
1462
1811
  };
1463
1812
 
1464
- //# debugId=EF77EB82048A32D864756E2164756E21
1813
+ //# debugId=DF164E399EBD3CA764756E2164756E21