@guren/server 2.23.3 → 2.25.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.
Files changed (72) hide show
  1. package/dist/DailyFileChannel-CTTPA0EF.js +114 -0
  2. package/dist/{DocsViewerServiceProvider-DWnlXx_y.js → DocsViewerServiceProvider-CIRNHQ2I.js} +2 -2
  3. package/dist/{authorization-0mCGUFoI.js → Gate-YOt54xGF.js} +2 -217
  4. package/dist/{Job-BVvaY-7p.js → Job-COMzBNOL.js} +3 -10
  5. package/dist/McpServiceProvider-B-LioPSz.js +43 -0
  6. package/dist/Resource-BdYd4J9a.js +1035 -0
  7. package/dist/{loopback-guard-DT9gHF0F.js → ServiceProvider-DDW3MqQJ.js} +10 -68
  8. package/dist/agent/audit-file.d.ts +3 -0
  9. package/dist/agent/audit-sink.d.ts +16 -0
  10. package/dist/agent/call-budget.d.ts +22 -0
  11. package/dist/agent/events.d.ts +6 -6
  12. package/dist/api-token-BbgDEd6j.js +298 -0
  13. package/dist/audit-file-DocumbCr.js +29 -0
  14. package/dist/auth/index.js +2 -1
  15. package/dist/auth/oauth/index.d.ts +7 -0
  16. package/dist/{auth-Jp_MB8Il.js → auth-vFeem6uM.js} +8 -298
  17. package/dist/authorization/index.js +2 -1
  18. package/dist/authorization-BLhwA2Yh.js +217 -0
  19. package/dist/broadcasting/index.js +1 -1
  20. package/dist/{broadcasting-DVfG2vgN.js → broadcasting-BUBCPCnu.js} +1 -1
  21. package/dist/config/define.d.ts +49 -0
  22. package/dist/config/env-reads.d.ts +12 -0
  23. package/dist/config/env.d.ts +122 -0
  24. package/dist/container/Container.d.ts +13 -2
  25. package/dist/container/ServiceProvider.d.ts +7 -0
  26. package/dist/container/bindings.d.ts +8 -0
  27. package/dist/{default-application-Chbrul_m.js → default-application-D5ezhhiV.js} +18 -1
  28. package/dist/encryption/index.js +1 -1
  29. package/dist/{encryption-BRjZnshr.js → encryption-D1dxfMqD.js} +1 -1
  30. package/dist/{endpoint-BXipU2Jj.js → endpoint-CTIzcagh.js} +1 -1
  31. package/dist/{endpoint-Dsw3Acvq.js → endpoint-Coq0K_6I.js} +1 -1
  32. package/dist/events/index.js +1 -1
  33. package/dist/{events-CaJKZ2qk.js → events-c94CdUFc.js} +1 -1
  34. package/dist/http/Application.d.ts +22 -0
  35. package/dist/http/vite-manifest.d.ts +5 -1
  36. package/dist/i18n/index.js +1 -1
  37. package/dist/i18n/injected-translations.d.ts +8 -0
  38. package/dist/i18n/loaders/JsonLoader.d.ts +3 -2
  39. package/dist/{i18n-DRo1g0AN.js → i18n-DqcRD4qL.js} +4 -3
  40. package/dist/index.d.ts +11 -0
  41. package/dist/index.js +525 -1075
  42. package/dist/inertia-defaults-BjrcT7za.js +30 -0
  43. package/dist/internal/request.d.ts +4 -3
  44. package/dist/internal/request.js +2 -1
  45. package/dist/internal/testing.d.ts +17 -0
  46. package/dist/internal/testing.js +6 -0
  47. package/dist/lambda/index.js +1 -1
  48. package/dist/logging/index.js +2 -1
  49. package/dist/{logging-CXotojgW.js → logging-YbKmbAd7.js} +3 -113
  50. package/dist/loopback-guard-CG8xB4v0.js +68 -0
  51. package/dist/mail/index.js +1 -1
  52. package/dist/{mail-zMjQimaJ.js → mail-uRBrUl9q.js} +3 -2
  53. package/dist/mcp/McpServiceProvider.d.ts +21 -4
  54. package/dist/mcp/endpoint.d.ts +3 -3
  55. package/dist/mcp/index.d.ts +0 -2
  56. package/dist/mcp/index.js +2 -2
  57. package/dist/mvc/Controller.d.ts +11 -1
  58. package/dist/mvc/Router.d.ts +6 -0
  59. package/dist/mvc/inertia/InertiaEngine.d.ts +2 -0
  60. package/dist/mvc/validated-input.d.ts +55 -0
  61. package/dist/notifications/index.js +1 -1
  62. package/dist/{notifications-BLid0Y6M.js → notifications-LHuujttf.js} +2 -2
  63. package/dist/providers/ConfigServiceProvider.d.ts +19 -0
  64. package/dist/queue/index.js +2 -2
  65. package/dist/{queue-IdJjqbyJ.js → queue-BiBn5Sff.js} +1 -1
  66. package/dist/resolve-optional-ax6gPWTp.js +9 -0
  67. package/dist/runtime/index.js +2 -1
  68. package/dist/validated-input-D84J8wcC.js +25 -0
  69. package/dist/{vite-manifest-DeWRFXTm.js → vite-manifest-C5kqRoBV.js} +7 -32
  70. package/package.json +6 -3
  71. package/dist/McpServiceProvider-BvJRcDOm.js +0 -458
  72. package/dist/mcp/create-mcp-server.d.ts +0 -180
