@torpor/build 0.4.10 → 0.4.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/{_page-DBSsnHFG.mjs → _page-BQs4WvCO.mjs} +2 -2
  2. package/dist/_page-BQs4WvCO.mjs.map +1 -0
  3. package/dist/nav.mjs +2 -2
  4. package/dist/nav.mjs.map +1 -1
  5. package/dist/state.mjs +1 -1
  6. package/dist/test.mjs +1 -1
  7. package/package.json +4 -4
  8. package/src/bin/index.ts +11 -0
  9. package/src/index.ts +30 -0
  10. package/src/nav/formSubmit.ts +56 -0
  11. package/src/nav/load.ts +9 -0
  12. package/src/nav/loadData.ts +134 -0
  13. package/src/nav/navigate.ts +164 -0
  14. package/src/nav/reload.ts +9 -0
  15. package/src/nav.ts +4 -0
  16. package/src/response/badRequest.ts +19 -0
  17. package/src/response/created.ts +20 -0
  18. package/src/response/forbidden.ts +21 -0
  19. package/src/response/found.ts +30 -0
  20. package/src/response/methodNotAllowed.ts +18 -0
  21. package/src/response/movedPermanently.ts +25 -0
  22. package/src/response/notFound.ts +24 -0
  23. package/src/response/notModified.ts +34 -0
  24. package/src/response/ok.ts +29 -0
  25. package/src/response/permanentRedirect.ts +30 -0
  26. package/src/response/response.ts +22 -0
  27. package/src/response/seeOther.ts +19 -0
  28. package/src/response/serverError.ts +24 -0
  29. package/src/response/temporaryRedirect.ts +31 -0
  30. package/src/response/transfer.ts +14 -0
  31. package/src/response/unauthorized.ts +21 -0
  32. package/src/response/unprocessable.ts +18 -0
  33. package/src/response.ts +37 -0
  34. package/src/run/prepareTemplate.ts +39 -0
  35. package/src/run/run.ts +62 -0
  36. package/src/run/runBuild.ts +77 -0
  37. package/src/run/runDev.ts +89 -0
  38. package/src/run/runPreview.ts +93 -0
  39. package/src/run.ts +6 -0
  40. package/src/server/CookieHelper.ts +36 -0
  41. package/src/server/HeaderHelper.ts +25 -0
  42. package/src/server/Routerx.ts +72 -0
  43. package/src/server/Server.ts +144 -0
  44. package/src/server/ServerEvent.ts +39 -0
  45. package/src/server/connect/bufferToArrayBuffer.ts +8 -0
  46. package/src/server/connect/connectMiddleware.ts +81 -0
  47. package/src/server/connect/flattenHeaders.ts +44 -0
  48. package/src/server/connect/nodeMessageToNodeResponse.ts +89 -0
  49. package/src/server/connect/readableToBuffer.ts +16 -0
  50. package/src/server/connect/requestToNodeMessage.ts +26 -0
  51. package/src/server/contentType.ts +85 -0
  52. package/src/server/types/HttpMethod.ts +12 -0
  53. package/src/server/types/MiddlewareFunction.ts +8 -0
  54. package/src/server/types/ServerFunction.ts +7 -0
  55. package/src/server.ts +7 -0
  56. package/src/site/Router.ts +164 -0
  57. package/src/site/Site.ts +214 -0
  58. package/src/site/clientEntry.ts +108 -0
  59. package/src/site/clientEntryDev.ts +3 -0
  60. package/src/site/defaultAdapter.ts +11 -0
  61. package/src/site/manifest.ts +54 -0
  62. package/src/site/serverEntry.ts +417 -0
  63. package/src/state/$page.ts +24 -0
  64. package/src/state/client.ts +15 -0
  65. package/src/state.ts +3 -0
  66. package/src/test/runTest.ts +350 -0
  67. package/src/test.ts +3 -0
  68. package/src/types/Adapter.ts +8 -0
  69. package/src/types/ClientState.ts +8 -0
  70. package/src/types/InternalState.ts +7 -0
  71. package/src/types/LayoutHandler.ts +5 -0
  72. package/src/types/LayoutPath.ts +10 -0
  73. package/src/types/ManifestRoute.ts +6 -0
  74. package/src/types/PageEndPoint.ts +39 -0
  75. package/src/types/PageLoadEvent.ts +14 -0
  76. package/src/types/PageServerAction.ts +7 -0
  77. package/src/types/PageServerEndPoint.ts +16 -0
  78. package/src/types/PageServerLoad.ts +7 -0
  79. package/src/types/PageState.ts +8 -0
  80. package/src/types/Route.ts +11 -0
  81. package/src/types/RouteHandler.ts +16 -0
  82. package/src/types/RouteLayoutHandler.ts +5 -0
  83. package/src/types/RouteMatchResult.ts +7 -0
  84. package/src/types/RouteType.ts +19 -0
  85. package/src/types/ServerEndPoint.ts +37 -0
  86. package/src/types/ServerHook.ts +11 -0
  87. package/src/types/ServerLoadEvent.ts +37 -0
  88. package/src/types/ServerRequest.ts +7 -0
  89. package/src/utils/pathToRegex.ts +15 -0
  90. package/src/vite-env.d.ts +2 -0
  91. package/dist/_page-DBSsnHFG.mjs.map +0 -1
