@flexireact/core 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Fetch API Polyfill for Universal Compatibility
3
+ *
4
+ * Ensures Request, Response, Headers work everywhere
5
+ */
6
+
7
+ // Use native Web APIs if available, otherwise polyfill
8
+ const globalFetch = globalThis.fetch;
9
+ const GlobalRequest = globalThis.Request;
10
+ const GlobalResponse = globalThis.Response;
11
+ const GlobalHeaders = globalThis.Headers;
12
+
13
+ // Extended Request with FlexiReact helpers
14
+ export class FlexiRequest extends GlobalRequest {
15
+ private _parsedUrl?: URL;
16
+ private _cookies?: Map<string, string>;
17
+
18
+ constructor(input: RequestInfo | URL, init?: RequestInit) {
19
+ super(input, init);
20
+ }
21
+
22
+ get pathname(): string {
23
+ if (!this._parsedUrl) {
24
+ this._parsedUrl = new URL(this.url);
25
+ }
26
+ return this._parsedUrl.pathname;
27
+ }
28
+
29
+ get searchParams(): URLSearchParams {
30
+ if (!this._parsedUrl) {
31
+ this._parsedUrl = new URL(this.url);
32
+ }
33
+ return this._parsedUrl.searchParams;
34
+ }
35
+
36
+ get cookies(): Map<string, string> {
37
+ if (!this._cookies) {
38
+ this._cookies = new Map();
39
+ const cookieHeader = this.headers.get('cookie');
40
+ if (cookieHeader) {
41
+ cookieHeader.split(';').forEach(cookie => {
42
+ const [name, ...rest] = cookie.trim().split('=');
43
+ if (name) {
44
+ this._cookies!.set(name, rest.join('='));
45
+ }
46
+ });
47
+ }
48
+ }
49
+ return this._cookies;
50
+ }
51
+
52
+ cookie(name: string): string | undefined {
53
+ return this.cookies.get(name);
54
+ }
55
+
56
+ // Parse JSON body
57
+ async jsonBody<T = any>(): Promise<T> {
58
+ return this.json();
59
+ }
60
+
61
+ // Parse form data
62
+ async formBody(): Promise<FormData> {
63
+ return this.formData();
64
+ }
65
+
66
+ // Get query param
67
+ query(name: string): string | null {
68
+ return this.searchParams.get(name);
69
+ }
70
+
71
+ // Get all query params
72
+ queryAll(name: string): string[] {
73
+ return this.searchParams.getAll(name);
74
+ }
75
+ }
76
+
77
+ // Extended Response with FlexiReact helpers
78
+ export class FlexiResponse extends GlobalResponse {
79
+ // Static helpers for common responses
80
+
81
+ static json(data: any, init?: ResponseInit): FlexiResponse {
82
+ const headers = new Headers(init?.headers);
83
+ headers.set('Content-Type', 'application/json');
84
+
85
+ return new FlexiResponse(JSON.stringify(data), {
86
+ ...init,
87
+ headers
88
+ });
89
+ }
90
+
91
+ static html(html: string, init?: ResponseInit): FlexiResponse {
92
+ const headers = new Headers(init?.headers);
93
+ headers.set('Content-Type', 'text/html; charset=utf-8');
94
+
95
+ return new FlexiResponse(html, {
96
+ ...init,
97
+ headers
98
+ });
99
+ }
100
+
101
+ static text(text: string, init?: ResponseInit): FlexiResponse {
102
+ const headers = new Headers(init?.headers);
103
+ headers.set('Content-Type', 'text/plain; charset=utf-8');
104
+
105
+ return new FlexiResponse(text, {
106
+ ...init,
107
+ headers
108
+ });
109
+ }
110
+
111
+ static redirect(url: string, status: 301 | 302 | 303 | 307 | 308 = 307): FlexiResponse {
112
+ return new FlexiResponse(null, {
113
+ status,
114
+ headers: { Location: url }
115
+ });
116
+ }
117
+
118
+ static notFound(message: string = 'Not Found'): FlexiResponse {
119
+ return new FlexiResponse(message, {
120
+ status: 404,
121
+ headers: { 'Content-Type': 'text/plain' }
122
+ });
123
+ }
124
+
125
+ static error(message: string = 'Internal Server Error', status: number = 500): FlexiResponse {
126
+ return new FlexiResponse(message, {
127
+ status,
128
+ headers: { 'Content-Type': 'text/plain' }
129
+ });
130
+ }
131
+
132
+ // Stream response
133
+ static stream(
134
+ stream: ReadableStream,
135
+ init?: ResponseInit
136
+ ): FlexiResponse {
137
+ return new FlexiResponse(stream, init);
138
+ }
139
+
140
+ // Set cookie helper
141
+ withCookie(
142
+ name: string,
143
+ value: string,
144
+ options: {
145
+ maxAge?: number;
146
+ expires?: Date;
147
+ path?: string;
148
+ domain?: string;
149
+ secure?: boolean;
150
+ httpOnly?: boolean;
151
+ sameSite?: 'Strict' | 'Lax' | 'None';
152
+ } = {}
153
+ ): FlexiResponse {
154
+ const parts = [`${name}=${encodeURIComponent(value)}`];
155
+
156
+ if (options.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);
157
+ if (options.expires) parts.push(`Expires=${options.expires.toUTCString()}`);
158
+ if (options.path) parts.push(`Path=${options.path}`);
159
+ if (options.domain) parts.push(`Domain=${options.domain}`);
160
+ if (options.secure) parts.push('Secure');
161
+ if (options.httpOnly) parts.push('HttpOnly');
162
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
163
+
164
+ const headers = new Headers(this.headers);
165
+ headers.append('Set-Cookie', parts.join('; '));
166
+
167
+ return new FlexiResponse(this.body, {
168
+ status: this.status,
169
+ statusText: this.statusText,
170
+ headers
171
+ });
172
+ }
173
+
174
+ // Add headers helper
175
+ withHeaders(newHeaders: Record<string, string>): FlexiResponse {
176
+ const headers = new Headers(this.headers);
177
+ Object.entries(newHeaders).forEach(([key, value]) => {
178
+ headers.set(key, value);
179
+ });
180
+
181
+ return new FlexiResponse(this.body, {
182
+ status: this.status,
183
+ statusText: this.statusText,
184
+ headers
185
+ });
186
+ }
187
+ }
188
+
189
+ // Extended Headers
190
+ export class FlexiHeaders extends GlobalHeaders {
191
+ // Get bearer token
192
+ getBearerToken(): string | null {
193
+ const auth = this.get('Authorization');
194
+ if (auth?.startsWith('Bearer ')) {
195
+ return auth.slice(7);
196
+ }
197
+ return null;
198
+ }
199
+
200
+ // Get basic auth credentials
201
+ getBasicAuth(): { username: string; password: string } | null {
202
+ const auth = this.get('Authorization');
203
+ if (auth?.startsWith('Basic ')) {
204
+ try {
205
+ const decoded = atob(auth.slice(6));
206
+ const [username, password] = decoded.split(':');
207
+ return { username, password };
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+
215
+ // Check content type
216
+ isJson(): boolean {
217
+ return this.get('Content-Type')?.includes('application/json') ?? false;
218
+ }
219
+
220
+ isFormData(): boolean {
221
+ const ct = this.get('Content-Type') ?? '';
222
+ return ct.includes('multipart/form-data') || ct.includes('application/x-www-form-urlencoded');
223
+ }
224
+
225
+ isHtml(): boolean {
226
+ return this.get('Accept')?.includes('text/html') ?? false;
227
+ }
228
+ }
229
+
230
+ // Export both native and extended versions
231
+ export {
232
+ FlexiRequest as Request,
233
+ FlexiResponse as Response,
234
+ FlexiHeaders as Headers
235
+ };
236
+
237
+ // Also export native versions for compatibility
238
+ export const NativeRequest = GlobalRequest;
239
+ export const NativeResponse = GlobalResponse;
240
+ export const NativeHeaders = GlobalHeaders;
241
+
242
+ export default {
243
+ Request: FlexiRequest,
244
+ Response: FlexiResponse,
245
+ Headers: FlexiHeaders,
246
+ fetch: globalFetch
247
+ };
@@ -0,0 +1,248 @@
1
+ /**
2
+ * FlexiReact Universal Edge Handler
3
+ *
4
+ * Single handler that works on all platforms:
5
+ * - Node.js (http.createServer)
6
+ * - Bun (Bun.serve)
7
+ * - Deno (Deno.serve)
8
+ * - Cloudflare Workers (fetch handler)
9
+ * - Vercel Edge (edge function)
10
+ */
11
+
12
+ import { FlexiRequest, FlexiResponse } from './fetch-polyfill.js';
13
+ import runtime, { detectRuntime } from './runtime.js';
14
+ import { cache, CacheOptions } from './cache.js';
15
+
16
+ // Handler context
17
+ export interface EdgeContext {
18
+ runtime: typeof runtime;
19
+ cache: typeof cache;
20
+ env: Record<string, string | undefined>;
21
+ waitUntil: (promise: Promise<any>) => void;
22
+ passThroughOnException?: () => void;
23
+ }
24
+
25
+ // Route handler type
26
+ export type EdgeHandler = (
27
+ request: FlexiRequest,
28
+ context: EdgeContext
29
+ ) => Promise<FlexiResponse> | FlexiResponse;
30
+
31
+ // Middleware type
32
+ export type EdgeMiddleware = (
33
+ request: FlexiRequest,
34
+ context: EdgeContext,
35
+ next: () => Promise<FlexiResponse>
36
+ ) => Promise<FlexiResponse> | FlexiResponse;
37
+
38
+ // App configuration
39
+ export interface EdgeAppConfig {
40
+ routes?: Map<string, EdgeHandler>;
41
+ middleware?: EdgeMiddleware[];
42
+ notFound?: EdgeHandler;
43
+ onError?: (error: Error, request: FlexiRequest) => FlexiResponse;
44
+ basePath?: string;
45
+ }
46
+
47
+ // Create universal edge app
48
+ export function createEdgeApp(config: EdgeAppConfig = {}) {
49
+ const {
50
+ routes = new Map(),
51
+ middleware = [],
52
+ notFound = () => FlexiResponse.notFound(),
53
+ onError = (error) => FlexiResponse.error(error.message),
54
+ basePath = ''
55
+ } = config;
56
+
57
+ // Main fetch handler (Web Standard)
58
+ async function handleRequest(
59
+ request: Request,
60
+ env: Record<string, any> = {},
61
+ executionContext?: { waitUntil: (p: Promise<any>) => void; passThroughOnException?: () => void }
62
+ ): Promise<Response> {
63
+ const flexiRequest = new FlexiRequest(request.url, {
64
+ method: request.method,
65
+ headers: request.headers,
66
+ body: request.body,
67
+ // @ts-ignore - duplex is needed for streaming
68
+ duplex: 'half'
69
+ });
70
+
71
+ const context: EdgeContext = {
72
+ runtime,
73
+ cache,
74
+ env: env as Record<string, string | undefined>,
75
+ waitUntil: executionContext?.waitUntil || (() => {}),
76
+ passThroughOnException: executionContext?.passThroughOnException
77
+ };
78
+
79
+ try {
80
+ // Run middleware chain
81
+ const response = await runMiddleware(flexiRequest, context, middleware, async () => {
82
+ // Match route
83
+ const pathname = flexiRequest.pathname.replace(basePath, '') || '/';
84
+
85
+ // Try exact match first
86
+ let handler = routes.get(pathname);
87
+
88
+ // Try pattern matching
89
+ if (!handler) {
90
+ for (const [pattern, h] of routes) {
91
+ if (matchRoute(pathname, pattern)) {
92
+ handler = h;
93
+ break;
94
+ }
95
+ }
96
+ }
97
+
98
+ if (handler) {
99
+ return await handler(flexiRequest, context);
100
+ }
101
+
102
+ return await notFound(flexiRequest, context);
103
+ });
104
+
105
+ return response;
106
+ } catch (error: any) {
107
+ console.error('Edge handler error:', error);
108
+ return onError(error, flexiRequest);
109
+ }
110
+ }
111
+
112
+ // Run middleware chain
113
+ async function runMiddleware(
114
+ request: FlexiRequest,
115
+ context: EdgeContext,
116
+ middlewares: EdgeMiddleware[],
117
+ finalHandler: () => Promise<FlexiResponse>
118
+ ): Promise<FlexiResponse> {
119
+ let index = 0;
120
+
121
+ async function next(): Promise<FlexiResponse> {
122
+ if (index >= middlewares.length) {
123
+ return finalHandler();
124
+ }
125
+ const mw = middlewares[index++];
126
+ return mw(request, context, next);
127
+ }
128
+
129
+ return next();
130
+ }
131
+
132
+ // Simple route matching
133
+ function matchRoute(pathname: string, pattern: string): boolean {
134
+ // Exact match
135
+ if (pathname === pattern) return true;
136
+
137
+ // Convert pattern to regex
138
+ const regexPattern = pattern
139
+ .replace(/\[\.\.\.(\w+)\]/g, '(?<$1>.+)') // [...slug] -> catch-all
140
+ .replace(/\[(\w+)\]/g, '(?<$1>[^/]+)'); // [id] -> dynamic segment
141
+
142
+ const regex = new RegExp(`^${regexPattern}$`);
143
+ return regex.test(pathname);
144
+ }
145
+
146
+ // Return platform-specific exports
147
+ return {
148
+ // Web Standard fetch handler (Cloudflare, Vercel Edge, Deno)
149
+ fetch: handleRequest,
150
+
151
+ // Cloudflare Workers
152
+ async scheduled(event: any, env: any, ctx: any) {
153
+ // Handle scheduled events
154
+ },
155
+
156
+ // Add route
157
+ route(path: string, handler: EdgeHandler) {
158
+ routes.set(path, handler);
159
+ return this;
160
+ },
161
+
162
+ // Add middleware
163
+ use(mw: EdgeMiddleware) {
164
+ middleware.push(mw);
165
+ return this;
166
+ },
167
+
168
+ // Node.js adapter
169
+ toNodeHandler() {
170
+ return async (req: any, res: any) => {
171
+ const url = `http://${req.headers.host}${req.url}`;
172
+ const headers = new Headers();
173
+ Object.entries(req.headers).forEach(([key, value]) => {
174
+ if (typeof value === 'string') headers.set(key, value);
175
+ });
176
+
177
+ const body = ['GET', 'HEAD'].includes(req.method) ? undefined : req;
178
+
179
+ const request = new Request(url, {
180
+ method: req.method,
181
+ headers,
182
+ body,
183
+ // @ts-ignore
184
+ duplex: 'half'
185
+ });
186
+
187
+ const response = await handleRequest(request, process.env);
188
+
189
+ res.writeHead(response.status, Object.fromEntries(response.headers));
190
+
191
+ if (response.body) {
192
+ const reader = response.body.getReader();
193
+ while (true) {
194
+ const { done, value } = await reader.read();
195
+ if (done) break;
196
+ res.write(value);
197
+ }
198
+ }
199
+ res.end();
200
+ };
201
+ },
202
+
203
+ // Bun adapter
204
+ toBunHandler() {
205
+ return {
206
+ fetch: handleRequest,
207
+ port: parseInt(process.env.PORT || '3000', 10)
208
+ };
209
+ },
210
+
211
+ // Deno adapter
212
+ toDenoHandler() {
213
+ return handleRequest;
214
+ },
215
+
216
+ // Start server based on runtime
217
+ async listen(port: number = 3000) {
218
+ const rt = detectRuntime();
219
+
220
+ switch (rt) {
221
+ case 'bun':
222
+ console.log(`🚀 FlexiReact Edge running on Bun at http://localhost:${port}`);
223
+ // @ts-ignore - Bun global
224
+ return Bun.serve({
225
+ port,
226
+ fetch: handleRequest
227
+ });
228
+
229
+ case 'deno':
230
+ console.log(`🚀 FlexiReact Edge running on Deno at http://localhost:${port}`);
231
+ // @ts-ignore - Deno global
232
+ return Deno.serve({ port }, handleRequest);
233
+
234
+ case 'node':
235
+ default:
236
+ const http = await import('http');
237
+ const server = http.createServer(this.toNodeHandler());
238
+ server.listen(port, () => {
239
+ console.log(`🚀 FlexiReact Edge running on Node.js at http://localhost:${port}`);
240
+ });
241
+ return server;
242
+ }
243
+ }
244
+ };
245
+ }
246
+
247
+ // Export default app creator
248
+ export default createEdgeApp;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * FlexiReact Edge Runtime
3
+ *
4
+ * Universal edge runtime that works everywhere:
5
+ * - Node.js
6
+ * - Bun
7
+ * - Deno
8
+ * - Cloudflare Workers
9
+ * - Vercel Edge
10
+ * - Netlify Edge
11
+ */
12
+
13
+ // Runtime detection and capabilities
14
+ export {
15
+ detectRuntime,
16
+ getRuntimeCapabilities,
17
+ runtime as edgeRuntimeInfo,
18
+ type RuntimeEnvironment,
19
+ type RuntimeCapabilities
20
+ } from './runtime.js';
21
+
22
+ // Fetch polyfill with helpers
23
+ export {
24
+ FlexiRequest,
25
+ FlexiResponse,
26
+ FlexiHeaders,
27
+ Request,
28
+ Response,
29
+ Headers,
30
+ NativeRequest,
31
+ NativeResponse,
32
+ NativeHeaders
33
+ } from './fetch-polyfill.js';
34
+
35
+ // Universal handler
36
+ export {
37
+ createEdgeApp,
38
+ type EdgeContext,
39
+ type EdgeHandler,
40
+ type EdgeMiddleware,
41
+ type EdgeAppConfig
42
+ } from './handler.js';
43
+
44
+ // Smart caching
45
+ export {
46
+ cache as smartCache,
47
+ initCache,
48
+ cacheFunction,
49
+ unstable_cache,
50
+ revalidateTag,
51
+ revalidatePath,
52
+ getRequestCache,
53
+ reactCache,
54
+ type CacheEntry,
55
+ type CacheOptions,
56
+ type CacheStorage
57
+ } from './cache.js';
58
+
59
+ // Partial Prerendering
60
+ export {
61
+ dynamic,
62
+ staticComponent,
63
+ PPRBoundary,
64
+ PPRShell,
65
+ prerenderWithPPR,
66
+ streamPPR,
67
+ pprFetch,
68
+ PPRLoading,
69
+ getPPRStyles,
70
+ experimental_ppr,
71
+ type PPRConfig,
72
+ type PPRRenderResult,
73
+ type PPRPageConfig,
74
+ type GenerateStaticParams
75
+ } from './ppr.js';
76
+
77
+ // Default export
78
+ export { default as edgeRuntime } from './runtime.js';
79
+ export { default as edgeCache } from './cache.js';
80
+ export { default as edgePPR } from './ppr.js';
81
+ export { default as createApp } from './handler.js';