@ngrok/app-server 0.4.1 → 0.5.1

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 (119) hide show
  1. package/README.md +223 -64
  2. package/dist/brotli-only-BVAagKt3.js +63 -0
  3. package/dist/build-id-CwMbED1n.js +245 -0
  4. package/dist/{build-manifest-DBMWe3Lx.js → build-manifest-CoBztw_6.js} +13 -4
  5. package/dist/bun-BCz6K_Xv.js +1 -2
  6. package/dist/check-count-DQl5z_qe.js +17 -0
  7. package/dist/cli.js +9 -6
  8. package/dist/client-browser.d.ts +2 -3
  9. package/dist/client-browser.js +1 -1
  10. package/dist/client.d.ts +5 -4
  11. package/dist/client.js +9 -6
  12. package/dist/{compress-Cp5NfXCC.js → compress-2w3jqBh7.js} +2 -3
  13. package/dist/{compression-CT2mWlKM.js → compression-uJxu0JVb.js} +32 -5
  14. package/dist/content-types-Le-5BNEC.js +10 -0
  15. package/dist/{create-server-Bp1yILQk.js → create-server-DVTZun6D.js} +617 -306
  16. package/dist/create-server-PA0qniaK.js +3 -0
  17. package/dist/{create-server-X2GR-U6t.d.ts → create-server-UVsHFQyK.d.ts} +116 -54
  18. package/dist/deno-aqhikNMG.js +1 -2
  19. package/dist/{entry-BoxCqc6w.js → entry-CMhX3yf8.js} +85 -65
  20. package/dist/entry-CvZ4U0ia.js +3 -0
  21. package/dist/{entry-DZTCaL3d.d.ts → entry-DBq_3s8X.d.ts} +10 -36
  22. package/dist/entry-protocol-C30UPXzy.js +14 -0
  23. package/dist/entry-source-DSE5NAJu.js +70 -0
  24. package/dist/entry-source-SHoE-DUP.js +3 -0
  25. package/dist/exit-Hh-O3gp4.js +83 -0
  26. package/dist/{header-hook-Vzw9J9BY.js → header-hook-JfqaTt34.js} +69 -23
  27. package/dist/{index-B8LsM6Mh.d.ts → index-gzGs53Ue.d.ts} +43 -38
  28. package/dist/index.d.ts +88 -44
  29. package/dist/index.js +216 -84
  30. package/dist/listen-options-7TaXjyrk.js +1 -2
  31. package/dist/{load-entry-CCPWbsrj.js → load-entry-Bgq1_HDV.js} +11 -12
  32. package/dist/{log-DQAS5gGT.js → log-DfC9D5_T.js} +70 -49
  33. package/dist/{node-D6m6e6EI.js → node-DQPrMFyc.js} +20 -8
  34. package/dist/node-DyKDFII0.js +263 -0
  35. package/dist/node-vite.d.ts +2 -3
  36. package/dist/node-vite.js +1 -1
  37. package/dist/node.d.ts +41 -64
  38. package/dist/node.js +3 -3
  39. package/dist/react-router-vite.d.ts +2 -3
  40. package/dist/react-router-vite.js +1 -1
  41. package/dist/react-router.d.ts +6 -17
  42. package/dist/react-router.js +9 -14
  43. package/dist/request-context-Cslbrscf.js +163 -0
  44. package/dist/{response-edge-CU8ZvL_F.js → response-edge-Ow5Pi5qF.js} +13 -10
  45. package/dist/{response-writer-D7KHfr8n.js → response-writer-Dd4Ey99f.js} +57 -21
  46. package/dist/{script-hashes-CU7P9oZU.js → script-hashes-BdvJ0QI_.js} +2 -3
  47. package/dist/serve-AatMo9k6.js +26 -0
  48. package/dist/{stale-build-navigation-rg5xxmTr.js → stale-build-navigation-Qf_Lem39.js} +4 -5
  49. package/dist/{stale-build-navigation-ypV7Ow4o.d.ts → stale-build-navigation-WjhD8zHi.d.ts} +4 -4
  50. package/dist/start-DYFyGKsM.js +470 -0
  51. package/dist/static-files-BdTPam5b.js +438 -0
  52. package/dist/static-pages-6IBHdYQc.d.ts +30 -0
  53. package/dist/tanstack-start-vite.d.ts +2 -3
  54. package/dist/tanstack-start-vite.js +1 -1
  55. package/dist/tanstack-start.d.ts +3 -4
  56. package/dist/tanstack-start.js +2 -3
  57. package/dist/tcp-3v4pmnYU.js +58 -0
  58. package/dist/testing.d.ts +8 -6
  59. package/dist/testing.js +19 -17
  60. package/dist/{trailing-slash-D2QWKWEu.d.ts → trailing-slash-C-yBKCib.d.ts} +2 -3
  61. package/dist/{types-MgFtkNQW.d.ts → types-KsKRDwAv.d.ts} +97 -46
  62. package/dist/vercel-pages.d.ts +3 -16
  63. package/dist/vercel-pages.js +1 -2
  64. package/dist/vercel-vite.d.ts +4 -5
  65. package/dist/vercel-vite.js +48 -44
  66. package/dist/vercel.d.ts +13 -10
  67. package/dist/vercel.js +48 -35
  68. package/dist/{vite-D4hfj3ph.js → vite-Brb8YR9I.js} +2 -7
  69. package/dist/{vite-B-GfswoH.js → vite-CHppJWp_.js} +5 -7
  70. package/dist/{vite-DyrhyKEr.js → vite-DjlHdyTM.js} +2 -7
  71. package/dist/vite.d.ts +2 -2
  72. package/dist/vite.js +885 -2
  73. package/package.json +13 -12
  74. package/dist/brotli-only-DrA29Ecw.js +0 -97
  75. package/dist/brotli-only-DrA29Ecw.js.map +0 -1
  76. package/dist/build-id-B0448vZH.js +0 -151
  77. package/dist/build-id-B0448vZH.js.map +0 -1
  78. package/dist/build-manifest-DBMWe3Lx.js.map +0 -1
  79. package/dist/bun-BCz6K_Xv.js.map +0 -1
  80. package/dist/cli.js.map +0 -1
  81. package/dist/client.js.map +0 -1
  82. package/dist/compress-Cp5NfXCC.js.map +0 -1
  83. package/dist/compression-CT2mWlKM.js.map +0 -1
  84. package/dist/create-server-Bp1yILQk.js.map +0 -1
  85. package/dist/deno-aqhikNMG.js.map +0 -1
  86. package/dist/entry-BoxCqc6w.js.map +0 -1
  87. package/dist/header-hook-Vzw9J9BY.js.map +0 -1
  88. package/dist/index.js.map +0 -1
  89. package/dist/listen-options-7TaXjyrk.js.map +0 -1
  90. package/dist/load-entry-CCPWbsrj.js.map +0 -1
  91. package/dist/log-DQAS5gGT.js.map +0 -1
  92. package/dist/node-CVVdk2N6.js +0 -334
  93. package/dist/node-CVVdk2N6.js.map +0 -1
  94. package/dist/node-D6m6e6EI.js.map +0 -1
  95. package/dist/react-router.js.map +0 -1
  96. package/dist/request-context-Bxdbk5P1.js +0 -80
  97. package/dist/request-context-Bxdbk5P1.js.map +0 -1
  98. package/dist/response-edge-CU8ZvL_F.js.map +0 -1
  99. package/dist/response-writer-D7KHfr8n.js.map +0 -1
  100. package/dist/script-hashes-CU7P9oZU.js.map +0 -1
  101. package/dist/serve-W4WacdOw.js +0 -29
  102. package/dist/serve-W4WacdOw.js.map +0 -1
  103. package/dist/stale-build-navigation-rg5xxmTr.js.map +0 -1
  104. package/dist/start-j0VlxeiI.js +0 -324
  105. package/dist/start-j0VlxeiI.js.map +0 -1
  106. package/dist/static-files-C2ea8KQ6.js +0 -310
  107. package/dist/static-files-C2ea8KQ6.js.map +0 -1
  108. package/dist/tanstack-start.js.map +0 -1
  109. package/dist/tcp-BgDXbjOG.js +0 -42
  110. package/dist/tcp-BgDXbjOG.js.map +0 -1
  111. package/dist/testing.js.map +0 -1
  112. package/dist/vercel-pages.js.map +0 -1
  113. package/dist/vercel-vite.js.map +0 -1
  114. package/dist/vercel.js.map +0 -1
  115. package/dist/vite-B-GfswoH.js.map +0 -1
  116. package/dist/vite-D4hfj3ph.js.map +0 -1
  117. package/dist/vite-DPiSKHDn.js +0 -870
  118. package/dist/vite-DPiSKHDn.js.map +0 -1
  119. package/dist/vite-DyrhyKEr.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-B0448vZH.js";