@@ -0,0 +1,30 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 302 Found
5
+ *
6
+ * The HTTP 302 Found redirection response status code indicates that the
7
+ * requested resource has been temporarily moved to the URL in the Location
8
+ * header.
9
+ *
10
+ * A browser receiving this status will automatically request the resource at
11
+ * the URL in the Location header, redirecting the user to the new page. Search
12
+ * engines receiving this response will not attribute links to the original URL
13
+ * to the new resource, meaning no SEO value is transferred to the new URL.
14
+ *
15
+ * > Note: In the Fetch Standard, when a user agent receives a 302 in response
16
+ * > to a POST request, it uses the GET method in the subsequent redirection
17
+ * > request, as permitted by the HTTP specification. To avoid user agents
18
+ * > modifying the request, use 307 Temporary Redirect instead, as altering the
19
+ * > method after a 307 response is prohibited.
20
+ *
21
+ * > In cases where you want any request method to be changed to GET, use 303
22
+ * > See Other. This is useful when you want to give a response to a PUT method
23
+ * > that is not the uploaded resource but a confirmation message such as: "you
24
+ * > successfully uploaded XYZ".
25
+ *
26
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302
27
+ */
28
+ export default function permRedirect(location: string): Response {
29
+ return transfer(308, location);
30
+ }
@@ -0,0 +1,18 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 405 Method Not Allowed
5
+ *
6
+ * The HTTP 405 Method Not Allowed client error response status code indicates
7
+ * that the server knows the request method, but the target resource doesn't
8
+ * support this method. The server must generate an Allow header in a 405
9
+ * response with a list of methods that the target resource currently supports.
10
+ *
11
+ * Improper server-side permissions set on files or directories may cause a 405
12
+ * response when the request would otherwise be expected to succeed.
13
+ *
14
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/405
15
+ */
16
+ export default function methodNotAllowed(body?: object | string): Response {
17
+ return response(405, body ?? "Method not allowed");
18
+ }
@@ -0,0 +1,25 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 301 Moved Permanently
5
+ *
6
+ * The HTTP 301 Moved Permanently redirection response status code indicates
7
+ * that the requested resource has been permanently moved to the URL in the
8
+ * Location header.
9
+ *
10
+ * A browser receiving this status will automatically request the resource at
11
+ * the URL in the Location header, redirecting the user to the new page. Search
12
+ * engines receiving this response will attribute links to the original URL to
13
+ * the redirected resource, passing the SEO ranking to the new URL.
14
+ *
15
+ * > Note: In the Fetch Standard, when a user agent receives a 301 in response
16
+ * > to a POST request, it uses the GET method in the subsequent redirection
17
+ * > request, as permitted by the HTTP specification. To avoid user agents
18
+ * > modifying the request, use 308 Permanent Redirect instead, as altering the
19
+ * > method after a 308 response is prohibited.
20
+ *
21
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301
22
+ */
23
+ export default function permRedirect(location: string): Response {
24
+ return transfer(308, location);
25
+ }
@@ -0,0 +1,24 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 404 Not Found
5
+ *
6
+ * The HTTP 404 Not Found client error response status code indicates that the
7
+ * server cannot find the requested resource. Links that lead to a 404 page are
8
+ * often called broken or dead links and can be subject to link rot.
9
+ *
10
+ * A 404 status code only indicates that the resource is missing without
11
+ * indicating if this is temporary or permanent. If a resource is permanently
12
+ * removed, servers should send the 410 Gone status instead.
13
+ *
14
+ * 404 errors on a website can lead to a poor user experience for your visitors,
15
+ * so the number of broken links (internal and external) should be minimized to
16
+ * prevent frustration for readers. Common causes of 404 responses are mistyped
17
+ * URLs or pages that are moved or deleted without redirection. For more
18
+ * information, see the Redirections in HTTP guide.
19
+ *
20
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/404
21
+ */
22
+ export default function notFound(body?: object | string): Response {
23
+ return response(404, body ?? "Not found");
24
+ }
@@ -0,0 +1,34 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 304 Not Modified
5
+ *
6
+ * The HTTP 304 Not Modified redirection response status code indicates that
7
+ * there is no need to retransmit the requested resources.
8
+ *
9
+ * This response code is sent when the request is a conditional GET or HEAD
10
+ * request with an If-None-Match or an If-Modified-Since header and the
11
+ * condition evaluates to 'false'. It confirms that the resource cached by the
12
+ * client is still valid and that the server would have sent a 200 OK response
13
+ * with the resource if the condition evaluated to 'true'. See HTTP caching for
14
+ * more information.
15
+ *
16
+ * The response must not contain a body and must include the headers that would
17
+ * have been sent in an equivalent 200 response, such as:
18
+ *
19
+ * - Cache-Control
20
+ * - Content-Location
21
+ * - Date
22
+ * - ETag
23
+ * - Expires
24
+ * - Vary
25
+ *
26
+ * > Note: Many developer tools' network panels of browsers create extraneous
27
+ * > requests leading to 304 responses, so that access to the local cache is
28
+ * > visible to developers.
29
+ *
30
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/304
31
+ */
32
+ export default function notModified(location: string): Response {
33
+ return transfer(304, location);
34
+ }
@@ -0,0 +1,29 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 200 OK
5
+ *
6
+ * The HTTP 200 OK successful response status code indicates that a request has
7
+ * succeeded. A 200 OK response is cacheable by default.
8
+ *
9
+ * A 200 OK response has a different meaning and format depending on the HTTP
10
+ * request method. Here's how they vary for different methods:
11
+ *
12
+ * - GET: A resource was retrieved by the server and included in the response
13
+ * body.
14
+ * - POST: An action succeeded; the response has a message body describing the
15
+ * result.
16
+ * - HEAD: Identical to GET, except there is no message body.
17
+ * - TRACE: The response has a message body containing the request as received
18
+ * by the server.
19
+ *
20
+ * Although possible, successful PUT or DELETE requests often do not result in a
21
+ * 200 OK response. It is more common to see 201 Created if the resource is
22
+ * uploaded or created for the first time, or 204 No Content upon successful
23
+ * deletion of a resource.
24
+ *
25
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/200
26
+ */
27
+ export default function ok(body?: object | string): Response {
28
+ return response(200, body);
29
+ }
@@ -0,0 +1,30 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 308 Permanent Redirect
5
+ *
6
+ * The HTTP 308 Permanent Redirect redirection response status code indicates
7
+ * that the requested resource has been permanently moved to the URL given by
8
+ * the Location header.
9
+ *
10
+ * A browser receiving this status will automatically request the resource at
11
+ * the URL in the Location header, redirecting the user to the new page. Search
12
+ * engines receiving this response will attribute links to the original URL to
13
+ * the redirected resource, passing the SEO ranking to the new URL.
14
+ *
15
+ * The request method and the body will not be modified by the client in the
16
+ * redirected request. A 301 Moved Permanently requires the request method and
17
+ * the body to remain unchanged when redirection is performed, but this is
18
+ * incorrectly handled by older clients to use the GET method instead.
19
+ *
20
+ * > Note: Some Web applications may use the 308 Permanent Redirect in a
21
+ * > non-standard way and for different purposes. For example, Google Drive uses
22
+ * > a 308 Resume Incomplete response to indicate to the client when an
23
+ * > unfinished upload has stalled. See Perform a resumable download on the
24
+ * > Google Drive documentation for more information.
25
+ *
26
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308
27
+ */
28
+ export default function permanentRedirect(location: string): Response {
29
+ return transfer(308, location);
30
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Creates a response with the supplied status code and optional body.
3
+ *
4
+ * If the body is an object, it will be converted to JSON and the content-type
5
+ * header set to "application/json". Otherwise, if the body is a string, the
6
+ * content-type header will be set to "text/plain".
7
+ */
8
+ export default function response(status: number, body?: object | string): Response {
9
+ let headers: Record<string, string> | undefined = undefined;
10
+ if (body) {
11
+ if (typeof body === "object") {
12
+ headers = { "content-type": "application/json" };
13
+ body = JSON.stringify(body);
14
+ } else {
15
+ headers = { "content-type": "text/plain" };
16
+ }
17
+ }
18
+ return new Response(body, {
19
+ status,
20
+ headers,
21
+ });
22
+ }
@@ -0,0 +1,19 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 303 See Other
5
+ *
6
+ * The HTTP 303 See Other redirection response status code indicates that the
7
+ * browser should redirect to the URL in the Location header instead of
8
+ * rendering the requested resource.
9
+ *
10
+ * This response code is often sent back as a result of PUT or POST methods so
11
+ * the client may retrieve a confirmation, or view a representation of a
12
+ * real-world object (see HTTP range-14). The method to retrieve the redirected
13
+ * resource is always GET.
14
+ *
15
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303
16
+ */
17
+ export default function seeOther(location: string): Response {
18
+ return transfer(303, location);
19
+ }
@@ -0,0 +1,24 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 500 Server Error
5
+ *
6
+ * The HTTP 500 Internal Server Error server error response status code
7
+ * indicates that the server encountered an unexpected condition that prevented
8
+ * it from fulfilling the request. This error is a generic "catch-all" response
9
+ * to server issues, indicating that the server cannot find a more appropriate
10
+ * 5XX error to respond with.
11
+ *
12
+ * If you're a visitor seeing 500 errors on a web page, these issues require
13
+ * investigation by server owners or administrators. There are many possible
14
+ * causes of 500 errors, including: improper server configuration, out-of-memory
15
+ * (OOM) issues, unhandled exceptions, improper file permissions, or other
16
+ * complex factors. Server administrators may proactively log occurrences of
17
+ * server error responses, like the 500 status code, with details about the
18
+ * initiating requests to improve the stability of a service in the future.
19
+ *
20
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/500
21
+ */
22
+ export default function serverError(body?: object | string): Response {
23
+ return response(500, body ?? "Server error");
24
+ }
@@ -0,0 +1,31 @@
1
+ import transfer from "./transfer";
2
+
3
+ /**
4
+ * 307 Temporary Redirect
5
+ *
6
+ * The HTTP 307 Temporary Redirect redirection response status code indicates
7
+ * that the resource requested has been temporarily moved to the URL in the
8
+ * Location header.
9
+ *
10
+ * A browser receiving this status will automatically request the resource at
11
+ * the URL in the Location header, redirecting the user to the new page. Search
12
+ * engines receiving this response will not attribute links to the original URL
13
+ * to the new resource, meaning no SEO value is transferred to the new URL.
14
+ *
15
+ * The method and the body of the original request are reused to perform the
16
+ * redirected request. In the cases where you want the request method to be
17
+ * changed to GET, use 303 See Other instead. This is useful when you want to
18
+ * give an answer to a successful PUT request that is not the uploaded resource,
19
+ * but a status monitor or confirmation message like "You have successfully
20
+ * uploaded XYZ".
21
+ *
22
+ * The difference between 307 and 302 is that 307 guarantees that the client
23
+ * will not change the request method and body when the redirected request is
24
+ * made. With 302, older clients incorrectly changed the method to GET. 307 and
25
+ * 302 responses are identical when the request method is GET.
26
+ *
27
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307
28
+ */
29
+ export default function temporaryRedirect(location: string): Response {
30
+ return transfer(307, location);
31
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Creates a redirect response with the supplied status code.
3
+ */
4
+ export default function transfer(
5
+ status: 300 | 301 | 302 | 303 | 304 | 307 | 308,
6
+ location: string,
7
+ ): Response {
8
+ return new Response(null, {
9
+ status,
10
+ headers: {
11
+ location,
12
+ },
13
+ });
14
+ }
@@ -0,0 +1,21 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 401 Unauthorized
5
+ *
6
+ * The HTTP 401 Unauthorized client error response status code indicates that a
7
+ * request was not successful because it lacks valid authentication credentials
8
+ * for the requested resource. This status code is sent with an HTTP
9
+ * WWW-Authenticate response header that contains information on the
10
+ * authentication scheme the server expects the client to include to make the
11
+ * request successfully.
12
+ *
13
+ * A 401 Unauthorized is similar to the 403 Forbidden response, except that a
14
+ * 403 is returned when a request contains valid credentials, but the client
15
+ * does not have permissions to perform a certain action.
16
+ *
17
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401
18
+ */
19
+ export default function unauthorized(body?: object | string): Response {
20
+ return response(401, body ?? "Unauthorized");
21
+ }
@@ -0,0 +1,18 @@
1
+ import response from "./response";
2
+
3
+ /**
4
+ * 422 Unprocessable Content
5
+ *
6
+ * The HTTP 422 Unprocessable Content client error response status code
7
+ * indicates that the server understood the content type of the request content,
8
+ * and the syntax of the request content was correct, but it was unable to
9
+ * process the contained instructions.
10
+ *
11
+ * Clients that receive a 422 response should expect that repeating the request
12
+ * without modification will fail with the same error.
13
+ *
14
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/422
15
+ */
16
+ export default function unprocessable(body?: object | string): Response {
17
+ return response(422, body ?? "Unprocessable");
18
+ }
@@ -0,0 +1,37 @@
1
+ import badRequest from "./response/badRequest";
2
+ import created from "./response/created";
3
+ import forbidden from "./response/forbidden";
4
+ import found from "./response/found";
5
+ import methodNotAllowed from "./response/methodNotAllowed";
6
+ import movedPermanently from "./response/movedPermanently";
7
+ import notFound from "./response/notFound";
8
+ import notModified from "./response/notModified";
9
+ import ok from "./response/ok";
10
+ import permanentRedirect from "./response/permanentRedirect";
11
+ import response from "./response/response";
12
+ import seeOther from "./response/seeOther";
13
+ import serverError from "./response/serverError";
14
+ import temporaryRedirect from "./response/temporaryRedirect";
15
+ import transfer from "./response/transfer";
16
+ import unauthorized from "./response/unauthorized";
17
+ import unprocessable from "./response/unprocessable";
18
+
19
+ export {
20
+ response,
21
+ ok,
22
+ created,
23
+ transfer,
24
+ movedPermanently,
25
+ found,
26
+ seeOther,
27
+ notModified,
28
+ temporaryRedirect,
29
+ permanentRedirect,
30
+ badRequest,
31
+ unauthorized,
32
+ forbidden,
33
+ notFound,
34
+ methodNotAllowed,
35
+ unprocessable,
36
+ serverError,
37
+ };
@@ -0,0 +1,39 @@
1
+ export default function prepareTemplate(
2
+ template: string,
3
+ clientScript: string,
4
+ clientDevScript?: string,
5
+ ): string {
6
+ let result = template;
7
+
8
+ // Put %COMPONENT_HEAD% before </head>
9
+ // This is where styles will go
10
+ let headStart = result.indexOf("</head>");
11
+ if (headStart === -1) {
12
+ throw new Error(`Couldn't find <head> end tag`);
13
+ }
14
+ result = result.substring(0, headStart) + "%COMPONENT_HEAD%" + result.substring(headStart);
15
+
16
+ // Put %COMPONENT_BODY% inside <div id="app"></div>
17
+ // This is where the component's HTML will go
18
+ let bodyStart = regexIndexOf(result, /<div\s+id=("app"|'app'|app)\s+/);
19
+ bodyStart = result.indexOf(">", bodyStart) + 1;
20
+ let bodyEnd = result.indexOf("</div>", bodyStart);
21
+ if (bodyStart === -1 || bodyEnd === -1) {
22
+ throw new Error(`Couldn't find <div id="app"></div>`);
23
+ }
24
+ result = result.substring(0, bodyStart) + "%COMPONENT_BODY%" + result.substring(bodyEnd);
25
+
26
+ // Add the clientEntry script at the very end, for hydrating and navigating
27
+ if (clientDevScript) {
28
+ result += `<script type="module" src="${clientDevScript}"></script>`;
29
+ }
30
+ result += `<script type="module" src="${clientScript}"></script>`;
31
+
32
+ return result;
33
+ }
34
+
35
+ // From https://stackoverflow.com/a/274094
36
+ function regexIndexOf(string: string, regex: RegExp, position?: number) {
37
+ var indexOf = string.substring(position || 0).search(regex);
38
+ return indexOf >= 0 ? indexOf + (position || 0) : indexOf;
39
+ }
package/src/run/run.ts ADDED
@@ -0,0 +1,62 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { transformWithEsbuild } from "vite";
4
+ import Site from "../site/Site";
5
+ import runBuild from "./runBuild";
6
+ import runDev from "./runDev";
7
+ import runPreview from "./runPreview";
8
+
9
+ export default async function run(
10
+ folder: string,
11
+ mode: "dev" | "build" | "preview",
12
+ ): Promise<void> {
13
+ // Look for and load a site.config.js/ts file in the working directory
14
+ let configFile = "";
15
+ let deleteConfigFile = false;
16
+ const jsConfigFile = path.join(folder, "site.config.js");
17
+ const tsConfigFile = path.join(folder, "site.config.ts");
18
+ if (fs.existsSync(jsConfigFile)) {
19
+ // If it's JS, we can just import it straight up
20
+ configFile = jsConfigFile;
21
+ } else if (fs.existsSync(tsConfigFile)) {
22
+ // If it's TS, we need to convert it to JS
23
+ // TODO: Put the generated file somewhere better (dist?)
24
+ configFile = path.join(folder, "site.config.temp.js");
25
+ let source = fs.readFileSync(tsConfigFile, "utf-8");
26
+ let transformed = await transformWithEsbuild(source, tsConfigFile, {
27
+ loader: "ts",
28
+ });
29
+ fs.writeFileSync(configFile, transformed.code);
30
+ deleteConfigFile = true;
31
+ } else {
32
+ throw new Error("site.config file not found");
33
+ }
34
+
35
+ const site = (await import(configFile)).default as Site;
36
+ if (!site || !site.root || !site.routes) {
37
+ throw new Error("Invalid site in config file");
38
+ }
39
+ if (deleteConfigFile) {
40
+ fs.rmSync(configFile);
41
+ }
42
+
43
+ switch (mode) {
44
+ case "dev": {
45
+ await runDev(site);
46
+ break;
47
+ }
48
+ case "build": {
49
+ await runBuild(site);
50
+ break;
51
+ }
52
+ case "preview": {
53
+ await runPreview(site);
54
+ break;
55
+ }
56
+ default: {
57
+ console.log("No mode passed, running in dev");
58
+ await runDev(site);
59
+ break;
60
+ }
61
+ }
62
+ }
@@ -0,0 +1,77 @@
1
+ import torpor from "@torpor/unplugin/vite";
2
+ import { existsSync, promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+ import { build, defineConfig } from "vite";
5
+ import Site from "../site/Site";
6
+ import manifest from "../site/manifest.ts";
7
+
8
+ // TODO: Don't cache index.html in dev?
9
+ // TODO: Multiple hook.server locations
10
+ // TODO: Don't reload layouts during client routing
11
+ // TODO: Call the correct +page and +server routes when in the same folder
12
+
13
+ export default async function runBuild(site: Site): Promise<void> {
14
+ // Delete the dist folder if it exists
15
+ const distFolder = path.resolve(site.root, "dist");
16
+ if (existsSync(distFolder)) {
17
+ await fs.rm(distFolder, { recursive: true });
18
+ }
19
+ const clientFolder = path.join(distFolder, "client");
20
+ const serverFolder = path.join(distFolder, "server");
21
+
22
+ // HOOK: Prebuild
23
+ if (site.adapter.prebuild) {
24
+ await site.adapter.prebuild(site);
25
+ }
26
+
27
+ // TODO: From a setting
28
+ let siteHtml = path.resolve(site.root, "src/site.html");
29
+
30
+ const siteFolder = path.resolve(site.root, "./node_modules/@torpor/build/src/site/");
31
+ let clientScript = path.join(siteFolder, "clientEntry.ts");
32
+ let serverScript = path.join(siteFolder, "serverEntry.ts");
33
+
34
+ // Build the client assets, including site.html and the route files
35
+ // EXCLUDING anything with `server.js` in the name
36
+ const clientConfig = structuredClone(site.viteConfig ?? {});
37
+ clientConfig.plugins = [manifest(site), torpor(), ...site.plugins];
38
+ clientConfig.build ??= {};
39
+ clientConfig.build.outDir = clientFolder;
40
+ clientConfig.build.rollupOptions ??= {};
41
+ clientConfig.build.rollupOptions.input = [
42
+ siteHtml,
43
+ clientScript,
44
+ ...site.routes
45
+ .filter((r) => !/server\.(ts|js)$/.test(r.file))
46
+ .map((r) => path.resolve(site.root, r.file)),
47
+ ...site.inputs.filter((f) => !/server\.(ts|js)$/.test(f)),
48
+ ];
49
+ clientConfig.build.ssrManifest = true;
50
+ await build(defineConfig(clientConfig));
51
+
52
+ // Build the server assets, including the server entry script and the route
53
+ // files
54
+ const serverConfig = structuredClone(site.viteConfig ?? {});
55
+ serverConfig.plugins = [manifest(site, true), torpor(), ...site.plugins];
56
+ serverConfig.build ??= {};
57
+ serverConfig.build.outDir = serverFolder;
58
+ serverConfig.build.rollupOptions ??= {};
59
+ serverConfig.build.rollupOptions.input = [
60
+ serverScript,
61
+ ...site.routes.map((r) => path.resolve(site.root, r.file)),
62
+ ...site.inputs,
63
+ ];
64
+ serverConfig.build.ssr = serverScript;
65
+ await build(defineConfig(serverConfig));
66
+
67
+ // Move the site.html file into /client
68
+ // HACK: Should do this in Rollup if possible?
69
+ siteHtml = path.join(clientFolder, "site.html");
70
+ await fs.rename(path.join(clientFolder, "src", "site.html"), siteHtml);
71
+ await fs.rm(path.join(clientFolder, "src"), { recursive: true });
72
+
73
+ // HOOK: Postbuild
74
+ if (site.adapter.postbuild) {
75
+ await site.adapter.postbuild(site);
76
+ }
77
+ }
@@ -0,0 +1,89 @@
1
+ import estorpor from "@torpor/unplugin/esbuild";
2
+ import torpor from "@torpor/unplugin/vite";
3
+ import { configDotenv } from "dotenv";
4
+ import { promises as fs } from "node:fs";
5
+ import path from "node:path";
6
+ import { createServer as createViteServer } from "vite";
7
+ import { serverError } from "../response.ts";
8
+ import Server from "../server/Server.ts";
9
+ import connectMiddleware from "../server/connect/connectMiddleware.ts";
10
+ import Site from "../site/Site.ts";
11
+ import manifest from "../site/manifest.ts";
12
+ import prepareTemplate from "./prepareTemplate.ts";
13
+
14
+ export default async function runDev(site: Site): Promise<void> {
15
+ const server = new Server();
16
+
17
+ // Create the Vite server in middleware mode and configure the app type as
18
+ // "custom", disabling Vite's own HTML serving logic so the parent server
19
+ // can take control
20
+ const config = structuredClone(site.viteConfig ?? {});
21
+ config.server = { middlewareMode: true };
22
+ config.appType = "custom";
23
+ config.plugins = [manifest(site, true), torpor({ dev: true }), ...site.plugins];
24
+
25
+ // HACK: To be able to import `.torp` files from barrel files in
26
+ // node_modules, we need to add their libraries to `ssr.noExternal` in
27
+ // site.config.ts, and let esbuild know how to compile them here
28
+ config.optimizeDeps ??= {};
29
+ config.optimizeDeps.extensions ??= [];
30
+ config.optimizeDeps.extensions.push(".torp");
31
+ config.optimizeDeps.esbuildOptions ??= {};
32
+ config.optimizeDeps.esbuildOptions.plugins ??= [];
33
+ config.optimizeDeps.esbuildOptions.plugins.push(estorpor());
34
+
35
+ const vite = await createViteServer(config);
36
+
37
+ // Read site.html
38
+ // It's called site.html because @torpor/build builds the site (html, routes
39
+ // etc) while the user builds the app (components etc)
40
+ const templateFile = path.resolve(site.root, "src/site.html");
41
+ let template = await fs.readFile(templateFile, "utf-8");
42
+
43
+ // Apply Vite HTML transforms. This injects the Vite HMR client, and also
44
+ // applies HTML transforms from Vite plugins. Note that we only support a
45
+ // universal transform, not individual transforms for each route
46
+ template = await vite.transformIndexHtml("", template);
47
+
48
+ const siteFolder = path.resolve(site.root, "./node_modules/@torpor/build/src/site/");
49
+ let clientScript = path.join(siteFolder, "clientEntry.ts");
50
+ let clientDevScript = path.join(siteFolder, "clientEntryDev.ts");
51
+ let serverScript = path.join(siteFolder, "serverEntry.ts");
52
+
53
+ // Prepare site.html so that we can just splice components into it
54
+ template = prepareTemplate(template, clientScript, clientDevScript);
55
+
56
+ // Use Vite's Connect instance as middleware. We need to wrap it with
57
+ // createMiddlewareHandler that converts Connect middleware to
58
+ // Request/Response web handlers
59
+ server.use(connectMiddleware(vite.middlewares));
60
+
61
+ // Every request (GET, POST, etc) goes through loadEndPoint
62
+ server.add("*", async (ev) => {
63
+ try {
64
+ // Load the server entry. ssrLoadModule automatically transforms ESM
65
+ // source code to be usable in Node.js. No bundling is required, and
66
+ // it provides efficient invalidation similar to HMR
67
+ const { load } = await vite.ssrLoadModule(serverScript);
68
+
69
+ // Render the app HTML (or fetch server data etc) via serverEntry's
70
+ // exported `load` function
71
+ return await load(ev, template);
72
+ } catch (e: any) {
73
+ // If an error is caught, let Vite fix the stack trace so it maps
74
+ // back to your actual source code
75
+ vite.ssrFixStacktrace(e);
76
+ return serverError(e);
77
+ }
78
+ });
79
+
80
+ // Load environment variables from a `.env` file, with defaults if not set
81
+ configDotenv();
82
+
83
+ process.env.PROTOCOL ??= "http:";
84
+ process.env.HOST ??= "localhost";
85
+ process.env.PORT ??= "7059";
86
+
87
+ // Serve the site
88
+ site.adapter.serve(server, site);
89
+ }