-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite-plugin-app-api.js
More file actions
executable file
·212 lines (148 loc) · 6.06 KB
/
vite-plugin-app-api.js
File metadata and controls
executable file
·212 lines (148 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function appApiPlugin() {
let appRoutes = new Map();
return {
name: 'vite-plugin-app-api',
async configureServer(server) {
await discoverAppApis(appRoutes);
server.middlewares.use(async (req, res, next) => {
if (!req.url?.startsWith('/api/')) {
return next();
}
const urlParts = req.url.split('?')[0].split('/').filter(Boolean);
if (urlParts.length < 2) {
return sendJson(res, 400, { error: 'Invalid API path' });
}
const appId = urlParts[1];
const apiPath = '/' + urlParts.slice(2).join('/');
const method = req.method?.toUpperCase() || 'GET';
const routes = appRoutes.get(appId);
if (!routes) {
return sendJson(res, 404, { error: `App API not found: ${appId}` });
}
const handler = findRouteHandler(routes, method, apiPath);
if (!handler) {
return sendJson(res, 404, {
error: `Route not found: ${method} ${apiPath}`,
availableRoutes: Object.keys(routes)
});
}
try {
let body = {};
if (['POST', 'PUT', 'PATCH'].includes(method)) {
body = await parseBody(req);
}
const url = new URL(req.url, `http://${req.headers.host}`);
const query = Object.fromEntries(url.searchParams);
const params = extractParams(handler.pattern, apiPath);
const request = {
method,
path: apiPath,
params,
query,
body,
headers: req.headers
};
const result = await handler.fn(request);
if (result && !res.headersSent) {
sendJson(res, 200, result);
}
} catch (error) {
console.error(`[API Error] ${appId}${apiPath}:`, error);
sendJson(res, 500, { error: error.message });
}
});
console.log('[AppAPI] API middleware installed');
}
};
}
async function discoverAppApis(appRoutes) {
const appsDir = path.resolve(__dirname, 'src/apps');
if (!fs.existsSync(appsDir)) {
console.warn('[AppAPI] Apps directory not found');
return;
}
const appFolders = fs.readdirSync(appsDir, { withFileTypes: true })
.filter(d => d.isDirectory())
.map(d => d.name);
for (const appFolder of appFolders) {
const apiIndexPath = path.join(appsDir, appFolder, 'api', 'index.js');
if (fs.existsSync(apiIndexPath)) {
try {
const apiModule = await import(`file://${apiIndexPath}`);
if (apiModule.routes) {
const manifestPath = path.join(appsDir, appFolder, 'manifest.js');
let appId = appFolder.toLowerCase();
if (fs.existsSync(manifestPath)) {
const manifestModule = await import(`file://${manifestPath}`);
if (manifestModule.manifest?.id) {
appId = manifestModule.manifest.id;
}
}
appRoutes.set(appId, apiModule.routes);
console.log(`[AppAPI] Loaded: /api/${appId}/* (${Object.keys(apiModule.routes).length} routes)`);
}
} catch (e) {
console.error(`[AppAPI] Failed to load ${appFolder}/api:`, e.message);
}
}
}
console.log(`[AppAPI] Discovered ${appRoutes.size} app APIs`);
}
function findRouteHandler(routes, method, path) {
for (const [pattern, handler] of Object.entries(routes)) {
const [routeMethod, routePath] = pattern.split(' ');
if (routeMethod !== method) continue;
if (matchPath(routePath, path)) {
return {
fn: handler,
pattern: routePath
};
}
}
return null;
}
function matchPath(pattern, path) {
const patternParts = pattern.split('/').filter(Boolean);
const pathParts = path.split('/').filter(Boolean);
if (patternParts.length !== pathParts.length) return false;
for (let i = 0; i < patternParts.length; i++) {
if (patternParts[i].startsWith(':')) continue;
if (patternParts[i] !== pathParts[i]) return false;
}
return true;
}
function extractParams(pattern, path) {
const params = {};
const patternParts = pattern.split('/').filter(Boolean);
const pathParts = path.split('/').filter(Boolean);
for (let i = 0; i < patternParts.length; i++) {
if (patternParts[i].startsWith(':')) {
const paramName = patternParts[i].slice(1);
params[paramName] = decodeURIComponent(pathParts[i]);
}
}
return params;
}
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
resolve(body ? JSON.parse(body) : {});
} catch (e) {
reject(new Error('Invalid JSON body'));
}
});
req.on('error', reject);
});
}
function sendJson(res, status, data) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(data));
}