rossa 0.0.3 → 0.0.5
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.d.ts +100 -26
- package/dist/index.js +2 -2
- package/package.json +5 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,44 @@
|
|
|
1
1
|
import { ServerSide, Auth } from 'authored';
|
|
2
2
|
import * as bun from 'bun';
|
|
3
|
-
import { Server, ServerWebSocket, Serve,
|
|
3
|
+
import { Server, ServerWebSocket, WebSocketHandler, Serve, BunFile } from 'bun';
|
|
4
4
|
|
|
5
5
|
type obj<T> = Record<string, T>;
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* A custom Map implementation that provides additional utility methods for working with objects and maps.
|
|
9
|
+
*
|
|
10
|
+
* @template K - The type of the keys in the map.
|
|
11
|
+
* @template V - The type of the values in the map.
|
|
12
|
+
*/
|
|
13
|
+
declare class Mapper<K, V> extends Map<K, V> {
|
|
14
|
+
obj(obj?: object | null): void;
|
|
15
|
+
map(map: Mapper<K, V>): void;
|
|
16
|
+
ass<T>(key: K, obj: T): void;
|
|
17
|
+
lacks(key: K): boolean;
|
|
18
|
+
init(key: K, val: V): V;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
declare class log {
|
|
22
|
+
static set i(a: any);
|
|
23
|
+
static set e(a: any);
|
|
24
|
+
static set w(a: any);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
declare class Time {
|
|
28
|
+
date: Date;
|
|
29
|
+
constructor(dateMS?: number);
|
|
30
|
+
delta(date2?: number | null, _Date?: boolean): number | Date;
|
|
31
|
+
timed(time?: {
|
|
32
|
+
year?: number;
|
|
33
|
+
month?: number;
|
|
34
|
+
day?: number;
|
|
35
|
+
hour?: number;
|
|
36
|
+
minute?: number;
|
|
37
|
+
second?: number;
|
|
38
|
+
}): Date;
|
|
39
|
+
static delta(date1: number, date2?: number | null): number;
|
|
40
|
+
static local(date: number): string;
|
|
41
|
+
static get now(): number;
|
|
9
42
|
}
|
|
10
43
|
|
|
11
44
|
declare class session {
|
|
@@ -37,6 +70,7 @@ declare class request {
|
|
|
37
70
|
method: string;
|
|
38
71
|
__cookies: Map<string, string>;
|
|
39
72
|
constructor(req: Request, server?: Server | undefined);
|
|
73
|
+
json<T extends {}>(): Promise<T>;
|
|
40
74
|
form(): Promise<FormData>;
|
|
41
75
|
authgroup(): Promise<{
|
|
42
76
|
sid: string;
|
|
@@ -52,6 +86,8 @@ declare class request {
|
|
|
52
86
|
get ip(): bun.SocketAddress | null | undefined;
|
|
53
87
|
get isForm(): boolean;
|
|
54
88
|
get path(): string;
|
|
89
|
+
get hash(): string;
|
|
90
|
+
get fullPath(): string;
|
|
55
91
|
get parsed(): string[];
|
|
56
92
|
get searchParams(): URLSearchParams;
|
|
57
93
|
get range(): string | undefined;
|
|
@@ -85,6 +121,7 @@ declare class response extends ResponseSession implements response {
|
|
|
85
121
|
status?: number;
|
|
86
122
|
stream?: eStream;
|
|
87
123
|
path: string;
|
|
124
|
+
hash: string;
|
|
88
125
|
private headers;
|
|
89
126
|
constructor(request: request, args?: Record<string, string>);
|
|
90
127
|
get?(): Promise<any> | any;
|
|
@@ -129,48 +166,53 @@ interface pathConfig {
|
|
|
129
166
|
preload?: boolean;
|
|
130
167
|
}
|
|
131
168
|
interface wssConfig {
|
|
132
|
-
credentials?: boolean;
|
|
133
169
|
broadcast?: boolean;
|
|
134
170
|
maxClient?: number;
|
|
135
171
|
requireSession?: boolean;
|
|
136
172
|
}
|
|
137
173
|
|
|
138
|
-
declare class
|
|
139
|
-
dir: string;
|
|
140
|
-
apt: string;
|
|
174
|
+
declare class routeCFG {
|
|
141
175
|
files: (...file: ([string, pathConfig] | string)[]) => void;
|
|
142
|
-
_statics?: obj<Response>;
|
|
143
176
|
statics: (statics?: obj<Response>) => void;
|
|
144
|
-
constructor(dir?: string, options?: yveOptions);
|
|
145
177
|
/** --------------------
|
|
146
178
|
* string | int | float | file | uuid
|
|
147
179
|
* - /url/\<string:hell>
|
|
148
180
|
*/
|
|
149
|
-
route(path: string)
|
|
150
|
-
wss(path: string, config?: wssConfig)
|
|
151
|
-
error(...codes: number[])
|
|
152
|
-
folders(...folder: ([
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
181
|
+
route: (path: string) => <T extends typeof response>(f?: T | undefined) => T | undefined;
|
|
182
|
+
wss: (path: string, config?: wssConfig) => <T extends typeof websocket>(f?: T | undefined) => T | undefined;
|
|
183
|
+
error: (...codes: number[]) => <T extends typeof response>(f?: T | undefined) => T | undefined;
|
|
184
|
+
folders: (...folder: ([
|
|
185
|
+
string,
|
|
186
|
+
{
|
|
187
|
+
requireSession?: boolean;
|
|
188
|
+
}
|
|
189
|
+
] | string)[]) => void;
|
|
190
|
+
redirect: (url: string, headers?: obj<string>) => Response;
|
|
156
191
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
192
|
+
declare class Formula extends routeCFG {
|
|
193
|
+
dir: string;
|
|
194
|
+
apt: string;
|
|
195
|
+
base: string;
|
|
196
|
+
protected _statics?: obj<Response>;
|
|
197
|
+
constructor(dir?: string, options?: yveOptions);
|
|
198
|
+
protected _base(str: string): string;
|
|
163
199
|
}
|
|
164
200
|
|
|
165
201
|
interface yveOptions {
|
|
166
202
|
dir?: string;
|
|
167
|
-
|
|
203
|
+
clientDir?: string;
|
|
168
204
|
envPath?: string;
|
|
169
205
|
session?: Auth;
|
|
206
|
+
base?: string;
|
|
170
207
|
}
|
|
171
|
-
type
|
|
208
|
+
type for_srver = Partial<Serve> & dev & {
|
|
209
|
+
fn?: (port: number) => void;
|
|
210
|
+
};
|
|
211
|
+
type _server = (server?: for_srver, wss?: Partial<WebSocketHandler>) => Promise<void>;
|
|
172
212
|
declare class Rossa extends Formula {
|
|
173
|
-
|
|
213
|
+
html: (server?: dev & {
|
|
214
|
+
name?: string;
|
|
215
|
+
}) => Promise<void>;
|
|
174
216
|
serve: _server;
|
|
175
217
|
constructor(options?: yveOptions);
|
|
176
218
|
}
|
|
@@ -183,4 +225,36 @@ declare class Render<T> {
|
|
|
183
225
|
static jwt(jwtSession: any): Promise<Render<ServerSide>>;
|
|
184
226
|
}
|
|
185
227
|
|
|
186
|
-
|
|
228
|
+
interface fs {
|
|
229
|
+
[key: string]: string | undefined | boolean | number;
|
|
230
|
+
}
|
|
231
|
+
declare class JSONCacher<T extends fs> {
|
|
232
|
+
fs: string;
|
|
233
|
+
f_timed: number;
|
|
234
|
+
data: Map<any, T>;
|
|
235
|
+
key: string;
|
|
236
|
+
dir: string;
|
|
237
|
+
constructor({ dir, fs, key }: {
|
|
238
|
+
dir: string;
|
|
239
|
+
fs: string;
|
|
240
|
+
key: string;
|
|
241
|
+
});
|
|
242
|
+
init(): Promise<void>;
|
|
243
|
+
get(val: string | undefined): Promise<T | null>;
|
|
244
|
+
queue(): Promise<void>;
|
|
245
|
+
set(data: T): Promise<boolean>;
|
|
246
|
+
delete(key: string): Promise<void>;
|
|
247
|
+
json(): Promise<any>;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
declare const getTLS: (dir: string) => Record<string, BunFile>;
|
|
251
|
+
|
|
252
|
+
interface dev {
|
|
253
|
+
path?: string;
|
|
254
|
+
hostname?: string;
|
|
255
|
+
method?: string;
|
|
256
|
+
port?: number;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export { JSONCacher, Mapper, Render, Rossa, Time, auths, getTLS, log, response, websocket };
|
|
260
|
+
export type { dev };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var k=function(t,n,r,o){var i=arguments.length,s=i<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,r):o,e;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")s=Reflect.decorate(t,n,r,o);else for(var f=t.length-1;f>=0;f--)if(e=t[f])s=(i<3?e(s):i>3?e(n,r,s):e(n,r))||s;return i>3&&s&&Object.defineProperty(n,r,s),s};var v=(t,n)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(t,n)};import{Auth as Tn}from"authored";var tt=(t)=>typeof t==="function";var J=(t)=>{return!isNaN(parseFloat(t))&&isFinite(t)};var nt=(t)=>{return t instanceof Uint8Array||t instanceof ArrayBuffer||typeof t==="string"};var A=(t)=>typeof t==="string",C=(t)=>Array.isArray(t),rt=(t)=>typeof t==="object";var ot=(t)=>{return Number.isInteger(Number(t))};function it(t,n){m(n).forEach(([r,o])=>{et(t,r,{value:o,writable:!1,configurable:!1,enumerable:!0})})}class M{static set p(t){if(Array.isArray(t))console.log(...t);else console.log(t)}}class Q{_c=0;_id="";constructor(t){if(this._c=0,this._id=t??S(5),t?.includes("-")){let[n,r]=[t.split("-").slice(0,-1).join("-"),t.split("-").slice(-1)[0]];this._id=n,this._c=J(r)?parseInt(r):0}}get id(){return this._id+"-"+this._c}get mid(){return this._id+"-"+ ++this._c}}var st=(t,n)=>{let[r,o]=n.replace(/bytes=/,"").split("-").map((i,s)=>{let e=parseInt(i,10);return isNaN(e)?s===0?0:t-1:e});return[r,o,t]};var Bn=new RegExp(/(\d+)(\d*)/,"m"),jt=(t)=>Array.from({length:t},(n,r)=>r),zt="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Ft="abcdefghijklmnopqrstuvwxyz",Kt=jt(10).join("");var T=(t)=>JSON.stringify(t),ft=(t)=>{return JSON.parse(t)},P=(t)=>{if(t.startsWith("webkit"))t="-"+t;return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()},S=(t)=>{let n=zt+Ft;return Array.from({length:t},(r,o)=>n+(o?Kt:"")).reduce((r,o)=>{return r+=o.charAt(Math.floor(Math.random()*o.length))},"")};class l extends Map{obj(t){t&&m(t).forEach(([n,r])=>this.set(n,r))}map(t){t.forEach((n,r)=>{if(n instanceof l)this.set(r,n);else if(C(n)){if(this.lacks(r))this.set(r,[]);this.get(r).push(...n)}else if(rt(n))this.ass(r,n);else this.set(r,n)})}ass(t,n){if(!this.has(t))this.set(t,{});d(this.get(t),n)}lacks(t){return!this.has(t)}init(t,n){return this.has(t)?this.get(t):this.set(t,n).get(t)}}var{values:E,keys:X,entries:m}=Object;var _t=Object.hasOwn;var{defineProperty:et,assign:d}=Object,$=(t)=>{return Object.keys(t).length};function ut(t){return class extends t{constructor(...n){super(...n);let r=new Map;return new Proxy(this,{get(o,i){let s=`__${i}`;if(!r.has(s)){let e=o[i];if(tt(e))e=function(...f){let u=`${s}_${JSON.stringify(f)}`;if(!r.has(u)){let h=o[i].apply(o,f);r.set(u,h)}return r.get(u)};r.set(s,e)}return r.get(s)},set(o,i,s){let e=`__${i}`;return r.set(e,s),!0}})}}}var b=(t,n)=>{return{name:t,content:n}},Vt=(t,n)=>{return{property:t,content:n}},kt=(t,n)=>{return{"http-equiv":t,content:n}};class Y{metas=[];constructor(t){t&&this.metas.push(b("description",t))}author(t){return this.meta=b("author",t),this}charset(t){return this.meta={charset:t},this}keywords(...t){return this.meta=b("keywords",t.join(", ")),this}viewport(t){let n=m(t).map(([r,o])=>[P(r),String(o)].join("="));return this.meta=b("viewport",n.join(", ")),this}httpEquiv(t){return m(t).forEach(([n,r])=>{this.meta=kt(P(n),String(r))}),this}robots(...t){return this.meta=b("robots",t.join(", ")),this}themeColor(t){return this.meta=b("theme-color",t),this}openGraph(t){return m(t).forEach(([n,r])=>{this.meta=Vt("og:"+n,String(r))}),this}twitter(t){return m(t).forEach(([n,r])=>{this.meta=b("twitter:"+n,String(r))}),this}and(t){return this}set meta(t){this.metas.push(t)}}var vt=["charset","name","property","http-equiv"],mt=(t,n)=>{n.forEach((r)=>{for(let o of vt)if(o in r){let i=r[o];t[`${o}_${o==="charset"?"":i}`]=r}})},tn=(t,n)=>{n.forEach((r)=>{if("href"in r){let o=r.href;t[`${o}`]=r}})};class pt{_head;idm;constructor(t){this._head=new l(t)}set head(t){m(t).forEach(([n,r])=>{if(n==="title"||n==="base"){if(r!==void 0)this._head.set(n,r);return}if(r instanceof Y)return mt(this._head.init("meta",{}),r.metas);if(!C(r))return;switch(n){case"meta":return mt(this._head.init("meta",{}),r);case"link":return tn(this._head.init("link",{}),r);case"script":if(r.length){this._head.init(n,[]);let o=r.map((i)=>{if(!i.yid&&this.idm)i.yid="sc"+this.idm.mid;return i});this._head.get(n).push(...o)}return}})}get head(){return this._head}set id(t){this.idm=new Q(t)}}class nn{lang="en";htmlHead=new l;head;constructor(){this.head=(t={})=>{let n=new pt(this.htmlHead);n.head=t,this.htmlHead=n.head}}}var ht=(t,n="",{maxAge:r,expires:o,path:i,domain:s,secure:e,httpOnly:f,sameSite:u})=>{if(r instanceof Date)r=r.getSeconds();if(o instanceof Date)o=o.toUTCString();else if(o===0)o=new Date().toUTCString();return[["Domain",s],["Expires",o],["Max-Age",r],["Secure",e],["HttpOnly",f],["Path",i],["SameSite",u]].reduce((c,[w,g])=>{if(g!==void 0)c.push(`${w}=${g}`);return c},[`${t}=${n}`]).join("; ")};var B=(t,n=!1)=>{if(J(t))return[+t,ot(t)?"int":"float"];if(n&&/\.\w+$/.test(t))return[t,"file"];if(t==="/")return[t,"-"];if(t.length===36&&t.match(/\-/g)?.length===4)return[t,"uuid"];return[t,"string"]},y=(t)=>{let n=t.startsWith("/")?t:"/"+t,r=n.match(/(?<=\/)[^/].*?(?=\/|$)/g)??["/"],[o,i]=r.reduce(([s,e],f)=>{if(f.includes("<")){let u=f.match(/(?<=<)[^/].*?(?=>|$)/g);if(u?.length){let[h,c]=u[0].split(":");if(h&&c)s.push(h),e.push(c)}}else s.push(f===">"?"/":f);return[s,e]},[[],[]]);if(n.endsWith("/")&&n.length>1)o.push("/");return{parsed:o,args:i}};class W{storage=new l;cache(t,n){if(this.storage.lacks(t))this.storage.set(t,n());return this.storage.get(t)}}var rn=["int","float","file","uuid","string"],on=new W;class L{_storage=new l;set(t){let{parsed:n,path:r}=t,o=T(n);if(!this._storage.get(o))this._storage.set(o,t);else throw`path: ${r} already used.`}get(t){let{parsed:n}=on.cache(t,()=>y(t)),r={},o=this._storage.get(T(n));if(!o&&t!=="/")for(let i of this._storage.keys()){let s=[],e=ft(i);if(n.length===e.length){let f=e.map((c,w)=>{let g=B(n[w],n.length-1===w);if(c===g[0])return g[0];if(rn.includes(g[1]))return s.push(g[0]),g[1];return c}),u=T(f);if(this._storage.has(u)){o=this._storage.get(u),o?.args.forEach((c,w)=>{r[c]=s[w]});break}}}return[o,r]}}class N{constructor(...t){t.forEach((n)=>{if(!this[n])this[n]=new L})}get(t){return this[t]}}class U{path="";parsed=[];args=[];constructor(t){it(this,{path:t,...y(t)})}}class G{date;constructor(t){this.date=t?new Date(t):new Date}delta(t=null,n=!1){let r=G.delta(this.date.getTime(),t);return n?new Date(r):r}timed(t){if(!t)return this.date;return[["year","FullYear"],["month","Month"],["day","Date"],["hour","Hours"],["minute","Minutes"],["second","Seconds"]].reduce((r,[o,i])=>{let s=t[o];return s?new Date(r[`set${i}`](r[`get${i}`]()+s)):r},new Date(this.date))}static delta(t,n=null){return n?n-t:t-Date.now()}static get now(){return Date.now()}}var{file:fn}=globalThis.Bun;import{JWTInterface as sn}from"authored";class lt{session;jwt;jwtInt;constructor(){this.jwtInt=new sn}init(t){this.session=t.session,this.jwt=t.jwt}}var p=new lt;class x{__session;__jwt;get session(){if(!this.__session)this.__session=p.session.new;return this.__session}set session(t){this.__session=t}get jwt(){if(!this.__jwt)this.__jwt=p.jwt.new;return this.__jwt}set jwt(t){this.__jwt=t}get timedJWT(){return p.jwtInt.jwt()}setServerSession(t){let{__jwt:n,__session:r}=t;this.__session=r,this.__jwt=n}}var at=async(t,n)=>{await p.session.saveSession(t,n)};async function ct({sid:t,jwtv:n,refreshjwt:r},o){let i=new x;if(t){if(i.session=await p.session.openSession(t),!i.session.new)o.session=!0}if(n){if(i.jwt=p.jwtInt.open(n,{hours:6}),!i.jwt.new)o.jwt=!0;if(r){if(!(await p.jwt.openSession(r)).new)o.jwt_refresh=!0}}if("session"in o||"jwt"in o)return i}var en={session(...t){return Z(t[0],t[2],"session")},jwt(...t){return Z(t[0],t[2],"jwt")},jwt_refresh(...t){return Z(t[0],t[2],"jwt_refresh")}},Z=(t,n,r)=>{let o=n.value;return n.value=async function(i={}){if(r in i&&i.session)return delete i[r],o.call(t,i);return{error:401}},n};var un=["GET","POST","PUT","DELETE","OPTIONS"];class St extends U{config;_class;options="";bytes;fileType="text/plain";fileSize=0;constructor(t,n={}){super(t);this.config=n}set serverClass(t){this._class=t,this.options=un.filter((n)=>t.prototype[n.toLowerCase()]).join(", ")}get serverClass(){return this._class}async loadBytes(t){if(!this.config.preload)return;try{let n=fn(this.path);this.fileType=n.type,this.bytes=await n.bytes(),this.fileSize=this.bytes.byteLength}catch{throw`error: can't preload ${this.path}. File not found.`}}}var yt={path:Symbol("path"),wss:Symbol("wss"),file:Symbol("file"),folder:Symbol("folder"),error:Symbol("error")},mn=new N(...E(yt)),bt=(t)=>{let n=yt[t];if(!n)throw new Error("Invalid storage type");return mn[n]},R=(t,n,r={},o)=>{return(i)=>{let s=new St(n,r);if(i)s.serverClass=i;if(t==="file")s.loadBytes(o);return bt(t).set(s),i}},gt={args:{}};async function a(t){let[n,r]=bt(t).get(this.path);if(!n)return gt;let{requireSession:o}=n.config,i=void 0;if(o){if(i=await ct(await this.request.authgroup(),r),!i)return gt}return{serverPath:n,args:r,session:i}}class j{dir;apt;files;_statics;statics;constructor(t=".",n={}){this.dir=t;let{dir:r,appDir:o}=n;if(r)this.dir=r;this.apt=this.dir+"/"+(o??"app"),this.files=(...i)=>{i.forEach((s)=>{let[e,f]=Rt(s),u=e.replace(/^\.+/,""),h=u.startsWith("/")?u:"/"+u;R("file",h,f,this.apt)()})},this.statics=(i={})=>{if(!this._statics)this._statics={};d(this._statics,i)}}route(t){return R("path",t)}wss(t,n={}){return R("wss",t,n)}error(...t){return(n)=>{if(t.length)t.forEach((r)=>{R("error",r.toString(),{})(n)});else R("error","404",{})(n);return n}}folders(...t){t.forEach((n)=>{R("folder",...Rt(n))()})}redirect(t,n={}){return new Response("",{status:302,headers:new Headers({...n,Location:t})})}}var Rt=(t)=>{let n=A(t);return[n?t:t[0],n?{}:t[1]]};var{inflateSync:dn,serve:xn,write:Cn}=globalThis.Bun;class wt extends l{}var z=new wt;var F={async open(t){let n=t.data.wclass,{args:r,client:o}=t.data;if(n){n.ws=t;let i=n.id,s=$(o);if(!(i in o)){let e=s?"joiner":"maker";o[i]={role:e}}if(typeof n.init=="function")await n.init(r);if(n.broadcasting)n.ws.subscribe(n.path);await n.open()}else t.close()},async message(t,n){let r=t.data.wclass;if(r)await r.message(n)},async close(t,n,r){let o=t.data.wclass,i=t.data.client;if(o){if(await o.close(n,r),o.broadcasting)o.ws.unsubscribe(o.path);let s=o.id;if(delete i[s],$(i)===1)X(i).forEach((e)=>{i[e].role="maker"})}}};async function K(){let{serverPath:t,args:n,session:r}=await a.call(this,"wss");if(!t)return this.status=426,"upgrade error";let{serverClass:o}=t;if(!o)return"upgrade error";let i=new o(this.request);r&&i.setServerSession(r);let s=i.path,e=dt(s),f=e?.size??0,{broadcast:u,maxClient:h}=t.config;if(i.broadcasting=!!u,i.max=h??0,h&&f>=h)return this.status=400,"upgrade error";return this.request.upgradeConnection({data:{wclass:i,args:n,client:e}}),null}class xt extends x{request;ws;path;id;broadcasting=!1;max=0;constructor(t){super();this.request=t;this.path=t.path,this.id=S(10)}open(){}message(t){}close(t,n){}set send(t){if(t)if(this.broadcasting)this.ws.publish(this.path,t);else this.ws.send(t)}get role(){let t=z.get(this.path);if(t&&t.has(this.id))return t.get(this.id)?.role}}var dt=(t)=>{return z.init(t,new l)};var{deflateSync:Sn,gzipSync:yn}=globalThis.Bun;var{Server:pn,file:hn}=globalThis.Bun;class q{req;server;formData;url;method;__cookies=new Map;constructor(t,n){this.req=t;this.server=n;this.url=new URL(t.url),this.method=this.req.method.toLowerCase()}async form(){if(this.isForm){if(!this.formData)this.formData=await this.req.formData();return this.formData}return new FormData}async authgroup(){let{cookies:t,auth:n}=this,r=t.get("session")??"",o=n??"",i="",s=this.isForm?await this.form():void 0;if(s){let e=s.get("refresh_token");i=e?e.toString():""}return{sid:r,jwtv:o,refreshjwt:i}}upgradeConnection(t={}){return!!this.server?.upgrade(this.req,t)}get auth(){let t=this.headers.get("authorization");if(t){let[n,r]=t.split(" ",2);if(n.trim()=="Bearer")return r.trim()}}get accept(){return this.headers.get("accept")}get contentType(){return this.headers.get("content-type")}get cookies(){if(!this.__cookies.size){let t=this.headers.get("cookie");if(t){let n=t.split(";").reduce((r,o)=>{let[i,s]=o.trim().split(/=(.*)/s);return r.push([i,s]),r},[]);this.__cookies=new Map(n)}}return this.__cookies}get headers(){return this.req.headers??new Headers}get ip(){return this.server?.requestIP(this.req)}get isForm(){let t=this.contentType;return t?t.indexOf("multipart/form-data")>=0||t.indexOf("x-www-form-urlencoded")>=0:!1}get path(){return this.url.pathname}get parsed(){let{parsed:t}=y(this.path);return t}get searchParams(){return this.url.searchParams}get range(){return this.headers.get("range")??void 0}get isEventStream(){return this.accept?.includes("text/event-stream")}get isWSS(){return!!this.headers.get("upgrade")}get isFile(){let t=this.parsed.slice().pop();return t?B(t,!0).pop()==="file":!1}get type(){return hn(this.path).type}get upgrade(){return this.headers.get("upgrade")}get request(){return this.req}get signal(){return this.req.signal}}q=k([ut,v("design:paramtypes",[typeof Request==="undefined"?Object:Request,typeof pn==="undefined"?Object:pn])],q);class Ct{ctrl;intervalID=[];constructor(t){this.ctrl=t}push(t,n=2000){if(this.ctrl){let r=setInterval(()=>{let{id:o,retry:i,data:s,event:e,end:f}=t();if(this.ctrl){let u=f?"end":s;if(i){let h=i>2000?i:2000;this.ctrl.enqueue(`retry: ${h}\\n`)}if(this.ctrl.enqueue(`id: ${o}\\n`),e&&this.ctrl.enqueue(`event: ${e}\\n`),typeof u=="object")this.ctrl.enqueue("data: "+JSON.stringify(u)+"\\n\\\n");else this.ctrl.enqueue("data: "+JSON.stringify({message:u})+"\\n\\n");f&&this.close()}},n>1000?n:1000);this.intervalID.push(r)}}close(){if(this.intervalID.length)this.intervalID.forEach((t)=>{clearInterval(t)}),this.intervalID=[];this.ctrl?.close()}}async function Tt(t,n,r){this.status=200,this.header={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};let o=this.request,i=new ReadableStream({async start(e){t.stream=new Ct(e),await r.call(t,n),o.signal.addEventListener("abort",()=>{if(t.stream?.close(),t.stream?.intervalID.length)e.close()})}}),s=await r.call(t,n);if(typeof s==="object"&&"error"in s)return this.status=s.error,null;return i}async function Et(t){let n=p.jwtInt.save(t);return t.access_token=n,await p.jwt.saveSession(t,this.headers),{access_token:n,refresh_token:t.sid,status:"ok"}}function $t(t){return this.status=403,{error:t}}async function qt(t){let{jwtv:n,refreshjwt:r}=await this.request.authgroup();if(!r){if(n||!t.modified)return this.status=204,this.type="application/json",JSON.stringify({});return JSON.stringify(await Et.call(this,t))}let o=await p.jwt.openSession(r),i=o.data.access_token,s={};if(n!==i)s=$t.call(this,"tokens don't match.");else if(!p.jwtInt.verify(i,{days:5}))await p.jwt.saveSession(o,void 0,!0),s=$t.call(this,"expired refresh_token.");else s=await Et.call(this,o);return this.type="application/json",JSON.stringify(s)}var{file:ln}=globalThis.Bun;async function Ot(){let t=this.path,{parsed:n}=y(this.path),r=n.slice(0,-1).join("/");this.path=r;let{serverPath:o}=await a.call(this,"folder");if(!o)return null;return this.path=t,await _.call(this)}async function Dt(){let{serverPath:t}=await a.call(this,"file");if(!t)return await Ot.call(this);if(t.bytes)return V.call(this,t.bytes,t.fileSize);return await _.call(this)}async function _(){try{let t=ln(this.dir+this.path);if(t.type.startsWith("video/"))return V.call(this,t,t.size);else{let n=await t.bytes();return V.call(this,n,n.byteLength)}}catch{return`${this.path} file not found.`}}function V(t,n){let{type:r,range:o}=this.request;if(this.type=r,this.status=206,!o)return this.header={"Cache-Control":"max-age=86400, must-revalidate"},nt(t)?this.compress("gzip",t):t;let[i,s,e]=st(n,o);return this.header={"Content-Range":`bytes ${i}-${s}/${e}`,"Content-Length":n.toString()},t.slice(i,s+1)}async function Jt(t){return this.status=t.status,this.header=t.headers.toJSON(),await t.arrayBuffer()}import{ServerSide as an}from"authored";function O(t,n){if(this.status=n||200,typeof t==="object")return this.type="application/json",JSON.stringify(t);return this.type="text/html",String(t)}async function Mt(t){if(t instanceof an)return qt.call(this,t);return O.call(this,t)}class D{type;render;data;constructor(t,n,r={}){this.type=t;this.render=n;this.data=r}static async jwt(t){return new D("jwt",t)}}async function Pt(t,n=!1){let{type:r,render:o,data:i}=t;switch(r){case"jwt":return"jwt"}return"render"}function cn(t){return this.status=t??204,null}async function gn(t){let{header:n,status:r,__session:o}=t;if($(n))this.header=n;if(r)this.status=r;o&&await at(o,this.headers)}async function I(t,n,r=!1){if(!n)return cn.call(this,t.status);if(typeof n==="object"&&"error"in n)return this.status=n.error,null;if(await gn.call(this,t),n instanceof Response)return await Jt.call(this,n);if(n instanceof D){if(t.status)this.status=t.status;return await Pt.call(this,n,r)}switch(this.request.method){case"post":return Mt.call(this,n);default:return O.call(this,n)}}async function Bt(){let{serverPath:t,args:n,session:r}=await a.call(this,"path");if(!t)return this.request.isFile?Dt.call(this):null;let{serverClass:o}=t;if(!o)return null;let i=new o(this.request,n);r&&i.setServerSession(r);let{isEventStream:s,method:e}=this.request;if(s&&i?.eventStream)return Tt.call(this,i,n,i.eventStream);if(e==="options")return this.status=204,this.options(t.options);if(i?.[e]){let f=await i[e]();return this.status=200,this.compress("deflate",await I.call(this,i,f)??"")}return null}async function Wt(){let t=this.path;this.path=this.status.toString();let{serverPath:n,args:r,session:o}=await a.call(this,"error");if(this.path=t,!n)return null;let{serverClass:i}=n;if(!i)return null;let s=new i(this.request,r);s.status=this.status;let{method:e}=this.request;if(s?.[e]){let f=await s[e]();return this.compress("deflate",await I.call(this,s,f,!0)??"")}return null}class Nt extends x{request;args;status;stream;path;headers={};constructor(t,n={}){super();this.request=t;this.args=n;this.path=t.path}set header(t){d(this.headers,t)}get header(){return this.headers}set type(t){this.header={"Content-Type":t}}setCookie({key:t,val:n,path:r="/",days:o=31,httpOnly:i=!1}){let s=ht(t,n,{expires:new G().timed({day:o}),path:r,httpOnly:i,sameSite:"Strict"});this.header={"Set-Cookie":s}}deleteCookie(t){this.setCookie({key:t,val:"",days:0})}}class Ut{status=404;headers=new Headers({"Content-Type":"text/plain"});set header(t){m(t).forEach(([n,r])=>{this.headers.set(n,r)})}set type(t){this.headers.set("Content-Type",t)}options(t){return t+=", OPTIONS",this.header={Allow:t,"Access-Control-Allow-Methods":t,"Access-Control-Max-Age":"86400"},null}compress(t,n){let o=(t==="gzip"?yn:Sn)(n);return this.header={"Content-Length":o.byteLength.toString(),"Content-Encoding":t},o}get init(){return{status:this.status,headers:this.headers}}}class H extends Ut{dir;request;path="";constructor(t,n,r="./"){super();this.dir=r;this.request=new q(t,n)}async response(){let{path:t,isWSS:n}=this.request;this.path=t;let r=await(n?K:Bt).call(this);if(!r)r=await Wt.call(this);return new Response(r,this.init)}}import{mkdirSync as bn,writeFileSync as Rn,existsSync as Ht}from"fs";var{file:wn}=globalThis.Bun;var Gt=(t,n="")=>{if(Ht(t))return!0;return Rn(t,n,{flag:"wx"}),!0},It=(t)=>{if(Ht(t))return!0;return bn(t,{recursive:!0}),!0},At=(t,n)=>{if(!n)It(t),Gt(t+"/.env",`SECRET_KEY="${S(20)}"
|
|
2
|
+
var nt=function(t,n,r,o){var i=arguments.length,s=i<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,r):o,e;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")s=Reflect.decorate(t,n,r,o);else for(var f=t.length-1;f>=0;f--)if(e=t[f])s=(i<3?e(s):i>3?e(n,r,s):e(n,r))||s;return i>3&&s&&Object.defineProperty(n,r,s),s};var rt=(t,n)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(t,n)};import{Auth as bn}from"authored";var ot=(t)=>typeof t==="function";var C=(t)=>{return!isNaN(parseFloat(t))&&isFinite(t)};var it=(t)=>{return t instanceof Uint8Array||t instanceof ArrayBuffer||typeof t==="string"};var G=(t)=>typeof t==="string",x=(t)=>Array.isArray(t),st=(t)=>typeof t==="object";var et=(t)=>{return Number.isInteger(Number(t))};function ft(t,n){l(n).forEach(([r,o])=>{mt(t,r,{value:o,writable:!1,configurable:!1,enumerable:!0})})}var Y=(t)=>{return x(t)?t:[t]};class d{static set i(t){console.info(...Y(t))}static set e(t){console.error(...Y(t))}static set w(t){console.warn(...Y(t))}}var ut=(t,n)=>{let[r,o]=n.replace(/bytes=/,"").split("-").map((i,s)=>{let e=parseInt(i,10);return isNaN(e)?s===0?0:t-1:e});return[r,o,t]};var zt=(t)=>Array.from({length:t},(n,r)=>r),Ft="ABCDEFGHIJKLMNOPQRSTUVWXYZ",jt="abcdefghijklmnopqrstuvwxyz";var E=(t)=>JSON.stringify(t),pt=(t)=>{return JSON.parse(t)};var b=(t)=>{let n=Ft+jt,r=zt(10).join("");return Array.from({length:t},(o,i)=>n+(i?r:"")).reduce((o,i)=>{return o+=i.charAt(Math.floor(Math.random()*i.length))},"")};var J=(t,n)=>{let r=n==="/"?"":n;if(n.startsWith("#"))return t+n;return n.startsWith("/")?t+r:n};class a extends Map{obj(t){t&&l(t).forEach(([n,r])=>this.set(n,r))}map(t){t.forEach((n,r)=>{if(n instanceof a)this.set(r,n);else if(x(n)){if(this.lacks(r))this.set(r,[]);this.get(r).push(...n)}else if(st(n))this.ass(r,n);else this.set(r,n)})}ass(t,n){if(!this.has(t))this.set(t,{});R(this.get(t),n)}lacks(t){return!this.has(t)}init(t,n){return this.has(t)?this.get(t):this.set(t,n).get(t)}}var{values:N,keys:Z,entries:l}=Object;var{defineProperty:mt,assign:R}=Object;var q=(t)=>{return Object.keys(t).length};function ht(t){return class extends t{constructor(...n){super(...n);let r=new Map;return new Proxy(this,{get(o,i){let s=`__${i}`;if(!r.has(s)){let e=o[i];if(ot(e))e=function(...f){let u=`${s}_${JSON.stringify(f)}`;if(!r.has(u)){let m=o[i].apply(o,f);r.set(u,m)}return r.get(u)};r.set(s,e)}return r.get(s)},set(o,i,s){let e=`__${i}`;return r.set(e,s),!0}})}}}var lt=(t,n="",{maxAge:r,expires:o,path:i,domain:s,secure:e,httpOnly:f,sameSite:u})=>{if(r instanceof Date)r=r.getSeconds();if(o instanceof Date)o=o.toUTCString();else if(o===0)o=new Date().toUTCString();return[["Domain",s],["Expires",o],["Max-Age",r],["Secure",e],["HttpOnly",f],["Path",i],["SameSite",u]].reduce((p,[S,c])=>{if(c!==void 0)p.push(`${S}=${c}`);return p},[`${t}=${n}`]).join("; ")};var W=(t,n=!1)=>{if(C(t))return[+t,et(t)?"int":"float"];if(n&&/\.\w+$/.test(t))return[t,"file"];if(t==="/")return[t,"-"];if(t.length===36&&t.match(/\-/g)?.length===4)return[t,"uuid"];return[t,"string"]},y=(t)=>{let n=t.startsWith("/")?t:"/"+t,r=n.match(/(?<=\/)[^/].*?(?=\/|$)/g)??["/"],[o,i]=r.reduce(([s,e],f)=>{if(f.includes("<")){let u=f.match(/(?<=<)[^/].*?(?=>|$)/g);if(u?.length){let[m,p]=u[0].split(":");if(m)s.push(m),e.push(p||"_")}}else s.push(f===">"?"/":f);return[s,e]},[[],[]]);if(n.endsWith("/")&&n.length>1)o.push("/");return{parsed:o,args:i}};class ${storage;constructor(){this.storage=new a}cache(t,n){if(this.storage.lacks(t))this.storage.set(t,n());return this.storage.get(t)}}var Vt=["int","float","file","uuid","string"];class H{_storage;CC;constructor(){this._storage=new a,this.CC=new $}set(t){let{parsed:n,path:r}=t,o=E(n);if(!this._storage.get(o))this._storage.set(o,t);else throw`path: ${r} already used.`}get(t){let{parsed:n}=this.CC.cache(t,()=>y(t)),r={},o=this._storage.get(E(n));if(!o&&t!=="/")for(let i of this._storage.keys()){let s=[],e=pt(i);if(n.length===e.length){let f=e.map((p,S)=>{let c=W(n[S],n.length-1===S);if(p===c[0])return c[0];if(Vt.includes(c[1]))return s.push(c[0]),c[1];return p}),u=E(f);if(this._storage.has(u)){o=this._storage.get(u),o?.args.forEach((p,S)=>{r[p]=s[S]});break}}}return[o,r]}}class I{constructor(...t){t.forEach((n)=>{if(!this[n])this[n]=new H})}get(t){return this[t]}}class U{path="";parsed=[];args=[];constructor(t){ft(this,{path:t,...y(t)})}}class B{date;constructor(t){this.date=t?new Date(t):new Date}delta(t=null,n=!1){let r=B.delta(this.date.getTime(),t);return n?new Date(r):r}timed(t){if(!t)return this.date;return[["year","FullYear"],["month","Month"],["day","Date"],["hour","Hours"],["minute","Minutes"],["second","Seconds"]].reduce((r,[o,i])=>{let s=t[o];return s?new Date(r[`set${i}`](r[`get${i}`]()+s)):r},new Date(this.date))}static delta(t,n=null){return n?n-t:t-Date.now()}static local(t){return new Date(t).toLocaleString()}static get now(){return Date.now()}}var{file:tn}=globalThis.Bun;import{JWTInterface as kt}from"authored";class at{session;jwt;jwtInt;constructor(){this.jwtInt=new kt}init(t){this.session=t.session,this.jwt=t.jwt}}var h=new at;class T{__session;__jwt;get session(){if(!this.__session)this.__session=h.session.new;return this.__session}set session(t){this.__session=t}get jwt(){if(!this.__jwt)this.__jwt=h.jwt.new;return this.__jwt}set jwt(t){this.__jwt=t}get timedJWT(){return h.jwtInt.jwt()}setServerSession(t){let{__jwt:n,__session:r}=t;this.__session=r,this.__jwt=n}}var ct=async(t,n)=>{await h.session.saveSession(t,n)};async function gt({sid:t,jwtv:n,refreshjwt:r},o){let i=new T;if(t){if(i.session=await h.session.openSession(t),!i.session.new)o.session=!0}if(n){if(i.jwt=h.jwtInt.open(n,{hours:6}),!i.jwt.new)o.jwt=!0;if(r){if(!(await h.jwt.openSession(r)).new)o.jwt_refresh=!0}}if("session"in o||"jwt"in o)return i}var vt={session(...t){return A(t[0],t[2],"session")},jwt(...t){return A(t[0],t[2],"jwt")},jwt_refresh(...t){return A(t[0],t[2],"jwt_refresh")}},A=(t,n,r)=>{let o=n.value;return n.value=async function(i={}){if(r in i&&i.session)return delete i[r],o.call(t,i);return{error:401}},n};var nn=["GET","POST","PUT","DELETE","OPTIONS"];class St extends U{config;_class;options="";bytes;fileType="text/plain";fileSize=0;constructor(t,n={}){super(t);this.config=n}set serverClass(t){this._class=t,this.options=nn.filter((n)=>t.prototype[n.toLowerCase()]).join(", ")}get serverClass(){return this._class}async loadBytes(t="."){if(!this.config.preload)return;try{d.i=this.path;let n=this.path.startsWith("/")?this.path:"/"+this.path,r=tn(t+this.path);this.fileType=r.type,this.bytes=await r.bytes(),this.fileSize=this.bytes.byteLength}catch{throw`error: can't preload ${this.path}. File not found.`}}}var bt={path:Symbol("path"),wss:Symbol("wss"),file:Symbol("file"),folder:Symbol("folder"),error:Symbol("error")},rn=new I(...N(bt)),wt=(t)=>{let n=bt[t];if(!n)throw new Error("Invalid storage type");return rn[n]},w=(t,n,r={},o)=>{return(i)=>{let s=new St(n,r);if(i)s.serverClass=i;if(t==="file")s.loadBytes(o);return wt(t).set(s),i}},yt={args:{}};async function g(t){let[n,r]=wt(t).get(this.path);if(!n)return yt;let{requireSession:o}=n.config,i=void 0;if(o){if(i=await gt(await this.request.authgroup(),r),!i)return yt}return{serverPath:n,args:r,session:i}}class dt{}class L extends dt{dir;apt;base;_statics;constructor(t=".",n={}){super();this.dir=t;let{dir:r,base:o,clientDir:i}=n;if(r)this.dir=r;this.apt=i?i:"./client",this.base=o??"",this.files=(...s)=>{s.forEach((e)=>{let[f,u]=xt.call(this,e),m=f.replace(/^\.+/,""),p=m.startsWith("/")?m:"/"+m;w("file",p,u,this.apt)()})},this.folders=(...s)=>{s.forEach((e)=>{w("folder",...xt.call(this,e))()})},this.statics=(s={})=>{if(!this._statics)this._statics={};R(this._statics,s)},this.route=(s)=>{return w("path",this._base(s))},this.wss=(s,e={})=>{return w("wss",this._base(s),e)},this.error=(...s)=>{return(e)=>{if(s.length)s.forEach((f)=>{w("error",this._base(f.toString()),{})(e)});else w("error",this._base("404"),{})(e);return e}},this.redirect=(s,e={})=>{return new Response("",{status:302,headers:new Headers({...e,Location:this._base(s)})})}}_base(t){return J(this.base,t)}}function xt(t){let n=G(t);return[n?this._base(t):this._base(t[0]),n?{}:t[1]]}var{inflateSync:gn,serve:yn,write:Sn}=globalThis.Bun;class Rt extends a{}var z=new Rt;var F={async open(t){let n=t.data.wclass,{args:r,client:o}=t.data;if(n){n.ws=t;let i=n.id,s=q(o);if(!(i in o)){let e=s?"joiner":"maker";o[i]={role:e}}if(typeof n.init=="function")await n.init(r);if(n.broadcasting)n.ws.subscribe(n.path);await n.open()}else t.close()},async message(t,n){let r=t.data.wclass;if(r)await r.message(n)},async close(t,n,r){let o=t.data.wclass,i=t.data.client;if(o){if(await o.close(n,r),o.broadcasting)o.ws.unsubscribe(o.path);let s=o.id;if(delete i[s],q(i)===1)Z(i).forEach((e)=>{i[e].role="maker"})}}};async function j(){let{serverPath:t,args:n,session:r}=await g.call(this,"wss");if(!t)return this.status=426,"upgrade error";let{serverClass:o}=t;if(!o)return"upgrade error";let i=new o(this.request);r&&i.setServerSession(r);let s=i.path,e=Tt(s),f=e?.size??0,{broadcast:u,maxClient:m}=t.config;if(i.broadcasting=!!u,i.max=m??0,m&&f>=m)return this.status=400,"upgrade error";return this.request.upgradeConnection({data:{wclass:i,args:n,client:e}}),null}class Ct extends T{request;ws;path;id;broadcasting=!1;max=0;constructor(t){super();this.request=t;this.path=t.path,this.id=b(10)}open(){}message(t){}close(t,n){}set send(t){if(t)if(this.broadcasting)this.ws.publish(this.path,t);else this.ws.send(t)}get role(){let t=z.get(this.path);if(t&&t.has(this.id))return t.get(this.id)?.role}}var Tt=(t)=>{return z.init(t,new a)};var{deflateSync:pn,gzipSync:hn}=globalThis.Bun;var{Server:on,file:sn}=globalThis.Bun;class M{req;server;formData;url;method;__cookies=new Map;constructor(t,n){this.req=t;this.server=n;this.url=new URL(t.url),this.method=this.req.method.toLowerCase()}async json(){return await this.req.json()}async form(){if(this.isForm){if(!this.formData)this.formData=await this.req.formData();return this.formData}return new FormData}async authgroup(){let{cookies:t,auth:n}=this,r=t.get("session")??"",o=n??"",i="",s=this.isForm?await this.form():void 0;if(s){let e=s.get("refresh_token");i=e?e.toString():""}return{sid:r,jwtv:o,refreshjwt:i}}upgradeConnection(t={}){return!!this.server?.upgrade(this.req,t)}get auth(){let t=this.headers.get("authorization");if(t){let[n,r]=t.split(" ",2);if(n.trim()=="Bearer")return r.trim()}}get accept(){return this.headers.get("accept")}get contentType(){return this.headers.get("content-type")}get cookies(){if(!this.__cookies.size){let t=this.headers.get("cookie");if(t){let n=t.split(";").reduce((r,o)=>{let[i,s]=o.trim().split(/=(.*)/s);return r.push([i,s]),r},[]);this.__cookies=new Map(n)}}return this.__cookies}get headers(){return this.req.headers??new Headers}get ip(){return this.server?.requestIP(this.req)}get isForm(){let t=this.contentType;return t?t.indexOf("multipart/form-data")>=0||t.indexOf("x-www-form-urlencoded")>=0:!1}get path(){return this.url.pathname}get hash(){return this.url.hash}get fullPath(){let{pathname:t,hash:n}=this.url;return t+n}get parsed(){let{parsed:t}=y(this.path);return t}get searchParams(){return this.url.searchParams}get range(){return this.headers.get("range")??void 0}get isEventStream(){return this.accept?.includes("text/event-stream")}get isWSS(){return!!this.headers.get("upgrade")}get isFile(){let t=this.parsed.slice().pop();return t?W(t,!0).pop()==="file":!1}get type(){return sn(this.path).type}get upgrade(){return this.headers.get("upgrade")}get request(){return this.req}get signal(){return this.req.signal}}M=nt([ht,rt("design:paramtypes",[typeof Request==="undefined"?Object:Request,typeof on==="undefined"?Object:on])],M);class Et{ctrl;intervalID=[];constructor(t){this.ctrl=t}push(t,n=2000){if(this.ctrl){let r=setInterval(()=>{let{id:o,retry:i,data:s,event:e,end:f}=t();if(this.ctrl){let u=f?"end":s;if(i){let m=i>2000?i:2000;this.ctrl.enqueue(`retry: ${m}\\n`)}if(this.ctrl.enqueue(`id: ${o}\\n`),e&&this.ctrl.enqueue(`event: ${e}\\n`),typeof u=="object")this.ctrl.enqueue("data: "+JSON.stringify(u)+"\\n\\\n");else this.ctrl.enqueue("data: "+JSON.stringify({message:u})+"\\n\\n");f&&this.close()}},n>1000?n:1000);this.intervalID.push(r)}}close(){if(this.intervalID.length)this.intervalID.forEach((t)=>{clearInterval(t)}),this.intervalID=[];this.ctrl?.close()}}async function qt(t,n,r){this.status=200,this.header={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};let o=this.request,i=new ReadableStream({async start(e){t.stream=new Et(e),await r.call(t,n),o.signal.addEventListener("abort",()=>{if(t.stream?.close(),t.stream?.intervalID.length)e.close()})}}),s=await r.call(t,n);if(typeof s==="object"&&"error"in s)return this.status=s.error,null;return i}async function Bt(t){let n=h.jwtInt.save(t);return t.access_token=n,await h.jwt.saveSession(t,this.headers),{access_token:n,refresh_token:t.sid,status:"ok"}}function Mt(t){return this.status=403,{error:t}}async function Ot(t){let{jwtv:n,refreshjwt:r}=await this.request.authgroup();if(!r){if(n||!t.modified)return this.status=204,this.type="application/json",JSON.stringify({});return JSON.stringify(await Bt.call(this,t))}let o=await h.jwt.openSession(r),i=o.data.access_token,s={};if(n!==i)s=Mt.call(this,"tokens don't match.");else if(!h.jwtInt.verify(i,{days:5}))await h.jwt.saveSession(o,void 0,!0),s=Mt.call(this,"expired refresh_token.");else s=await Bt.call(this,o);return this.type="application/json",JSON.stringify(s)}var{file:en}=globalThis.Bun;async function Dt(){let t=this.path,{parsed:n}=y(this.path),r=n.slice(0,-1).join("/");this.path=r;let{serverPath:o}=await g.call(this,"folder");if(!o)return null;return this.path=t,await K.call(this)}async function Jt(){let{serverPath:t}=await g.call(this,"file");if(!t)return await Dt.call(this);if(t.bytes)return _.call(this,t.bytes,t.fileSize);return await K.call(this)}async function K(){try{let t=en(this.dir+this.path);if(t.type.startsWith("video/"))return _.call(this,t,t.size);else{let n=await t.bytes();return _.call(this,n,n.byteLength)}}catch{return`${this.path} file not found.`}}function _(t,n){let{type:r,range:o}=this.request;if(this.type=r,this.status=206,!o)return this.header={"Cache-Control":"max-age=86400, must-revalidate"},it(t)?this.compress("gzip",t):t;let[i,s,e]=ut(n,o);return this.header={"Content-Range":`bytes ${i}-${s}/${e}`,"Content-Length":n.toString()},t.slice(i,s+1)}async function Nt(t){return this.status=t.status,this.header=t.headers.toJSON(),await t.arrayBuffer()}import{ServerSide as fn}from"authored";function O(t,n){if(this.status=n||200,typeof t==="object")return this.type="application/json",JSON.stringify(t);return this.type="text/html",String(t)}async function Wt(t){if(t instanceof fn)return Ot.call(this,t);return O.call(this,t)}class D{type;render;data;constructor(t,n,r={}){this.type=t;this.render=n;this.data=r}static async jwt(t){return new D("jwt",t)}}async function $t(t,n=!1){let{type:r,render:o,data:i}=t;switch(r){case"jwt":return"jwt"}return"render"}function un(t){return this.status=t??204,null}async function mn(t){let{header:n,status:r,__session:o}=t;if(q(n))this.header=n;if(r)this.status=r;o&&await ct(o,this.headers)}async function P(t,n,r=!1){if(!n)return un.call(this,t.status);if(typeof n==="object"&&"error"in n&&C(n.error))return this.status=n.error,null;if(await mn.call(this,t),n instanceof Response)return await Nt.call(this,n);if(n instanceof D){if(t.status)this.status=t.status;return await $t.call(this,n,r)}switch(this.request.method){case"post":return Wt.call(this,n);default:return O.call(this,n)}}async function It(){let{serverPath:t,args:n,session:r}=await g.call(this,"path");if(!t)return this.request.isFile?await Jt.call(this):null;let{serverClass:o}=t;if(!o)return null;let i=new o(this.request,n);r&&i.setServerSession(r);let{isEventStream:s,method:e}=this.request;if(s&&i?.eventStream)return await qt.call(this,i,n,i.eventStream);if(e==="options")return this.status=204,this.options(t.options);if(i?.[e]){let f=await i[e]();return this.status=200,this.compress("deflate",await P.call(this,i,f)??"")}return null}async function Ut(){let t=this.path;this.path=this.status.toString();let{serverPath:n,args:r,session:o}=await g.call(this,"error");if(this.path=t,!n)return null;let{serverClass:i}=n;if(!i)return null;let s=new i(this.request,r);s.status=this.status;let{method:e}=this.request;if(s?.[e]){let f=await s[e]();return this.compress("deflate",await P.call(this,s,f,!0)??"")}return null}class Pt extends T{request;args;status;stream;path;hash;headers={};constructor(t,n={}){super();this.request=t;this.args=n;this.path=t.path,this.hash=t.hash}set header(t){R(this.headers,t)}get header(){return this.headers}set type(t){this.header={"Content-Type":t}}setCookie({key:t,val:n,path:r="/",days:o=31,httpOnly:i=!1}){let s=lt(t,n,{expires:new B().timed({day:o}),path:r,httpOnly:i,sameSite:"Strict"});this.header={"Set-Cookie":s}}deleteCookie(t){this.setCookie({key:t,val:"",days:0})}}class Qt{status=404;headers=new Headers({"Content-Type":"text/plain"});set header(t){l(t).forEach(([n,r])=>{this.headers.set(n,r)})}set type(t){this.headers.set("Content-Type",t)}options(t){return t+=", OPTIONS",this.header={Allow:t,"Access-Control-Allow-Methods":t,"Access-Control-Max-Age":"86400"},null}compress(t,n){let o=(t==="gzip"?hn:pn)(n);return this.header={"Content-Length":o.byteLength.toString(),"Content-Encoding":t},o}get init(){return{status:this.status,headers:this.headers}}}class Q extends Qt{dir;base;request;path="";constructor(t,n,r="./",o=""){super();this.dir=r;this.base=o;this.request=new M(t,n)}async response(){let{fullPath:t,isWSS:n}=this.request;this.path=this._base(t);let r=await(n?j:It).call(this);if(!r&&!this.request.isFile)r=await Ut.call(this);return new Response(r,this.init)}_base(t){return J(this.base,t)}}import{mkdirSync as ln,writeFileSync as an,existsSync as Gt}from"fs";var{file:cn}=globalThis.Bun;var{file:X,write:Xt}=globalThis.Bun;class V{fs;f_timed;data;key;dir;constructor({dir:t,fs:n,key:r}){this.dir=t+"/ffs",this.key=r,this.f_timed=Date.now(),this.data=new Map,this.fs=this.dir+`/${n}.json`}async init(){if(v(this.dir)&&k(this.fs,"{}"))X(this.fs).text().then((t)=>{let n=JSON.parse(t);this.data=new Map(l(n))}).catch((t)=>{})}async get(t){let n=this.data.get(t);if(n)return n;return null}async queue(){}async set(t){if(this.key in t){let n=await X(this.fs).text();if(n){let r=JSON.parse(n),o=t[this.key];r[o]=t,await Xt(this.fs,JSON.stringify(r))}this.data.set(t[this.key],t)}return!1}async delete(t){if(await this.get(t)){let n=await X(this.fs).text();if(n){let r=JSON.parse(n.toString());if(t in r)delete r[t],await Xt(this.fs,JSON.stringify(r));this.data.delete(t)}}}async json(){let t=await X(this.fs).text();return JSON.parse(t)}}var k=(t,n="")=>{if(Gt(t))return!0;return an(t,n,{flag:"wx"}),!0},v=(t)=>{if(Gt(t))return!0;return ln(t,{recursive:!0}),!0},Yt=(t,n)=>{if(!n)v(t),k(t+"/.env",`SECRET_KEY="${b(20)}"
|
|
3
3
|
TLS_KEY=""
|
|
4
|
-
TLS_CERT=""`)},
|
|
4
|
+
TLS_CERT=""`)},tt=(t)=>{return l(process.env).filter(([n])=>n.startsWith("TLS_")).reduce((n,[r,o])=>{if(o){let i=r.replace("TLS_","").toLowerCase();n[i]=cn(t+o)}return n},{})};async function Zt(t){let{server:n,wss:r}=t,o=n.fn;delete n.fn;let{key:i,cert:s}=tt(this.dir),e=n.port||3000,f=yn({...n,...this._statics&&{static:this._statics},port:e,tls:{key:await i.text(),cert:await s.text()},fetch:async(m,p)=>{return await new Q(m,p,this.apt,this.base).response()},websocket:{sendPings:!0,perMessageDeflate:!0,...r,...F}});o?.(e);let u=()=>{f.stop(),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u)}var Ht=async(t,n,r="")=>{let{path:o,hostname:i,method:s,port:e,name:f}=t,m=await(await new Q({url:`http://${i??"127.0.0.1"}:${e||3000}${o}`,method:s??"GET"},void 0,n).response()).arrayBuffer(),p=o?.slice(1),c=(f?`/${f}`:p?"/"+p:"").split("#")[0];if(m.byteLength)await Sn(n+r+`${c}/index.html`,gn(m));return c+"/index"};import{config as wn}from"dotenv";class At extends L{html;serve;constructor(t={}){super(".",t);let{envPath:n,session:r}=t,o=this.dir+"/.private";Yt(o,n),wn({path:(n?n:o)+"/.env"});let i=r??new bn({dir:this.dir});h.init(i),this.html=async(s={})=>{s.path=this._base(s.path||"/");let e=await Ht(s,this.apt,this.base),f=new Date().toLocaleTimeString();d.i=`${e}.html @ ${f}`},this.serve=async(s={},e)=>await Zt.call(this,{server:s,wss:e}),this.folders("/")}}export{Ct as websocket,Pt as response,d as log,tt as getTLS,vt as auths,B as Time,At as Rossa,D as Render,a as Mapper,V as JSONCacher};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rossa",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"description": "Rossa Bun JS framework",
|
|
5
5
|
"author": "Marky <markjotep@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -35,13 +35,13 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"jsonwebtoken": "^9.0.2",
|
|
37
37
|
"authored": "latest",
|
|
38
|
-
"dotenv": "^16.
|
|
38
|
+
"dotenv": "^16.6.1"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@types/jsonwebtoken": "^9.0.
|
|
41
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
42
42
|
"@types/bun": "1.2.2",
|
|
43
|
-
"rollup": "^4.
|
|
44
|
-
"rollup-plugin-dts": "^6.
|
|
43
|
+
"rollup": "^4.46.2",
|
|
44
|
+
"rollup-plugin-dts": "^6.2.1"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"typescript": "^5.7.2"
|