@flexireact/core 3.0.0 → 3.0.2

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.
Files changed (56) hide show
  1. package/README.md +204 -52
  2. package/dist/cli/index.js +1514 -0
  3. package/dist/cli/index.js.map +1 -0
  4. package/dist/core/client/index.js +373 -0
  5. package/dist/core/client/index.js.map +1 -0
  6. package/dist/core/index.js +6415 -0
  7. package/dist/core/index.js.map +1 -0
  8. package/dist/core/server/index.js +3094 -0
  9. package/dist/core/server/index.js.map +1 -0
  10. package/package.json +80 -80
  11. package/bin/flexireact.js +0 -23
  12. package/cli/generators.ts +0 -616
  13. package/cli/index.ts +0 -1182
  14. package/core/actions/index.ts +0 -364
  15. package/core/api.ts +0 -143
  16. package/core/build/index.ts +0 -425
  17. package/core/cli/logger.ts +0 -353
  18. package/core/client/Link.tsx +0 -345
  19. package/core/client/hydration.ts +0 -147
  20. package/core/client/index.ts +0 -12
  21. package/core/client/islands.ts +0 -143
  22. package/core/client/navigation.ts +0 -212
  23. package/core/client/runtime.ts +0 -52
  24. package/core/config.ts +0 -116
  25. package/core/context.ts +0 -83
  26. package/core/dev.ts +0 -47
  27. package/core/devtools/index.ts +0 -644
  28. package/core/edge/cache.ts +0 -344
  29. package/core/edge/fetch-polyfill.ts +0 -247
  30. package/core/edge/handler.ts +0 -248
  31. package/core/edge/index.ts +0 -81
  32. package/core/edge/ppr.ts +0 -264
  33. package/core/edge/runtime.ts +0 -161
  34. package/core/font/index.ts +0 -306
  35. package/core/helpers.ts +0 -494
  36. package/core/image/index.ts +0 -413
  37. package/core/index.ts +0 -218
  38. package/core/islands/index.ts +0 -293
  39. package/core/loader.ts +0 -111
  40. package/core/logger.ts +0 -242
  41. package/core/metadata/index.ts +0 -622
  42. package/core/middleware/index.ts +0 -416
  43. package/core/plugins/index.ts +0 -373
  44. package/core/render/index.ts +0 -1243
  45. package/core/render.ts +0 -136
  46. package/core/router/index.ts +0 -551
  47. package/core/router.ts +0 -141
  48. package/core/rsc/index.ts +0 -199
  49. package/core/server/index.ts +0 -779
  50. package/core/server.ts +0 -203
  51. package/core/ssg/index.ts +0 -346
  52. package/core/start-dev.ts +0 -6
  53. package/core/start-prod.ts +0 -6
  54. package/core/tsconfig.json +0 -30
  55. package/core/types.ts +0 -239
  56. package/core/utils.ts +0 -176
