barejs 0.1.54 → 0.1.56

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.
@@ -23,10 +23,11 @@ export let BARE_CONFIG = DEFAULT_CONFIG;
23
23
 
24
24
 
25
25
  export const initConfig = (userConfig: Partial<BareConfig> = {}) => {
26
+ const cfg = userConfig && typeof userConfig === 'object' && !Array.isArray(userConfig) ? userConfig : {};
26
27
  BARE_CONFIG = {
27
28
  ...DEFAULT_CONFIG,
28
- ...userConfig,
29
- hash: { ...DEFAULT_CONFIG.hash, ...userConfig.hash }
29
+ ...cfg,
30
+ hash: { ...DEFAULT_CONFIG.hash, ...(cfg.hash && typeof cfg.hash === 'object' && !Array.isArray(cfg.hash) ? cfg.hash : {}) }
30
31
  };
31
32
  return BARE_CONFIG;
32
33
  };
@@ -1,5 +1,25 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
2
 
3
+ let _userStreamsCreated = 0;
4
+ const _userStreams = new WeakSet<ReadableStream>();
5
+ if (typeof globalThis.ReadableStream === 'function' && !(globalThis.ReadableStream as any).__bareTracked) {
6
+ const OrigRS = globalThis.ReadableStream;
7
+ const ProxiedRS = new Proxy(OrigRS, {
8
+ construct(target, args, newTarget) {
9
+ const inst = Reflect.construct(target, args, newTarget);
10
+ if (args[0] && typeof args[0].pull === 'function') {
11
+ _userStreamsCreated++;
12
+ _userStreams.add(inst);
13
+ }
14
+ return inst;
15
+ }
16
+ });
17
+ (ProxiedRS as any).__bareTracked = true;
18
+ globalThis.ReadableStream = ProxiedRS;
19
+ }
20
+ const _sharedTextDecoder = new TextDecoder();
21
+
22
+
3
23
  export type Params = Record<string, string>;
4
24
  export type Next = () => Promise<any> | any;
5
25
  export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