1
+ import { a as serverTimingMetrics, i as isBuildMetric, n as BUILD_ID_METRIC, t as BUILD_ID_HEADER } from "./build-id-CwMbED1n.js";
2
2
 
3
3
  // src/client/document-nonce.ts
4
4
  /**
@@ -81,7 +81,7 @@ function onAbort(signal, clear) {
81
81
  signal.addEventListener("abort", clear, { once: true });
82
82
  }
83
83
  /** Reads the build of each response, and tells when the server runs a new build. */
84
- function watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }) {
84
+ function watchBuild({ headerName = BUILD_ID_HEADER, build, onNewBuild }) {
85
85
  if (typeof document === "undefined") return null;
86
86
  const current = build ?? timingBuild(performance.getEntriesByType("navigation"));
87
87
  if (current == null) return null;
@@ -106,7 +106,7 @@ function watchBuild({ header = BUILD_ID_HEADER, build, onNewBuild }) {
106
106
  isStale: () => stale,
107
107
  /** Whether `response` comes from a new build of this origin. `url` is the URL of the request. */
108
108
  isNew: (response, url) => {
109
- const served = isOwn(response.url === "" ? url : response.url) ? response.headers.get(header) ?? headerBuild(response.headers.get("Server-Timing")) : null;
109
+ const served = isOwn(response.url === "" ? url : response.url) ? response.headers.get(headerName) ?? headerBuild(response.headers.get("Server-Timing")) : null;
110
110
  see(served);
111
111
  return served != null && served !== current;
112
112
  },
@@ -335,5 +335,4 @@ function staleBuildTanStack(router, options = {}) {
335
335
  };
336
336
  }
337
337
 
338
- export { staleBuildTanStack as n, documentNonce as r, staleBuildReactRouter as t };
339
- //# sourceMappingURL=stale-build-navigation-rg5xxmTr.js.map
338
+ export { staleBuildTanStack as n, documentNonce as r, staleBuildReactRouter as t };
@@ -1,10 +1,11 @@
1
1
  /** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */
2
2
  type StaleBuildOptions = {
3
3
  /**
4
- * The header that `buildId()` sets on data responses.
4
+ * The header that `buildId()` sets on data responses: the `headerName` of
5
+ * `buildId()`.
5
6
  * @default "X-Build-Id"
6
7
  */
7
- header?: string;
8
+ headerName?: string;
8
9
  /**
9
10
  * The build that this document runs. Set it only when the server does not
10
11
  * send it.
@@ -137,5 +138,4 @@ declare function staleBuildReactRouter(options?: StaleBuildOptions): StaleBuildR
137
138
  * }
138
139
  */
139
140
  declare function staleBuildTanStack(router: NavigationEvents, options?: StaleBuildOptions): () => void;
140
- export { staleBuildReactRouter as a, StaleBuildReactRouter as i, RouterFetchContext as n, staleBuildTanStack as o, StaleBuildOptions as r, NavigationEvents as t };
141
- //# sourceMappingURL=stale-build-navigation-ypV7Ow4o.d.ts.map
141
+ export { staleBuildReactRouter as a, StaleBuildReactRouter as i, RouterFetchContext as n, staleBuildTanStack as o, StaleBuildOptions as r, NavigationEvents as t };
@@ -0,0 +1,470 @@
1
+ import { c as textSink, r as hookSink, t as asError } from "./log-DfC9D5_T.js";
2
+ import { t as publicScriptHashes } from "./script-hashes-BdvJ0QI_.js";
3
+ import { t as exitAfterFlush } from "./exit-Hh-O3gp4.js";
4
+ import { t as requestListener } from "./response-writer-Dd4Ey99f.js";
5
+ import { t as parsePort } from "./tcp-3v4pmnYU.js";
6
+ import { n as SERVER_ENTRY_ID } from "./entry-source-DSE5NAJu.js";
7
+ import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
8
+ import { t as loadEntry } from "./load-entry-Bgq1_HDV.js";
9
+ import { styleText } from "node:util";
10
+ import { networkInterfaces } from "node:os";
11
+ import { IncomingMessage, ServerResponse, createServer } from "node:http";
12
+ import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
13
+ import { createServer as createServer$1 } from "node:net";
14
+
15
+ // src/node/dev-server.ts
16
+ function isServerResponse(value) {
17
+ return value instanceof ServerResponse;
18
+ }
19
+ /**
20
+ * Makes `outgoing` run `hooks` before it sends its head, and returns the
21
+ * function that undoes it. Why `writeHead`: Node calls it for each
22
+ * response, also from `write` and `end`.
23
+ */
24
+ function runHooksAtHead(outgoing, hooks) {
25
+ const headers = {
26
+ get: (name) => {
27
+ const value = outgoing.getHeader(name);
28
+ return value == null ? null : String(value);
29
+ },
30
+ has: (name) => outgoing.hasHeader(name),
31
+ set: (name, value) => {
32
+ outgoing.setHeader(name, value);
33
+ },
34
+ append: (name, value) => {
35
+ outgoing.appendHeader(name, value);
36
+ },
37
+ delete: (name) => {
38
+ outgoing.removeHeader(name);
39
+ }
40
+ };
41
+ const writeHead = outgoing.writeHead.bind(outgoing);
42
+ outgoing.writeHead = (statusCode, reason, values) => {
43
+ const [message, given] = typeof reason === "string" ? [reason, values] : [void 0, reason];
44
+ if (Array.isArray(given)) {
45
+ const names = given.filter((_, index) => index % 2 === 0).map(String);
46
+ for (const name of names) outgoing.removeHeader(name);
47
+ for (const [index, name] of names.entries()) {
48
+ const value = given[index * 2 + 1];
49
+ if (value != null) outgoing.appendHeader(name, typeof value === "number" ? String(value) : value);
50
+ }
51
+ } else if (given != null) {
52
+ for (const [name, value] of Object.entries(given)) if (value != null) outgoing.setHeader(name, value);
53
+ }
54
+ for (const hook of hooks.toReversed()) hook(headers);
55
+ return message == null ? writeHead(statusCode) : writeHead(statusCode, message);
56
+ };
57
+ return () => {
58
+ outgoing.writeHead = writeHead;
59
+ };
60
+ }
61
+ /** The script hashes of the public HTML file at `pathname`, or `undefined` when there is none. */
62
+ function publicFileHashes({ directory, base }, pathname) {
63
+ const prefix = base.replace(/\/$/u, "");
64
+ return publicScriptHashes(directory, pathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : pathname);
65
+ }
66
+ /**
67
+ * Runs a Connect middleware, such as Vite's, inside the pipeline. The
68
+ * middleware answers or calls `next`. A request with no Node request and
69
+ * response goes on.
70
+ *
71
+ * @example
72
+ * entry.fetchDev(request, {
73
+ * bindings,
74
+ * devServer: devServerStage(viteServer.middlewares, {
75
+ * publicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),
76
+ * }),
77
+ * });
78
+ */
79
+ function devServerStage(middleware, { publicFiles } = {}) {
80
+ return async (context, next) => {
81
+ const { incoming, outgoing } = context.env;
82
+ if (!(incoming instanceof IncomingMessage) || !isServerResponse(outgoing)) return next();
83
+ const hashes = publicFiles == null ? void 0 : publicFileHashes(publicFiles(), new URL(context.req.url).pathname);
84
+ const earlierHashes = context.get("documentScriptHashes");
85
+ if (hashes != null) context.set("documentScriptHashes", hashes);
86
+ for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
87
+ const hooks = context.get("headerHooks") ?? [];
88
+ const undoHooks = runHooksAtHead(outgoing, hooks);
89
+ if (await new Promise((resolve, reject) => {
90
+ const onFinish = () => {
91
+ resolve(true);
92
+ };
93
+ outgoing.once("finish", onFinish);
94
+ middleware(incoming, outgoing, (error) => {
95
+ outgoing.off("finish", onFinish);
96
+ undoHooks();
97
+ if (hashes != null) context.set("documentScriptHashes", earlierHashes);
98
+ if (error == null) resolve(false);
99
+ else reject(new Error("The dev server middleware failed", { cause: error }));
100
+ });
101
+ })) {
102
+ hooks.length = 0;
103
+ const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
104
+ for (const [name, value] of Object.entries(outgoing.getHeaders())) for (const each of Array.isArray(value) ? value : [value]) if (each != null) headers.append(name, String(each));
105
+ return new Response(null, {
106
+ status: outgoing.statusCode,
107
+ headers
108
+ });
109
+ }
110
+ return next();
111
+ };
112
+ }
113
+
114
+ // src/cli/dev-urls.ts
115
+ const wildcardHosts = /* @__PURE__ */ new Set([
116
+ "",
117
+ "0.0.0.0",
118
+ "::"
119
+ ]);
120
+ const loopbackHosts = /* @__PURE__ */ new Set([
121
+ "localhost",
122
+ "127.0.0.1",
123
+ "::1"
124
+ ]);
125
+ /**
126
+ * The URLs that `app-server start` listens on, in the shape of Vite's `server.resolvedUrls`. Each
127
+ * URL ends with `base`, Vite's base path. A wildcard host gets a `localhost` URL, then one URL for
128
+ * each IPv4 (Internet Protocol version 4) interface.
129
+ *
130
+ * @example
131
+ * devUrls({ hostname: "localhost", port: 3000, base: "/" });
132
+ * // => { local: ["http://localhost:3000/"], network: [], networkInterfaceNames: [] }
133
+ */
134
+ function devUrls({ hostname, port, base }, interfaces = networkInterfaces()) {
135
+ const urlOf = (host) => `${listenerUrl(host, port).slice(0, -1)}${base}`;
136
+ const addresses = Object.entries(interfaces).flatMap(([name, details = []]) => details.map(({ address, family }) => ({
137
+ name,
138
+ address,
139
+ family
140
+ })));
141
+ if (hostname != null && !wildcardHosts.has(hostname)) return loopbackHosts.has(hostname) ? {
142
+ local: [urlOf(hostname)],
143
+ network: [],
144
+ networkInterfaceNames: []
145
+ } : {
146
+ local: [],
147
+ network: [urlOf(hostname)],
148
+ networkInterfaceNames: [addresses.find(({ address }) => address === hostname)?.name]
149
+ };
150
+ const reachable = addresses.filter(({ address, family }) => family === "IPv4" && address !== "127.0.0.1");
151
+ return {
152
+ local: [urlOf("localhost")],
153
+ network: reachable.map(({ address }) => urlOf(address)),
154
+ networkInterfaceNames: reachable.map(({ name }) => name)
155
+ };
156
+ }
157
+ /** `url` in the colors of `vite dev`, which makes the port bold. */
158
+ function link(url) {
159
+ return styleText("cyan", url.replace(/:(?<port>\d+)\//u, `:${styleText("bold", "$<port>")}/`));
160
+ }
161
+ /**
162
+ * The lines that `app-server start` prints for `urls` when it listens, in the format of `vite dev`.
163
+ *
164
+ * @example
165
+ * devUrlLines({ local: ["http://localhost:3000/"], network: [] }); // => [" ➜ Local: http://localhost:3000/"]
166
+ */
167
+ function devUrlLines({ local, network, networkInterfaceNames = [] }) {
168
+ const arrow = styleText("green", "➜");
169
+ const width = Math.max(0, ...network.map((url) => url.length));
170
+ return [...local.map((url) => ` ${arrow} ${styleText("bold", "Local")}: ${link(url)}`), ...network.map((url, index) => {
171
+ const name = networkInterfaceNames[index];
172
+ const suffix = name == null ? "" : " ".repeat(width - url.length + 2) + styleText("dim", name);
173
+ return ` ${arrow} ${styleText("bold", "Network")}: ${link(url)}${suffix}`;
174
+ })];
175
+ }
176
+
177
+ // src/cli/served-apps.ts
178
+ /**
179
+ * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a
180
+ * new app, and the old app's plugins still hold what their `setup` opened.
181
+ * When the last request that the old app took returns, its `onShutdown` hooks
182
+ * run, and the tracker lets go of it. A route edit makes a new entry with the
183
+ * same app, which keeps its plugins.
184
+ */
185
+ function servedApps() {
186
+ let current;
187
+ const served = /* @__PURE__ */ new Set();
188
+ const retire = async (app) => {
189
+ try {
190
+ await app.entry.stopPlugins();
191
+ } finally {
192
+ served.delete(app);
193
+ }
194
+ };
195
+ return {
196
+ serve: async (entry, handle) => {
197
+ if (current?.entry.app === entry.app) current.entry = entry;
198
+ else {
199
+ if (current != null) {
200
+ current.replaced = true;
201
+ if (current.pending === 0) retire(current);
202
+ }
203
+ current = {
204
+ entry,
205
+ pending: 0,
206
+ replaced: false
207
+ };
208
+ served.add(current);
209
+ }
210
+ const app = current;
211
+ app.pending += 1;
212
+ try {
213
+ return await handle(entry);
214
+ } finally {
215
+ app.pending -= 1;
216
+ if (app.replaced && app.pending === 0) retire(app);
217
+ }
218
+ },
219
+ stopAll: async () => {
220
+ await Promise.all(Array.from(served, async (app) => {
221
+ app.entry.abortShutdownSignal();
222
+ await retire(app);
223
+ }));
224
+ }
225
+ };
226
+ }
227
+
228
+ // src/cli/start-port.ts
229
+ const MAX_PORT = 65535;
230
+ /**
231
+ * Starts `server` on `port`. When the port is in use, it tries each next port
232
+ * up to 65535, like Vite and `react-router-serve` do in development. Each
233
+ * error for a port in use has the words of `vite dev`.
234
+ *
235
+ * @returns the port that the server listens on
236
+ */
237
+ async function listenFromPort(server, { port, hostname, strictPort, onPortInUse, onWildcardInUse }) {
238
+ if (port === 0) {
239
+ await bind(server, port, hostname);
240
+ return boundPort(server, port);
241
+ }
242
+ if (strictPort) {
243
+ const freeOnWildcard = hostname == null || await isFreeOnWildcard(port);
244
+ try {
245
+ await bind(server, port, hostname);
246
+ } catch (error) {
247
+ throw isAddressInUse(error) ? new Error(`Port ${port} is already in use`, { cause: error }) : error;
248
+ }
249
+ if (!freeOnWildcard) onWildcardInUse?.(port);
250
+ return port;
251
+ }
252
+ for (let candidate = port; candidate <= MAX_PORT; candidate++) {
253
+ if (hostname == null || await isFreeOnWildcard(candidate)) try {
254
+ await bind(server, candidate, hostname);
255
+ return candidate;
256
+ } catch (error) {
257
+ if (!isAddressInUse(error)) throw error;
258
+ }
259
+ onPortInUse?.(candidate);
260
+ }
261
+ throw new Error(`No available ports found between ${port} and ${MAX_PORT}`);
262
+ }
263
+ async function bind(server, port, hostname) {
264
+ return new Promise((resolve, reject) => {
265
+ function onError(error) {
266
+ server.off("listening", onListening);
267
+ reject(error);
268
+ }
269
+ function onListening() {
270
+ server.off("error", onError);
271
+ resolve();
272
+ }
273
+ server.once("error", onError);
274
+ server.once("listening", onListening);
275
+ server.listen(port, hostname);
276
+ });
277
+ }
278
+ async function isFreeOnWildcard(port) {
279
+ const probe = createServer$1();
280
+ try {
281
+ await bind(probe, port, void 0);
282
+ } catch (error) {
283
+ if (isAddressInUse(error)) return false;
284
+ throw error;
285
+ }
286
+ await new Promise((resolve) => {
287
+ probe.close(() => {
288
+ resolve();
289
+ });
290
+ });
291
+ return true;
292
+ }
293
+ /** The port that `server` listens on, or `fallback` for a server with no TCP address. */
294
+ function boundPort(server, fallback) {
295
+ const address = server.address();
296
+ return typeof address === "object" && address != null ? address.port : fallback;
297
+ }
298
+ function isAddressInUse(error) {
299
+ return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
300
+ }
301
+
302
+ // src/cli/start.ts
303
+ /**
304
+ * Runs the app in development: the same pipeline as production, with Vite in
305
+ * middleware mode inside it. Each request loads the server entry through
306
+ * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies
307
+ * at once. HMR shares the port. Vite's plugins get the CLI's HTTP server as
308
+ * `server.httpServer`, and its URLs as `server.resolvedUrls`.
309
+ *
310
+ * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the
311
+ * server tries each next port, unless Vite's `server.strictPort` is true. The
312
+ * host is `HOST`, else Vite's `server.host`. Vite's `server.open` opens the browser. The server
313
+ * speaks HTTP only: see `shareHttpServer` for `server.https`.
314
+ */
315
+ async function start() {
316
+ const vite = await import("vite");
317
+ const httpServer = createServer();
318
+ /** The host and the port that the HTTP server listens on. No value before it listens. */
319
+ let listensOn;
320
+ const resolvedUrls = (base) => listensOn == null ? null : devUrls({
321
+ ...listensOn,
322
+ base
323
+ });
324
+ const viteServer = await vite.createServer({
325
+ server: {
326
+ middlewareMode: true,
327
+ ws: { server: httpServer }
328
+ },
329
+ appType: "custom",
330
+ plugins: [shareHttpServer({
331
+ httpServer,
332
+ resolvedUrls
333
+ })]
334
+ });
335
+ const ssrRunner = () => {
336
+ const { ssr } = viteServer.environments;
337
+ if (ssr == null || !vite.isRunnableDevEnvironment(ssr)) throw new Error("Vite's SSR environment cannot run modules.");
338
+ return ssr.runner;
339
+ };
340
+ ssrRunner();
341
+ if (!viteServer.config.plugins.some((plugin) => plugin.name === "@ngrok/app-server")) {
342
+ await viteServer.close();
343
+ throw new Error("`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.");
344
+ }
345
+ const devServer = devServerStage(viteServer.middlewares, { publicFiles: () => ({
346
+ directory: viteServer.config.publicDir,
347
+ base: viteServer.config.base
348
+ }) });
349
+ const sink = hookSink(textSink());
350
+ const apps = servedApps();
351
+ const listener = requestListener(async (request, bindings) => {
352
+ try {
353
+ return await apps.serve(await loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)), async (entry) => entry.fetchDev(request, {
354
+ bindings,
355
+ devServer
356
+ }));
357
+ } catch (error) {
358
+ if (error instanceof Error) viteServer.ssrFixStacktrace(error);
359
+ sink.log({
360
+ level: "error",
361
+ message: "dev request failed",
362
+ attributes: { error: asError(error) }
363
+ });
364
+ return new Response(error instanceof Error ? error.stack ?? error.message : String(error), {
365
+ status: 500,
366
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
367
+ });
368
+ }
369
+ });
370
+ httpServer.on("request", (request, response) => {
371
+ listener(request, response);
372
+ });
373
+ const port = process.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);
374
+ const hostname = process.env.HOST || viteHostname(viteServer.config.server.host);
375
+ const { logger } = viteServer.config;
376
+ httpServer.prependOnceListener("listening", () => {
377
+ listensOn = {
378
+ hostname,
379
+ port: boundPort(httpServer, port)
380
+ };
381
+ viteServer.resolvedUrls = resolvedUrls(viteServer.config.base);
382
+ });
383
+ await listenFromPort(httpServer, {
384
+ port,
385
+ hostname,
386
+ strictPort: viteServer.config.server.strictPort,
387
+ onPortInUse: (inUse) => {
388
+ logger.info(`Port ${inUse} is in use, trying another one...`);
389
+ },
390
+ onWildcardInUse: (inUse) => {
391
+ logger.warn(styleText("yellow", `Port ${inUse} is in use on a wildcard address, but ${hostname ?? "localhost"}:${inUse} is available. There may be another server running on a wildcard IP on port ${inUse}.`));
392
+ }
393
+ });
394
+ logger.info("");
395
+ for (const line of devUrlLines(viteServer.resolvedUrls ?? {
396
+ local: [],
397
+ network: []
398
+ })) logger.info(line);
399
+ const { open } = viteServer.config.server;
400
+ if (open === true || typeof open === "string" && open !== "") viteServer.openBrowser();
401
+ for (const signal of ["SIGTERM", "SIGINT"]) process.once(signal, () => {
402
+ const pluginsStopped = apps.stopAll();
403
+ httpServer.closeAllConnections();
404
+ const httpClosed = new Promise((resolve) => {
405
+ httpServer.close(() => {
406
+ resolve();
407
+ });
408
+ });
409
+ const viteClosed = viteServer.close().catch((error) => {
410
+ sink.log({
411
+ level: "error",
412
+ message: "Vite close failed",
413
+ attributes: { error: asError(error) }
414
+ });
415
+ process.exitCode = 1;
416
+ });
417
+ Promise.all([
418
+ pluginsStopped,
419
+ httpClosed,
420
+ viteClosed
421
+ ]).finally(exitAfterFlush);
422
+ });
423
+ }
424
+ /**
425
+ * A Vite plugin that gives the CLI's HTTP server to the app's plugins, because Vite has no HTTP
426
+ * server of its own in middleware mode:
427
+ *
428
+ * - It sets `server.httpServer` and `server.resolvedUrls` before the `configureServer` hooks of
429
+ * the app's plugins run. Vite sets both to `null`. Then a plugin that waits for `listening` or
430
+ * `close`, or that reads the URLs, does nothing, with no error.
431
+ * - It removes a `server.https` that has HTTPS on, with a warning. The CLI makes the HTTP server
432
+ * before Vite reads the config, so the server speaks HTTP only.
433
+ *
434
+ * `resolvedUrls` gives the URLs for a base path, or `null` before the HTTP server listens.
435
+ *
436
+ * @example
437
+ * vite.createServer({ plugins: [shareHttpServer({ httpServer, resolvedUrls: () => null })] });
438
+ */
439
+ function shareHttpServer({ httpServer, resolvedUrls }) {
440
+ const plugin = {
441
+ name: "@ngrok/app-server:http-server",
442
+ configResolved: {
443
+ order: "post",
444
+ handler: (config) => {
445
+ const plugins = config.plugins;
446
+ plugins.splice(plugins.indexOf(plugin), 1);
447
+ plugins.unshift(plugin);
448
+ if (config.server.https) {
449
+ delete config.server.https;
450
+ config.logger.warn(styleText("yellow", "`app-server start` serves HTTP only, so it ignores `server.https`. For HTTPS in development, put a proxy or a tunnel that ends TLS in front of it."));
451
+ }
452
+ }
453
+ },
454
+ configureServer: {
455
+ order: "pre",
456
+ handler: (server) => {
457
+ server.httpServer = httpServer;
458
+ server.resolvedUrls = resolvedUrls(server.config.base);
459
+ }
460
+ }
461
+ };
462
+ return plugin;
463
+ }
464
+ /** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */
465
+ function viteHostname(host) {
466
+ if (host === true) return;
467
+ return typeof host === "string" && host !== "" ? host : "localhost";
468
+ }
469
+
470
+ export { start };