@geekmidas/cli 10.0.0-alpha.80 → 10.0.0-alpha.82

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 (105) hide show
  1. package/dist/{EndpointGenerator-DftalLYg.mjs → EndpointGenerator-DtnIGafh.mjs} +71 -8
  2. package/dist/EndpointGenerator-DtnIGafh.mjs.map +1 -0
  3. package/dist/{EndpointGenerator-CP6sBvQV.cjs → EndpointGenerator-cKlnllIu.cjs} +88 -7
  4. package/dist/EndpointGenerator-cKlnllIu.cjs.map +1 -0
  5. package/dist/{OpenApiTsGenerator-nu1r1NgB.mjs → OpenApiTsGenerator-ByRPMbBN.mjs} +34 -7
  6. package/dist/OpenApiTsGenerator-ByRPMbBN.mjs.map +1 -0
  7. package/dist/{OpenApiTsGenerator-CKBCckKz.cjs → OpenApiTsGenerator-CdUM6Hvv.cjs} +34 -7
  8. package/dist/OpenApiTsGenerator-CdUM6Hvv.cjs.map +1 -0
  9. package/dist/{SubscriberGenerator-CajwOa5W.cjs → SubscriberGenerator-CYriX5BV.cjs} +2 -2
  10. package/dist/{SubscriberGenerator-CajwOa5W.cjs.map → SubscriberGenerator-CYriX5BV.cjs.map} +1 -1
  11. package/dist/{SubscriberGenerator-5looQ3gB.mjs → SubscriberGenerator-DQZeGkDW.mjs} +2 -2
  12. package/dist/{SubscriberGenerator-5looQ3gB.mjs.map → SubscriberGenerator-DQZeGkDW.mjs.map} +1 -1
  13. package/dist/{add-DJ0VE-y-.cjs → add-1T3y6E4M.cjs} +2 -2
  14. package/dist/{add-DJ0VE-y-.cjs.map → add-1T3y6E4M.cjs.map} +1 -1
  15. package/dist/{add-CIxT-Iq6.mjs → add-DnYHJOap.mjs} +2 -2
  16. package/dist/{add-CIxT-Iq6.mjs.map → add-DnYHJOap.mjs.map} +1 -1
  17. package/dist/{bundler-D4pl87A5.mjs → bundler-DlKdxCGh.mjs} +3 -3
  18. package/dist/{bundler-D4pl87A5.mjs.map → bundler-DlKdxCGh.mjs.map} +1 -1
  19. package/dist/{bundler-BlbSLFLn.cjs → bundler-YNvLdvlh.cjs} +3 -3
  20. package/dist/{bundler-BlbSLFLn.cjs.map → bundler-YNvLdvlh.cjs.map} +1 -1
  21. package/dist/{cli-BkNZBe_-.cjs → cli-CWee1-wU.cjs} +3 -3
  22. package/dist/{cli-BkNZBe_-.cjs.map → cli-CWee1-wU.cjs.map} +1 -1
  23. package/dist/{cli-7aLfgIGt.mjs → cli-qMszGvDu.mjs} +3 -3
  24. package/dist/{cli-7aLfgIGt.mjs.map → cli-qMszGvDu.mjs.map} +1 -1
  25. package/dist/{compose-n7K8H5j8.mjs → compose-D4sD4Lgr.mjs} +83 -351
  26. package/dist/compose-D4sD4Lgr.mjs.map +1 -0
  27. package/dist/{compose-Bn4OJONR.cjs → compose-qnDyPJNp.cjs} +101 -369
  28. package/dist/compose-qnDyPJNp.cjs.map +1 -0
  29. package/dist/deploy/public.cjs +5 -5
  30. package/dist/deploy/public.d.cts.map +1 -1
  31. package/dist/deploy/public.d.mts.map +1 -1
  32. package/dist/deploy/public.mjs +5 -5
  33. package/dist/{deploy-DK4Y6ev4.mjs → deploy-C00DAKOt.mjs} +3 -3
  34. package/dist/{deploy-DK4Y6ev4.mjs.map → deploy-C00DAKOt.mjs.map} +1 -1
  35. package/dist/{deploy-Ppnh8MHS.cjs → deploy-CXP2fXvK.cjs} +3 -3
  36. package/dist/{deploy-Ppnh8MHS.cjs.map → deploy-CXP2fXvK.cjs.map} +1 -1
  37. package/dist/{dokploy-Bjq05wkw.mjs → dokploy-B3zoCmJb.mjs} +2 -2
  38. package/dist/{dokploy-Bjq05wkw.mjs.map → dokploy-B3zoCmJb.mjs.map} +1 -1
  39. package/dist/{dokploy-CJvdoNc3.cjs → dokploy-BHcSmghb.cjs} +2 -2
  40. package/dist/{dokploy-CJvdoNc3.cjs.map → dokploy-BHcSmghb.cjs.map} +1 -1
  41. package/dist/{drivers-Ch1rJitn.mjs → drivers-B4RP2B2O.mjs} +2 -2
  42. package/dist/{drivers-Ch1rJitn.mjs.map → drivers-B4RP2B2O.mjs.map} +1 -1
  43. package/dist/{drivers-BdvtCKc7.cjs → drivers-CJx76mcb.cjs} +2 -2
  44. package/dist/{drivers-BdvtCKc7.cjs.map → drivers-CJx76mcb.cjs.map} +1 -1
  45. package/dist/{encryption-CAyR6D7B.cjs → encryption-DLin89I_.cjs} +2 -2
  46. package/dist/{encryption-CAyR6D7B.cjs.map → encryption-DLin89I_.cjs.map} +1 -1
  47. package/dist/{encryption-BrsOJFFz.mjs → encryption-DPFljXtM.mjs} +2 -2
  48. package/dist/{encryption-BrsOJFFz.mjs.map → encryption-DPFljXtM.mjs.map} +1 -1
  49. package/dist/{engine-DzBZR5D0.cjs → engine-BS3iX9Mu.cjs} +2 -2
  50. package/dist/{engine-DzBZR5D0.cjs.map → engine-BS3iX9Mu.cjs.map} +1 -1
  51. package/dist/{engine-ba9CvjTo.mjs → engine-CgzgIg-_.mjs} +2 -2
  52. package/dist/{engine-ba9CvjTo.mjs.map → engine-CgzgIg-_.mjs.map} +1 -1
  53. package/dist/{github-BLjU59Ye.cjs → github-D8KVmNRg.cjs} +2 -2
  54. package/dist/{github-BLjU59Ye.cjs.map → github-D8KVmNRg.cjs.map} +1 -1
  55. package/dist/{github-CVdbVlT5.mjs → github-DL4zwJsR.mjs} +2 -2
  56. package/dist/{github-CVdbVlT5.mjs.map → github-DL4zwJsR.mjs.map} +1 -1
  57. package/dist/index.cjs +225 -49
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.mjs +226 -50
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/{migrate-iEdyEx4S.cjs → migrate-BdKhIJgT.cjs} +2 -2
  62. package/dist/{migrate-iEdyEx4S.cjs.map → migrate-BdKhIJgT.cjs.map} +1 -1
  63. package/dist/{migrate-DlBgATa-.mjs → migrate-CCejlgU0.mjs} +2 -2
  64. package/dist/{migrate-DlBgATa-.mjs.map → migrate-CCejlgU0.mjs.map} +1 -1
  65. package/dist/{migrate-pfu4aYzX.mjs → migrate-Cd3kcI7o.mjs} +2 -2
  66. package/dist/{migrate-pfu4aYzX.mjs.map → migrate-Cd3kcI7o.mjs.map} +1 -1
  67. package/dist/{migrate-DkB833Jj.cjs → migrate-DIjG8-QR.cjs} +2 -2
  68. package/dist/{migrate-DkB833Jj.cjs.map → migrate-DIjG8-QR.cjs.map} +1 -1
  69. package/dist/openapi.cjs +16 -11
  70. package/dist/openapi.cjs.map +1 -1
  71. package/dist/openapi.d.cts +28 -0
  72. package/dist/openapi.d.cts.map +1 -1
  73. package/dist/openapi.d.mts +28 -0
  74. package/dist/openapi.d.mts.map +1 -1
  75. package/dist/openapi.mjs +16 -12
  76. package/dist/openapi.mjs.map +1 -1
  77. package/dist/{ready-BB9xS4S9.cjs → ready-4kx2pAhm.cjs} +5 -5
  78. package/dist/{ready-BB9xS4S9.cjs.map → ready-4kx2pAhm.cjs.map} +1 -1
  79. package/dist/{ready-ZZoNskrr.mjs → ready-DhZbZtFw.mjs} +5 -5
  80. package/dist/{ready-ZZoNskrr.mjs.map → ready-DhZbZtFw.mjs.map} +1 -1
  81. package/dist/{resolve-4_5N67Fk.cjs → resolve-ApSUK_HB.cjs} +3 -3
  82. package/dist/{resolve-4_5N67Fk.cjs.map → resolve-ApSUK_HB.cjs.map} +1 -1
  83. package/dist/{resolve-CQPn66jr.mjs → resolve-DY9TaVeV.mjs} +3 -3
  84. package/dist/{resolve-CQPn66jr.mjs.map → resolve-DY9TaVeV.mjs.map} +1 -1
  85. package/dist/{rollback-CgYUPLbq.cjs → rollback-CdGhCk1d.cjs} +3 -3
  86. package/dist/{rollback-CgYUPLbq.cjs.map → rollback-CdGhCk1d.cjs.map} +1 -1
  87. package/dist/{rollback-C0cbdsM-.mjs → rollback-DXU6cr7q.mjs} +3 -3
  88. package/dist/{rollback-C0cbdsM-.mjs.map → rollback-DXU6cr7q.mjs.map} +1 -1
  89. package/dist/{seeds-ZljwYV_p.cjs → seeds-BLzrSwEr.cjs} +3889 -2953
  90. package/dist/seeds-BLzrSwEr.cjs.map +1 -0
  91. package/dist/{seeds-BdkFpW0P.mjs → seeds-DbyqaXW4.mjs} +2344 -1528
  92. package/dist/seeds-DbyqaXW4.mjs.map +1 -0
  93. package/dist/target/public.cjs +1 -1
  94. package/dist/target/public.mjs +1 -1
  95. package/dist/vitest.cjs +1 -1
  96. package/dist/vitest.mjs +1 -1
  97. package/package.json +15 -15
  98. package/dist/EndpointGenerator-CP6sBvQV.cjs.map +0 -1
  99. package/dist/EndpointGenerator-DftalLYg.mjs.map +0 -1
  100. package/dist/OpenApiTsGenerator-CKBCckKz.cjs.map +0 -1
  101. package/dist/OpenApiTsGenerator-nu1r1NgB.mjs.map +0 -1
  102. package/dist/compose-Bn4OJONR.cjs.map +0 -1
  103. package/dist/compose-n7K8H5j8.mjs.map +0 -1
  104. package/dist/seeds-BdkFpW0P.mjs.map +0 -1
  105. package/dist/seeds-ZljwYV_p.cjs.map +0 -1