@@ -53,8 +73,9 @@ export class Context {
53
73
  public _setCookies: string[] | undefined = undefined;
54
74
  public _requestId: string | undefined = undefined;
55
75
  public _peerIp: string | undefined = undefined;
56
- public _trustProxy: boolean = true;
57
- constructor(trustProxy: boolean = true) {
76
+ public _trustProxy: boolean = false;
77
+ public _detached: boolean = false;
78
+ constructor(trustProxy: boolean = false) {
58
79
  this._trustProxy = trustProxy;
59
80
  }
60
81
 
@@ -107,6 +128,17 @@ export class Context {
107
128
  return result;
108
129
  }
109
130
 
131
+ /** All values for a (possibly repeated) query key, in order. */
132
+ public queryAll(key: string): string[] {
133
+ const url = this.req?.url;
134
+ const qIdx = url ? url.indexOf('?') : -1;
135
+ if (qIdx === -1) return [];
136
+ const out: string[] = [];
137
+ const sp = new URLSearchParams(url!.slice(qIdx + 1));
138
+ for (const [k, v] of sp) if (k === key) out.push(v);
139
+ return out;
140
+ }
141
+
110
142
  public getQuery(key: string): string | undefined {
111
143
  const q = this.query;
112
144
  return Object.hasOwn(q, key) ? q[key] : undefined;
@@ -114,7 +146,7 @@ export class Context {
114
146
 
115
147
  public get cookies(): Record<string, string> {
116
148
  if (this._cookies !== undefined) return this._cookies;
117
- const result: Record<string, string> = {};
149
+ const result: Record<string, string> = Object.create(null);
118
150
  const header = this.req?.headers?.get('cookie');
119
151
  if (header) {
120
152
  let start = 0;
@@ -151,6 +183,10 @@ export class Context {
151
183
  if (options.domain && /[\r\n;]/.test(options.domain)) {
152
184
  throw new Error('Invalid cookie domain');
153
185
  }
186
+ const sameSite = options.sameSite ?? 'Lax';
187
+ if (sameSite !== 'Strict' && sameSite !== 'Lax' && sameSite !== 'None') {
188
+ throw new Error('Invalid cookie sameSite');
189
+ }
154
190
  let finalVal = value;
155
191
  if (options.secret) {
156
192
  const sig = createHmac('sha256', options.secret).update(value).digest('base64url');
@@ -159,11 +195,15 @@ export class Context {
159
195
  let cookieStr = `${name}=${encodeURIComponent(finalVal)}`;
160
196
  cookieStr += `; Path=${path}`;
161
197
  if (options.domain) cookieStr += `; Domain=${options.domain}`;
162
- if (options.maxAge !== undefined) cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
163
- if (options.expires) cookieStr += `; Expires=${options.expires.toUTCString()}`;
198
+ if (options.maxAge !== undefined && Number.isFinite(options.maxAge)) {
199
+ cookieStr += `; Max-Age=${Math.floor(options.maxAge)}`;
200
+ }
201
+ if (options.expires && !Number.isNaN(options.expires.getTime())) {
202
+ cookieStr += `; Expires=${options.expires.toUTCString()}`;
203
+ }
164
204
  if (options.httpOnly !== false) cookieStr += '; HttpOnly';
165
205
  if (options.secure) cookieStr += '; Secure';
166
- cookieStr += `; SameSite=${options.sameSite ?? 'Lax'}`;
206
+ cookieStr += `; SameSite=${sameSite}`;
167
207
 
168
208
  if (!this._setCookies) this._setCookies = [];
169
209
  this._setCookies.push(cookieStr);
@@ -171,12 +211,15 @@ export class Context {
171
211
  }
172
212
 
173
213
  public getSignedCookie(name: string, secret: string): string | null {
174
- const raw = this.cookies[name];
175
- if (!raw) return null;
214
+ const cookies = this.cookies;
215
+ if (!Object.hasOwn(cookies, name)) return null;
216
+ const raw = cookies[name];
217
+ if (typeof raw !== 'string' || !raw) return null;
176
218
  const dotIdx = raw.lastIndexOf('.');
177
- if (dotIdx <= 0) return null;
219
+ if (dotIdx < 0) return null;
178
220
  const value = raw.slice(0, dotIdx);
179
221
  const sigB64 = raw.slice(dotIdx + 1);
222
+ if (!/^[A-Za-z0-9_-]{43}$/.test(sigB64)) return null;
180
223
  const expected = createHmac('sha256', secret).update(value).digest();
181
224
  const actual = Buffer.from(sigB64, 'base64url');
182
225
  if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
@@ -185,7 +228,7 @@ export class Context {
185
228
  return value;
186
229
  }
187
230
 
188
- public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): this {
231
+ public deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain' | 'secure' | 'sameSite'> = {}): this {
189
232
  return this.setCookie(name, '', {
190
233
  ...options,
191
234
  maxAge: 0,
@@ -193,42 +236,132 @@ export class Context {
193
236
  });
194
237
  }
195
238
 
196
- public async jsonBody(maxBytes: number = 1048576): Promise<any> {
239
+ private async readBodyWithLimit(maxBytes: number): Promise<Uint8Array> {
240
+ const reader = this.req.body!.getReader();
241
+ const chunks: Uint8Array[] = [];
242
+ let received = 0;
243
+ while (true) {
244
+ const { done, value } = await reader.read();
245
+ if (done) break;
246
+ if (value) {
247
+ received += value.byteLength;
248
+ if (received > maxBytes) {
249
+ try { await reader.cancel(); } catch {}
250
+ throw Object.assign(new Error("Payload Too Large"), { status: 413 });
251
+ }
252
+ chunks.push(value);
253
+ }
254
+ }
255
+ const combined = new Uint8Array(received);
256
+ let offset = 0;
257
+ for (let i = 0; i < chunks.length; i++) {
258
+ combined.set(chunks[i]!, offset);
259
+ offset += chunks[i]!.byteLength;
260
+ }
261
+ return combined;
262
+ }
263
+
264
+ private _parseAndSanitizeJson(text: string, maxBytes: number): any {
265
+ if (text.length > maxBytes || (text.length * 3 > maxBytes && Buffer.byteLength(text, 'utf-8') > maxBytes)) {
266
+ const err: any = new Error("Payload Too Large");
267
+ err.status = 413;
268
+ throw err;
269
+ }
270
+ const parsed = JSON.parse(text);
271
+ if (
272
+ text.indexOf('__proto__') !== -1 ||
273
+ text.indexOf('constructor') !== -1 ||
274
+ text.indexOf('prototype') !== -1 ||
275
+ text.indexOf('\\u') !== -1
276
+ ) {
277
+ const stack: any[] = [parsed];
278
+ while (stack.length > 0) {
279
+ const cur = stack.pop();
280
+ if (!cur || typeof cur !== 'object') continue;
281
+ if (Array.isArray(cur)) {
282
+ for (let i = 0; i < cur.length; i++) stack.push(cur[i]);
283
+ } else {
284
+ if (Object.hasOwn(cur, '__proto__')) delete cur['__proto__'];
285
+ if (Object.hasOwn(cur, 'constructor')) delete cur['constructor'];
286
+ if (Object.hasOwn(cur, 'prototype')) delete cur['prototype'];
287
+ const keys = Object.keys(cur);
288
+ for (let i = 0; i < keys.length; i++) stack.push(cur[keys[i]!]);
289
+ }
290
+ }
291
+ }
292
+ return this.body = parsed;
293
+ }
294
+
295
+ public jsonBodySyncOrAsync(maxBytes: number = 1048576): any {
197
296
  if (this.body !== undefined) return this.body;
198
297
 
199
- const contentType = this.req.headers.get("content-type");
200
- if (contentType && contentType.includes("application/json")) {
201
- const lenHeader = this.req.headers.get("content-length");
298
+ const headers = this.req.headers;
299
+ const contentType = headers.get("content-type");
300
+ if (
301
+ contentType &&
302
+ (contentType === "application/json" ||
303
+ contentType.startsWith("application/json;") ||
304
+ contentType.toLowerCase().includes("application/json"))
305
+ ) {
306
+ const lenHeader = headers.get("content-length");
202
307
  if (lenHeader !== null) {
203
308
  const trimmed = lenHeader.trim();
204
309
  const lenNum = trimmed.length > 0 ? Number(trimmed) : NaN;
205
- if (Number.isInteger(lenNum) && lenNum >= 0) {
206
- if (lenNum > maxBytes) {
207
- const err: any = new Error("Payload Too Large");
208
- err.status = 413;
209
- throw err;
210
- }
211
- try {
212
- return this.body = await this.req.json();
213
- } catch {
214
- return this.body = null;
215
- }
216
- }
217
- }
218
- try {
219
- const text = await this.req.text();
220
- if (Buffer.byteLength(text, 'utf-8') > maxBytes) {
310
+ if (Number.isInteger(lenNum) && lenNum > maxBytes) {
221
311
  const err: any = new Error("Payload Too Large");
222
312
  err.status = 413;
223
313
  throw err;
224
314
  }
225
- return this.body = JSON.parse(text);
226
- } catch (e: any) {
227
- if (e?.status === 413) throw e;
228
- return this.body = null;
229
315
  }
316
+ if (
317
+ (lenHeader === null && headers.get("transfer-encoding") !== null) ||
318
+ (_userStreamsCreated > 0 && this.req.body && _userStreams.has(this.req.body))
319
+ ) {
320
+ return this.readBodyWithLimit(maxBytes).then(
321
+ (bytes) => {
322
+ try {
323
+ return this._parseAndSanitizeJson(_sharedTextDecoder.decode(bytes), maxBytes);
324
+ } catch (e: any) {
325
+ if (e?.status === 413) throw e;
326
+ return (this.body = null);
327
+ }
328
+ },
329
+ (e: any) => {
330
+ if (e?.status === 413) throw e;
331
+ return (this.body = null);
332
+ }
333
+ );
334
+ }
335
+ const tp = this.req.text();
336
+ const peeked = Bun.peek(tp);
337
+ if (typeof peeked === "string") {
338
+ try {
339
+ return this._parseAndSanitizeJson(peeked, maxBytes);
340
+ } catch (e: any) {
341
+ if (e?.status === 413) throw e;
342
+ return (this.body = null);
343
+ }
344
+ }
345
+ return tp.then(
346
+ (text) => {
347
+ try {
348
+ return this._parseAndSanitizeJson(text, maxBytes);
349
+ } catch (e: any) {
350
+ if (e?.status === 413) throw e;
351
+ return (this.body = null);
352
+ }
353
+ },
354
+ (e: any) => {
355
+ if (e?.status === 413) throw e;
356
+ return (this.body = null);
357
+ }
358
+ );
230
359
  }
231
- return this.body = null;
360
+ return (this.body = null);
361
+ }
362
+
363
+ public async jsonBody(maxBytes: number = 1048576): Promise<any> {
364
+ return this.jsonBodySyncOrAsync(maxBytes);
232
365
  }
233
366
 
234
367
  public reset(req: Request): this {
@@ -241,7 +374,9 @@ export class Context {
241
374
  this._cookies = undefined;
242
375
  this._setCookies = undefined;
243
376
  this.body = undefined;
377
+ this._requestId = undefined;
244
378
  this._peerIp = undefined;
379
+ this._detached = false;
245
380
  return this;
246
381
  }
247
382
 
@@ -269,14 +404,9 @@ export class Context {
269
404
  ? Response.json(data)
270
405
  : Response.json(data, { status });
271
406
  } else {
272
- let headers = this._headers;
273
- if (headers["content-type"] === undefined) {
274
- if (Object.isFrozen(headers)) {
275
- headers = { ...headers };
276
- this._headers = headers;
277
- }
278
- headers["content-type"] = "application/json";
279
- }
407
+ const headers = this._headers["content-type"] === undefined
408
+ ? { ...this._headers, "content-type": "application/json" }
409
+ : this._headers;
280
410
  res = Response.json(data, {
281
411
  status,
282
412
  headers: headers as any
@@ -298,7 +428,15 @@ export class Context {
298
428
  public setHeader(name: string, value: string): this {
299
429
  if (!this._headers) this._headers = {};
300
430
  else if (Object.isFrozen(this._headers)) this._headers = { ...this._headers };
301
- this._headers[name.toLowerCase()] = value;
431
+ const lower = name.toLowerCase();
432
+ if (lower === 'vary' && this._headers['vary']) {
433
+ const existing = this._headers['vary'];
434
+ const parts = existing.toLowerCase().split(',').map((s) => s.trim());
435
+ const toAdd = value.split(',').map((s) => s.trim()).filter((s) => s && !parts.includes(s.toLowerCase()));
436
+ this._headers['vary'] = toAdd.length > 0 ? `${existing}, ${toAdd.join(', ')}` : existing;
437
+ } else {
438
+ this._headers[lower] = value;
439
+ }
302
440
  return this;
303
441
  }
304
442
 
@@ -319,24 +457,27 @@ export class Context {
319
457
 
320
458
  public html(content: string, status?: number): Response {
321
459
  const headers: Record<string, string> = {
322
- 'content-type': 'text/html; charset=utf-8',
323
- ...(this._headers || {})
460
+ ...(this._headers || {}),
461
+ 'content-type': 'text/html; charset=utf-8'
324
462
  };
325
463
  return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
326
464
  }
327
465
 
328
466
  public text(content: string, status?: number): Response {
329
467
  const headers: Record<string, string> = {
330
- 'content-type': 'text/plain; charset=utf-8',
331
- ...(this._headers || {})
468
+ ...(this._headers || {}),
469
+ 'content-type': 'text/plain; charset=utf-8'
332
470
  };
333
471
  return this._applyCookies(new Response(content, { status: status ?? this._status, headers }));
334
472
  }
335
473
 
336
474
  public redirect(url: string, status: number = 302): Response {
475
+ if (/[\r\n]/.test(url)) {
476
+ throw new Error('Invalid redirect URL');
477
+ }
337
478
  const headers: Record<string, string> = {
338
- 'location': url,
339
- ...(this._headers || {})
479
+ ...(this._headers || {}),
480
+ 'location': url
340
481
  };
341
482
  return this._applyCookies(new Response(null, { status, headers }));
342
483
  }
@@ -347,44 +488,60 @@ export class Context {
347
488
  | ((send: (data: any, event?: string, id?: string) => void, close: () => void) => Promise<void> | void)
348
489
  ): Response {
349
490
  const encoder = new TextEncoder();
491
+ const formatDataLines = (raw: string): string =>
492
+ raw.split(/\r\n|\r|\n/).map((line) => `data: ${line}`).join('\n') + '\n\n';
350
493
  const formatChunk = (chunk: string | { event?: string; data: any; id?: string; retry?: number }): Uint8Array => {
351
494
  if (typeof chunk === 'string') {
352
- return encoder.encode(`data: ${chunk}\n\n`);
495
+ return encoder.encode(formatDataLines(chunk));
353
496
  }
354
497
  let out = '';
355
- if (chunk.id !== undefined) out += `id: ${chunk.id}\n`;
356
- if (chunk.event !== undefined) out += `event: ${chunk.event}\n`;
357
- if (chunk.retry !== undefined) out += `retry: ${chunk.retry}\n`;
358
- const payload = typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data);
359
- out += `data: ${payload}\n\n`;
498
+ if (chunk.id !== undefined) out += `id: ${String(chunk.id).replace(/[\r\n]/g, '')}\n`;
499
+ if (chunk.event !== undefined) out += `event: ${String(chunk.event).replace(/[\r\n]/g, '')}\n`;
500
+ if (chunk.retry !== undefined && Number.isFinite(chunk.retry)) out += `retry: ${Math.max(0, Math.floor(chunk.retry))}\n`;
501
+ const payload = chunk.data === undefined
502
+ ? ''
503
+ : (typeof chunk.data === 'string' ? chunk.data : JSON.stringify(chunk.data));
504
+ out += formatDataLines(payload);
360
505
  return encoder.encode(out);
361
506
  };
362
507
 
508
+ let closed = false;
363
509
  const stream = new ReadableStream<Uint8Array>({
364
510
  async start(controller) {
511
+ const safeClose = () => {
512
+ if (!closed) {
513
+ closed = true;
514
+ try { controller.close(); } catch { /* already closed */ }
515
+ }
516
+ };
365
517
  try {
366
518
  if (typeof source === 'function') {
367
- let closed = false;
368
519
  const send = (data: any, event?: string, id?: string) => {
369
- if (!closed) controller.enqueue(formatChunk({ data, event, id }));
370
- };
371
- const close = () => {
372
520
  if (!closed) {
373
- closed = true;
374
- controller.close();
521
+ try { controller.enqueue(formatChunk({ data, event, id })); } catch { closed = true; }
375
522
  }
376
523
  };
377
- await source(send, close);
378
- close();
524
+ const maybePromise = source(send, safeClose);
525
+ if (maybePromise && typeof (maybePromise as any).then === 'function') {
526
+ await maybePromise;
527
+ safeClose();
528
+ }
379
529
  } else {
380
530
  for await (const item of source) {
381
- controller.enqueue(formatChunk(item));
531
+ if (closed) break;
532
+ try { controller.enqueue(formatChunk(item)); } catch { closed = true; break; }
382
533
  }
383
- controller.close();
534
+ safeClose();
384
535
  }
385
536
  } catch (err) {
386
- controller.error(err);
537
+ if (!closed) {
538
+ closed = true;
539
+ try { controller.error(err); } catch { /* already closed */ }
540
+ }
387
541
  }
542
+ },
543
+ cancel() {
544
+ closed = true;
388
545
  }
389
546
  });
390
547
 
@@ -399,18 +556,22 @@ export class Context {
399
556
 
400
557
  public get requestId(): string {
401
558
  if (this._requestId !== undefined) return this._requestId;
402
- const hdr = this.req?.headers?.get('x-request-id');
403
- this._requestId = hdr && hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
559
+ const raw = this.req?.headers?.get('x-request-id');
560
+ const hdr = raw ? raw.replace(/[\x00-\x1f\x7f]/g, '') : '';
561
+ this._requestId = hdr.length > 0 && hdr.length <= 128 ? hdr : crypto.randomUUID();
404
562
  return this._requestId;
405
563
  }
406
564
 
407
565
  public get ip(): string {
408
566
  if (this._trustProxy) {
409
567
  const xff = this.req?.headers?.get('x-forwarded-for');
410
- if (xff) return xff.split(',')[0]!.trim();
568
+ if (xff) {
569
+ const first = xff.split(',')[0]?.trim();
570
+ if (first) return first;
571
+ }
411
572
  const forwarded =
412
- this.req?.headers?.get('x-real-ip') ||
413
- this.req?.headers?.get('cf-connecting-ip');
573
+ this.req?.headers?.get('x-real-ip')?.trim() ||
574
+ this.req?.headers?.get('cf-connecting-ip')?.trim();
414
575
  if (forwarded) return forwarded;
415
576
  }
416
577
  return this._peerIp || '127.0.0.1';
@@ -419,24 +580,44 @@ export class Context {
419
580
  public async upload(options: UploadOptions = {}): Promise<UploadResult> {
420
581
  const maxFileSize = options.maxFileSize ?? 5 * 1024 * 1024;
421
582
  const maxFiles = options.maxFiles ?? 10;
422
- const allowed = options.allowedTypes ? new Set(options.allowedTypes) : null;
583
+ const allowed = options.allowedTypes
584
+ ? new Set(options.allowedTypes.map((t) => t.trim().toLowerCase()))
585
+ : null;
423
586
 
424
- const ct = this.req?.headers?.get('content-type') || '';
587
+ const ct = (this.req?.headers?.get('content-type') || '').toLowerCase();
425
588
  if (!ct.includes('multipart/form-data')) {
426
589
  throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
427
590
  }
428
591
 
592
+ const maxTotalBytes = maxFileSize * maxFiles;
593
+ const maxRawBytes = maxTotalBytes + 65536;
429
594
  const contentLen = Number(this.req?.headers?.get('content-length') || 0);
430
- if (contentLen > maxFileSize * maxFiles + 65536) {
595
+ if (Number.isFinite(contentLen) && contentLen > maxRawBytes) {
431
596
  throw Object.assign(new Error('Payload Too Large'), { status: 413 });
432
597
  }
433
598
 
434
- const form = await this.req.formData();
599
+ let form: Awaited<ReturnType<Request['formData']>>;
600
+ try {
601
+ if (this.req.body) {
602
+ const combined = await this.readBodyWithLimit(maxRawBytes);
603
+ form = await new Response(combined, { headers: this.req.headers }).formData();
604
+ } else {
605
+ form = await this.req.formData();
606
+ }
607
+ } catch (e: any) {
608
+ if (e?.status === 413) throw e;
609
+ throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
610
+ }
435
611
  const fields: Record<string, string> = {};
436
612
  const files: UploadedFile[] = [];
613
+ let totalBytes = 0;
437
614
 
438
615
  for (const [fieldName, value] of form.entries()) {
439
616
  if (typeof value === 'string') {
617
+ totalBytes += Buffer.byteLength(value, 'utf-8');
618
+ if (totalBytes > maxTotalBytes) {
619
+ throw Object.assign(new Error(`Total upload size exceeds ${maxTotalBytes} bytes`), { status: 413 });
620
+ }
440
621
  if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
441
622
  fields[fieldName] = value;
442
623
  }
@@ -450,6 +631,10 @@ export class Context {
450
631
  if (fileObj.size > maxFileSize) {
451
632
  throw Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
452
633
  }
634
+ totalBytes += fileObj.size;
635
+ if (totalBytes > maxTotalBytes) {
636
+ throw Object.assign(new Error(`Total upload size exceeds ${maxTotalBytes} bytes`), { status: 413 });
637
+ }
453
638
  const mime = (fileObj.type || '').split(';')[0]!.trim().toLowerCase();
454
639
  if (allowed && !allowed.has(mime)) {
455
640
  throw Object.assign(new Error(`Unsupported file type: ${fileObj.type || 'unknown'}`), { status: 415 });
@@ -1,13 +1,23 @@
1
1
  // src/core/loader.ts
2
+ import { existsSync } from "node:fs";
3
+ import { createRequire } from "node:module";
2
4
  import { join } from "node:path";
3
5
  import { initConfig } from "./config";
4
6
 
7
+ const req = createRequire(import.meta.url);
8
+
5
9
  export async function bootstrapConfig() {
6
10
  const configPath = join(process.cwd(), "bare.config.ts");
11
+ if (!existsSync(configPath)) {
12
+ return initConfig();
13
+ }
7
14
  try {
8
- const userModule = await import(configPath);
9
- return initConfig(userModule.default);
10
- } catch {
15
+ const resolved = req.resolve(configPath);
16
+ delete req.cache[resolved];
17
+ const userModule = req(resolved);
18
+ return initConfig(userModule?.default ?? userModule);
19
+ } catch (err: any) {
20
+ console.warn(`[BareJS] Failed to load bare.config.ts:`, err?.message || err);
11
21
  return initConfig();
12
22
  }
13
23
  }