kizunajs 2.0.0-beta.28 → 2.0.0-beta.29

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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  A spec-driven framework for building fully typed REST APIs in TypeScript, where your route declarations produce the validation, the documentation, the clients, and the AI tools.
6
6
 
7
- [![npm](https://img.shields.io/npm/v/kizunajs/beta?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs/v/2.0.0-beta.28)
7
+ [![npm](https://img.shields.io/npm/v/kizunajs/beta?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs/v/2.0.0-beta.29)
8
8
  ![license](https://img.shields.io/badge/license-MIT-blue)
9
9
 
10
10
  [Documentation](https://kizunajs.com)
@@ -907,15 +907,55 @@ interface RouteMatch {
907
907
  route: RouteDefinition;
908
908
  params: Record<string, string>;
909
909
  }
910
+ /**
911
+ * `malformed-path` is a path whose params hold a percent-encoding that does not decode (RFC 3986 section 2.1).
912
+ */
910
913
  type MatchResult = {
911
914
  kind: 'matched';
912
915
  match: RouteMatch;
913
916
  } | {
914
917
  kind: 'method-mismatch';
915
918
  allowed: Method[];
919
+ } | {
920
+ kind: 'malformed-path';
921
+ } | {
922
+ kind: 'not-found';
923
+ };
924
+ type PathParamsResult = {
925
+ kind: 'matched';
926
+ params: Record<string, string>;
927
+ } | {
928
+ kind: 'malformed-path';
916
929
  } | {
917
930
  kind: 'not-found';
918
931
  };
932
+ /**
933
+ * Whether a raw pathname holds a percent-encoding that does not decode, like `/users/%E0`.
934
+ */
935
+ declare const isMalformedPath: (pathname: string) => boolean;
936
+ interface SharedSegmentRoute {
937
+ /**
938
+ * The route's path with each segment that holds several params written as
939
+ * one param, for a router that reads one param per segment, like Hono's.
940
+ */
941
+ routerPath: string;
942
+ /**
943
+ * The route's params, read from the request's raw pathname the way
944
+ * `matchRoute` reads them.
945
+ */
946
+ readParams: (pathname: string) => PathParamsResult;
947
+ }
948
+ /**
949
+ * How an adapter mounts a route with several params in one segment, like
950
+ * `/range/:from-:to`, so the route gives the same params on every adapter.
951
+ * Returns `undefined` for any other route, which mounts on the framework's
952
+ * router as it is.
953
+ *
954
+ * @example
955
+ * const shared = sharedSegmentRoute('/range/:from-:to');
956
+ * shared?.readParams('/range/2024-01-2024-02');
957
+ */
958
+ declare const sharedSegmentRoute: (path: string) => SharedSegmentRoute | undefined;
919
959
  declare const sortFlattenedRoutes: <T extends {
920
960
  route: RouteDefinition;
921
961
  }>(routes: T[]) => T[];
@@ -2381,6 +2421,12 @@ declare const bearerChallenge: (parameters: Record<string, string | undefined>)
2381
2421
  */
2382
2422
  declare const guardDenyFor: (scheme: SecurityScheme | undefined) => GuardDeny<GuardDenialBody>;
2383
2423
  declare const isGuardDenial: (value: unknown) => value is GuardDenial;
2424
+ /**
2425
+ * Run a guard with the `deny` for its scheme. A guard that calls `deny` is
2426
+ * denied whether or not it returns the denial, and a returned denial wins over
2427
+ * one it only called.
2428
+ */
2429
+ declare const callGuard: <HandlerContext>(guard: GuardRun<HandlerContext>, scheme: SecurityScheme | undefined, args: Record<string, unknown>) => Promise<Record<string, unknown> | GuardDenial | void>;
2384
2430
  /**
2385
2431
  * The runtime behavior of a guard. It receives one object: the adapter's handler
2386
2432
  * context (e.g. `req`/`res`) plus the credential the identity's method extracted
@@ -2559,10 +2605,13 @@ interface AdapterRequest<NativeRequest> {
2559
2605
  /**
2560
2606
  * - `core-match`: core matches the path against the routes (Next-style catch-all routing).
2561
2607
  * - `pre-resolved`: adapter has already routed the request and tells core which route was matched (Express-style per-route registration).
2608
+ * - `malformed-path`: adapter has routed the request, but its params hold a percent-encoding that does not decode.
2562
2609
  */
2563
2610
  resolution: {
2564
2611
  kind: 'core-match';
2565
2612
  path: string;
2613
+ } | {
2614
+ kind: 'malformed-path';
2566
2615
  } | {
2567
2616
  kind: 'pre-resolved';
2568
2617
  routeKey: string;
@@ -2586,6 +2635,8 @@ interface AdapterRequest<NativeRequest> {
2586
2635
  */
2587
2636
  type AdapterResult = {
2588
2637
  kind: 'not-found';
2638
+ } | {
2639
+ kind: 'malformed-path';
2589
2640
  } | {
2590
2641
  kind: 'method-not-allowed';
2591
2642
  allowed: Method[];
@@ -2776,4 +2827,4 @@ declare const parseBodyText: (text: string, route: RouteDefinition) => unknown;
2776
2827
  declare const parseFetchBody: (request: Request, route: RouteDefinition) => Promise<unknown>;
2777
2828
  declare const headersToObject: (headers: Headers) => ResponseHeaders;
2778
2829
  //#endregion
2779
- export { jobRoutes as $, StreamBodyOf as $i, isJobDefinition as $n, AuthContextOf as $r, PluginsBySlug as $t, RenderedResult as A, BasicConfig as Aa, ToolRunOptions as Ai, RoutesOf as An, parseCron as Ar, sanitizeIdentifier as At, bearerChallenge as B, IdentityParamsOf as Ba, toolOptionsOf as Bi, JobHandler as Bn, GroupSet as Br, PluginApi as Bt, JOBS_META as C, toolEvents as Ca, isRouteDefinition as Ci, GeneratedFile as Cn, ParsedCron as Cr, resolveResponseBody as Ct, REQUEST_CONTEXT_META as D, withPermissions as Da, ToolAnswer as Di, GuardSchemaOf as Dn, firesBetween as Dr, resolveResponseHeaders as Dt, MountedOf as E, requiresDenial as Ea, StreamTools as Ei, ApiPluginsOf as En, dueSchedules as Er, resolveResponseEtag as Et, RouteMatcher as F, CredentialOf as Fa, buildToolInputSchema as Fi, CompiledJobs as Fn, RequestContextHeaderValues as Fr, AnyPlugin as Ft, dispatchRoute as G, RoleOf as Ga, PathParamsCheck as Gi, JobRunnerConfig as Gn, isRawResponse as Gr, PluginExportsOf as Gt, contractOf as H, NoCredential as Ha, ExtractPathParams as Hi, JobHandlerReturn as Hn, createGroups as Hr, PluginDeclaration as Ht, SCHEMES_META as I, CustomConfig as Ia, describeTool as Ii, FlattenedJob as In, RequestContextSchema as Ir, ApiPlugins as It, getHeaderValue as J, buildPath as Ji, JobsArg as Jn, RouteWithHandler as Jr, PluginRouteBuilder as Jt, entriesToObject as K, RolesOf as Ka, PathSegment as Ki, JobVoidReturn as Kn, rawResponse as Kr, PluginFactory as Kt, ServerOptions as L, GrantsOf as La, selectToolRoutes as Li, HttpJobsConfig as Ln, GroupOptions as Lr, InstallOptions as Lt, RequestContextRun as M, BearerConfig as Ma, ToolDefinition as Mi, AuthoredJobDefinition as Mn, scheduleTimezone as Mr, statusToCamelCase as Mt, RequestPipeline as N, BearerCredential as Na, ToolInputSchema as Ni, AuthoredJobs as Nn, RequestContextConfig as Nr, toCamelCase as Nt, ROUTER_META as O, ApiKeyConfig as Oa, ToolEventYield as Oi, JobsOf as On, nextRun as Or, resolveResponseStream as Ot, ResponseValidationError as P, Credential as Pa, buildToolDefinitions as Pi, CompiledJob as Pn, RequestContextHeaderInputs as Pr, toPascalCase as Pt, jobRouter as Q, StreamBody as Qi, isCompiledJob as Qn, sortFlattenedRoutes as Qr, PluginSetupContext as Qt, adapterContextOf as R, GuardHoldings as Ra, toolInputJsonSchema as Ri, InProcessJobsConfig as Rn, GroupPaths as Rr, PLUGIN_ROUTES_META_KEY as Rt, HandlerContextOf as S, expandStreamTools as Sa, formatValidationError as Si, DiffSettings as Sn, JobSchedule as Sr, mergeHeaderFields as St, MountArgsOf as T, insufficientScope as Ta, ModelToolCall as Ti, ApiDefinition as Tn, cron as Tr, resolveResponseContentType as Tt, defineAdapter as U, OAuth2Config as Ua, HasPathParams as Ui, JobHandlers as Un, isGroupSet as Ur, PluginDefinition as Ut, boundJobKeys as V, IdentityRole as Va, toolRefusal as Vi, JobHandlerArgs as Vn, ResolvedGroup as Vr, PluginArgs as Vt, dispatchHandler as W, OpenIdConnectConfig as Wa, PathParamName as Wi, JobResponses as Wn, RawResponse as Wr, PluginExportValues as Wt, headersToObject as X, EVENT_STREAM_MEDIA_TYPE as Xi, NoJobs as Xn, RouteMatch as Xr, PluginRoutesOf as Xt, guardDenyFor as Y, parsePath as Yi, JobsConfig as Yn, MatchResult as Yr, PluginRoutes as Yt, isGuardDenial as Z, EncodeStreamOptions as Zi, flattenJobs as Zn, matchRoute as Zr, PluginSetup as Zt, GuardDeny as _, ToolCall as _a, ThrowableReturn as _i, ConfiguredRequestContextSchemas as _n, JobTransportSupports as _r, isJsonMediaType as _t, AdapterRequest as a, StreamMode as aa, GuardReturn as ai, pluginRouteTree as an, JobQueueArgs as ar, runHandler as at, HANDLER_ARG_KEYS as b, ToolKeys as ba, allowedMethodsForPath as bi, KizunaConfigShape as bn, ScheduledJob as br, isZodSchema as bt, ApiBrand as c, isNamedStream as ca, HandlerArgs as ci, ConfiguredAdapterContext as cn, JobRunner as cr, ApiRouter as ct, DISPATCH_ROUTE_KEY as d, streamContentType as da, RawInputs as di, ConfiguredGroups as dn, jobFnAt as dr, createApiReference as dt, StreamChunk as ea, BrandedHandlerContext as ei, ResolvedPlugin as en, jobAt as er, jobRunnerFrom as et, ErrorFormatter as f, streamMode as fa, RequestContextValues as fi, ConfiguredGuardSchema as fn, JobDescriptor as fr, pluginExportsOf as ft, GuardDenialBody as g, ToolAt as ga, RoutesWithHandlerContext as gi, ConfiguredRequestContext as gn, JobTransportDefinition as gr, isHintPrefix as gt, GuardDenial as h, StreamWithTools as ha, Router as hi, ConfiguredPlugins as hn, JobTransport as hr, resolvePlugins as ht, AdapterDefinition as i, StreamMessageOf as ia, GuardParams as ii, definePlugin as in, JobInputError as ir, routerFromRoutes as it, RequestContextMap as j, BasicCredential as ja, ToolRunResult as ji, SchemesOf as jn, scheduleExpression as jr, shortTypeName as jt, RUN_ROUTE_KEY as k, ApiKeyCredential as ka, ToolRunCall as ki, RequestContextOf as kn, nextRuns as kr, sanitizeFieldName as kt, ApiParts as l, routeStreams as la, HandlerReturn as li, ConfiguredAdapterValue as ln, JobRunnerOptions as lr, ResponseError as lt, GUARD_SCHEMA_META as m, streamStatuses as ma, RouteHandler as mi, ConfiguredJobs as mn, JobMessage as mr, pluginRoutesOf as mt, API_META as n, StreamContext as na, FlattenedRoute as ni, RoutePathSchema as nn, JobFn as nr, parseFetchBody as nt, AdapterResult as o, StreamYield as oa, GuardSuccess as oi, route as on, JobQueueOptions as or, runRoute as ot, GUARDS_META as p, streamSchemas as pa, RouteGuardBrandOf as pi, ConfiguredIdentities as pn, JobDispatchError as pr, pluginRouterOf as pt, extractCredential as q, RoutePathParamsCheck as qi, Jobs as qn, RouteBuilder as qr, PluginList as qt, Adapter as r, StreamMessage as ra, GuardAnswer as ri, SlugOption as rn, JobFnByKey as rr, renderJsonResult as rt, AnyAdapter as s, encodeStreamBody as sa, GuardedParamNames as si, ApiContext as sn, JobRunArgs as sr, warnUnsupportedJobOptions as st, ADAPTER_CONTEXT as t, StreamComment as ta, ContextFromAuth as ti, RouteAuthSchema as tn, JobErrorHandler as tr, parseBodyText as tt, ApiWithRouter as u, soleStreamResponse as ua, HandlersFromRoutes as ui, ConfiguredCodes as un, createJobRunner as ur, groupRoutes as ut, GuardMap as v, ToolError as va, ValidationFailure as vi, JobFnOf as vn, JobWorker as vr, isStreamResponse as vt, JobsMeta as w, AccessCheckInput as wa, validateRequest as wi, apiEntries as wn, assertValidSchedule as wr, resolveResponseCache as wt, HandleArgs as x, ToolResult as xa, flattenRoutes as xi, ApiEntry as xn, defineJobTransport as xr, localTypeName as xt, GuardRun as y, ToolEvents as ya, ValidationStage as yi, JobsOfTree as yn, JobWorkerContext as yr, isSuccessStatus as yt, assembleApi as z, Identity as za, toolJsonSchema as zi, JobDefinition as zn, GroupPathsOf as zr, PLUGIN_SERVERS_META_KEY as zt };
2830
+ export { jobRouter as $, buildPath as $i, isCompiledJob as $n, SharedSegmentRoute as $r, PluginSetupContext as $t, RenderedResult as A, insufficientScope as Aa, ModelToolCall as Ai, RequestContextOf as An, nextRuns as Ar, sanitizeFieldName as At, bearerChallenge as B, CredentialOf as Ba, buildToolInputSchema as Bi, JobDefinition as Bn, GroupPathsOf as Br, PLUGIN_SERVERS_META_KEY as Bt, JOBS_META as C, ToolError as Ca, ValidationFailure as Ci, DiffSettings as Cn, JobSchedule as Cr, mergeHeaderFields as Ct, REQUEST_CONTEXT_META as D, expandStreamTools as Da, formatValidationError as Di, ApiPluginsOf as Dn, dueSchedules as Dr, resolveResponseEtag as Dt, MountedOf as E, ToolResult as Ea, flattenRoutes as Ei, ApiDefinition as En, cron as Er, resolveResponseContentType as Et, RouteMatcher as F, BasicConfig as Fa, ToolRunOptions as Fi, CompiledJob as Fn, RequestContextHeaderInputs as Fr, toPascalCase as Ft, dispatchHandler as G, IdentityParamsOf as Ga, toolOptionsOf as Gi, JobResponses as Gn, RawResponse as Gr, PluginExportValues as Gt, callGuard as H, GrantsOf as Ha, selectToolRoutes as Hi, JobHandlerArgs as Hn, ResolvedGroup as Hr, PluginArgs as Ht, SCHEMES_META as I, BasicCredential as Ia, ToolRunResult as Ii, CompiledJobs as In, RequestContextHeaderValues as Ir, AnyPlugin as It, extractCredential as J, OAuth2Config as Ja, HasPathParams as Ji, Jobs as Jn, RouteBuilder as Jr, PluginList as Jt, dispatchRoute as K, IdentityRole as Ka, toolRefusal as Ki, JobRunnerConfig as Kn, isRawResponse as Kr, PluginExportsOf as Kt, ServerOptions as L, BearerConfig as La, ToolDefinition as Li, FlattenedJob as Ln, RequestContextSchema as Lr, ApiPlugins as Lt, RequestContextRun as M, withPermissions as Ma, ToolAnswer as Mi, SchemesOf as Mn, scheduleExpression as Mr, shortTypeName as Mt, RequestPipeline as N, ApiKeyConfig as Na, ToolEventYield as Ni, AuthoredJobDefinition as Nn, scheduleTimezone as Nr, statusToCamelCase as Nt, ROUTER_META as O, toolEvents as Oa, isRouteDefinition as Oi, GuardSchemaOf as On, firesBetween as Or, resolveResponseHeaders as Ot, ResponseValidationError as P, ApiKeyCredential as Pa, ToolRunCall as Pi, AuthoredJobs as Pn, RequestContextConfig as Pr, toCamelCase as Pt, isGuardDenial as Q, RoutePathParamsCheck as Qi, flattenJobs as Qn, RouteMatch as Qr, PluginSetup as Qt, adapterContextOf as R, BearerCredential as Ra, ToolInputSchema as Ri, HttpJobsConfig as Rn, GroupOptions as Rr, InstallOptions as Rt, HandlerContextOf as S, ToolCall as Sa, ThrowableReturn as Si, ApiEntry as Sn, defineJobTransport as Sr, localTypeName as St, MountArgsOf as T, ToolKeys as Ta, allowedMethodsForPath as Ti, apiEntries as Tn, assertValidSchedule as Tr, resolveResponseCache as Tt, contractOf as U, GuardHoldings as Ua, toolInputJsonSchema as Ui, JobHandlerReturn as Un, createGroups as Ur, PluginDeclaration as Ut, boundJobKeys as V, CustomConfig as Va, describeTool as Vi, JobHandler as Vn, GroupSet as Vr, PluginApi as Vt, defineAdapter as W, Identity as Wa, toolJsonSchema as Wi, JobHandlers as Wn, isGroupSet as Wr, PluginDefinition as Wt, guardDenyFor as X, RoleOf as Xa, PathParamsCheck as Xi, JobsConfig as Xn, MatchResult as Xr, PluginRoutes as Xt, getHeaderValue as Y, OpenIdConnectConfig as Ya, PathParamName as Yi, JobsArg as Yn, RouteWithHandler as Yr, PluginRouteBuilder as Yt, headersToObject as Z, RolesOf as Za, PathSegment as Zi, NoJobs as Zn, PathParamsResult as Zr, PluginRoutesOf as Zt, GuardDeny as _, streamMode as _a, RequestContextValues as _i, ConfiguredRequestContext as _n, JobTransportDefinition as _r, isHintPrefix as _t, AdapterRequest as a, StreamChunk as aa, BrandedHandlerContext as ai, definePlugin as an, JobInputError as ar, routerFromRoutes as at, HANDLER_ARG_KEYS as b, StreamWithTools as ba, Router as bi, JobsOfTree as bn, JobWorkerContext as br, isSuccessStatus as bt, ApiBrand as c, StreamMessage as ca, GuardAnswer as ci, ApiContext as cn, JobRunArgs as cr, warnUnsupportedJobOptions as ct, DISPATCH_ROUTE_KEY as d, StreamYield as da, GuardSuccess as di, ConfiguredCodes as dn, createJobRunner as dr, groupRoutes as dt, parsePath as ea, isMalformedPath as ei, PluginsBySlug as en, isJobDefinition as er, jobRoutes as et, ErrorFormatter as f, encodeStreamBody as fa, GuardedParamNames as fi, ConfiguredGroups as fn, jobFnAt as fr, createApiReference as ft, GuardDenialBody as g, streamContentType as ga, RawInputs as gi, ConfiguredPlugins as gn, JobTransport as gr, resolvePlugins as gt, GuardDenial as h, soleStreamResponse as ha, HandlersFromRoutes as hi, ConfiguredJobs as hn, JobMessage as hr, pluginRoutesOf as ht, AdapterDefinition as i, StreamBodyOf as ia, AuthContextOf as ii, SlugOption as in, JobFnByKey as ir, renderJsonResult as it, RequestContextMap as j, requiresDenial as ja, StreamTools as ji, RoutesOf as jn, parseCron as jr, sanitizeIdentifier as jt, RUN_ROUTE_KEY as k, AccessCheckInput as ka, validateRequest as ki, JobsOf as kn, nextRun as kr, resolveResponseStream as kt, ApiParts as l, StreamMessageOf as la, GuardParams as li, ConfiguredAdapterContext as ln, JobRunner as lr, ApiRouter as lt, GUARD_SCHEMA_META as m, routeStreams as ma, HandlerReturn as mi, ConfiguredIdentities as mn, JobDispatchError as mr, pluginRouterOf as mt, API_META as n, EncodeStreamOptions as na, sharedSegmentRoute as ni, RouteAuthSchema as nn, JobErrorHandler as nr, parseBodyText as nt, AdapterResult as o, StreamComment as oa, ContextFromAuth as oi, pluginRouteTree as on, JobQueueArgs as or, runHandler as ot, GUARDS_META as p, isNamedStream as pa, HandlerArgs as pi, ConfiguredGuardSchema as pn, JobDescriptor as pr, pluginExportsOf as pt, entriesToObject as q, NoCredential as qa, ExtractPathParams as qi, JobVoidReturn as qn, rawResponse as qr, PluginFactory as qt, Adapter as r, StreamBody as ra, sortFlattenedRoutes as ri, RoutePathSchema as rn, JobFn as rr, parseFetchBody as rt, AnyAdapter as s, StreamContext as sa, FlattenedRoute as si, route as sn, JobQueueOptions as sr, runRoute as st, ADAPTER_CONTEXT as t, EVENT_STREAM_MEDIA_TYPE as ta, matchRoute as ti, ResolvedPlugin as tn, jobAt as tr, jobRunnerFrom as tt, ApiWithRouter as u, StreamMode as ua, GuardReturn as ui, ConfiguredAdapterValue as un, JobRunnerOptions as ur, ResponseError as ut, GuardMap as v, streamSchemas as va, RouteGuardBrandOf as vi, ConfiguredRequestContextSchemas as vn, JobTransportSupports as vr, isJsonMediaType as vt, JobsMeta as w, ToolEvents as wa, ValidationStage as wi, GeneratedFile as wn, ParsedCron as wr, resolveResponseBody as wt, HandleArgs as x, ToolAt as xa, RoutesWithHandlerContext as xi, KizunaConfigShape as xn, ScheduledJob as xr, isZodSchema as xt, GuardRun as y, streamStatuses as ya, RouteHandler as yi, JobFnOf as yn, JobWorker as yr, isStreamResponse as yt, assembleApi as z, Credential as za, buildToolDefinitions as zi, InProcessJobsConfig as zn, GroupPaths as zr, PLUGIN_ROUTES_META_KEY as zt };
@@ -907,15 +907,55 @@ interface RouteMatch {
907
907
  route: RouteDefinition;
908
908
  params: Record<string, string>;
909
909
  }
910
+ /**
911
+ * `malformed-path` is a path whose params hold a percent-encoding that does not decode (RFC 3986 section 2.1).
912
+ */
910
913
  type MatchResult = {
911
914
  kind: 'matched';
912
915
  match: RouteMatch;
913
916
  } | {
914
917
  kind: 'method-mismatch';
915
918
  allowed: Method[];
919
+ } | {
920
+ kind: 'malformed-path';
921
+ } | {
922
+ kind: 'not-found';
923
+ };
924
+ type PathParamsResult = {
925
+ kind: 'matched';
926
+ params: Record<string, string>;
927
+ } | {
928
+ kind: 'malformed-path';
916
929
  } | {
917
930
  kind: 'not-found';
918
931
  };
932
+ /**
933
+ * Whether a raw pathname holds a percent-encoding that does not decode, like `/users/%E0`.
934
+ */
935
+ declare const isMalformedPath: (pathname: string) => boolean;
936
+ interface SharedSegmentRoute {
937
+ /**
938
+ * The route's path with each segment that holds several params written as
939
+ * one param, for a router that reads one param per segment, like Hono's.
940
+ */
941
+ routerPath: string;
942
+ /**
943
+ * The route's params, read from the request's raw pathname the way
944
+ * `matchRoute` reads them.
945
+ */
946
+ readParams: (pathname: string) => PathParamsResult;
947
+ }
948
+ /**
949
+ * How an adapter mounts a route with several params in one segment, like
950
+ * `/range/:from-:to`, so the route gives the same params on every adapter.
951
+ * Returns `undefined` for any other route, which mounts on the framework's
952
+ * router as it is.
953
+ *
954
+ * @example
955
+ * const shared = sharedSegmentRoute('/range/:from-:to');
956
+ * shared?.readParams('/range/2024-01-2024-02');
957
+ */
958
+ declare const sharedSegmentRoute: (path: string) => SharedSegmentRoute | undefined;
919
959
  declare const sortFlattenedRoutes: <T extends {
920
960
  route: RouteDefinition;
921
961
  }>(routes: T[]) => T[];
@@ -2381,6 +2421,12 @@ declare const bearerChallenge: (parameters: Record<string, string | undefined>)
2381
2421
  */
2382
2422
  declare const guardDenyFor: (scheme: SecurityScheme | undefined) => GuardDeny<GuardDenialBody>;
2383
2423
  declare const isGuardDenial: (value: unknown) => value is GuardDenial;
2424
+ /**
2425
+ * Run a guard with the `deny` for its scheme. A guard that calls `deny` is
2426
+ * denied whether or not it returns the denial, and a returned denial wins over
2427
+ * one it only called.
2428
+ */
2429
+ declare const callGuard: <HandlerContext>(guard: GuardRun<HandlerContext>, scheme: SecurityScheme | undefined, args: Record<string, unknown>) => Promise<Record<string, unknown> | GuardDenial | void>;
2384
2430
  /**
2385
2431
  * The runtime behavior of a guard. It receives one object: the adapter's handler
2386
2432
  * context (e.g. `req`/`res`) plus the credential the identity's method extracted
@@ -2559,10 +2605,13 @@ interface AdapterRequest<NativeRequest> {
2559
2605
  /**
2560
2606
  * - `core-match`: core matches the path against the routes (Next-style catch-all routing).
2561
2607
  * - `pre-resolved`: adapter has already routed the request and tells core which route was matched (Express-style per-route registration).
2608
+ * - `malformed-path`: adapter has routed the request, but its params hold a percent-encoding that does not decode.
2562
2609
  */
2563
2610
  resolution: {
2564
2611
  kind: 'core-match';
2565
2612
  path: string;
2613
+ } | {
2614
+ kind: 'malformed-path';
2566
2615
  } | {
2567
2616
  kind: 'pre-resolved';
2568
2617
  routeKey: string;
@@ -2586,6 +2635,8 @@ interface AdapterRequest<NativeRequest> {
2586
2635
  */
2587
2636
  type AdapterResult = {
2588
2637
  kind: 'not-found';
2638
+ } | {
2639
+ kind: 'malformed-path';
2589
2640
  } | {
2590
2641
  kind: 'method-not-allowed';
2591
2642
  allowed: Method[];
@@ -2776,4 +2827,4 @@ declare const parseBodyText: (text: string, route: RouteDefinition) => unknown;
2776
2827
  declare const parseFetchBody: (request: Request, route: RouteDefinition) => Promise<unknown>;
2777
2828
  declare const headersToObject: (headers: Headers) => ResponseHeaders;
2778
2829
  //#endregion
2779
- export { jobRoutes as $, StreamBodyOf as $i, isJobDefinition as $n, AuthContextOf as $r, PluginsBySlug as $t, RenderedResult as A, BasicConfig as Aa, ToolRunOptions as Ai, RoutesOf as An, parseCron as Ar, sanitizeIdentifier as At, bearerChallenge as B, IdentityParamsOf as Ba, toolOptionsOf as Bi, JobHandler as Bn, GroupSet as Br, PluginApi as Bt, JOBS_META as C, toolEvents as Ca, isRouteDefinition as Ci, GeneratedFile as Cn, ParsedCron as Cr, resolveResponseBody as Ct, REQUEST_CONTEXT_META as D, withPermissions as Da, ToolAnswer as Di, GuardSchemaOf as Dn, firesBetween as Dr, resolveResponseHeaders as Dt, MountedOf as E, requiresDenial as Ea, StreamTools as Ei, ApiPluginsOf as En, dueSchedules as Er, resolveResponseEtag as Et, RouteMatcher as F, CredentialOf as Fa, buildToolInputSchema as Fi, CompiledJobs as Fn, RequestContextHeaderValues as Fr, AnyPlugin as Ft, dispatchRoute as G, RoleOf as Ga, PathParamsCheck as Gi, JobRunnerConfig as Gn, isRawResponse as Gr, PluginExportsOf as Gt, contractOf as H, NoCredential as Ha, ExtractPathParams as Hi, JobHandlerReturn as Hn, createGroups as Hr, PluginDeclaration as Ht, SCHEMES_META as I, CustomConfig as Ia, describeTool as Ii, FlattenedJob as In, RequestContextSchema as Ir, ApiPlugins as It, getHeaderValue as J, buildPath as Ji, JobsArg as Jn, RouteWithHandler as Jr, PluginRouteBuilder as Jt, entriesToObject as K, RolesOf as Ka, PathSegment as Ki, JobVoidReturn as Kn, rawResponse as Kr, PluginFactory as Kt, ServerOptions as L, GrantsOf as La, selectToolRoutes as Li, HttpJobsConfig as Ln, GroupOptions as Lr, InstallOptions as Lt, RequestContextRun as M, BearerConfig as Ma, ToolDefinition as Mi, AuthoredJobDefinition as Mn, scheduleTimezone as Mr, statusToCamelCase as Mt, RequestPipeline as N, BearerCredential as Na, ToolInputSchema as Ni, AuthoredJobs as Nn, RequestContextConfig as Nr, toCamelCase as Nt, ROUTER_META as O, ApiKeyConfig as Oa, ToolEventYield as Oi, JobsOf as On, nextRun as Or, resolveResponseStream as Ot, ResponseValidationError as P, Credential as Pa, buildToolDefinitions as Pi, CompiledJob as Pn, RequestContextHeaderInputs as Pr, toPascalCase as Pt, jobRouter as Q, StreamBody as Qi, isCompiledJob as Qn, sortFlattenedRoutes as Qr, PluginSetupContext as Qt, adapterContextOf as R, GuardHoldings as Ra, toolInputJsonSchema as Ri, InProcessJobsConfig as Rn, GroupPaths as Rr, PLUGIN_ROUTES_META_KEY as Rt, HandlerContextOf as S, expandStreamTools as Sa, formatValidationError as Si, DiffSettings as Sn, JobSchedule as Sr, mergeHeaderFields as St, MountArgsOf as T, insufficientScope as Ta, ModelToolCall as Ti, ApiDefinition as Tn, cron as Tr, resolveResponseContentType as Tt, defineAdapter as U, OAuth2Config as Ua, HasPathParams as Ui, JobHandlers as Un, isGroupSet as Ur, PluginDefinition as Ut, boundJobKeys as V, IdentityRole as Va, toolRefusal as Vi, JobHandlerArgs as Vn, ResolvedGroup as Vr, PluginArgs as Vt, dispatchHandler as W, OpenIdConnectConfig as Wa, PathParamName as Wi, JobResponses as Wn, RawResponse as Wr, PluginExportValues as Wt, headersToObject as X, EVENT_STREAM_MEDIA_TYPE as Xi, NoJobs as Xn, RouteMatch as Xr, PluginRoutesOf as Xt, guardDenyFor as Y, parsePath as Yi, JobsConfig as Yn, MatchResult as Yr, PluginRoutes as Yt, isGuardDenial as Z, EncodeStreamOptions as Zi, flattenJobs as Zn, matchRoute as Zr, PluginSetup as Zt, GuardDeny as _, ToolCall as _a, ThrowableReturn as _i, ConfiguredRequestContextSchemas as _n, JobTransportSupports as _r, isJsonMediaType as _t, AdapterRequest as a, StreamMode as aa, GuardReturn as ai, pluginRouteTree as an, JobQueueArgs as ar, runHandler as at, HANDLER_ARG_KEYS as b, ToolKeys as ba, allowedMethodsForPath as bi, KizunaConfigShape as bn, ScheduledJob as br, isZodSchema as bt, ApiBrand as c, isNamedStream as ca, HandlerArgs as ci, ConfiguredAdapterContext as cn, JobRunner as cr, ApiRouter as ct, DISPATCH_ROUTE_KEY as d, streamContentType as da, RawInputs as di, ConfiguredGroups as dn, jobFnAt as dr, createApiReference as dt, StreamChunk as ea, BrandedHandlerContext as ei, ResolvedPlugin as en, jobAt as er, jobRunnerFrom as et, ErrorFormatter as f, streamMode as fa, RequestContextValues as fi, ConfiguredGuardSchema as fn, JobDescriptor as fr, pluginExportsOf as ft, GuardDenialBody as g, ToolAt as ga, RoutesWithHandlerContext as gi, ConfiguredRequestContext as gn, JobTransportDefinition as gr, isHintPrefix as gt, GuardDenial as h, StreamWithTools as ha, Router as hi, ConfiguredPlugins as hn, JobTransport as hr, resolvePlugins as ht, AdapterDefinition as i, StreamMessageOf as ia, GuardParams as ii, definePlugin as in, JobInputError as ir, routerFromRoutes as it, RequestContextMap as j, BasicCredential as ja, ToolRunResult as ji, SchemesOf as jn, scheduleExpression as jr, shortTypeName as jt, RUN_ROUTE_KEY as k, ApiKeyCredential as ka, ToolRunCall as ki, RequestContextOf as kn, nextRuns as kr, sanitizeFieldName as kt, ApiParts as l, routeStreams as la, HandlerReturn as li, ConfiguredAdapterValue as ln, JobRunnerOptions as lr, ResponseError as lt, GUARD_SCHEMA_META as m, streamStatuses as ma, RouteHandler as mi, ConfiguredJobs as mn, JobMessage as mr, pluginRoutesOf as mt, API_META as n, StreamContext as na, FlattenedRoute as ni, RoutePathSchema as nn, JobFn as nr, parseFetchBody as nt, AdapterResult as o, StreamYield as oa, GuardSuccess as oi, route as on, JobQueueOptions as or, runRoute as ot, GUARDS_META as p, streamSchemas as pa, RouteGuardBrandOf as pi, ConfiguredIdentities as pn, JobDispatchError as pr, pluginRouterOf as pt, extractCredential as q, RoutePathParamsCheck as qi, Jobs as qn, RouteBuilder as qr, PluginList as qt, Adapter as r, StreamMessage as ra, GuardAnswer as ri, SlugOption as rn, JobFnByKey as rr, renderJsonResult as rt, AnyAdapter as s, encodeStreamBody as sa, GuardedParamNames as si, ApiContext as sn, JobRunArgs as sr, warnUnsupportedJobOptions as st, ADAPTER_CONTEXT as t, StreamComment as ta, ContextFromAuth as ti, RouteAuthSchema as tn, JobErrorHandler as tr, parseBodyText as tt, ApiWithRouter as u, soleStreamResponse as ua, HandlersFromRoutes as ui, ConfiguredCodes as un, createJobRunner as ur, groupRoutes as ut, GuardMap as v, ToolError as va, ValidationFailure as vi, JobFnOf as vn, JobWorker as vr, isStreamResponse as vt, JobsMeta as w, AccessCheckInput as wa, validateRequest as wi, apiEntries as wn, assertValidSchedule as wr, resolveResponseCache as wt, HandleArgs as x, ToolResult as xa, flattenRoutes as xi, ApiEntry as xn, defineJobTransport as xr, localTypeName as xt, GuardRun as y, ToolEvents as ya, ValidationStage as yi, JobsOfTree as yn, JobWorkerContext as yr, isSuccessStatus as yt, assembleApi as z, Identity as za, toolJsonSchema as zi, JobDefinition as zn, GroupPathsOf as zr, PLUGIN_SERVERS_META_KEY as zt };
2830
+ export { jobRouter as $, buildPath as $i, isCompiledJob as $n, SharedSegmentRoute as $r, PluginSetupContext as $t, RenderedResult as A, insufficientScope as Aa, ModelToolCall as Ai, RequestContextOf as An, nextRuns as Ar, sanitizeFieldName as At, bearerChallenge as B, CredentialOf as Ba, buildToolInputSchema as Bi, JobDefinition as Bn, GroupPathsOf as Br, PLUGIN_SERVERS_META_KEY as Bt, JOBS_META as C, ToolError as Ca, ValidationFailure as Ci, DiffSettings as Cn, JobSchedule as Cr, mergeHeaderFields as Ct, REQUEST_CONTEXT_META as D, expandStreamTools as Da, formatValidationError as Di, ApiPluginsOf as Dn, dueSchedules as Dr, resolveResponseEtag as Dt, MountedOf as E, ToolResult as Ea, flattenRoutes as Ei, ApiDefinition as En, cron as Er, resolveResponseContentType as Et, RouteMatcher as F, BasicConfig as Fa, ToolRunOptions as Fi, CompiledJob as Fn, RequestContextHeaderInputs as Fr, toPascalCase as Ft, dispatchHandler as G, IdentityParamsOf as Ga, toolOptionsOf as Gi, JobResponses as Gn, RawResponse as Gr, PluginExportValues as Gt, callGuard as H, GrantsOf as Ha, selectToolRoutes as Hi, JobHandlerArgs as Hn, ResolvedGroup as Hr, PluginArgs as Ht, SCHEMES_META as I, BasicCredential as Ia, ToolRunResult as Ii, CompiledJobs as In, RequestContextHeaderValues as Ir, AnyPlugin as It, extractCredential as J, OAuth2Config as Ja, HasPathParams as Ji, Jobs as Jn, RouteBuilder as Jr, PluginList as Jt, dispatchRoute as K, IdentityRole as Ka, toolRefusal as Ki, JobRunnerConfig as Kn, isRawResponse as Kr, PluginExportsOf as Kt, ServerOptions as L, BearerConfig as La, ToolDefinition as Li, FlattenedJob as Ln, RequestContextSchema as Lr, ApiPlugins as Lt, RequestContextRun as M, withPermissions as Ma, ToolAnswer as Mi, SchemesOf as Mn, scheduleExpression as Mr, shortTypeName as Mt, RequestPipeline as N, ApiKeyConfig as Na, ToolEventYield as Ni, AuthoredJobDefinition as Nn, scheduleTimezone as Nr, statusToCamelCase as Nt, ROUTER_META as O, toolEvents as Oa, isRouteDefinition as Oi, GuardSchemaOf as On, firesBetween as Or, resolveResponseHeaders as Ot, ResponseValidationError as P, ApiKeyCredential as Pa, ToolRunCall as Pi, AuthoredJobs as Pn, RequestContextConfig as Pr, toCamelCase as Pt, isGuardDenial as Q, RoutePathParamsCheck as Qi, flattenJobs as Qn, RouteMatch as Qr, PluginSetup as Qt, adapterContextOf as R, BearerCredential as Ra, ToolInputSchema as Ri, HttpJobsConfig as Rn, GroupOptions as Rr, InstallOptions as Rt, HandlerContextOf as S, ToolCall as Sa, ThrowableReturn as Si, ApiEntry as Sn, defineJobTransport as Sr, localTypeName as St, MountArgsOf as T, ToolKeys as Ta, allowedMethodsForPath as Ti, apiEntries as Tn, assertValidSchedule as Tr, resolveResponseCache as Tt, contractOf as U, GuardHoldings as Ua, toolInputJsonSchema as Ui, JobHandlerReturn as Un, createGroups as Ur, PluginDeclaration as Ut, boundJobKeys as V, CustomConfig as Va, describeTool as Vi, JobHandler as Vn, GroupSet as Vr, PluginApi as Vt, defineAdapter as W, Identity as Wa, toolJsonSchema as Wi, JobHandlers as Wn, isGroupSet as Wr, PluginDefinition as Wt, guardDenyFor as X, RoleOf as Xa, PathParamsCheck as Xi, JobsConfig as Xn, MatchResult as Xr, PluginRoutes as Xt, getHeaderValue as Y, OpenIdConnectConfig as Ya, PathParamName as Yi, JobsArg as Yn, RouteWithHandler as Yr, PluginRouteBuilder as Yt, headersToObject as Z, RolesOf as Za, PathSegment as Zi, NoJobs as Zn, PathParamsResult as Zr, PluginRoutesOf as Zt, GuardDeny as _, streamMode as _a, RequestContextValues as _i, ConfiguredRequestContext as _n, JobTransportDefinition as _r, isHintPrefix as _t, AdapterRequest as a, StreamChunk as aa, BrandedHandlerContext as ai, definePlugin as an, JobInputError as ar, routerFromRoutes as at, HANDLER_ARG_KEYS as b, StreamWithTools as ba, Router as bi, JobsOfTree as bn, JobWorkerContext as br, isSuccessStatus as bt, ApiBrand as c, StreamMessage as ca, GuardAnswer as ci, ApiContext as cn, JobRunArgs as cr, warnUnsupportedJobOptions as ct, DISPATCH_ROUTE_KEY as d, StreamYield as da, GuardSuccess as di, ConfiguredCodes as dn, createJobRunner as dr, groupRoutes as dt, parsePath as ea, isMalformedPath as ei, PluginsBySlug as en, isJobDefinition as er, jobRoutes as et, ErrorFormatter as f, encodeStreamBody as fa, GuardedParamNames as fi, ConfiguredGroups as fn, jobFnAt as fr, createApiReference as ft, GuardDenialBody as g, streamContentType as ga, RawInputs as gi, ConfiguredPlugins as gn, JobTransport as gr, resolvePlugins as gt, GuardDenial as h, soleStreamResponse as ha, HandlersFromRoutes as hi, ConfiguredJobs as hn, JobMessage as hr, pluginRoutesOf as ht, AdapterDefinition as i, StreamBodyOf as ia, AuthContextOf as ii, SlugOption as in, JobFnByKey as ir, renderJsonResult as it, RequestContextMap as j, requiresDenial as ja, StreamTools as ji, RoutesOf as jn, parseCron as jr, sanitizeIdentifier as jt, RUN_ROUTE_KEY as k, AccessCheckInput as ka, validateRequest as ki, JobsOf as kn, nextRun as kr, resolveResponseStream as kt, ApiParts as l, StreamMessageOf as la, GuardParams as li, ConfiguredAdapterContext as ln, JobRunner as lr, ApiRouter as lt, GUARD_SCHEMA_META as m, routeStreams as ma, HandlerReturn as mi, ConfiguredIdentities as mn, JobDispatchError as mr, pluginRouterOf as mt, API_META as n, EncodeStreamOptions as na, sharedSegmentRoute as ni, RouteAuthSchema as nn, JobErrorHandler as nr, parseBodyText as nt, AdapterResult as o, StreamComment as oa, ContextFromAuth as oi, pluginRouteTree as on, JobQueueArgs as or, runHandler as ot, GUARDS_META as p, isNamedStream as pa, HandlerArgs as pi, ConfiguredGuardSchema as pn, JobDescriptor as pr, pluginExportsOf as pt, entriesToObject as q, NoCredential as qa, ExtractPathParams as qi, JobVoidReturn as qn, rawResponse as qr, PluginFactory as qt, Adapter as r, StreamBody as ra, sortFlattenedRoutes as ri, RoutePathSchema as rn, JobFn as rr, parseFetchBody as rt, AnyAdapter as s, StreamContext as sa, FlattenedRoute as si, route as sn, JobQueueOptions as sr, runRoute as st, ADAPTER_CONTEXT as t, EVENT_STREAM_MEDIA_TYPE as ta, matchRoute as ti, ResolvedPlugin as tn, jobAt as tr, jobRunnerFrom as tt, ApiWithRouter as u, StreamMode as ua, GuardReturn as ui, ConfiguredAdapterValue as un, JobRunnerOptions as ur, ResponseError as ut, GuardMap as v, streamSchemas as va, RouteGuardBrandOf as vi, ConfiguredRequestContextSchemas as vn, JobTransportSupports as vr, isJsonMediaType as vt, JobsMeta as w, ToolEvents as wa, ValidationStage as wi, GeneratedFile as wn, ParsedCron as wr, resolveResponseBody as wt, HandleArgs as x, ToolAt as xa, RoutesWithHandlerContext as xi, KizunaConfigShape as xn, ScheduledJob as xr, isZodSchema as xt, GuardRun as y, streamStatuses as ya, RouteHandler as yi, JobFnOf as yn, JobWorker as yr, isStreamResponse as yt, assembleApi as z, Credential as za, buildToolDefinitions as zi, InProcessJobsConfig as zn, GroupPaths as zr, PLUGIN_ROUTES_META_KEY as zt };
@@ -1,6 +1,6 @@
1
1
  import { g as ROUTES_GROUP, n as PLUGIN_SERVERS_META_KEY, o as pluginRouteTree, p as HANDLER, t as PLUGIN_ROUTES_META_KEY } from "./plugin-xxCxibmu.mjs";
2
2
  import { D as resolveBaseType, E as readObjectShape, O as unwrapOptionalWrappers, c as isBinarySchema, m as readDef, o as findCoercedSchemaPath, p as isVoidSchema, t as ProblemDetailsSchema, u as isFileSchema } from "./error-response-D7urgxeq.mjs";
3
- import { A as deriveToolNames, B as streamSchemas, G as isSuccessStatus, I as routeStreams, K as isZodSchema, M as EVENT_STREAM_MEDIA_TYPE, N as assertValidStreams, P as encodeStreamBody, Q as resolveResponseEtag, R as streamContentType, S as dueSchedules, U as isJsonMediaType, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, c as cacheHeaders, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, k as encodeForWire, lt as allowedMethodsForPath, m as flattenJobs, mt as resolveCoercionPlans, pt as validateRequest, u as deprecationHeaders, ut as flattenRoutes, y as toJobResponse } from "./plugin-server-B-JDZ7GV.mjs";
3
+ import { A as deriveToolNames, B as streamSchemas, G as isSuccessStatus, I as routeStreams, K as isZodSchema, M as EVENT_STREAM_MEDIA_TYPE, N as assertValidStreams, P as encodeStreamBody, Q as resolveResponseEtag, R as streamContentType, S as dueSchedules, U as isJsonMediaType, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, c as cacheHeaders, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, k as encodeForWire, lt as allowedMethodsForPath, m as flattenJobs, mt as resolveCoercionPlans, pt as validateRequest, u as deprecationHeaders, ut as flattenRoutes, y as toJobResponse } from "./plugin-server-D8XrYDQU.mjs";
4
4
  import { l as authenticationChallenge, p as resolveSecurityRequirements } from "./schemas-DBX8DwFb.mjs";
5
5
  import { z } from "zod";
6
6
  //#region src/tool-definitions.ts
@@ -803,6 +803,33 @@ var ResponseError = class extends Error {
803
803
  }
804
804
  };
805
805
  //#endregion
806
+ //#region src/wait-until.ts
807
+ /**
808
+ * The longest delay `setTimeout` holds. Node fires a longer one at once.
809
+ */
810
+ const LONGEST_TIMER_DELAY = 2 ** 31 - 1;
811
+ /**
812
+ * Run `callback` at `time`, in milliseconds since the epoch, however far away
813
+ * it is. The wait goes in steps one timer can hold and checks the clock after
814
+ * each one.
815
+ */
816
+ const waitUntil = (time, callback) => {
817
+ let timer;
818
+ const arm = () => {
819
+ const remaining = Math.max(time - Date.now(), 0);
820
+ timer = setTimeout(() => {
821
+ if (Date.now() < time) {
822
+ arm();
823
+ return;
824
+ }
825
+ callback();
826
+ }, Math.min(remaining, LONGEST_TIMER_DELAY));
827
+ timer.unref?.();
828
+ };
829
+ arm();
830
+ return { cancel: () => clearTimeout(timer) };
831
+ };
832
+ //#endregion
806
833
  //#region src/job-runner.ts
807
834
  var JobInputError = class extends Error {
808
835
  job;
@@ -886,12 +913,12 @@ const createJobRunner = (source, handlers, options) => {
886
913
  console.error(`[kizuna] Queued job "${jobKey}" failed:`, error);
887
914
  });
888
915
  };
889
- const delay = runAt ? runAt.getTime() - Date.now() : 0;
890
- if (delay <= 0) {
916
+ const time = runAt?.getTime();
917
+ if (time === void 0 || time <= Date.now()) {
891
918
  start();
892
919
  return;
893
920
  }
894
- setTimeout(start, delay).unref?.();
921
+ waitUntil(time, start);
895
922
  };
896
923
  /**
897
924
  * Once per job and option: a `queue` in a loop should not bury the log.
@@ -1073,19 +1100,92 @@ const requiresDenial = (input) => {
1073
1100
  //#endregion
1074
1101
  //#region src/route-matcher.ts
1075
1102
  const REGEX_ESCAPE = /[.+?^${}()|[\]\\]/g;
1076
- const compileRoute = (routeKey, route) => {
1077
- const { segments, paramNames } = parsePath(route.path);
1103
+ const CHARACTER_CLASS_ESCAPE = /[\\\]^-]/g;
1104
+ const escapeLiteral = (text) => text.replace(REGEX_ESCAPE, "\\$&");
1105
+ /**
1106
+ * A param that follows another in the same segment, like `:to` in
1107
+ * `/range/:from-:to`. It cannot contain the text between the two, apart from
1108
+ * being exactly that text, so a path that fails to match fails in linear time
1109
+ * instead of trying every split of the segment. So the last param takes what
1110
+ * follows the last separator, and the param before it takes the rest.
1111
+ */
1112
+ const paramAfter = (separator) => {
1113
+ return `(${separator.length === 1 ? `[^/${separator.replace(CHARACTER_CLASS_ESCAPE, "\\$&")}]` : `(?:(?!${escapeLiteral(separator)})[^/])`}+|${escapeLiteral(separator)})`;
1114
+ };
1115
+ const compilePath = (path) => {
1116
+ const { segments, paramNames } = parsePath(path);
1078
1117
  let body = "";
1079
- for (const segment of segments) if (segment.kind === "literal") body += segment.value.replace(REGEX_ESCAPE, "\\$&");
1080
- else body += "([^/]+)";
1118
+ let separator;
1119
+ for (const segment of segments) if (segment.kind === "literal") {
1120
+ body += escapeLiteral(segment.value);
1121
+ separator = separator === void 0 || segment.value.includes("/") ? void 0 : separator + segment.value;
1122
+ } else {
1123
+ body += separator ? paramAfter(separator) : "([^/]+)";
1124
+ separator = "";
1125
+ }
1081
1126
  return {
1082
- routeKey,
1083
- route,
1084
1127
  segments,
1085
1128
  paramNames,
1086
1129
  pattern: new RegExp(`^${body}$`)
1087
1130
  };
1088
1131
  };
1132
+ const compileRoute = (routeKey, route) => ({
1133
+ routeKey,
1134
+ route,
1135
+ ...compilePath(route.path)
1136
+ });
1137
+ const decoded = (text) => {
1138
+ try {
1139
+ return decodeURIComponent(text);
1140
+ } catch {
1141
+ return;
1142
+ }
1143
+ };
1144
+ /**
1145
+ * Whether a raw pathname holds a percent-encoding that does not decode, like `/users/%E0`.
1146
+ */
1147
+ const isMalformedPath = (pathname) => pathname.split("/").some((segment) => decoded(segment) === void 0);
1148
+ const paramsOf = (paramNames, result) => {
1149
+ const params = {};
1150
+ for (const [index, name] of paramNames.entries()) {
1151
+ const captured = result[index + 1];
1152
+ if (captured === void 0) continue;
1153
+ const value = decoded(captured);
1154
+ if (value === void 0) return { kind: "malformed-path" };
1155
+ params[name] = value;
1156
+ }
1157
+ return {
1158
+ kind: "matched",
1159
+ params
1160
+ };
1161
+ };
1162
+ /**
1163
+ * How an adapter mounts a route with several params in one segment, like
1164
+ * `/range/:from-:to`, so the route gives the same params on every adapter.
1165
+ * Returns `undefined` for any other route, which mounts on the framework's
1166
+ * router as it is.
1167
+ *
1168
+ * @example
1169
+ * const shared = sharedSegmentRoute('/range/:from-:to');
1170
+ * shared?.readParams('/range/2024-01-2024-02');
1171
+ */
1172
+ const sharedSegmentRoute = (path) => {
1173
+ const pathSegments = path.split("/");
1174
+ const holdsSeveral = (segment) => parsePath(segment).paramNames.length > 1;
1175
+ if (!pathSegments.some(holdsSeveral)) return void 0;
1176
+ let sharedIndex = 0;
1177
+ const routerPath = pathSegments.map((segment) => holdsSeveral(segment) ? `:kizunaSegment${sharedIndex++}` : segment).join("/");
1178
+ const { paramNames, pattern } = compilePath(path);
1179
+ return {
1180
+ routerPath,
1181
+ readParams: (pathname) => {
1182
+ const tail = pathname.split("/").slice(1 - pathSegments.length);
1183
+ const result = pattern.exec("/" + tail.join("/"));
1184
+ if (!result) return { kind: "not-found" };
1185
+ return paramsOf(paramNames, result);
1186
+ }
1187
+ };
1188
+ };
1089
1189
  const cache = /* @__PURE__ */ new WeakMap();
1090
1190
  const getCompiled = (routes) => {
1091
1191
  const existing = cache.get(routes);
@@ -1127,17 +1227,14 @@ const sortFlattenedRoutes = (routes) => {
1127
1227
  return parsed.map((p) => p.entry);
1128
1228
  };
1129
1229
  const toMatch = (candidate, result) => {
1130
- const params = {};
1131
- candidate.paramNames.forEach((name, index) => {
1132
- const captured = result[index + 1];
1133
- if (captured !== void 0) params[name] = decodeURIComponent(captured);
1134
- });
1230
+ const params = paramsOf(candidate.paramNames, result);
1231
+ if (params.kind !== "matched") return params;
1135
1232
  return {
1136
1233
  kind: "matched",
1137
1234
  match: {
1138
1235
  routeKey: candidate.routeKey,
1139
1236
  route: candidate.route,
1140
- params
1237
+ params: params.params
1141
1238
  }
1142
1239
  };
1143
1240
  };
@@ -1435,6 +1532,24 @@ const guardDenyFor = (scheme) => {
1435
1532
  };
1436
1533
  const isGuardDenial = (value) => typeof value === "object" && value !== null && GUARD_DENY in value;
1437
1534
  /**
1535
+ * Run a guard with the `deny` for its scheme. A guard that calls `deny` is
1536
+ * denied whether or not it returns the denial, and a returned denial wins over
1537
+ * one it only called.
1538
+ */
1539
+ const callGuard = async (guard, scheme, args) => {
1540
+ const buildDenial = guardDenyFor(scheme);
1541
+ let calledDenial;
1542
+ const result = await guard({
1543
+ ...args,
1544
+ deny: (denial) => {
1545
+ const built = buildDenial(denial);
1546
+ calledDenial ??= built;
1547
+ return built;
1548
+ }
1549
+ });
1550
+ return isGuardDenial(result) ? result : calledDenial ?? result;
1551
+ };
1552
+ /**
1438
1553
  * The api's own definition, for plugins needing more than the routes.
1439
1554
  */
1440
1555
  const contractOf = (api) => api[CONTRACT_META];
@@ -1769,7 +1884,11 @@ const resolveRoute = (request, routes, matcher, basePath) => {
1769
1884
  params: request.resolution.params
1770
1885
  }
1771
1886
  };
1772
- const matched = matcher(request.method, request.resolution.path, routes, basePath);
1887
+ const matched = request.resolution.kind === "malformed-path" ? request.resolution : matcher(request.method, request.resolution.path, routes, basePath);
1888
+ if (matched.kind === "malformed-path") return {
1889
+ ok: false,
1890
+ result: { kind: "malformed-path" }
1891
+ };
1773
1892
  if (matched.kind === "not-found") return {
1774
1893
  ok: false,
1775
1894
  result: { kind: "not-found" }
@@ -1830,6 +1949,7 @@ const withDeprecationHeaders = (result, route) => {
1830
1949
  switch (result.kind) {
1831
1950
  case "raw-response":
1832
1951
  case "not-found":
1952
+ case "malformed-path":
1833
1953
  case "method-not-allowed": return result;
1834
1954
  default: {
1835
1955
  const announced = deprecationHeaders(route);
@@ -1853,6 +1973,7 @@ const statusOf = (result) => {
1853
1973
  switch (result.kind) {
1854
1974
  case "raw-response":
1855
1975
  case "not-found":
1976
+ case "malformed-path":
1856
1977
  case "method-not-allowed": return;
1857
1978
  case "success":
1858
1979
  case "guard-denied": return result.status;
@@ -1873,7 +1994,7 @@ const statusOf = (result) => {
1873
1994
  * headers alone.
1874
1995
  */
1875
1996
  const withCacheHeaders = (result, route) => {
1876
- if (result.kind === "raw-response" || result.kind === "not-found" || result.kind === "method-not-allowed") return result;
1997
+ if (result.kind === "raw-response" || result.kind === "not-found" || result.kind === "malformed-path" || result.kind === "method-not-allowed") return result;
1877
1998
  const status = statusOf(result);
1878
1999
  if (status === void 0) return result;
1879
2000
  const policy = cacheHeaders(resolveResponseCache(route.responses[status]));
@@ -2079,11 +2200,10 @@ const invokeRoute = async (invocation) => {
2079
2200
  if (!guard) throw new Error(`No guard registered for security scheme "${scheme}" required by route "${routeKey}".`);
2080
2201
  const schemeDefinition = schemes?.[scheme];
2081
2202
  const credential = schemeDefinition ? extractCredential(schemeDefinition, request) : {};
2082
- const guardResult = await guard({
2203
+ const guardResult = await callGuard(guard, schemeDefinition, {
2083
2204
  ...handlerContext,
2084
2205
  ...credential,
2085
2206
  params,
2086
- deny: guardDenyFor(schemeDefinition),
2087
2207
  ...hasRequestContext ? { requestContext } : {}
2088
2208
  });
2089
2209
  if (isGuardDenial(guardResult)) {
@@ -2293,6 +2413,7 @@ const renderResult = (result, formatError, request) => {
2293
2413
  }
2294
2414
  case "not-found": return renderError(404, "Not Found");
2295
2415
  case "method-not-allowed": return renderError(405, "Method Not Allowed", { allowed: result.allowed }, { allow: result.allowed.join(", ") });
2416
+ case "malformed-path": return renderError(400, "The path holds a percent-encoding that does not decode.");
2296
2417
  case "invalid-body": return renderError(400, result.detail, void 0, result.headers);
2297
2418
  case "validation-failed": return renderError(400, result.detail, { errors: result.issues.map((issue) => ({
2298
2419
  code: issue.code ?? "custom",
@@ -2351,4 +2472,4 @@ const headersToObject = (headers) => {
2351
2472
  return result;
2352
2473
  };
2353
2474
  //#endregion
2354
- export { dispatchDueJobs as $, parseFetchBody as A, matchRoute as B, guardDenyFor as C, toolJsonSchema as Ct, jobRoutes as D, jobRouter as E, warnUnsupportedJobOptions as F, JobDispatchError as G, insufficientScope as H, isRawResponse as I, createJobRunner as J, defineJobTransport as K, rawResponse as L, routerFromRoutes as M, runHandler as N, jobRunnerFrom as O, runRoute as P, DispatchResultSchema as Q, assertNoPathCollisions as R, getHeaderValue as S, toolInputJsonSchema as St, isGuardDenial as T, toolRefusal as Tt, requiresDenial as U, sortFlattenedRoutes as V, withPermissions as W, ResponseError as X, jobFnAt as Y, DispatchFailedSchema as Z, defineAdapter as _, toolEvents as _t, HANDLER_ARG_KEYS as a, STATUS_TITLES as at, entriesToObject as b, describeTool as bt, ROUTER_META as c, createRoles as ct, SCHEMES_META as d, permissionNames as dt, dispatchSucceeded as et, adapterContextOf as f, createGroups as ft, contractOf as g, expandStreamTools as gt, boundJobKeys as h, groupRoutes as ht, GUARD_SCHEMA_META as i, problemFromBody as it, renderJsonResult as j, parseBodyText as k, RUN_ROUTE_KEY as l, isPermissions as lt, bearerChallenge as m, assembleRoutes as mt, DISPATCH_ROUTE_KEY as n, failedJobs as nt, JOBS_META as o, getStatusText as ot, assembleApi as p, isGroupSet as pt, JobInputError as q, GUARDS_META as r, problemDetails as rt, REQUEST_CONTEXT_META as s, createPermissions as st, API_META as t, dueJobs as tt, ResponseValidationError as u, isRoles as ut, dispatchHandler as v, buildToolDefinitions as vt, headersToObject as w, toolOptionsOf as wt, extractCredential as x, selectToolRoutes as xt, dispatchRoute as y, buildToolInputSchema as yt, routeClaims as z };
2475
+ export { waitUntil as $, parseBodyText as A, toolRefusal as At, routeClaims as B, getHeaderValue as C, buildToolDefinitions as Ct, jobRouter as D, toolInputJsonSchema as Dt, isGuardDenial as E, selectToolRoutes as Et, runRoute as F, insufficientScope as G, matchRoute as H, warnUnsupportedJobOptions as I, JobDispatchError as J, requiresDenial as K, isRawResponse as L, renderJsonResult as M, routerFromRoutes as N, jobRoutes as O, toolJsonSchema as Ot, runHandler as P, jobFnAt as Q, rawResponse as R, extractCredential as S, toolEvents as St, headersToObject as T, describeTool as Tt, sharedSegmentRoute as U, isMalformedPath as V, sortFlattenedRoutes as W, JobInputError as X, defineJobTransport as Y, createJobRunner as Z, contractOf as _, isGroupSet as _t, HANDLER_ARG_KEYS as a, dueJobs as at, dispatchRoute as b, expandStreamTools as bt, ROUTER_META as c, problemFromBody as ct, SCHEMES_META as d, createPermissions as dt, ResponseError as et, adapterContextOf as f, createRoles as ft, callGuard as g, createGroups as gt, boundJobKeys as h, permissionNames as ht, GUARD_SCHEMA_META as i, dispatchSucceeded as it, parseFetchBody as j, jobRunnerFrom as k, toolOptionsOf as kt, RUN_ROUTE_KEY as l, STATUS_TITLES as lt, bearerChallenge as m, isRoles as mt, DISPATCH_ROUTE_KEY as n, DispatchResultSchema as nt, JOBS_META as o, failedJobs as ot, assembleApi as p, isPermissions as pt, withPermissions as q, GUARDS_META as r, dispatchDueJobs as rt, REQUEST_CONTEXT_META as s, problemDetails as st, API_META as t, DispatchFailedSchema as tt, ResponseValidationError as u, getStatusText as ut, defineAdapter as v, assembleRoutes as vt, guardDenyFor as w, buildToolInputSchema as wt, entriesToObject as x, streamToolsOf as xt, dispatchHandler as y, groupRoutes as yt, assertNoPathCollisions as z };