@kodycodes/cli 3.39.0 → 3.40.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.
@@ -19,13 +19,15 @@ import {
19
19
  devHostExposureWarning,
20
20
  parseDevHost,
21
21
  planDevListen
22
- } from "./chunk-TJ4YVG6B.js";
22
+ } from "./chunk-CSXFRVBI.js";
23
23
  import {
24
24
  collectPackageCheckFiles,
25
+ devPackageAppOrigin,
25
26
  formatUnpublishedBundleInputMessage,
26
27
  listPackageCheckPaths,
28
+ localUsernameFor,
27
29
  unpublishedBundleInputPaths
28
- } from "./chunk-IEGR76KD.js";
30
+ } from "./chunk-3IYBIEX6.js";
29
31
  import {
30
32
  publishOutsideCloudAdvice
31
33
  } from "./chunk-XQY2VX3O.js";
@@ -818,7 +820,7 @@ import { randomBytes } from "node:crypto";
818
820
  import { rmSync, statSync } from "node:fs";
819
821
  import { mkdir as mkdir2, mkdtemp, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
820
822
  import {
821
- createServer,
823
+ createServer as createServer2,
822
824
  request as httpRequest
823
825
  } from "node:http";
824
826
  import { tmpdir as tmpdir2 } from "node:os";
@@ -1161,6 +1163,7 @@ fix: ${event.fix}` : ""}`
1161
1163
 
1162
1164
  // src/dev/dev-port.ts
1163
1165
  import { createHash as createHash2 } from "node:crypto";
1166
+ import { createServer } from "node:http";
1164
1167
  var devPortRange = { min: 4100, max: 4999 };
1165
1168
  var fallbackAttempts = 20;
1166
1169
  function defaultDevPort(kodyId) {
@@ -1201,6 +1204,12 @@ async function listenDevServer(server, input) {
1201
1204
  fix: "Stop old `kody dev` processes, or pass --port 0 for any free port."
1202
1205
  });
1203
1206
  }
