@marko/run 0.1.2 → 0.1.4

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.
@@ -1,4 +1,4 @@
1
- declare type ValuesOf<T> = T[keyof T];
1
+ type ValuesOf<T> = T[keyof T];
2
2
  export declare const markoRunFilePrefix = "__marko-run__";
3
3
  export declare const virtualFilePrefix = "virtual:marko-run";
4
4
  export declare const virtualRoutesPrefix: string;
@@ -15,6 +15,6 @@ export declare const RoutableFileTypes: {
15
15
  readonly NotFound: "404";
16
16
  readonly Error: "500";
17
17
  };
18
- export declare type RoutableFileType = ValuesOf<typeof RoutableFileTypes>;
19
- export declare type HttpVerb = typeof httpVerbs[number];
18
+ export type RoutableFileType = ValuesOf<typeof RoutableFileTypes>;
19
+ export type HttpVerb = typeof httpVerbs[number];
20
20
  export {};
@@ -26,7 +26,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
26
26
  // src/vite/index.ts
27
27
  var vite_exports = {};
28
28
  __export(vite_exports, {
29
- default: () => markoServe,
29
+ default: () => markoRun,
30
30
  getAvailablePort: () => getAvailablePort,
31
31
  isPortInUse: () => isPortInUse,
32
32
  loadEnv: () => loadEnv,
@@ -663,7 +663,7 @@ function renderRouter(routes, options = {
663
663
  writer.writeLines(`// @marko/run/router`);
664
664
  const imports = writer.branch("imports");
665
665
  imports.writeLines(
666
- `import { NotHandled, NotMatched, createInput } from 'virtual:marko-run/internal';`
666
+ `import { NotHandled, NotMatched, createContext } from 'virtual:marko-run/internal';`
667
667
  );
668
668
  for (const route of routes.list) {
669
669
  const verbs = getVerbs(route);
@@ -680,7 +680,7 @@ function renderRouter(routes, options = {
680
680
  `import page${key} from '${virtualFilePrefix}/${markoRunFilePrefix}special__${key}.marko${serverEntryQuery}';`
681
681
  );
682
682
  }
683
- writer.writeLines(``).writeBlockStart(`export function match(method, pathname) {`).writeLines(
683
+ writer.writeLines("").writeBlockStart(`export function match(method, pathname) {`).writeLines(
684
684
  `if (!pathname) {
685
685
  pathname = '/';
686
686
  } else if (pathname.charAt(0) !== '/') {
@@ -698,17 +698,10 @@ function renderRouter(routes, options = {
698
698
  }
699
699
  writer.writeBlockEnd("}").writeLines("return null;").writeBlockEnd("}");
700
700
  writer.write(`
701
- export async function invoke(route, request, platform, url = new URL(request.url)) {
702
- const context = {
703
- url,
704
- request,
705
- platform
706
- };
707
- const buildInput = createInput(context);
701
+ export async function invoke(route, request, platform, url) {
702
+ const [context, buildInput] = createContext(route, request, platform, url);
708
703
  try {
709
704
  if (route) {
710
- context.params = route.params;
711
- context.meta = route.meta;
712
705
  try {
713
706
  const response = await route.handler(context, buildInput);
714
707
  if (response) return response;
@@ -719,36 +712,40 @@ export async function invoke(route, request, platform, url = new URL(request.url
719
712
  throw error;
720
713
  }
721
714
  }
722
- `).indent = 2;
715
+ `);
723
716
  if (routes.special[RoutableFileTypes.NotFound]) {
717
+ writer.indent = 2;
718
+ imports.writeLines(
719
+ `
720
+ const page404ResponseInit = {
721
+ status: 404,
722
+ headers: { "content-type": "text/html;charset=UTF-8" },
723
+ };`
724
+ );
724
725
  writer.write(
725
726
  ` } else {
726
- context.params = {};
727
- context.meta = {};
728
727
  }
729
728
  if (context.request.headers.get('Accept')?.includes('text/html')) {
730
- return new Response(page404.stream(buildInput()), {
731
- status: 404,
732
- headers: { "content-type": "text/html;charset=UTF-8" },
733
- });
729
+ return new Response(page404.stream(buildInput()), page404ResponseInit);
734
730
  }
735
731
  `
736
732
  );
737
733
  } else {
734
+ writer.indent = 3;
738
735
  writer.writeBlockEnd("}");
739
736
  }
740
737
  writer.indent--;
741
738
  writer.writeBlockStart(`} catch (error) {`);
742
739
  if (routes.special[RoutableFileTypes.Error]) {
740
+ imports.writeLines(`
741
+ const page500ResponseInit = {
742
+ status: 404,
743
+ headers: { "content-type": "text/html;charset=UTF-8" },
744
+ };`);
743
745
  writer.writeBlockStart(
744
746
  `if (context.request.headers.get('Accept')?.includes('text/html')) {`
745
- ).writeBlock(
746
- `return new Response(page500.stream(buildInput({ error })), {`,
747
- [
748
- `status: 500,`,
749
- `headers: { "content-type": "text/html;charset=UTF-8" },`
750
- ],
751
- `});`
747
+ ).writeLines(
748
+ `return new Response(page500.stream(buildInput({ error })), page500ResponseInit);`
752
749
  ).writeBlockEnd("}");
753
750
  }
754
751
  writer.writeLines(`throw error;`).writeBlockEnd("}").writeBlockEnd("}").write(`
@@ -929,7 +926,7 @@ function renderParamsInfo(params, pathIndex) {
929
926
  for (const { name, index } of params) {
930
927
  if (index >= 0) {
931
928
  result += `${sep} ${wrapPropertyName(name)}: s${index + 1}`;
932
- sep || (sep = ",");
929
+ sep = ",";
933
930
  } else if (pathIndex) {
934
931
  catchAll = name;
935
932
  }
@@ -984,8 +981,8 @@ function stripTsExtension(path3) {
984
981
  }
985
982
  return path3;
986
983
  }
987
- function renderRouteTypeInfo(routes, pathPrefix = ".", adapterTypes = "") {
988
- var _a, _b;
984
+ async function renderRouteTypeInfo(routes, pathPrefix = ".", adapter) {
985
+ var _a, _b, _c, _d;
989
986
  const writer = createStringWriter();
990
987
  writer.writeLines(
991
988
  `/*
@@ -993,28 +990,25 @@ function renderRouteTypeInfo(routes, pathPrefix = ".", adapterTypes = "") {
993
990
  Do NOT manually edit this file or your changes will be lost.
994
991
  */
995
992
  `,
996
- `import type { HandlerLike, Route as AnyRoute, Context as AnyContext, ValidatePath, ValidateHref } from "@marko/run";`,
997
- adapterTypes,
998
- `
999
-
1000
- declare global {
1001
- namespace MarkoRun {`
993
+ `import type { HandlerLike, Route as AnyRoute, Context as AnyContext, ParamsObject, ValidatePath, ValidateHref } from "@marko/run";`
1002
994
  );
1003
- const pathsWriter = writer.branch("paths");
1004
- writer.write(`
1005
- type GetablePath<T extends string> = ValidatePath<GetPaths, T>;
1006
- type GetableHref<T extends string> = ValidateHref<GetPaths, T>;
1007
- type PostablePath<T extends string> = ValidatePath<PostPaths, T>;
1008
- type PostableHref<T extends string> = ValidateHref<PostPaths, T>;
995
+ let platformType = "unknown";
996
+ if (adapter && adapter.typeInfo) {
997
+ platformType = await adapter.typeInfo((data) => writer.write(data));
998
+ writer.writeLines("");
1009
999
  }
1010
- }
1000
+ writer.writeLines(`
1001
+ interface NoParams extends ParamsObject {}
1002
+ interface NoMeta {}
1011
1003
  `);
1004
+ const pathsWriter = writer.branch("paths");
1012
1005
  const routesWriter = writer.branch("types");
1013
1006
  const serverWriter = writer.branch("server");
1014
1007
  const middlewareRouteTypes = /* @__PURE__ */ new Map();
1015
1008
  const layoutRouteTypes = /* @__PURE__ */ new Map();
1016
1009
  const getPaths = /* @__PURE__ */ new Set();
1017
1010
  const postPaths = /* @__PURE__ */ new Set();
1011
+ writeModuleDeclaration(serverWriter, void 0, void 0, platformType);
1018
1012
  for (const route of routes.list) {
1019
1013
  const { meta, handler, params, middleware, page, layouts } = route;
1020
1014
  const routeType = `Route${route.index}`;
@@ -1022,8 +1016,8 @@ declare global {
1022
1016
  /\/\$(\$?)([^\/]*)/,
1023
1017
  (_, catchAll, name) => catchAll ? `/:${name || "rest"}*` : `/:${name}`
1024
1018
  )}\``;
1025
- const paramsType = params ? renderParamsInfoType(params) : "{}";
1026
- let metaType = "undefined";
1019
+ const paramsType = (params == null ? void 0 : params.length) ? renderParamsInfoType(params) : "NoParams";
1020
+ let metaType = "NoMeta";
1027
1021
  if (page || handler) {
1028
1022
  const isGet = page || ((_a = handler == null ? void 0 : handler.verbs) == null ? void 0 : _a.includes("get"));
1029
1023
  const isPost = (_b = handler == null ? void 0 : handler.verbs) == null ? void 0 : _b.includes("post");
@@ -1043,31 +1037,31 @@ declare global {
1043
1037
  }
1044
1038
  }
1045
1039
  if (meta) {
1046
- metaType = `typeof import('${pathPrefix}/${stripTsExtension(
1047
- meta.relativePath
1048
- )}')`;
1040
+ const path3 = stripTsExtension(`${pathPrefix}/${meta.relativePath}`);
1041
+ metaType = `typeof import('${path3}')`;
1049
1042
  if (/\.(ts|js|mjs)$/.test(meta.relativePath)) {
1050
1043
  metaType += `['default']`;
1051
1044
  }
1052
1045
  }
1053
1046
  if (handler) {
1054
- writeRouteTypeModule(
1047
+ writeModuleDeclaration(
1055
1048
  serverWriter,
1056
- pathPrefix,
1057
- handler.relativePath,
1058
- routeType
1049
+ `${pathPrefix}/${handler.relativePath}`,
1050
+ routeType,
1051
+ platformType
1059
1052
  );
1060
1053
  }
1061
1054
  if (page) {
1062
- writer.writeLines(`
1063
- declare module '${pathPrefix}/${page.relativePath}' {
1064
- export interface Input {}
1065
-
1066
- namespace MarkoRun {
1067
- type Route = ${routeType};
1068
- type Context = AnyContext<AnyContext['platform'], Route>;
1069
- }
1070
- }`);
1055
+ writeModuleDeclaration(
1056
+ writer,
1057
+ `${pathPrefix}/${page.relativePath}`,
1058
+ routeType,
1059
+ platformType,
1060
+ `
1061
+ export interface Input {
1062
+ renderBody: Marko.Body;
1063
+ }`
1064
+ );
1071
1065
  }
1072
1066
  if (middleware) {
1073
1067
  let i = 0;
@@ -1097,74 +1091,106 @@ declare module '${pathPrefix}/${page.relativePath}' {
1097
1091
  }
1098
1092
  }
1099
1093
  routesWriter.writeLines(
1100
- `interface ${routeType} extends AnyRoute<${paramsType}, ${metaType}, ${pathType}> {}`
1094
+ `type ${routeType} = AnyRoute<${paramsType}, ${metaType}, ${pathType}>;`
1101
1095
  );
1102
1096
  }
1103
- pathsWriter.write(" type GetPaths =");
1104
- for (const path3 of getPaths) {
1105
- pathsWriter.write(`
1106
- | '${path3}'`);
1097
+ pathsWriter.write(`type Get =`);
1098
+ if (getPaths.size) {
1099
+ for (const path3 of getPaths) {
1100
+ pathsWriter.write(`
1101
+ | '${path3}'`);
1102
+ }
1103
+ } else {
1104
+ pathsWriter.write(" never");
1107
1105
  }
1108
1106
  pathsWriter.writeLines(";", "");
1109
- pathsWriter.write(" type PostPaths =");
1110
- for (const path3 of postPaths) {
1111
- pathsWriter.write(`
1112
- | '${path3}'`);
1107
+ pathsWriter.write("type Post =");
1108
+ if (postPaths.size) {
1109
+ for (const path3 of postPaths) {
1110
+ pathsWriter.write(`
1111
+ | '${path3}'`);
1112
+ }
1113
+ } else {
1114
+ pathsWriter.write(" never");
1113
1115
  }
1114
- pathsWriter.writeLines(";");
1116
+ pathsWriter.writeLines(";", "");
1115
1117
  pathsWriter.join();
1116
1118
  for (const [file, { routeTypes }] of middlewareRouteTypes) {
1117
- writeRouteTypeModule(
1119
+ writeModuleDeclaration(
1118
1120
  serverWriter,
1119
- pathPrefix,
1120
- file.relativePath,
1121
- routeTypes.join(" | ")
1121
+ `${pathPrefix}/${file.relativePath}`,
1122
+ routeTypes.join(" | "),
1123
+ platformType
1122
1124
  );
1123
1125
  }
1124
1126
  for (const [file, { routeTypes }] of layoutRouteTypes) {
1125
- writer.writeLines(`
1126
- declare module '${pathPrefix}/${file.relativePath}' {
1127
+ writeModuleDeclaration(
1128
+ writer,
1129
+ `${pathPrefix}/${file.relativePath}`,
1130
+ routeTypes.join(" | "),
1131
+ platformType,
1132
+ `
1127
1133
  export interface Input {
1128
1134
  renderBody: Marko.Body;
1135
+ }`
1136
+ );
1129
1137
  }
1130
-
1131
- namespace MarkoRun {
1132
- type Route = ${routeTypes.join(" | ")};
1133
- type Context = AnyContext<AnyContext['platform'], Route>;
1134
- }
1135
- }`);
1138
+ if ((_c = routes.special["404"]) == null ? void 0 : _c.page) {
1139
+ writeModuleDeclaration(
1140
+ writer,
1141
+ `${pathPrefix}/${routes.special["404"].page.relativePath}`,
1142
+ void 0,
1143
+ platformType,
1144
+ `
1145
+ export interface Input {}`
1146
+ );
1136
1147
  }
1137
- for (const route of [routes.special["404"], routes.special["500"]]) {
1138
- if (route && route.page) {
1139
- writer.write(`
1140
- declare module '${pathPrefix}/${route.page.relativePath}' {
1141
- export interface Input {`);
1142
- if (route.page.type === RoutableFileTypes.Error) {
1143
- writer.write(`
1148
+ if ((_d = routes.special["500"]) == null ? void 0 : _d.page) {
1149
+ writeModuleDeclaration(
1150
+ writer,
1151
+ `${pathPrefix}/${routes.special["500"].page.relativePath}`,
1152
+ void 0,
1153
+ platformType,
1154
+ `
1155
+ export interface Input {
1144
1156
  error: unknown;
1145
- `);
1146
- }
1147
- writer.writeLines(`}
1148
-
1149
- namespace MarkoRun {
1150
- type Route = AnyRoute;
1151
- type Context = AnyContext<AnyContext['platform'], Route>;
1152
- }
1153
- }`);
1154
- }
1157
+ }`
1158
+ );
1155
1159
  }
1156
1160
  serverWriter.join();
1157
1161
  return writer.end();
1158
1162
  }
1159
- function writeRouteTypeModule(writer, pathPrefix, path3, routeType) {
1160
- writer.writeLines(`
1161
- declare module '${pathPrefix}/${stripTsExtension(path3)}' {
1163
+ function writeModuleDeclaration(writer, path3 = "global", routeType = "AnyRoute", platformType = "unknown", moduleTypes) {
1164
+ writer.writeLines("");
1165
+ if (path3 === "global") {
1166
+ writer.write("declare global {");
1167
+ } else {
1168
+ writer.write(`declare module '${stripTsExtension(path3)}' {`);
1169
+ }
1170
+ if (moduleTypes) {
1171
+ writer.writeLines(moduleTypes);
1172
+ }
1173
+ const isMarko = path3.endsWith(".marko");
1174
+ writer.write(`
1162
1175
  namespace MarkoRun {
1176
+ type GetPaths = Get;
1177
+ type PostPaths = Post;
1178
+ type GetablePath<T extends string> = ValidatePath<Get, T>;
1179
+ type GetableHref<T extends string> = ValidateHref<Get, T>;
1180
+ type PostablePath<T extends string> = ValidatePath<Post, T>;
1181
+ type PostableHref<T extends string> = ValidateHref<Post, T>;
1182
+ type Platform = ${platformType};`);
1183
+ if (path3 !== "global") {
1184
+ writer.write(`
1163
1185
  type Route = ${routeType};
1164
- type Context = AnyContext<AnyContext['platform'], Route>;
1186
+ type Context = AnyContext<Platform, Route>${isMarko ? " & Marko.Global" : ""};
1165
1187
  type Handler<_Params = Route['params'], _Meta = Route['meta']> = HandlerLike<Route>;
1166
1188
  function route(handler: Handler): typeof handler;
1167
1189
  function route<_Params = Route['params'], _Meta = Route['meta']>(handler: Handler): typeof handler;
1190
+ const NotHandled: unique symbol;
1191
+ const NotMatched: unique symbol;`);
1192
+ }
1193
+ writer.writeLines(`
1168
1194
  }
1169
1195
  }`);
1170
1196
  }
@@ -1363,8 +1389,9 @@ var normalizePath = import_path2.default.sep === WINDOWS_SEP ? (id) => id.replac
1363
1389
  function isMarkoFile(id) {
1364
1390
  return id.endsWith(markoExt);
1365
1391
  }
1366
- function markoServe(opts = {}) {
1367
- const { routesDir = "src/routes", adapter, ...markoOptions } = opts;
1392
+ function markoRun(opts = {}) {
1393
+ let { routesDir = "src/routes", adapter, ...markoOptions } = opts;
1394
+ let compiler;
1368
1395
  let store;
1369
1396
  let root;
1370
1397
  let resolvedRoutesDir;
@@ -1395,8 +1422,11 @@ function markoServe(opts = {}) {
1395
1422
  "{.tsconfig*,tsconfig*.json}"
1396
1423
  ))) {
1397
1424
  const filepath = import_path2.default.join(typesDir, "routes.d.ts");
1398
- const adapterTypeInfo = (adapter == null ? void 0 : adapter.writeTypeInfo) && await (adapter == null ? void 0 : adapter.writeTypeInfo());
1399
- const data = renderRouteTypeInfo(routes, import_path2.default.relative(typesDir, routesDir), adapterTypeInfo);
1425
+ const data = await renderRouteTypeInfo(
1426
+ routes,
1427
+ import_path2.default.relative(typesDir, routesDir),
1428
+ adapter
1429
+ );
1400
1430
  if (data !== typesFile || !import_fs2.default.existsSync(filepath)) {
1401
1431
  await ensureDir(typesDir);
1402
1432
  await import_fs2.default.promises.writeFile(filepath, typesFile = data);
@@ -1409,13 +1439,16 @@ function markoServe(opts = {}) {
1409
1439
  route.handler.verbs = await extractVerbs(route.handler.filePath);
1410
1440
  if (!route.handler.verbs.length) {
1411
1441
  console.warn(
1412
- `Did not find any valid exports in middleware entry file:'${route.handler.filePath}' - expected to find any of 'get', 'post', 'put' or 'del'`
1442
+ `Did not find any valid exports in middleware entry file:'${route.handler.filePath}' - expected to find any of 'GET', 'POST', 'PUT' or 'DELETE'`
1413
1443
  );
1414
1444
  }
1415
1445
  }
1416
1446
  if (route.page) {
1417
1447
  virtualFiles.set(
1418
- import_path2.default.posix.join(root, `${markoRunFilePrefix}route__${route.key}.marko`),
1448
+ import_path2.default.posix.join(
1449
+ root,
1450
+ `${markoRunFilePrefix}route__${route.key}.marko`
1451
+ ),
1419
1452
  render ? renderRouteTemplate(route) : ""
1420
1453
  );
1421
1454
  }
@@ -1426,7 +1459,10 @@ function markoServe(opts = {}) {
1426
1459
  }
1427
1460
  for (const route of Object.values(routes.special)) {
1428
1461
  virtualFiles.set(
1429
- import_path2.default.posix.join(root, `${markoRunFilePrefix}special__${route.key}.marko`),
1462
+ import_path2.default.posix.join(
1463
+ root,
1464
+ `${markoRunFilePrefix}special__${route.key}.marko`
1465
+ ),
1430
1466
  render ? renderRouteTemplate(route) : ""
1431
1467
  );
1432
1468
  }
@@ -1466,22 +1502,32 @@ function markoServe(opts = {}) {
1466
1502
  if (externalPluginOptions) {
1467
1503
  opts = (0, import_vite.mergeConfig)(opts, externalPluginOptions);
1468
1504
  }
1505
+ root = normalizePath(config2.root || process.cwd());
1506
+ isBuild = env.command === "build";
1507
+ isSSRBuild = isBuild && Boolean((_a = config2.build) == null ? void 0 : _a.ssr);
1508
+ adapter = await resolveAdapter(root, opts, config2.logLevel !== "silent" && !isBuild || isSSRBuild);
1469
1509
  if (adapter) {
1470
1510
  const externalAdapterConfig = getExternalAdapterOptions(config2);
1471
1511
  if (externalAdapterConfig && adapter.configure) {
1472
1512
  adapter.configure(externalAdapterConfig);
1473
1513
  }
1474
- const adapterOptions = await ((_a = adapter.pluginOptions) == null ? void 0 : _a.call(adapter, opts));
1514
+ const adapterOptions = await ((_b = adapter.pluginOptions) == null ? void 0 : _b.call(adapter, opts));
1475
1515
  if (adapterOptions) {
1476
1516
  opts = (0, import_vite.mergeConfig)(opts, adapterOptions);
1477
1517
  }
1478
1518
  }
1479
- root = normalizePath(config2.root || process.cwd());
1519
+ compiler ?? (compiler = await import(opts.compiler || "@marko/compiler"));
1520
+ compiler.taglib.register("@marko/run", {
1521
+ "<*>": {
1522
+ transform: import_path2.default.resolve(
1523
+ __dirname,
1524
+ "../components/src-attributes-transformer.cjs"
1525
+ )
1526
+ }
1527
+ });
1480
1528
  store = opts.store || new import_vite2.FileStore(
1481
1529
  `marko-serve-vite-${import_crypto.default.createHash("SHA1").update(root).digest("hex")}`
1482
1530
  );
1483
- isBuild = env.command === "build";
1484
- isSSRBuild = isBuild && Boolean((_b = config2.build) == null ? void 0 : _b.ssr);
1485
1531
  resolvedRoutesDir = import_path2.default.resolve(root, routesDir);
1486
1532
  typesDir = import_path2.default.join(root, ".marko-run");
1487
1533
  devEntryFile = import_path2.default.join(root, "index.html");
@@ -1723,6 +1769,31 @@ async function ensureDir(dir) {
1723
1769
  await import_fs2.default.promises.mkdir(dir, { recursive: true });
1724
1770
  }
1725
1771
  }
1772
+ async function resolveAdapter(root, options, log) {
1773
+ const { adapter } = options;
1774
+ if (adapter !== void 0) {
1775
+ return adapter;
1776
+ }
1777
+ const pkg = (0, import_vite.resolvePackageData)(".", root);
1778
+ if (pkg) {
1779
+ const dependecies = { ...pkg.data.dependecies, ...pkg.data.devDependencies };
1780
+ for (const name of Object.keys(dependecies)) {
1781
+ if (name.startsWith("@marko/run-adapter") || name.indexOf("marko-run-adapter") !== -1) {
1782
+ try {
1783
+ const module3 = await import(name);
1784
+ log && console.log(`Using adapter ${name} listed in your package.json dependecies`);
1785
+ return module3.default();
1786
+ } catch (err) {
1787
+ log && console.warn(`Attempt to use package '${name}' failed`, err);
1788
+ }
1789
+ }
1790
+ }
1791
+ }
1792
+ const defaultAdapter = "@marko/run/adapter";
1793
+ const module2 = await import(defaultAdapter);
1794
+ log && console.log("Using default adapter");
1795
+ return module2.default();
1796
+ }
1726
1797
 
1727
1798
  // src/vite/utils/server.ts
1728
1799
  var import_net = __toESM(require("net"), 1);