@guren/server 2.20.0 → 2.21.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.
package/dist/index.js CHANGED
@@ -5,20 +5,20 @@ import { _ as setGate, a as withAuthorization, b as mergeCapabilities, c as Gate
5
5
  import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, s as AGENT_PREFLIGHT_VERDICT_HEADER, t as PREFLIGHT_ARGUMENT } from "./dispatch-BAwzftws.js";
6
6
  import { t as trimSlashes } from "./trim-slashes-BLY9hKAa.js";
7
7
  import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
8
- import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-CvDwk2Gj.js";
9
- import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
10
8
  import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
11
9
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
12
- import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-BXcHQwHf.js";
10
+ import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, _t as getSessionFromContext, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as defaultCookieSecure, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-CjE2oO50.js";
11
+ import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-CdfPfQdj.js";
12
+ import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-CvDwk2Gj.js";
13
+ import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
13
14
  import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-D2DFd8xX.js";
14
15
  import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-CXk_umpT.js";
15
16
  import { n as filterSensitiveData, t as Logger } from "./Logger-DFifRAtc.js";
16
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-DUhlolkJ.js";
17
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-thXRnaju.js";
17
18
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
18
19
  import { r as isMcpEndpointEnabled } from "./endpoint-Dsw3Acvq.js";
19
20
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
20
- import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-Cg1aajRP.js";
21
- import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-BZQ-75hf.js";
21
+ import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-BZ2VrSud.js";
22
22
  import { r as isDocsViewerEnabled } from "./endpoint-BXipU2Jj.js";
23
23
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
24
24
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
@@ -30,17 +30,17 @@ import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY
30
30
  import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-B5RzB0A2.js";
31
31
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-S0OvCuR8.js";
32
32
  import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-uwP3Di4D.js";
33
- import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-BB59f07j.js";
33
+ import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-D_yNe54O.js";
34
34
  import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "./health-DQSvUplL.js";
35
35
  import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-C6tcOtUl.js";
36
36
  import { Hono } from "hono";
37
37
  import { deleteCookie, getCookie } from "hono/cookie";
38
38
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
39
+ import { isAbsolute, join, resolve as resolve$1 } from "node:path";
40
+ import { pathToFileURL } from "node:url";
39
41
  import { cors } from "hono/cors";
40
42
  import { createMiddleware } from "hono/factory";
41
43
  import { parseAccept } from "hono/utils/accept";
42
- import { isAbsolute, join, resolve as resolve$1 } from "node:path";
43
- import { pathToFileURL } from "node:url";
44
44
  import { serialize } from "hono/utils/cookie";
45
45
  import { existsSync } from "node:fs";
46
46
  import * as readline from "readline";
@@ -61,49 +61,549 @@ function ensureErrorStackTracePolyfill() {
61
61
  patched = true;
62
62
  return;
63
63
  }