1207
+ async function reserveDevPort(input) {
1208
+ const probe = createServer();
1209
+ const port = await listenDevServer(probe, input);
1210
+ await new Promise((resolve9) => probe.close(() => resolve9()));
1211
+ return port;
1212
+ }
1204
1213
  function portInUseError(host, port) {
1205
1214
  return new StructuredCliError({
1206
1215
  code: "dev_port_in_use",
@@ -4087,6 +4096,17 @@ async function startPackageAppDev(options) {
4087
4096
  assertTokenSafeApiUrl(options.apiUrl);
4088
4097
  const host = options.host ?? defaultDevHost;
4089
4098
  const appBasePath = resolveDevAppBasePath(options);
4099
+ const appOriginAt = (port) => devPackageAppOrigin({
4100
+ username: options.localKody?.username ?? localUsernameFor(options.manifest),
4101
+ kodyId: options.manifest.kodyId,
4102
+ port,
4103
+ appBasePath
4104
+ });
4105
+ if (options.localKody && !appOriginAt(1)) {
4106
+ throw new Error(
4107
+ `${options.manifest.name} cannot be served on its own host: "${options.manifest.kodyId}" and its scope do not form a valid {name}--{scope} host label (lowercase letters, digits and single hyphens, at most 63 characters together).`
4108
+ );
4109
+ }
4090
4110
  const root = options.manifest.root;
4091
4111
  const runSecret = randomBytes(32).toString("hex");
4092
4112
  const emit = (event) => options.onEvent?.(event);
@@ -4147,7 +4167,7 @@ async function startPackageAppDev(options) {
4147
4167
  }
4148
4168
  };
4149
4169
  process.once("exit", killAllSync);
4150
- const proxy = createServer((req, res) => {
4170
+ const proxy = createServer2((req, res) => {
4151
4171
  void handleRequest(req, res);
4152
4172
  });
4153
4173
  try {
@@ -4163,67 +4183,75 @@ async function startPackageAppDev(options) {
4163
4183
  throw error;
4164
4184
  }
4165
4185
  const address = proxy.address();
4166
- const listenPlan = planDevListen({ bindHost: host, port: address.port });
4186
+ const appOrigin = appOriginAt(address.port);
4187
+ const listenPlan = planDevListen({
4188
+ bindHost: host,
4189
+ port: address.port,
4190
+ appOrigin
4191
+ });
4167
4192
  const { hostedUrl, localUrl, networkUrls } = listenPlan;
4168
- proxy.on("upgrade", (req, socket, head) => {
4169
- const upstream = active?.upstream;
4170
- const publicHost = resolveAllowedDevHost({
4171
- incomingHost: req.headers.host,
4172
- trustedHost: trustedDevHostFromHostedUrl(hostedUrl),
4173
- aliases: [
4174
- ...options.hostAliases ?? [],
4175
- ...listenPlan.extraAllowedHosts()
4176
- ]
4177
- });
4178
- if (!upstream || !publicHost) {
4179
- socket.destroy();
4180
- return;
4181
- }
4193
+ const allowedHostFor = (req) => resolveAllowedDevHost({
4194
+ incomingHost: req.headers.host,
4195
+ trustedHost: trustedDevHostFromHostedUrl(hostedUrl),
4196
+ aliases: [
4197
+ ...options.hostAliases ?? [],
4198
+ ...listenPlan.extraAllowedHosts(),
4199
+ ...appOrigin ? [new URL(appOrigin).host] : []
4200
+ ]
4201
+ });
4202
+ const presentAs = (req, publicHost, viaLocalKody) => {
4203
+ const host2 = appOrigin && (viaLocalKody || hostedUrl === appOrigin) ? new URL(appOrigin).host : publicHost;
4204
+ const origin = req.headers.origin === `http://${publicHost}` ? `http://${host2}` : req.headers.origin;
4205
+ return { host: host2, origin };
4206
+ };
4207
+ let appSession = null;
4208
+ const localKodyTarget = async (upstream, req) => {
4182
4209
  const incomingUrl = new URL(req.url ?? "/", hostedUrl);
4183
- const restPath = stripMount(incomingUrl.pathname, appBasePath);
4184
4210
  const forwardUrl = new URL(
4185
4211
  buildTrustedDevForwardUrl({
4186
4212
  baseUrl: upstream.origin,
4187
- restPath: `${upstream.appPath}${restPath === "/" ? "/" : restPath}`,
4213
+ restPath: incomingUrl.pathname,
4188
4214
  search: incomingUrl.search
4189
4215
  })
4190
4216
  );
4191
- const upstreamReq = httpRequest(forwardUrl, {
4192
- method: req.method,
4193
- headers: devVisitorHeaders(req.headers, {
4194
- host: forwardUrl.host,
4195
- cookie: upstream.cookie
4196
- })
4217
+ if (isAnonymousDevVisitor(req.headers)) {
4218
+ return { forwardUrl, cookie: void 0 };
4219
+ }
4220
+ appSession ??= upstream.appSessionCookie({ rootMounted: !appBasePath });
4221
+ const session = await appSession.catch((error) => {
4222
+ appSession = null;
4223
+ throw error;
4197
4224
  });
4198
- upstreamReq.on("upgrade", (upstreamRes, upstreamSocket, upstreamHead) => {
4199
- const lines = [
4200
- `HTTP/1.1 101 ${upstreamRes.statusMessage ?? "Switching Protocols"}`
4201
- ];
4202
- for (let i = 0; i < upstreamRes.rawHeaders.length; i += 2) {
4203
- lines.push(
4204
- `${upstreamRes.rawHeaders[i]}: ${upstreamRes.rawHeaders[i + 1]}`
4205
- );
4225
+ return {
4226
+ forwardUrl,
4227
+ cookie: [req.headers.cookie, session].filter(Boolean).join("; ")
4228
+ };
4229
+ };
4230
+ const setHeader = (headers, name, value) => {
4231
+ if (value === void 0) delete headers[name];
4232
+ else headers[name] = value;
4233
+ };
4234
+ proxy.on("upgrade", (req, socket, head) => {
4235
+ void (async () => {
4236
+ const upstream = active?.upstream;
4237
+ const publicHost = allowedHostFor(req);
4238
+ if (!upstream || !publicHost) {
4239
+ socket.destroy();
4240
+ return;
4206
4241
  }
4207
- socket.write(`${lines.join("\r\n")}\r
4208
- \r
4209
- `);
4210
- if (upstreamHead.length > 0) socket.write(upstreamHead);
4211
- if (head.length > 0) upstreamSocket.write(head);
4212
- upstreamSocket.pipe(socket).pipe(upstreamSocket);
4213
- upstreamSocket.on("error", () => socket.destroy());
4214
- socket.on("error", () => upstreamSocket.destroy());
4215
- });
4216
- upstreamReq.on("response", (upstreamRes) => {
4217
- socket.end(
4218
- `HTTP/1.1 ${upstreamRes.statusCode ?? 502} ${upstreamRes.statusMessage ?? ""}\r
4219
- connection: close\r
4220
- \r
4221
- `
4222
- );
4223
- upstreamRes.resume();
4224
- });
4225
- upstreamReq.on("error", () => socket.destroy());
4226
- upstreamReq.end();
4242
+ const { forwardUrl, cookie } = await localKodyTarget(upstream, req);
4243
+ const presented = presentAs(req, publicHost, true);
4244
+ const headers = { ...req.headers };
4245
+ delete headers[devVisitorHeader];
4246
+ setHeader(headers, "host", presented.host);
4247
+ setHeader(headers, "origin", presented.origin);
4248
+ setHeader(headers, "cookie", cookie);
4249
+ const upstreamReq = httpRequest(forwardUrl, {
4250
+ method: req.method,
4251
+ headers
4252
+ });
4253
+ proxyUpgrade(upstreamReq, socket, head);
4254
+ })().catch(() => socket.destroy());
4227
4255
  });
4228
4256
  try {
4229
4257
  await options.onListening?.({
@@ -4711,14 +4739,7 @@ connection: close\r
4711
4739
  }
4712
4740
  async function handleRequest(req, res) {
4713
4741
  try {
4714
- const publicHost = resolveAllowedDevHost({
4715
- incomingHost: req.headers.host,
4716
- trustedHost: trustedDevHostFromHostedUrl(hostedUrl),
4717
- aliases: [
4718
- ...options.hostAliases ?? [],
4719
- ...listenPlan.extraAllowedHosts()
4720
- ]
4721
- });
4742
+ const publicHost = allowedHostFor(req);
4722
4743
  if (!publicHost) {
4723
4744
  res.writeHead(400, { "content-type": "text/plain; charset=utf-8" });
4724
4745
  res.end(
@@ -4780,7 +4801,10 @@ connection: close\r
4780
4801
  }
4781
4802
  }
4782
4803
  }
4783
- function forwardRequest(generation, req, res, trustedHost) {
4804
+ async function forwardRequest(generation, req, res, publicHost) {
4805
+ const upstream = generation.upstream;
4806
+ const presented = presentAs(req, publicHost, Boolean(upstream));
4807
+ const trustedHost = presented.host;
4784
4808
  const incomingUrl = new URL(req.url ?? "/", hostedUrl);
4785
4809
  const restPath = stripMount(incomingUrl.pathname, appBasePath);
4786
4810
  const publicUrl = buildTrustedDevPublicUrl({
@@ -4788,11 +4812,11 @@ connection: close\r
4788
4812
  restPath,
4789
4813
  search: incomingUrl.search
4790
4814
  });
4791
- const upstream = generation.upstream;
4792
- const forwardUrl = new URL(
4815
+ const localKody = upstream ? await localKodyTarget(upstream, req) : null;
4816
+ const forwardUrl = localKody?.forwardUrl ?? new URL(
4793
4817
  buildTrustedDevForwardUrl({
4794
- baseUrl: upstream?.origin ?? `http://127.0.0.1:${generation.workerd.port}`,
4795
- restPath: upstream ? `${upstream.appPath}${restPath === "/" ? "/" : restPath}` : restPath,
4818
+ baseUrl: `http://127.0.0.1:${generation.workerd.port}`,
4819
+ restPath,
4796
4820
  search: incomingUrl.search
4797
4821
  })
4798
4822
  );
@@ -4808,10 +4832,9 @@ connection: close\r
4808
4832
  runSecret,
4809
4833
  requestId: tag.id
4810
4834
  });
4811
- if (upstream) {
4812
- headers.host = forwardUrl.host;
4813
- if (isAnonymousDevVisitor(req.headers)) delete headers.cookie;
4814
- else headers.cookie = upstream.cookie;
4835
+ setHeader(headers, "origin", presented.origin);
4836
+ if (localKody) {
4837
+ setHeader(headers, "cookie", localKody.cookie);
4815
4838
  delete headers[devVisitorHeader];
4816
4839
  }
4817
4840
  const startedAt2 = performance.now();
@@ -4832,6 +4855,7 @@ connection: close\r
4832
4855
  forwardUrl,
4833
4856
  { method: req.method, headers },
4834
4857
  (upstreamRes) => {
4858
+ if (upstreamRes.headers["x-kody-handoff"]) appSession = null;
4835
4859
  if (upstreamRes.headers[devErrorHeader]) {
4836
4860
  void readStream(upstreamRes).then((raw) => {
4837
4861
  respondWithRuntimeError(generation, req, res, tag, raw);
@@ -5157,15 +5181,19 @@ function normalizeBasePath(value) {
5157
5181
  return withSlash.replace(/\/+$/, "");
5158
5182
  }
5159
5183
  function resolveDevAppBasePath(options) {
5160
- const requested = options.appBasePath === void 0 ? void 0 : normalizeBasePath(options.appBasePath);
5161
- if (!options.localKody) return requested ?? "";
5162
- const mount = normalizeBasePath(options.localKody.appPath);
5163
- if (requested !== void 0 && requested !== mount) {
5184
+ const requested = normalizeBasePath(options.appBasePath ?? "");
5185
+ const oldPath = `/${options.manifest.kodyId}`;
5186
+ if (options.localKody && requested && options.localKody.username === options.manifest.kodyId) {
5164
5187
  throw new Error(
5165
- `--app-base-path ${requested || "/"} does not match the local Kody mount ${mount}. kody dev --target mock serves the app where local Kody renders its links; drop --app-base-path or pass ${mount}.`
5188
+ `--app-base-path does not apply to ${options.manifest.name}: a profile package is only served at the root of its owner's host. Drop --app-base-path.`
5166
5189
  );
5167
5190
  }
5168
- return mount;
5191
+ if (options.localKody && requested && requested !== oldPath) {
5192
+ throw new Error(
5193
+ `--app-base-path ${requested} is not an address local Kody serves. Drop --app-base-path to serve the app at the root of its own host, or pass ${oldPath} for the old path address.`
5194
+ );
5195
+ }
5196
+ return requested;
5169
5197
  }
5170
5198
  function stripMount(pathname, appBasePath) {
5171
5199
  if (!appBasePath) return pathname || "/";
@@ -5185,12 +5213,36 @@ var devVisitorHeader = "x-kody-dev-visitor";
5185
5213
  function isAnonymousDevVisitor(headers) {
5186
5214
  return String(headers[devVisitorHeader] ?? "").trim() === "anonymous";
5187
5215
  }
5188
- function devVisitorHeaders(base, local) {
5189
- const headers = { ...base, host: local.host };
5190
- delete headers[devVisitorHeader];
5191
- if (isAnonymousDevVisitor(base)) delete headers.cookie;
5192
- else headers.cookie = local.cookie;
5193
- return headers;
5216
+ function proxyUpgrade(upstreamReq, socket, head) {
5217
+ upstreamReq.on("upgrade", (upstreamRes, upstreamSocket, upstreamHead) => {
5218
+ const lines = [
5219
+ `HTTP/1.1 101 ${upstreamRes.statusMessage ?? "Switching Protocols"}`
5220
+ ];
5221
+ for (let i = 0; i < upstreamRes.rawHeaders.length; i += 2) {
5222
+ lines.push(
5223
+ `${upstreamRes.rawHeaders[i]}: ${upstreamRes.rawHeaders[i + 1]}`
5224
+ );
5225
+ }
5226
+ socket.write(`${lines.join("\r\n")}\r
5227
+ \r
5228
+ `);
5229
+ if (upstreamHead.length > 0) socket.write(upstreamHead);
5230
+ if (head.length > 0) upstreamSocket.write(head);
5231
+ upstreamSocket.pipe(socket).pipe(upstreamSocket);
5232
+ upstreamSocket.on("error", () => socket.destroy());
5233
+ socket.on("error", () => upstreamSocket.destroy());
5234
+ });
5235
+ upstreamReq.on("response", (upstreamRes) => {
5236
+ socket.end(
5237
+ `HTTP/1.1 ${upstreamRes.statusCode ?? 502} ${upstreamRes.statusMessage ?? ""}\r
5238
+ connection: close\r
5239
+ \r
5240
+ `
5241
+ );
5242
+ upstreamRes.resume();
5243
+ });
5244
+ upstreamReq.on("error", () => socket.destroy());
5245
+ upstreamReq.end();
5194
5246
  }
5195
5247
  var devCallOperations = /* @__PURE__ */ new Set([
5196
5248
  "jobList",
@@ -5267,7 +5319,12 @@ async function runDevServe(input) {
5267
5319
  const onEvent = input.json ? (event) => writeJsonEvent(input.io, event) : (event) => writeDevEvent(input.io, event);
5268
5320
  let registered = false;
5269
5321
  let server;
5270
- const localKody = input.startLocalKody ? await input.startLocalKody(manifest) : null;
5322
+ const localKodyPort = input.startLocalKody ? await reserveDevPort({
5323
+ host: input.host ?? defaultDevHost,
5324
+ port: input.port ?? defaultDevPort(manifest.kodyId),
5325
+ explicit: input.port !== void 0
5326
+ }) : void 0;
5327
+ const localKody = input.startLocalKody && localKodyPort !== void 0 ? await input.startLocalKody(manifest, localKodyPort) : null;
5271
5328
  try {
5272
5329
  server = await startPackageAppDev({
5273
5330
  manifest,
@@ -5276,7 +5333,7 @@ async function runDevServe(input) {
5276
5333
  apiUrl: input.auth.apiUrl,
5277
5334
  target: input.target,
5278
5335
  ...input.host !== void 0 ? { host: input.host } : {},
5279
- port: input.port,
5336
+ port: localKodyPort ?? input.port,
5280
5337
  defaultPort: defaultDevPort(manifest.kodyId),
5281
5338
  appBasePath: input.appBasePath,
5282
5339
  ...input.auth.org ? { org: input.auth.org } : {},
@@ -5340,6 +5397,7 @@ async function runDevServe(input) {
5340
5397
  );
5341
5398
  const ready = {
5342
5399
  url: status.url,
5400
+ localUrl: `${server.localUrl}${server.appBasePath || "/"}`,
5343
5401
  port: server.port,
5344
5402
  basePath: server.appBasePath,
5345
5403
  pid: process.pid,
@@ -5547,9 +5605,10 @@ async function tryAttachedDevCall(input) {
5547
5605
  };
5548
5606
  } else {
5549
5607
  if (process.env.KODY_DEV_STUB_RUNTIME === "1") return null;
5550
- const local = await import("./local-kody-NDNDB5MV.js");
5608
+ const local = await import("./local-kody-RYKBNHAP.js");
5551
5609
  const kody = await local.startLocalKody({
5552
5610
  manifest,
5611
+ packageAppPort: defaultDevPort(manifest.kodyId),
5553
5612
  onStatus: (message) => input.io.stderr(`${message}
5554
5613
  `)
5555
5614
  });
@@ -6267,4 +6326,4 @@ export {
6267
6326
  chokidar/esm/index.js:
6268
6327
  (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
6269
6328
  */
6270
- //# sourceMappingURL=dev-command-ILYM5NXU.js.map
6329
+ //# sourceMappingURL=dev-command-2HKWG2GT.js.map