@seip/bluebird-js 0.1.7 → 0.2.1

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.
Files changed (151) hide show
  1. package/AGENTS.md +727 -620
  2. package/README.md +670 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +55 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/table.html +15 -0
  8. package/app/resources/html/terms.html +46 -0
  9. package/app/resources/index.html +27 -0
  10. package/app/resources/layouts/AppLayout.jsx +92 -0
  11. package/app/resources/main.jsx +18 -0
  12. package/app/resources/pages/Dashboard.jsx +93 -0
  13. package/app/resources/pages/Home.jsx +140 -0
  14. package/app/resources/pages/Login.jsx +35 -0
  15. package/app/resources/pages/NotFound.jsx +16 -0
  16. package/app/resources/pages/Register.jsx +55 -0
  17. package/app/resources/pages/TableDemo.jsx +85 -0
  18. package/app/resources/routes.jsx +59 -0
  19. package/app/resources/spa.js +73 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +129 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +89 -47
  24. package/core/ai.js +30 -10
  25. package/core/app.d.ts +2 -18
  26. package/core/app.js +987 -801
  27. package/core/auth.d.ts +2 -13
  28. package/core/auth.js +444 -326
  29. package/core/cli/build.js +37 -0
  30. package/core/cli/dev.js +155 -0
  31. package/core/cli/doctor.js +37 -2
  32. package/core/cli/export.js +191 -0
  33. package/core/cli/init.js +91 -322
  34. package/core/cli/nginx.js +1 -1
  35. package/core/cli/templates.js +139 -0
  36. package/core/cli/view.js +98 -161
  37. package/core/config.js +44 -2
  38. package/core/csrf.js +156 -24
  39. package/core/database.js +1184 -1131
  40. package/core/debug.js +1 -1
  41. package/core/html.js +8 -1
  42. package/core/index.d.ts +126 -310
  43. package/core/paths.js +55 -0
  44. package/core/ratelimit.js +10 -1
  45. package/core/react/client/api.js +239 -0
  46. package/core/react/client/auth.js +236 -0
  47. package/core/react/client/components.js +1321 -0
  48. package/core/react/client/datatable.js +595 -0
  49. package/core/react/client/i18n.js +440 -0
  50. package/core/react/client/index.d.ts +314 -0
  51. package/core/react/client/index.js +50 -0
  52. package/core/react/client/router.js +26 -0
  53. package/core/react/client/theme.css +512 -0
  54. package/core/render-cache.js +250 -212
  55. package/core/render.d.ts +25 -21
  56. package/core/render.js +738 -736
  57. package/core/router.d.ts +2 -3
  58. package/core/router.js +171 -171
  59. package/core/seo.js +10 -0
  60. package/core/spa.js +599 -0
  61. package/core/view-loader.js +155 -613
  62. package/core/vite-plugin.d.ts +18 -0
  63. package/core/vite-plugin.js +162 -0
  64. package/core/vite.js +250 -145
  65. package/index.js +22 -18
  66. package/jsconfig.json +5 -3
  67. package/package.json +114 -92
  68. package/production.md +8 -3
  69. package/public/js/bluebird.js +1886 -0
  70. package/templates/_auth/app/database.js +19 -0
  71. package/templates/_auth/app/models/user.js +22 -0
  72. package/templates/_auth/app/routes/auth-router.js +304 -0
  73. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  74. package/templates/_base/app/resources/html/notFound.html +14 -0
  75. package/templates/_base/app/resources/index.html +27 -0
  76. package/templates/_base/app/resources/styles.css +9 -0
  77. package/templates/api/app/models/note.js +18 -0
  78. package/templates/api/app/routes/api.js +82 -0
  79. package/templates/api/app/routes/auth.js +11 -0
  80. package/templates/api/index.js +19 -0
  81. package/templates/api/template.json +13 -0
  82. package/templates/auth/app/mail.js +11 -0
  83. package/templates/auth/app/models/password_reset.js +18 -0
  84. package/templates/auth/app/resources/html/home.html +21 -0
  85. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  86. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  87. package/templates/auth/app/resources/main.jsx +18 -0
  88. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  89. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  90. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  91. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  92. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  93. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  94. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  95. package/templates/auth/app/resources/routes.jsx +54 -0
  96. package/templates/auth/app/resources/spa.js +29 -0
  97. package/templates/auth/app/routes/api.js +17 -0
  98. package/templates/auth/app/routes/auth.js +13 -0
  99. package/templates/auth/app/routes/web.js +21 -0
  100. package/templates/auth/index.js +19 -0
  101. package/templates/auth/template.json +15 -0
  102. package/templates/blank/app/models/.gitkeep +0 -0
  103. package/templates/blank/app/resources/html/home.html +27 -0
  104. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  105. package/templates/blank/app/resources/main.jsx +16 -0
  106. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  107. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  108. package/templates/blank/app/resources/routes.jsx +15 -0
  109. package/templates/blank/app/resources/spa.js +24 -0
  110. package/templates/blank/app/routes/api.js +11 -0
  111. package/templates/blank/app/routes/web.js +21 -0
  112. package/templates/blank/index.js +13 -0
  113. package/templates/blank/template.json +12 -0
  114. package/templates/blog/app/lib/blog.js +149 -0
  115. package/templates/blog/app/models/post.js +22 -0
  116. package/templates/blog/app/resources/html/home.html +28 -0
  117. package/templates/blog/app/resources/html/not-found.html +5 -0
  118. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  119. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  120. package/templates/blog/app/resources/html/post.html +8 -0
  121. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  122. package/templates/blog/app/resources/main.jsx +18 -0
  123. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  124. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  125. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  126. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  127. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  128. package/templates/blog/app/resources/routes.jsx +51 -0
  129. package/templates/blog/app/resources/spa.js +25 -0
  130. package/templates/blog/app/resources/styles.css +40 -0
  131. package/templates/blog/app/routes/api.js +77 -0
  132. package/templates/blog/app/routes/auth.js +10 -0
  133. package/templates/blog/app/routes/web.js +114 -0
  134. package/templates/blog/index.js +21 -0
  135. package/templates/blog/template.json +14 -0
  136. package/vite.config.js +11 -0
  137. package/app/views/components/Header.jsx +0 -42
  138. package/app/views/components/LiveCounter.jsx +0 -67
  139. package/app/views/layouts/main/view.jsx +0 -201
  140. package/app/views/legal/terms.html +0 -29
  141. package/app/views/pages/about.jsx +0 -98
  142. package/app/views/pages/dashboard.jsx +0 -278
  143. package/app/views/pages/index.jsx +0 -123
  144. package/app/views/pages/login.jsx +0 -141
  145. package/core/actions.d.ts +0 -4
  146. package/core/actions.js +0 -355
  147. package/core/jsx.d.ts +0 -38
  148. package/core/jsx.js +0 -1597
  149. package/core/vite.d.ts +0 -3
  150. package/public/js/bluebird-client.js +0 -3265
  151. package/public/js/tailwind.js +0 -8