@@ -0,0 +1,30 @@
1
+ //#region src/support/import-map.ts
2
+ /**
3
+ * Empty, null and undefined entries are dropped, so callers can merge optional
4
+ * overrides without filtering first.
5
+ */
6
+ function parseImportMap(value, options = {}) {
7
+ if (!value) return {};
8
+ try {
9
+ const parsed = JSON.parse(value);
10
+ const result = {};
11
+ for (const [key, entry] of Object.entries(parsed)) if (typeof entry === "string" && entry.length > 0) result[key] = entry;
12
+ return result;
13
+ } catch (error) {
14
+ const label = options.context ?? "import map";
15
+ console.warn(`Failed to parse ${label}. Expected JSON object.`, error);
16
+ return {};
17
+ }
18
+ }
19
+ //#endregion
20
+ //#region src/support/inertia-defaults.ts
21
+ /**
22
+ * The stylesheet *source* path the dev asset configuration falls back to. A
23
+ * leaf module because two sides must agree on it: `http/inertia-assets.ts`
24
+ * publishes it into `GUREN_INERTIA_STYLES` and `mvc/inertia/InertiaEngine.ts`
25
+ * drops exactly this path when a dev server owns the script entry. Importing
26
+ * either from the other would cross the Workers/Lambda boundary or cycle.
27
+ */
28
+ const DEFAULT_DEV_STYLES_ENTRY = "/resources/css/app.css";
29
+ //#endregion
30
+ export { parseImportMap as n, DEFAULT_DEV_STYLES_ENTRY as t };
@@ -2,11 +2,12 @@
2
2
  * The one set of request-reading rules: which content types are read, how a
3
3
  * repeated form field collapses, what an unreadable body falls back to, how a
4
4
  * multipart upload is read, and how repeated query parameters flatten.
5
- * `@guren/testing`'s controller mock wraps its `Request` in a `HonoRequest` and
6
- * calls into these rather than restating them — a second copy is how the two
7
- * came to disagree on an uppercase media type and on a repeated `field[]`.
5
+ * `@guren/testing` imports these instead of restating them. Keep every name: published
6
+ * `@guren/testing` releases import some that its current source does not.
8
7
  * Internal per `contributing/api-stability.md`: reachable only through this
9
8
  * deep import. `parseRequestPayload` beside them is public.
10
9
  */
11
10
  export { parseRequestBody, parseRequestUploads, asRecord, flattenRequestQueries, } from '../http/request.js';
12
11
  export type { RequestBodyContext, RequestQueryContext, RequestUploads, RequestUploadsContext, } from '../http/request.js';
12
+ export { VALIDATED_INPUT_CONTEXT_KEY, readValidatedInput } from '../mvc/validated-input.js';
13
+ export type { UntypedValidatedInput, ValidatedInputRecord } from '../mvc/validated-input.js';
@@ -1,2 +1,3 @@
1
1
  import { i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, t as asRecord } from "../request-CLOYytGP.js";
2
- export { asRecord, flattenRequestQueries, parseRequestBody, parseRequestUploads };
2
+ import { r as readValidatedInput, t as VALIDATED_INPUT_CONTEXT_KEY } from "../validated-input-D84J8wcC.js";
3
+ export { VALIDATED_INPUT_CONTEXT_KEY, asRecord, flattenRequestQueries, parseRequestBody, parseRequestUploads, readValidatedInput };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The framework classes and helpers `@guren/testing`'s controller mock installs as its own
3
+ * exports. A mock that suites install as `@guren/server` itself cannot import
4
+ * that specifier (the factory would be mocking what it imports), so it reaches
5
+ * the same modules through this deep import; `instanceof` then agrees with the runtime.
6
+ * Internal per `contributing/api-stability.md`: reachable only through this path.
7
+ */
8
+ export { Controller } from '../mvc/Controller.js';
9
+ export type { InertiaPageContractLike, InertiaResponseOptions } from '../mvc/Controller.js';
10
+ export { acceptsJson, serializePage } from '../mvc/inertia/InertiaEngine.js';
11
+ export { Resource, JsonResource, collect } from '../http/resources/Resource.js';
12
+ export { ValidationException } from '../errors/exceptions/ValidationException.js';
13
+ export { AuthenticationException } from '../errors/exceptions/AuthenticationException.js';
14
+ export { ServiceProvider } from '../container/ServiceProvider.js';
15
+ export { defineModule } from '../container/defineModule.js';
16
+ export { definePlugin } from '../container/definePlugin.js';
17
+ export { formatValidationErrors } from '../http/request.js';
@@ -0,0 +1,6 @@
1
+ import { _ as acceptsJson, f as definePlugin, i as Controller, n as Resource, r as collect, t as JsonResource, u as defineModule, y as serializePage } from "../Resource-BdYd4J9a.js";
2
+ import { r as formatValidationErrors } from "../request-CLOYytGP.js";
3
+ import { n as ValidationException } from "../errors-JpkcCjjn.js";
4
+ import { n as ServiceProvider } from "../ServiceProvider-DDW3MqQJ.js";
5
+ import { o as AuthenticationException } from "../context-af2n5abO.js";
6
+ export { AuthenticationException, Controller, JsonResource, Resource, ServiceProvider, ValidationException, acceptsJson, collect, defineModule, definePlugin, formatValidationErrors, serializePage };
@@ -1,5 +1,5 @@
1
1
  import { n as detectServerlessRuntime } from "../serverless-D96rJb6x.js";
