@kosmojs/dev 0.2.1 → 0.2.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/package.json +32 -17
- package/pkg/chassis.js +322 -415
- package/pkg/chassis.js.map +1 -1
- package/pkg/index.js +7880 -28
- package/pkg/index.js.map +1 -1
package/pkg/chassis.js
CHANGED
|
@@ -1,420 +1,327 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
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
|
-
for (const sourceFolder of projectSettings.sourceFolders) for (const base of folderGenerators(sourceFolder)) {
|
|
72
|
-
if (!base.meta?.name || typeof base.factory !== "function") throw new Error(`${sourceFolder.name}: Unrecognized generator - must be created via defineGenerator()`);
|
|
73
|
-
const factory = base.factory(sourceFolder);
|
|
74
|
-
if (!factory.meta?.name) throw new Error(`${sourceFolder.name}: ${base.meta.name} generator is missing meta property`);
|
|
75
|
-
try {
|
|
76
|
-
await factory.start?.();
|
|
77
|
-
} catch (error) {
|
|
78
|
-
console.error(styleText("red", `${sourceFolder.name}: ${base.meta.name} generator failed to initialize`));
|
|
79
|
-
throw error;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
if (command === "build") {
|
|
83
|
-
for (const sourceFolder of projectSettings.sourceFolders) {
|
|
84
|
-
const { createPath } = pathResolver(sourceFolder);
|
|
85
|
-
const resolvedRoutes = [];
|
|
86
|
-
{
|
|
87
|
-
const { resolvers } = await routesFactory(sourceFolder, cacheFactory);
|
|
88
|
-
const spinner = spinnerFactory(`${sourceFolder.name}: resolving routes`);
|
|
89
|
-
for (const { name, handler } of resolvers.values()) {
|
|
90
|
-
spinner.append(`[ ${resolvedRoutes.length + 1} of ${resolvers.size} ] ${name}`);
|
|
91
|
-
resolvedRoutes.push(await handler());
|
|
92
|
-
}
|
|
93
|
-
spinner.succeed("ready ✨");
|
|
94
|
-
}
|
|
95
|
-
const generators = folderGenerators(sourceFolder);
|
|
96
|
-
for (const generator of generators) await generator.factory(sourceFolder).build?.(resolvedRoutes);
|
|
97
|
-
const plugins = [vitePlugins.tsconfigPaths(sourceFolder), vitePlugins.nodePrefix()];
|
|
98
|
-
await build(mergeConfigs(sourceFolder.config, ...generators.map(({ factory }) => {
|
|
99
|
-
return factory(sourceFolder).config?.({
|
|
100
|
-
kind: "client",
|
|
101
|
-
command
|
|
102
|
-
});
|
|
103
|
-
}), {
|
|
104
|
-
root: createPath.src(),
|
|
105
|
-
cacheDir: cacheDir(sourceFolder, command, "client"),
|
|
106
|
-
plugins,
|
|
107
|
-
build: {
|
|
108
|
-
outDir: createPath.distDir("client"),
|
|
109
|
-
manifest: true,
|
|
110
|
-
emptyOutDir: true
|
|
111
|
-
}
|
|
112
|
-
}));
|
|
113
|
-
const apiGenerator = generators.find((e) => e.meta.slot === "api");
|
|
114
|
-
if (apiGenerator) {
|
|
115
|
-
const dir = createPath.distDir("api");
|
|
116
|
-
await build(mergeConfigs(apiGenerator.options, apiGenerator.factory(sourceFolder).config?.({
|
|
117
|
-
kind: "backend",
|
|
118
|
-
command
|
|
119
|
-
}), {
|
|
120
|
-
base: "./",
|
|
121
|
-
root: createPath.src(),
|
|
122
|
-
appType: "custom",
|
|
123
|
-
plugins,
|
|
124
|
-
resolve: { conditions: ["node"] },
|
|
125
|
-
build: {
|
|
126
|
-
ssr: true,
|
|
127
|
-
target: "esnext",
|
|
128
|
-
sourcemap: true,
|
|
129
|
-
emptyOutDir: true,
|
|
130
|
-
rolldownOptions: {
|
|
131
|
-
input: [createPath.api("app.ts"), createPath.api("server.ts")],
|
|
132
|
-
output: {
|
|
133
|
-
dir,
|
|
134
|
-
format: "esm"
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
},
|
|
138
|
-
cacheDir: cacheDir(sourceFolder, command, "backend")
|
|
139
|
-
}));
|
|
140
|
-
}
|
|
141
|
-
for (const generator of generators) await generator.factory(sourceFolder).postBuild?.(resolvedRoutes);
|
|
142
|
-
}
|
|
143
|
-
return async () => {};
|
|
144
|
-
}
|
|
145
|
-
const requestHandlers = [];
|
|
146
|
-
const teardownHandlers = [];
|
|
147
|
-
const eventMap = {};
|
|
148
|
-
for (const sourceFolder of projectSettings.sourceFolders) eventMap[sourceFolder.name] = await eventFactory(sourceFolder);
|
|
149
|
-
let port = await findFreePort(devPort);
|
|
150
|
-
for (const sourceFolder of projectSettings.sourceFolders) {
|
|
151
|
-
const { createPath } = pathResolver(sourceFolder);
|
|
152
|
-
const requestMatchers = matchersFactory(sourceFolder);
|
|
153
|
-
const generators = folderGenerators(sourceFolder);
|
|
154
|
-
const plugins = [vitePlugins.tsconfigPaths(sourceFolder), vitePlugins.nodePrefix()];
|
|
155
|
-
{
|
|
156
|
-
const viteServer = await createServer(mergeConfigs(sourceFolder.config, ...generators.map(({ factory }) => {
|
|
157
|
-
return factory(sourceFolder).config?.({
|
|
158
|
-
kind: "client",
|
|
159
|
-
command
|
|
160
|
-
});
|
|
161
|
-
}), {
|
|
162
|
-
root: createPath.src(),
|
|
163
|
-
cacheDir: cacheDir(sourceFolder, command, "client"),
|
|
164
|
-
plugins,
|
|
165
|
-
server: {
|
|
166
|
-
port: port++,
|
|
167
|
-
middlewareMode: true,
|
|
168
|
-
hmr: { port: port++ }
|
|
169
|
-
}
|
|
170
|
-
}));
|
|
171
|
-
for (const [evt, handler] of Object.entries(eventMap[sourceFolder.name])) viteServer.watcher.on(evt, handler);
|
|
172
|
-
requestHandlers.push([
|
|
173
|
-
[sourceFolder.config.base],
|
|
174
|
-
() => requestMatchers.base,
|
|
175
|
-
() => viteServer.middlewares
|
|
176
|
-
]);
|
|
177
|
-
teardownHandlers.push(viteServer.close);
|
|
178
|
-
}
|
|
179
|
-
const apiGenerator = generators.find((e) => e.meta.slot === "api");
|
|
180
|
-
if (apiGenerator) {
|
|
181
|
-
const viteServer = await createServer(mergeConfigs(apiGenerator.options, apiGenerator.factory(sourceFolder).config?.({
|
|
182
|
-
kind: "backend",
|
|
183
|
-
command
|
|
184
|
-
}), {
|
|
185
|
-
root: createPath.src(),
|
|
186
|
-
appType: "custom",
|
|
187
|
-
cacheDir: cacheDir(sourceFolder, command, "backend"),
|
|
188
|
-
plugins,
|
|
189
|
-
server: {
|
|
190
|
-
port: port++,
|
|
191
|
-
middlewareMode: true,
|
|
192
|
-
hmr: { port: port++ }
|
|
193
|
-
},
|
|
194
|
-
resolve: { conditions: ["node"] },
|
|
195
|
-
environments: { api: { resolve: { conditions: ["node"] } } }
|
|
196
|
-
}));
|
|
197
|
-
const env = viteServer.environments.api;
|
|
198
|
-
const loadDevSetup = async () => {
|
|
199
|
-
env.runner.clearCache();
|
|
200
|
-
return env.runner.import(join(defaults.apiDir, "dev.ts")).then((e) => e.default);
|
|
201
|
-
};
|
|
202
|
-
let devSetup = await loadDevSetup();
|
|
203
|
-
for (const [evt, handler] of Object.entries(eventMap[sourceFolder.name])) viteServer.watcher.on(evt, async (file) => {
|
|
204
|
-
if (env.moduleGraph.getModulesByFile(file)?.size) {
|
|
205
|
-
await handler(file);
|
|
206
|
-
await devSetup?.teardownHandler?.();
|
|
207
|
-
devSetup = await loadDevSetup();
|
|
208
|
-
}
|
|
209
|
-
});
|
|
210
|
-
requestHandlers.push([
|
|
211
|
-
[sourceFolder.config.base, sourceFolder.config.apiBase],
|
|
212
|
-
() => devSetup.requestMatcher || requestMatchers.api,
|
|
213
|
-
() => devSetup.requestHandler()
|
|
214
|
-
]);
|
|
215
|
-
teardownHandlers.push(viteServer.close);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* Sorting is essential to ensure more specific paths are matched before broader ones.
|
|
220
|
-
*
|
|
221
|
-
* Given source folders:
|
|
222
|
-
* - main app: baseurl=/ apiurl=/api
|
|
223
|
-
* - admin app: baseurl=/admin apiurl=/admin/api
|
|
224
|
-
*
|
|
225
|
-
* Correct sort order:
|
|
226
|
-
* 1. /admin/api — most specific
|
|
227
|
-
* 2. /api
|
|
228
|
-
* 3. /admin
|
|
229
|
-
* 4. /
|
|
230
|
-
* */
|
|
231
|
-
const requestHandlerWeight = ([segments]) => {
|
|
232
|
-
const [base, api] = segments;
|
|
233
|
-
/**
|
|
234
|
-
* set weight to number of non-empty segments:
|
|
235
|
-
* "/" weight is 0
|
|
236
|
-
* "/admin" weight is 1
|
|
237
|
-
* */
|
|
238
|
-
const weight = base.split("/").filter(Boolean).length;
|
|
239
|
-
return api ? weight + 5 : weight;
|
|
240
|
-
};
|
|
241
|
-
const handlers = requestHandlers.sort((a, b) => requestHandlerWeight(b) - requestHandlerWeight(a));
|
|
242
|
-
const httpServer = http.createServer((req, res) => {
|
|
243
|
-
for (const [, matcherFactory, handlerFactory] of handlers) {
|
|
244
|
-
const [matcher, handler] = [matcherFactory(), handlerFactory()];
|
|
245
|
-
if (matcher(req)) {
|
|
246
|
-
handler(req, res);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
res.writeHead(404, { "Content-Type": "text/html" });
|
|
251
|
-
res.end("<h1>404: Not Found</h1>");
|
|
252
|
-
});
|
|
253
|
-
httpServer.on("error", (error) => {
|
|
254
|
-
console.error(styleText("red", `Failed to start dev server on port ${devPort}`));
|
|
255
|
-
console.error(error.message);
|
|
256
|
-
process.exit(1);
|
|
257
|
-
});
|
|
258
|
-
httpServer.listen(devPort);
|
|
259
|
-
teardownHandlers.push(async () => {
|
|
260
|
-
httpServer.close();
|
|
261
|
-
});
|
|
262
|
-
return async () => {
|
|
263
|
-
for (const handler of teardownHandlers) await handler();
|
|
264
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
265
|
-
};
|
|
266
|
-
};
|
|
267
|
-
var cacheDir = ({ root, name }, command, mode) => {
|
|
268
|
-
return resolve(root, `var/.vite/${name}/${command}/${mode}`);
|
|
269
|
-
};
|
|
270
|
-
var folderGenerators = (sourceFolder) => {
|
|
271
|
-
const { generators = [] } = sourceFolder.config;
|
|
272
|
-
const coreGenerators = {};
|
|
273
|
-
const userGenerators = [];
|
|
274
|
-
for (const base of generators) if (base.meta.slot) coreGenerators[base.meta.slot] = base;
|
|
275
|
-
else userGenerators.push(base);
|
|
276
|
-
return [
|
|
277
|
-
coreGenerator(),
|
|
278
|
-
...coreGenerators.api ? [coreGenerators.api] : [],
|
|
279
|
-
...coreGenerators.fetch && coreGenerators.api ? [coreGenerators.fetch] : [],
|
|
280
|
-
...userGenerators,
|
|
281
|
-
...coreGenerators.ssr ? [coreGenerators.ssr] : [],
|
|
282
|
-
...coreGenerators.ssg ? [coreGenerators.ssg] : []
|
|
283
|
-
];
|
|
284
|
-
};
|
|
285
|
-
var eventFactory = async (sourceFolder) => {
|
|
286
|
-
const { resolvers, resolversFactory } = await routesFactory(sourceFolder, cacheFactory);
|
|
287
|
-
const { createPath } = pathResolver(sourceFolder);
|
|
288
|
-
const generators = [];
|
|
289
|
-
for (const base of folderGenerators(sourceFolder)) {
|
|
290
|
-
const factory = base.factory(sourceFolder);
|
|
291
|
-
generators.push({
|
|
292
|
-
name: base.meta.name,
|
|
293
|
-
factory
|
|
294
|
-
});
|
|
295
|
-
}
|
|
296
|
-
const resolvedRoutes = /* @__PURE__ */ new Map();
|
|
297
|
-
const runGenerators = async (event) => {
|
|
298
|
-
/**
|
|
299
|
-
* Watch handlers receive the full list of entries
|
|
300
|
-
* and should process only those whose source file or dependencies were updated.
|
|
301
|
-
* */
|
|
302
|
-
const entries = Array.from(resolvedRoutes.values());
|
|
303
|
-
for (const { name, factory } of generators) try {
|
|
304
|
-
await factory.watch?.(entries, event);
|
|
305
|
-
} catch (error) {
|
|
306
|
-
console.error(styleText("red", `${sourceFolder.name}: ${name} generator failed`));
|
|
307
|
-
if (event) console.error(event);
|
|
308
|
-
console.error(error);
|
|
309
|
-
}
|
|
310
|
-
};
|
|
311
|
-
const updateResolvedEntry = async (file) => {
|
|
312
|
-
const resolver = resolvers.get(file);
|
|
313
|
-
if (!resolver) return;
|
|
314
|
-
try {
|
|
315
|
-
const resolvedEntry = await resolver.handler(file);
|
|
316
|
-
resolvedRoutes.set(resolvedEntry.entry.fileFullpath, resolvedEntry);
|
|
317
|
-
return resolvedEntry;
|
|
318
|
-
} catch (error) {
|
|
319
|
-
const route = file.replace(`${createPath.api()}/`, "");
|
|
320
|
-
console.error(styleText("red", `${sourceFolder.name}: ${route} route resolution failed`));
|
|
321
|
-
console.error(error);
|
|
322
|
-
return;
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
{
|
|
326
|
-
const spinner = spinnerFactory(`${sourceFolder.name}: resolving routes`);
|
|
327
|
-
for (const { name, handler } of resolvers.values()) {
|
|
328
|
-
spinner.append(`[ ${resolvedRoutes.size + 1} of ${resolvers.size} ] ${name}`);
|
|
329
|
-
const route = await handler();
|
|
330
|
-
resolvedRoutes.set(route.entry.fileFullpath, route);
|
|
331
|
-
}
|
|
332
|
-
spinner.succeed("ready ✨");
|
|
333
|
-
}
|
|
334
|
-
await runGenerators();
|
|
335
|
-
return {
|
|
336
|
-
async add(file) {
|
|
337
|
-
const [resolver] = resolversFactory([file]).values();
|
|
338
|
-
if (!resolver) return;
|
|
339
|
-
resolvers.set(file, resolver);
|
|
340
|
-
if (await updateResolvedEntry(file)) await runGenerators({
|
|
341
|
-
kind: "create",
|
|
342
|
-
file
|
|
343
|
-
});
|
|
344
|
-
},
|
|
345
|
-
async change(file) {
|
|
346
|
-
if (resolvedRoutes.has(file)) await updateResolvedEntry(file);
|
|
347
|
-
else {
|
|
348
|
-
const relatedRoutes = resolvedRoutes.values().flatMap(({ kind, entry }) => {
|
|
349
|
-
return kind === "apiRoute" ? entry.referencedFiles.includes(file) ? [entry] : [] : [];
|
|
350
|
-
});
|
|
351
|
-
for (const route of relatedRoutes) await updateResolvedEntry(route.fileFullpath);
|
|
352
|
-
}
|
|
353
|
-
await runGenerators({
|
|
354
|
-
kind: "update",
|
|
355
|
-
file
|
|
356
|
-
});
|
|
357
|
-
},
|
|
358
|
-
async unlink(file) {
|
|
359
|
-
resolvers.delete(file);
|
|
360
|
-
resolvedRoutes.delete(file);
|
|
361
|
-
await runGenerators({
|
|
362
|
-
kind: "delete",
|
|
363
|
-
file
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
};
|
|
367
|
-
};
|
|
368
|
-
var matchersFactory = ({ config }) => {
|
|
369
|
-
const basePattern = new RegExp(`^${config.base}($|/*)`);
|
|
370
|
-
const apiPattern = new RegExp(`^${join(config.base, config.apiBase)}($|/*)`);
|
|
371
|
-
return {
|
|
372
|
-
base(req) {
|
|
373
|
-
return apiPattern.test(req.url) ? false : basePattern.test(req.url);
|
|
374
|
-
},
|
|
375
|
-
api(req) {
|
|
376
|
-
return apiPattern.test(req.url);
|
|
377
|
-
}
|
|
378
|
-
};
|
|
1
|
+
import{createRequire as e}from"node:module";import{dirname as t,join as n,resolve as r}from"node:path";import{styleText as i}from"node:util";import{defaults as a}from"@kosmojs/core";import{defineGenerator as o,defineGeneratorFactory as s,mergeConfigs as c,pathExists as l,pathResolver as u,renderFactory as d,renderToFile as f,routesFactory as p,spinnerFactory as m,vitePlugins as h}from"@kosmojs/lib";import{routeRenderHelpers as g}from"@kosmojs/core/generators";import _ from"crc/crc32";import{build as v,createServer as y}from"vite";import{mkdir as b,readFile as x,writeFile as S}from"node:fs/promises";import C from"node:http";import w from"node:net";import{readFileSync as T}from"node:fs";var E={type:`module`,private:!0,name:`@kosmojs/core-generator`,version:`0.2.5`,author:`Slee Woo`,license:`MIT`,files:[`pkg/*`],exports:{".":{types:`./pkg/index.d.ts`,default:`./pkg/index.js`}},scripts:{build:`wsbuild src/index.ts`},dependencies:{"@kosmojs/core":`workspace:^`,"@kosmojs/lib":`workspace:^`},devDependencies:{"path-to-regexp":`^8.4.2`}},D=`export const base = "{{config.base}}";
|
|
2
|
+
export const apiBase = "{{config.apiBase}}";
|
|
3
|
+
`,O=`export * from "./config";
|
|
4
|
+
export * from "./routeMap";
|
|
5
|
+
`,k=`import { compile } from "path-to-regexp";
|
|
6
|
+
|
|
7
|
+
import type { PathMapperSignature } from "@kosmojs/core";
|
|
8
|
+
import { createHost, join, stringify } from "@kosmojs/core/fetch";
|
|
9
|
+
|
|
10
|
+
export const pathMapper = <ParamsT extends readonly unknown[]>(
|
|
11
|
+
basePath: string,
|
|
12
|
+
routeName: string,
|
|
13
|
+
pathPattern: string,
|
|
14
|
+
paramsMap: Array<[name: string, kind: string]>,
|
|
15
|
+
numericParams: Array<string>,
|
|
16
|
+
): PathMapperSignature<ParamsT> => {
|
|
17
|
+
const toPath = compile(pathPattern);
|
|
18
|
+
|
|
19
|
+
const castParam = (name: string, value: unknown) => {
|
|
20
|
+
if (numericParams.includes(name)) {
|
|
21
|
+
const n = Number(value);
|
|
22
|
+
return Number.isFinite(n) ? n : String(value);
|
|
23
|
+
}
|
|
24
|
+
return String(value);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const paramsMapper: PathMapperSignature<ParamsT>["paramsMapper"] = (
|
|
28
|
+
params,
|
|
29
|
+
) => {
|
|
30
|
+
return paramsMap.reduce<Record<string, unknown>>((map, [name, kind], i) => {
|
|
31
|
+
if (kind === "splat") {
|
|
32
|
+
if (Array.isArray(params[i]) && params[i].length) {
|
|
33
|
+
map[name] = params[i].map((v) => castParam(name, v));
|
|
34
|
+
}
|
|
35
|
+
} else if (params[i] !== undefined) {
|
|
36
|
+
map[name] = castParam(name, params[i]);
|
|
37
|
+
}
|
|
38
|
+
return map;
|
|
39
|
+
}, {});
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const parametrize: PathMapperSignature<ParamsT>["parametrize"] = (params) => {
|
|
43
|
+
try {
|
|
44
|
+
return toPath(paramsMapper(params) as never);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
console.error(\`❗ERROR: Failed building path for \${routeName}\`);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const base: PathMapperSignature<ParamsT>["base"] = (params, query) => {
|
|
52
|
+
const path = join("/", parametrize(params));
|
|
53
|
+
return query ? [path, stringify(query)].join("?") : path;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const path: PathMapperSignature<ParamsT>["path"] = (params, query) => {
|
|
57
|
+
return join(basePath, base(params, query));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const href: PathMapperSignature<ParamsT>["href"] = (host, params, query) => {
|
|
61
|
+
return createHost(host) + path(params, query);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
paramsMapper,
|
|
66
|
+
parametrize,
|
|
67
|
+
base,
|
|
68
|
+
path,
|
|
69
|
+
href,
|
|
70
|
+
};
|
|
379
71
|
};
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
if (!freePort) throw new Error(`No free ports found in range ${minPort}-${maxPort}`);
|
|
404
|
-
return freePort;
|
|
72
|
+
`,A=`{{> pathMapper}}
|
|
73
|
+
|
|
74
|
+
import { base, apiBase } from "./config";
|
|
75
|
+
|
|
76
|
+
{{#if pageRoutes.length}}
|
|
77
|
+
export type LinkProps =
|
|
78
|
+
{{#each pageRoutes}}
|
|
79
|
+
| [ "{{name}}", {{serializeParamsTupleElements .}} ]
|
|
80
|
+
{{/each}};
|
|
81
|
+
{{else}}
|
|
82
|
+
export type LinkProps = never;
|
|
83
|
+
{{/if}}
|
|
84
|
+
|
|
85
|
+
export const apiRouteMap = {
|
|
86
|
+
{{#each apiRoutes}}
|
|
87
|
+
"{{name}}": pathMapper<[{{serializeParamsTupleElements .}}]>(
|
|
88
|
+
apiBase,
|
|
89
|
+
"{{name}}",
|
|
90
|
+
"{{pathPattern}}",
|
|
91
|
+
[{{#each params.schema}}["{{name}}", "{{kind}}"], {{/each}}],
|
|
92
|
+
[{{#each numericParams}}"{{.}}", {{/each}}],
|
|
93
|
+
),
|
|
94
|
+
{{/each}}
|
|
405
95
|
};
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
96
|
+
|
|
97
|
+
export const pageRouteMap = {
|
|
98
|
+
{{#each pageRoutes}}
|
|
99
|
+
"{{name}}": pathMapper<[{{serializeParamsTupleElements .}}]>(
|
|
100
|
+
base,
|
|
101
|
+
"{{name}}",
|
|
102
|
+
"{{pathPattern}}",
|
|
103
|
+
[{{#each params.schema}}["{{name}}", "{{kind}}"], {{/each}}],
|
|
104
|
+
[{{#each numericParams}}"{{.}}", {{/each}}],
|
|
105
|
+
),
|
|
106
|
+
{{/each}}
|
|
416
107
|
};
|
|
417
|
-
|
|
418
|
-
|
|
108
|
+
`,j=`declare const KOSMO_PRODUCTION_BUILD: boolean;
|
|
109
|
+
declare const KOSMO_SERVERSIDE_FETCH: boolean;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Enhances base TypeScript types with JSON Schema validation constraints.
|
|
113
|
+
* Allows declaring refined types that carry validation metadata for runtime
|
|
114
|
+
* schema validation while maintaining full TypeScript type safety.
|
|
115
|
+
*
|
|
116
|
+
* Useful for generating validation schemas and ensuring
|
|
117
|
+
* data conforms to specific business rules beyond basic type checking.
|
|
118
|
+
* */
|
|
119
|
+
declare type VRefine<
|
|
120
|
+
T extends unknown[] | number | string | object,
|
|
121
|
+
_ extends T extends unknown[]
|
|
122
|
+
? TArrayOptions
|
|
123
|
+
: T extends number
|
|
124
|
+
? TNumberOptions
|
|
125
|
+
: T extends string
|
|
126
|
+
? TStringOptions
|
|
127
|
+
: TObjectOptions,
|
|
128
|
+
> = T;
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Type definitions inspired by and gently adapted from TypeBox.
|
|
132
|
+
* Original TypeBox created by sinclairzx81: https://github.com/sinclairzx81/typebox
|
|
133
|
+
* TypeBox is licensed under MIT: https://github.com/sinclairzx81/typebox/blob/main/license
|
|
134
|
+
*
|
|
135
|
+
* These types provide JSON Schema compatible type refinements for TypeScript.
|
|
136
|
+
* */
|
|
137
|
+
interface TSchema {}
|
|
138
|
+
|
|
139
|
+
// ------------------------------------------------------------------
|
|
140
|
+
// ObjectOptions
|
|
141
|
+
// ------------------------------------------------------------------
|
|
142
|
+
interface TObjectOptions {
|
|
143
|
+
/**
|
|
144
|
+
* Defines whether additional properties are allowed beyond those explicitly defined in \`properties\`.
|
|
145
|
+
*/
|
|
146
|
+
additionalProperties?: TSchema | boolean;
|
|
147
|
+
/**
|
|
148
|
+
* The minimum number of properties required in the object.
|
|
149
|
+
*/
|
|
150
|
+
minProperties?: number;
|
|
151
|
+
/**
|
|
152
|
+
* The maximum number of properties allowed in the object.
|
|
153
|
+
*/
|
|
154
|
+
maxProperties?: number;
|
|
155
|
+
/**
|
|
156
|
+
* Defines conditional requirements for properties.
|
|
157
|
+
*/
|
|
158
|
+
dependencies?: Record<string, boolean | TSchema | string[]>;
|
|
159
|
+
/**
|
|
160
|
+
* Specifies properties that *must* be present if a given property is present.
|
|
161
|
+
*/
|
|
162
|
+
dependentRequired?: Record<string, string[]>;
|
|
163
|
+
/**
|
|
164
|
+
* Defines schemas that apply if a specific property is present.
|
|
165
|
+
*/
|
|
166
|
+
dependentSchemas?: Record<string, TSchema>;
|
|
167
|
+
/**
|
|
168
|
+
* Maps regular expressions to schemas properties matching a pattern must validate against the schema.
|
|
169
|
+
*/
|
|
170
|
+
patternProperties?: Record<string, TSchema>;
|
|
171
|
+
/**
|
|
172
|
+
* A schema that all property names within the object must validate against.
|
|
173
|
+
*/
|
|
174
|
+
propertyNames?: TSchema;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ------------------------------------------------------------------
|
|
178
|
+
// ArrayOptions
|
|
179
|
+
// ------------------------------------------------------------------
|
|
180
|
+
interface TArrayOptions {
|
|
181
|
+
/**
|
|
182
|
+
* The minimum number of items allowed in the array.
|
|
183
|
+
*/
|
|
184
|
+
minItems?: number;
|
|
185
|
+
/**
|
|
186
|
+
* The maximum number of items allowed in the array.
|
|
187
|
+
*/
|
|
188
|
+
maxItems?: number;
|
|
189
|
+
/**
|
|
190
|
+
* A schema that at least one item in the array must validate against.
|
|
191
|
+
*/
|
|
192
|
+
contains?: TSchema;
|
|
193
|
+
/**
|
|
194
|
+
* The minimum number of array items that must validate against the \`contains\` schema.
|
|
195
|
+
*/
|
|
196
|
+
minContains?: number;
|
|
197
|
+
/**
|
|
198
|
+
* The maximum number of array items that may validate against the \`contains\` schema.
|
|
199
|
+
*/
|
|
200
|
+
maxContains?: number;
|
|
201
|
+
/**
|
|
202
|
+
* An array of schemas, where each schema in \`prefixItems\` validates against items at corresponding positions from the beginning of the array.
|
|
203
|
+
*/
|
|
204
|
+
prefixItems?: TSchema[];
|
|
205
|
+
/**
|
|
206
|
+
* If \`true\`, all items in the array must be unique.
|
|
207
|
+
*/
|
|
208
|
+
uniqueItems?: boolean;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ------------------------------------------------------------------
|
|
212
|
+
// NumberOptions
|
|
213
|
+
// ------------------------------------------------------------------
|
|
214
|
+
interface TNumberOptions {
|
|
215
|
+
/**
|
|
216
|
+
* Specifies an exclusive upper limit for the number (number must be less than this value).
|
|
217
|
+
*/
|
|
218
|
+
exclusiveMaximum?: number | bigint;
|
|
219
|
+
/**
|
|
220
|
+
* Specifies an exclusive lower limit for the number (number must be greater than this value).
|
|
221
|
+
*/
|
|
222
|
+
exclusiveMinimum?: number | bigint;
|
|
223
|
+
/**
|
|
224
|
+
* Specifies an inclusive upper limit for the number (number must be less than or equal to this value).
|
|
225
|
+
*/
|
|
226
|
+
maximum?: number | bigint;
|
|
227
|
+
/**
|
|
228
|
+
* Specifies an inclusive lower limit for the number (number must be greater than or equal to this value).
|
|
229
|
+
*/
|
|
230
|
+
minimum?: number | bigint;
|
|
231
|
+
/**
|
|
232
|
+
* Specifies that the number must be a multiple of this value.
|
|
233
|
+
*/
|
|
234
|
+
multipleOf?: number | bigint;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// ------------------------------------------------------------------
|
|
238
|
+
// StringOptions
|
|
239
|
+
// ------------------------------------------------------------------
|
|
240
|
+
type TFormat =
|
|
241
|
+
| "date-time"
|
|
242
|
+
| "date"
|
|
243
|
+
| "duration"
|
|
244
|
+
| "email"
|
|
245
|
+
| "hostname"
|
|
246
|
+
| "idn-email"
|
|
247
|
+
| "idn-hostname"
|
|
248
|
+
| "ipv4"
|
|
249
|
+
| "ipv6"
|
|
250
|
+
| "iri-reference"
|
|
251
|
+
| "iri"
|
|
252
|
+
| "json-pointer-uri-fragment"
|
|
253
|
+
| "json-pointer"
|
|
254
|
+
| "json-string"
|
|
255
|
+
| "regex"
|
|
256
|
+
| "relative-json-pointer"
|
|
257
|
+
| "time"
|
|
258
|
+
| "uri-reference"
|
|
259
|
+
| "uri-template"
|
|
260
|
+
| "url"
|
|
261
|
+
| "uuid";
|
|
262
|
+
|
|
263
|
+
interface TStringOptions {
|
|
264
|
+
/**
|
|
265
|
+
* Specifies the expected string format.
|
|
266
|
+
*
|
|
267
|
+
* Common values include:
|
|
268
|
+
* - \`base64\` – Base64-encoded string.
|
|
269
|
+
* - \`date-time\` – [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time format.
|
|
270
|
+
* - \`date\` – [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date (YYYY-MM-DD).
|
|
271
|
+
* - \`duration\` – [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) duration format.
|
|
272
|
+
* - \`email\` – RFC 5321/5322 compliant email address.
|
|
273
|
+
* - \`hostname\` – RFC 1034/1035 compliant host name.
|
|
274
|
+
* - \`idn-email\` – Internationalized email address.
|
|
275
|
+
* - \`idn-hostname\` – Internationalized host name.
|
|
276
|
+
* - \`ipv4\` – IPv4 address.
|
|
277
|
+
* - \`ipv6\` – IPv6 address.
|
|
278
|
+
* - \`iri\` / \`iri-reference\` – Internationalized Resource Identifier.
|
|
279
|
+
* - \`json-pointer\` / \`json-pointer-uri-fragment\` – JSON Pointer format.
|
|
280
|
+
* - \`json-string\` – String containing valid JSON.
|
|
281
|
+
* - \`regex\` – Regular expression syntax.
|
|
282
|
+
* - \`relative-json-pointer\` – Relative JSON Pointer format.
|
|
283
|
+
* - \`time\` – [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) time (HH:MM:SS).
|
|
284
|
+
* - \`uri-reference\` / \`uri-template\` – URI reference or template.
|
|
285
|
+
* - \`url\` – Web URL format.
|
|
286
|
+
* - \`uuid\` – RFC 4122 UUID string.
|
|
287
|
+
*
|
|
288
|
+
* May also be a custom format string.
|
|
289
|
+
*/
|
|
290
|
+
format?: TFormat;
|
|
291
|
+
/**
|
|
292
|
+
* Specifies the minimum number of characters allowed in the string.
|
|
293
|
+
* Must be a non-negative integer.
|
|
294
|
+
*/
|
|
295
|
+
minLength?: number;
|
|
296
|
+
/**
|
|
297
|
+
* Specifies the maximum number of characters allowed in the string.
|
|
298
|
+
* Must be a non-negative integer.
|
|
299
|
+
*/
|
|
300
|
+
maxLength?: number;
|
|
301
|
+
/**
|
|
302
|
+
* Specifies a regular expression pattern that the string value must match.
|
|
303
|
+
* Can be provided as a string (ECMA-262 regex syntax) or a \`RegExp\` object.
|
|
304
|
+
*/
|
|
305
|
+
pattern?: string | RegExp;
|
|
306
|
+
}
|
|
307
|
+
`,M=`# Ignore all files
|
|
308
|
+
*
|
|
309
|
+
|
|
310
|
+
# But don't ignore directories (so Git can traverse them)
|
|
311
|
+
!*/
|
|
419
312
|
|
|
313
|
+
# And don't ignore these files at any depth
|
|
314
|
+
!cache.json
|
|
315
|
+
!types.ts
|
|
316
|
+
`,N=`export declare global {
|
|
317
|
+
interface Window {
|
|
318
|
+
__KOSMO_HYDRATION_BOOL__: boolean;
|
|
319
|
+
__KOSMO_HYDRATION_DATA__: Record<string, unknown> | undefined;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
`,P=`// stub schemas, specialized generators supposed to overwrite this file
|
|
323
|
+
import type { ValidationSchemas } from "@kosmojs/core/api";
|
|
324
|
+
export type { ValidationSchemas };
|
|
325
|
+
export const validationSchemas: ValidationSchemas = {};
|
|
326
|
+
`,F=e=>{let t="${configDir}",n={types:[`@types/node`,`vite/client`],moduleResolution:`bundler`,module:`ESNext`,target:`ESNext`,strict:!0,exactOptionalPropertyTypes:!0,noImplicitAny:!0,noImplicitThis:!0,noImplicitOverride:!0,noImplicitReturns:!0,noUnusedLocals:!1,noUnusedParameters:!1,allowArbitraryExtensions:!0,allowImportingTsExtensions:!0,allowUnreachableCode:!1,allowUnusedLabels:!1,useUnknownInCatchVariables:!0,noFallthroughCasesInSwitch:!0,noUncheckedSideEffectImports:!0,resolveJsonModule:!0,esModuleInterop:!0,verbatimModuleSyntax:!0,skipLibCheck:!0,noEmit:!0};return e?{include:[`${t}/`,`${t}/../../${a.libDir}/${e}/`,`${t}/../../**/*.d.ts`],compilerOptions:{...n,types:[...n.types],paths:{[`${a.appPrefix}/*`]:[`${t}/../../*`],[`${a.srcPrefix}/*`]:[`${t}/*`],[`${a.libPrefix}/*`]:[`${t}/../../${a.libDir}/${e}/*`]},jsx:`preserve`}}:{include:[`${t}/`],exclude:[`${t}/${a.srcDir}/`],compilerOptions:{...n,paths:{[`${a.appPrefix}/*`]:[`${t}/*`]}}}},I=s((e,n)=>{let{createPath:r,createImportHelpers:i}=u(n),a=async()=>{await f(r.lib(`../tsconfig.base.json`),JSON.stringify(F(),void 0,2),{});{let e=F(n.name),t={},i=new Set(e.compilerOptions.types||[]);for(let{meta:e}of n.config.generators||[]){e.jsxImportSource&&(t.jsxImportSource=e.jsxImportSource);for(let t of e.types||[])i.add(t)}await f(r.lib(`tsconfig.base.json`),JSON.stringify({...e,compilerOptions:{...e.compilerOptions,...t,types:[...i.values()]}},void 0,2),{})}for(let[e,t]of[[`env.d.ts`,j],[`global.d.ts`,N]])await f(r.lib(`../${e}`),t,{});await f(r.lib(`../.gitignore`),M,{},{overwrite:!1}),await f(r.lib(`ssg.ts`),`export default [];`,{})},o=async e=>{let{renderToFile:a}=d({helpers:{...i({origin:`lib`}),...g()},partials:{pathMapper:k}});await a(r.libCore(`routeMap.ts`),A,{apiRoutes:e.flatMap(({kind:e,entry:t})=>e===`apiRoute`?[t]:[]),pageRoutes:e.flatMap(({kind:e,entry:t})=>e===`pageRoute`?[t]:[])});for(let[e,t]of[[`config.ts`,D],[`index.ts`,O]])await a(r.libCore(e),t,n);for(let{kind:n,entry:i}of e)n===`apiRoute`&&await a(r.libApi(t(i.file),`schemas.ts`),P,{route:i},{overwrite:!1})};return{meta:e,start:a,watch:o,build:o}}),L=o(()=>{let e={name:`Core`,dependencies:{"path-to-regexp":E.devDependencies[`path-to-regexp`]}};return{meta:e,options:void 0,factory:t=>I(e,t)}}),R=JSON.parse(T(e(import.meta.url).resolve(`@kosmojs/dev/package.json`),`utf-8`)),z=(e,n,i)=>{let a=u(n).createPath.libApi(t(e.file),`cache.json`),o=async t=>{if(!t?.hash||!t.typeDeclarations||!t.referencedFiles)return;let a=await B(e.fileFullpath,{...i});if(V(t.hash,a)){for(let[e,i]of Object.entries(t.referencedFiles))if(!V(i,await B(r(n.root,e))))return;return t}};return{async get(e){if(await l(a))try{let t=JSON.parse(await x(a,`utf8`));return e?.validate?o(t):t}catch{}},async set(r){let o=await B(e.fileFullpath,{...i}),s={};for(let e of r.referencedFiles)s[e.replace(`${n.root}/`,``)]=await B(e);let c={...r,hash:o,referencedFiles:s};return await b(t(a),{recursive:!0}),await S(a,JSON.stringify(c,null,2),`utf8`),c}}},B=async(e,t)=>{let n;try{n=await x(e,`utf8`)}catch{return 0}return n?_(JSON.stringify({...t,[R.cacheVersion]:n})):0},V=(e,t)=>e===t,H=async e=>{let{devPort:t,command:r}=e;for(let t of e.sourceFolders)for(let e of W(t)){if(!e.meta?.name||typeof e.factory!=`function`)throw Error(`${t.name}: Unrecognized generator - must be created via defineGenerator()`);let n=e.factory(t);if(!n.meta?.name)throw Error(`${t.name}: ${e.meta.name} generator is missing meta property`);try{await n.start?.()}catch(n){throw console.error(i(`red`,`${t.name}: ${e.meta.name} generator failed to initialize`)),n}}if(r===`build`){for(let t of e.sourceFolders){let{createPath:e}=u(t),n=[];{let{resolvers:e}=await p(t,z),r=m(`${t.name}: resolving routes`);for(let{name:t,handler:i}of e.values())r.append(`[ ${n.length+1} of ${e.size} ] ${t}`),n.push(await i());r.succeed(`ready ✨`)}let i=W(t);for(let e of i)await e.factory(t).build?.(n);let a=[h.tsconfigPaths(t),h.nodePrefix()];await v(c(t.config,...i.map(({factory:e})=>e(t).config?.({kind:`client`,command:r})),{root:e.src(),cacheDir:U(t,r,`client`),plugins:a,build:{outDir:e.distDir(`client`),manifest:!0,emptyOutDir:!0}}));let o=i.find(e=>e.meta.slot===`api`);if(o){let n=e.distDir(`api`);await v(c(o.options,o.factory(t).config?.({kind:`backend`,command:r}),{base:`./`,root:e.src(),appType:`custom`,plugins:a,resolve:{conditions:[`node`]},build:{ssr:!0,target:`esnext`,sourcemap:!0,emptyOutDir:!0,rolldownOptions:{input:[e.api(`app.ts`),e.api(`server.ts`)],output:{dir:n,format:`esm`}}},cacheDir:U(t,r,`backend`)}))}for(let e of i)await e.factory(t).postBuild?.(n)}return async()=>{}}let o=[],s=[],l={};for(let t of e.sourceFolders)l[t.name]=await G(t);let d=await q(t);for(let t of e.sourceFolders){let{createPath:e}=u(t),i=K(t),f=W(t),p=[h.tsconfigPaths(t),h.nodePrefix()];{let n=await y(c(t.config,...f.map(({factory:e})=>e(t).config?.({kind:`client`,command:r})),{root:e.src(),cacheDir:U(t,r,`client`),plugins:p,server:{port:d++,middlewareMode:!0,hmr:{port:d++}}}));for(let[e,r]of Object.entries(l[t.name]))n.watcher.on(e,r);o.push([[t.config.base],()=>i.base,()=>n.middlewares]),s.push(n.close)}let m=f.find(e=>e.meta.slot===`api`);if(m){let u=await y(c(m.options,m.factory(t).config?.({kind:`backend`,command:r}),{root:e.src(),appType:`custom`,cacheDir:U(t,r,`backend`),plugins:p,server:{port:d++,middlewareMode:!0,hmr:{port:d++}},resolve:{conditions:[`node`]},environments:{api:{resolve:{conditions:[`node`]}}}})),f=u.environments.api,h=async()=>(f.runner.clearCache(),f.runner.import(n(a.apiDir,`dev.ts`)).then(e=>e.default)),g=await h();for(let[e,n]of Object.entries(l[t.name]))u.watcher.on(e,async e=>{f.moduleGraph.getModulesByFile(e)?.size&&(await n(e),await g?.teardownHandler?.(),g=await h())});o.push([[t.config.base,t.config.apiBase],()=>g.requestMatcher||i.api,()=>g.requestHandler()]),s.push(u.close)}}let f=([e])=>{let[t,n]=e,r=t.split(`/`).filter(Boolean).length;return n?r+5:r},g=o.sort((e,t)=>f(t)-f(e)),_=C.createServer((e,t)=>{for(let[,n,r]of g){let[i,a]=[n(),r()];if(i(e)){a(e,t);return}}t.writeHead(404,{"Content-Type":`text/html`}),t.end(`<h1>404: Not Found</h1>`)});return _.on(`error`,e=>{console.error(i(`red`,`Failed to start dev server on port ${t}`)),console.error(e.message),process.exit(1)}),_.listen(t),s.push(async()=>{_.close()}),async()=>{for(let e of s)await e();await new Promise(e=>setTimeout(e,100))}},U=({root:e,name:t},n,i)=>r(e,`var/.vite/${t}/${n}/${i}`),W=e=>{let{generators:t=[]}=e.config,n={},r=[];for(let e of t)e.meta.slot?n[e.meta.slot]=e:r.push(e);return[L(),...n.api?[n.api]:[],...n.fetch&&n.api?[n.fetch]:[],...r,...n.ssr?[n.ssr]:[],...n.ssg?[n.ssg]:[]]},G=async e=>{let{resolvers:t,resolversFactory:n}=await p(e,z),{createPath:r}=u(e),a=[];for(let t of W(e)){let n=t.factory(e);a.push({name:t.meta.name,factory:n})}let o=new Map,s=async t=>{let n=Array.from(o.values());for(let{name:r,factory:o}of a)try{await o.watch?.(n,t)}catch(n){console.error(i(`red`,`${e.name}: ${r} generator failed`)),t&&console.error(t),console.error(n)}},c=async n=>{let a=t.get(n);if(a)try{let e=await a.handler(n);return o.set(e.entry.fileFullpath,e),e}catch(t){let a=n.replace(`${r.api()}/`,``);console.error(i(`red`,`${e.name}: ${a} route resolution failed`)),console.error(t);return}};{let n=m(`${e.name}: resolving routes`);for(let{name:e,handler:r}of t.values()){n.append(`[ ${o.size+1} of ${t.size} ] ${e}`);let i=await r();o.set(i.entry.fileFullpath,i)}n.succeed(`ready ✨`)}return await s(),{async add(e){let[r]=n([e]).values();r&&(t.set(e,r),await c(e)&&await s({kind:`create`,file:e}))},async change(e){if(o.has(e))await c(e);else{let t=o.values().flatMap(({kind:t,entry:n})=>t===`apiRoute`&&n.referencedFiles.includes(e)?[n]:[]);for(let e of t)await c(e.fileFullpath)}await s({kind:`update`,file:e})},async unlink(e){t.delete(e),o.delete(e),await s({kind:`delete`,file:e})}}},K=({config:e})=>{let t=RegExp(`^${e.base}($|/*)`),r=RegExp(`^${n(e.base,e.apiBase)}($|/*)`);return{base(e){return!r.test(e.url)&&t.test(e.url)},api(e){return r.test(e.url)}}},q=async e=>{let t=0,n=0;for(let r of[3,2,1,``])if(t=Number(`${r}${e}`)+100,n=t+100,n<65e3)break;if(n>=65e3)throw Error(`the devPort in package.json should be less than 64000`);let r=n-t+1,i=Math.floor(Math.random()*r),a=await Array.from({length:r},(e,n)=>t+(i+n)%r).reduce(async(e,t)=>await e||(await J(t)?t:void 0),Promise.resolve(void 0));if(!a)throw Error(`No free ports found in range ${t}-${n}`);return a},J=e=>new Promise(t=>{let n=w.createServer();n.once(`error`,()=>t(!1)),n.once(`listening`,()=>{n.close(),t(!0)}),n.listen(e,`127.0.0.1`)});export{H as default};
|
|
420
327
|
//# sourceMappingURL=chassis.js.map
|