@@ -3,6 +3,39 @@ import { basename, dirname, join, relative, resolve } from "node:path";
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { Endpoint } from "@geekmidas/constructs/endpoints";
6
+ //#region src/generators/clientTelemetry.ts
7
+ /** A `sampleRate` outside 0–1, which no sampler can honour. */
8
+ var InvalidClientTelemetrySampleRate = class extends Error {
9
+ sampleRate;
10
+ constructor(sampleRate) {
11
+ super(`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`);
12
+ this.sampleRate = sampleRate;
13
+ this.name = "InvalidClientTelemetrySampleRate";
14
+ }
15
+ };
16
+ /** The `telemetry` default as the generated module prints it. */
17
+ function printTelemetryDefault(telemetry) {
18
+ if (typeof telemetry === "boolean") return String(telemetry);
19
+ const { sampleRate } = telemetry;
20
+ if (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) throw new InvalidClientTelemetrySampleRate(sampleRate);
21
+ return `{ sampleRate: ${sampleRate} }`;
22
+ }
23
+ /**
24
+ * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and
25
+ * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.
26
+ */
27
+ function telemetryArgs(telemetry) {
28
+ if (!telemetry) return [];
29
+ if (telemetry === true) return ["--telemetry"];
30
+ return ["--telemetry", String(telemetry.sampleRate)];
31
+ }
32
+ /** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */
33
+ function parseTelemetryFlag(value) {
34
+ if (value === void 0 || value === false) return void 0;
35
+ if (value === true) return true;
36
+ return { sampleRate: Number(value) };
37
+ }
38
+ //#endregion
6
39
  //#region src/generators/telemetry.ts
