barejs 0.1.56 → 0.1.58
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/README.md +32 -18
- package/dist/index.js +198 -186
- package/dist/types/core/bare.d.ts +16 -0
- package/dist/types/core/context.d.ts +24 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/index.d.ts +2 -2
- package/llms.txt +4 -1
- package/package.json +1 -1
- package/src/core/bare.ts +153 -42
- package/src/core/context.ts +290 -0
- package/src/core/router.ts +6 -0
- package/src/index.ts +4 -2
- package/src/security/idempotency.ts +3 -1
package/src/core/context.ts
CHANGED
|
@@ -61,6 +61,27 @@ export interface UploadResult {
|
|
|
61
61
|
files: UploadedFile[];
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
+
export interface UploadStreamOptions {
|
|
65
|
+
/** Max size per file in bytes (default: 100MB) */
|
|
66
|
+
maxFileSize?: number;
|
|
67
|
+
/** Max number of uploaded files (default: 10) */
|
|
68
|
+
maxFiles?: number;
|
|
69
|
+
/** Max size per text field in bytes (default: 1MB) */
|
|
70
|
+
maxFieldSize?: number;
|
|
71
|
+
/** Allowed MIME types (e.g. ['image/png', 'application/octet-stream']) */
|
|
72
|
+
allowedTypes?: string[];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface UploadStreamPart {
|
|
76
|
+
type: 'file' | 'field';
|
|
77
|
+
fieldName: string;
|
|
78
|
+
filename?: string;
|
|
79
|
+
safeName?: string;
|
|
80
|
+
contentType?: string;
|
|
81
|
+
stream?: ReadableStream<Uint8Array>;
|
|
82
|
+
value?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
64
85
|
export class Context {
|
|
65
86
|
public req!: Request;
|
|
66
87
|
public params: Params = {};
|
|
@@ -656,4 +677,273 @@ export class Context {
|
|
|
656
677
|
|
|
657
678
|
return { fields, files };
|
|
658
679
|
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* True streaming multipart/form-data parser.
|
|
683
|
+
* Streams file parts chunk-by-chunk with backpressure and constant O(chunk) memory usage.
|
|
684
|
+
*/
|
|
685
|
+
public async *uploadStream(options: UploadStreamOptions = {}): AsyncGenerator<UploadStreamPart> {
|
|
686
|
+
const maxFileSize = options.maxFileSize ?? 100 * 1024 * 1024;
|
|
687
|
+
const maxFiles = options.maxFiles ?? 10;
|
|
688
|
+
const maxFieldSize = options.maxFieldSize ?? 1024 * 1024;
|
|
689
|
+
const allowed = options.allowedTypes
|
|
690
|
+
? new Set(options.allowedTypes.map((t) => t.trim().toLowerCase()))
|
|
691
|
+
: null;
|
|
692
|
+
|
|
693
|
+
const ct = this.req?.headers?.get('content-type') || '';
|
|
694
|
+
if (!ct.toLowerCase().includes('multipart/form-data')) {
|
|
695
|
+
throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
|
|
696
|
+
}
|
|
697
|
+
const bMatch = ct.match(/boundary=(?:"([^"]+)"|([^;\s]+))/i);
|
|
698
|
+
const boundary = bMatch?.[1] || bMatch?.[2];
|
|
699
|
+
if (!boundary) {
|
|
700
|
+
throw Object.assign(new Error('Missing multipart boundary'), { status: 400 });
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (!this.req.body) return;
|
|
704
|
+
|
|
705
|
+
const encoder = new TextEncoder();
|
|
706
|
+
const firstBoundary = encoder.encode(`--${boundary}`);
|
|
707
|
+
const partBoundary = encoder.encode(`\r\n--${boundary}`);
|
|
708
|
+
const crlfcrlf = encoder.encode('\r\n\r\n');
|
|
709
|
+
|
|
710
|
+
const indexOfBytes = (haystack: Uint8Array, needle: Uint8Array, from = 0): number => {
|
|
711
|
+
const nLen = needle.byteLength;
|
|
712
|
+
const limit = haystack.byteLength - nLen;
|
|
713
|
+
const first = needle[0]!;
|
|
714
|
+
let i = from;
|
|
715
|
+
while (i <= limit) {
|
|
716
|
+
const pos = haystack.indexOf(first, i);
|
|
717
|
+
if (pos === -1 || pos > limit) return -1;
|
|
718
|
+
let match = true;
|
|
719
|
+
for (let j = 1; j < nLen; j++) {
|
|
720
|
+
if (haystack[pos + j] !== needle[j]) {
|
|
721
|
+
match = false;
|
|
722
|
+
break;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
if (match) return pos;
|
|
726
|
+
i = pos + 1;
|
|
727
|
+
}
|
|
728
|
+
return -1;
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
const concatBytes = (a: Uint8Array, b: Uint8Array): Uint8Array => {
|
|
732
|
+
if (a.byteLength === 0) return b;
|
|
733
|
+
if (b.byteLength === 0) return a;
|
|
734
|
+
const out = new Uint8Array(a.byteLength + b.byteLength);
|
|
735
|
+
out.set(a, 0);
|
|
736
|
+
out.set(b, a.byteLength);
|
|
737
|
+
return out;
|
|
738
|
+
};
|
|
739
|
+
|
|
740
|
+
const reader = this.req.body.getReader();
|
|
741
|
+
let buf: Uint8Array = new Uint8Array(0);
|
|
742
|
+
let eof = false;
|
|
743
|
+
|
|
744
|
+
const readMore = async (): Promise<boolean> => {
|
|
745
|
+
if (eof) return false;
|
|
746
|
+
const { done, value } = await reader.read();
|
|
747
|
+
if (done || !value) {
|
|
748
|
+
eof = true;
|
|
749
|
+
return false;
|
|
750
|
+
}
|
|
751
|
+
buf = concatBytes(buf, value);
|
|
752
|
+
return true;
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
const ensureBytes = async (minLen: number): Promise<boolean> => {
|
|
756
|
+
while (buf.byteLength < minLen) {
|
|
757
|
+
if (!(await readMore())) return false;
|
|
758
|
+
}
|
|
759
|
+
return true;
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
let fileCount = 0;
|
|
763
|
+
|
|
764
|
+
try {
|
|
765
|
+
// 1. Find initial boundary
|
|
766
|
+
while (true) {
|
|
767
|
+
const idx = indexOfBytes(buf, firstBoundary);
|
|
768
|
+
if (idx !== -1) {
|
|
769
|
+
buf = buf.subarray(idx + firstBoundary.byteLength);
|
|
770
|
+
break;
|
|
771
|
+
}
|
|
772
|
+
if (buf.byteLength > firstBoundary.byteLength) {
|
|
773
|
+
buf = buf.subarray(buf.byteLength - firstBoundary.byteLength);
|
|
774
|
+
}
|
|
775
|
+
if (!(await readMore())) {
|
|
776
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// Check for immediate closing "--" or "\r\n"
|
|
781
|
+
while (true) {
|
|
782
|
+
if (!(await ensureBytes(2))) {
|
|
783
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
784
|
+
}
|
|
785
|
+
if (buf[0] === 0x2d && buf[1] === 0x2d) {
|
|
786
|
+
return; // "--" end of multipart
|
|
787
|
+
}
|
|
788
|
+
if (buf[0] === 0x0d && buf[1] === 0x0a) {
|
|
789
|
+
buf = buf.subarray(2);
|
|
790
|
+
} else if (buf[0] === 0x0a) {
|
|
791
|
+
buf = buf.subarray(1);
|
|
792
|
+
} else {
|
|
793
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// 2. Read part headers up to \r\n\r\n (cap at 16KB)
|
|
797
|
+
let hdrEnd = -1;
|
|
798
|
+
while (true) {
|
|
799
|
+
hdrEnd = indexOfBytes(buf, crlfcrlf);
|
|
800
|
+
if (hdrEnd !== -1) break;
|
|
801
|
+
if (buf.byteLength > 16384) {
|
|
802
|
+
throw Object.assign(new Error('Multipart header too large'), { status: 400 });
|
|
803
|
+
}
|
|
804
|
+
if (!(await readMore())) {
|
|
805
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
const headerText = _sharedTextDecoder.decode(buf.subarray(0, hdrEnd));
|
|
810
|
+
buf = buf.subarray(hdrEnd + 4);
|
|
811
|
+
|
|
812
|
+
let fieldName = '';
|
|
813
|
+
let filename: string | undefined;
|
|
814
|
+
let partContentType = 'application/octet-stream';
|
|
815
|
+
|
|
816
|
+
for (const line of headerText.split('\r\n')) {
|
|
817
|
+
const colon = line.indexOf(':');
|
|
818
|
+
if (colon === -1) continue;
|
|
819
|
+
const k = line.slice(0, colon).trim().toLowerCase();
|
|
820
|
+
const v = line.slice(colon + 1).trim();
|
|
821
|
+
if (k === 'content-disposition') {
|
|
822
|
+
const nameMatch = v.match(/;\s*name="([^"]*)"/i);
|
|
823
|
+
if (nameMatch) fieldName = nameMatch[1]!;
|
|
824
|
+
const fileMatch = v.match(/;\s*filename="([^"]*)"/i);
|
|
825
|
+
if (fileMatch) filename = fileMatch[1]!;
|
|
826
|
+
} else if (k === 'content-type') {
|
|
827
|
+
partContentType = v;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
if (filename === undefined) {
|
|
832
|
+
// 3a. Text field part
|
|
833
|
+
while (true) {
|
|
834
|
+
const bIdx = indexOfBytes(buf, partBoundary);
|
|
835
|
+
if (bIdx !== -1) {
|
|
836
|
+
if (bIdx > maxFieldSize) {
|
|
837
|
+
throw Object.assign(new Error(`Field size exceeds ${maxFieldSize} bytes`), { status: 413 });
|
|
838
|
+
}
|
|
839
|
+
const val = _sharedTextDecoder.decode(buf.subarray(0, bIdx));
|
|
840
|
+
buf = buf.subarray(bIdx + partBoundary.byteLength);
|
|
841
|
+
if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
|
|
842
|
+
yield { type: 'field', fieldName, value: val };
|
|
843
|
+
}
|
|
844
|
+
break;
|
|
845
|
+
}
|
|
846
|
+
if (buf.byteLength - partBoundary.byteLength > maxFieldSize) {
|
|
847
|
+
throw Object.assign(new Error(`Field size exceeds ${maxFieldSize} bytes`), { status: 413 });
|
|
848
|
+
}
|
|
849
|
+
if (!(await readMore())) {
|
|
850
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
} else {
|
|
854
|
+
// 3b. File part (streamed with backpressure)
|
|
855
|
+
if (fileCount >= maxFiles) {
|
|
856
|
+
throw Object.assign(new Error(`Too many files (max ${maxFiles})`), { status: 413 });
|
|
857
|
+
}
|
|
858
|
+
fileCount++;
|
|
859
|
+
|
|
860
|
+
const mime = (partContentType || '').split(';')[0]!.trim().toLowerCase();
|
|
861
|
+
if (allowed && !allowed.has(mime)) {
|
|
862
|
+
throw Object.assign(new Error(`Unsupported file type: ${partContentType || 'unknown'}`), { status: 415 });
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
const baseName = filename.split(/[\\/]/).pop() || 'file';
|
|
866
|
+
const safeName = baseName.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '') || 'file';
|
|
867
|
+
|
|
868
|
+
let fileBytes = 0;
|
|
869
|
+
let streamDone = false;
|
|
870
|
+
let streamErrored: any = null;
|
|
871
|
+
const keepTail = partBoundary.byteLength - 1;
|
|
872
|
+
|
|
873
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
874
|
+
async pull(controller) {
|
|
875
|
+
while (true) {
|
|
876
|
+
const bIdx = indexOfBytes(buf, partBoundary);
|
|
877
|
+
if (bIdx !== -1) {
|
|
878
|
+
const slice = buf.subarray(0, bIdx);
|
|
879
|
+
fileBytes += slice.byteLength;
|
|
880
|
+
if (fileBytes > maxFileSize) {
|
|
881
|
+
streamErrored = Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
882
|
+
controller.error(streamErrored);
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (slice.byteLength > 0) controller.enqueue(slice);
|
|
886
|
+
buf = buf.subarray(bIdx + partBoundary.byteLength);
|
|
887
|
+
streamDone = true;
|
|
888
|
+
controller.close();
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
const safeLen = buf.byteLength - keepTail;
|
|
893
|
+
if (safeLen > 0) {
|
|
894
|
+
const slice = buf.subarray(0, safeLen);
|
|
895
|
+
fileBytes += slice.byteLength;
|
|
896
|
+
if (fileBytes > maxFileSize) {
|
|
897
|
+
streamErrored = Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
898
|
+
controller.error(streamErrored);
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
buf = buf.subarray(safeLen);
|
|
902
|
+
controller.enqueue(slice);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
if (!(await readMore())) {
|
|
907
|
+
streamErrored = Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
908
|
+
controller.error(streamErrored);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
},
|
|
913
|
+
cancel() {
|
|
914
|
+
streamDone = true;
|
|
915
|
+
}
|
|
916
|
+
});
|
|
917
|
+
|
|
918
|
+
yield {
|
|
919
|
+
type: 'file',
|
|
920
|
+
fieldName,
|
|
921
|
+
filename,
|
|
922
|
+
safeName,
|
|
923
|
+
contentType: partContentType,
|
|
924
|
+
stream
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
if (streamErrored) throw streamErrored;
|
|
928
|
+
|
|
929
|
+
// If consumer didn't drain the stream, skip remaining bytes up to next boundary
|
|
930
|
+
if (!streamDone) {
|
|
931
|
+
try {
|
|
932
|
+
const sr = stream.getReader();
|
|
933
|
+
while (true) {
|
|
934
|
+
const { done } = await sr.read();
|
|
935
|
+
if (done) break;
|
|
936
|
+
}
|
|
937
|
+
sr.releaseLock();
|
|
938
|
+
} catch (e) {
|
|
939
|
+
if (streamErrored) throw streamErrored;
|
|
940
|
+
throw e;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
} finally {
|
|
946
|
+
try { reader.releaseLock(); } catch { /* ignore */ }
|
|
947
|
+
}
|
|
948
|
+
}
|
|
659
949
|
}
|
package/src/core/router.ts
CHANGED
|
@@ -70,6 +70,7 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
|
70
70
|
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
71
71
|
declare readonly __routes: Routes;
|
|
72
72
|
public routes: any[] = [];
|
|
73
|
+
protected _onRouteMutate?(): void;
|
|
73
74
|
|
|
74
75
|
constructor(
|
|
75
76
|
public prefix: string = "",
|
|
@@ -97,6 +98,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
97
98
|
path: fullPath || "",
|
|
98
99
|
handlers: [...this.groupMiddleware, ...resolvedHandlers]
|
|
99
100
|
});
|
|
101
|
+
this._onRouteMutate?.();
|
|
100
102
|
return this;
|
|
101
103
|
}
|
|
102
104
|
|
|
@@ -123,6 +125,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
123
125
|
|
|
124
126
|
callback(subRouter);
|
|
125
127
|
this.routes.push(...subRouter.routes);
|
|
128
|
+
this._onRouteMutate?.();
|
|
126
129
|
return this;
|
|
127
130
|
};
|
|
128
131
|
|
|
@@ -137,6 +140,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
137
140
|
handlers: [...this.groupMiddleware, ...r.handlers]
|
|
138
141
|
});
|
|
139
142
|
}
|
|
143
|
+
this._onRouteMutate?.();
|
|
140
144
|
}
|
|
141
145
|
|
|
142
146
|
public route<P extends string, R2 extends RouteSchema = {}>(
|
|
@@ -174,6 +178,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
174
178
|
}
|
|
175
179
|
}
|
|
176
180
|
}
|
|
181
|
+
this._onRouteMutate?.();
|
|
177
182
|
return this;
|
|
178
183
|
}
|
|
179
184
|
|
|
@@ -188,6 +193,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
188
193
|
this.groupMiddleware.push(item);
|
|
189
194
|
}
|
|
190
195
|
}
|
|
196
|
+
this._onRouteMutate?.();
|
|
191
197
|
return this;
|
|
192
198
|
}
|
|
193
199
|
}
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
9
|
+
export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
10
10
|
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
@@ -27,7 +27,9 @@ export type {
|
|
|
27
27
|
CookieOptions,
|
|
28
28
|
UploadOptions,
|
|
29
29
|
UploadedFile,
|
|
30
|
-
UploadResult
|
|
30
|
+
UploadResult,
|
|
31
|
+
UploadStreamOptions,
|
|
32
|
+
UploadStreamPart
|
|
31
33
|
} from './core/context';
|
|
32
34
|
|
|
33
35
|
// --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
|
|
@@ -274,7 +274,9 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
274
274
|
if (!(ctx as any)._detached && !isStream && status >= 200 && status < 300) {
|
|
275
275
|
if (isResp) {
|
|
276
276
|
let cloned: any = null;
|
|
277
|
-
|
|
277
|
+
if (!resVal.bodyUsed) {
|
|
278
|
+
try { cloned = resVal.clone(); } catch { cloned = null; }
|
|
279
|
+
}
|
|
278
280
|
if (cloned) {
|
|
279
281
|
const ct = cloned.headers.get('content-type') || 'application/json';
|
|
280
282
|
return cloned.arrayBuffer().then((buf: ArrayBuffer) => {
|