bini-server 1.0.10 → 2.0.0

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 (3) hide show
  1. package/dist/cli.js +100 -25
  2. package/dist/index.js +99 -24
  3. package/package.json +2 -1
package/dist/cli.js CHANGED
@@ -36,16 +36,10 @@ function detectEnvFiles(root) {
36
36
  }
37
37
  function getEnvVar(key, defaultValue) {
38
38
  const biniKey = `BINI_${key}`;
39
- if (process.env[biniKey] !== void 0) {
40
- return process.env[biniKey];
41
- }
39
+ if (process.env[biniKey] !== void 0) return process.env[biniKey];
42
40
  const viteKey = `VITE_${key}`;
43
- if (process.env[viteKey] !== void 0) {
44
- return process.env[viteKey];
45
- }
46
- if (process.env[key] !== void 0) {
47
- return process.env[key];
48
- }
41
+ if (process.env[viteKey] !== void 0) return process.env[viteKey];
42
+ if (process.env[key] !== void 0) return process.env[key];
49
43
  return defaultValue;
50
44
  }
51
45
  function getEnvVarBoolean(key, defaultValue) {
@@ -59,6 +53,65 @@ function getEnvVarNumber(key, defaultValue) {
59
53
  const parsed = parseInt(value, 10);
60
54
  return isNaN(parsed) ? defaultValue : parsed;
61
55
  }
56
+ function scanShellRoutes() {
57
+ const shellRoutes = /* @__PURE__ */ new Set();
58
+ const rootDir = DIST_DIR;
59
+ function walkDir(dir, currentPath) {
60
+ try {
61
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
62
+ for (const entry of entries) {
63
+ if (!entry.isDirectory()) continue;
64
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
65
+ const fullPath = path.join(dir, entry.name);
66
+ const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
67
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
68
+ const indexPath = path.join(fullPath, "index.html");
69
+ if (fs.existsSync(indexPath)) {
70
+ shellRoutes.add(`/${routePath}`);
71
+ }
72
+ }
73
+ walkDir(fullPath, routePath);
74
+ }
75
+ } catch {
76
+ }
77
+ }
78
+ try {
79
+ walkDir(rootDir, "");
80
+ } catch {
81
+ }
82
+ return shellRoutes;
83
+ }
84
+ function getShellRoutes() {
85
+ if (!shellRouteCache) {
86
+ shellRouteCache = scanShellRoutes();
87
+ }
88
+ return shellRouteCache;
89
+ }
90
+ function findMatchingShellRoute(pathname) {
91
+ const shellRoutes = getShellRoutes();
92
+ const cleanPath = pathname.replace(/^\/|\/$/g, "");
93
+ const pathSegments = cleanPath.split("/").filter(Boolean);
94
+ for (const shellRoute of shellRoutes) {
95
+ const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
96
+ const shellSegments = cleanShell.split("/").filter(Boolean);
97
+ if (shellSegments.length !== pathSegments.length) continue;
98
+ let matches = true;
99
+ for (let i = 0; i < shellSegments.length; i++) {
100
+ const segment = shellSegments[i];
101
+ if (segment.startsWith("[") && segment.endsWith("]")) {
102
+ continue;
103
+ }
104
+ if (segment !== pathSegments[i]) {
105
+ matches = false;
106
+ break;
107
+ }
108
+ }
109
+ if (matches) {
110
+ return shellRoute;
111
+ }
112
+ }
113
+ return null;
114
+ }
62
115
  function getNetworkIp() {
63
116
  const ifaces = os.networkInterfaces();
64
117
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
@@ -116,17 +169,15 @@ async function findFreePort(start3) {
116
169
  throw new Error(`No free port found in range ${start3}\u2013${start3 + 99}`);
117
170
  }
118
171
  function startKeyboardLoop(port) {
119
- if (!process.stdin.isTTY) {
120
- return;
121
- }
172
+ if (!process.stdin.isTTY) return;
122
173
  const rl = readline.createInterface({ input: process.stdin });
123
174
  rl.on("line", (line) => {
124
175
  switch (line.trim()) {
125
176
  case "h":
126
177
  console.log("");
127
178
  console.log(" Shortcuts");
128
- console.log(` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
129
- console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
179
+ console.log(` ${C.DIM}press ${C.RESET}o + enter${C.RESET} to open in browser${C.RESET}`);
180
+ console.log(` ${C.DIM}press ${C.RESET}q + enter${C.RESET} to quit${C.RESET}`);
130
181
  console.log("");
131
182
  break;
132
183
  case "o": {
@@ -150,7 +201,7 @@ function getRouteCache() {
150
201
  routeIndex.set(routeCache[i].routePath, routeCache[i]);
151
202
  }
152
203
  if (process.env.NODE_ENV === "development") {
153
- console.log(`[bini-server] Routes scanned in ${Date.now() - start3}ms`);
204
+ console.log(`[bini-server] API routes scanned in ${Date.now() - start3}ms`);
154
205
  }
155
206
  }
156
207
  return routeCache;
@@ -273,9 +324,6 @@ function normalizeHeaders(raw) {
273
324
  }
274
325
  return out;
275
326
  }
276
- function invokeHono(honoApp, request) {
277
- return honoApp.fetch(request, process.env);
278
- }
279
327
  async function handleApiRequest(req, res, next) {
280
328
  if (req.method === "OPTIONS") {
281
329
  const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
@@ -340,7 +388,7 @@ async function handleApiRequest(req, res, next) {
340
388
  try {
341
389
  if (typeof handler.fetch === "function") {
342
390
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
343
- webRes = await invokeHono(handler, new Request(honoUrl, {
391
+ webRes = await handler.fetch(new Request(honoUrl, {
344
392
  method,
345
393
  headers: normalizedHeaders,
346
394
  body: body ? new Uint8Array(body) : null
@@ -421,15 +469,40 @@ async function sendFile(filePath, req, res) {
421
469
  async function serveStatic(req, res, next) {
422
470
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
423
471
  if (pathname.startsWith("/api")) return next();
424
- const filePath = path.join(DIST_DIR, pathname);
472
+ const hasExtension = path.extname(pathname).length > 0;
473
+ if (hasExtension) {
474
+ const filePath = path.join(DIST_DIR, pathname);
475
+ try {
476
+ const stat = await fs.promises.stat(filePath);
477
+ if (stat.isFile()) {
478
+ await sendFile(filePath, req, res);
479
+ return;
480
+ }
481
+ } catch {
482
+ }
483
+ return next();
484
+ }
485
+ const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
425
486
  try {
426
- const stat = await fs.promises.stat(filePath);
487
+ const stat = await fs.promises.stat(staticFilePath);
427
488
  if (stat.isFile()) {
428
- await sendFile(filePath, req, res);
489
+ await sendFile(staticFilePath, req, res);
429
490
  return;
430
491
  }
431
492
  } catch {
432
493
  }
494
+ const matchingShell = findMatchingShellRoute(pathname);
495
+ if (matchingShell) {
496
+ const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
497
+ try {
498
+ const stat = await fs.promises.stat(shellPath);
499
+ if (stat.isFile()) {
500
+ await sendFile(shellPath, req, res);
501
+ return;
502
+ }
503
+ } catch {
504
+ }
505
+ }
433
506
  const indexPath = path.join(DIST_DIR, "index.html");
434
507
  try {
435
508
  await fs.promises.access(indexPath);
@@ -464,6 +537,7 @@ async function start() {
464
537
  `);
465
538
  process.exit(1);
466
539
  }
540
+ getShellRoutes();
467
541
  const port = await findFreePort(DEFAULT_PORT);
468
542
  const handler = compose([
469
543
  async (req, res, next) => {
@@ -499,7 +573,7 @@ async function start() {
499
573
  process.on("SIGTERM", shutdown);
500
574
  process.on("SIGINT", shutdown);
501
575
  }
502
- var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, CORS_ENABLED, C, API_EXTS, CATCH_ALL_PATTERN, DYNAMIC_PATTERN, SKIP_PATTERN, routeCache, routeIndex, moduleCache, CORS_HEADERS, MIME_TYPES;
576
+ var DEFAULT_PORT, BODY_TIMEOUT, HANDLER_TIMEOUT, BODY_SIZE_LIMIT, API_DIR, DIST_DIR, CORS_ENABLED, C, shellRouteCache, routeCache, routeIndex, API_EXTS, CATCH_ALL_PATTERN, DYNAMIC_PATTERN, SKIP_PATTERN, moduleCache, CORS_HEADERS, MIME_TYPES;
503
577
  var init_src = __esm({
504
578
  "src/index.ts"() {
505
579
  "use strict";
@@ -519,12 +593,13 @@ var init_src = __esm({
519
593
  BOLD: "\x1B[1m",
520
594
  DIM: "\x1B[2m"
521
595
  };
596
+ shellRouteCache = null;
597
+ routeCache = null;
598
+ routeIndex = /* @__PURE__ */ new Map();
522
599
  API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
523
600
  CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
524
601
  DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
525
602
  SKIP_PATTERN = /^[_.]/;
526
- routeCache = null;
527
- routeIndex = /* @__PURE__ */ new Map();
528
603
  moduleCache = /* @__PURE__ */ new Map();
529
604
  CORS_HEADERS = {
530
605
  "Access-Control-Allow-Origin": "*",
package/dist/index.js CHANGED
@@ -21,16 +21,10 @@ function detectEnvFiles(root) {
21
21
  }
22
22
  function getEnvVar(key, defaultValue) {
23
23
  const biniKey = `BINI_${key}`;
24
- if (process.env[biniKey] !== void 0) {
25
- return process.env[biniKey];
26
- }
24
+ if (process.env[biniKey] !== void 0) return process.env[biniKey];
27
25
  const viteKey = `VITE_${key}`;
28
- if (process.env[viteKey] !== void 0) {
29
- return process.env[viteKey];
30
- }
31
- if (process.env[key] !== void 0) {
32
- return process.env[key];
33
- }
26
+ if (process.env[viteKey] !== void 0) return process.env[viteKey];
27
+ if (process.env[key] !== void 0) return process.env[key];
34
28
  return defaultValue;
35
29
  }
36
30
  function getEnvVarBoolean(key, defaultValue) {
@@ -60,6 +54,66 @@ var C = {
60
54
  BOLD: "\x1B[1m",
61
55
  DIM: "\x1B[2m"
62
56
  };
57
+ function scanShellRoutes() {
58
+ const shellRoutes = /* @__PURE__ */ new Set();
59
+ const rootDir = DIST_DIR;
60
+ function walkDir(dir, currentPath) {
61
+ try {
62
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
63
+ for (const entry of entries) {
64
+ if (!entry.isDirectory()) continue;
65
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
66
+ const fullPath = path.join(dir, entry.name);
67
+ const routePath = currentPath ? `${currentPath}/${entry.name}` : entry.name;
68
+ if (entry.name.startsWith("[") && entry.name.endsWith("]")) {
69
+ const indexPath = path.join(fullPath, "index.html");
70
+ if (fs.existsSync(indexPath)) {
71
+ shellRoutes.add(`/${routePath}`);
72
+ }
73
+ }
74
+ walkDir(fullPath, routePath);
75
+ }
76
+ } catch {
77
+ }
78
+ }
79
+ try {
80
+ walkDir(rootDir, "");
81
+ } catch {
82
+ }
83
+ return shellRoutes;
84
+ }
85
+ var shellRouteCache = null;
86
+ function getShellRoutes() {
87
+ if (!shellRouteCache) {
88
+ shellRouteCache = scanShellRoutes();
89
+ }
90
+ return shellRouteCache;
91
+ }
92
+ function findMatchingShellRoute(pathname) {
93
+ const shellRoutes = getShellRoutes();
94
+ const cleanPath = pathname.replace(/^\/|\/$/g, "");
95
+ const pathSegments = cleanPath.split("/").filter(Boolean);
96
+ for (const shellRoute of shellRoutes) {
97
+ const cleanShell = shellRoute.replace(/^\/|\/$/g, "");
98
+ const shellSegments = cleanShell.split("/").filter(Boolean);
99
+ if (shellSegments.length !== pathSegments.length) continue;
100
+ let matches = true;
101
+ for (let i = 0; i < shellSegments.length; i++) {
102
+ const segment = shellSegments[i];
103
+ if (segment.startsWith("[") && segment.endsWith("]")) {
104
+ continue;
105
+ }
106
+ if (segment !== pathSegments[i]) {
107
+ matches = false;
108
+ break;
109
+ }
110
+ }
111
+ if (matches) {
112
+ return shellRoute;
113
+ }
114
+ }
115
+ return null;
116
+ }
63
117
  function getNetworkIp() {
64
118
  const ifaces = os.networkInterfaces();
65
119
  const SKIP = /docker|veth|br-|lo|loopback|vmnet|vbox|utun|tun|tap/i;
@@ -117,17 +171,15 @@ async function findFreePort(start2) {
117
171
  throw new Error(`No free port found in range ${start2}\u2013${start2 + 99}`);
118
172
  }
119
173
  function startKeyboardLoop(port) {
120
- if (!process.stdin.isTTY) {
121
- return;
122
- }
174
+ if (!process.stdin.isTTY) return;
123
175
  const rl = readline.createInterface({ input: process.stdin });
124
176
  rl.on("line", (line) => {
125
177
  switch (line.trim()) {
126
178
  case "h":
127
179
  console.log("");
128
180
  console.log(" Shortcuts");
129
- console.log(` ${C.DIM}press ${C.RESET}o + enter${C.DIM} to open in browser${C.RESET}`);
130
- console.log(` ${C.DIM}press ${C.RESET}q + enter${C.DIM} to quit${C.RESET}`);
181
+ console.log(` ${C.DIM}press ${C.RESET}o + enter${C.RESET} to open in browser${C.RESET}`);
182
+ console.log(` ${C.DIM}press ${C.RESET}q + enter${C.RESET} to quit${C.RESET}`);
131
183
  console.log("");
132
184
  break;
133
185
  case "o": {
@@ -142,12 +194,12 @@ function startKeyboardLoop(port) {
142
194
  });
143
195
  rl.on("close", () => process.exit(0));
144
196
  }
197
+ var routeCache = null;
198
+ var routeIndex = /* @__PURE__ */ new Map();
145
199
  var API_EXTS = /* @__PURE__ */ new Set([".ts", ".js"]);
146
200
  var CATCH_ALL_PATTERN = /^\[\.\.\.[^\]]+\]$/;
147
201
  var DYNAMIC_PATTERN = /^\[[^\]]+\]$/;
148
202
  var SKIP_PATTERN = /^[_.]/;
149
- var routeCache = null;
150
- var routeIndex = /* @__PURE__ */ new Map();
151
203
  function getRouteCache() {
152
204
  if (!routeCache) {
153
205
  const start2 = Date.now();
@@ -157,7 +209,7 @@ function getRouteCache() {
157
209
  routeIndex.set(routeCache[i].routePath, routeCache[i]);
158
210
  }
159
211
  if (process.env.NODE_ENV === "development") {
160
- console.log(`[bini-server] Routes scanned in ${Date.now() - start2}ms`);
212
+ console.log(`[bini-server] API routes scanned in ${Date.now() - start2}ms`);
161
213
  }
162
214
  }
163
215
  return routeCache;
@@ -287,9 +339,6 @@ var CORS_HEADERS = {
287
339
  "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Request-ID",
288
340
  "Vary": "Origin"
289
341
  };
290
- function invokeHono(honoApp, request) {
291
- return honoApp.fetch(request, process.env);
292
- }
293
342
  async function handleApiRequest(req, res, next) {
294
343
  if (req.method === "OPTIONS") {
295
344
  const headers = CORS_ENABLED ? { ...CORS_HEADERS, "Access-Control-Max-Age": "86400" } : {};
@@ -354,7 +403,7 @@ async function handleApiRequest(req, res, next) {
354
403
  try {
355
404
  if (typeof handler.fetch === "function") {
356
405
  const honoUrl = `http://${host}${pathname.replace(/^\/api/, "") || "/"}${search}`;
357
- webRes = await invokeHono(handler, new Request(honoUrl, {
406
+ webRes = await handler.fetch(new Request(honoUrl, {
358
407
  method,
359
408
  headers: normalizedHeaders,
360
409
  body: body ? new Uint8Array(body) : null
@@ -458,15 +507,40 @@ var MIME_TYPES = {
458
507
  async function serveStatic(req, res, next) {
459
508
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
460
509
  if (pathname.startsWith("/api")) return next();
461
- const filePath = path.join(DIST_DIR, pathname);
510
+ const hasExtension = path.extname(pathname).length > 0;
511
+ if (hasExtension) {
512
+ const filePath = path.join(DIST_DIR, pathname);
513
+ try {
514
+ const stat = await fs.promises.stat(filePath);
515
+ if (stat.isFile()) {
516
+ await sendFile(filePath, req, res);
517
+ return;
518
+ }
519
+ } catch {
520
+ }
521
+ return next();
522
+ }
523
+ const staticFilePath = path.join(DIST_DIR, pathname, "index.html");
462
524
  try {
463
- const stat = await fs.promises.stat(filePath);
525
+ const stat = await fs.promises.stat(staticFilePath);
464
526
  if (stat.isFile()) {
465
- await sendFile(filePath, req, res);
527
+ await sendFile(staticFilePath, req, res);
466
528
  return;
467
529
  }
468
530
  } catch {
469
531
  }
532
+ const matchingShell = findMatchingShellRoute(pathname);
533
+ if (matchingShell) {
534
+ const shellPath = path.join(DIST_DIR, matchingShell, "index.html");
535
+ try {
536
+ const stat = await fs.promises.stat(shellPath);
537
+ if (stat.isFile()) {
538
+ await sendFile(shellPath, req, res);
539
+ return;
540
+ }
541
+ } catch {
542
+ }
543
+ }
470
544
  const indexPath = path.join(DIST_DIR, "index.html");
471
545
  try {
472
546
  await fs.promises.access(indexPath);
@@ -501,6 +575,7 @@ async function start() {
501
575
  `);
502
576
  process.exit(1);
503
577
  }
578
+ getShellRoutes();
504
579
  const port = await findFreePort(DEFAULT_PORT);
505
580
  const handler = compose([
506
581
  async (req, res, next) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bini-server",
3
- "version": "1.0.10",
3
+ "version": "2.0.0",
4
4
  "description": "Production server for bini-router apps.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -40,6 +40,7 @@
40
40
  "bini-router",
41
41
  "server",
42
42
  "spa",
43
+ "ssg",
43
44
  "vite",
44
45
  "hono",
45
46
  "production",