rossa 0.0.2 → 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/LICENSE +1 -1
- package/dist/index.d.ts +100 -54
- package/dist/index.js +2 -3
- package/package.json +6 -6
package/LICENSE
CHANGED
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,
|
|
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,80 +166,57 @@ 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
|
}
|
|
177
219
|
|
|
178
|
-
declare class Builder {
|
|
179
|
-
dir: string;
|
|
180
|
-
out: string;
|
|
181
|
-
files: string[];
|
|
182
|
-
external: string[];
|
|
183
|
-
drop: string[];
|
|
184
|
-
target: string;
|
|
185
|
-
define: Record<string, any>;
|
|
186
|
-
exclude: string[];
|
|
187
|
-
hashAsset: boolean;
|
|
188
|
-
plugins: BunPlugin[];
|
|
189
|
-
private clearing?;
|
|
190
|
-
constructor({ files, target, define, hashAsset, external, drop, plugins, }: {
|
|
191
|
-
files: string[];
|
|
192
|
-
target?: "browser" | "bun";
|
|
193
|
-
define?: Record<string, any>;
|
|
194
|
-
hashAsset?: boolean;
|
|
195
|
-
external?: string[];
|
|
196
|
-
drop?: string[];
|
|
197
|
-
plugins?: BunPlugin[];
|
|
198
|
-
});
|
|
199
|
-
clear(c?: {
|
|
200
|
-
exclude: string[];
|
|
201
|
-
}): this;
|
|
202
|
-
build(): this;
|
|
203
|
-
watch(fn?: (event: any, filename: any) => void): void;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
220
|
declare class Render<T> {
|
|
207
221
|
type: "yra" | "jwt";
|
|
208
222
|
render: T;
|
|
@@ -211,4 +225,36 @@ declare class Render<T> {
|
|
|
211
225
|
static jwt(jwtSession: any): Promise<Render<ServerSide>>;
|
|
212
226
|
}
|
|
213
227
|
|
|
214
|
-
|
|
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,5 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var tt=function(t,r,n,o){var s=arguments.length,i=s<3?r:o===null?o=Object.getOwnPropertyDescriptor(r,n):o,e;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")i=Reflect.decorate(t,r,n,o);else for(var f=t.length-1;f>=0;f--)if(e=t[f])i=(s<3?e(i):s>3?e(r,n,i):e(r,n))||i;return s>3&&i&&Object.defineProperty(r,n,i),i};var rt=(t,r)=>{if(typeof Reflect==="object"&&typeof Reflect.metadata==="function")return Reflect.metadata(t,r)};import{Auth as dr}from"authored";var B=(t)=>typeof t==="function";var D=(t)=>{return!isNaN(parseFloat(t))&&isFinite(t)};var nt=(t)=>{return t instanceof Uint8Array||t instanceof ArrayBuffer||typeof t==="string"};var L=(t)=>typeof t==="string",M=(t)=>Array.isArray(t),ot=(t)=>typeof t==="object";var st=(t)=>{return Number.isInteger(Number(t))};function it(t,r){p(r).forEach(([n,o])=>{ft(t,n,{value:o,writable:!1,configurable:!1,enumerable:!0})})}class S{static set p(t){if(Array.isArray(t))console.log(...t);else console.log(t)}}class Z{_c=0;_id="";constructor(t){if(this._c=0,this._id=t??y(5),t?.includes("-")){let[r,n]=[t.split("-").slice(0,-1).join("-"),t.split("-").slice(-1)[0]];this._id=r,this._c=D(n)?parseInt(n):0}}get id(){return this._id+"-"+this._c}get mid(){return this._id+"-"+ ++this._c}}var et=(t,r)=>{let[n,o]=r.replace(/bytes=/,"").split("-").map((s,i)=>{let e=parseInt(s,10);return isNaN(e)?i===0?0:t-1:e});return[n,o,t]};var Yr=new RegExp(/(\d+)(\d*)/,"m"),At=(t)=>Array.from({length:t},(r,n)=>n),Kt="ABCDEFGHIJKLMNOPQRSTUVWXYZ",Ft="abcdefghijklmnopqrstuvwxyz",Vt=At(10).join("");var R=(t)=>JSON.stringify(t),ut=(t)=>{return JSON.parse(t)},W=(t)=>{if(t.startsWith("webkit"))t="-"+t;return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()},y=(t)=>{let r=Kt+Ft;return Array.from({length:t},(n,o)=>r+(o?Vt:"")).reduce((n,o)=>{return n+=o.charAt(Math.floor(Math.random()*o.length))},"")};class c extends Map{obj(t){t&&p(t).forEach(([r,n])=>this.set(r,n))}map(t){t.forEach((r,n)=>{if(r instanceof c)this.set(n,r);else if(M(r)){if(this.lacks(n))this.set(n,[]);this.get(n).push(...r)}else if(ot(r))this.ass(n,r);else this.set(n,r)})}ass(t,r){if(!this.has(t))this.set(t,{});T(this.get(t),r)}lacks(t){return!this.has(t)}init(t,r){return this.has(t)?this.get(t):this.set(t,r).get(t)}}var{values:E,keys:H,entries:p,fromEntries:pt,hasOwn:_t}=Object;var{defineProperty:ft,assign:T}=Object,q=(t)=>{return Object.keys(t).length};function mt(t){return class extends t{constructor(...r){super(...r);let n=new Map;return new Proxy(this,{get(o,s){let i=`__${s}`;if(!n.has(i)){let e=o[s];if(B(e))e=function(...f){let u=`${i}_${JSON.stringify(f)}`;if(!n.has(u)){let h=o[s].apply(o,f);n.set(u,h)}return n.get(u)};n.set(i,e)}return n.get(i)},set(o,s,i){let e=`__${s}`;return n.set(e,i),!0}})}}}var w=(t,r)=>{return{name:t,content:r}},kt=(t,r)=>{return{property:t,content:r}},vt=(t,r)=>{return{"http-equiv":t,content:r}};class j{metas=[];constructor(t){t&&this.metas.push(w("description",t))}author(t){return this.meta=w("author",t),this}charset(t){return this.meta={charset:t},this}keywords(...t){return this.meta=w("keywords",t.join(", ")),this}viewport(t){let r=p(t).map(([n,o])=>[W(n),String(o)].join("="));return this.meta=w("viewport",r.join(", ")),this}httpEquiv(t){return p(t).forEach(([r,n])=>{this.meta=vt(W(r),String(n))}),this}robots(...t){return this.meta=w("robots",t.join(", ")),this}themeColor(t){return this.meta=w("theme-color",t),this}openGraph(t){return p(t).forEach(([r,n])=>{this.meta=kt("og:"+r,String(n))}),this}twitter(t){return p(t).forEach(([r,n])=>{this.meta=w("twitter:"+r,String(n))}),this}and(t){return this}set meta(t){this.metas.push(t)}}var tr=["charset","name","property","http-equiv"],ht=(t,r)=>{r.forEach((n)=>{for(let o of tr)if(o in n){let s=n[o];t[`${o}_${o==="charset"?"":s}`]=n}})},rr=(t,r)=>{r.forEach((n)=>{if("href"in n){let o=n.href;t[`${o}`]=n}})};class ct{_head;idm;constructor(t){this._head=new c(t)}set head(t){p(t).forEach(([r,n])=>{if(r==="title"||r==="base"){if(n!==void 0)this._head.set(r,n);return}if(n instanceof j)return ht(this._head.init("meta",{}),n.metas);if(!M(n))return;switch(r){case"meta":return ht(this._head.init("meta",{}),n);case"link":return rr(this._head.init("link",{}),n);case"script":if(n.length){this._head.init(r,[]);let o=n.map((s)=>{if(!s.yid&&this.idm)s.yid="sc"+this.idm.mid;return s});this._head.get(r).push(...o)}return}})}get head(){return this._head}set id(t){this.idm=new Z(t)}}class nr{lang="en";htmlHead=new c;head;constructor(){this.head=(t={})=>{let r=new ct(this.htmlHead);r.head=t,this.htmlHead=r.head}}}var lt=(t,r="",{maxAge:n,expires:o,path:s,domain:i,secure:e,httpOnly:f,sameSite:u})=>{if(n instanceof Date)n=n.getSeconds();if(o instanceof Date)o=o.toUTCString();else if(o===0)o=new Date().toUTCString();return[["Domain",i],["Expires",o],["Max-Age",n],["Secure",e],["HttpOnly",f],["Path",s],["SameSite",u]].reduce((a,[x,g])=>{if(g!==void 0)a.push(`${x}=${g}`);return a},[`${t}=${r}`]).join("; ")};var N=(t,r=!1)=>{if(D(t))return[+t,st(t)?"int":"float"];if(r&&/\.\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"]},b=(t)=>{let r=t.startsWith("/")?t:"/"+t,n=r.match(/(?<=\/)[^/].*?(?=\/|$)/g)??["/"],[o,s]=n.reduce(([i,e],f)=>{if(f.includes("<")){let u=f.match(/(?<=<)[^/].*?(?=>|$)/g);if(u?.length){let[h,a]=u[0].split(":");if(h&&a)i.push(h),e.push(a)}}else i.push(f===">"?"/":f);return[i,e]},[[],[]]);if(r.endsWith("/")&&r.length>1)o.push("/");return{parsed:o,args:s}};class U{storage=new c;cache(t,r){if(this.storage.lacks(t))this.storage.set(t,r());return this.storage.get(t)}}var or=["int","float","file","uuid","string"],sr=new U;class z{_storage=new c;set(t){let{parsed:r,path:n}=t,o=R(r);if(!this._storage.get(o))this._storage.set(o,t);else throw`path: ${n} already used.`}get(t){let{parsed:r}=sr.cache(t,()=>b(t)),n={},o=this._storage.get(R(r));if(!o&&t!=="/")for(let s of this._storage.keys()){let i=[],e=ut(s);if(r.length===e.length){let f=e.map((a,x)=>{let g=N(r[x],r.length-1===x);if(a===g[0])return g[0];if(or.includes(g[1]))return i.push(g[0]),g[1];return a}),u=R(f);if(this._storage.has(u)){o=this._storage.get(u),o?.args.forEach((a,x)=>{n[a]=i[x]});break}}}return[o,n]}}class G{constructor(...t){t.forEach((r)=>{if(!this[r])this[r]=new z})}get(t){return this[t]}}class P{path="";parsed=[];args=[];constructor(t){it(this,{path:t,...b(t)})}}class I{date;constructor(t){this.date=t?new Date(t):new Date}delta(t=null,r=!1){let n=I.delta(this.date.getTime(),t);return r?new Date(n):n}timed(t){if(!t)return this.date;return[["year","FullYear"],["month","Month"],["day","Date"],["hour","Hours"],["minute","Minutes"],["second","Seconds"]].reduce((n,[o,s])=>{let i=t[o];return i?new Date(n[`set${s}`](n[`get${s}`]()+i)):n},new Date(this.date))}static delta(t,r=null){return r?r-t:t-Date.now()}static get now(){return Date.now()}}var{file:fr}=globalThis.Bun;import{JWTInterface as ir}from"authored";class at{session;jwt;jwtInt;constructor(){this.jwtInt=new ir}init(t){this.session=t.session,this.jwt=t.jwt}}var m=new at;class d{__session;__jwt;get session(){if(!this.__session)this.__session=m.session.new;return this.__session}set session(t){this.__session=t}get jwt(){if(!this.__jwt)this.__jwt=m.jwt.new;return this.__jwt}set jwt(t){this.__jwt=t}get timedJWT(){return m.jwtInt.jwt()}setServerSession(t){let{__jwt:r,__session:n}=t;this.__session=n,this.__jwt=r}}var gt=async(t,r)=>{await m.session.saveSession(t,r)};async function St({sid:t,jwtv:r,refreshjwt:n},o){let s=new d;if(t){if(s.session=await m.session.openSession(t),!s.session.new)o.session=!0}if(r){if(s.jwt=m.jwtInt.open(r,{hours:6}),!s.jwt.new)o.jwt=!0;if(n){if(!(await m.jwt.openSession(n)).new)o.jwt_refresh=!0}}if("session"in o||"jwt"in o)return s}var er={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,r,n)=>{let o=r.value;return r.value=async function(s={}){if(n in s&&s.session)return delete s[n],o.call(t,s);return{error:401}},r};var ur=["GET","POST","PUT","DELETE","OPTIONS"];class bt extends P{config;_class;options="";bytes;fileType="text/plain";fileSize=0;constructor(t,r={}){super(t);this.config=r}set serverClass(t){this._class=t,this.options=ur.filter((r)=>t.prototype[r.toLowerCase()]).join(", ")}get serverClass(){return this._class}async loadBytes(t){if(!this.config.preload)return;try{let r=fr(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 Rt={path:Symbol("path"),wss:Symbol("wss"),file:Symbol("file"),folder:Symbol("folder"),error:Symbol("error")},pr=new G(...E(Rt)),wt=(t)=>{let r=Rt[t];if(!r)throw new Error("Invalid storage type");return pr[r]},C=(t,r,n={},o)=>{return(s)=>{let i=new bt(r,n);if(s)i.serverClass=s;if(t==="file")i.loadBytes(o);return wt(t).set(i),s}},yt={args:{}};async function l(t){let[r,n]=wt(t).get(this.path);if(!r)return yt;let{requireSession:o}=r.config,s=void 0;if(o){if(s=await St(await this.request.authgroup(),n),!s)return yt}return{serverPath:r,args:n,session:s}}class K{dir;apt;files;_statics;statics;constructor(t=".",r={}){this.dir=t;let{dir:n,appDir:o}=r;if(n)this.dir=n;this.apt=this.dir+"/"+(o??"app"),this.files=(...s)=>{s.forEach((i)=>{let[e,f]=Ct(i),u=e.replace(/^\.+/,""),h=u.startsWith("/")?u:"/"+u;C("file",h,f,this.apt)()})},this.statics=(s={})=>{if(!this._statics)this._statics={};T(this._statics,s)}}route(t){return C("path",t)}wss(t,r={}){return C("wss",t,r)}error(...t){return(r)=>{if(t.length)t.forEach((n)=>{C("error",n.toString(),{})(r)});else C("error","404",{})(r);return r}}folders(...t){t.forEach((r)=>{C("folder",...Ct(r))()})}redirect(t,r={}){return new Response("",{status:302,headers:new Headers({...r,Location:t})})}}var Ct=(t)=>{let r=L(t);return[r?t:t[0],r?{}:t[1]]};var{inflateSync:Cr,serve:xr,write:Tr}=globalThis.Bun;class xt extends c{}var F=new xt;var V={async open(t){let r=t.data.wclass,{args:n,client:o}=t.data;if(r){r.ws=t;let s=r.id,i=q(o);if(!(s in o)){let e=i?"joiner":"maker";o[s]={role:e}}if(typeof r.init=="function")await r.init(n);if(r.broadcasting)r.ws.subscribe(r.path);await r.open()}else t.close()},async message(t,r){let n=t.data.wclass;if(n)await n.message(r)},async close(t,r,n){let o=t.data.wclass,s=t.data.client;if(o){if(await o.close(r,n),o.broadcasting)o.ws.unsubscribe(o.path);let i=o.id;if(delete s[i],q(s)===1)H(s).forEach((e)=>{s[e].role="maker"})}}};async function _(){let{serverPath:t,args:r,session:n}=await l.call(this,"wss");if(!t)return this.status=426,"upgrade error";let{serverClass:o}=t;if(!o)return"upgrade error";let s=new o(this.request);n&&s.setServerSession(n);let i=s.path,e=Tt(i),f=e?.size??0,{broadcast:u,maxClient:h}=t.config;if(s.broadcasting=!!u,s.max=h??0,h&&f>=h)return this.status=400,"upgrade error";return this.request.upgradeConnection({data:{wclass:s,args:r,client:e}}),null}class dt extends d{request;ws;path;id;broadcasting=!1;max=0;constructor(t){super();this.request=t;this.path=t.path,this.id=y(10)}open(){}message(t){}close(t,r){}set send(t){if(t)if(this.broadcasting)this.ws.publish(this.path,t);else this.ws.send(t)}get role(){let t=F.get(this.path);if(t&&t.has(this.id))return t.get(this.id)?.role}}var Tt=(t)=>{return F.init(t,new c)};var{deflateSync:Sr,gzipSync:yr}=globalThis.Bun;var{Server:mr,file:hr}=globalThis.Bun;class ${req;server;formData;url;method;__cookies=new Map;constructor(t,r){this.req=t;this.server=r;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:r}=this,n=t.get("session")??"",o=r??"",s="",i=this.isForm?await this.form():void 0;if(i){let e=i.get("refresh_token");s=e?e.toString():""}return{sid:n,jwtv:o,refreshjwt:s}}upgradeConnection(t={}){return!!this.server?.upgrade(this.req,t)}get auth(){let t=this.headers.get("authorization");if(t){let[r,n]=t.split(" ",2);if(r.trim()=="Bearer")return n.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 r=t.split(";").reduce((n,o)=>{let[s,i]=o.trim().split(/=(.*)/s);return n.push([s,i]),n},[]);this.__cookies=new Map(r)}}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}=b(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?N(t,!0).pop()==="file":!1}get type(){return hr(this.path).type}get upgrade(){return this.headers.get("upgrade")}get request(){return this.req}get signal(){return this.req.signal}}$=tt([mt,rt("design:paramtypes",[typeof Request==="undefined"?Object:Request,typeof mr==="undefined"?Object:mr])],$);class Et{ctrl;intervalID=[];constructor(t){this.ctrl=t}push(t,r=2000){if(this.ctrl){let n=setInterval(()=>{let{id:o,retry:s,data:i,event:e,end:f}=t();if(this.ctrl){let u=f?"end":i;if(s){let h=s>2000?s: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()}},r>1000?r:1000);this.intervalID.push(n)}}close(){if(this.intervalID.length)this.intervalID.forEach((t)=>{clearInterval(t)}),this.intervalID=[];this.ctrl?.close()}}async function qt(t,r,n){this.status=200,this.header={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};let o=this.request,s=new ReadableStream({async start(e){t.stream=new Et(e),await n.call(t,r),o.signal.addEventListener("abort",()=>{if(t.stream?.close(),t.stream?.intervalID.length)e.close()})}}),i=await n.call(t,r);if(typeof i==="object"&&"error"in i)return this.status=i.error,null;return s}async function $t(t){let r=m.jwtInt.save(t);return t.access_token=r,await m.jwt.saveSession(t,this.headers),{access_token:r,refresh_token:t.sid,status:"ok"}}function Ot(t){return this.status=403,{error:t}}async function Jt(t){let{jwtv:r,refreshjwt:n}=await this.request.authgroup();if(!n){if(r||!t.modified)return this.status=204,this.type="application/json",JSON.stringify({});return JSON.stringify(await $t.call(this,t))}let o=await m.jwt.openSession(n),s=o.data.access_token,i={};if(r!==s)i=Ot.call(this,"tokens don't match.");else if(!m.jwtInt.verify(s,{days:5}))await m.jwt.saveSession(o,void 0,!0),i=Ot.call(this,"expired refresh_token.");else i=await $t.call(this,o);return this.type="application/json",JSON.stringify(i)}var{file:cr}=globalThis.Bun;async function Bt(){let t=this.path,{parsed:r}=b(this.path),n=r.slice(0,-1).join("/");this.path=n;let{serverPath:o}=await l.call(this,"folder");if(!o)return null;return this.path=t,await k.call(this)}async function Dt(){let{serverPath:t}=await l.call(this,"file");if(!t)return await Bt.call(this);if(t.bytes)return v.call(this,t.bytes,t.fileSize);return await k.call(this)}async function k(){try{let t=cr(this.dir+this.path);if(t.type.startsWith("video/"))return v.call(this,t,t.size);else{let r=await t.bytes();return v.call(this,r,r.byteLength)}}catch{return`${this.path} file not found.`}}function v(t,r){let{type:n,range:o}=this.request;if(this.type=n,this.status=206,!o)return this.header={"Cache-Control":"max-age=86400, must-revalidate"},nt(t)?this.compress("gzip",t):t;let[s,i,e]=et(r,o);return this.header={"Content-Range":`bytes ${s}-${i}/${e}`,"Content-Length":r.toString()},t.slice(s,i+1)}async function Mt(t){return this.status=t.status,this.header=t.headers.toJSON(),await t.arrayBuffer()}import{ServerSide as lr}from"authored";function O(t,r){if(this.status=r||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 lr)return Jt.call(this,t);return O.call(this,t)}class J{type;render;data;constructor(t,r,n={}){this.type=t;this.render=r;this.data=n}static async jwt(t){return new J("jwt",t)}}async function Nt(t,r=!1){let{type:n,render:o,data:s}=t;switch(n){case"jwt":return"jwt"}return"render"}function ar(t){return this.status=t??204,null}async function gr(t){let{header:r,status:n,__session:o}=t;if(q(r))this.header=r;if(n)this.status=n;o&&await gt(o,this.headers)}async function Q(t,r,n=!1){if(!r)return ar.call(this,t.status);if(typeof r==="object"&&"error"in r)return this.status=r.error,null;if(await gr.call(this,t),r instanceof Response)return await Mt.call(this,r);if(r instanceof J){if(t.status)this.status=t.status;return await Nt.call(this,r,n)}switch(this.request.method){case"post":return Wt.call(this,r);default:return O.call(this,r)}}async function Ut(){let{serverPath:t,args:r,session:n}=await l.call(this,"path");if(!t)return this.request.isFile?Dt.call(this):null;let{serverClass:o}=t;if(!o)return null;let s=new o(this.request,r);n&&s.setServerSession(n);let{isEventStream:i,method:e}=this.request;if(i&&s?.eventStream)return qt.call(this,s,r,s.eventStream);if(e==="options")return this.status=204,this.options(t.options);if(s?.[e]){let f=await s[e]();return this.status=200,this.compress("deflate",await Q.call(this,s,f)??"")}return null}async function Gt(){let t=this.path;this.path=this.status.toString();let{serverPath:r,args:n,session:o}=await l.call(this,"error");if(this.path=t,!r)return null;let{serverClass:s}=r;if(!s)return null;let i=new s(this.request,n);i.status=this.status;let{method:e}=this.request;if(i?.[e]){let f=await i[e]();return this.compress("deflate",await Q.call(this,i,f,!0)??"")}return null}class Pt extends d{request;args;status;stream;path;headers={};constructor(t,r={}){super();this.request=t;this.args=r;this.path=t.path}set header(t){T(this.headers,t)}get header(){return this.headers}set type(t){this.header={"Content-Type":t}}setCookie({key:t,val:r,path:n="/",days:o=31,httpOnly:s=!1}){let i=lt(t,r,{expires:new I().timed({day:o}),path:n,httpOnly:s,sameSite:"Strict"});this.header={"Set-Cookie":i}}deleteCookie(t){this.setCookie({key:t,val:"",days:0})}}class It{status=404;headers=new Headers({"Content-Type":"text/plain"});set header(t){p(t).forEach(([r,n])=>{this.headers.set(r,n)})}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,r){let o=(t==="gzip"?yr:Sr)(r);return this.header={"Content-Length":o.byteLength.toString(),"Content-Encoding":t},o}get init(){return{status:this.status,headers:this.headers}}}class X extends It{dir;request;path="";constructor(t,r,n="./"){super();this.dir=n;this.request=new $(t,r)}async response(){let{path:t,isWSS:r}=this.request;this.path=t;let n=await(r?_:Ut).call(this);if(!n)n=await Gt.call(this);return new Response(n,this.init)}}import{mkdirSync as br,writeFileSync as Rr,existsSync as Xt}from"fs";var{file:wr}=globalThis.Bun;var Qt=(t,r="")=>{if(Xt(t))return!0;return Rr(t,r,{flag:"wx"}),!0},Y=(t)=>{if(Xt(t))return!0;return br(t,{recursive:!0}),!0},Yt=(t,r)=>{if(!r)Y(t),Qt(t+"/.env",`SECRET_KEY="${y(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=""`)},
|
|
5
|
-
watcher closed...`),r.close(),process.exit(0)})}}var Mr=(t)=>{return pt(p(t).map(([r,n])=>{let o=n;if(B(n))o=n();return[r,R(o)]}))};export{dt as websocket,Pt as response,er as auths,jt as Rossa,J as Render,zt as Builder,S as $$};
|
|
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.
|
|
39
|
-
"rollup": "^4.34.6",
|
|
40
|
-
"rollup-plugin-dts": "^6.1.1"
|
|
38
|
+
"dotenv": "^16.6.1"
|
|
41
39
|
},
|
|
42
40
|
"devDependencies": {
|
|
43
|
-
"@types/jsonwebtoken": "^9.0.
|
|
44
|
-
"@types/bun": "
|
|
41
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
42
|
+
"@types/bun": "1.2.2",
|
|
43
|
+
"rollup": "^4.46.2",
|
|
44
|
+
"rollup-plugin-dts": "^6.2.1"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"typescript": "^5.7.2"
|