2
- import { a as getJob } from "../Job-BVvaY-7p.js";
2
+ import { a as getJob } from "../Job-COMzBNOL.js";
3
3
  import { handle } from "hono/aws-lambda";
4
4
  //#region src/lambda/index.ts
5
5
  /** Create an AWS Lambda handler from an already booted Guren application. */
@@ -1,3 +1,4 @@
1
1
  import { n as filterSensitiveData, t as Logger } from "../Logger-DWXdtLSJ.js";
2
- import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "../logging-CXotojgW.js";
2
+ import { a as LOG_LEVEL_PRIORITY, i as matchDailyFileDate, n as dailyFileDateStamp, r as dailyFilePath, t as DailyFileChannel } from "../DailyFileChannel-CTTPA0EF.js";
3
+ import { a as FileChannel, i as setLogManager, n as createLogManager, o as ConsoleChannel, r as getLogManager, t as LogManager } from "../logging-YbKmbAd7.js";
3
4
  export { ConsoleChannel, DailyFileChannel, FileChannel, LOG_LEVEL_PRIORITY, LogManager, Logger, createLogManager, dailyFileDateStamp, dailyFilePath, filterSensitiveData, getLogManager, matchDailyFileDate, setLogManager };
@@ -1,20 +1,8 @@
1
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
1
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
2
2
  import { r as isPromiseLike, t as Logger } from "./Logger-DWXdtLSJ.js";
3
+ import { a as LOG_LEVEL_PRIORITY, t as DailyFileChannel } from "./DailyFileChannel-CTTPA0EF.js";
3
4
  import * as path$1 from "node:path";
4
5
  import * as fs from "node:fs";
5
- //#region src/logging/types.ts
6
- /** Log level priority (lower = more severe). */
7
- const LOG_LEVEL_PRIORITY = {
8
- emergency: 0,
9
- alert: 1,
10
- critical: 2,
11
- error: 3,
12
- warning: 4,
13
- notice: 5,
14
- info: 6,
15
- debug: 7
16
- };
17
- //#endregion
18
6
  //#region src/logging/channels/ConsoleChannel.ts
