@markopack/core 0.1.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.
- package/README.md +3 -0
- package/dist/adapter/middleware.d.ts +45 -0
- package/dist/adapter/middleware.d.ts.map +1 -0
- package/dist/adapter/middleware.js +134 -0
- package/dist/adapter/middleware.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/vite/codegen/index.d.ts +7 -0
- package/dist/vite/codegen/index.d.ts.map +1 -0
- package/dist/vite/codegen/index.js +698 -0
- package/dist/vite/codegen/index.js.map +1 -0
- package/dist/vite/codegen/writer.d.ts +21 -0
- package/dist/vite/codegen/writer.d.ts.map +1 -0
- package/dist/vite/codegen/writer.js +136 -0
- package/dist/vite/codegen/writer.js.map +1 -0
- package/dist/vite/constants.d.ts +17 -0
- package/dist/vite/constants.d.ts.map +1 -0
- package/dist/vite/constants.js +22 -0
- package/dist/vite/constants.js.map +1 -0
- package/dist/vite/routes/builder.d.ts +10 -0
- package/dist/vite/routes/builder.d.ts.map +1 -0
- package/dist/vite/routes/builder.js +205 -0
- package/dist/vite/routes/builder.js.map +1 -0
- package/dist/vite/routes/parse.d.ts +14 -0
- package/dist/vite/routes/parse.d.ts.map +1 -0
- package/dist/vite/routes/parse.js +156 -0
- package/dist/vite/routes/parse.js.map +1 -0
- package/dist/vite/routes/vdir.d.ts +19 -0
- package/dist/vite/routes/vdir.d.ts.map +1 -0
- package/dist/vite/routes/vdir.js +137 -0
- package/dist/vite/routes/vdir.js.map +1 -0
- package/dist/vite/routes/walk.d.ts +15 -0
- package/dist/vite/routes/walk.d.ts.map +1 -0
- package/dist/vite/routes/walk.js +71 -0
- package/dist/vite/routes/walk.js.map +1 -0
- package/dist/vite/types.d.ts +128 -0
- package/dist/vite/types.d.ts.map +1 -0
- package/dist/vite/types.js +2 -0
- package/dist/vite/types.js.map +1 -0
- package/dist/vite/utils/fs.d.ts +2 -0
- package/dist/vite/utils/fs.d.ts.map +1 -0
- package/dist/vite/utils/fs.js +7 -0
- package/dist/vite/utils/fs.js.map +1 -0
- package/dist/vite/utils/route.d.ts +6 -0
- package/dist/vite/utils/route.d.ts.map +1 -0
- package/dist/vite/utils/route.js +27 -0
- package/dist/vite/utils/route.js.map +1 -0
- package/dist/vite/utils/server.d.ts +23 -0
- package/dist/vite/utils/server.d.ts.map +1 -0
- package/dist/vite/utils/server.js +177 -0
- package/dist/vite/utils/server.js.map +1 -0
- package/package.json +79 -0
|
@@ -0,0 +1,698 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { httpVerbs, markoRunFilePrefix, RoutableFileTypes, virtualFilePrefix, } from "../constants";
|
|
3
|
+
import { normalizePath } from "../utils/fs";
|
|
4
|
+
import { getRouteVirtualFileName, getVerbs, hasVerb } from "../utils/route";
|
|
5
|
+
import { createStringWriter } from "./writer";
|
|
6
|
+
function normalizedRelativePath(from, to) {
|
|
7
|
+
const relativePath = normalizePath(path.relative(from, to));
|
|
8
|
+
return relativePath.startsWith(".") ? relativePath : "./" + relativePath;
|
|
9
|
+
}
|
|
10
|
+
export function renderRouteTemplate(route, markoApi) {
|
|
11
|
+
if (!route.page) {
|
|
12
|
+
throw new Error(`Route ${route.key} has no page to render`);
|
|
13
|
+
}
|
|
14
|
+
if (!route.templateFilePath) {
|
|
15
|
+
throw new Error(`Route ${route.key} has no template file path`);
|
|
16
|
+
}
|
|
17
|
+
const writer = createStringWriter();
|
|
18
|
+
if (markoApi) {
|
|
19
|
+
writer.writeLines(`<!-- use ${markoApi} -->\n`);
|
|
20
|
+
}
|
|
21
|
+
writer.branch("imports");
|
|
22
|
+
writer.writeLines("");
|
|
23
|
+
writeEntryTemplateTag(writer, [...route.layouts, route.page].map((file) => normalizedRelativePath(path.dirname(route.templateFilePath), file.filePath)), route.key === RoutableFileTypes.Error ? ["error"] : []);
|
|
24
|
+
return writer.end();
|
|
25
|
+
}
|
|
26
|
+
function writeEntryTemplateTag(writer, [file, ...rest], pageInputs, index = 1) {
|
|
27
|
+
if (file) {
|
|
28
|
+
const isLast = !rest.length;
|
|
29
|
+
const tag = isLast ? "Page" : `Layout${index}`;
|
|
30
|
+
writer.branch("imports").writeLines(`import ${tag} from "${file}";`);
|
|
31
|
+
if (isLast) {
|
|
32
|
+
const attributes = pageInputs.length
|
|
33
|
+
? " " + pageInputs.map((name) => `${name}=input.${name}`).join(" ")
|
|
34
|
+
: "";
|
|
35
|
+
writer.writeLines(`<${tag}${attributes}/>`);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
writer.writeBlockStart(`<${tag}>`);
|
|
39
|
+
writeEntryTemplateTag(writer, rest, pageInputs, index + 1);
|
|
40
|
+
writer.writeBlockEnd(`</>`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function renderRouteEntry(route, rootDir) {
|
|
45
|
+
const { key, index, handler, page, middleware, meta } = route;
|
|
46
|
+
const verbs = getVerbs(route);
|
|
47
|
+
if (!verbs) {
|
|
48
|
+
throw new Error(`Route ${key} doesn't have a handler or page for any HTTP verbs`);
|
|
49
|
+
}
|
|
50
|
+
const writer = createStringWriter();
|
|
51
|
+
const imports = writer.branch("imports");
|
|
52
|
+
const runtimeImports = [];
|
|
53
|
+
if (handler) {
|
|
54
|
+
runtimeImports.push("normalizeHandler");
|
|
55
|
+
}
|
|
56
|
+
if (meta) {
|
|
57
|
+
runtimeImports.push("normalizeMeta");
|
|
58
|
+
}
|
|
59
|
+
if (handler || middleware.length) {
|
|
60
|
+
runtimeImports.push("call");
|
|
61
|
+
}
|
|
62
|
+
if (!page || verbs.some((verb) => verb !== "get" && verb !== "head")) {
|
|
63
|
+
runtimeImports.push("noContent");
|
|
64
|
+
}
|
|
65
|
+
if (verbs.includes("head")) {
|
|
66
|
+
runtimeImports.push("stripResponseBody");
|
|
67
|
+
}
|
|
68
|
+
if (runtimeImports.length) {
|
|
69
|
+
imports.writeLines(`import { ${runtimeImports.join(", ")} } from "${virtualFilePrefix}/runtime/internal";`);
|
|
70
|
+
}
|
|
71
|
+
if (middleware.length) {
|
|
72
|
+
const names = middleware.map((m) => `mware${m.id}`);
|
|
73
|
+
imports.writeLines(`import { ${names.join(", ")} } from "${virtualFilePrefix}/${markoRunFilePrefix}middleware.js";`);
|
|
74
|
+
}
|
|
75
|
+
if (handler?.verbs?.length) {
|
|
76
|
+
writer.writeLines("");
|
|
77
|
+
const names = [];
|
|
78
|
+
for (const verb of handler.verbs) {
|
|
79
|
+
const importName = verb.toUpperCase();
|
|
80
|
+
names.push(importName);
|
|
81
|
+
writer.writeLines(`const ${verb}Handler = normalizeHandler(${importName});`);
|
|
82
|
+
}
|
|
83
|
+
imports.writeLines(`import { ${names.join(", ")} } from "${normalizedRelativePath(rootDir, handler.filePath)}";`);
|
|
84
|
+
}
|
|
85
|
+
if (page) {
|
|
86
|
+
imports.writeLines(`import page from "${normalizedRelativePath(rootDir, route.templateFilePath || page.filePath)}";`);
|
|
87
|
+
}
|
|
88
|
+
if (meta) {
|
|
89
|
+
const metaName = `meta${index}`;
|
|
90
|
+
const metaVerbsExports = verbs
|
|
91
|
+
.map((verb) => {
|
|
92
|
+
const name = verb === "head" && !handler?.verbs?.includes(verb)
|
|
93
|
+
? "GET"
|
|
94
|
+
: verb.toUpperCase();
|
|
95
|
+
return `${name}: ${verb}${index}_meta`;
|
|
96
|
+
})
|
|
97
|
+
.join(", ");
|
|
98
|
+
writer.writeLines("");
|
|
99
|
+
imports.writeLines(`import ${metaName} from "${normalizedRelativePath(rootDir, meta.filePath)}";`);
|
|
100
|
+
writer.writeLines(`export const { ${metaVerbsExports} } = normalizeMeta(${metaName});`);
|
|
101
|
+
}
|
|
102
|
+
for (const verb of verbs) {
|
|
103
|
+
writeRouteEntryHandler(writer, route, verb);
|
|
104
|
+
}
|
|
105
|
+
return writer.end();
|
|
106
|
+
}
|
|
107
|
+
function writeRouteEntryHandler(writer, route, verb) {
|
|
108
|
+
const { key, index, page, handler, middleware } = route;
|
|
109
|
+
const len = middleware.length;
|
|
110
|
+
let nextName;
|
|
111
|
+
let currentName;
|
|
112
|
+
let hasBody = false;
|
|
113
|
+
writer.writeLines("");
|
|
114
|
+
if (page && (verb === "get" || verb === "head")) {
|
|
115
|
+
writer.writeBlockStart(`export function ${verb}${index}(context) {`);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
writer.writeBlockStart(`export function ${verb}${index}(context) {`);
|
|
119
|
+
}
|
|
120
|
+
const continuations = writer.branch("cont");
|
|
121
|
+
if (page && (verb === "get" || verb === "head")) {
|
|
122
|
+
currentName = "__page";
|
|
123
|
+
if (handler?.verbs?.includes(verb)) {
|
|
124
|
+
const name = `${verb}Handler`;
|
|
125
|
+
continuations.writeLines(`const ${currentName} = () => context.render(page, {});`);
|
|
126
|
+
if (len) {
|
|
127
|
+
nextName = currentName;
|
|
128
|
+
currentName = `__${name}`;
|
|
129
|
+
continuations.writeLines(`const ${currentName} = () => call(${name}, ${nextName}, context);`);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
if (verb === "head") {
|
|
133
|
+
writer.writeLines(`return stripResponseBody(call(${name}, ${currentName}, context));`);
|
|
134
|
+
}
|
|
135
|
+
else {
|
|
136
|
+
writer.writeLines(`return call(${name}, ${currentName}, context);`);
|
|
137
|
+
}
|
|
138
|
+
hasBody = true;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
else if (verb === "head") {
|
|
142
|
+
writer.writeLines(`return stripResponseBody(get${index}(context));`);
|
|
143
|
+
hasBody = true;
|
|
144
|
+
}
|
|
145
|
+
else if (len) {
|
|
146
|
+
continuations.writeLines(`const ${currentName} = () => context.render(page, {});`);
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
writer.writeLines(`return context.render(page, {});`);
|
|
150
|
+
hasBody = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
else if (handler?.verbs?.includes(verb)) {
|
|
154
|
+
const name = `${verb}Handler`;
|
|
155
|
+
currentName = `__${name}`;
|
|
156
|
+
nextName = "noContent";
|
|
157
|
+
if (len) {
|
|
158
|
+
continuations.writeLines(`const ${currentName} = () => call(${name}, ${nextName}, context);`);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
if (verb === "head") {
|
|
162
|
+
writer.writeLines(`return stripResponseBody(call(${name}, ${nextName}, context));`);
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
writer.writeLines(`return call(${name}, ${nextName}, context);`);
|
|
166
|
+
}
|
|
167
|
+
hasBody = true;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else if (verb === "head" && route.handler?.verbs?.includes("get")) {
|
|
171
|
+
writer.writeLines(`return stripResponseBody(get${index}(context));`);
|
|
172
|
+
hasBody = true;
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
throw new Error(`Route ${key} has no handler for ${verb} requests`);
|
|
176
|
+
}
|
|
177
|
+
if (!hasBody) {
|
|
178
|
+
let i = len;
|
|
179
|
+
while (i--) {
|
|
180
|
+
const { id } = middleware[i];
|
|
181
|
+
const name = `mware${id}`;
|
|
182
|
+
nextName = currentName;
|
|
183
|
+
currentName = i ? `__${name}` : "";
|
|
184
|
+
if (currentName) {
|
|
185
|
+
continuations.writeLines(`const ${currentName} = () => call(${name}, ${nextName}, context);`);
|
|
186
|
+
}
|
|
187
|
+
else if (verb === "head") {
|
|
188
|
+
continuations.writeLines(`return stripResponseBody(call(${name}, ${nextName}, context));`);
|
|
189
|
+
}
|
|
190
|
+
else {
|
|
191
|
+
continuations.writeLines(`return call(${name}, ${nextName}, context);`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
continuations.join();
|
|
196
|
+
writer.writeBlockEnd("}");
|
|
197
|
+
}
|
|
198
|
+
export function renderRouter(routes, rootDir, runtimeInclude, options = {
|
|
199
|
+
trailingSlashes: "RedirectWithout",
|
|
200
|
+
}) {
|
|
201
|
+
const writer = createStringWriter();
|
|
202
|
+
const hasErrorPage = Boolean(routes.special[RoutableFileTypes.Error]);
|
|
203
|
+
const hasNotFoundPage = Boolean(routes.special[RoutableFileTypes.NotFound]);
|
|
204
|
+
const imports = writer.branch("imports");
|
|
205
|
+
if (runtimeInclude) {
|
|
206
|
+
imports.writeLines(`import "${normalizePath(runtimeInclude)}";`);
|
|
207
|
+
}
|
|
208
|
+
imports.writeLines(`import { NotHandled, NotMatched, createContext } from "${virtualFilePrefix}/runtime/internal";`);
|
|
209
|
+
for (const route of routes.list) {
|
|
210
|
+
const verbs = getVerbs(route);
|
|
211
|
+
const routeImports = [];
|
|
212
|
+
for (const verb of verbs) {
|
|
213
|
+
const verbName = `${verb}${route.index}`;
|
|
214
|
+
routeImports.push(verbName);
|
|
215
|
+
if (route.meta) {
|
|
216
|
+
routeImports.push(`${verbName}_meta`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
imports.writeLines(`import { ${routeImports.join(", ")} } from "${virtualFilePrefix}/${getRouteVirtualFileName(route)}";`);
|
|
220
|
+
}
|
|
221
|
+
for (const route of Object.values(routes.special)) {
|
|
222
|
+
imports.writeLines(`import page${route.key} from "${normalizedRelativePath(rootDir, route.templateFilePath || route.page.filePath)}";`);
|
|
223
|
+
}
|
|
224
|
+
writer
|
|
225
|
+
.writeLines(`
|
|
226
|
+
globalThis.__marko_run__ = { match, fetch, invoke };
|
|
227
|
+
`)
|
|
228
|
+
.writeBlockStart(`export function match(method, pathname) {`)
|
|
229
|
+
.writeLines(`const last = pathname.length - 1;
|
|
230
|
+
return match_internal(method, last && pathname.charAt(last) === '/' ? pathname.slice(0, last) : pathname)
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
function match_internal(method, pathname) {
|
|
234
|
+
const len = pathname.length;`)
|
|
235
|
+
.writeBlockStart(`switch (method) {`);
|
|
236
|
+
for (const verb of httpVerbs) {
|
|
237
|
+
const filteredRoutes = routes.list.filter((route) => hasVerb(route, verb));
|
|
238
|
+
if (filteredRoutes.length) {
|
|
239
|
+
const trie = createRouteTrie(filteredRoutes);
|
|
240
|
+
writer.writeLines(`case '${verb.toUpperCase()}':`);
|
|
241
|
+
writer.writeBlockStart(`case '${verb.toLowerCase()}': {`);
|
|
242
|
+
writeRouterVerb(writer, trie, verb);
|
|
243
|
+
writer.writeBlockEnd("}");
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
writer.writeBlockEnd("}").writeLines("return null;").writeBlockEnd("}");
|
|
247
|
+
writer
|
|
248
|
+
.writeLines("")
|
|
249
|
+
.writeBlockStart("export async function invoke(route, request, platform, url) {")
|
|
250
|
+
.writeLines("const context = createContext(route, request, platform, url);");
|
|
251
|
+
if (hasErrorPage) {
|
|
252
|
+
writer.writeBlockStart("try {");
|
|
253
|
+
}
|
|
254
|
+
writer
|
|
255
|
+
.writeBlockStart("if (route) {")
|
|
256
|
+
.writeBlockStart("try {")
|
|
257
|
+
.writeLines("const response = await route.handler(context);", "if (response) return response;").indent--;
|
|
258
|
+
writer
|
|
259
|
+
.writeBlockStart("} catch (error) {")
|
|
260
|
+
.writeLines("if (error === NotHandled) return;", "if (error !== NotMatched) throw error;")
|
|
261
|
+
.writeBlockEnd("}")
|
|
262
|
+
.writeBlockEnd("}");
|
|
263
|
+
if (hasNotFoundPage) {
|
|
264
|
+
imports.writeLines(`
|
|
265
|
+
const page404ResponseInit = {
|
|
266
|
+
status: 404,
|
|
267
|
+
headers: { "content-type": "text/html;charset=UTF-8" },
|
|
268
|
+
};`);
|
|
269
|
+
writer.write(`
|
|
270
|
+
if (context.request.headers.get('Accept')?.includes('text/html')) {
|
|
271
|
+
return context.render(page404, {}, page404ResponseInit);
|
|
272
|
+
}`);
|
|
273
|
+
}
|
|
274
|
+
writer.indent--;
|
|
275
|
+
if (routes.list.length) {
|
|
276
|
+
writer.writeLines(`
|
|
277
|
+
return new Response(null, {
|
|
278
|
+
status: 404,
|
|
279
|
+
});`);
|
|
280
|
+
}
|
|
281
|
+
if (hasErrorPage) {
|
|
282
|
+
imports.writeLines(`
|
|
283
|
+
const page500ResponseInit = {
|
|
284
|
+
status: 500,
|
|
285
|
+
headers: { "content-type": "text/html;charset=UTF-8" },
|
|
286
|
+
};`);
|
|
287
|
+
writer
|
|
288
|
+
.writeBlockStart(`} catch (error) {`)
|
|
289
|
+
.writeBlockStart(`if (context.request.headers.get('Accept')?.includes('text/html')) {`)
|
|
290
|
+
.writeLines(`return context.render(page500, { error }, page500ResponseInit);`)
|
|
291
|
+
.writeBlockEnd("}")
|
|
292
|
+
.writeLines("throw error;")
|
|
293
|
+
.writeBlockEnd("}");
|
|
294
|
+
}
|
|
295
|
+
writer.writeBlockEnd("}");
|
|
296
|
+
renderFetch(writer, options);
|
|
297
|
+
return writer.end();
|
|
298
|
+
}
|
|
299
|
+
function renderFetch(writer, options) {
|
|
300
|
+
writer.write(`
|
|
301
|
+
export async function fetch(request, platform) {
|
|
302
|
+
try {
|
|
303
|
+
const url = new URL(request.url);
|
|
304
|
+
const { pathname } = url;
|
|
305
|
+
const last = pathname.length - 1;
|
|
306
|
+
const hasTrailingSlash = last && pathname.charAt(last) === '/';
|
|
307
|
+
const normalizedPathname = hasTrailingSlash ? pathname.slice(0, last) : pathname;
|
|
308
|
+
const route = match_internal(request.method, normalizedPathname);`);
|
|
309
|
+
switch (options.trailingSlashes) {
|
|
310
|
+
case "RedirectWithout":
|
|
311
|
+
writer.write(`
|
|
312
|
+
if (route && hasTrailingSlash) {
|
|
313
|
+
url.pathname = normalizedPathname
|
|
314
|
+
return Response.redirect(url);
|
|
315
|
+
}`);
|
|
316
|
+
break;
|
|
317
|
+
case "RedirectWith":
|
|
318
|
+
writer.write(`
|
|
319
|
+
if (route && pathname !== '/' && !hasTrailingSlash) {
|
|
320
|
+
url.pathname += '/';
|
|
321
|
+
return Response.redirect(url);
|
|
322
|
+
}`);
|
|
323
|
+
break;
|
|
324
|
+
case "RewriteWithout":
|
|
325
|
+
writer.write(`
|
|
326
|
+
if (route && hasTrailingSlash) {
|
|
327
|
+
url.pathname = normalizedPathname;
|
|
328
|
+
}`);
|
|
329
|
+
break;
|
|
330
|
+
case "RewriteWith":
|
|
331
|
+
writer.write(`
|
|
332
|
+
if (route && pathname !== '/' && !hasTrailingSlash) {
|
|
333
|
+
url.pathname += '/';
|
|
334
|
+
}`);
|
|
335
|
+
break;
|
|
336
|
+
}
|
|
337
|
+
writer.write(`
|
|
338
|
+
return await invoke(route, request, platform, url);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (import.meta.env.DEV) {
|
|
341
|
+
throw error;
|
|
342
|
+
}
|
|
343
|
+
return new Response(null, {
|
|
344
|
+
status: 500
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}`);
|
|
348
|
+
}
|
|
349
|
+
function writeRouterVerb(writer, trie, verb, level = 0, offset = 1) {
|
|
350
|
+
const { route, dynamic, catchAll } = trie;
|
|
351
|
+
let closeCount = 0;
|
|
352
|
+
if (level === 0) {
|
|
353
|
+
if (route) {
|
|
354
|
+
writer.writeLines(`if (len === 1) return ${renderMatch(verb, route, trie.path)};`);
|
|
355
|
+
}
|
|
356
|
+
else if (trie.static || dynamic) {
|
|
357
|
+
writer.writeBlockStart(`if (len > 1) {`);
|
|
358
|
+
closeCount++;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
if (trie.static || dynamic) {
|
|
362
|
+
const next = level + 1;
|
|
363
|
+
const index = `i${next}`;
|
|
364
|
+
let terminal;
|
|
365
|
+
let children;
|
|
366
|
+
writer.writeLines(`const ${index} = pathname.indexOf('/', ${offset}) + 1;`);
|
|
367
|
+
if (trie.static) {
|
|
368
|
+
for (const child of trie.static.values()) {
|
|
369
|
+
if (child.route) {
|
|
370
|
+
(terminal ??= []).push(child);
|
|
371
|
+
}
|
|
372
|
+
if (child.static || child.dynamic || child.catchAll) {
|
|
373
|
+
(children ??= []).push(child);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (terminal || dynamic?.route) {
|
|
378
|
+
closeCount++;
|
|
379
|
+
writer.writeBlockStart(`if (!${index} || ${index} === len) {`);
|
|
380
|
+
let value = `pathname.slice(${offset}, ${index} ? -1 : len)`;
|
|
381
|
+
if (dynamic?.route) {
|
|
382
|
+
const segment = `s${next}`;
|
|
383
|
+
writer.writeLines(`const ${segment} = decodeURIComponent(${value});`);
|
|
384
|
+
value = segment;
|
|
385
|
+
}
|
|
386
|
+
else if (terminal?.some((terminal) => decodeURIComponent(terminal.key) !== terminal.key)) {
|
|
387
|
+
value = `decodeURIComponent(${value})`;
|
|
388
|
+
}
|
|
389
|
+
if (terminal) {
|
|
390
|
+
const useSwitch = terminal.length > 1;
|
|
391
|
+
if (useSwitch) {
|
|
392
|
+
writer.writeBlockStart(`switch (${value}) {`);
|
|
393
|
+
}
|
|
394
|
+
for (const { key, path, route } of terminal) {
|
|
395
|
+
const decodedKey = decodeURIComponent(key);
|
|
396
|
+
if (useSwitch) {
|
|
397
|
+
writer.write(`case '${decodedKey}': `, true);
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
writer.write(`if (${value} === '${decodedKey}') `, true);
|
|
401
|
+
}
|
|
402
|
+
writer.write(`return ${renderMatch(verb, route, path)};\n`);
|
|
403
|
+
}
|
|
404
|
+
if (useSwitch) {
|
|
405
|
+
writer.writeBlockEnd("}");
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
if (dynamic?.route) {
|
|
409
|
+
writer.writeLines(`if (${value}) return ${renderMatch(verb, dynamic.route, dynamic.path)};`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (children || dynamic?.static || dynamic?.dynamic || dynamic?.catchAll) {
|
|
413
|
+
if (terminal || dynamic?.route) {
|
|
414
|
+
writer.writeBlockEnd("} else {").indent++;
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
writer.writeBlockStart(`if (${index} && ${index} !== len) {`);
|
|
418
|
+
closeCount++;
|
|
419
|
+
}
|
|
420
|
+
let value = `pathname.slice(${offset}, ${index} - 1)`;
|
|
421
|
+
if (dynamic?.static || dynamic?.dynamic || dynamic?.catchAll) {
|
|
422
|
+
const segment = `s${next}`;
|
|
423
|
+
writer.writeLines(`const ${segment} = decodeURIComponent(${value});`);
|
|
424
|
+
value = segment;
|
|
425
|
+
}
|
|
426
|
+
else if (children?.some((child) => decodeURIComponent(child.key) !== child.key)) {
|
|
427
|
+
value = `decodeURIComponent(${value})`;
|
|
428
|
+
}
|
|
429
|
+
if (children) {
|
|
430
|
+
const useSwitch = children.length > 1;
|
|
431
|
+
if (useSwitch) {
|
|
432
|
+
writer.writeBlockStart(`switch (${value}) {`);
|
|
433
|
+
}
|
|
434
|
+
for (const child of children) {
|
|
435
|
+
const decodedKey = decodeURIComponent(child.key);
|
|
436
|
+
if (useSwitch) {
|
|
437
|
+
writer.writeBlockStart(`case '${decodedKey}': {`);
|
|
438
|
+
}
|
|
439
|
+
else {
|
|
440
|
+
writer.writeBlockStart(`if (${value} === '${decodedKey}') {`);
|
|
441
|
+
}
|
|
442
|
+
const nextOffset = typeof offset === "string" ? index : offset + child.key.length + 1;
|
|
443
|
+
writeRouterVerb(writer, child, verb, next, nextOffset);
|
|
444
|
+
if (useSwitch) {
|
|
445
|
+
writer.writeBlockEnd("} break;");
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
writer.writeBlockEnd("}");
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (useSwitch) {
|
|
452
|
+
writer.writeBlockEnd("}");
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (dynamic?.static || dynamic?.dynamic || dynamic?.catchAll) {
|
|
456
|
+
writer.writeBlockStart(`if (${value}) {`);
|
|
457
|
+
writeRouterVerb(writer, dynamic, verb, next, index);
|
|
458
|
+
writer.writeBlockEnd(`}`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
while (closeCount--) {
|
|
463
|
+
writer.writeBlockEnd("}");
|
|
464
|
+
}
|
|
465
|
+
if (catchAll) {
|
|
466
|
+
writer.writeLines(`return ${renderMatch(verb, catchAll.route, catchAll.path, String(offset))};`);
|
|
467
|
+
}
|
|
468
|
+
else if (level === 0) {
|
|
469
|
+
writer.writeLines("return null;");
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function wrapPropertyName(name) {
|
|
473
|
+
name = decodeURIComponent(name);
|
|
474
|
+
return /^[^A-Za-z_$]|[^A-Za-z0-9$_]/.test(name) ? `'${name}'` : name;
|
|
475
|
+
}
|
|
476
|
+
function renderParams(params, pathIndex) {
|
|
477
|
+
let result = "";
|
|
478
|
+
let catchAll = "";
|
|
479
|
+
let sep = "{";
|
|
480
|
+
for (const [name, index] of Object.entries(params)) {
|
|
481
|
+
if (typeof index === "number") {
|
|
482
|
+
result += `${sep} ${wrapPropertyName(name)}: s${index + 1}`;
|
|
483
|
+
sep = ",";
|
|
484
|
+
}
|
|
485
|
+
else if (pathIndex) {
|
|
486
|
+
catchAll = name;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (catchAll) {
|
|
490
|
+
result += `${sep} ${wrapPropertyName(catchAll)}: pathname.slice(${pathIndex})`;
|
|
491
|
+
}
|
|
492
|
+
return result ? result + " }" : "{}";
|
|
493
|
+
}
|
|
494
|
+
function renderMatch(verb, route, path, pathIndex) {
|
|
495
|
+
const handler = `${verb}${route.index}`;
|
|
496
|
+
const params = path.params ? renderParams(path.params, pathIndex) : "{}";
|
|
497
|
+
const meta = route.meta ? `${verb}${route.index}_meta` : "{}";
|
|
498
|
+
return `{ handler: ${handler}, params: ${params}, meta: ${meta}, path: '${path.path}' }`;
|
|
499
|
+
}
|
|
500
|
+
export function renderMiddleware(middleware, rootDir) {
|
|
501
|
+
const writer = createStringWriter();
|
|
502
|
+
const imports = writer.branch("imports");
|
|
503
|
+
imports.writeLines(`import { normalizeHandler } from "${virtualFilePrefix}/runtime/internal";`);
|
|
504
|
+
writer.writeLines("");
|
|
505
|
+
for (const { id, filePath } of middleware) {
|
|
506
|
+
const importName = `middleware${id}`;
|
|
507
|
+
imports.writeLines(`import ${importName} from "${normalizedRelativePath(rootDir, filePath)}";`);
|
|
508
|
+
writer.writeLines(`export const mware${id} = normalizeHandler(${importName});`);
|
|
509
|
+
}
|
|
510
|
+
imports.join();
|
|
511
|
+
return writer.end();
|
|
512
|
+
}
|
|
513
|
+
function stripTsExtension(path) {
|
|
514
|
+
const index = path.lastIndexOf(".");
|
|
515
|
+
if (index !== -1) {
|
|
516
|
+
const ext = path.slice(index + 1);
|
|
517
|
+
if (ext.toLowerCase() === "ts") {
|
|
518
|
+
return path.slice(0, index);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return path;
|
|
522
|
+
}
|
|
523
|
+
export async function renderRouteTypeInfo(routes, outDir, adapter) {
|
|
524
|
+
const writer = createStringWriter();
|
|
525
|
+
writer.writeLines(`/*
|
|
526
|
+
WARNING: This file is automatically generated and any changes made to it will be overwritten without warning.
|
|
527
|
+
Do NOT manually edit this file or your changes will be lost.
|
|
528
|
+
*/
|
|
529
|
+
`, `import { NotHandled, NotMatched, GetPaths, PostPaths, GetablePath, GetableHref, PostablePath, PostableHref, Platform } from "@marko/run/namespace";`, `import type * as Run from "@marko/run";`);
|
|
530
|
+
const headWriter = writer.branch("head");
|
|
531
|
+
writer.writeLines("\n").writeBlockStart(`declare module "@marko/run" {`);
|
|
532
|
+
if (adapter && adapter.typeInfo) {
|
|
533
|
+
const platformType = await adapter.typeInfo((data) => headWriter.write(data));
|
|
534
|
+
if (platformType) {
|
|
535
|
+
writer.writeLines(`interface Platform extends ${platformType} {}\n`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
headWriter.join();
|
|
539
|
+
writer
|
|
540
|
+
.writeBlockStart(`interface AppData extends Run.DefineApp<{`)
|
|
541
|
+
.writeBlockStart("routes: {");
|
|
542
|
+
const routesWriter = writer.branch("routes");
|
|
543
|
+
writer.writeBlockEnd("}").writeBlockEnd(`}> {}`).writeBlockEnd(`}`);
|
|
544
|
+
const routeTypes = new Map();
|
|
545
|
+
for (const route of routes.list) {
|
|
546
|
+
let routeType = "";
|
|
547
|
+
let routeDefinition = "";
|
|
548
|
+
if (route.page || route.handler) {
|
|
549
|
+
const verbs = [];
|
|
550
|
+
if (route.page || route.handler?.verbs?.includes("get")) {
|
|
551
|
+
verbs.push(`"get"`);
|
|
552
|
+
}
|
|
553
|
+
if (route.handler?.verbs?.includes("post")) {
|
|
554
|
+
verbs.push(`"post"`);
|
|
555
|
+
}
|
|
556
|
+
routeDefinition = `{ verb: ${verbs.join(" | ")};`;
|
|
557
|
+
if (route.meta) {
|
|
558
|
+
const metaPath = stripTsExtension(normalizedRelativePath(outDir, route.meta.filePath));
|
|
559
|
+
let metaType = `typeof import("${metaPath}")`;
|
|
560
|
+
if (/\.(ts|js|mjs)$/.test(route.meta.name)) {
|
|
561
|
+
metaType += `["default"]`;
|
|
562
|
+
}
|
|
563
|
+
routeDefinition += ` meta: ${metaType};`;
|
|
564
|
+
}
|
|
565
|
+
routeDefinition += " }";
|
|
566
|
+
}
|
|
567
|
+
const pathType = `"${route.path.path}"`;
|
|
568
|
+
routeType += routeType ? " | " + pathType : pathType;
|
|
569
|
+
routesWriter.writeLines(`${pathType}: ${routeDefinition};`);
|
|
570
|
+
for (const file of [route.handler, route.page]) {
|
|
571
|
+
if (file) {
|
|
572
|
+
const existing = routeTypes.get(file);
|
|
573
|
+
if (!existing) {
|
|
574
|
+
routeTypes.set(file, [routeType]);
|
|
575
|
+
}
|
|
576
|
+
else {
|
|
577
|
+
existing.push(routeType);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
for (const files of [route.middleware, route.layouts]) {
|
|
582
|
+
if (files) {
|
|
583
|
+
for (const file of files) {
|
|
584
|
+
const existing = routeTypes.get(file);
|
|
585
|
+
if (!existing) {
|
|
586
|
+
routeTypes.set(file, [routeType]);
|
|
587
|
+
}
|
|
588
|
+
else {
|
|
589
|
+
existing.push(routeType);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
for (const special of Object.values(routes.special)) {
|
|
596
|
+
routeTypes.set(special.page, []);
|
|
597
|
+
}
|
|
598
|
+
routesWriter.join();
|
|
599
|
+
const handlerWriter = writer.branch("handler");
|
|
600
|
+
const middlewareWriter = writer.branch("middleware");
|
|
601
|
+
const pageWriter = writer.branch("page");
|
|
602
|
+
const layoutWriter = writer.branch("layout");
|
|
603
|
+
for (const [file, types] of routeTypes) {
|
|
604
|
+
const modulePath = stripTsExtension(normalizedRelativePath(outDir, file.filePath));
|
|
605
|
+
const routeType = `Run.Routes[${types.join(" | ")}]`;
|
|
606
|
+
switch (file.type) {
|
|
607
|
+
case RoutableFileTypes.Handler:
|
|
608
|
+
writeModuleDeclaration(handlerWriter, modulePath, routeType);
|
|
609
|
+
break;
|
|
610
|
+
case RoutableFileTypes.Middleware:
|
|
611
|
+
writeModuleDeclaration(middlewareWriter, modulePath, routeType);
|
|
612
|
+
break;
|
|
613
|
+
case RoutableFileTypes.Page:
|
|
614
|
+
writeModuleDeclaration(pageWriter, modulePath, routeType);
|
|
615
|
+
break;
|
|
616
|
+
case RoutableFileTypes.Layout:
|
|
617
|
+
writeModuleDeclaration(layoutWriter, modulePath, routeType, `
|
|
618
|
+
export interface Input extends Run.LayoutInput<typeof import("${modulePath}")> {}`);
|
|
619
|
+
break;
|
|
620
|
+
case RoutableFileTypes.Error:
|
|
621
|
+
writeModuleDeclaration(writer, modulePath, "globalThis.MarkoRun.Route", `
|
|
622
|
+
export interface Input {
|
|
623
|
+
error: unknown;
|
|
624
|
+
}`);
|
|
625
|
+
break;
|
|
626
|
+
case RoutableFileTypes.NotFound:
|
|
627
|
+
writeModuleDeclaration(writer, modulePath, "Run.Route");
|
|
628
|
+
break;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
handlerWriter.join();
|
|
632
|
+
middlewareWriter.join();
|
|
633
|
+
pageWriter.join();
|
|
634
|
+
layoutWriter.join();
|
|
635
|
+
return writer.end();
|
|
636
|
+
}
|
|
637
|
+
function writeModuleDeclaration(writer, name, routeType, moduleTypes) {
|
|
638
|
+
writer.writeLines("").write(`declare module "${name}" {`);
|
|
639
|
+
if (moduleTypes) {
|
|
640
|
+
writer.write(moduleTypes);
|
|
641
|
+
}
|
|
642
|
+
if (routeType) {
|
|
643
|
+
const isMarko = name.endsWith(".marko");
|
|
644
|
+
writer.write(`
|
|
645
|
+
namespace MarkoRun {
|
|
646
|
+
export { NotHandled, NotMatched, GetPaths, PostPaths, GetablePath, GetableHref, PostablePath, PostableHref, Platform };
|
|
647
|
+
export type Route = ${routeType};
|
|
648
|
+
export type Context = Run.MultiRouteContext<Route>${isMarko ? " & Marko.Global" : ""};
|
|
649
|
+
export type Handler = Run.HandlerLike<Route>;`);
|
|
650
|
+
for (const verb of httpVerbs) {
|
|
651
|
+
writer.write(`
|
|
652
|
+
export type ${verb.toUpperCase()} = Run.HandlerLike<Route, "${verb.toUpperCase()}">;`);
|
|
653
|
+
}
|
|
654
|
+
writer.write(`
|
|
655
|
+
/** @deprecated use \`((context, next) => { ... }) satisfies MarkoRun.Handler\` instead */
|
|
656
|
+
export const route: Run.HandlerTypeFn<Route>;
|
|
657
|
+
}`);
|
|
658
|
+
}
|
|
659
|
+
writer.writeLines(`
|
|
660
|
+
}`);
|
|
661
|
+
}
|
|
662
|
+
function createRouteTrie(routes) {
|
|
663
|
+
const root = {
|
|
664
|
+
key: "",
|
|
665
|
+
};
|
|
666
|
+
function insert(path, route) {
|
|
667
|
+
let node = root;
|
|
668
|
+
for (const segment of path.segments) {
|
|
669
|
+
if (segment === "$$") {
|
|
670
|
+
node.catchAll ??= { route, path };
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
else if (segment === "$") {
|
|
674
|
+
node = node.dynamic ??= {
|
|
675
|
+
key: "",
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
node.static ??= new Map();
|
|
680
|
+
let next = node.static.get(segment);
|
|
681
|
+
if (!next) {
|
|
682
|
+
next = {
|
|
683
|
+
key: segment,
|
|
684
|
+
};
|
|
685
|
+
node.static.set(segment, next);
|
|
686
|
+
}
|
|
687
|
+
node = next;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
node.path ??= path;
|
|
691
|
+
node.route ??= route;
|
|
692
|
+
}
|
|
693
|
+
for (const route of routes) {
|
|
694
|
+
insert(route.path, route);
|
|
695
|
+
}
|
|
696
|
+
return root;
|
|
697
|
+
}
|
|
698
|
+
//# sourceMappingURL=index.js.map
|