7
40
  /**
8
41
  * Every package `@geekmidas/telescope/instrumentation` loads at runtime.
@@ -69,9 +102,15 @@ const HEADER = `/**
69
102
 
70
103
  import type { MiddlewareHandler } from 'hono';
71
104
 
72
- /** Requests whose spans would only be noise: health checks, by default. */
73
105
  export interface StartTelemetryOptions {
106
+ /** Requests whose spans would only be noise: health checks, by default. */
74
107
  ignorePaths?: string[];
108
+ /**
109
+ * The API's own sites — the origins its CORS allows — read on each request.
110
+ * Their \`traceparent\` is continued, as is an internal caller's; anyone
111
+ * else's starts a new trace linked to the one it claimed.
112
+ */
113
+ trustedOrigins?: () => readonly string[];
75
114
  }
76
115
 
77
116
  /** Telemetry was asked for and cannot start. The server runs without it. */
@@ -153,10 +192,13 @@ export async function startTelemetry(
153
192
  }
154
193
 
155
194
  // A SERVER span per request, opened by the app itself rather than by
156
- // hooking node:http: \`GET /users/:id\`, continuing an incoming traceparent,
157
- // with the handler — its logs, fetches and queries — running inside it.
195
+ // hooking node:http: \`GET /users/:id\`, continuing an incoming traceparent
196
+ // from the API's own sites and internal callers (a new, linked trace from
197
+ // anyone else), with the handler — its logs, fetches and queries — running
198
+ // inside it.
158
199
  return instrumentation.honoTelemetryMiddleware({
159
200
  ignorePaths: options.ignorePaths,
201
+ trustedOrigins: options.trustedOrigins,
160
202
  });
161
203
  }
162
204
  `;
@@ -216,11 +258,13 @@ function corsFor(surface) {
216
258
  setup: ""
217
259
  };
218
260
  const cors = surface.cors ?? {};
219
- const allowHeaders = [
261
+ const allowHeaders = [.../* @__PURE__ */ new Set([
220
262
  "content-type",
221
263
  "authorization",
264
+ "traceparent",
265
+ "tracestate",
222
266
  ...cors.allowHeaders ?? []
223
- ];
267
+ ])];
224
268
  return {
225
269
  imports: `import { cors } from 'hono/cors';`,
226
270
  setup: `
@@ -237,6 +281,10 @@ function corsFor(surface) {
237
281
  }))
238
282
  .parse();
239
283
 