@@ -0,0 +1,37 @@
1
+ import path from "node:path";
2
+ import colors from "../util/colors.js";
3
+ import ViteBridge from "../vite.js";
4
+ import { BUILD_DIRS, resolveClientInputs } from "../vite-plugin.js";
5
+
6
+ /**
7
+ * `npx bluebird-js build`: builds the client SPA bundle and compiled Tailwind CSS into `public/build/`.
8
+ */
9
+ async function build() {
10
+ const root = process.cwd();
11
+ delete process.env.DEBUG;
12
+ process.env.NODE_ENV = process.env.NODE_ENV || "production";
13
+
14
+ const inputs = resolveClientInputs(root);
15
+ if (inputs.length === 0) {
16
+ console.log(colors.yellow("[BUILD] No client entry (app/resources/main.jsx) or stylesheet (app/resources/styles.css) found. Nothing to build."));
17
+ return;
18
+ }
19
+
20
+ const { build: viteBuild } = await import("vite");
21
+ const bridge = new ViteBridge({ root, dev: false });
22
+ const config = await bridge.inlineConfig();
23
+ const started = Date.now();
24
+
25
+ console.log(colors.cyan("[BUILD] Client bundle ->"), BUILD_DIRS.client);
26
+ await viteBuild({ ...config, mode: "production", logLevel: "warn" });
27
+
28
+ console.log(
29
+ colors.green(`[OK] Build completed in ${((Date.now() - started) / 1000).toFixed(1)}s.`),
30
+ colors.gray(`Start with: npm start (${path.join(BUILD_DIRS.client, ".vite/manifest.json")})`)
31
+ );
32
+ }
33
+
34
+ build().catch((err) => {
35
+ console.error(colors.red("[BUILD ERROR]"), err?.message || err);
36
+ process.exit(1);
37
+ });
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { spawn } from "node:child_process";
6
+ import colors from "../util/colors.js";
7
+
8
+ const SERVER_EXTENSIONS = new Set([".js", ".mjs", ".cjs", ".json"]);
9
+ const IGNORED_SEGMENTS = new Set(["node_modules", ".vite", ".vite-temp", "logs", "cache", ".git", "dist", "build"]);
10
+ const DEFAULT_DIRS = ["app", "core"];
11
+ const CLIENT_DIRS = ["app/resources/"];
12
+ const DEFAULT_FILES = ["index.js", ".env", "app/resources/spa.js"];
13
+
14
+ /**
15
+ * Parses `bluebird-js dev [entry] [--watch <path>]... [--delay <ms>]` arguments.
16
+ * @param {string[]} argv
17
+ * @returns {{ entry: string, watch: string[], delay: number }}
18
+ */
19
+ function parseArgs(argv) {
20
+ const out = { entry: "index.js", watch: [], delay: 150 };
21
+ for (let i = 0; i < argv.length; i++) {
22
+ const arg = argv[i];
23
+ if (arg === "--watch" && argv[i + 1]) out.watch.push(argv[++i]);
24
+ else if (arg.startsWith("--watch=")) out.watch.push(arg.slice(8));
25
+ else if (arg === "--delay" && argv[i + 1]) out.delay = Number(argv[++i]) || out.delay;
26
+ else if (!arg.startsWith("-")) out.entry = arg;
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /**
32
+ * Checks whether a changed file should restart the server (server code only, never build output or logs).
33
+ * Every server file under `app/` (routes, models, jobs, lib, database.js, ...) restarts the server.
34
+ * Client code in `app/resources/` is hot-reloaded by Vite, so only explicitly watched files there restart.
35
+ * @param {string} relPath
36
+ * @param {Set<string>} watchedFiles
37
+ * @returns {boolean}
38
+ */
39
+ export function shouldRestart(relPath, watchedFiles) {
40
+ const clean = relPath.replace(/\\/g, "/").replace(/^\.\//, "");
41
+ if (watchedFiles.has(clean)) return true;
42
+ if (CLIENT_DIRS.some((dir) => clean.startsWith(dir))) return false;
43
+ const segments = clean.split("/");
44
+ if (segments.some((s) => IGNORED_SEGMENTS.has(s))) return false;
45
+ if (segments.some((s) => s.includes(".timestamp-"))) return false;
46
+ return SERVER_EXTENSIONS.has(path.extname(clean));
47
+ }
48
+
49
+ /**
50
+ * `npx bluebird-js dev`: runs the server with `--env-file-if-exists=.env` and restarts it when server files change.
51
+ * Replaces `node --watch-path`, which on some platforms reports changes outside the watched paths
52
+ * (`logs/`, `node_modules/.vite-temp`, esbuild binaries) and restarts endlessly.
53
+ */
54
+ function dev() {
55
+ const root = process.cwd();
56
+ const args = parseArgs(process.argv.slice(3));
57
+ const entry = args.entry;
58
+
59
+ if (!fs.existsSync(path.join(root, entry))) {
60
+ console.error(colors.red(`[DEV] Entry file '${entry}' not found.`));
61
+ process.exit(1);
62
+ }
63
+
64
+ const watchedFiles = new Set([entry, ...DEFAULT_FILES].map((f) => f.replace(/\\/g, "/")));
65
+ const watchedDirs = [];
66
+ for (const item of [...DEFAULT_DIRS, ...args.watch]) {
67
+ const abs = path.resolve(root, item);
68
+ if (!fs.existsSync(abs)) continue;
69
+ if (fs.statSync(abs).isDirectory()) watchedDirs.push(abs);
70
+ else watchedFiles.add(path.relative(root, abs).replace(/\\/g, "/"));
71
+ }
72
+
73
+ let child = null;
74
+ let restarting = false;
75
+ let timer = null;
76
+ let pendingReason = "";
77
+
78
+ const start = () => {
79
+ child = spawn(process.execPath, ["--env-file-if-exists=.env", entry], {
80
+ cwd: root,
81
+ stdio: ["inherit", "inherit", "inherit", "ipc"],
82
+ env: { ...process.env, BLUEBIRD_DEV_RUNNER: "1" },
83
+ });
84
+ child.on("exit", (code, signal) => {
85
+ const wasRestart = restarting;
86
+ child = null;
87
+ if (wasRestart) {
88
+ restarting = false;
89
+ start();
90
+ } else if (signal !== "SIGTERM" && signal !== "SIGINT") {
91
+ console.log(colors.yellow(`[DEV] Server exited (code ${code ?? signal}). Waiting for file changes...`));
92
+ }
93
+ });
94
+ };
95
+
96
+ const restart = (reason) => {
97
+ console.log(colors.cyan(`[DEV] ${reason} changed, restarting...`));
98
+ if (child) {
99
+ restarting = true;
100
+ child.kill("SIGTERM");
101
+ } else {
102
+ start();
103
+ }
104
+ };
105
+
106
+ const bootedAt = Date.now();
107
+ const mtimes = new Map();
108
+ const hasRealChange = (relPath) => {
109
+ let mtime = -1;
110
+ try {
111
+ mtime = fs.statSync(path.join(root, relPath)).mtimeMs;
112
+ } catch {}
113
+ const previous = mtimes.has(relPath) ? mtimes.get(relPath) : bootedAt;
114
+ mtimes.set(relPath, mtime);
115
+ return (mtime === -1 && previous !== -1) || mtime > previous;
116
+ };
117
+
118
+ const schedule = (relPath) => {
119
+ if (!shouldRestart(relPath, watchedFiles)) return;
120
+ if (!hasRealChange(relPath)) return;
121
+ pendingReason = relPath.replace(/\\/g, "/");
122
+ clearTimeout(timer);
123
+ timer = setTimeout(() => restart(pendingReason), args.delay);
124
+ };
125
+
126
+ for (const dir of watchedDirs) {
127
+ fs.watch(dir, { recursive: true }, (event, filename) => {
128
+ if (filename) schedule(path.relative(root, path.join(dir, filename.toString())));
129
+ });
130
+ }
131
+
132
+ const fileDirs = new Set([...watchedFiles].map((f) => path.dirname(path.join(root, f))));
133
+ for (const dir of fileDirs) {
134
+ if (!fs.existsSync(dir) || watchedDirs.some((w) => dir === w || dir.startsWith(w + path.sep))) continue;
135
+ fs.watch(dir, (event, filename) => {
136
+ if (!filename) return;
137
+ const rel = path.relative(root, path.join(dir, filename.toString())).replace(/\\/g, "/");
138
+ if (watchedFiles.has(rel)) schedule(rel);
139
+ });
140
+ }
141
+
142
+ const stop = () => {
143
+ clearTimeout(timer);
144
+ if (child) child.kill("SIGTERM");
145
+ process.exit(0);
146
+ };
147
+ process.on("SIGINT", stop);
148
+ process.on("SIGTERM", stop);
149
+
150
+ const dirs = watchedDirs.map((d) => path.relative(root, d).replace(/\\/g, "/")).join(", ");
151
+ console.log(colors.gray(`[DEV] Watching ${dirs || "(no dirs)"} + ${[...watchedFiles].join(", ")}`));
152
+ start();
153
+ }
154
+
155
+ if (process.argv[2] === "dev") dev();
@@ -60,8 +60,6 @@ function findSampleStaticAsset() {
60
60
  if (!fs.existsSync(publicDir)) return null;
61
61
 
62
62
  const candidates = [
63
- "js/tailwind.js",
64
- "js/bluebird-client.js",
65
63
  "images/favicon.ico",
66
64
  ];
67
65
 
@@ -184,6 +182,24 @@ export async function runDoctor() {
184
182
  } else {
185
183
  console.log(colors.green(" [PASS] 'app/' directory exists."));
186
184
  }
185
+
186
+ const cwd = process.cwd();
187
+ for (const legacy of ["app/views", "app/client", "app/styles.css"]) {
188
+ if (fs.existsSync(path.join(cwd, legacy))) {
189
+ console.log(colors.yellow(` [WARN] Legacy '${legacy}' found: move it into 'app/resources/' (html/ for views).`));
190
+ warningsFound++;
191
+ }
192
+ }
193
+ const hasSpaEntry = ["main.jsx", "main.tsx", "main.js", "main.ts"].some((f) => fs.existsSync(path.join(cwd, "app/resources", f)));
194
+ if (hasSpaEntry) {
195
+ console.log(colors.green(" [PASS] React SPA entry found in 'app/resources/'."));
196
+ if (fs.existsSync(path.join(cwd, "public/build/.vite/manifest.json"))) {
197
+ console.log(colors.green(" [PASS] Production client build found (public/build/.vite/manifest.json)."));
198
+ } else {
199
+ console.log(colors.yellow(" [WARN] No production build: run 'npx bluebird-js build' before 'npm start'."));
200
+ warningsFound++;
201
+ }
202
+ }
187
203
  console.log("");
188
204
 
189
205
  console.log(colors.bold("[3/5] Port Availability & Binding:"));
@@ -209,8 +225,10 @@ export async function runDoctor() {
209
225
  }
210
226
 
211
227
  let serverReachable = false;
228
+ let foreignServer = false;
212
229
 
213
230
  for (const item of testUrls) {
231
+ if (foreignServer) break;
214
232
  try {
215
233
  const controller = new AbortController();
216
234
  const timeoutId = setTimeout(() => controller.abort(), 3000);
@@ -219,6 +237,23 @@ export async function runDoctor() {
219
237
 
220
238
  serverReachable = true;
221
239
 
240
+ if (item.isApi) {
241
+ const body = await res.text();
242
+ let isBluebird = false;
243
+ try {
244
+ const json = JSON.parse(body);
245
+ isBluebird = json?.status === "ok" && "uptime" in json;
246
+ } catch {}
247
+ if (!isBluebird) {
248
+ foreignServer = true;
249
+ console.log(colors.yellow(` [WARN] ${appUrl} answered, but it is not this Bluebird app (HTTP ${res.status}, ${res.headers.get("content-type") || "no content type"}).`));
250
+ console.log(colors.yellow(` Another process is using port ${port} (e.g. VS Code Live Preview or another dev server).`));
251
+ console.log(colors.yellow(" Stop it or set PORT to a free port, then run doctor again with your app started."));
252
+ warningsFound++;
253
+ continue;
254
+ }
255
+ }
256
+
222
257
  if (res.status === 200) {
223
258
  console.log(colors.green(` [PASS] ${item.name} returned HTTP 200 OK.`));
224
259
  } else if (res.status === 403) {
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import colors from "../util/colors.js";
7
+
8
+ try {
9
+ process.loadEnvFile?.();
10
+ } catch {}
11
+
12
+ const PROTECTED_DIRS = new Set(["app", "core", "public", "node_modules", "database", ".git"]);
13
+ const HELP = `Usage: npx bluebird-js export [options]
14
+
15
+ Builds the React SPA (app/resources/) into a 100% static HTML/JS/CSS folder for Electron, Capacitor,
16
+ Tauri, or any static host. The same index.html shell, spa.js metadata, and React code used by router.spa().
17
+
18
+ Options:
19
+ --out <dir> Output directory (default: dist/client)
20
+ --api <url> API server URL used by api() (default: EXPORT_API_URL or APP_URL from .env)
21
+ --router <mode> hash | browser | memory (default: hash, works with file://)
22
+ --base <path> Asset base URL (default: ./ for hash/memory, / for browser)
23
+ --basename <path> Browser router basename (default: /)
24
+ --auth <mode> token | cookie (default: token, Authorization: Bearer)
25
+ --config <file> SPA config module (default: app/resources/spa.js)
26
+ --no-public Do not copy public/ into the output directory`;
27
+
28
+ /**
29
+ * Parses `--flag value` and `--flag=value` CLI arguments.
30
+ * @param {string[]} argv
31
+ * @returns {Record<string, string|boolean>}
32
+ */
33
+ function parseArgs(argv) {
34
+ const out = {};
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const arg = argv[i];
37
+ if (!arg.startsWith("--")) continue;
38
+ const [key, inline] = arg.slice(2).split("=");
39
+ if (inline !== undefined) out[key] = inline;
40
+ else if (argv[i + 1] && !argv[i + 1].startsWith("--")) out[key] = argv[++i];
41
+ else out[key] = true;
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /**
47
+ * Rejects output directories that would wipe the project or its sources when emptied.
48
+ * @param {string} root
49
+ * @param {string} outDir
50
+ */
51
+ function assertSafeOutDir(root, outDir) {
52
+ const rel = path.relative(root, outDir);
53
+ const isAncestor = root === outDir || root.startsWith(outDir + path.sep);
54
+ const first = rel.split(/[\\/]/)[0];
55
+ if (rel === "" || isAncestor || PROTECTED_DIRS.has(first)) {
56
+ throw new Error(`Refusing to export into '${outDir}': choose a dedicated folder such as dist/client.`);
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Loads the SPA configuration module (default export) when present.
62
+ * @param {string} file
63
+ * @returns {Promise<Object|null>}
64
+ */
65
+ async function loadSpaConfig(file) {
66
+ if (!fs.existsSync(file)) return null;
67
+ const mod = await import(pathToFileURL(file).href);
68
+ return mod.default || mod.spa || null;
69
+ }
70
+
71
+ /**
72
+ * Rewrites root-absolute `src` / `href` attributes (e.g. `/images/favicon.ico`) to the export base.
73
+ * @param {string} html
74
+ * @param {string} base
75
+ * @returns {string}
76
+ */
77
+ function rebaseLocalUrls(html, base) {
78
+ if (base === "/") return html;
79
+ return html.replace(/(\s(?:src|href)=["'])\/(?!\/)/g, `$1${base}`);
80
+ }
81
+
82
+ /**
83
+ * `npx bluebird-js export`: static client build of the React SPA.
84
+ */
85
+ async function exportSpa() {
86
+ const args = parseArgs(process.argv.slice(3));
87
+ if (args.help || args.h) {
88
+ console.log(HELP);
89
+ return;
90
+ }
91
+
92
+ delete process.env.DEBUG;
93
+ process.env.NODE_ENV = process.env.NODE_ENV || "production";
94
+
95
+ const root = process.cwd();
96
+ const { default: ViteBridge } = await import("../vite.js");
97
+ const { PATHS } = await import("../paths.js");
98
+ const { compileMetaTree, renderSpaDocument, resolveSpaMeta, spaAssetEntries } = await import("../spa.js");
99
+ delete process.env.DEBUG;
100
+
101
+ const router = ["hash", "browser", "memory"].includes(args.router) ? args.router : "hash";
102
+ const base = typeof args.base === "string" ? args.base.replace(/\/?$/, "/") : router === "browser" ? "/" : "./";
103
+ const auth = args.auth === "cookie" ? "cookie" : "token";
104
+ const apiUrl = String(
105
+ (typeof args.api === "string" && args.api) || process.env.EXPORT_API_URL || process.env.APP_URL || ""
106
+ ).replace(/\/+$/, "");
107
+ const outDir = path.resolve(root, typeof args.out === "string" ? args.out : "dist/client");
108
+ assertSafeOutDir(root, outDir);
109
+
110
+ const configFile = path.resolve(root, typeof args.config === "string" ? args.config : PATHS.spaConfig);
111
+ const options = (await loadSpaConfig(configFile)) || {};
112
+ if (!fs.existsSync(configFile)) {
113
+ console.log(colors.yellow(`[WARN] ${path.relative(root, configFile)} not found: exporting with index.html defaults only.`));
114
+ }
115
+
116
+ const mount = options.mount || "/";
117
+ const compiled = compileMetaTree(options.meta || {}, mount);
118
+ const stubReq = { params: {}, query: {}, headers: {}, cookies: {}, path: mount, lang: options.lang || "en" };
119
+ let merged;
120
+ try {
121
+ merged = await resolveSpaMeta(options, compiled, "/", stubReq);
122
+ } catch (err) {
123
+ console.log(colors.yellow(`[WARN] Dynamic meta for '/' failed (${err.message}); using base options.`));
124
+ merged = await resolveSpaMeta(options, { wildcard: null, routes: [] }, "/", stubReq);
125
+ }
126
+ merged.canonical = typeof merged.canonical === "string" ? merged.canonical : false;
127
+
128
+ const entries = spaAssetEntries(merged, root);
129
+ const missing = entries.filter((rel) => !fs.existsSync(path.join(root, rel)));
130
+ if (missing.length > 0) {
131
+ throw new Error(`Missing SPA entry files: ${missing.join(", ")}`);
132
+ }
133
+
134
+ const exportConfig = { apiUrl, router, auth, basename: typeof args.basename === "string" ? args.basename : "/" };
135
+ const bridge = new ViteBridge({ root, base });
136
+ const viteConfig = await bridge.inlineConfig();
137
+ const { build: viteBuild } = await import("vite");
138
+ const started = Date.now();
139
+
140
+ console.log(colors.cyan("[EXPORT] Static client build ->"), path.relative(root, outDir) || outDir);
141
+ await viteBuild({
142
+ ...viteConfig,
143
+ mode: "production",
144
+ logLevel: "warn",
145
+ base,
146
+ publicDir: false,
147
+ define: { __BLUEBIRD_EXPORT__: JSON.stringify(exportConfig) },
148
+ build: {
149
+ outDir,
150
+ emptyOutDir: true,
151
+ manifest: true,
152
+ rollupOptions: { input: entries.map((rel) => path.join(root, rel)) },
153
+ },
154
+ });
155
+
156
+ if (!args["no-public"]) {
157
+ const publicDir = path.join(root, "public");
158
+ if (fs.existsSync(publicDir)) {
159
+ fs.cpSync(publicDir, outDir, {
160
+ recursive: true,
161
+ force: false,
162
+ filter: (src) => path.relative(publicDir, src).split(/[\\/]/)[0] !== "build",
163
+ });
164
+ }
165
+ }
166
+
167
+ const manifestFile = path.join(outDir, ".vite/manifest.json");
168
+ bridge.manifest = JSON.parse(fs.readFileSync(manifestFile, "utf-8"));
169
+ bridge.mode = "build";
170
+ const assets = bridge.assetTags(entries);
171
+
172
+ const html = await renderSpaDocument(merged, { fullPath: mount, assets, root, lang: options.lang });
173
+ fs.writeFileSync(path.join(outDir, "index.html"), rebaseLocalUrls(html, base), "utf-8");
174
+ fs.rmSync(path.join(outDir, ".vite"), { recursive: true, force: true });
175
+
176
+ const relOut = path.relative(root, outDir).replace(/\\/g, "/") || ".";
177
+ console.log(colors.green(`[OK] Exported in ${((Date.now() - started) / 1000).toFixed(1)}s -> ${relOut}/index.html`));
178
+ console.log(colors.gray(` router: ${router} | base: ${base} | auth: ${auth} | api: ${apiUrl || "(same origin)"}`));
179
+ if (!apiUrl) {
180
+ console.log(colors.yellow(" [WARN] No API URL: pass --api https://your-server.com for Electron/Capacitor builds."));
181
+ }
182
+ console.log(colors.white("Next steps:"));
183
+ console.log(colors.cyan(` Electron : mainWindow.loadFile("${relOut}/index.html")`));
184
+ console.log(colors.cyan(` Capacitor: set "webDir": "${relOut}" in capacitor.config.json, then npx cap sync`));
185
+ console.log(colors.cyan(" Server : allow the app origin in new App({ cors }) (default origin \"*\" already works with bearer tokens)"));
186
+ }
187
+
188
+ exportSpa().catch((err) => {
189
+ console.error(colors.red("[EXPORT ERROR]"), err?.message || err);
190
+ process.exit(1);
191
+ });