64
- Error.captureStackTrace = (target, constructorOpt) => {
65
- if (target instanceof Error) try {
66
- return capture(target, constructorOpt);
67
- } catch {}
68
- const placeholder = /* @__PURE__ */ new Error();
69
- capture(placeholder, constructorOpt);
70
- copyStackFromError(target, placeholder);
71
- return target;
64
+ Error.captureStackTrace = (target, constructorOpt) => {
65
+ if (target instanceof Error) try {
66
+ return capture(target, constructorOpt);
67
+ } catch {}
68
+ const placeholder = /* @__PURE__ */ new Error();
69
+ capture(placeholder, constructorOpt);
70
+ copyStackFromError(target, placeholder);
71
+ return target;
72
+ };
73
+ patched = true;
74
+ }
75
+ function copyStackFromNewError(target) {
76
+ copyStackFromError(target, /* @__PURE__ */ new Error());
77
+ }
78
+ function copyStackFromError(target, source) {
79
+ if (!target || typeof target !== "object") return;
80
+ if (source.stack) Object.defineProperty(target, "stack", {
81
+ configurable: true,
82
+ enumerable: false,
83
+ writable: true,
84
+ value: source.stack
85
+ });
86
+ if (source.name && !("name" in target)) Object.defineProperty(target, "name", {
87
+ configurable: true,
88
+ enumerable: false,
89
+ writable: true,
90
+ value: source.name
91
+ });
92
+ if (source.message && !("message" in target)) Object.defineProperty(target, "message", {
93
+ configurable: true,
94
+ enumerable: false,
95
+ writable: true,
96
+ value: source.message
97
+ });
98
+ }
99
+ //#endregion
100
+ //#region src/mvc/mount-route.ts
101
+ /**
102
+ * Mounts a route with a dynamic HTTP method string. Hono's `app.on()` overloads
103
+ * expect literal method types, so this helper holds the one narrowing cast.
104
+ */
105
+ function mountRoute(app, method, path, ...handlers) {
106
+ app.on(method, path, ...handlers);
107
+ }
108
+ //#endregion
109
+ //#region src/mvc/inertia/InertiaEngine.ts
110
+ ensureErrorStackTracePolyfill();
111
+ let documentOptions;
112
+ /**
113
+ * Register app-wide document defaults for server-rendered Inertia responses;
114
+ * call it at module scope in the app entry so every runtime picks it up.
115
+ * Process-wide, not request-scoped: calling it mid-flight leaks the policy into
116
+ * in-flight requests — use the {@link InertiaOptions} fields per response.
117
+ * Values are emitted verbatim, so never pass user input. `undefined` clears.
118
+ */
119
+ function setInertiaDocument(options) {
120
+ documentOptions = options;
121
+ }
122
+ let defaultSsrRenderer;
123
+ /**
124
+ * Register a process-wide default SSR renderer, for adapters whose bundler
125
+ * cannot resolve a runtime path (Workers has no filesystem for
126
+ * `GUREN_INERTIA_SSR_ENTRY`'s dynamic import). Per-call `ssr.render` still
127
+ * wins; `undefined` clears (test isolation).
128
+ */
129
+ function setInertiaSsrRenderer(renderer) {
130
+ defaultSsrRenderer = renderer;
131
+ }
132
+ const DEFAULT_TITLE = "Guren";
133
+ const DEV_FALLBACK_IMPORT_MAP = {
134
+ react: "https://esm.sh/react@19.0.0?dev",
135
+ "react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
136
+ "react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
137
+ "react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
138
+ "@guren/inertia-client": "/vendor/inertia-client.tsx",
139
+ "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
140
+ };
141
+ async function inertia(component, props, options = {}) {
142
+ const resolvedVersion = options.version ?? process.env.GUREN_INERTIA_VERSION ?? void 0;
143
+ const page = {
144
+ component,
145
+ props,
146
+ url: options.url ?? inertiaPageUrl(options.request) ?? "",
147
+ version: resolvedVersion
148
+ };
149
+ const request = options.request;
150
+ const isInertiaVisit = Boolean(request?.headers.get("X-Inertia"));
151
+ const prefersJson = request ? acceptsJson(request) : false;
152
+ const versionHeader = resolvedVersion ? { "X-Inertia-Version": resolvedVersion } : {};
153
+ if (request && resolvedVersion && isInertiaVisit && request.method === "GET") {
154
+ if (request.headers.get("X-Inertia-Version") !== resolvedVersion) return new Response(null, {
155
+ status: 409,
156
+ headers: {
157
+ "X-Inertia-Location": options.url ?? request.url,
158
+ Vary: "Accept"
159
+ }
160
+ });
161
+ }
162
+ if (isInertiaVisit || prefersJson) return new Response(serializePage(page), {
163
+ status: options.status ?? 200,
164
+ headers: {
165
+ "Content-Type": "application/json; charset=utf-8",
166
+ "X-Inertia": "true",
167
+ Vary: "Accept",
168
+ ...versionHeader,
169
+ ...options.headers
170
+ }
171
+ });
172
+ const html = await renderDocument$1(page, options);
173
+ return new Response(html, {
174
+ status: options.status ?? 200,
175
+ headers: {
176
+ "Content-Type": "text/html; charset=utf-8",
177
+ "X-Inertia": "true",
178
+ Vary: "Accept",
179
+ ...versionHeader,
180
+ ...options.headers
181
+ }
182
+ });
183
+ }
184
+ /**
185
+ * The Inertia protocol's page `url` is the request path plus query string, kept
186
+ * relative. Derived from the request when the caller does not override it.
187
+ */
188
+ function inertiaPageUrl(request) {
189
+ if (!request) return;
190
+ const { pathname, search } = new URL(request.url);
191
+ return `${pathname}${search}`;
192
+ }
193
+ async function renderDocument$1(page, options) {
194
+ const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
195
+ const entry = options.entry ?? defaultEntry;
196
+ const title = escapeHtml$2(options.title ?? DEFAULT_TITLE);
197
+ const isProduction = process.env.NODE_ENV === "production";
198
+ const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
199
+ const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
200
+ const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP" });
201
+ const importMapEntries = {
202
+ ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
203
+ ...envImportMap,
204
+ ...options.importMap
205
+ };
206
+ const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
207
+ const serializedPage = serializePage(page);
208
+ const stylesheetLinks = renderStyles(styles);
209
+ const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
210
+ const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
211
+ const headMarkup = resolveDocumentValue("head", options, page.component);
212
+ const ssrResult = await tryRenderSsr(page, options);
213
+ const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
214
+ const headSegments = [
215
+ "<meta charset=\"utf-8\" />",
216
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
217
+ headElements.some((element) => /<title\b[^>]*>/iu.test(element)) ? "" : `<title>${title}</title>`,
218
+ headMarkup ?? "",
219
+ criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
220
+ prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
221
+ stylesheetLinks,
222
+ ...headElements,
223
+ Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : "",
224
+ `<script>window.__INERTIA_PAGE__ = ${serializedPage};<\/script>`
225
+ ].filter((segment) => segment && segment.length > 0);
226
+ const appMarkup = ssrResult?.body ?? `<script data-page="app" type="application/json">${serializedPage}<\/script><div id="app"></div>`;
227
+ const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
228
+ const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
229
+ return `<!DOCTYPE html>
230
+ <html lang="${escapeAttribute(options.lang ?? "en")}">
231
+ <head>
232
+ ${headSegments.join("\n ")}
233
+ </head>
234
+ <body${bodyAttributes}>
235
+ ${appMarkup}
236
+ <script type="module" src="${entry}"><\/script>
237
+ </body>
238
+ </html>`;
239
+ }
240
+ async function tryRenderSsr(page, options) {
241
+ const ssrOptions = options.ssr;
242
+ if (ssrOptions?.enabled === false) return;
243
+ const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
244
+ const renderer = ssrOptions?.render ?? defaultSsrRenderer ?? await loadSsrRenderer(ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY);
245
+ if (!renderer) return;
246
+ try {
247
+ const result = await renderer({
248
+ page,
249
+ request: options.request,
250
+ manifest
251
+ });
252
+ if (!result || typeof result.body !== "string") return;
253
+ return {
254
+ body: result.body,
255
+ head: Array.isArray(result.head) ? result.head : []
256
+ };
257
+ } catch (error) {
258
+ console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
259
+ return;
260
+ }
261
+ }
262
+ async function loadSsrRenderer(entry) {
263
+ const specifier = entry?.trim();
264
+ if (!specifier) return;
265
+ const normalized = normalizeSsrSpecifier(specifier);
266
+ try {
267
+ const renderCandidate = extractSsrRenderer(await import(normalized));
268
+ if (!renderCandidate) {
269
+ console.warn(`Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`);
270
+ return;
271
+ }
272
+ return renderCandidate;
273
+ } catch (error) {
274
+ console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
275
+ return;
276
+ }
277
+ }
278
+ function extractSsrRenderer(module) {
279
+ if (!module || typeof module !== "object") return;
280
+ const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
281
+ if (!candidate) return;
282
+ return (context) => Promise.resolve(candidate(context));
283
+ }
284
+ function normalizeSsrSpecifier(specifier) {
285
+ if (specifier.startsWith("file://") || isUrlLike(specifier)) return specifier;
286
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
287
+ const absolute = resolve$1(process.cwd(), specifier);
288
+ return pathToFileURL(absolute).href;
289
+ }
290
+ if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
291
+ return specifier;
292
+ }
293
+ function isUrlLike(specifier) {
294
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
295
+ }
296
+ /**
297
+ * An absolute http(s) entry means an asset dev server (Vite) is serving the
298
+ * module graph; a same-origin path means source files are served directly,
299
+ * where the raw stylesheet link is the only styling.
300
+ */
301
+ function isDevServerEntry(entry) {
302
+ return /^https?:\/\//iu.test(entry);
303
+ }
304
+ function renderStyles(styles) {
305
+ if (!styles.length) return "";
306
+ return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
307
+ }
308
+ function normalizeHeadElement(element) {
309
+ return (typeof element === "string" ? element : String(element ?? "")).replace(/href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g, (_match, file, query = "") => `href="/public/assets/${file}${query}"`);
310
+ }
311
+ /** One document field: per-response override, then app-wide default, then "". */
312
+ function resolveDocumentValue(key, options, componentName) {
313
+ const override = options[key];
314
+ if (override !== void 0) return override;
315
+ const value = documentOptions?.[key];
316
+ return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
317
+ }
318
+ function serializePage(page) {
319
+ return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
320
+ switch (char) {
321
+ case "<": return "\\u003c";
322
+ case "\u2028": return "\\u2028";
323
+ case "\u2029": return "\\u2029";
324
+ default: return char;
325
+ }
326
+ });
327
+ }
328
+ function acceptsJson(request) {
329
+ const accept = request.headers.get("accept")?.toLowerCase() ?? "";
330
+ if (!accept || accept === "*/*") return false;
331
+ if (accept.includes("text/html")) return false;
332
+ return accept.includes("application/json") || accept.includes("json");
333
+ }
334
+ function escapeHtml$2(value) {
335
+ return value.replace(/[&<>"']/gu, (char) => {
336
+ switch (char) {
337
+ case "&": return "&amp;";
338
+ case "<": return "&lt;";
339
+ case ">": return "&gt;";
340
+ case "\"": return "&quot;";
341
+ case "'": return "&#39;";
342
+ default: return char;
343
+ }
344
+ });
345
+ }
346
+ function escapeAttribute(value) {
347
+ return value.replace(/[&"]/gu, (char) => {
348
+ if (char === "&") return "&amp;";
349
+ return "&quot;";
350
+ });
351
+ }
352
+ function parseStylesEnv(value) {
353
+ if (!value) return [];
354
+ return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
355
+ }
356
+ //#endregion
357
+ //#region src/mvc/inertia/shared.ts
358
+ /** Container binding key for the scoped {@link SharedInertiaPropsRegistry}. */
359
+ const INERTIA_SHARED_PROPS_BINDING = "inertia.sharedProps";
360
+ /**
361
+ * Registrations are numbered from one process-wide counter so that props keep
362
+ * resolving in registration order — later registrations win on conflicting
363
+ * keys — no matter which registry each one landed in.
364
+ */
365
+ let registrationSequence = 0;
366
+ /**
367
+ * Holds the shared-props resolvers for one scope: either a single
368
+ * Application's container or the module-global fallback for bare-Hono apps.
369
+ */
370
+ var SharedInertiaPropsRegistry = class {
371
+ resolvers = [];
372
+ /** Replace every resolver registered in this scope. */
373
+ set(resolverFn) {
374
+ this.resolvers = resolverFn ? [orderedResolver(resolverFn)] : [];
375
+ }
376
+ /**
377
+ * Register additional shared props without replacing resolvers registered
378
+ * earlier — the new resolver's props are merged over the previous ones.
379
+ */
380
+ share(resolverFn) {
381
+ this.resolvers.push(orderedResolver(resolverFn));
382
+ }
383
+ /** The resolvers registered in this scope, ordered by registration. */
384
+ entries() {
385
+ return this.resolvers;
386
+ }
387
+ /**
388
+ * The scope's registrations composed into one resolver, or null when empty.
389
+ * The composition is a snapshot: resolvers registered later are not picked up.
390
+ */
391
+ get() {
392
+ if (this.resolvers.length === 0) return null;
393
+ if (this.resolvers.length === 1) return this.resolvers[0].resolve;
394
+ const snapshot = [...this.resolvers];
395
+ return (ctx) => applyResolvers(snapshot, ctx);
396
+ }
397
+ async resolve(ctx) {
398
+ return applyResolvers(this.resolvers, ctx);
399
+ }
400
+ };
401
+ function orderedResolver(resolverFn) {
402
+ return {
403
+ seq: registrationSequence++,
404
+ resolve: resolverFn
72
405
  };
73
- patched = true;
74
406
  }