284
+ // The same origins are the ones whose trace context the request spans
285
+ // continue — the server reads them back from \`createApp\`.
286
+ trustedOrigins.push(...origins);
287
+
240
288
  honoApp.use('*', cors({
241
289
  origin: origins,
242
290
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
@@ -505,6 +553,8 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
505
553
 
506
554
  ` : ""}export interface ServerApp {
507
555
  app: HonoType;
556
+ /** The origins this API's CORS allows: its own sites. */
557
+ trustedOrigins: readonly string[];
508
558
  start: (options?: {
509
559
  port?: number;
510
560
  /** Returns the server, so a shutdown can stop it taking requests. */
@@ -548,6 +598,7 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
548
598
  */
549
599
  export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
550
600
  const honoApp = app || new Hono();
601
+ const trustedOrigins: string[] = [];
551
602
  ${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}
552
603
  // Setup HTTP endpoints
553
604
  await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
@@ -555,6 +606,7 @@ ${afterSetupCall}
555
606
 
556
607
  return {
557
608
  app: honoApp,
609
+ trustedOrigins,
558
610
  async start(options) {
559
611
  if (!options?.serve) {
560
612
  throw new Error(
@@ -731,6 +783,8 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
731
783
 
732
784
  ` : ""}export interface ServerApp {
733
785
  app: HonoType;
786
+ /** The origins this API's CORS allows: its own sites. */
787
+ trustedOrigins: readonly string[];
734
788
  start: (options?: {
735
789
  port?: number;
736
790
  serve: (app: HonoType, port: number) => void | Promise<void>;
@@ -742,6 +796,7 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
742
796
  */
743
797
  export async function createApp(app?: HonoType): Promise<ServerApp> {
744
798
  const honoApp = app || new Hono();
799
+ const trustedOrigins: string[] = [];
745
800
 
746
801
  // Health check endpoint (always first)
747
802
  honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
@@ -781,6 +836,7 @@ ${cors.setup}${beforeSetupCall}
781
836
  ${afterSetupCall}
782
837
  return {
783
838
  app: honoApp,
839
+ trustedOrigins,
784
840
  async start(options) {
785
841
  if (!options?.serve) {
786
842
  throw new Error(
@@ -826,9 +882,14 @@ import { serve } from '@hono/node-server';
826
882
  import { Hono } from 'hono';
827
883
  import { startTelemetry } from './telemetry.js';
828
884
 
885
+ // The API's own sites, known once the app has read its configuration: the
886
+ // origins its CORS allows are the ones whose trace context is continued.
887
+ let trustedOrigins: readonly string[] = [];
888
+
829
889
  // Before the app is imported, so the libraries it loads are instrumented.
830
890
  const requestSpans = await startTelemetry({
831
891
  ignorePaths: [${JSON.stringify(context.production?.healthCheck ?? "/health")}, '/ready'],
892
+ trustedOrigins: () => trustedOrigins,
832
893
  });
833
894
 
834
895
  const { createApp } = await import('./app.js');
@@ -839,7 +900,9 @@ const port = Number(process.env.PORT) || 3000;
839
900
  const app = new Hono();
840
901
  if (requestSpans) app.use('*', requestSpans);
841
902
 
842
- const { start } = await createApp(app);
903
+ const created = await createApp(app);
904
+ trustedOrigins = created.trustedOrigins;
905
+ const { start } = created;
843
906
 
844
907
  await start({
845
908
  port,
@@ -850,6 +913,6 @@ await start({
850
913
  }
851
914
  };
852
915
  //#endregion
853
- export { telemetryFor as i, runtimeFor as n, generateTelemetryModule as r, EndpointGenerator as t };
916
+ export { parseTelemetryFlag as a, telemetryFor as i, runtimeFor as n, printTelemetryDefault as o, generateTelemetryModule as r, telemetryArgs as s, EndpointGenerator as t };
854
917
 
855
- //# sourceMappingURL=EndpointGenerator-DftalLYg.mjs.map
918
+ //# sourceMappingURL=EndpointGenerator-DtnIGafh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EndpointGenerator-DtnIGafh.mjs","names":[],"sources":["../src/generators/clientTelemetry.ts","../src/generators/telemetry.ts","../src/generators/EndpointGenerator.ts"],"sourcesContent":["/**\n * Whether a generated client propagates trace context by default.\n *\n * `false` (the default) prints a client that sends no trace headers unless\n * its caller passes `telemetry`. Anything else prints that default into\n * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page\n * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option\n * still wins.\n */\nexport type ClientTelemetryDefault = boolean | { sampleRate: number };\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientTelemetrySampleRate extends Error {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientTelemetrySampleRate';\n\t}\n}\n\n/** The `telemetry` default as the generated module prints it. */\nexport function printTelemetryDefault(\n\ttelemetry: ClientTelemetryDefault,\n): string {\n\tif (typeof telemetry === 'boolean') return String(telemetry);\n\tconst { sampleRate } = telemetry;\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientTelemetrySampleRate(sampleRate);\n\t}\n\treturn `{ sampleRate: ${sampleRate} }`;\n}\n\n/**\n * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and\n * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.\n */\nexport function telemetryArgs(telemetry?: ClientTelemetryDefault): string[] {\n\tif (!telemetry) return [];\n\tif (telemetry === true) return ['--telemetry'];\n\treturn ['--telemetry', String(telemetry.sampleRate)];\n}\n\n/** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */\nexport function parseTelemetryFlag(\n\tvalue: boolean | string | undefined,\n): ClientTelemetryDefault | undefined {\n\tif (value === undefined || value === false) return undefined;\n\tif (value === true) return true;\n\treturn { sampleRate: Number(value) };\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\n\n/**\n * What a production entry needs to start OpenTelemetry, decided at build time.\n *\n * Carried on the build context so the generator prints values rather than\n * working them out: which service this is, which product it belongs to, and\n * whether the packages to export with were there to build against.\n */\nexport interface TelemetryContext {\n\t/** `service.name` — the surface the server serves, or the app's directory. */\n\tserviceName: string;\n\t/** `service.namespace` — the workspace the app is part of. */\n\tserviceNamespace?: string;\n\t/**\n\t * Whether `@geekmidas/telescope/instrumentation` and the OpenTelemetry\n\t * packages it imports resolve from the app.\n\t *\n\t * They are optional peers, so an app may not have them. An entry built\n\t * without them never imports them: the bundler would otherwise fail on the\n\t * first one it cannot find, and an app that never asked for telemetry\n\t * would stop building.\n\t */\n\tavailable: boolean;\n}\n\n/**\n * Every package `@geekmidas/telescope/instrumentation` loads at runtime.\n *\n * All of them, rather than one as a proxy: the production bundle follows each\n * import, and a single missing one fails the build rather than the telemetry.\n */\nexport const TELEMETRY_PACKAGES = [\n\t'@opentelemetry/api',\n\t'@opentelemetry/auto-instrumentations-node',\n\t'@opentelemetry/exporter-logs-otlp-http',\n\t'@opentelemetry/exporter-trace-otlp-http',\n\t'@opentelemetry/instrumentation-pino',\n\t'@opentelemetry/resources',\n\t'@opentelemetry/sdk-logs',\n\t'@opentelemetry/sdk-node',\n\t'@opentelemetry/sdk-trace-base',\n\t'@opentelemetry/sdk-trace-node',\n\t'@opentelemetry/semantic-conventions',\n] as const;\n\n/**\n * The directory of `name` as `node_modules` lookup finds it from `fromDir`,\n * symlinks resolved — or undefined.\n *\n * The directory walk alone, not `require.resolve`: that also searches\n * `NODE_PATH`, which a package manager's bin shim sets to its own store, so a\n * `gkm build` run through one would find packages the app never installed —\n * and the bundler, which does not look there, would then fail on them.\n */\nfunction packageDir(fromDir: string, name: string): string | undefined {\n\tfor (let dir = resolve(fromDir); ; dir = dirname(dir)) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(dir) === dir) return undefined;\n\t}\n}\n\n/**\n * Whether the telemetry packages resolve the way the bundler will resolve them:\n * telescope from the app, and the OpenTelemetry packages from telescope —\n * where a peer is linked under pnpm, which need not be where the app sees it.\n */\nexport function telemetryResolvesFrom(appRoot: string): boolean {\n\tconst telescope = packageDir(appRoot, '@geekmidas/telescope');\n\tif (!telescope) return false;\n\n\treturn TELEMETRY_PACKAGES.every((pkg) => packageDir(telescope, pkg));\n}\n\n/** The telemetry half of a build context. */\nexport function telemetryFor(options: {\n\tappRoot: string;\n\tsurfaceId?: string;\n\tworkspaceName?: string;\n}): TelemetryContext {\n\treturn {\n\t\tserviceName: options.surfaceId ?? basename(options.appRoot),\n\t\t...(options.workspaceName && { serviceNamespace: options.workspaceName }),\n\t\tavailable: telemetryResolvesFrom(options.appRoot),\n\t};\n}\n\nconst HEADER = `/**\n * Generated by 'gkm build --production'.\n *\n * Starts OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT names a collector, and\n * does nothing otherwise: without it, the telemetry packages are not loaded.\n * The standard OTEL_* variables (OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG,\n * OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME)\n * configure the rest.\n */\n\nimport type { MiddlewareHandler } from 'hono';\n\nexport interface StartTelemetryOptions {\n /** Requests whose spans would only be noise: health checks, by default. */\n ignorePaths?: string[];\n /**\n * The API's own sites — the origins its CORS allows — read on each request.\n * Their \\`traceparent\\` is continued, as is an internal caller's; anyone\n * else's starts a new trace linked to the one it claimed.\n */\n trustedOrigins?: () => readonly string[];\n}\n\n/** Telemetry was asked for and cannot start. The server runs without it. */\nexport class TelemetryUnavailable extends Error {\n constructor(readonly reason: string, options?: { cause?: unknown }) {\n super(\n \\`OTEL_EXPORTER_OTLP_ENDPOINT is set, but \\${reason} This server exports no traces or logs until that is fixed.\\`,\n options,\n );\n this.name = 'TelemetryUnavailable';\n }\n}\n`;\n\n/**\n * The entry's `telemetry.ts`: a `startTelemetry()` the server awaits before it\n * imports the app, so the libraries the app loads are instrumented. It returns\n * the Hono middleware that traces each request, or undefined when telemetry is\n * off — the server mounts it ahead of every route.\n *\n * Failing to start telemetry warns (a named `TelemetryUnavailable`, through\n * `process.emitWarning`) and never stops the server: an outage in observability\n * is not a reason to have an outage in the service.\n */\nexport function generateTelemetryModule(\n\ttelemetry: TelemetryContext | undefined,\n): string {\n\tif (!telemetry?.available) {\n\t\treturn `${HEADER}\nexport async function startTelemetry(\n _options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n process.emitWarning(\n new TelemetryUnavailable(\n 'this server was built without @geekmidas/telescope and the @opentelemetry packages it needs. Add them to the app and rebuild.',\n ),\n );\n return undefined;\n}\n`;\n\t}\n\n\tconst options = [\n\t\t`serviceName: ${JSON.stringify(telemetry.serviceName)},`,\n\t\t...(telemetry.serviceNamespace\n\t\t\t? [`serviceNamespace: ${JSON.stringify(telemetry.serviceNamespace)},`]\n\t\t\t: []),\n\t\t// The stage the deploy set, so one service's stages stay apart.\n\t\t'deploymentEnvironment: process.env.STAGE,',\n\t\t// The exporters read OTEL_EXPORTER_OTLP_* themselves, and the SDK reads\n\t\t// OTEL_TRACES_SAMPLER — so no endpoint and no ratio are printed here.\n\t\t// The server's own shutdown decides when the process exits.\n\t\t'handleSignals: false,',\n\t\t// Neither is left to module-load hooks, which see nothing inside a\n\t\t// bundle: @geekmidas/logger emits each record through the logs API\n\t\t// itself, and the middleware returned below opens each request's span.\n\t\t// Hooked as well where they can be, every record and request would be\n\t\t// sent twice.\n\t\t'instrumentPino: false,',\n\t\t'incomingHttpSpans: false,',\n\t];\n\n\treturn `${HEADER}\nexport async function startTelemetry(\n options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n let instrumentation;\n try {\n instrumentation = await import('@geekmidas/telescope/instrumentation');\n } catch (cause) {\n process.emitWarning(\n new TelemetryUnavailable(\n '@geekmidas/telescope/instrumentation or an @opentelemetry package it needs could not be loaded. Install them in the app and rebuild.',\n { cause },\n ),\n );\n return undefined;\n }\n\n instrumentation.setupTelemetry({\n ${options.join('\\n ')}\n });\n\n // Flush what is buffered when the process is told to stop. When nothing\n // else handles the signal, re-raise it once flushed, so the process still\n // stops the way it would have without this listener.\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.once(signal, () => {\n void instrumentation.flushTelemetry().finally(() => {\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n });\n });\n }\n\n // A SERVER span per request, opened by the app itself rather than by\n // hooking node:http: \\`GET /users/:id\\`, continuing an incoming traceparent\n // from the API's own sites and internal callers (a new, linked trace from\n // anyone else), with the handler — its logs, fetches and queries — running\n // inside it.\n return instrumentation.honoTelemetryMiddleware({\n ignorePaths: options.ignorePaths,\n trustedOrigins: options.trustedOrigins,\n });\n}\n`;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport { generateTelemetryModule } from './telemetry';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\t// `traceparent` and `tracestate` always: a site's client sends them when\n\t// its telemetry is on, and a preflight that refused them would fail every\n\t// request it makes rather than only its tracing. The API decides whether\n\t// to continue the trace (it does only for these same origins), so allowing\n\t// the headers grants nothing on its own.\n\tconst allowHeaders = [\n\t\t...new Set([\n\t\t\t'content-type',\n\t\t\t'authorization',\n\t\t\t'traceparent',\n\t\t\t'tracestate',\n\t\t\t...(cors.allowHeaders ?? []),\n\t\t]),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n // The same origins are the ones whose trace context the request spans\n // continue — the server reads them back from \\`createApp\\`.\n trustedOrigins.push(...origins);\n\n honoApp.use('*', cors({\n origin: origins,\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// One registration for every build, production included: each endpoint\n\t\t// is served by HonoEndpoint, which is what `gkm dev` and a feature test\n\t\t// serve it with. Production used to generate its own handlers per\n\t\t// \"tier\", and each was a hand-copy of the adaptor that drifted from it —\n\t\t// a session left undefined, an HttpError answered 500, an auditor\n\t\t// hard-coded to undefined, cookies a handler set never sent.\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ err: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which drivers exist — storage, cache, events — is the entry point's\n// decision: the scheme in each injected URL picks one, so no construct and no\n// application module names a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from './endpoints.js';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n\n // An HttpError a handler or a session callback throws — a 401, a 404 —\n // answers with its own status, as it does under gkm dev. The optimized\n // handlers do not catch, so without this every one of them was a 500.\n // Anything else is a 500 that says nothing about why, and is logged.\n honoApp.onError((error, c) => {\n const http = error as {\n isHttpError?: boolean;\n statusCode?: number;\n statusMessage?: string;\n code?: string;\n details?: unknown;\n };\n if (http.isHttpError === true && typeof http.statusCode === 'number') {\n return c.json(\n {\n name: error.name,\n message: error.message,\n statusCode: http.statusCode,\n statusMessage: http.statusMessage,\n code: http.code,\n details: http.details,\n },\n http.statusCode as 500,\n );\n }\n logger.error({ err: error }, 'Unhandled error');\n return c.json({ message: 'Internal Server Error' }, 500);\n });\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir, context);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\tawait writeFile(\n\t\t\tjoin(outputDir, 'telemetry.ts'),\n\t\t\tgenerateTelemetryModule(context.telemetry),\n\t\t);\n\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\nimport { startTelemetry } from './telemetry.js';\n\n// The API's own sites, known once the app has read its configuration: the\n// origins its CORS allows are the ones whose trace context is continued.\nlet trustedOrigins: readonly string[] = [];\n\n// Before the app is imported, so the libraries it loads are instrumented.\nconst requestSpans = await startTelemetry({\n ignorePaths: [${JSON.stringify(context.production?.healthCheck ?? '/health')}, '/ready'],\n trustedOrigins: () => trustedOrigins,\n});\n\nconst { createApp } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\n// The span middleware goes on before any route, so every request runs in it.\nconst app = new Hono();\nif (requestSpans) app.use('*', requestSpans);\n\nconst created = await createApp(app);\ntrustedOrigins = created.trustedOrigins;\nconst { start } = created;\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n"],"mappings":";;;;;;;AAYA,IAAa,mCAAb,cAAsD,MAAM;CACtC;CAArB,YAAY,YAA6B;EACxC,MACC,wEAAwE,WAAW,6DACpF;EAHoB,KAAA,aAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,sBACf,WACS;CACT,IAAI,OAAO,cAAc,WAAW,OAAO,OAAO,SAAS;CAC3D,MAAM,EAAE,eAAe;CACvB,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,KAAK,aAAa,GAClE,MAAM,IAAI,iCAAiC,UAAU;CAEtD,OAAO,iBAAiB,WAAW;AACpC;;;;;AAMA,SAAgB,cAAc,WAA8C;CAC3E,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,IAAI,cAAc,MAAM,OAAO,CAAC,aAAa;CAC7C,OAAO,CAAC,eAAe,OAAO,UAAU,UAAU,CAAC;AACpD;;AAG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_constructs_endpoints = require("@geekmidas/constructs/endpoints");
6
+ //#region src/generators/clientTelemetry.ts
7
+ /** A `sampleRate` outside 0–1, which no sampler can honour. */
8
+ var InvalidClientTelemetrySampleRate = class extends Error {
9
+ sampleRate;
10
+ constructor(sampleRate) {
11
+ super(`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`);
12
+ this.sampleRate = sampleRate;
13
+ this.name = "InvalidClientTelemetrySampleRate";
14
+ }
15
+ };
16
+ /** The `telemetry` default as the generated module prints it. */
17
+ function printTelemetryDefault(telemetry) {
18
+ if (typeof telemetry === "boolean") return String(telemetry);
19
+ const { sampleRate } = telemetry;
20
+ if (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) throw new InvalidClientTelemetrySampleRate(sampleRate);
21
+ return `{ sampleRate: ${sampleRate} }`;
22
+ }
23
+ /**
24
+ * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and
25
+ * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.
26
+ */
27
+ function telemetryArgs(telemetry) {
28
+ if (!telemetry) return [];
29
+ if (telemetry === true) return ["--telemetry"];
30
+ return ["--telemetry", String(telemetry.sampleRate)];
31
+ }
32
+ /** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */
33
+ function parseTelemetryFlag(value) {
34
+ if (value === void 0 || value === false) return void 0;
35
+ if (value === true) return true;
36
+ return { sampleRate: Number(value) };
37
+ }
38
+ //#endregion
6
39
  //#region src/generators/telemetry.ts
7
40
  /**
8
41
  * Every package `@geekmidas/telescope/instrumentation` loads at runtime.
@@ -69,9 +102,15 @@ const HEADER = `/**
69
102
 
70
103
  import type { MiddlewareHandler } from 'hono';
71
104
 
72
- /** Requests whose spans would only be noise: health checks, by default. */
73
105
  export interface StartTelemetryOptions {
106
+ /** Requests whose spans would only be noise: health checks, by default. */
74
107
  ignorePaths?: string[];
108
+ /**
109
+ * The API's own sites — the origins its CORS allows — read on each request.
110
+ * Their \`traceparent\` is continued, as is an internal caller's; anyone
111
+ * else's starts a new trace linked to the one it claimed.
112
+ */
113
+ trustedOrigins?: () => readonly string[];
75
114
  }
76
115
 
77
116
  /** Telemetry was asked for and cannot start. The server runs without it. */
@@ -153,10 +192,13 @@ export async function startTelemetry(
153
192
  }
154
193
 
155
194
  // A SERVER span per request, opened by the app itself rather than by
156
- // hooking node:http: \`GET /users/:id\`, continuing an incoming traceparent,
157
- // with the handler — its logs, fetches and queries — running inside it.
195
+ // hooking node:http: \`GET /users/:id\`, continuing an incoming traceparent
196
+ // from the API's own sites and internal callers (a new, linked trace from
197
+ // anyone else), with the handler — its logs, fetches and queries — running
198
+ // inside it.
158
199
  return instrumentation.honoTelemetryMiddleware({
159
200
  ignorePaths: options.ignorePaths,
201
+ trustedOrigins: options.trustedOrigins,
160
202
  });
161
203
  }
162
204
  `;
@@ -216,11 +258,13 @@ function corsFor(surface) {
216
258
  setup: ""
217
259
  };
218
260
  const cors = surface.cors ?? {};
219
- const allowHeaders = [
261
+ const allowHeaders = [.../* @__PURE__ */ new Set([
220
262
  "content-type",
221
263
  "authorization",
264
+ "traceparent",
265
+ "tracestate",
222
266
  ...cors.allowHeaders ?? []
223
- ];
267
+ ])];
224
268
  return {
225
269
  imports: `import { cors } from 'hono/cors';`,
226
270
  setup: `
@@ -237,6 +281,10 @@ function corsFor(surface) {
237
281
  }))
238
282
  .parse();
239
283
 
284
+ // The same origins are the ones whose trace context the request spans
285
+ // continue — the server reads them back from \`createApp\`.
286
+ trustedOrigins.push(...origins);
287
+
240
288
  honoApp.use('*', cors({
241
289
  origin: origins,
242
290
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
@@ -505,6 +553,8 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
505
553
 
506
554
  ` : ""}export interface ServerApp {
507
555
  app: HonoType;
556
+ /** The origins this API's CORS allows: its own sites. */
557
+ trustedOrigins: readonly string[];
508
558
  start: (options?: {
509
559
  port?: number;
510
560
  /** Returns the server, so a shutdown can stop it taking requests. */
@@ -548,6 +598,7 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
548
598
  */
549
599
  export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
550
600
  const honoApp = app || new Hono();
601
+ const trustedOrigins: string[] = [];
551
602
  ${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}
552
603
  // Setup HTTP endpoints
553
604
  await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
@@ -555,6 +606,7 @@ ${afterSetupCall}
555
606
 
556
607
  return {
557
608
  app: honoApp,
609
+ trustedOrigins,
558
610
  async start(options) {
559
611
  if (!options?.serve) {
560
612
  throw new Error(
@@ -731,6 +783,8 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
731
783
 
732
784
  ` : ""}export interface ServerApp {
733
785
  app: HonoType;
786
+ /** The origins this API's CORS allows: its own sites. */
787
+ trustedOrigins: readonly string[];
734
788
  start: (options?: {
735
789
  port?: number;
736
790
  serve: (app: HonoType, port: number) => void | Promise<void>;
@@ -742,6 +796,7 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
742
796
  */
743
797
  export async function createApp(app?: HonoType): Promise<ServerApp> {
744
798
  const honoApp = app || new Hono();
799
+ const trustedOrigins: string[] = [];
745
800
 
746
801
  // Health check endpoint (always first)
747
802
  honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
@@ -781,6 +836,7 @@ ${cors.setup}${beforeSetupCall}
781
836
  ${afterSetupCall}
782
837
  return {
783
838
  app: honoApp,
839
+ trustedOrigins,
784
840
  async start(options) {
785
841
  if (!options?.serve) {
786
842
  throw new Error(
@@ -826,9 +882,14 @@ import { serve } from '@hono/node-server';
826
882
  import { Hono } from 'hono';
827
883
  import { startTelemetry } from './telemetry.js';
828
884
 
885
+ // The API's own sites, known once the app has read its configuration: the
886
+ // origins its CORS allows are the ones whose trace context is continued.
887
+ let trustedOrigins: readonly string[] = [];
888
+
829
889
  // Before the app is imported, so the libraries it loads are instrumented.
830
890
  const requestSpans = await startTelemetry({
831
891
  ignorePaths: [${JSON.stringify(context.production?.healthCheck ?? "/health")}, '/ready'],
892
+ trustedOrigins: () => trustedOrigins,
832
893
  });
833
894
 
834
895
  const { createApp } = await import('./app.js');
@@ -839,7 +900,9 @@ const port = Number(process.env.PORT) || 3000;
839
900
  const app = new Hono();
840
901
  if (requestSpans) app.use('*', requestSpans);
841
902
 
842
- const { start } = await createApp(app);
903
+ const created = await createApp(app);
904
+ trustedOrigins = created.trustedOrigins;
905
+ const { start } = created;
843
906
 
844
907
  await start({
845
908
  port,
@@ -862,12 +925,30 @@ Object.defineProperty(exports, "generateTelemetryModule", {
862
925
  return generateTelemetryModule;
863
926
  }
864
927
  });
928
+ Object.defineProperty(exports, "parseTelemetryFlag", {
929
+ enumerable: true,
930
+ get: function() {
931
+ return parseTelemetryFlag;
932
+ }
933
+ });
934
+ Object.defineProperty(exports, "printTelemetryDefault", {
935
+ enumerable: true,
936
+ get: function() {
937
+ return printTelemetryDefault;
938
+ }
939
+ });
865
940
  Object.defineProperty(exports, "runtimeFor", {
866
941
  enumerable: true,
867
942
  get: function() {
868
943
  return runtimeFor;
869
944
  }
870
945
  });
946
+ Object.defineProperty(exports, "telemetryArgs", {
947
+ enumerable: true,
948
+ get: function() {
949
+ return telemetryArgs;
950
+ }
951
+ });
871
952
  Object.defineProperty(exports, "telemetryFor", {
872
953
  enumerable: true,
873
954
  get: function() {
@@ -875,4 +956,4 @@ Object.defineProperty(exports, "telemetryFor", {
875
956
  }
876
957
  });
877
958
 
878
- //# sourceMappingURL=EndpointGenerator-CP6sBvQV.cjs.map
959
+ //# sourceMappingURL=EndpointGenerator-cKlnllIu.cjs.map