@rexezuge/http 1.11.0 → 1.12.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/README.md +39 -3
- package/dist/hono/contracts.d.ts +44 -0
- package/dist/hono/contracts.d.ts.map +1 -0
- package/dist/hono/contracts.js +1 -0
- package/dist/hono/contracts.js.map +7 -0
- package/dist/hono/createApiApp.d.ts.map +1 -1
- package/dist/hono/createApiApp.js +1 -1
- package/dist/hono/createApiApp.js.map +3 -3
- package/dist/hono/docs.d.ts +41 -0
- package/dist/hono/docs.d.ts.map +1 -0
- package/dist/hono/docs.js +1 -0
- package/dist/hono/docs.js.map +7 -0
- package/dist/hono/index.d.ts +4 -0
- package/dist/hono/index.d.ts.map +1 -1
- package/dist/hono/index.js +1 -1
- package/dist/hono/index.js.map +3 -3
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -41,6 +41,7 @@ dependency is `jose` (Cloudflare Access JWT verification).
|
|
|
41
41
|
| `requestGuards` | `HttpHardening.ts` ×4, AWS-AccessBridge `RequestGuards.ts`, Image-Host's CSRF guard, Pigeongram's `origin.ts` |
|
|
42
42
|
| `openApiErrors` | AWS-AccessBridge's `exceptionResponses.ts` |
|
|
43
43
|
| `/hono` | Each API worker's constructor stack, the seven `IBaseRoute.ts` copies, the `userAuthentication` middleware |
|
|
44
|
+
| `/hono` contracts | One route class plus a hand-copied `apps/web/src/types.ts` entry per endpoint |
|
|
44
45
|
|
|
45
46
|
## The three decisions worth knowing
|
|
46
47
|
|
|
@@ -165,7 +166,10 @@ messages kept, 5xx masked, zod/chanfana validation → 400, a retryable
|
|
|
165
166
|
`DatabaseError` → 503, a spent D1 allowance → 503 + `Retry-After`. The log line
|
|
166
167
|
is a static message with `type`, `status` and `requestId` — never the caught value.
|
|
167
168
|
An unmatched path is the `404 NotFound` envelope. `/docs` and `/openapi.json` are
|
|
168
|
-
served unless `docs: false`.
|
|
169
|
+
served unless `docs: false`. The docs page, and only that path, gets
|
|
170
|
+
`DOCS_CONTENT_SECURITY_POLICY`: the strict HTML policy plus the exact Swagger UI
|
|
171
|
+
asset directory chanfana loads (`cdn.jsdelivr.net/npm/swagger-ui-dist@<version>/`).
|
|
172
|
+
That policy is closed. There is no option to widen the CSP for your own pages.
|
|
169
173
|
|
|
170
174
|
`FamilyVariables` is the typed context: `AuthenticatedUserEmailAddress`,
|
|
171
175
|
`AuthenticatedUserId`, `requestId`, `logger`. Add your own with the second type
|
|
@@ -181,11 +185,43 @@ that redeclares `handle` or `execute` is **refused at registration**
|
|
|
181
185
|
(`assertFinalMembers` from `@rexezuge/shared`): chanfana constructs each route
|
|
182
186
|
once when it is registered.
|
|
183
187
|
|
|
188
|
+
### Contracts: `registerContract` / `routeFromEndpoint`
|
|
189
|
+
|
|
190
|
+
An endpoint from `@rexezuge/contracts` becomes a `FamilyRoute` whose chanfana
|
|
191
|
+
schema is derived from it: request `params`/`query`/`body`, `200` with the
|
|
192
|
+
response schema (or `204` for `response: null`), and every documented error as
|
|
193
|
+
the `{Exception}` envelope via `errorResponses`. The SPA calls the same object
|
|
194
|
+
through `@rexezuge/web`'s `createContractClient`.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { registerContract } from '@rexezuge/http/hono';
|
|
198
|
+
import { itemsContract } from '@my-repo/contracts';
|
|
199
|
+
|
|
200
|
+
createApiApp<Env>({
|
|
201
|
+
routes: (app) =>
|
|
202
|
+
registerContract(app, itemsContract, {
|
|
203
|
+
getItem: async ({ params }, c) => new ItemDAO(c.env.DB).get(c.get('AuthenticatedUserId'), params.id),
|
|
204
|
+
renameItem: async ({ params, body }, c) => (await new ItemDAO(c.env.DB).rename(params.id, body.name), null),
|
|
205
|
+
}),
|
|
206
|
+
});
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
- The handler map must name exactly the contract's endpoints. A missing key is a
|
|
210
|
+
compile error, and a missing or unknown key also throws at startup.
|
|
211
|
+
- The handler gets the validated zod **output** and returns the response's zod
|
|
212
|
+
**input**, `null`, or a `Response` of its own.
|
|
213
|
+
- **Fail-closed auth:** an `access`/`apiKey` endpoint answers `401` when no auth
|
|
214
|
+
middleware set `AuthenticatedUserId` on its path.
|
|
215
|
+
- `http` depends on `contracts` (framework-free, zod as types only). The adapter
|
|
216
|
+
is in `/hono` because it needs chanfana, so the root barrel stays
|
|
217
|
+
framework-free and the layer order stays `contracts` → `http` → `web`.
|
|
218
|
+
|
|
184
219
|
## Extending
|
|
185
220
|
|
|
186
221
|
| You want | Door |
|
|
187
222
|
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
188
223
|
| Your own routes | `routes(app)`, or register on the returned app; `FamilyRoute.handleRequest` |
|
|
224
|
+
| Routes from a shared contract | `registerContract(app, contract, handlers)`; `schemaFromEndpoint` for a hand-written `FamilyRoute` |
|
|
189
225
|
| Middleware before / after authentication | `hooks.beforeAuth` / `hooks.afterAuth` (a handler, or `{ path, handler }`) |
|
|
190
226
|
| Another authenticated surface | `auth: { '/partner/*': apiKeyAuth({ verify }) }` |
|
|
191
227
|
| Your PAT / HMAC / path-key scheme | `apiKeyAuth({ verify })` — return a principal or `null`; throw a `ServiceError` for 403 |
|
|
@@ -196,8 +232,8 @@ once when it is registered.
|
|
|
196
232
|
| A protocol dialect (Subsonic, WebDAV) | `errors.toResponse` app-wide, or `FamilyRoute.errorMapping()` per route |
|
|
197
233
|
| More context variables | the `V` type parameter |
|
|
198
234
|
|
|
199
|
-
Closed, with no flag: the slot order, the error envelope and its masking,
|
|
200
|
-
redaction, `email_verified` enforcement, the origin guard on `/user/*`, the
|
|
235
|
+
Closed, with no flag: the slot order, the error envelope and its masking, the CSP
|
|
236
|
+
(strict everywhere, Swagger UI's directory on the docs page only), log redaction, `email_verified` enforcement, the origin guard on `/user/*`, the
|
|
201
237
|
`@final` route `handle()`.
|
|
202
238
|
|
|
203
239
|
## Renamed: `toErrorResponse` → `errorResponseFromUnknown`
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { OpenAPIRoute, OpenAPIRouteSchema } from 'chanfana';
|
|
2
|
+
import type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';
|
|
3
|
+
import type { ApiApp } from './createApiApp.ts';
|
|
4
|
+
import type { RouteResult } from './FamilyRoute.ts';
|
|
5
|
+
import type { FamilyContext } from './types.ts';
|
|
6
|
+
/**
|
|
7
|
+
* Your implementation of one endpoint. `input` is the validated request (zod
|
|
8
|
+
* output), and the return value is the response schema's input, `null` for a
|
|
9
|
+
* `204` endpoint, or a `Response` you built yourself.
|
|
10
|
+
*/
|
|
11
|
+
type EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (input: EndpointServerInput<EP>, c: FamilyContext<E, V>) => Promise<RouteResult<EndpointResult<EP>>>;
|
|
12
|
+
/**
|
|
13
|
+
One handler per contract endpoint, by name. A missing key is a compile error.
|
|
14
|
+
*/
|
|
15
|
+
type ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {
|
|
16
|
+
[K in keyof C]: EndpointHandler<C[K], E, V>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* A route class, in the type chanfana's `app.get(path, Route)` accepts. It is
|
|
20
|
+
* constructed once, at registration.
|
|
21
|
+
*/
|
|
22
|
+
type EndpointRoute = typeof OpenAPIRoute<any>;
|
|
23
|
+
/**
|
|
24
|
+
* The chanfana schema for an endpoint: request, success and error responses.
|
|
25
|
+
*/
|
|
26
|
+
declare function schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema;
|
|
27
|
+
/**
|
|
28
|
+
* One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.
|
|
29
|
+
* Prefer `registerContract`, which also checks the method and path for you.
|
|
30
|
+
*/
|
|
31
|
+
declare function routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(endpoint: EP, handler: EndpointHandler<EP, E, V>): EndpointRoute;
|
|
32
|
+
/**
|
|
33
|
+
* Register every endpoint of a contract. `handlers` must name exactly the
|
|
34
|
+
* contract's endpoints: the type requires every key, and a missing or an extra
|
|
35
|
+
* key also throws a `TypeError` here, at startup.
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
declare function registerContract<E extends object, V extends object, C extends ContractEndpoints>(app: ApiApp<E, V>, contract: Contract<C>, handlers: ContractHandlers<C, E, V>): void;
|
|
42
|
+
export { registerContract, routeFromEndpoint, schemaFromEndpoint };
|
|
43
|
+
export type { ContractHandlers, EndpointHandler, EndpointRoute };
|
|
44
|
+
//# sourceMappingURL=contracts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/hono/contracts.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAiC,MAAM,UAAU,CAAC;AAEhG,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAEtH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;GAIG;AACH,KAAK,eAAe,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,CAChG,KAAK,EAAE,mBAAmB,CAAC,EAAE,CAAC,EAC9B,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,KACnB,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,EAAE,CAAC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ezuge/errors";import{errorResponses as g}from"../openApiErrors.js";import{FamilyRoute as w}from"./FamilyRoute.js";function l(e){const r={};e.params!==void 0&&(r.params=e.params),e.query!==void 0&&(r.query=e.query),e.body!==void 0&&(r.body=y(e.body));const o=e.response===null?{204:{description:"No Content"}}:{200:{description:e.summary??"OK",...y(e.response)}},a=Object.assign({},...e.errorResponses.map(({status:t,description:u})=>g(u===null?[t]:{[t]:u})));return{...e.summary!==void 0&&{summary:e.summary},...e.description!==void 0&&{description:e.description},...e.tags!==void 0&&{tags:[...e.tags]},request:r,responses:{...o,...a}}}i(l,"schemaFromEndpoint");function d(e,r){const o=l(e),a=e.auth!=="public";class t extends w{static{i(this,"ContractRoute")}schema=o;async handleRequest(f,s){if(a&&!s.get("AuthenticatedUserId"))throw new b;const n=f,c={};e.params!==void 0&&(c.params=n.params),e.query!==void 0&&(c.query=n.query),e.body!==void 0&&(c.body=n.body);const m=await r(c,s);return e.response===null&&!(m instanceof Response)?null:m}}return Object.defineProperty(t,"name",{value:`${e.method} ${e.path}`}),t}i(d,"routeFromEndpoint");function p(e,r,o){const a=Object.keys(r),t=a.filter(s=>typeof o[s]!="function");if(t.length>0)throw new TypeError(`registerContract: no handler for ${t.join(", ")}`);const u=Object.keys(o).filter(s=>!Object.hasOwn(r,s));if(u.length>0)throw new TypeError(`registerContract: ${u.join(", ")} is not in the contract`);const f=e;for(const s of a){const n=r[s],c=o[s];f[n.method.toLowerCase()]?.call(e,n.path,d(n,c))}}i(p,"registerContract");export{p as registerContract,d as routeFromEndpoint,l as schemaFromEndpoint};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hono/contracts.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The backend half of `@rexezuge/contracts`: an endpoint becomes a chanfana\n * route on the family app.\n *\n * ## Why here, and why `http` depends on `contracts`\n *\n * The adapter needs chanfana (`contentJson`, `OpenAPIRoute`), and the kit's rule\n * is that `hono`/`chanfana` are imported under `packages/http/src/hono/` and\n * nowhere else. So the adapter lives in `/hono`, and `http` takes a dependency on\n * `contracts`, a framework-free package that depends on neither `http` nor\n * `web`. The graph stays acyclic: `errors`/`shared` → `contracts` → `http` →\n * `web`. The other direction (a `/hono` subpath inside `contracts`) would have\n * put a second framework package in the kit.\n *\n * ## Closed\n *\n * - The route's chanfana `schema` is **derived** from the endpoint: request\n * `params`/`query`/`body`, the success response (`200` + the response schema,\n * or `204`), and every documented error as the kit's `{Exception}` envelope\n * (`errorResponses`). There is no second hand-written schema to drift.\n * - The route is a `FamilyRoute`, so validation, result shaping and error\n * mapping are the kit's `@final` `handle()`.\n * - **Fail-closed auth.** An `access`/`apiKey` endpoint answers `401` when no\n * auth middleware set `AuthenticatedUserId`, so forgetting to mount\n * `accessAuth` on a path does not publish an authenticated route.\n * - `registerContract` refuses a missing or an unknown handler at startup.\n *\n * ## Open\n *\n * The handler, the app (`E`, `V`), and `schemaFromEndpoint` for a hand-written\n * `FamilyRoute` subclass that needs `errorMapping()` or a raw `Response`.\n */\nimport { contentJson } from 'chanfana';\nimport type { OpenAPIRoute, OpenAPIRouteSchema, ResponseConfig, ValidatedData } from 'chanfana';\nimport { UnauthorizedError } from '@rexezuge/errors';\nimport type { Contract, ContractEndpoints, Endpoint, EndpointResult, EndpointServerInput } from '@rexezuge/contracts';\nimport { errorResponses } from '../openApiErrors.ts';\nimport type { ApiApp } from './createApiApp.ts';\nimport { FamilyRoute } from './FamilyRoute.ts';\nimport type { RouteResult } from './FamilyRoute.ts';\nimport type { FamilyContext } from './types.ts';\n\n/**\n * Your implementation of one endpoint. `input` is the validated request (zod\n * output), and the return value is the response schema's input, `null` for a\n * `204` endpoint, or a `Response` you built yourself.\n */\ntype EndpointHandler<EP extends Endpoint, E extends object = object, V extends object = object> = (\n input: EndpointServerInput<EP>,\n c: FamilyContext<E, V>,\n) => Promise<RouteResult<EndpointResult<EP>>>;\n\n/**\nOne handler per contract endpoint, by name. A missing key is a compile error.\n*/\ntype ContractHandlers<C extends ContractEndpoints, E extends object = object, V extends object = object> = {\n [K in keyof C]: EndpointHandler<C[K], E, V>;\n};\n\n/**\n * A route class, in the type chanfana's `app.get(path, Route)` accepts. It is\n * constructed once, at registration.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- chanfana's own registration parameter type\ntype EndpointRoute = typeof OpenAPIRoute<any>;\n\n/**\n * The chanfana schema for an endpoint: request, success and error responses.\n */\nfunction schemaFromEndpoint(endpoint: Endpoint): OpenAPIRouteSchema {\n const request: NonNullable<OpenAPIRouteSchema['request']> = {};\n if (endpoint.params !== undefined) request.params = endpoint.params;\n if (endpoint.query !== undefined) request.query = endpoint.query;\n if (endpoint.body !== undefined) request.body = contentJson(endpoint.body);\n\n const success: Record<string, ResponseConfig> =\n endpoint.response === null\n ? { '204': { description: 'No Content' } }\n : { '200': { description: endpoint.summary ?? 'OK', ...contentJson(endpoint.response) } };\n const errors = Object.assign(\n {},\n ...endpoint.errorResponses.map(({ status, description }) =>\n errorResponses(description === null ? [status] : { [status]: description }),\n ),\n ) as ReturnType<typeof errorResponses>;\n\n return {\n ...(endpoint.summary !== undefined && { summary: endpoint.summary }),\n ...(endpoint.description !== undefined && { description: endpoint.description }),\n ...(endpoint.tags !== undefined && { tags: [...endpoint.tags] }),\n request,\n responses: { ...success, ...errors },\n };\n}\n\n/**\n * One endpoint as a route class: `app.get(endpoint.path, routeFromEndpoint(endpoint, handler))`.\n * Prefer `registerContract`, which also checks the method and path for you.\n */\nfunction routeFromEndpoint<EP extends Endpoint, E extends object = object, V extends object = object>(\n endpoint: EP,\n handler: EndpointHandler<EP, E, V>,\n): EndpointRoute {\n const schema = schemaFromEndpoint(endpoint);\n const authenticated = endpoint.auth !== 'public';\n\n class ContractRoute extends FamilyRoute<OpenAPIRouteSchema, E, V> {\n public override schema = schema;\n\n protected async handleRequest(input: ValidatedData<OpenAPIRouteSchema>, c: FamilyContext<E, V>): Promise<RouteResult<unknown>> {\n // Read loosely on purpose: the variable is typed as always present, and\n // this is the check that it really is.\n if (authenticated && !(c.get('AuthenticatedUserId') as string | undefined)) throw new UnauthorizedError();\n const validated = input as { params?: unknown; query?: unknown; body?: unknown };\n const slots: Record<string, unknown> = {};\n if (endpoint.params !== undefined) slots.params = validated.params;\n if (endpoint.query !== undefined) slots.query = validated.query;\n if (endpoint.body !== undefined) slots.body = validated.body;\n const result = await handler(slots as EndpointServerInput<EP>, c);\n // A 204 endpoint answers 204 whatever the handler returned, unless it\n // built its own Response.\n if (endpoint.response === null && !(result instanceof Response)) return null;\n return result;\n }\n }\n Object.defineProperty(ContractRoute, 'name', { value: `${endpoint.method} ${endpoint.path}` });\n return ContractRoute;\n}\n\ntype Register = (path: string, route: unknown) => unknown;\n\n/**\n * Register every endpoint of a contract. `handlers` must name exactly the\n * contract's endpoints: the type requires every key, and a missing or an extra\n * key also throws a `TypeError` here, at startup.\n *\n * ```ts\n * createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, { getItem, listItems, renameItem }) });\n * ```\n */\nfunction registerContract<E extends object, V extends object, C extends ContractEndpoints>(\n app: ApiApp<E, V>,\n contract: Contract<C>,\n handlers: ContractHandlers<C, E, V>,\n): void {\n const names = Object.keys(contract);\n const missing = names.filter((name) => typeof (handlers as Record<string, unknown>)[name] !== 'function');\n if (missing.length > 0) throw new TypeError(`registerContract: no handler for ${missing.join(', ')}`);\n const unknown = Object.keys(handlers).filter((name) => !Object.hasOwn(contract, name));\n if (unknown.length > 0) throw new TypeError(`registerContract: ${unknown.join(', ')} is not in the contract`);\n\n const router = app as unknown as Record<string, Register>;\n for (const name of names) {\n const endpoint = contract[name] as Endpoint;\n const handler = (handlers as Record<string, EndpointHandler<Endpoint, E, V>>)[name];\n router[endpoint.method.toLowerCase()]?.call(app, endpoint.path, routeFromEndpoint(endpoint, handler));\n }\n}\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint };\nexport type { ContractHandlers, EndpointHandler, EndpointRoute };\n"],
|
|
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AAI,qBAAqB,EAA0B,MAAM,IAAIjB,EACtF,MAAMkB,EAAYF,EACZG,EAAiC,CAAA,EACnCf,EAAS,SAAW,SAAWe,EAAM,OAASD,EAAU,QACxDd,EAAS,QAAU,SAAWe,EAAM,MAAQD,EAAU,OACtDd,EAAS,OAAS,SAAWe,EAAM,KAAOD,EAAU,MACxD,MAAME,EAAS,MAAMR,EAAQO,EAAkCF,CAAC,EAGhE,OAAIb,EAAS,WAAa,MAAQ,EAAEgB,aAAkB,UAAkB,KACjEA,CACT,EAEF,cAAO,eAAeL,EAAe,OAAQ,CAAE,MAAO,GAAGX,EAAS,MAAM,IAAIA,EAAS,IAAI,EAAE,CAAE,EACtFW,CACT,CA5BSL,EAAAC,EAAA,qBAyCT,SAASU,EACPC,EACAC,EACAC,EAAmC,CAEnC,MAAMC,EAAQ,OAAO,KAAKF,CAAQ,EAC5BG,EAAUD,EAAM,OAAQE,GAAS,OAAQH,EAAqCG,CAAI,GAAM,UAAU,EACxG,GAAID,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,oCAAoCA,EAAQ,KAAK,IAAI,CAAC,EAAE,EACpG,MAAME,EAAU,OAAO,KAAKJ,CAAQ,EAAE,OAAQG,GAAS,CAAC,OAAO,OAAOJ,EAAUI,CAAI,CAAC,EACrF,GAAIC,EAAQ,OAAS,EAAG,MAAM,IAAI,UAAU,qBAAqBA,EAAQ,KAAK,IAAI,CAAC,yBAAyB,EAE5G,MAAMC,EAASP,EACf,UAAWK,KAAQF,EAAO,CACxB,MAAMrB,EAAWmB,EAASI,CAAI,EACxBf,EAAWY,EAA6DG,CAAI,EAClFE,EAAOzB,EAAS,OAAO,YAAW,CAAE,GAAG,KAAKkB,EAAKlB,EAAS,KAAMO,EAAkBP,EAAUQ,CAAO,CAAC,CACtG,CACF,CAjBSF,EAAAW,EAAA",
|
|
6
|
+
"names": ["contentJson", "UnauthorizedError", "errorResponses", "FamilyRoute", "schemaFromEndpoint", "endpoint", "request", "success", "errors", "status", "description", "__name", "routeFromEndpoint", "handler", "schema", "authenticated", "ContractRoute", "input", "c", "validated", "slots", "result", "registerContract", "app", "contract", "handlers", "names", "missing", "name", "unknown", "router"]
|
|
7
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;AAErE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"createApiApp.d.ts","sourceRoot":"","sources":["../../src/hono/createApiApp.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,qBAAqB,EAAiB,MAAM,UAAU,CAAC;AAErE,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAGxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C,KAAK,MAAM,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI,qBAAqB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAElG,KAAK,WAAW,GAAG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;MAEE;IACF,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC;CACtC;AAED,KAAK,OAAO,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,IAC7C,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA;CAAE,CAAC;AAErG;;EAEE;AACF,QAAA,MAAM,iBAAiB,uBAAuB,CAAC;AA8D/C;;;;GAIG;AACH,iBAAS,YAAY,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,OAAO,GAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAM,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAmBlH;AAED,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC3C,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var n=(e,r)=>d(e,"name",{value:r,configurable:!0});import{fromHono as m}from"chanfana";import{Hono as p}from"hono";import{cors as h}from"hono/cors";import{securityHeaders as y,sensitivePaths as _}from"../securityHeaders.js";import{d1Bookmarks as T}from"./bookmarks.js";import{DOCS_CONTENT_SECURITY_POLICY as O,isDocsPath as E}from"./docs.js";import{createErrorHandler as H,createNotFoundHandler as P}from"./errorHandler.js";import{bodyLimitGuard as R,contentTypeGuard as k,methodGuard as A,originGuard as C}from"./hardening.js";import{rateLimitRule as i}from"./rateLimits.js";import{requestContext as N}from"./requestContext.js";const c="errorMapperOptions",S=["/user/*"],g=["/user/*","/api/*"];function f(e,r){for(const s of r??[])typeof s=="function"?e.use("*",s):e.use(s.path,s.handler)}n(f,"mountHooks");function w(e){return e===!1?{docs_url:null,openapi_url:null,redoc_url:null,raiseOnError:!0}:{docs_url:e?.url??"/docs",openapi_url:e?.openapiUrl??"/openapi.json",redoc_url:null,raiseOnError:!0,...e?.info&&{schema:{info:e.info}}}}n(w,"routerOptions");function x(e,r){e.use("*",N(r)),e.use("*",async(t,o)=>{t.set(c,r.errors??{}),await o()});const s=y(_(...r.sensitivePaths??["/user/","/api/"])),a=r.docs===!1?null:r.docs?.url??"/docs";if(e.use("*",async(t,o)=>{await s(t,o),a!==null&&E(t.req.path,a)&&(t.res.headers.get("content-type")??"").includes("text/html")&&t.header("Content-Security-Policy",O)}),r.cors){const t=[...new Set([...r.cors.exposeHeaders??[],"X-Request-Id"])];e.use("*",h({...r.cors,exposeHeaders:t}))}const u=r.hardening??{};e.use("*",A(u.methods)),e.use("*",R(u.maxBodyBytes));for(const t of u.contentType?.paths??g)e.use(t,k(u.contentType?.allowed));for(const t of u.origin?.paths??S)e.use(t,C(u.origin));if(r.d1)for(const t of r.d1.paths??["*"])e.use(t,T(r.d1))}n(x,"mountPlatform");function I(e={}){const r=new p;r.onError(H(e.errors)),r.notFound(P()),x(r,e);const s=e.rateLimits??[],a=s.filter(o=>o.key==="ip"),u=s.filter(o=>o.key!=="ip");for(const o of a)r.use(o.path,i(o));f(r,e.hooks?.beforeAuth);for(const[o,l]of Object.entries(e.auth??{}))r.use(o,l);for(const o of u)r.use(o.path,i(o));f(r,e.hooks?.afterAuth);const t=m(r,w(e.docs));return e.routes?.(t),t}n(I,"createApiApp");export{c as ERROR_OPTIONS_KEY,I as createApiApp};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/createApiApp.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePaths } from '../securityHeaders.ts';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`. Defaults to\n * `['/user/', '/api/']`: both surfaces carry credentials or account data.\n */\n sensitivePaths?: readonly string[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).\n */\n errors?: ErrorMapperOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n
|
|
5
|
-
"mappings": "+EA2BA,OAAS,YAAAA,MAAgB,WAEzB,OAAS,QAAAC,MAAY,OAErB,OAAS,QAAAC,MAAY,YACrB,OAAS,mBAAAC,EAAiB,kBAAAC,MAAsB,wBAEhD,OAAS,eAAAC,MAAmB,
|
|
6
|
-
"names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePaths", "d1Bookmarks", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "rateLimitRule", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "mountPlatform", "options", "c", "next", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
|
|
4
|
+
"sourcesContent": ["/**\n * `createApiApp` — the family API worker's Hono + chanfana app, pre-wired.\n *\n * Every family worker hand-assembled the same stack in its constructor, and each\n * assembly had its own ordering bug: a limiter installed before auth (per-IP\n * buckets for an office NAT), security headers registered after a middleware\n * that returns early (no headers on the 401), no `onError` (a text 500 the SPA\n * cannot parse), a D1 session opened by mutating the shared `env`. The order is\n * the kit's now, and it is **closed**:\n *\n * | # | Slot | Why here |\n * | -- | ----------------------- | ---------------------------------------------------------------- |\n * | 1 | request id + logger | everything after can log and correlate |\n * | 2 | security headers | wraps the rest, so a 401/404/500 leaves with them |\n * | 3 | CORS (option) | a preflight answers before any guard or auth |\n * | 4 | hardening | method, body size, JSON content type, origin guard: cheap, no I/O |\n * | 5 | D1 bookmarks (option) | auth's account lookup already reads through the session |\n * | 6 | `ip` rate limits | throttle before the auth step spends D1 on an anonymous caller |\n * | 7 | `beforeAuth` hooks | your middleware that must see the request unauthenticated |\n * | 8 | auth surfaces | `accessAuth` on `/user/*`, `apiKeyAuth` on `/api/*`, … |\n * | 9 | `identity` rate limits | keyed on the account, which only exists after 8 |\n * | 10 | `afterAuth` hooks | your middleware that needs the account (request scope, audit) |\n * | 11 | `routes(app)` | your routes |\n *\n * plus `onError` (the kit mapper → `{Exception:{Type,Message}}`), `notFound` (the\n * same envelope) and `/docs` + `/openapi.json` (option).\n */\nimport { fromHono } from 'chanfana';\nimport type { HonoOpenAPIRouterType, RouterOptions } from 'chanfana';\nimport { Hono } from 'hono';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { cors } from 'hono/cors';\nimport { securityHeaders, sensitivePaths } from '../securityHeaders.ts';\nimport type { ErrorMapperOptions } from '../ErrorMapper.ts';\nimport { d1Bookmarks } from './bookmarks.ts';\nimport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath } from './docs.ts';\nimport type { D1BookmarkOptions } from './bookmarks.ts';\nimport { createErrorHandler, createNotFoundHandler } from './errorHandler.ts';\nimport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nimport type { HardeningOptions } from './hardening.ts';\nimport { rateLimitRule } from './rateLimits.ts';\nimport type { RateLimitRule } from './rateLimits.ts';\nimport { requestContext } from './requestContext.ts';\nimport type { RequestContextOptions } from './requestContext.ts';\nimport type { FamilyEnv } from './types.ts';\n\ntype ApiApp<E extends object, V extends object = object> = HonoOpenAPIRouterType<FamilyEnv<E, V>>;\n\ntype CorsOptions = NonNullable<Parameters<typeof cors>[0]>;\n\ninterface DocsOptions {\n /**\n Defaults to `/docs`.\n */\n url?: string;\n /**\n Defaults to `/openapi.json`.\n */\n openapiUrl?: string;\n /**\n The OpenAPI document's `info`.\n */\n info?: { title: string; version: string; description?: string };\n}\n\ninterface ApiAppOptions<E extends object, V extends object = object> extends RequestContextOptions<E> {\n /**\n * The paths whose responses get `Cache-Control: no-store`. Defaults to\n * `['/user/', '/api/']`: both surfaces carry credentials or account data.\n */\n sensitivePaths?: readonly string[];\n /**\n Hono `cors()` options. Off unless given. `X-Request-Id` is always exposed.\n */\n cors?: CorsOptions;\n /**\n Tunes the hardening slot. The guards themselves are not optional.\n */\n hardening?: HardeningOptions<E>;\n /**\n Open a D1 session per request and round-trip its bookmark.\n */\n d1?: D1BookmarkOptions;\n /**\n Rate-limit rules; each rule's `key` decides its slot (6 or 9).\n */\n rateLimits?: readonly RateLimitRule<E>[];\n /**\n * The authenticated surfaces: a path pattern → its auth middleware, e.g.\n * `{ '/user/*': accessAuth({...}), '/api/*': apiKeyAuth({...}) }`.\n */\n auth?: Readonly<Record<string, MiddlewareHandler<FamilyEnv<E, V>>>>;\n /**\n Your middleware, at the two documented slots. Each entry mounts on `path` (default `*`).\n */\n hooks?: {\n beforeAuth?: readonly AppHook<E, V>[];\n afterAuth?: readonly AppHook<E, V>[];\n };\n /**\n Options for the error boundary (`dailyLimit`, `headers`, a surface `toResponse`).\n */\n errors?: ErrorMapperOptions;\n /**\n `/docs` and `/openapi.json`. Pass `false` to serve neither.\n */\n docs?: DocsOptions | false;\n /**\n Register your routes. Runs last, after every kit slot.\n */\n routes?: (app: ApiApp<E, V>) => void;\n}\n\ntype AppHook<E extends object, V extends object> =\n MiddlewareHandler<FamilyEnv<E, V>> | { path: string; handler: MiddlewareHandler<FamilyEnv<E, V>> };\n\n/**\nThe context key `FamilyRoute` reads the app's mapper options from.\n*/\nconst ERROR_OPTIONS_KEY = 'errorMapperOptions';\n\nconst DEFAULT_ORIGIN_PATHS: readonly string[] = ['/user/*'];\nconst DEFAULT_CONTENT_TYPE_PATHS: readonly string[] = ['/user/*', '/api/*'];\n\nfunction mountHooks<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, hooks: readonly AppHook<E, V>[] | undefined): void {\n for (const hook of hooks ?? []) {\n if (typeof hook === 'function') hono.use('*', hook);\n else hono.use(hook.path, hook.handler);\n }\n}\n\nfunction routerOptions(docs: DocsOptions | false | undefined): RouterOptions {\n if (docs === false) return { docs_url: null, openapi_url: null, redoc_url: null, raiseOnError: true };\n return {\n docs_url: docs?.url ?? '/docs',\n openapi_url: docs?.openapiUrl ?? '/openapi.json',\n redoc_url: null,\n raiseOnError: true,\n ...(docs?.info && { schema: { info: docs.info } }),\n };\n}\n\n/**\n * Slots 1–5: identity of the request, headers, CORS, the guards, the session.\n */\nfunction mountPlatform<E extends object, V extends object>(hono: Hono<FamilyEnv<E, V>>, options: ApiAppOptions<E, V>): void {\n hono.use('*', requestContext<E, V>(options));\n hono.use('*', async (c, next) => {\n (c as unknown as Context).set(ERROR_OPTIONS_KEY, options.errors ?? {});\n await next();\n });\n const headers = securityHeaders(sensitivePaths(...(options.sensitivePaths ?? ['/user/', '/api/']))) as unknown as MiddlewareHandler;\n const docsUrl = options.docs === false ? null : (options.docs?.url ?? '/docs');\n hono.use('*', async (c, next) => {\n await headers(c, next);\n // Closed: the docs page (and only it) gets the policy that admits the\n // Swagger UI assets. Every other HTML response keeps the strict one.\n if (docsUrl !== null && isDocsPath(c.req.path, docsUrl) && (c.res.headers.get('content-type') ?? '').includes('text/html')) {\n c.header('Content-Security-Policy', DOCS_CONTENT_SECURITY_POLICY);\n }\n });\n if (options.cors) {\n const exposeHeaders = [...new Set([...(options.cors.exposeHeaders ?? []), 'X-Request-Id'])];\n hono.use('*', cors({ ...options.cors, exposeHeaders }));\n }\n\n const hardening = options.hardening ?? {};\n hono.use('*', methodGuard(hardening.methods));\n hono.use('*', bodyLimitGuard(hardening.maxBodyBytes));\n for (const path of hardening.contentType?.paths ?? DEFAULT_CONTENT_TYPE_PATHS) {\n hono.use(path, contentTypeGuard(hardening.contentType?.allowed));\n }\n for (const path of hardening.origin?.paths ?? DEFAULT_ORIGIN_PATHS) {\n hono.use(path, originGuard<E>(hardening.origin));\n }\n\n if (options.d1) {\n for (const path of options.d1.paths ?? ['*']) hono.use(path, d1Bookmarks<E>(options.d1));\n }\n}\n\n/**\n * Build the app. The returned value is the chanfana router: register routes on\n * it (or in `routes`), and hand `app.fetch` the request from your entrypoint's\n * `onRequest`.\n */\nfunction createApiApp<E extends object, V extends object = object>(options: ApiAppOptions<E, V> = {}): ApiApp<E, V> {\n const hono = new Hono<FamilyEnv<E, V>>();\n hono.onError(createErrorHandler(options.errors));\n hono.notFound(createNotFoundHandler());\n\n mountPlatform(hono, options);\n\n const rules = options.rateLimits ?? [];\n const ipRules = rules.filter((entry) => entry.key === 'ip');\n const identityRules = rules.filter((entry) => entry.key !== 'ip');\n for (const rule of ipRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.beforeAuth);\n for (const [path, middleware] of Object.entries(options.auth ?? {})) hono.use(path, middleware);\n for (const rule of identityRules) hono.use(rule.path, rateLimitRule<E>(rule));\n mountHooks(hono, options.hooks?.afterAuth);\n\n const app = fromHono(hono, routerOptions(options.docs))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AA0DR,EAA+B,CAAA,EAAE,CAClG,MAAMP,EAAO,IAAInB,EACjBmB,EAAK,QAAQZ,EAAmBmB,EAAQ,MAAM,CAAC,EAC/CP,EAAK,SAASX,EAAqB,CAAE,EAErCiB,EAAcN,EAAMO,CAAO,EAE3B,MAAMS,EAAQT,EAAQ,YAAc,CAAA,EAC9BU,EAAUD,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EACpDC,EAAgBH,EAAM,OAAQE,GAAUA,EAAM,MAAQ,IAAI,EAChE,UAAWE,KAAQH,EAASjB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EACtErB,EAAWC,EAAMO,EAAQ,OAAO,UAAU,EAC1C,SAAW,CAACO,EAAMO,CAAU,IAAK,OAAO,QAAQd,EAAQ,MAAQ,CAAA,CAAE,EAAGP,EAAK,IAAIc,EAAMO,CAAU,EAC9F,UAAWD,KAAQD,EAAenB,EAAK,IAAIoB,EAAK,KAAM1B,EAAiB0B,CAAI,CAAC,EAC5ErB,EAAWC,EAAMO,EAAQ,OAAO,SAAS,EAEzC,MAAMe,EAAM1C,EAASoB,EAAMI,EAAcG,EAAQ,IAAI,CAAC,EACtD,OAAAA,EAAQ,SAASe,CAAG,EACbA,CACT,CAnBSnB,EAAAY,EAAA",
|
|
6
|
+
"names": ["fromHono", "Hono", "cors", "securityHeaders", "sensitivePaths", "d1Bookmarks", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "createErrorHandler", "createNotFoundHandler", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "rateLimitRule", "requestContext", "ERROR_OPTIONS_KEY", "DEFAULT_ORIGIN_PATHS", "DEFAULT_CONTENT_TYPE_PATHS", "mountHooks", "hono", "hooks", "hook", "__name", "routerOptions", "docs", "mountPlatform", "options", "c", "next", "headers", "docsUrl", "exposeHeaders", "hardening", "path", "createApiApp", "rules", "ipRules", "entry", "identityRules", "rule", "middleware", "app"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Content-Security-Policy for the Swagger UI page `createApiApp` serves.
|
|
3
|
+
*
|
|
4
|
+
* chanfana's `/docs` page is an HTML shell that loads Swagger UI's script and
|
|
5
|
+
* stylesheet from jsDelivr. The kit's strict HTML policy
|
|
6
|
+
* (`CONTENT_SECURITY_POLICY`, `script-src 'self'`) blocks both, so the page
|
|
7
|
+
* rendered blank: the boundary was doing its job on a page the kit itself served.
|
|
8
|
+
*
|
|
9
|
+
* The fix is a **second, narrower** policy, applied by `createApiApp` to the docs
|
|
10
|
+
* path and nothing else:
|
|
11
|
+
*
|
|
12
|
+
* - The only extra source is the exact Swagger UI asset directory chanfana
|
|
13
|
+
* references (`swagger-ui-dist@<version>/`), a CSP path source, not the whole
|
|
14
|
+
* CDN. A different package on the same CDN is still refused.
|
|
15
|
+
* - It is **closed**. There is no option to pass a policy, and the public
|
|
16
|
+
* `securityHeaders` middleware is unchanged. A consumer cannot loosen the CSP
|
|
17
|
+
* for its own pages through this door. The docs page is the kit's page, so the
|
|
18
|
+
* policy for it is the kit's too.
|
|
19
|
+
*
|
|
20
|
+
* The suite parses chanfana's own `getSwaggerUI` output and asserts every
|
|
21
|
+
* external asset is covered, so a chanfana bump that moves the Swagger UI
|
|
22
|
+
* version fails the test rather than blanking `/docs` again.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
The Swagger UI asset directory chanfana 3.4's `getSwaggerUI` loads from.
|
|
26
|
+
*/
|
|
27
|
+
declare const SWAGGER_UI_ASSET_SOURCE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/";
|
|
28
|
+
/**
|
|
29
|
+
* The strict HTML policy, plus the Swagger UI directory for scripts and styles.
|
|
30
|
+
* `'unsafe-inline'` was already in the base policy: chanfana's page boots Swagger
|
|
31
|
+
* UI from one inline script.
|
|
32
|
+
*/
|
|
33
|
+
declare const DOCS_CONTENT_SECURITY_POLICY: string;
|
|
34
|
+
/**
|
|
35
|
+
* Whether `pathname` is the docs page. An exact match, with or without one
|
|
36
|
+
* trailing slash: the policy must not reach a route that merely starts with
|
|
37
|
+
* `/docs`.
|
|
38
|
+
*/
|
|
39
|
+
declare function isDocsPath(pathname: string, docsUrl: string): boolean;
|
|
40
|
+
export { DOCS_CONTENT_SECURITY_POLICY, isDocsPath, SWAGGER_UI_ASSET_SOURCE };
|
|
41
|
+
//# sourceMappingURL=docs.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../../src/hono/docs.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH;;EAEE;AACF,QAAA,MAAM,uBAAuB,0DAA0D,CAAC;AAExF;;;;GAIG;AACH,QAAA,MAAM,4BAA4B,QAUtB,CAAC;AAEb;;;;GAIG;AACH,iBAAS,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAG9D;AAED,OAAO,EAAE,4BAA4B,EAAE,UAAU,EAAE,uBAAuB,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var c=Object.defineProperty;var r=(s,n)=>c(s,"name",{value:n,configurable:!0});const i="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/",l=["default-src 'self'","img-src 'self' data:",`style-src 'self' 'unsafe-inline' ${i}`,`script-src 'self' 'unsafe-inline' ${i}`,"object-src 'none'","form-action 'self'","base-uri 'self'","frame-ancestors 'none'","upgrade-insecure-requests"].join("; ");function o(s,n){const t=r(e=>e.length>1&&e.endsWith("/")?e.slice(0,-1):e,"normalize");return t(s)===t(n)}r(o,"isDocsPath");export{l as DOCS_CONTENT_SECURITY_POLICY,i as SWAGGER_UI_ASSET_SOURCE,o as isDocsPath};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/hono/docs.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The Content-Security-Policy for the Swagger UI page `createApiApp` serves.\n *\n * chanfana's `/docs` page is an HTML shell that loads Swagger UI's script and\n * stylesheet from jsDelivr. The kit's strict HTML policy\n * (`CONTENT_SECURITY_POLICY`, `script-src 'self'`) blocks both, so the page\n * rendered blank: the boundary was doing its job on a page the kit itself served.\n *\n * The fix is a **second, narrower** policy, applied by `createApiApp` to the docs\n * path and nothing else:\n *\n * - The only extra source is the exact Swagger UI asset directory chanfana\n * references (`swagger-ui-dist@<version>/`), a CSP path source, not the whole\n * CDN. A different package on the same CDN is still refused.\n * - It is **closed**. There is no option to pass a policy, and the public\n * `securityHeaders` middleware is unchanged. A consumer cannot loosen the CSP\n * for its own pages through this door. The docs page is the kit's page, so the\n * policy for it is the kit's too.\n *\n * The suite parses chanfana's own `getSwaggerUI` output and asserts every\n * external asset is covered, so a chanfana bump that moves the Swagger UI\n * version fails the test rather than blanking `/docs` again.\n */\n\n/**\nThe Swagger UI asset directory chanfana 3.4's `getSwaggerUI` loads from.\n*/\nconst SWAGGER_UI_ASSET_SOURCE = 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/';\n\n/**\n * The strict HTML policy, plus the Swagger UI directory for scripts and styles.\n * `'unsafe-inline'` was already in the base policy: chanfana's page boots Swagger\n * UI from one inline script.\n */\nconst DOCS_CONTENT_SECURITY_POLICY = [\n \"default-src 'self'\",\n \"img-src 'self' data:\",\n `style-src 'self' 'unsafe-inline' ${SWAGGER_UI_ASSET_SOURCE}`,\n `script-src 'self' 'unsafe-inline' ${SWAGGER_UI_ASSET_SOURCE}`,\n \"object-src 'none'\",\n \"form-action 'self'\",\n \"base-uri 'self'\",\n \"frame-ancestors 'none'\",\n 'upgrade-insecure-requests',\n].join('; ');\n\n/**\n * Whether `pathname` is the docs page. An exact match, with or without one\n * trailing slash: the policy must not reach a route that merely starts with\n * `/docs`.\n */\nfunction isDocsPath(pathname: string, docsUrl: string): boolean {\n const normalize = (path: string): string => (path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path);\n return normalize(pathname) === normalize(docsUrl);\n}\n\nexport { DOCS_CONTENT_SECURITY_POLICY, isDocsPath, SWAGGER_UI_ASSET_SOURCE };\n"],
|
|
5
|
+
"mappings": "+EA2BA,MAAMA,EAA0B,wDAO1BC,EAA+B,CACnC,qBACA,uBACA,oCAAoCD,CAAuB,GAC3D,qCAAqCA,CAAuB,GAC5D,oBACA,qBACA,kBACA,yBACA,6BACA,KAAK,IAAI,EAOX,SAASE,EAAWC,EAAkBC,EAAe,CACnD,MAAMC,EAAYC,EAACC,GAA0BA,EAAK,OAAS,GAAKA,EAAK,SAAS,GAAG,EAAIA,EAAK,MAAM,EAAG,EAAE,EAAIA,EAAvF,aAClB,OAAOF,EAAUF,CAAQ,IAAME,EAAUD,CAAO,CAClD,CAHSE,EAAAJ,EAAA",
|
|
6
|
+
"names": ["SWAGGER_UI_ASSET_SOURCE", "DOCS_CONTENT_SECURITY_POLICY", "isDocsPath", "pathname", "docsUrl", "normalize", "__name", "path"]
|
|
7
|
+
}
|
package/dist/hono/index.d.ts
CHANGED
|
@@ -13,11 +13,15 @@
|
|
|
13
13
|
* | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |
|
|
14
14
|
* | `d1Bookmarks` | the `onRequest` D1-session blocks |
|
|
15
15
|
* | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |
|
|
16
|
+
* | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |
|
|
16
17
|
*/
|
|
17
18
|
export { createApiApp } from './createApiApp.ts';
|
|
18
19
|
export type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';
|
|
20
|
+
export { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';
|
|
19
21
|
export { FamilyRoute } from './FamilyRoute.ts';
|
|
20
22
|
export type { RouteResult } from './FamilyRoute.ts';
|
|
23
|
+
export { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';
|
|
24
|
+
export type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';
|
|
21
25
|
export { accessAuth, apiKeyAuth } from './auth.ts';
|
|
22
26
|
export type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';
|
|
23
27
|
export { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';
|
package/dist/hono/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hono/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElG,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzF,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEvF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACnD,YAAY,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5G,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC5F,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAExF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEvG,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEhG,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACvF,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAEjE,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,gBAAgB,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/hono/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createApiApp as e}from"./createApiApp.js";import{FamilyRoute as a}from"./FamilyRoute.js";import{accessAuth as
|
|
1
|
+
import{createApiApp as e}from"./createApiApp.js";import{DOCS_CONTENT_SECURITY_POLICY as m}from"./docs.js";import{FamilyRoute as a}from"./FamilyRoute.js";import{registerContract as d,routeFromEndpoint as i,schemaFromEndpoint as u}from"./contracts.js";import{accessAuth as f,apiKeyAuth as E}from"./auth.js";import{bodyLimitGuard as s,contentTypeGuard as C,methodGuard as h,originGuard as l}from"./hardening.js";import{d1Bookmarks as R}from"./bookmarks.js";import{rateLimitRule as _}from"./rateLimits.js";import{createErrorHandler as y,createNotFoundHandler as F,respondWithError as G}from"./errorHandler.js";import{consoleLogger as D,requestContext as H,REQUEST_ID_HEADER as I}from"./requestContext.js";export{m as DOCS_CONTENT_SECURITY_POLICY,a as FamilyRoute,I as REQUEST_ID_HEADER,f as accessAuth,E as apiKeyAuth,s as bodyLimitGuard,D as consoleLogger,C as contentTypeGuard,e as createApiApp,y as createErrorHandler,F as createNotFoundHandler,R as d1Bookmarks,h as methodGuard,l as originGuard,_ as rateLimitRule,d as registerContract,H as requestContext,G as respondWithError,i as routeFromEndpoint,u as schemaFromEndpoint};
|
package/dist/hono/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/hono/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { RouteResult } from './FamilyRoute.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["createApiApp", "FamilyRoute", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
|
|
4
|
+
"sourcesContent": ["/**\n * `@rexezuge/http/hono` — the Hono + chanfana app kernel.\n *\n * Everything in `@rexezuge/http` that imports `hono` or `chanfana` lives here,\n * so the root barrel stays framework-free. `hono` and `chanfana` are optional\n * peers of the package and **required** by a repo that imports this subpath.\n *\n * | Export | Replaces |\n * | ------------------------------- | ------------------------------------------------------------------------ |\n * | `createApiApp` | each API worker's hand-assembled constructor stack |\n * | `FamilyRoute` | the seven `endpoints/IBaseRoute.ts` copies |\n * | `accessAuth` / `apiKeyAuth` | `MiddlewareHandlers.userAuthentication()` and the PAT/API-key middleware |\n * | `originGuard`, `contentTypeGuard`, `bodyLimitGuard`, `methodGuard` | `HttpHardening.ts` ×4, `RequestGuards.ts`, Image-Host's CSRF guard |\n * | `d1Bookmarks` | the `onRequest` D1-session blocks |\n * | `createErrorHandler` | the hand-built `{Exception}` envelopes and Hono's text 500 |\n * | `registerContract`, `routeFromEndpoint` | a route class + hand-copied `apps/web/src/types.ts` per endpoint |\n */\nexport { createApiApp } from './createApiApp.ts';\nexport type { ApiApp, ApiAppOptions, AppHook, CorsOptions, DocsOptions } from './createApiApp.ts';\n\nexport { DOCS_CONTENT_SECURITY_POLICY } from './docs.ts';\n\nexport { FamilyRoute } from './FamilyRoute.ts';\nexport type { RouteResult } from './FamilyRoute.ts';\n\nexport { registerContract, routeFromEndpoint, schemaFromEndpoint } from './contracts.ts';\nexport type { ContractHandlers, EndpointHandler, EndpointRoute } from './contracts.ts';\n\nexport { accessAuth, apiKeyAuth } from './auth.ts';\nexport type { AccessAuthMiddlewareOptions, ApiKeyAuthOptions, ApiPrincipal, ResolvedUser } from './auth.ts';\n\nexport { bodyLimitGuard, contentTypeGuard, methodGuard, originGuard } from './hardening.ts';\nexport type { ContentTypePolicy, HardeningOptions, OriginPolicy } from './hardening.ts';\n\nexport { d1Bookmarks } from './bookmarks.ts';\nexport type { BookmarkPort, BookmarkSession, BookmarkSource, D1BookmarkOptions } from './bookmarks.ts';\n\nexport { rateLimitRule } from './rateLimits.ts';\nexport type { NativeRateLimiter, RateLimitRule } from './rateLimits.ts';\n\nexport { createErrorHandler, createNotFoundHandler, respondWithError } from './errorHandler.ts';\n\nexport { consoleLogger, requestContext, REQUEST_ID_HEADER } from './requestContext.ts';\nexport type { RequestContextOptions } from './requestContext.ts';\n\nexport type { FamilyContext, FamilyEnv, FamilyMiddleware, FamilyVariables, FromEnv, HttpLogger } from './types.ts';\n"],
|
|
5
|
+
"mappings": "AAiBA,OAAS,gBAAAA,MAAoB,oBAG7B,OAAS,gCAAAC,MAAoC,YAE7C,OAAS,eAAAC,MAAmB,mBAG5B,OAAS,oBAAAC,EAAkB,qBAAAC,EAAmB,sBAAAC,MAA0B,iBAGxE,OAAS,cAAAC,EAAY,cAAAC,MAAkB,YAGvC,OAAS,kBAAAC,EAAgB,oBAAAC,EAAkB,eAAAC,EAAa,eAAAC,MAAmB,iBAG3E,OAAS,eAAAC,MAAmB,iBAG5B,OAAS,iBAAAC,MAAqB,kBAG9B,OAAS,sBAAAC,EAAoB,yBAAAC,EAAuB,oBAAAC,MAAwB,oBAE5E,OAAS,iBAAAC,EAAe,kBAAAC,EAAgB,qBAAAC,MAAyB",
|
|
6
|
+
"names": ["createApiApp", "DOCS_CONTENT_SECURITY_POLICY", "FamilyRoute", "registerContract", "routeFromEndpoint", "schemaFromEndpoint", "accessAuth", "apiKeyAuth", "bodyLimitGuard", "contentTypeGuard", "methodGuard", "originGuard", "d1Bookmarks", "rateLimitRule", "createErrorHandler", "createNotFoundHandler", "respondWithError", "consoleLogger", "requestContext", "REQUEST_ID_HEADER"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/http",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,8 +34,9 @@
|
|
|
34
34
|
],
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"jose": "^6.2.12",
|
|
37
|
-
"@rexezuge/
|
|
38
|
-
"@rexezuge/
|
|
37
|
+
"@rexezuge/contracts": "1.12.0",
|
|
38
|
+
"@rexezuge/errors": "1.12.0",
|
|
39
|
+
"@rexezuge/shared": "1.12.0"
|
|
39
40
|
},
|
|
40
41
|
"peerDependencies": {
|
|
41
42
|
"chanfana": "^3.4.0",
|