@@ -1,364 +0,0 @@
1
- /**
2
- * FlexiReact Server Actions
3
- *
4
- * Server Actions allow you to define server-side functions that can be called
5
- * directly from client components. They are automatically serialized and executed
6
- * on the server.
7
- *
8
- * Usage:
9
- * ```tsx
10
- * // In a server file (actions.ts)
11
- * 'use server';
12
- *
13
- * export async function createUser(formData: FormData) {
14
- * const name = formData.get('name');
15
- * // Save to database...
16
- * return { success: true, id: 123 };
17
- * }
18
- *
19
- * // In a client component
20
- * 'use client';
21
- * import { createUser } from './actions';
22
- *
23
- * function Form() {
24
- * return (
25
- * <form action={createUser}>
26
- * <input name="name" />
27
- * <button type="submit">Create</button>
28
- * </form>
29
- * );
30
- * }
31
- * ```
32
- */
33
-
34
- import { cookies, headers, redirect, notFound, RedirectError, NotFoundError } from '../helpers.js';
35
-
36
- // Global action registry
37
- declare global {
38
- var __FLEXI_ACTIONS__: Record<string, ServerActionFunction>;
39
- var __FLEXI_ACTION_CONTEXT__: ActionContext | null;
40
- }
41
-
42
- globalThis.__FLEXI_ACTIONS__ = globalThis.__FLEXI_ACTIONS__ || {};
43
- globalThis.__FLEXI_ACTION_CONTEXT__ = null;
44
-
45
- export interface ActionContext {
46
- request: Request;
47
- cookies: typeof cookies;
48
- headers: typeof headers;
49
- redirect: typeof redirect;
50
- notFound: typeof notFound;
51
- }
52
-
53
- export type ServerActionFunction = (...args: any[]) => Promise<any>;
54
-
55
- export interface ActionResult<T = any> {
56
- success: boolean;
57
- data?: T;
58
- error?: string;
59
- redirect?: string;
60
- }
61
-
62
- /**
63
- * Decorator to mark a function as a server action
64
- */
65
- export function serverAction<T extends ServerActionFunction>(
66
- fn: T,
67
- actionId?: string
68
- ): T {
69
- const id = actionId || `action_${fn.name}_${generateActionId()}`;
70
-
71
- // Register the action
72
- globalThis.__FLEXI_ACTIONS__[id] = fn;
73
-
74
- // Create a proxy that will be serialized for the client
75
- const proxy = (async (...args: any[]) => {
76
- // If we're on the server, execute directly
77
- if (typeof window === 'undefined') {
78
- return await executeAction(id, args);
79
- }
80
-
81
- // If we're on the client, make a fetch request
82
- return await callServerAction(id, args);
83
- }) as T;
84
-
85
- // Mark as server action
86
- (proxy as any).$$typeof = Symbol.for('react.server.action');
87
- (proxy as any).$$id = id;
88
- (proxy as any).$$bound = null;
89
-
90
- return proxy;
91
- }
92
-
93
- /**
94
- * Register a server action
95
- */
96
- export function registerAction(id: string, fn: ServerActionFunction): void {
97
- globalThis.__FLEXI_ACTIONS__[id] = fn;
98
- }
99
-
100
- /**
101
- * Get a registered action
102
- */
103
- export function getAction(id: string): ServerActionFunction | undefined {
104
- return globalThis.__FLEXI_ACTIONS__[id];
105
- }
106
-
107
- /**
108
- * Execute a server action on the server
109
- */
110
- export async function executeAction(
111
- actionId: string,
112
- args: any[],
113
- context?: Partial<ActionContext>
114
- ): Promise<ActionResult> {
115
- const action = globalThis.__FLEXI_ACTIONS__[actionId];
116
-
117
- if (!action) {
118
- return {
119
- success: false,
120
- error: `Server action not found: ${actionId}`
121
- };
122
- }
123
-
124
- // Set up action context
125
- const actionContext: ActionContext = {
126
- request: context?.request || new Request('http://localhost'),
127
- cookies,
128
- headers,
129
- redirect,
130
- notFound
131
- };
132
-
133
- globalThis.__FLEXI_ACTION_CONTEXT__ = actionContext;
134
-
135
- try {
136
- const result = await action(...args);
137
-
138
- return {
139
- success: true,
140
- data: result
141
- };
142
- } catch (error: any) {
143
- // Handle redirect
144
- if (error instanceof RedirectError) {
145
- return {
146
- success: true,
147
- redirect: error.url
148
- };
149
- }
150
-
151
- // Handle not found
152
- if (error instanceof NotFoundError) {
153
- return {
154
- success: false,
155
- error: 'Not found'
156
- };
157
- }
158
-
159
- return {
160
- success: false,
161
- error: error.message || 'Action failed'
162
- };
163
- } finally {
164
- globalThis.__FLEXI_ACTION_CONTEXT__ = null;
165
- }
166
- }
167
-
168
- /**
169
- * Call a server action from the client
170
- */
171
- export async function callServerAction(
172
- actionId: string,
173
- args: any[]
174
- ): Promise<ActionResult> {
175
- try {
176
- const response = await fetch('/_flexi/action', {
177
- method: 'POST',
178
- headers: {
179
- 'Content-Type': 'application/json',
180
- 'X-Flexi-Action': actionId
181
- },
182
- body: JSON.stringify({
183
- actionId,
184
- args: serializeArgs(args)
185
- }),
186
- credentials: 'same-origin'
187
- });
188
-
189
- if (!response.ok) {
190
- throw new Error(`Action failed: ${response.statusText}`);
191
- }
192
-
193
- const result = await response.json();
194
-
195
- // Handle redirect
196
- if (result.redirect) {
197
- window.location.href = result.redirect;
198
- return result;
199
- }
200
-
201
- return result;
202
- } catch (error: any) {
203
- return {
204
- success: false,
205
- error: error.message || 'Network error'
206
- };
207
- }
208
- }
209
-
210
- /**
211
- * Serialize action arguments for transmission
212
- */
213
- function serializeArgs(args: any[]): any[] {
214
- return args.map(arg => {
215
- // Handle FormData
216
- if (arg instanceof FormData) {
217
- const obj: Record<string, any> = {};
218
- arg.forEach((value, key) => {
219
- if (obj[key]) {
220
- // Handle multiple values
221
- if (Array.isArray(obj[key])) {
222
- obj[key].push(value);
223
- } else {
224
- obj[key] = [obj[key], value];
225
- }
226
- } else {
227
- obj[key] = value;
228
- }
229
- });
230
- return { $$type: 'FormData', data: obj };
231
- }
232
-
233
- // Handle File
234
- if (typeof File !== 'undefined' && arg instanceof File) {
235
- return { $$type: 'File', name: arg.name, type: arg.type, size: arg.size };
236
- }
237
-
238
- // Handle Date
239
- if (arg instanceof Date) {
240
- return { $$type: 'Date', value: arg.toISOString() };
241
- }
242
-
243
- // Handle regular objects
244
- if (typeof arg === 'object' && arg !== null) {
245
- return JSON.parse(JSON.stringify(arg));
246
- }
247
-
248
- return arg;
249
- });
250
- }
251
-
252
- /**
253
- * Deserialize action arguments on the server
254
- */
255
- export function deserializeArgs(args: any[]): any[] {
256
- return args.map(arg => {
257
- if (arg && typeof arg === 'object') {
258
- // Handle FormData
259
- if (arg.$$type === 'FormData') {
260
- const formData = new FormData();
261
- for (const [key, value] of Object.entries(arg.data)) {
262
- if (Array.isArray(value)) {
263
- value.forEach(v => formData.append(key, v as string));
264
- } else {
265
- formData.append(key, value as string);
266
- }
267
- }
268
- return formData;
269
- }
270
-
271
- // Handle Date
272
- if (arg.$$type === 'Date') {
273
- return new Date(arg.value);
274
- }
275
- }
276
-
277
- return arg;
278
- });
279
- }
280
-
281
- /**
282
- * Generate a unique action ID
283
- */
284
- function generateActionId(): string {
285
- return Math.random().toString(36).substring(2, 10);
286
- }
287
-
288
- /**
289
- * Hook to get the current action context
290
- */
291
- export function useActionContext(): ActionContext | null {
292
- return globalThis.__FLEXI_ACTION_CONTEXT__;
293
- }
294
-
295
- /**
296
- * Create a form action handler
297
- * Wraps a server action for use with HTML forms
298
- */
299
- export function formAction<T>(
300
- action: (formData: FormData) => Promise<T>
301
- ): (formData: FormData) => Promise<ActionResult<T>> {
302
- return async (formData: FormData) => {
303
- try {
304
- const result = await action(formData);
305
- return { success: true, data: result };
306
- } catch (error: any) {
307
- if (error instanceof RedirectError) {
308
- return { success: true, redirect: error.url };
309
- }
310
- return { success: false, error: error.message };
311
- }
312
- };
313
- }
314
-
315
- /**
316
- * useFormState hook for progressive enhancement
317
- * Works with server actions and provides loading/error states
318
- */
319
- export function createFormState<T>(
320
- action: (formData: FormData) => Promise<ActionResult<T>>,
321
- initialState: T | null = null
322
- ) {
323
- return {
324
- action,
325
- initialState,
326
- // This will be enhanced on the client
327
- pending: false,
328
- error: null as string | null,
329
- data: initialState
330
- };
331
- }
332
-
333
- /**
334
- * Bind arguments to a server action
335
- * Creates a new action with pre-filled arguments
336
- */
337
- export function bindArgs<T extends ServerActionFunction>(
338
- action: T,
339
- ...boundArgs: any[]
340
- ): T {
341
- const boundAction = (async (...args: any[]) => {
342
- return await (action as any)(...boundArgs, ...args);
343
- }) as T;
344
-
345
- // Copy action metadata
346
- (boundAction as any).$$typeof = (action as any).$$typeof;
347
- (boundAction as any).$$id = (action as any).$$id;
348
- (boundAction as any).$$bound = boundArgs;
349
-
350
- return boundAction;
351
- }
352
-
353
- export default {
354
- serverAction,
355
- registerAction,
356
- getAction,
357
- executeAction,
358
- callServerAction,
359
- deserializeArgs,
360
- useActionContext,
361
- formAction,
362
- createFormState,
363
- bindArgs
364
- };
package/core/api.ts DELETED
@@ -1,143 +0,0 @@
1
- import { URL } from 'url';
2
-
3
- /**
4
- * Handles API route requests
5
- * @param {Object} req - HTTP request object
6
- * @param {Object} res - HTTP response object
7
- * @param {Object} route - Matched route object
8
- */
9
- export async function handleApiRoute(req, res, route) {
10
- try {
11
- // Import the API handler with cache busting for hot reload
12
- const modulePath = `file://${route.filePath.replace(/\\/g, '/')}?t=${Date.now()}`;
13
- const handler = await import(modulePath);
14
-
15
- // Parse request body for POST/PUT/PATCH
16
- const body = await parseBody(req);
17
-
18
- // Parse query parameters
19
- const url = new URL(req.url, `http://${req.headers.host}`);
20
- const query = Object.fromEntries(url.searchParams);
21
-
22
- // Create enhanced request object
23
- const enhancedReq = {
24
- ...req,
25
- body,
26
- query,
27
- params: route.params,
28
- method: req.method
29
- };
30
-
31
- // Create enhanced response object
32
- const enhancedRes = createEnhancedResponse(res);
33
-
34
- // Check for method-specific handlers
35
- const method = req.method.toLowerCase();
36
-
37
- if (handler[method]) {
38
- // Method-specific handler (get, post, put, delete, etc.)
39
- await handler[method](enhancedReq, enhancedRes);
40
- } else if (handler.default) {
41
- // Default handler
42
- await handler.default(enhancedReq, enhancedRes);
43
- } else {
44
- // No handler found
45
- enhancedRes.status(405).json({ error: 'Method not allowed' });
46
- }
47
- } catch (error) {
48
- console.error('API Error:', error);
49
-
50
- if (!res.headersSent) {
51
- res.writeHead(500, { 'Content-Type': 'application/json' });
52
- res.end(JSON.stringify({
53
- error: 'Internal Server Error',
54
- message: process.env.NODE_ENV === 'development' ? error.message : undefined
55
- }));
56
- }
57
- }
58
- }
59
-
60
- /**
61
- * Parses the request body
62
- */
63
- async function parseBody(req) {
64
- return new Promise((resolve, reject) => {
65
- const contentType = req.headers['content-type'] || '';
66
- let body = '';
67
-
68
- req.on('data', chunk => {
69
- body += chunk.toString();
70
- });
71
-
72
- req.on('end', () => {
73
- try {
74
- if (contentType.includes('application/json') && body) {
75
- resolve(JSON.parse(body));
76
- } else if (contentType.includes('application/x-www-form-urlencoded') && body) {
77
- resolve(Object.fromEntries(new URLSearchParams(body)));
78
- } else {
79
- resolve(body || null);
80
- }
81
- } catch (error) {
82
- resolve(body);
83
- }
84
- });
85
-
86
- req.on('error', reject);
87
- });
88
- }
89
-
90
- /**
91
- * Creates an enhanced response object with helper methods
92
- */
93
- function createEnhancedResponse(res) {
94
- const enhanced = {
95
- _res: res,
96
- _statusCode: 200,
97
- _headers: {},
98
-
99
- status(code) {
100
- this._statusCode = code;
101
- return this;
102
- },
103
-
104
- setHeader(name, value) {
105
- this._headers[name] = value;
106
- return this;
107
- },
108
-
109
- json(data) {
110
- this._headers['Content-Type'] = 'application/json';
111
- this._sendResponse(JSON.stringify(data));
112
- },
113
-
114
- send(data) {
115
- if (typeof data === 'object') {
116
- this.json(data);
117
- } else {
118
- this._headers['Content-Type'] = this._headers['Content-Type'] || 'text/plain';
119
- this._sendResponse(String(data));
120
- }
121
- },
122
-
123
- html(data) {
124
- this._headers['Content-Type'] = 'text/html';
125
- this._sendResponse(data);
126
- },
127
-
128
- redirect(url, statusCode = 302) {
129
- this._statusCode = statusCode;
130
- this._headers['Location'] = url;
131
- this._sendResponse('');
132
- },
133
-
134
- _sendResponse(body) {
135
- if (!this._res.headersSent) {
136
- this._res.writeHead(this._statusCode, this._headers);
137
- this._res.end(body);
138
- }
139
- }
140
- };
141
-
142
- return enhanced;
143
- }