19
7
  const LEVEL_COLORS = {
20
8
  emergency: "\x1B[41m\x1B[37m",
@@ -118,104 +106,6 @@ var FileChannel = class {
118
106
  close() {}
119
107
  };
120
108
  //#endregion
121
- //#region src/logging/daily-file-path.ts
122
- /**
123
- * The one rule for what a daily-rotated log file is called:
124
- * `dir/name-YYYY-MM-DD.ext`. {@link DailyFileChannel} names what it appends to
125
- * through this module, and the audit reader behind `guren tool:log` decides
126
- * what to read through the same one; a second copy drifts silently, leaving an
127
- * empty audit trail rather than an error. Naming only — nothing here touches
128
- * the filesystem, so a caller keeps "missing" and "unreadable" apart itself.
129
- */
130
- /**
131
- * The `YYYY-MM-DD` stamp a file rotated at `date` carries. UTC, because the
132
- * rotation boundary must be the same instant for every process appending to one
133
- * directory — a fleet across time zones would write two files for one day.
134
- */
135
- function dailyFileDateStamp(date) {
136
- return date.toISOString().slice(0, 10);
137
- }
138
- /** The dated file a base path rotates to on `date`. */
139
- function dailyFilePath(basePath, date) {
140
- const { dir, name, ext } = path$1.parse(basePath);
141
- return path$1.join(dir, `${name}-${dailyFileDateStamp(date)}${ext}`);
142
- }
143
- /**
144
- * The date stamp of `fileName` if it is one of `basePath`'s dated files, else
145
- * `null` — the inverse of {@link dailyFilePath}. The base name and extension
146
- * are escaped first: `app.v1.log` would otherwise match another app's files
147
- * into this rotation set, which for the cleanup consuming it means deleting them.
148
- */
149
- function matchDailyFileDate(basePath, fileName) {
150
- const { name, ext } = path$1.parse(basePath);
151
- return new RegExp(`^${escapeRegExp(name)}-(\\d{4}-\\d{2}-\\d{2})${escapeRegExp(ext)}$`, "u").exec(fileName)?.[1] ?? null;
152
- }
153
- /** Every character with meaning inside a regular expression, made literal. */
154
- function escapeRegExp(text) {
155
- return text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
156
- }
157
- //#endregion
158
- //#region src/logging/channels/DailyFileChannel.ts
159
- /** Daily rotating file log channel. */
160
- var DailyFileChannel = class {
161
- config;
162
- minLevel;
163
- currentDate = null;
164
- currentFilePath = null;
165
- constructor(config) {
166
- this.config = {
167
- days: 14,
168
- format: "text",
169
- ...config
170
- };
171
- this.minLevel = LOG_LEVEL_PRIORITY[this.config.level ?? "debug"];
172
- }
173
- log(entry) {
174
- if (LOG_LEVEL_PRIORITY[entry.level] > this.minLevel) return;
175
- const dateStr = dailyFileDateStamp(entry.timestamp);
176
- if (this.currentDate !== dateStr) this.rotate(entry.timestamp, dateStr);
177
- const line = this.format(entry) + "\n";
178
- this.write(line);
179
- }
180
- write(data) {
181
- if (this.currentFilePath) fs.appendFileSync(this.currentFilePath, data);
182
- }
183
- rotate(date, dateStr) {
184
- this.currentDate = dateStr;
185
- this.currentFilePath = dailyFilePath(this.config.path, date);
186
- this.ensureDirectory(this.currentFilePath);
187
- this.cleanup();
188
- }
189
- ensureDirectory(filePath) {
190
- const dir = path$1.dirname(filePath);
191
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
192
- }
193
- cleanup() {
194
- const dir = path$1.dirname(this.config.path);
195
- if (!fs.existsSync(dir)) return;
196
- const files = fs.readdirSync(dir);
197
- const cutoff = /* @__PURE__ */ new Date();
198
- cutoff.setDate(cutoff.getDate() - (this.config.days ?? 14));
199
- for (const file of files) {
200
- const stamp = matchDailyFileDate(this.config.path, file);
201
- if (stamp !== null && new Date(stamp) < cutoff) fs.unlinkSync(path$1.join(dir, file));
202
- }
203
- }
204
- format(entry) {
205
- if (this.config.format === "json") return JSON.stringify({
206
- timestamp: entry.timestamp.toISOString(),
207
- level: entry.level,
208
- message: entry.message,
209
- ...entry.context
210
- });
211
- const timestamp = entry.timestamp.toISOString();
212
- const level = entry.level.toUpperCase().padEnd(9);
213
- const context = Object.keys(entry.context).length > 0 ? " " + JSON.stringify(entry.context) : "";
214
- return `[${timestamp}] ${level} ${entry.message}${context}`;
215
- }
216
- close() {}
217
- };
218
- //#endregion
219
109
  //#region src/logging/LogManager.ts
220
110
  /** Log manager for managing multiple logging channels. */
221
111
  var LogManager = class {
@@ -370,4 +260,4 @@ function getLogManager() {
370
260
  return manager;
371
261
  }
372
262
  //#endregion
373
- export { DailyFileChannel as a, matchDailyFileDate as c, LOG_LEVEL_PRIORITY as d, setLogManager as i, FileChannel as l, createLogManager as n, dailyFileDateStamp as o, getLogManager as r, dailyFilePath as s, LogManager as t, ConsoleChannel as u };
263
+ export { FileChannel as a, setLogManager as i, createLogManager as n, ConsoleChannel as o, getLogManager as r, LogManager as t };
@@ -0,0 +1,68 @@
1
+ //#region src/http/middleware/loopback-guard.ts
2
+ const LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "[::1]"]);
3
+ const LOOPBACK_IPV4 = /^127\.\d+\.\d+\.\d+$/;
4
+ /**
5
+ * Whether an `Origin` header value belongs to the developer's own machine.
6
+ * Only a web page's request carries one; restricting it to loopback blocks
7
+ * cross-site requests and DNS rebinding (an attacker's domain resolving to
8
+ * 127.0.0.1 so the browser skips preflight). A *negative* filter only: any
9
+ * non-browser client sets the header with one flag, so never use it to satisfy the peer check.
10
+ */
11
+ function isLoopbackOrigin(origin) {
12
+ try {
13
+ const { hostname } = new URL(origin);
14
+ return LOOPBACK_HOSTNAMES.has(hostname) || LOOPBACK_IPV4.test(hostname);
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+ /**
20
+ * Whether a socket peer address belongs to this machine.
21
+ *
22
+ * Bun reports IPv4-mapped peers as `::ffff:127.0.0.1`, so unwrap that prefix
23
+ * before matching.
24
+ */
25
+ function isLoopbackAddress(address) {
26
+ const normalized = address.startsWith("::ffff:") ? address.slice(7) : address;
27
+ return normalized === "::1" || LOOPBACK_IPV4.test(normalized);
28
+ }
29
+ /**
30
+ * The peer address of the current request, when the runtime exposes one.
31
+ * `Bun.serve` passes `{ server }` through Hono's env, wired by
32
+ * `Application.listen()`; proxy headers are attacker-controlled and ignored.
33
+ * `undefined` means "the runtime did not say", not "remote": no `server` in env
34
+ * (Node, Vercel's `app.fetch(request)`, in-process tests), or `requestIP()` null (closed or non-TCP socket).
35
+ */
36
+ function clientAddress(ctx) {
37
+ const env = ctx.env;
38
+ if (typeof env?.server?.requestIP !== "function") return;
39
+ return env.server.requestIP(ctx.req.raw)?.address;
40
+ }
41
+ /**
42
+ * Whether the operator accepted serving these endpoints on a runtime that
43
+ * cannot report the socket peer.
44
+ *
45
+ * Read per request, and written in the plain `process.env.X` form for the
46
+ * same bundler reason as the endpoint gates (see `mcp/endpoint.ts`).
47
+ */
48
+ function allowsUnverifiedPeer() {
49
+ return typeof process !== "undefined" && process.env.GUREN_ALLOW_UNVERIFIED_PEER === "1";
50
+ }
51
+ /**
52
+ * Restricts an endpoint to the developer's own machine. `resource` names the
53
+ * endpoint in the 403 body (e.g. "the MCP endpoint"). The two denials say
54
+ * different things on purpose: a present non-loopback peer is a remote caller,
55
+ * a peer the runtime never reported is a deployment the guard cannot vouch for.
56
+ */
57
+ function createLoopbackGuard(resource) {
58
+ return async (ctx, next) => {
59
+ const origin = ctx.req.header("origin");
60
+ if (origin !== void 0 && !isLoopbackOrigin(origin)) return ctx.json({ message: `Forbidden: cross-origin request to ${resource}` }, 403);
61
+ const address = clientAddress(ctx);
62
+ if (address !== void 0 && !isLoopbackAddress(address)) return ctx.json({ message: `Forbidden: remote request to ${resource}` }, 403);
63
+ if (address === void 0 && !allowsUnverifiedPeer()) return ctx.json({ message: `Forbidden: this runtime does not report the peer address, so ${resource} cannot confirm the request came from this machine. Serve the app with Application.listen() on Bun, or set GUREN_ALLOW_UNVERIFIED_PEER=1 to accept requests from anywhere the process is reachable.` }, 403);
64
+ await next();
65
+ };
66
+ }
67
+ //#endregion
68
+ export { createLoopbackGuard as t };
@@ -1,2 +1,2 @@
1
- import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "../mail-zMjQimaJ.js";
1
+ import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "../mail-uRBrUl9q.js";
2
2
  export { LogTransport, Mail, MailManager, MemoryTransport, ResendTransport, SmtpTransport, createMailManager, getMailManager, mail, setMailManager };
@@ -1,5 +1,6 @@
1
- import { c as pinnedQueueDriver, d as resolveQueueDriver, i as enqueueJob, l as registerJob, p as resolveOptional, t as Job } from "./Job-BVvaY-7p.js";
2
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
1
+ import { t as resolveOptional } from "./resolve-optional-ax6gPWTp.js";
2
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
3
+ import { c as pinnedQueueDriver, d as resolveQueueDriver, i as enqueueJob, l as registerJob, t as Job } from "./Job-COMzBNOL.js";
3
4
  import { t as parseMailAddress } from "./address-D0Iq-XIH.js";
4
5
  import nodemailer from "nodemailer";
5
6
  //#region src/mail/transports/SmtpTransport.ts
@@ -1,9 +1,26 @@
1
1
  import { ServiceProvider } from '../container/ServiceProvider.js';
2
2
  /**
3
- * Registers the MCP endpoint at /_guren/mcp, so AI coding agents can introspect
4
- * the project, run integrity checks, and scaffold code. Only active while
5
- * `isMcpEndpointEnabled()` holds — the same `GUREN_MCP=1` opt-in that exempts
6
- * the endpoint from CSRF. @guren/cli is imported dynamically to break a cycle.
3
+ * What this provider calls on `@guren/cli`, spelled here: the package cannot be
4
+ * declared as a dependency (it depends on this one), so an imported type would
5
+ * build as `any`. Same seam as `DocsViewerServiceProvider`'s.
6
+ */
7
+ export interface DevMcpCliApi {
8
+ createDevMcpHandler?(options: {
9
+ cwd: string;
10
+ }): {
11
+ fetch(request: Request): Promise<Response>;
12
+ };
13
+ }
14
+ export declare const DEV_MCP_CLI_TOO_OLD: string;
15
+ /** Whether this CLI ships the Dev MCP factory; `DEV_MCP_CLI_TOO_OLD` says what to do when it does not. */
16
+ export declare function canServeDevMcp(cli: DevMcpCliApi): cli is DevMcpCliApi & {
17
+ createDevMcpHandler: NonNullable<DevMcpCliApi['createDevMcpHandler']>;
18
+ };
19
+ /**
20
+ * Mounts the Dev MCP endpoint at /_guren/mcp while `isMcpEndpointEnabled()` holds.
21
+ * The server lives in @guren/cli (RFC 0028 §1), which every deploy target stubs, so
22
+ * this package imports no MCP SDK code.
23
+ * @experimental
7
24
  */
8
25
  export declare class McpServiceProvider extends ServiceProvider {
9
26
  register(): void;
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Identity and activation rules for the dev-only MCP endpoint. Free of MCP SDK
3
- * imports so middleware (CSRF) and the app bootstrap can reason about the
4
- * endpoint without `@modelcontextprotocol/sdk`, which apps need not install.
2
+ * Identity and activation rules for the dev-only MCP endpoint, which middleware
3
+ * (CSRF) and the app bootstrap read without mounting it. The server itself lives
4
+ * in `@guren/cli` (RFC 0028 §1).
5
5
  */
6
6
  import type { MiddlewareHandler } from 'hono';
7
7
  export { isLoopbackAddress, isLoopbackOrigin } from '../http/middleware/loopback-guard.js';
@@ -1,3 +1 @@
1
- export { createMcpServer } from './create-mcp-server.js';
2
- export type { CreateMcpServerOptions } from './create-mcp-server.js';
3
1
  export { McpServiceProvider } from './McpServiceProvider.js';
package/dist/mcp/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { r as createMcpServer, t as McpServiceProvider } from "../McpServiceProvider-BvJRcDOm.js";
2
- export { McpServiceProvider, createMcpServer };
1
+ import { t as McpServiceProvider } from "../McpServiceProvider-B-LioPSz.js";
2
+ export { McpServiceProvider };
@@ -7,6 +7,7 @@ import { type RegisteredTranslationKey, type ReplacementValues } from '../i18n/i
7
7
  import type { AuthContext } from '../auth/types.js';
8
8
  import type { ServiceBindings } from '../container/bindings.js';
9
9
  import type { ContainerLike } from '../container/types.js';
10
+ import { type ContractRouteName, type UntypedValidatedInput, type ValidatedInput } from './validated-input.js';
10
11
  /** Duck-typed Zod-like schema, so validation needs no direct Zod dependency. */
11
12
  interface ZodLikeSchema<T> {
12
13
  safeParse(data: unknown): {
@@ -69,7 +70,7 @@ export interface RedirectOptions {
69
70
  status?: number;
70
71
  headers?: HeadersInit;
71
72
  }
72
- type InertiaResponseOptions = Omit<InertiaOptions, 'url' | 'request' | 'container'> & {
73
+ export type InertiaResponseOptions = Omit<InertiaOptions, 'url' | 'request' | 'container'> & {
73
74
  url?: string;
74
75
  };
75
76
  type InertiaPageComponent<TPage extends InertiaPageContractLike> = TPage['id'];
@@ -181,6 +182,15 @@ export declare class Controller {
181
182
  protected has(key: string): Promise<boolean>;
182
183
  /** Flatten query string arrays to scalar values for cleaner schema usage. */
183
184
  private flattenQueries;
185
+ /**
186
+ * The input the route contract already validated: `params`, `query` and `body`
187
+ * as their schemas parsed them, coercions and defaults applied. A segment the
188
+ * contract does not declare is `undefined`. Pass the route name to type the
189
+ * result from `guren codegen`, or every name when one action serves several
190
+ * routes; a name that is not the current route's throws.
191
+ */
192
+ protected validated(): UntypedValidatedInput;
193
+ protected validated<TName extends ContractRouteName>(route: TName | readonly TName[]): ValidatedInput<TName>;
184
194
  /** Validate the request body; throws ValidationException on failure. */
185
195
  protected validateBody<T>(schema: ZodLikeSchema<T>): Promise<T>;
186
196
  /** Validate query parameters; throws ValidationException on failure. */
@@ -157,6 +157,12 @@ export interface RouteDefinition {
157
157
  };
158
158
  /** Route model bindings: param name → bound model class name (from `bind`) */
159
159
  bindings?: Record<string, string>;
160
+ /**
161
+ * `true` when a request to this route is refused with 422 unless its body
162
+ * satisfies `schemas.body`, controller actions included. A reader of another
163
+ * server version's definitions treats an absent flag as not enforced.
164
+ */
165
+ validatesBody?: true;
160
166
  /** Agent metadata as declared (RFC 0016), no defaults applied. Absent: not a tool. */
161
167
  agent?: AgentRouteMetadata;
162
168
  /** Still on its fixture (RFC 0021): registered with the `prototype` handler rather than a controller. */
@@ -102,4 +102,6 @@ export declare function setInertiaDocument(options: InertiaDocumentOptions | und
102
102
  */
103
103
  export declare function setInertiaSsrRenderer(renderer: InertiaSsrRenderer | undefined): void;
104
104
  export declare function inertia(component: string, props: Record<string, unknown>, options?: InertiaOptions): Promise<Response>;
105
+ export declare function serializePage(page: InertiaPagePayload): string;
106
+ export declare function acceptsJson(request: Request): boolean;
105
107
  export {};
@@ -0,0 +1,55 @@
1
+ import type { Context } from 'hono';
2
+ import type { RequestContextLike } from '../http/request-container.js';
3
+ /**
4
+ * Registry for the app's route contracts: `guren codegen` merges a `routes` map
5
+ * (route name → the parsed `params`/`query`/`body` its contract declares) into
6
+ * this interface. Left empty, `Controller.validated()` accepts any route name.
7
+ */
8
+ export interface GurenRouteContracts {
9
+ }
10
+ type RegisteredRouteContracts = GurenRouteContracts extends {
11
+ routes: infer R extends object;
12
+ } ? R : never;
13
+ /** A route name `Controller.validated()` accepts: a registered one after codegen, any string before. */
14
+ export type ContractRouteName = [RegisteredRouteContracts] extends [never] ? string : keyof RegisteredRouteContracts & string;
15
+ /** What `Controller.validated()` returns when no contract type is registered for the route. */
16
+ export interface UntypedValidatedInput {
17
+ params: Record<string, any> | undefined;
18
+ query: Record<string, any> | undefined;
19
+ body: any;
20
+ }
21
+ type SegmentOf<TEntry, TKey extends string> = TEntry extends {
22
+ [K in TKey]: infer T;
23
+ } ? T : undefined;
24
+ /** The contract-parsed input of one route. A segment the contract does not declare is `undefined`. */
25
+ export type ValidatedInput<TName extends string = string> = [RegisteredRouteContracts] extends [never] ? UntypedValidatedInput : TName extends keyof RegisteredRouteContracts ? {
26
+ params: SegmentOf<RegisteredRouteContracts[TName], 'params'>;
27
+ query: SegmentOf<RegisteredRouteContracts[TName], 'query'>;
28
+ body: SegmentOf<RegisteredRouteContracts[TName], 'body'>;
29
+ } : UntypedValidatedInput;
30
+ /** The request-scoped record the contract middleware leaves for the controller action. */
31
+ export interface ValidatedInputRecord {
32
+ /** The route's name at mount time, so a `validated('other.route')` call can be refused. */
33
+ route: string | undefined;
34
+ params?: unknown;
35
+ query?: unknown;
36
+ body?: unknown;
37
+ /** The payload the body schema parsed; boxed because `null` and `''` are parsed bodies too. */
38
+ rawBody?: {
39
+ value: unknown;
40
+ };
41
+ }
42
+ export declare const VALIDATED_INPUT_CONTEXT_KEY = "guren.validatedInput";
43
+ declare module 'hono' {
44
+ interface ContextVariableMap {
45
+ [VALIDATED_INPUT_CONTEXT_KEY]: ValidatedInputRecord;
46
+ }
47
+ }
48
+ export declare function getValidatedInput(ctx: RequestContextLike): ValidatedInputRecord | undefined;
49
+ export declare function setValidatedInput(ctx: Context, record: ValidatedInputRecord): void;
50
+ /**
51
+ * `Controller.validated()`, shared with `@guren/testing`'s controller mock so the
52
+ * two refuse the same calls. `route` lists every name the action is mounted on.
53
+ */
54
+ export declare function readValidatedInput(ctx: RequestContextLike, route?: string | readonly string[]): UntypedValidatedInput;
55
+ export {};
@@ -1,2 +1,2 @@
1
- import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "../notifications-BLid0Y6M.js";
1
+ import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "../notifications-LHuujttf.js";
2
2
  export { DatabaseChannel, MailChannel, MemoryChannel, Notification, NotificationManager, SlackChannel, clearNotificationRegistry, createNotificationManager, getNotification, getNotificationManager, registerNotification, resolveNotifiableType, setNotificationManager };
@@ -1,5 +1,5 @@
1
- import { l as registerJob, t as Job } from "./Job-BVvaY-7p.js";
2
- import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-Chbrul_m.js";
1
+ import { h as warnDeprecatedSetter, i as bindAmbient, m as warnDeprecatedGetter, n as ambientBinding } from "./default-application-D5ezhhiV.js";
2
+ import { l as registerJob, t as Job } from "./Job-COMzBNOL.js";
3
3
  import { t as parseMailAddress } from "./address-D0Iq-XIH.js";
4
4
  //#region src/notifications/Notification.ts
5
5
  /**
@@ -0,0 +1,19 @@
1
+ import { ServiceProvider, type OwnedBinding } from '../container/ServiceProvider.js';
2
+ /**
3
+ * Validates `createApp({ env })` and binds it as `env`, then resolves and binds
4
+ * each `createApp({ config })` definition (RFC 0027 §1-§3). Registered before
5
+ * every other provider: a bad environment fails the boot before anything
6
+ * registers, every later register() sees the configured managers, and a later
7
+ * provider that rebinds one fails the boot through {@link ownedBindings}.
8
+ */
9
+ export declare class ConfigServiceProvider extends ServiceProvider {
10
+ private env;
11
+ private unset;
12
+ private resolved;
13
+ private owned;
14
+ register(): void;
15
+ boot(): Promise<void>;
16
+ /** @internal The bindings the definitions made, for ProviderManager's twice-configured check. */
17
+ ownedBindings(): ReadonlyMap<string, OwnedBinding>;
18
+ private parseEnv;
19
+ }
@@ -1,3 +1,3 @@
1
- import { a as getJob, d as resolveQueueDriver, f as setQueueDriver, l as registerJob, n as clearJobRegistry, o as getQueueDriver, r as clearQueueDriver, s as getRegisteredJobs, t as Job, u as resolveJobName } from "../Job-BVvaY-7p.js";
2
- import { a as processJob, c as RedisDriver, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver } from "../queue-IdJjqbyJ.js";
1
+ import { a as getJob, d as resolveQueueDriver, f as setQueueDriver, l as registerJob, n as clearJobRegistry, o as getQueueDriver, r as clearQueueDriver, s as getRegisteredJobs, t as Job, u as resolveJobName } from "../Job-COMzBNOL.js";
2
+ import { a as processJob, c as RedisDriver, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver } from "../queue-BiBn5Sff.js";
3
3
  export { FailedJobReporter, Job, MemoryDriver, QueueManager, RedisDriver, SqsDriver, SyncDriver, Worker, clearJobRegistry, clearQueueDriver, createQueueManager, createSqsAdapter, getJob, getQueueDriver, getRegisteredJobs, processJob, registerJob, resolveJobName, resolveQueueDriver, setQueueDriver };
@@ -1,4 +1,4 @@
1
- import { a as getJob, i as enqueueJob } from "./Job-BVvaY-7p.js";
1
+ import { a as getJob, i as enqueueJob } from "./Job-COMzBNOL.js";
2
2
  //#region src/queue/drivers/MemoryDriver.ts
3
3
  /** In-memory queue driver for development and testing. */
4
4
  var MemoryDriver = class {
@@ -0,0 +1,9 @@
1
+ //#region src/container/resolve-optional.ts
2
+ function resolveOptional(container, key) {
3
+ if (!container) return;
4
+ const optional = container.makeOptional;
5
+ if (typeof optional === "function") return optional.call(container, key);
6
+ return container.has?.(key) ? container.make(key) : void 0;
7
+ }
8
+ //#endregion
9
+ export { resolveOptional as t };
@@ -1,6 +1,7 @@
1
1
  import { n as trimTrailingSlashes } from "../trim-slashes-BLY9hKAa.js";
2
- import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-DeWRFXTm.js";
2
+ import { n as parseImportMap } from "../inertia-defaults-BjrcT7za.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
+ import { a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-C5kqRoBV.js";
4
5
  import { createRequire } from "node:module";
5
6
  import { dirname, extname, join, resolve, sep } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
@@ -0,0 +1,25 @@
1
+ //#region src/mvc/validated-input.ts
2
+ const VALIDATED_INPUT_CONTEXT_KEY = "guren.validatedInput";
3
+ function getValidatedInput(ctx) {
4
+ return ctx.get(VALIDATED_INPUT_CONTEXT_KEY);
5
+ }
6
+ function setValidatedInput(ctx, record) {
7
+ ctx.set(VALIDATED_INPUT_CONTEXT_KEY, record);
8
+ }
9
+ /**
10
+ * `Controller.validated()`, shared with `@guren/testing`'s controller mock so the
11
+ * two refuse the same calls. `route` lists every name the action is mounted on.
12
+ */
13
+ function readValidatedInput(ctx, route) {
14
+ const record = getValidatedInput(ctx);
15
+ if (!record) throw new Error("Controller.validated() found no contract-validated input: the route declares no `params`, `query` or `body` schema. Add one to the route options, or use validateBody()/validateQuery()/validateParams(). In a controller unit test, seed it with contractInput().");
16
+ const names = typeof route === "string" ? [route] : route;
17
+ if (names && (record.route === void 0 || !names.includes(record.route))) throw new Error(`Controller.validated(${JSON.stringify(route)}) was called while serving ${record.route === void 0 ? "an unnamed route" : `route '${record.route}'`}. Pass the name of every route this action is mounted on.`);
18
+ return {
19
+ params: record.params,
20
+ query: record.query,
21
+ body: record.body
22
+ };
23
+ }
24
+ //#endregion
25
+ export { setValidatedInput as i, getValidatedInput as n, readValidatedInput as r, VALIDATED_INPUT_CONTEXT_KEY as t };