75
- function copyStackFromNewError(target) {
76
- copyStackFromError(target, /* @__PURE__ */ new Error());
407
+ async function applyResolvers(entries, ctx) {
408
+ const merged = {};
409
+ for (const entry of entries) {
410
+ const props = await entry.resolve(ctx);
411
+ if (props && typeof props === "object") Object.assign(merged, props);
412
+ }
413
+ return merged;
77
414
  }
78
- function copyStackFromError(target, source) {
79
- if (!target || typeof target !== "object") return;
80
- if (source.stack) Object.defineProperty(target, "stack", {
81
- configurable: true,
82
- enumerable: false,
83
- writable: true,
84
- value: source.stack
85
- });
86
- if (source.name && !("name" in target)) Object.defineProperty(target, "name", {
87
- configurable: true,
88
- enumerable: false,
89
- writable: true,
90
- value: source.name
91
- });
92
- if (source.message && !("message" in target)) Object.defineProperty(target, "message", {
93
- configurable: true,
94
- enumerable: false,
95
- writable: true,
96
- value: source.message
97
- });
415
+ const globalRegistry = new SharedInertiaPropsRegistry();
416
+ /** The registry bound to `container`, or null when it owns none yet. */
417
+ function scopedRegistry(container) {
418
+ if (!container?.has?.("inertia.sharedProps")) return null;
419
+ return container.make(INERTIA_SHARED_PROPS_BINDING);
98
420
  }
99
- //#endregion
100
- //#region src/mvc/mount-route.ts
101
421
  /**
102
- * Mounts a route with a dynamic HTTP method string. Hono's `app.on()` overloads
103
- * expect literal method types, so this helper holds the one narrowing cast.
422
+ * The shared-props registry scoped to `container`, binding a fresh one on
423
+ * first use.
104
424
  */
105
- function mountRoute(app, method, path, ...handlers) {
106
- app.on(method, path, ...handlers);
425
+ function ensureSharedInertiaPropsRegistry(container) {
426
+ const existing = scopedRegistry(container);
427
+ if (existing) return existing;
428
+ const registry = new SharedInertiaPropsRegistry();
429
+ container.instance(INERTIA_SHARED_PROPS_BINDING, registry);
430
+ return registry;
431
+ }
432
+ /**
433
+ * Replace the module-global shared props resolver. Props registered on an
434
+ * application's container (see {@link shareInertiaProps}) are unaffected.
435
+ */
436
+ function setInertiaSharedProps(resolverFn) {
437
+ globalRegistry.set(resolverFn);
438
+ }
439
+ /**
440
+ * The module-global registrations composed into one resolver, for manual
441
+ * composition. Container-scoped props are not included — get those from
442
+ * `ensureSharedInertiaPropsRegistry(container).get()`.
443
+ */
444
+ function getInertiaSharedPropsResolver() {
445
+ return globalRegistry.get();
446
+ }
447
+ /**
448
+ * Register additional shared props without replacing earlier resolvers, so
449
+ * several providers can each contribute (`setInertiaSharedProps` replaces
450
+ * wholesale). Pass the provider's `this.container` to scope them; without it
451
+ * they are module-global and a second Application in the process shares them.
452
+ */
453
+ function shareInertiaProps(resolverFn, container) {
454
+ (container ? ensureSharedInertiaPropsRegistry(container) : globalRegistry).share(resolverFn);
455
+ }
456
+ /**
457
+ * Resolve shared props for a request, merging the module-global registrations
458
+ * with those scoped to `container` in registration order.
459
+ */
460
+ async function resolveSharedInertiaProps(ctx, container) {
461
+ const scoped = scopedRegistry(container);
462
+ if (!scoped) return globalRegistry.resolve(ctx);
463
+ const globalEntries = globalRegistry.entries();
464
+ if (globalEntries.length === 0) return scoped.resolve(ctx);
465
+ return applyResolvers([...globalEntries, ...scoped.entries()].sort((a, b) => a.seq - b.seq), ctx);
466
+ }
467
+ //#endregion
468
+ //#region src/mvc/prototype.ts
469
+ const PROTOTYPE_HANDLER = Symbol.for("guren.prototype.handler");
470
+ const prototype = Object.freeze({ [PROTOTYPE_HANDLER]: true });
471
+ function isPrototypeHandler(value) {
472
+ return typeof value === "object" && value !== null && value[PROTOTYPE_HANDLER] === true;
473
+ }
474
+ /** Container key the loaded fixture is bound under once `Application` has validated the prototype routes. */
475
+ const PROTOTYPE_FIXTURE_BINDING = "prototype.fixture";
476
+ function isFixture(value) {
477
+ return typeof value === "object" && value !== null && typeof value.routes === "object" && value.routes !== null;
478
+ }
479
+ async function loadPrototypeFixture(loader) {
480
+ const loaded = await loader();
481
+ const fixture = isFixture(loaded) ? loaded : loaded.default;
482
+ if (!isFixture(fixture)) throw new Error("createApp({ prototype }) loaded a module that does not export a definePrototype() result as its default export.");
483
+ return fixture;
484
+ }
485
+ /** One `state()` per fixture per process: shared by every request, reset by a restart. */
486
+ const processState = /* @__PURE__ */ new WeakMap();
487
+ function stateOf(fixture) {
488
+ if (!processState.has(fixture)) processState.set(fixture, fixture.state?.() ?? {});
489
+ return processState.get(fixture);
490
+ }
491
+ function enforce(schema, data) {
492
+ if (!schema) return;
493
+ const result = schema.safeParse(data);
494
+ if (!result.success) throw ValidationException.withMessages(formatValidationErrors(result.error));
495
+ }
496
+ const BODYLESS_METHODS = /* @__PURE__ */ new Set([
497
+ "GET",
498
+ "HEAD",
499
+ "OPTIONS"
500
+ ]);
501
+ /**
502
+ * The route's handler: the fixture entry for the route name, run against the
503
+ * same context shape the browser client builds. The route contract is enforced
504
+ * first (`params`, `query`, `body`; not `output`, which only a response has), so `guren
505
+ * audit`'s "runtime-enforced" verdict stays true here.
506
+ */
507
+ function createPrototypeRouteHandler(route, deps) {
508
+ return async (c) => {
509
+ const fixture = resolveFixture(deps.container);
510
+ const name = route.name;
511
+ const handler = name ? fixture.routes[name] : void 0;
512
+ if (!name || !handler) throw new Error(`Prototype route ${route.method} ${route.path} has no fixture entry${name ? ` for "${name}"` : ""}.`);
513
+ const params = c.req.param();
514
+ const query = flattenRequestQueries(c);
515
+ enforce(route.schemas?.params, params);
516
+ enforce(route.schemas?.query, query);
517
+ const method = c.req.method.toUpperCase();
518
+ const body = BODYLESS_METHODS.has(method) ? void 0 : await parseRequestBody(c);
519
+ enforce(route.schemas?.body, body);
520
+ const session = getSessionFromContext(c);
521
+ const shared = {
522
+ ...fixture.shared,
523
+ ...await resolveSharedInertiaProps(c, deps.container)
524
+ };
525
+ const url = new URL(c.req.url);
526
+ const result = await handler({
527
+ method,
528
+ url: `${url.pathname}${url.search}`,
529
+ params,
530
+ query,
531
+ body,
532
+ state: stateOf(fixture),
533
+ shared,
534
+ page: (contract, props) => ({
535
+ kind: "page",
536
+ component: componentOf(contract),
537
+ props
538
+ }),
539
+ redirect: (to, redirectParams) => ({
540
+ kind: "redirect",
541
+ to,
542
+ params: redirectParams
543
+ }),
544
+ location: (target) => ({
545
+ kind: "location",
546
+ url: target
547
+ }),
548
+ errors: (errors) => ({
549
+ kind: "errors",
550
+ errors
551
+ }),
552
+ notFound: () => ({ kind: "not-found" }),
553
+ flash: (key, value) => session?.flash(key, value)
554
+ });
555
+ if (!isResult(result)) throw new Error(`Prototype entry "${name}" returned something other than page()/redirect()/errors()/location()/notFound().`);
556
+ return answer(result, c, fixture, shared, deps);
557
+ };
558
+ }
559
+ const RESULT_KINDS = /* @__PURE__ */ new Set([
560
+ "page",
561
+ "redirect",
562
+ "location",
563
+ "errors",
564
+ "not-found"
565
+ ]);
566
+ function componentOf(contract) {
567
+ return contract.component ?? contract.id;
568
+ }
569
+ function isResult(value) {
570
+ return typeof value === "object" && value !== null && RESULT_KINDS.has(String(value.kind));
571
+ }
572
+ function resolveFixture(container) {
573
+ let fixture;
574
+ try {
575
+ fixture = container?.make(PROTOTYPE_FIXTURE_BINDING);
576
+ } catch {
577
+ fixture = void 0;
578
+ }
579
+ if (!isFixture(fixture)) throw new Error("A prototype route was dispatched before its fixture was loaded. Pass `prototype: () => import(...)` to createApp() and mount routes through the application, which validates and loads it at boot.");
580
+ return fixture;
581
+ }
582
+ async function answer(result, c, fixture, shared, deps) {
583
+ switch (result.kind) {
584
+ case "page": return inertia(result.component, {
585
+ ...shared,
586
+ ...result.props
587
+ }, { request: c.req.raw });
588
+ case "redirect": return c.redirect(deps.routeUrl(result.to, result.params), 303);
589
+ case "location":
590
+ if (c.req.header("X-Inertia")) return new Response(null, {
591
+ status: 409,
592
+ headers: { "X-Inertia-Location": result.url }
593
+ });
594
+ return c.redirect(result.url, 302);
595
+ case "errors": throw ValidationException.withMessages(result.errors);
596
+ case "not-found":
597
+ if (fixture.notFoundPage) return inertia(componentOf(fixture.notFoundPage), {
598
+ ...shared,
599
+ status: 404,
600
+ message: "Not Found"
601
+ }, {
602
+ request: c.req.raw,
603
+ status: 404
604
+ });
605
+ throw HttpException.notFound();
606
+ }
107
607
  }
108
608
  //#endregion
109
609
  //#region src/mvc/Router.ts
@@ -287,7 +787,10 @@ var Router = class {
287
787
  mount(app, options = {}) {
288
788
  for (const route of this.registry) {
289
789
  const resolvedMiddlewares = this.resolveMiddlewareNames(route.routeMiddlewareNames);
290
- const handler = resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
790
+ const handler = isPrototypeHandler(route.handler) ? createPrototypeRouteHandler(route, {
791
+ container: options.container,
792
+ routeUrl: (name, params) => this.route(name, params)
793
+ }) : resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
291
794
  const contractMiddleware = createContractValidationMiddleware(route);
292
795
  const inlineMiddlewares = [...route.scopedMiddlewares, ...route.middlewares];
293
796
  const preflightMiddleware = createAgentPreflightMiddleware(route, () => this.aggregateCapabilities(route.routeMiddlewareNames, inlineMiddlewares));
@@ -310,11 +813,12 @@ var Router = class {
310
813
  this.modelBindings.clear();
311
814
  }
312
815
  definitions() {
313
- return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent }) => ({
816
+ return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent, prototype }) => ({
314
817
  method,
315
818
  path,
316
819
  name,
317
820
  schemas,
821
+ prototype,
318
822
  resource: serializeResourceHint(resource),
319
823
  agent: agent ? cloneAgentMetadata(agent) : void 0,
320
824
  middlewareNames: [...routeMiddlewareNames],
@@ -347,6 +851,13 @@ var Router = class {
347
851
  applyRouteContract(route, options);
348
852
  return builder;
349
853
  }
854
+ if (isPrototypeHandler(handlerOrAction)) {
855
+ const builder = this.add(method, path, handlerOrAction, options.middlewares ?? []);
856
+ if (options.name) builder.name(options.name);
857
+ const route = this.registry[this.registry.length - 1];
858
+ applyRouteContract(route, options);
859
+ return builder;
860
+ }
350
861
  const contractHandler = handlerOrAction;
351
862
  if (typeof contractHandler !== "function") throw new Error(`Router.${method.toLowerCase()} requires a handler function when route contract options are provided.`);
352
863
  const wrappedHandler = createContractHandler(path, options, contractHandler);
@@ -369,6 +880,7 @@ var Router = class {
369
880
  scopedMiddlewares: scope.handlers,
370
881
  routeMiddlewareNames: scope.names
371
882
  };
883
+ if (isPrototypeHandler(handler)) route.prototype = true;
372
884
  this.registry.push(route);
373
885
  return createRouteBuilder(route, this.namedRoutes);
374
886
  }
@@ -916,6 +1428,18 @@ var CookieSessionStore = class {
916
1428
  /** The store `SessionConfig.default` names when it names none, and the one driver that shares no state between requests. */
917
1429
  const DEFAULT_SESSION_STORE_NAME = "memory";
918
1430
  const PER_PROCESS_SESSION_DRIVERS = /* @__PURE__ */ new Set([DEFAULT_SESSION_STORE_NAME]);
1431
+ /**
1432
+ * Every driver the framework itself registers, and whether it survives a
1433
+ * runtime that shares no memory between requests. Read by static checks that
1434
+ * cannot boot the app; a plugin's driver is declared in its `gurenPlugin`
1435
+ * manifest instead, and a name in neither is unverifiable, not absent.
1436
+ */
1437
+ const BUILT_IN_SESSION_DRIVERS = /* @__PURE__ */ new Map([
1438
+ ["memory", false],
1439
+ ["cookie", true],
1440
+ ["database", true],
1441
+ ["redis", true]
1442
+ ]);
919
1443
  function isPrunable(store) {
920
1444
  return typeof store.deleteExpired === "function";
921
1445
  }
@@ -2016,7 +2540,7 @@ function createDefaultGuardFactory(providerName) {
2016
2540
  }
2017
2541
  //#endregion
2018
2542
  //#region src/errors/error-page.ts
2019
- function escapeHtml$2(value) {
2543
+ function escapeHtml$1(value) {
2020
2544
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2021
2545
  }
2022
2546
  /** Production error page: no stack traces or internal details are exposed. */
@@ -2055,7 +2579,7 @@ function renderErrorPage(statusCode, message) {
2055
2579
  <div class="container">
2056
2580
  <div class="status">${statusCode}</div>
2057
2581
  <h1 class="title">${title}</h1>
2058
- <p class="description">${escapeHtml$2(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
2582
+ <p class="description">${escapeHtml$1(message ?? STATUS_DESCRIPTIONS[statusCode] ?? "An unexpected error occurred.")}</p>
2059
2583
  <a href="/" class="home-link">Go Home</a>
2060
2584
  </div>
2061
2585
  </body>
@@ -2277,121 +2801,10 @@ var ErrorServiceProvider = class extends ServiceProvider {
2277
2801
  }
2278
2802
  boot() {
2279
2803
  const hono = this.container.make("hono");
2280
- const handler = this.container.make("exception.handler");
2281
- hono.onError((error, ctx) => handler.handle(error, ctx));
2282
- }
2283
- };
2284
- //#endregion
2285
- //#region src/mvc/inertia/shared.ts
2286
- /** Container binding key for the scoped {@link SharedInertiaPropsRegistry}. */
2287
- const INERTIA_SHARED_PROPS_BINDING = "inertia.sharedProps";
2288
- /**
2289
- * Registrations are numbered from one process-wide counter so that props keep
2290
- * resolving in registration order — later registrations win on conflicting
2291
- * keys — no matter which registry each one landed in.
2292
- */
2293
- let registrationSequence = 0;
2294
- /**
2295
- * Holds the shared-props resolvers for one scope: either a single
2296
- * Application's container or the module-global fallback for bare-Hono apps.
2297
- */
2298
- var SharedInertiaPropsRegistry = class {
2299
- resolvers = [];
2300
- /** Replace every resolver registered in this scope. */
2301
- set(resolverFn) {
2302
- this.resolvers = resolverFn ? [orderedResolver(resolverFn)] : [];
2303
- }
2304
- /**
2305
- * Register additional shared props without replacing resolvers registered
2306
- * earlier — the new resolver's props are merged over the previous ones.
2307
- */
2308
- share(resolverFn) {
2309
- this.resolvers.push(orderedResolver(resolverFn));
2310
- }
2311
- /** The resolvers registered in this scope, ordered by registration. */
2312
- entries() {
2313
- return this.resolvers;
2314
- }
2315
- /**
2316
- * The scope's registrations composed into one resolver, or null when empty.
2317
- * The composition is a snapshot: resolvers registered later are not picked up.
2318
- */
2319
- get() {
2320
- if (this.resolvers.length === 0) return null;
2321
- if (this.resolvers.length === 1) return this.resolvers[0].resolve;
2322
- const snapshot = [...this.resolvers];
2323
- return (ctx) => applyResolvers(snapshot, ctx);
2324
- }
2325
- async resolve(ctx) {
2326
- return applyResolvers(this.resolvers, ctx);
2327
- }
2328
- };
2329
- function orderedResolver(resolverFn) {
2330
- return {
2331
- seq: registrationSequence++,
2332
- resolve: resolverFn
2333
- };
2334
- }
2335
- async function applyResolvers(entries, ctx) {
2336
- const merged = {};
2337
- for (const entry of entries) {
2338
- const props = await entry.resolve(ctx);
2339
- if (props && typeof props === "object") Object.assign(merged, props);
2340
- }
2341
- return merged;
2342
- }
2343
- const globalRegistry = new SharedInertiaPropsRegistry();
2344
- /** The registry bound to `container`, or null when it owns none yet. */
2345
- function scopedRegistry(container) {
2346
- if (!container?.has?.("inertia.sharedProps")) return null;
2347
- return container.make(INERTIA_SHARED_PROPS_BINDING);
2348
- }
2349
- /**
2350
- * The shared-props registry scoped to `container`, binding a fresh one on
2351
- * first use.
2352
- */
2353
- function ensureSharedInertiaPropsRegistry(container) {
2354
- const existing = scopedRegistry(container);
2355
- if (existing) return existing;
2356
- const registry = new SharedInertiaPropsRegistry();
2357
- container.instance(INERTIA_SHARED_PROPS_BINDING, registry);
2358
- return registry;
2359
- }
2360
- /**
2361
- * Replace the module-global shared props resolver. Props registered on an
2362
- * application's container (see {@link shareInertiaProps}) are unaffected.
2363
- */
2364
- function setInertiaSharedProps(resolverFn) {
2365
- globalRegistry.set(resolverFn);
2366
- }
2367
- /**
2368
- * The module-global registrations composed into one resolver, for manual
2369
- * composition. Container-scoped props are not included — get those from
2370
- * `ensureSharedInertiaPropsRegistry(container).get()`.
2371
- */
2372
- function getInertiaSharedPropsResolver() {
2373
- return globalRegistry.get();
2374
- }
2375
- /**
2376
- * Register additional shared props without replacing earlier resolvers, so
2377
- * several providers can each contribute (`setInertiaSharedProps` replaces
2378
- * wholesale). Pass the provider's `this.container` to scope them; without it
2379
- * they are module-global and a second Application in the process shares them.
2380
- */
2381
- function shareInertiaProps(resolverFn, container) {
2382
- (container ? ensureSharedInertiaPropsRegistry(container) : globalRegistry).share(resolverFn);
2383
- }
2384
- /**
2385
- * Resolve shared props for a request, merging the module-global registrations
2386
- * with those scoped to `container` in registration order.
2387
- */
2388
- async function resolveSharedInertiaProps(ctx, container) {
2389
- const scoped = scopedRegistry(container);
2390
- if (!scoped) return globalRegistry.resolve(ctx);
2391
- const globalEntries = globalRegistry.entries();
2392
- if (globalEntries.length === 0) return scoped.resolve(ctx);
2393
- return applyResolvers([...globalEntries, ...scoped.entries()].sort((a, b) => a.seq - b.seq), ctx);
2394
- }
2804
+ const handler = this.container.make("exception.handler");
2805
+ hono.onError((error, ctx) => handler.handle(error, ctx));
2806
+ }
2807
+ };
2395
2808
  //#endregion
2396
2809
  //#region src/providers/I18nServiceProvider.ts
2397
2810
  /**
@@ -2459,254 +2872,6 @@ var I18nServiceProvider = class extends ServiceProvider {
2459
2872
  }
2460
2873
  };
2461
2874
  //#endregion
2462
- //#region src/mvc/inertia/InertiaEngine.ts
2463
- ensureErrorStackTracePolyfill();
2464
- let documentOptions;
2465
- /**
2466
- * Register app-wide document defaults for server-rendered Inertia responses;
2467
- * call it at module scope in the app entry so every runtime picks it up.
2468
- * Process-wide, not request-scoped: calling it mid-flight leaks the policy into
2469
- * in-flight requests — use the {@link InertiaOptions} fields per response.
2470
- * Values are emitted verbatim, so never pass user input. `undefined` clears.
2471
- */
2472
- function setInertiaDocument(options) {
2473
- documentOptions = options;
2474
- }
2475
- let defaultSsrRenderer;
2476
- /**
2477
- * Register a process-wide default SSR renderer, for adapters whose bundler
2478
- * cannot resolve a runtime path (Workers has no filesystem for
2479
- * `GUREN_INERTIA_SSR_ENTRY`'s dynamic import). Per-call `ssr.render` still
2480
- * wins; `undefined` clears (test isolation).
2481
- */
2482
- function setInertiaSsrRenderer(renderer) {
2483
- defaultSsrRenderer = renderer;
2484
- }
2485
- const DEFAULT_TITLE = "Guren";
2486
- const DEV_FALLBACK_IMPORT_MAP = {
2487
- react: "https://esm.sh/react@19.0.0?dev",
2488
- "react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime?dev",
2489
- "react/jsx-dev-runtime": "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev",
2490
- "react-dom/client": "https://esm.sh/react-dom@19.0.0/client?dev",
2491
- "@guren/inertia-client": "/vendor/inertia-client.tsx",
2492
- "@inertiajs/react": "https://esm.sh/@inertiajs/react@2.2.15?dev&external=react,react-dom/client"
2493
- };
2494
- async function inertia(component, props, options = {}) {
2495
- const resolvedVersion = options.version ?? process.env.GUREN_INERTIA_VERSION ?? void 0;
2496
- const page = {
2497
- component,
2498
- props,
2499
- url: options.url ?? inertiaPageUrl(options.request) ?? "",
2500
- version: resolvedVersion
2501
- };
2502
- const request = options.request;
2503
- const isInertiaVisit = Boolean(request?.headers.get("X-Inertia"));
2504
- const prefersJson = request ? acceptsJson(request) : false;
2505
- const versionHeader = resolvedVersion ? { "X-Inertia-Version": resolvedVersion } : {};
2506
- if (request && resolvedVersion && isInertiaVisit && request.method === "GET") {
2507
- if (request.headers.get("X-Inertia-Version") !== resolvedVersion) return new Response(null, {
2508
- status: 409,
2509
- headers: {
2510
- "X-Inertia-Location": options.url ?? request.url,
2511
- Vary: "Accept"
2512
- }
2513
- });
2514
- }
2515
- if (isInertiaVisit || prefersJson) return new Response(serializePage(page), {
2516
- status: options.status ?? 200,
2517
- headers: {
2518
- "Content-Type": "application/json; charset=utf-8",
2519
- "X-Inertia": "true",
2520
- Vary: "Accept",
2521
- ...versionHeader,
2522
- ...options.headers
2523
- }
2524
- });
2525
- const html = await renderDocument$1(page, options);
2526
- return new Response(html, {
2527
- status: options.status ?? 200,
2528
- headers: {
2529
- "Content-Type": "text/html; charset=utf-8",
2530
- "X-Inertia": "true",
2531
- Vary: "Accept",
2532
- ...versionHeader,
2533
- ...options.headers
2534
- }
2535
- });
2536
- }
2537
- /**
2538
- * The Inertia protocol's page `url` is the request path plus query string, kept
2539
- * relative. Derived from the request when the caller does not override it.
2540
- */
2541
- function inertiaPageUrl(request) {
2542
- if (!request) return;
2543
- const { pathname, search } = new URL(request.url);
2544
- return `${pathname}${search}`;
2545
- }
2546
- async function renderDocument$1(page, options) {
2547
- const defaultEntry = process.env.GUREN_INERTIA_ENTRY || "/resources/js/app.tsx";
2548
- const entry = options.entry ?? defaultEntry;
2549
- const title = escapeHtml$1(options.title ?? DEFAULT_TITLE);
2550
- const isProduction = process.env.NODE_ENV === "production";
2551
- const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2552
- const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
2553
- const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, { context: "GUREN_INERTIA_IMPORT_MAP" });
2554
- const importMapEntries = {
2555
- ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
2556
- ...envImportMap,
2557
- ...options.importMap
2558
- };
2559
- const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
2560
- const serializedPage = serializePage(page);
2561
- const stylesheetLinks = renderStyles(styles);
2562
- const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
2563
- const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
2564
- const headMarkup = resolveDocumentValue("head", options, page.component);
2565
- const ssrResult = await tryRenderSsr(page, options);
2566
- const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
2567
- const headSegments = [
2568
- "<meta charset=\"utf-8\" />",
2569
- "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
2570
- headElements.some((element) => /<title\b[^>]*>/iu.test(element)) ? "" : `<title>${title}</title>`,
2571
- headMarkup ?? "",
2572
- criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
2573
- prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
2574
- stylesheetLinks,
2575
- ...headElements,
2576
- Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : "",
2577
- `<script>window.__INERTIA_PAGE__ = ${serializedPage};<\/script>`
2578
- ].filter((segment) => segment && segment.length > 0);
2579
- const appMarkup = ssrResult?.body ?? `<script data-page="app" type="application/json">${serializedPage}<\/script><div id="app"></div>`;
2580
- const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
2581
- const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
2582
- return `<!DOCTYPE html>
2583
- <html lang="${escapeAttribute(options.lang ?? "en")}">
2584
- <head>
2585
- ${headSegments.join("\n ")}
2586
- </head>
2587
- <body${bodyAttributes}>
2588
- ${appMarkup}
2589
- <script type="module" src="${entry}"><\/script>
2590
- </body>
2591
- </html>`;
2592
- }
2593
- async function tryRenderSsr(page, options) {
2594
- const ssrOptions = options.ssr;
2595
- if (ssrOptions?.enabled === false) return;
2596
- const manifest = (ssrOptions?.manifest ?? process.env.GUREN_INERTIA_SSR_MANIFEST)?.trim() || void 0;
2597
- const renderer = ssrOptions?.render ?? defaultSsrRenderer ?? await loadSsrRenderer(ssrOptions?.entry ?? process.env.GUREN_INERTIA_SSR_ENTRY);
2598
- if (!renderer) return;
2599
- try {
2600
- const result = await renderer({
2601
- page,
2602
- request: options.request,
2603
- manifest
2604
- });
2605
- if (!result || typeof result.body !== "string") return;
2606
- return {
2607
- body: result.body,
2608
- head: Array.isArray(result.head) ? result.head : []
2609
- };
2610
- } catch (error) {
2611
- console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
2612
- return;
2613
- }
2614
- }
2615
- async function loadSsrRenderer(entry) {
2616
- const specifier = entry?.trim();
2617
- if (!specifier) return;
2618
- const normalized = normalizeSsrSpecifier(specifier);
2619
- try {
2620
- const renderCandidate = extractSsrRenderer(await import(normalized));
2621
- if (!renderCandidate) {
2622
- console.warn(`Inertia SSR entry "${specifier}" does not export a renderer. Expected a default export or a named "render" function.`);
2623
- return;
2624
- }
2625
- return renderCandidate;
2626
- } catch (error) {
2627
- console.error(`Failed to import Inertia SSR entry "${specifier}".`, error);
2628
- return;
2629
- }
2630
- }
2631
- function extractSsrRenderer(module) {
2632
- if (!module || typeof module !== "object") return;
2633
- const candidate = typeof module.render === "function" ? module.render : typeof module.default === "function" ? module.default : void 0;
2634
- if (!candidate) return;
2635
- return (context) => Promise.resolve(candidate(context));
2636
- }
2637
- function normalizeSsrSpecifier(specifier) {
2638
- if (specifier.startsWith("file://") || isUrlLike(specifier)) return specifier;
2639
- if (specifier.startsWith("./") || specifier.startsWith("../")) {
2640
- const absolute = resolve$1(process.cwd(), specifier);
2641
- return pathToFileURL(absolute).href;
2642
- }
2643
- if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
2644
- return specifier;
2645
- }
2646
- function isUrlLike(specifier) {
2647
- return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
2648
- }
2649
- /**
2650
- * An absolute http(s) entry means an asset dev server (Vite) is serving the
2651
- * module graph; a same-origin path means source files are served directly,
2652
- * where the raw stylesheet link is the only styling.
2653
- */
2654
- function isDevServerEntry(entry) {
2655
- return /^https?:\/\//iu.test(entry);
2656
- }
2657
- function renderStyles(styles) {
2658
- if (!styles.length) return "";
2659
- return styles.map((href) => `<link rel="stylesheet" href="${escapeAttribute(href)}" />`).join("\n ");
2660
- }
2661
- function normalizeHeadElement(element) {
2662
- return (typeof element === "string" ? element : String(element ?? "")).replace(/href="\/(?!public\/)([^"?]+\.(?:js|css))(\?[^"']*)?"/g, (_match, file, query = "") => `href="/public/assets/${file}${query}"`);
2663
- }
2664
- /** One document field: per-response override, then app-wide default, then "". */
2665
- function resolveDocumentValue(key, options, componentName) {
2666
- const override = options[key];
2667
- if (override !== void 0) return override;
2668
- const value = documentOptions?.[key];
2669
- return (typeof value === "function" ? value({ component: componentName }) : value) ?? "";
2670
- }
2671
- function serializePage(page) {
2672
- return JSON.stringify(page).replace(/[<\u2028\u2029]/gu, (char) => {
2673
- switch (char) {
2674
- case "<": return "\\u003c";
2675
- case "\u2028": return "\\u2028";
2676
- case "\u2029": return "\\u2029";
2677
- default: return char;
2678
- }
2679
- });
2680
- }
2681
- function acceptsJson(request) {
2682
- const accept = request.headers.get("accept")?.toLowerCase() ?? "";
2683
- if (!accept || accept === "*/*") return false;
2684
- if (accept.includes("text/html")) return false;
2685
- return accept.includes("application/json") || accept.includes("json");
2686
- }
2687
- function escapeHtml$1(value) {
2688
- return value.replace(/[&<>"']/gu, (char) => {
2689
- switch (char) {
2690
- case "&": return "&amp;";
2691
- case "<": return "&lt;";
2692
- case ">": return "&gt;";
2693
- case "\"": return "&quot;";
2694
- case "'": return "&#39;";
2695
- default: return char;
2696
- }
2697
- });
2698
- }
2699
- function escapeAttribute(value) {
2700
- return value.replace(/[&"]/gu, (char) => {
2701
- if (char === "&") return "&amp;";
2702
- return "&quot;";
2703
- });
2704
- }
2705
- function parseStylesEnv(value) {
2706
- if (!value) return [];
2707
- return value.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
2708
- }
2709
- //#endregion
2710
2875
  //#region src/mvc/ViewEngine.ts
2711
2876
  /**
2712
2877
  * Registry for view renderers. Engines are typically registered via service
@@ -3183,8 +3348,30 @@ var Application = class {
3183
3348
  for (const gurenModule of this.options.modules ?? []) await mountModuleRoutes(this.router, gurenModule);
3184
3349
  this.routesRegistered = true;
3185
3350
  }
3351
+ await this.preparePrototypeRoutes();
3186
3352
  this.router.mount(this.hono, { container: this.container });
3187
3353
  }
3354
+ /**
3355
+ * Every failure here is one a request would otherwise surface as a 500:
3356
+ * an unnamed prototype route cannot be looked up, a named one the fixture
3357
+ * does not answer, no loader to answer from at all. Process-shared fixture
3358
+ * state is a developer's own `bun run dev`, not a deployment, hence the
3359
+ * production refusal; `GUREN_PROTOTYPE_ROUTES=1` overrides it deliberately.
3360
+ */
3361
+ async preparePrototypeRoutes() {
3362
+ if (this.container.has("prototype.fixture")) return;
3363
+ const routes = this.router.definitions().filter((route) => route.prototype);
3364
+ if (routes.length === 0) return;
3365
+ const describe = (route) => `${route.method} ${route.path}${route.name ? ` (${route.name})` : ""}`;
3366
+ const unnamed = routes.find((route) => !route.name);
3367
+ if (unnamed) throw new Error(`Route ${describe(unnamed)} uses the prototype handler but has no name; the fixture is keyed by route name. Chain .name() on it or pass { name } in its options.`);
3368
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production" && process.env.GUREN_PROTOTYPE_ROUTES !== "1") throw new Error(`${routes.length} route(s) still answer from the prototype fixture (${routes.map(describe).join(", ")}), whose state is shared by every request of this process. Replace them with controllers before deploying, or set GUREN_PROTOTYPE_ROUTES=1 to run a deliberately fixture-backed server.`);
3369
+ if (!this.options.prototype) throw new Error(`Route ${describe(routes[0])} uses the prototype handler, but createApp() has no \`prototype\` option. Pass \`prototype: () => import('../resources/js/prototype/index.js')\`.`);
3370
+ const fixture = await loadPrototypeFixture(this.options.prototype);
3371
+ const missing = routes.filter((route) => typeof fixture.routes[route.name] !== "function");
3372
+ if (missing.length > 0) throw new Error(`The prototype fixture has no entry for ${missing.map(describe).join(", ")}. Add the route name to \`routes\` in resources/js/prototype/index.ts, or replace the handler with a controller.`);
3373
+ this.container.instance(PROTOTYPE_FIXTURE_BINDING, fixture);
3374
+ }
3188
3375
  use(path, ...middleware) {
3189
3376
  this.hono.use(path, ...middleware);
3190
3377
  }
@@ -3218,7 +3405,7 @@ var Application = class {
3218
3405
  await this.options.boot?.(this.hono);
3219
3406
  await this.mountRoutes();
3220
3407
  await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BvJRcDOm.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
3221
- await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-D2cuVgtN.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3408
+ await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-DWnlXx_y.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3222
3409
  await this.providerManager.bootAll();
3223
3410
  }
3224
3411
  /** Called once, from the constructor — see the note there for why. */
@@ -3855,6 +4042,10 @@ function deriveAgentTools(definitions) {
3855
4042
  if (!agent) continue;
3856
4043
  const method = definition.method.toUpperCase();
3857
4044
  const where = `${method} ${definition.path}`;
4045
+ if (definition.prototype) {
4046
+ warnings.push(`${where}: declares agent metadata while still on its prototype fixture, so it is not exposed as a tool.`);
4047
+ continue;
4048
+ }
3858
4049
  if (!definition.name) {
3859
4050
  warnings.push(`${where}: declares agent metadata but has no route name, so it is not exposed as a tool. Chain .name() on the route — the tool name is its identity.`);
3860
4051
  continue;
@@ -7716,4 +7907,4 @@ function renderEnvironmentSection() {
7716
7907
  //#region src/index.ts
7717
7908
  ensureErrorStackTracePolyfill();
7718
7909
  //#endregion
7719
- export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
7910
+ export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BUILT_IN_SESSION_DRIVERS, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PER_PROCESS_SESSION_DRIVERS, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, approvalStatusNotFoundMessage, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, detectServerlessRuntime, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, gateApproval, gatePreflight, gateToolCall, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, notifyApprovers, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, prototype, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopedShape, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toApprovalStatusReport, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };