@lpdjs/firestore-repo-service 2.6.32 → 2.6.34
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 +14 -373
- package/dist/{create-servers-nXXPnlJt.d.ts → create-servers-DDHHOqOW.d.ts} +3 -3
- package/dist/{create-servers-BoJrRNI2.d.cts → create-servers-DmQNkgM_.d.cts} +3 -3
- package/dist/{index-DZnXSClM.d.cts → index-bkOZzCvS.d.cts} +1 -1
- package/dist/{index-BE-Iuye5.d.ts → index-qSs2G4CW.d.ts} +1 -1
- package/dist/index.cjs +94 -94
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -5
- package/dist/index.d.ts +7 -5
- package/dist/index.js +94 -94
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +43 -21
- package/dist/llms.txt +1 -1
- package/dist/{openapi-BHW1HViI.d.cts → openapi-B_2O8iJW.d.cts} +1 -1
- package/dist/{openapi-BupSdudk.d.ts → openapi-DBi6hg2V.d.ts} +1 -1
- package/dist/servers/admin/index.d.cts +4 -2
- package/dist/servers/admin/index.d.ts +4 -2
- package/dist/servers/crud/index.cjs +7 -7
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +7 -171
- package/dist/servers/crud/index.d.ts +7 -171
- package/dist/servers/crud/index.js +7 -7
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.d.cts +5 -858
- package/dist/servers/hono/index.d.ts +5 -858
- package/dist/servers/index.cjs +98 -98
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +7 -5
- package/dist/servers/index.d.ts +7 -5
- package/dist/servers/index.js +98 -98
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +7 -7
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +7 -7
- package/dist/sync/index.js.map +1 -1
- package/dist/types-B4dMmfet.d.cts +860 -0
- package/dist/{types-CpkQQn4b.d.cts → types-BRS75oO7.d.cts} +10 -38
- package/dist/{types-BcT92G9B.d.ts → types-DnycnK_G.d.ts} +10 -38
- package/dist/types-DyKJJ9UQ.d.ts +860 -0
- package/package.json +1 -1
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
import { z, ZodError } from 'zod';
|
|
2
|
+
import { Env, Context, MiddlewareHandler } from 'hono';
|
|
3
|
+
import { F as FirebaseAdminAuthLike, D as DecodedIdTokenLike } from './firebase-auth-DZ8lb2Ec.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Global DI services container for the Hono server.
|
|
7
|
+
*
|
|
8
|
+
* Lets you declare all your singletons (repositories, SDK clients, useCases,
|
|
9
|
+
* loggers…) **once**, then inject them anywhere — routes, interceptors,
|
|
10
|
+
* cron jobs, Firestore triggers, tests.
|
|
11
|
+
*
|
|
12
|
+
* ## How it works
|
|
13
|
+
*
|
|
14
|
+
* - Each service is constructed **lazily** on first access and cached for
|
|
15
|
+
* the process lifetime (perfect for Cloud Functions cold-start).
|
|
16
|
+
* - Providers may be **classes** (auto-injected: `new Class(services)`)
|
|
17
|
+
* or **factories** (`(services) => instance`). Mix both freely.
|
|
18
|
+
* - Inter-service dependencies are inferred either by destructuring the
|
|
19
|
+
* factory argument (`postRepo: ({ db }) => new PostRepo(db)`) or by
|
|
20
|
+
* reading `this.services.*` inside a class.
|
|
21
|
+
* - A built-in `ctx` service exposes the **current request's** Hono
|
|
22
|
+
* `Context` via `AsyncLocalStorage`. UseCases access
|
|
23
|
+
* `this.services.ctx.c.get("user")` without any plumbing.
|
|
24
|
+
* - Cycles are detected at first access with a clear error.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* // src/services.ts — infrastructure singletons only (no useCases here)
|
|
29
|
+
* import { createServices } from "@lpdjs/firestore-repo-service/servers/hono";
|
|
30
|
+
* import { PostRepo } from "./domains/posts/PostRepo.js";
|
|
31
|
+
* import { Mailer } from "./services/Mailer.js";
|
|
32
|
+
*
|
|
33
|
+
* export const services = createServices({
|
|
34
|
+
* postRepo: PostRepo, // class form (auto-injected)
|
|
35
|
+
* mailer: ({ ctx }) => new Mailer(ctx), // factory form
|
|
36
|
+
* });
|
|
37
|
+
*
|
|
38
|
+
* export type Services = typeof services;
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* // src/apis.ts
|
|
44
|
+
* import { services } from "./services.js";
|
|
45
|
+
* export const apis = createApiRegistry(
|
|
46
|
+
* { v1: { basePath: "/v1", ... } },
|
|
47
|
+
* { services },
|
|
48
|
+
* );
|
|
49
|
+
* ```
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* // Inside a useCase — extends the UseCase base, owns its Zod schemas
|
|
54
|
+
* import { z } from "zod";
|
|
55
|
+
* import { UseCase } from "@lpdjs/firestore-repo-service/servers/hono";
|
|
56
|
+
* import type { Services } from "../../services.js";
|
|
57
|
+
*
|
|
58
|
+
* const input = z.object({ title: z.string() });
|
|
59
|
+
* const output = z.object({ id: z.string() });
|
|
60
|
+
*
|
|
61
|
+
* export class CreatePostUseCase extends UseCase<typeof input, typeof output, Services> {
|
|
62
|
+
* static readonly input = input;
|
|
63
|
+
* static readonly output = output;
|
|
64
|
+
*
|
|
65
|
+
* async execute(payload: z.infer<typeof input>): Promise<z.infer<typeof output>> {
|
|
66
|
+
* const user = this.services.ctx.c.get("user");
|
|
67
|
+
* return this.services.postRepo.create({ ...payload, authorId: user.id });
|
|
68
|
+
* }
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Per-request context exposed to every service / useCase.
|
|
75
|
+
* The instance is a **stable singleton** but its `c` getter resolves to the
|
|
76
|
+
* Hono `Context` of the currently-handled request via `AsyncLocalStorage`.
|
|
77
|
+
*
|
|
78
|
+
* Outside of a request (cron, manual scripts, tests), wrap your call in
|
|
79
|
+
* {@link withRequestContext} to supply a context, otherwise accessing `c`
|
|
80
|
+
* will throw.
|
|
81
|
+
*/
|
|
82
|
+
interface RequestContext<TEnv extends Env = Env> {
|
|
83
|
+
/** Hono `Context` of the currently-handled request. */
|
|
84
|
+
readonly c: Context<TEnv>;
|
|
85
|
+
/**
|
|
86
|
+
* Same as `c` but returns `undefined` instead of throwing when called
|
|
87
|
+
* outside a request scope. Useful for opportunistic logging.
|
|
88
|
+
*/
|
|
89
|
+
readonly maybeC: Context<TEnv> | undefined;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Hono middleware installed automatically by `HonoServer` when a `services`
|
|
93
|
+
* container is provided. Populates the AsyncLocalStorage so the built-in
|
|
94
|
+
* `ctx` service resolves to the current request.
|
|
95
|
+
*
|
|
96
|
+
* Exported for advanced cases (custom server / non-Hono adapter); you do not
|
|
97
|
+
* need to call this manually in the standard flow.
|
|
98
|
+
*/
|
|
99
|
+
declare function createRequestContextMiddleware(): MiddlewareHandler;
|
|
100
|
+
/**
|
|
101
|
+
* Run `fn` with a synthetic request context — required when invoking
|
|
102
|
+
* services outside an HTTP handler (cron jobs, Firestore triggers, scripts,
|
|
103
|
+
* unit tests). Inside `fn`, `services.ctx.c` resolves to the supplied `c`.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```ts
|
|
107
|
+
* // A cron that reuses a useCase
|
|
108
|
+
* export const dailyTask = onSchedule("every 24 hours", async () => {
|
|
109
|
+
* await withRequestContext({ c: fakeContext() }, async () => {
|
|
110
|
+
* await services.createPostUseCase.execute({ ... });
|
|
111
|
+
* });
|
|
112
|
+
* });
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
declare function withRequestContext<T>(ctx: {
|
|
116
|
+
c: Context;
|
|
117
|
+
}, fn: () => Promise<T> | T): Promise<T>;
|
|
118
|
+
/**
|
|
119
|
+
* Reserved service name — the built-in request context. User factories
|
|
120
|
+
* cannot override it.
|
|
121
|
+
*/
|
|
122
|
+
declare const CTX_KEY: "ctx";
|
|
123
|
+
/**
|
|
124
|
+
* Helper that derives the public services type from an output map.
|
|
125
|
+
* Each entry in `TMap` is the instance type returned by its provider.
|
|
126
|
+
* The built-in `ctx` is always present.
|
|
127
|
+
*/
|
|
128
|
+
type ServicesOf<TMap> = {
|
|
129
|
+
readonly ctx: RequestContext;
|
|
130
|
+
} & {
|
|
131
|
+
readonly [K in keyof TMap]: TMap[K];
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* A single provider entry — either a factory `(deps) => R` or a class
|
|
135
|
+
* `new (deps) => R`. `deps` is the *complete* services proxy
|
|
136
|
+
* (siblings + built-in `ctx`).
|
|
137
|
+
*/
|
|
138
|
+
type ServiceProvider<TMap, R> = ((deps: ServicesOf<TMap>) => R) | (new (deps: ServicesOf<TMap>) => R);
|
|
139
|
+
/**
|
|
140
|
+
* A provider map — each value is either a factory or a class constructor.
|
|
141
|
+
*/
|
|
142
|
+
type ServiceProviderMap<TMap> = {
|
|
143
|
+
[K in keyof TMap]: K extends typeof CTX_KEY ? never : ServiceProvider<TMap, TMap[K]>;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Extract the instance/return type from a single provider value.
|
|
147
|
+
*/
|
|
148
|
+
type ProviderReturn<P> = P extends new (...args: any) => infer R ? R : P extends (...args: any) => infer R ? R : never;
|
|
149
|
+
/**
|
|
150
|
+
* Compute the output service map from an inferred provider map.
|
|
151
|
+
*/
|
|
152
|
+
type MapFromProviders<P> = {
|
|
153
|
+
[K in keyof P]: ProviderReturn<P[K]>;
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Container returned by {@link createServices}. Behaves like a plain object
|
|
157
|
+
* keyed by service name — accessing a key triggers lazy instantiation.
|
|
158
|
+
* Use `type Services = typeof services` to derive the public type.
|
|
159
|
+
*/
|
|
160
|
+
type ServicesContainer<TMap> = TMap;
|
|
161
|
+
/**
|
|
162
|
+
* Build a lazy singleton DI container.
|
|
163
|
+
*
|
|
164
|
+
* @param providers A map of service name → factory function **or** class
|
|
165
|
+
* constructor. The single argument (factory deps / first
|
|
166
|
+
* ctor param) receives a deps proxy typed as the full
|
|
167
|
+
* services map (siblings + the built-in `ctx`).
|
|
168
|
+
*
|
|
169
|
+
* @example Factory form
|
|
170
|
+
* ```ts
|
|
171
|
+
* db: () => getFirestore(),
|
|
172
|
+
* postRepo: ({ db }) => new PostRepo(db),
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* @example Class form (zero-boilerplate auto-injection)
|
|
176
|
+
* ```ts
|
|
177
|
+
* class RepositoryService {
|
|
178
|
+
* constructor(private readonly services: Services) {}
|
|
179
|
+
* get posts() { return this.services.db.posts; }
|
|
180
|
+
* }
|
|
181
|
+
*
|
|
182
|
+
* createServices({
|
|
183
|
+
* db: () => getFirestore(), // ← factory
|
|
184
|
+
* repository: RepositoryService, // ← bare class (deps auto-injected)
|
|
185
|
+
* });
|
|
186
|
+
* ```
|
|
187
|
+
*/
|
|
188
|
+
declare function createServices<P extends Record<string, ((deps: any) => unknown) | (new (deps: any) => unknown)>>(providers: P): ServicesContainer<ServicesOf<MapFromProviders<P>>>;
|
|
189
|
+
/**
|
|
190
|
+
* Opaque container type used by registry / server signatures that don't
|
|
191
|
+
* need to know the concrete services map.
|
|
192
|
+
*/
|
|
193
|
+
type AnyServicesContainer = ServicesContainer<Record<string, any>>;
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Hono-native auth guards for the OpenAPI docs / spec endpoints.
|
|
197
|
+
*
|
|
198
|
+
* These return plain Hono `MiddlewareHandler`s, so they slot into
|
|
199
|
+
* `OpenAPIConfig.docsAuth` (which protects only `/docs` + `/openapi.json`,
|
|
200
|
+
* never the API routes). For a fully custom flow, pass your own middleware
|
|
201
|
+
* instead of these helpers.
|
|
202
|
+
*/
|
|
203
|
+
|
|
204
|
+
/** Decoded token shape — kept minimal to avoid a hard firebase-admin import. */
|
|
205
|
+
interface DecodedBearerToken {
|
|
206
|
+
uid: string;
|
|
207
|
+
email?: string;
|
|
208
|
+
[claim: string]: any;
|
|
209
|
+
}
|
|
210
|
+
/** Minimal Firebase Admin Auth surface used by {@link firebaseBearerAuth}. */
|
|
211
|
+
interface FirebaseBearerAuthLike {
|
|
212
|
+
verifyIdToken(idToken: string, checkRevoked?: boolean): Promise<DecodedBearerToken>;
|
|
213
|
+
}
|
|
214
|
+
/** Options for {@link firebaseBearerAuth}. */
|
|
215
|
+
interface FirebaseBearerAuthOptions {
|
|
216
|
+
/**
|
|
217
|
+
* Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called
|
|
218
|
+
* lazily on each request so `initializeApp()` runs first.
|
|
219
|
+
*/
|
|
220
|
+
getAuth: () => FirebaseBearerAuthLike;
|
|
221
|
+
/**
|
|
222
|
+
* Authorization policy. Return `false` (or throw) to reject the request,
|
|
223
|
+
* any truthy value to allow. Defaults to allowing any verified token.
|
|
224
|
+
*/
|
|
225
|
+
allow?: (token: DecodedBearerToken) => boolean | Promise<boolean>;
|
|
226
|
+
/** Revoke check passed to `verifyIdToken`. Default: `false`. */
|
|
227
|
+
checkRevoked?: boolean;
|
|
228
|
+
/**
|
|
229
|
+
* Context key under which the decoded token is stored (`c.set(key, token)`)
|
|
230
|
+
* for downstream handlers. Default: `"docsUser"`.
|
|
231
|
+
*/
|
|
232
|
+
contextKey?: string;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Guard the docs / spec endpoints with a Firebase ID token (Bearer scheme).
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* ```ts
|
|
239
|
+
* import { getAuth } from "firebase-admin/auth";
|
|
240
|
+
* import { firebaseBearerAuth } from "@lpdjs/firestore-repo-service/servers/hono";
|
|
241
|
+
*
|
|
242
|
+
* openapi: {
|
|
243
|
+
* info,
|
|
244
|
+
* docsAuth: firebaseBearerAuth({
|
|
245
|
+
* getAuth: () => getAuth(),
|
|
246
|
+
* allow: (t) => t.admin === true,
|
|
247
|
+
* }),
|
|
248
|
+
* }
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
declare function firebaseBearerAuth(options: FirebaseBearerAuthOptions): MiddlewareHandler;
|
|
252
|
+
/** Options for {@link basicAuth}. */
|
|
253
|
+
interface BasicAuthOptions {
|
|
254
|
+
username: string;
|
|
255
|
+
password: string;
|
|
256
|
+
/** Realm advertised in the `WWW-Authenticate` header. Default: `"Docs"`. */
|
|
257
|
+
realm?: string;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Guard the docs / spec endpoints with HTTP Basic Auth.
|
|
261
|
+
*
|
|
262
|
+
* @example
|
|
263
|
+
* ```ts
|
|
264
|
+
* openapi: { info, docsAuth: basicAuth({ username: "admin", password: "secret" }) }
|
|
265
|
+
* ```
|
|
266
|
+
*/
|
|
267
|
+
declare function basicAuth(options: BasicAuthOptions): MiddlewareHandler;
|
|
268
|
+
/** A bare auxiliary route name (relative to the docs directory). */
|
|
269
|
+
interface DocsAuthRoute {
|
|
270
|
+
method: "GET" | "POST";
|
|
271
|
+
/** Bare path segment relative to the docs directory, e.g. `"__login"`. */
|
|
272
|
+
name: string;
|
|
273
|
+
handler: MiddlewareHandler;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Richer `docsAuth` value (vs. a bare `MiddlewareHandler`): a guard middleware
|
|
277
|
+
* **plus** auxiliary routes (login page, session exchange, logout) that the
|
|
278
|
+
* {@link HonoServer} mounts next to the docs/spec endpoints. Mirrors the admin
|
|
279
|
+
* server's `AuthExtension`. Produced by {@link firebaseDocsAuth}.
|
|
280
|
+
*/
|
|
281
|
+
interface DocsAuthExtension {
|
|
282
|
+
readonly __docsAuthExtension: true;
|
|
283
|
+
/** Guard applied to the docs UI + JSON spec endpoints. */
|
|
284
|
+
middleware: MiddlewareHandler;
|
|
285
|
+
/** Auxiliary routes mounted (unguarded) in the docs directory. */
|
|
286
|
+
routes: DocsAuthRoute[];
|
|
287
|
+
/** Bare login route name, used to redirect unauthenticated browsers. */
|
|
288
|
+
loginName: string;
|
|
289
|
+
}
|
|
290
|
+
/** Type guard distinguishing a {@link DocsAuthExtension} from a raw middleware. */
|
|
291
|
+
declare function isDocsAuthExtension(value: unknown): value is DocsAuthExtension;
|
|
292
|
+
/** Options for {@link firebaseDocsAuth}. */
|
|
293
|
+
interface FirebaseDocsAuthOptions {
|
|
294
|
+
/**
|
|
295
|
+
* Returns the Firebase Admin Auth instance, e.g. `() => getAuth()`. Called
|
|
296
|
+
* lazily on each request so `initializeApp()` runs first. Must expose
|
|
297
|
+
* `verifyIdToken`, `verifySessionCookie`, `createSessionCookie`,
|
|
298
|
+
* `revokeRefreshTokens`.
|
|
299
|
+
*/
|
|
300
|
+
getAuth: () => FirebaseAdminAuthLike;
|
|
301
|
+
/** Firebase Web API key — required by the JS SDK on the login page. */
|
|
302
|
+
apiKey: string;
|
|
303
|
+
/** Firebase Auth domain (e.g. `my-project.firebaseapp.com`). */
|
|
304
|
+
authDomain: string;
|
|
305
|
+
/**
|
|
306
|
+
* Transport mode. `"cookie"` (default) gates the docs behind the bundled
|
|
307
|
+
* login form + a server-side session cookie. `"both"` additionally accepts a
|
|
308
|
+
* `Bearer` ID token (handy to embed the docs in an authenticated iframe).
|
|
309
|
+
*/
|
|
310
|
+
mode?: "cookie" | "both";
|
|
311
|
+
/**
|
|
312
|
+
* Authorization policy. Return `false` (or throw) to reject, any truthy value
|
|
313
|
+
* to allow. Defaults to allowing any verified user. Receives the decoded
|
|
314
|
+
* ID-token / session-cookie claims.
|
|
315
|
+
*/
|
|
316
|
+
allow?: (token: DecodedIdTokenLike) => boolean | Promise<boolean>;
|
|
317
|
+
/** Providers shown on the login page. Default: `["password", "google"]`. */
|
|
318
|
+
providers?: ("password" | "google")[];
|
|
319
|
+
/** Login page title. Default: `"Docs sign-in"`. */
|
|
320
|
+
title?: string;
|
|
321
|
+
/** Session cookie name. Default: `"__docs_session"`. */
|
|
322
|
+
cookieName?: string;
|
|
323
|
+
/** Session cookie TTL in days. Default: `5` (Firebase max is 14). */
|
|
324
|
+
sessionTtlDays?: number;
|
|
325
|
+
/** Cookie `Secure` flag. Default: `true` (set `false` only for local HTTP). */
|
|
326
|
+
secureCookie?: boolean;
|
|
327
|
+
/** Cookie `SameSite`. Default: `"Lax"`. */
|
|
328
|
+
sameSite?: "Strict" | "Lax" | "None";
|
|
329
|
+
/**
|
|
330
|
+
* Context key under which the decoded token is stored (`c.set(key, token)`)
|
|
331
|
+
* for downstream handlers. Default: `"docsUser"`.
|
|
332
|
+
*/
|
|
333
|
+
contextKey?: string;
|
|
334
|
+
/**
|
|
335
|
+
* Behaviour when authentication fails. `"redirect"` (default) sends browser
|
|
336
|
+
* `GET`s to the login page; `"401"` always returns a JSON 401.
|
|
337
|
+
*/
|
|
338
|
+
onUnauthenticated?: "redirect" | "401";
|
|
339
|
+
/**
|
|
340
|
+
* Firebase Auth emulator host (e.g. `127.0.0.1:9099`). When set, the login
|
|
341
|
+
* page's client SDK targets the emulator via `connectAuthEmulator`, matching
|
|
342
|
+
* the Admin SDK (which already routes to the emulator when
|
|
343
|
+
* `FIREBASE_AUTH_EMULATOR_HOST` is set). Defaults to that env var; pass `""`
|
|
344
|
+
* to force it off.
|
|
345
|
+
*/
|
|
346
|
+
authEmulatorHost?: string;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Guard the docs / spec endpoints with a Firebase **login form + session
|
|
350
|
+
* cookie**, the same flow as the admin server — instead of forcing callers to
|
|
351
|
+
* craft a `Bearer` token by hand.
|
|
352
|
+
*
|
|
353
|
+
* Returns a {@link DocsAuthExtension}: pass it straight to
|
|
354
|
+
* `OpenAPIConfig.docsAuth`. The {@link HonoServer} mounts the bundled
|
|
355
|
+
* `__login` / `__session` / `__logout` routes next to the docs and applies the
|
|
356
|
+
* guard. Unauthenticated browsers are redirected to the login page; once signed
|
|
357
|
+
* in, an HttpOnly session cookie keeps them authenticated.
|
|
358
|
+
*
|
|
359
|
+
* @example
|
|
360
|
+
* ```ts
|
|
361
|
+
* import { getAuth } from "firebase-admin/auth";
|
|
362
|
+
* import { firebaseDocsAuth } from "@lpdjs/firestore-repo-service/servers/hono";
|
|
363
|
+
*
|
|
364
|
+
* openapi: {
|
|
365
|
+
* info,
|
|
366
|
+
* docsAuth: firebaseDocsAuth({
|
|
367
|
+
* getAuth: () => getAuth(),
|
|
368
|
+
* apiKey: process.env.FIREBASE_API_KEY!,
|
|
369
|
+
* authDomain: process.env.FIREBASE_AUTH_DOMAIN!,
|
|
370
|
+
* allow: (t) => t.admin === true, // optional policy
|
|
371
|
+
* }),
|
|
372
|
+
* }
|
|
373
|
+
* ```
|
|
374
|
+
*/
|
|
375
|
+
declare function firebaseDocsAuth(options: FirebaseDocsAuthOptions): DocsAuthExtension;
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Public types for the Hono file-based API server.
|
|
379
|
+
*
|
|
380
|
+
* Designed to be:
|
|
381
|
+
* - **fully typed** end-to-end (Zod input/output → handler payload type),
|
|
382
|
+
* - **runtime-safe** via Zod parsing on every request,
|
|
383
|
+
* - **bundle-friendly** for Firebase Cloud Functions v2 cold-start (codegen
|
|
384
|
+
* emits static imports — no `fs`/`import()` at runtime).
|
|
385
|
+
*/
|
|
386
|
+
|
|
387
|
+
type HttpMethod = "get" | "post" | "put" | "patch" | "delete";
|
|
388
|
+
/** Where the validated payload comes from. */
|
|
389
|
+
type PayloadSource = "json" | "query" | "form" | "param";
|
|
390
|
+
/**
|
|
391
|
+
* Structured logger injected into every handler / interceptor / error-handler
|
|
392
|
+
* context. Implement it, or extend the package's `BaseLogger` and override its
|
|
393
|
+
* `write` hook to route to your sink (Firebase logger, pino, …).
|
|
394
|
+
*
|
|
395
|
+
* `error()` returns a correlation id so the same value can be both logged and
|
|
396
|
+
* returned to the client.
|
|
397
|
+
*/
|
|
398
|
+
interface Logger {
|
|
399
|
+
info(message: string, meta?: unknown): void;
|
|
400
|
+
warn(message: string, meta?: unknown): void;
|
|
401
|
+
/** @returns a correlation id (e.g. to include in the HTTP error response). */
|
|
402
|
+
error(error: unknown, meta?: unknown): string;
|
|
403
|
+
debug(message: string, meta?: unknown): void;
|
|
404
|
+
}
|
|
405
|
+
/** Context passed to {@link ErrorHandler.handle}. */
|
|
406
|
+
interface ErrorHandlerContext<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
|
|
407
|
+
/** The thrown value (an `AppError`, a Zod {@link ValidationError}, …). */
|
|
408
|
+
error: unknown;
|
|
409
|
+
/** Hono request context — set status, read headers, build the response. */
|
|
410
|
+
c: Context<TEnv>;
|
|
411
|
+
/** Route metadata (read-only). */
|
|
412
|
+
route: AnyRouteDef;
|
|
413
|
+
/** Global DI services container. */
|
|
414
|
+
services: TServices;
|
|
415
|
+
/** Injected {@link Logger} when one was passed to the API, else `undefined`. */
|
|
416
|
+
logger?: Logger;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Cross-cutting error strategy — a class (or object) you pass to the API and
|
|
420
|
+
* that the server injects everywhere **and** applies automatically.
|
|
421
|
+
*
|
|
422
|
+
* Implement {@link ErrorHandler.handle} to map any thrown value to an HTTP
|
|
423
|
+
* `Response` (e.g. your `AppError` → status + localized body, plus structured
|
|
424
|
+
* logging with a correlation id). Return `null` to decline the error and let
|
|
425
|
+
* the built-in fallback (`ValidationError` envelope) / `onError` take over.
|
|
426
|
+
*
|
|
427
|
+
* Prefer extending the package's {@link BaseErrorHandler} (it already maps the
|
|
428
|
+
* built-in errors) and overriding its `mapError` / `logError` hooks. Pass it
|
|
429
|
+
* **per API** via `ApiConfig.errorHandler`, or once via the registry
|
|
430
|
+
* (`{ services, errorHandler }`); it is then available in every handler /
|
|
431
|
+
* interceptor context as `errorHandler` and auto-applied on any uncaught error.
|
|
432
|
+
*/
|
|
433
|
+
interface ErrorHandler<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
|
|
434
|
+
handle(ctx: ErrorHandlerContext<TEnv, TServices>): Response | null | Promise<Response | null>;
|
|
435
|
+
}
|
|
436
|
+
/** Handler signature — receives a single typed context object. */
|
|
437
|
+
type RouteHandler<TIn, TOut, TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = (ctx: {
|
|
438
|
+
/** Validated (and typed) request payload. `void` when no `input` schema is defined. */
|
|
439
|
+
input: TIn;
|
|
440
|
+
/** Raw Hono `Context` for headers, set status, redirect, etc. */
|
|
441
|
+
c: Context<TEnv>;
|
|
442
|
+
/**
|
|
443
|
+
* Global DI services container — same instance shared by every handler.
|
|
444
|
+
* Empty `ServicesContainer` when the server was started without a
|
|
445
|
+
* `services` option.
|
|
446
|
+
*/
|
|
447
|
+
services: TServices;
|
|
448
|
+
/**
|
|
449
|
+
* Injected {@link ErrorHandler} when one was passed to the API, else
|
|
450
|
+
* `undefined`. Usually you just `throw` and let it apply automatically.
|
|
451
|
+
*/
|
|
452
|
+
errorHandler?: ErrorHandler<TEnv, TServices>;
|
|
453
|
+
/** Injected {@link Logger} when one was passed to the API, else `undefined`. */
|
|
454
|
+
logger?: Logger;
|
|
455
|
+
}) => Promise<TOut | Response> | TOut | Response;
|
|
456
|
+
/**
|
|
457
|
+
* One route declaration. Default-exported by every `routes.ts` file inside the
|
|
458
|
+
* domain tree. Use {@link defineRoute} for full type inference.
|
|
459
|
+
*/
|
|
460
|
+
interface RouteDef<TIn extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined, TOut extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined, TEnv extends Env = Env> {
|
|
461
|
+
/**
|
|
462
|
+
* Logical API tag — routes sharing the same `api` are mounted on the same
|
|
463
|
+
* `HonoServer` (typically one Cloud Function per `api`).
|
|
464
|
+
*
|
|
465
|
+
* To expose the **same logic** under several APIs with different
|
|
466
|
+
* inputs/outputs, export multiple `defineRoute({...})` from the same file
|
|
467
|
+
* (default + named exports are both picked up by the codegen).
|
|
468
|
+
*/
|
|
469
|
+
api: string;
|
|
470
|
+
/** HTTP method. */
|
|
471
|
+
method: HttpMethod;
|
|
472
|
+
/**
|
|
473
|
+
* URL path appended to the server `basePath`. If omitted, the codegen will
|
|
474
|
+
* derive it from the file location (e.g. `domains/activities/useCases/createCustom/routes.ts`
|
|
475
|
+
* → `/activities/createCustom`).
|
|
476
|
+
*/
|
|
477
|
+
path?: string;
|
|
478
|
+
/**
|
|
479
|
+
* Where the request payload comes from.
|
|
480
|
+
* Default: `"json"` for body methods (POST/PUT/PATCH/DELETE), `"query"` for GET.
|
|
481
|
+
*/
|
|
482
|
+
source?: PayloadSource;
|
|
483
|
+
/** Zod schema validating the payload. Failures yield a 400 response. */
|
|
484
|
+
input?: TIn;
|
|
485
|
+
/**
|
|
486
|
+
* Zod schema for the success response. Used to populate the OpenAPI spec
|
|
487
|
+
* and (when `validateOutput` is enabled on the server) to assert the
|
|
488
|
+
* runtime payload returned by the handler.
|
|
489
|
+
*/
|
|
490
|
+
output?: TOut;
|
|
491
|
+
/** Status code for the success response. Default: 200. */
|
|
492
|
+
status?: number;
|
|
493
|
+
/** Hono middlewares applied to this route only (after global middlewares). */
|
|
494
|
+
middlewares?: MiddlewareHandler<TEnv>[];
|
|
495
|
+
summary?: string;
|
|
496
|
+
description?: string;
|
|
497
|
+
tags?: string[];
|
|
498
|
+
/** Mark the operation as deprecated in the generated spec. */
|
|
499
|
+
deprecated?: boolean;
|
|
500
|
+
/** Security requirements (operationId-level override). */
|
|
501
|
+
security?: SecurityRequirement[];
|
|
502
|
+
/** The request handler. */
|
|
503
|
+
handler: RouteHandler<TIn extends z.ZodTypeAny ? z.infer<TIn> : void, TOut extends z.ZodTypeAny ? z.infer<TOut> : unknown, TEnv>;
|
|
504
|
+
}
|
|
505
|
+
/** Erased `RouteDef` used by registry/codegen — handler signature is opaque. */
|
|
506
|
+
type AnyRouteDef = RouteDef<any, any>;
|
|
507
|
+
/**
|
|
508
|
+
* What `routes.ts` can default-export:
|
|
509
|
+
* - a single {@link RouteDef} (most common case),
|
|
510
|
+
* - or an array of {@link RouteDef} (e.g. expose the same useCase on
|
|
511
|
+
* multiple `api` tags or under multiple paths). `readonly` arrays are
|
|
512
|
+
* accepted so that tuple-preserving helpers like {@link defineRoutes} (or a
|
|
513
|
+
* plain `as const` array) can be default-exported directly.
|
|
514
|
+
*/
|
|
515
|
+
type RouteModuleDefault = AnyRouteDef | readonly AnyRouteDef[];
|
|
516
|
+
/**
|
|
517
|
+
* Identity helper that **preserves the tuple type** of a `routes.ts` default
|
|
518
|
+
* export. A plain array literal (`export default [a, b]`) collapses every
|
|
519
|
+
* element to a single common type, which would lose each route's individual
|
|
520
|
+
* schema. Wrapping the array with `defineRoutes([...])` keeps the per-route
|
|
521
|
+
* types intact so {@link RouteInput} / {@link RouteOutput} can aggregate them
|
|
522
|
+
* into a union.
|
|
523
|
+
*
|
|
524
|
+
* @example
|
|
525
|
+
* export default defineRoutes([
|
|
526
|
+
* defineRoute({ ... }),
|
|
527
|
+
* defineRoute({ ... }),
|
|
528
|
+
* ]);
|
|
529
|
+
*/
|
|
530
|
+
declare function defineRoutes<const T extends readonly AnyRouteDef[]>(routes: T): T;
|
|
531
|
+
/**
|
|
532
|
+
* Normalizes a `routes.ts` default export — a single {@link RouteDef} or an
|
|
533
|
+
* array of them — to a *union* of its individual route members.
|
|
534
|
+
*/
|
|
535
|
+
type RoutesUnion<T> = T extends readonly (infer R)[] ? R : T;
|
|
536
|
+
type InferRouteInput<R> = R extends {
|
|
537
|
+
input?: infer I;
|
|
538
|
+
} ? I extends z.ZodTypeAny ? z.infer<I> : void : void;
|
|
539
|
+
type InferRouteOutput<R> = R extends {
|
|
540
|
+
output?: infer O;
|
|
541
|
+
} ? O extends z.ZodTypeAny ? z.infer<O> : unknown : unknown;
|
|
542
|
+
/**
|
|
543
|
+
* Union of validated request payloads across every route in a `routes.ts`
|
|
544
|
+
* module. Use it to type a useCase input without duplicating the Zod schema:
|
|
545
|
+
*
|
|
546
|
+
* @example
|
|
547
|
+
* type Routes = typeof import("./routes.js").default;
|
|
548
|
+
* export type CreatePostUseCaseInput = RouteInput<Routes>;
|
|
549
|
+
*/
|
|
550
|
+
type RouteInput<T> = InferRouteInput<RoutesUnion<T>>;
|
|
551
|
+
/**
|
|
552
|
+
* Union of success-response payloads across every route in a `routes.ts`
|
|
553
|
+
* module. Mirror of {@link RouteInput} for the useCase output type.
|
|
554
|
+
*/
|
|
555
|
+
type RouteOutput<T> = InferRouteOutput<RoutesUnion<T>>;
|
|
556
|
+
/**
|
|
557
|
+
* Thrown by the server when the incoming request fails Zod validation.
|
|
558
|
+
* Caught by the {@link RouteInterceptor} (if any) so users can shape the
|
|
559
|
+
* response envelope however they like; otherwise yields a default 400.
|
|
560
|
+
*/
|
|
561
|
+
declare class ValidationError extends Error {
|
|
562
|
+
/** Original Zod error — `error.issues` to enumerate field-level problems. */
|
|
563
|
+
readonly zodError: ZodError;
|
|
564
|
+
/** Where the offending payload came from. */
|
|
565
|
+
readonly source: PayloadSource;
|
|
566
|
+
readonly statusCode: 400;
|
|
567
|
+
constructor(
|
|
568
|
+
/** Original Zod error — `error.issues` to enumerate field-level problems. */
|
|
569
|
+
zodError: ZodError,
|
|
570
|
+
/** Where the offending payload came from. */
|
|
571
|
+
source: PayloadSource);
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Cross-cutting interceptor applied around every handler.
|
|
575
|
+
* Use it for response envelopes, business-error → HTTP mapping, structured
|
|
576
|
+
* logging, tracing spans, etc.
|
|
577
|
+
*
|
|
578
|
+
* Wrap `next()` in `try/catch` to intercept BOTH Zod {@link ValidationError}s
|
|
579
|
+
* (thrown before the handler runs) AND business errors thrown by the handler.
|
|
580
|
+
*
|
|
581
|
+
* @example
|
|
582
|
+
* ```ts
|
|
583
|
+
* interceptor: async ({ next, route, c }) => {
|
|
584
|
+
* try {
|
|
585
|
+
* const data = await next();
|
|
586
|
+
* return c.json({ success: true, data, error: null });
|
|
587
|
+
* } catch (err) {
|
|
588
|
+
* if (err instanceof ValidationError) {
|
|
589
|
+
* return c.json({ success: false, error: "validation", issues: err.zodError.issues }, 400);
|
|
590
|
+
* }
|
|
591
|
+
* if (err instanceof DomainError) {
|
|
592
|
+
* return c.json({ success: false, error: err.code }, err.statusCode);
|
|
593
|
+
* }
|
|
594
|
+
* throw err; // → falls back to onError or Hono's default 500
|
|
595
|
+
* }
|
|
596
|
+
* }
|
|
597
|
+
* ```
|
|
598
|
+
*/
|
|
599
|
+
type RouteInterceptor<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = (ctx: {
|
|
600
|
+
/**
|
|
601
|
+
* Calls validation + handler and returns the raw value.
|
|
602
|
+
* Throws {@link ValidationError} on Zod failure or any error thrown by the handler.
|
|
603
|
+
*/
|
|
604
|
+
next: () => Promise<unknown>;
|
|
605
|
+
/** Route metadata (read-only). */
|
|
606
|
+
route: AnyRouteDef;
|
|
607
|
+
/** Hono request context. */
|
|
608
|
+
c: Context<TEnv>;
|
|
609
|
+
/** Global DI services container. See {@link RouteHandler}. */
|
|
610
|
+
services: TServices;
|
|
611
|
+
/**
|
|
612
|
+
* Injected {@link ErrorHandler} when one was passed to the API. Call
|
|
613
|
+
* `errorHandler?.handle({ error, c, route, services })` in your `catch` to
|
|
614
|
+
* reuse the shared mapping, or simply rethrow to let it apply automatically.
|
|
615
|
+
*/
|
|
616
|
+
errorHandler?: ErrorHandler<TEnv, TServices>;
|
|
617
|
+
/** Injected {@link Logger} when one was passed to the API, else `undefined`. */
|
|
618
|
+
logger?: Logger;
|
|
619
|
+
}) => Promise<Response | unknown> | Response | unknown;
|
|
620
|
+
/**
|
|
621
|
+
* Success-envelope schema declared alongside an interceptor so the generated
|
|
622
|
+
* OpenAPI spec documents what the **wrapper actually returns** (not the raw
|
|
623
|
+
* handler output).
|
|
624
|
+
*
|
|
625
|
+
* - a **static** Zod schema → same envelope for every route (e.g.
|
|
626
|
+
* `z.object({ data: z.any(), intercepted: z.boolean() })`);
|
|
627
|
+
* - a **factory** `(routeOutput) => schema` → wraps each route's own `output`,
|
|
628
|
+
* so `data` is typed per endpoint in the docs.
|
|
629
|
+
*/
|
|
630
|
+
type InterceptorOutput = z.ZodTypeAny | ((routeOutput: z.ZodTypeAny | undefined) => z.ZodTypeAny);
|
|
631
|
+
/** A single declared error response for the OpenAPI spec. */
|
|
632
|
+
type InterceptorErrorResponse = z.ZodTypeAny | {
|
|
633
|
+
description?: string;
|
|
634
|
+
schema?: z.ZodTypeAny;
|
|
635
|
+
};
|
|
636
|
+
/**
|
|
637
|
+
* Structured interceptor — pairs the cross-cutting {@link RouteInterceptor}
|
|
638
|
+
* `handler` with the OpenAPI metadata describing what it returns, so the docs
|
|
639
|
+
* reflect the real wrapped responses (success envelope + error shapes).
|
|
640
|
+
*
|
|
641
|
+
* @example
|
|
642
|
+
* ```ts
|
|
643
|
+
* interceptor: {
|
|
644
|
+
* // factory: `data` reflects each route's own output schema
|
|
645
|
+
* output: (routeOutput) =>
|
|
646
|
+
* z.object({ data: routeOutput ?? z.unknown(), intercepted: z.boolean() }),
|
|
647
|
+
* errors: {
|
|
648
|
+
* 400: ValidationErrorSchema,
|
|
649
|
+
* 500: { description: "Internal", schema: ErrorSchema },
|
|
650
|
+
* },
|
|
651
|
+
* handler: async ({ c, next }) => {
|
|
652
|
+
* const data = await next();
|
|
653
|
+
* return c.json({ data, intercepted: true });
|
|
654
|
+
* },
|
|
655
|
+
* }
|
|
656
|
+
* ```
|
|
657
|
+
*/
|
|
658
|
+
interface InterceptorConfig<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> {
|
|
659
|
+
/** Success-envelope schema (static) or per-route factory. */
|
|
660
|
+
output?: InterceptorOutput;
|
|
661
|
+
/**
|
|
662
|
+
* Error responses applied to **every** operation, keyed by HTTP status. Pass
|
|
663
|
+
* a bare Zod schema or `{ description, schema }`.
|
|
664
|
+
*/
|
|
665
|
+
errors?: Record<number, InterceptorErrorResponse>;
|
|
666
|
+
/** The interceptor function. See {@link RouteInterceptor}. */
|
|
667
|
+
handler: RouteInterceptor<TEnv, TServices>;
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Interceptor option accepted by the server / registry — either a bare
|
|
671
|
+
* {@link RouteInterceptor} function (legacy) or a structured
|
|
672
|
+
* {@link InterceptorConfig} carrying OpenAPI metadata.
|
|
673
|
+
*/
|
|
674
|
+
type InterceptorOption<TEnv extends Env = Env, TServices extends AnyServicesContainer = AnyServicesContainer> = RouteInterceptor<TEnv, TServices> | InterceptorConfig<TEnv, TServices>;
|
|
675
|
+
/** OpenAPI document info (subset of the spec used by the helper). */
|
|
676
|
+
interface OpenAPIInfo {
|
|
677
|
+
title: string;
|
|
678
|
+
version: string;
|
|
679
|
+
description?: string;
|
|
680
|
+
}
|
|
681
|
+
/** Fields shared by every security scheme. */
|
|
682
|
+
interface SecuritySchemeBase {
|
|
683
|
+
/** Human-readable description (CommonMark). */
|
|
684
|
+
description?: string;
|
|
685
|
+
}
|
|
686
|
+
/** API key carried in a header, query param or cookie. */
|
|
687
|
+
interface ApiKeySecurityScheme extends SecuritySchemeBase {
|
|
688
|
+
type: "apiKey";
|
|
689
|
+
/** Name of the header, query parameter or cookie. */
|
|
690
|
+
name: string;
|
|
691
|
+
/** Location of the API key. */
|
|
692
|
+
in: "query" | "header" | "cookie";
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* HTTP authentication (RFC 7235), e.g. `bearer` (Firebase ID tokens) or
|
|
696
|
+
* `basic`.
|
|
697
|
+
*/
|
|
698
|
+
interface HttpSecurityScheme extends SecuritySchemeBase {
|
|
699
|
+
type: "http";
|
|
700
|
+
/** Auth scheme name — `"bearer"`, `"basic"`, `"digest"`, … */
|
|
701
|
+
scheme: "bearer" | "basic" | "digest" | (string & {});
|
|
702
|
+
/** Hint for the bearer token format, e.g. `"JWT"` / `"Firebase JWT"`. */
|
|
703
|
+
bearerFormat?: string;
|
|
704
|
+
}
|
|
705
|
+
/** Mutual TLS authentication. */
|
|
706
|
+
interface MutualTlsSecurityScheme extends SecuritySchemeBase {
|
|
707
|
+
type: "mutualTLS";
|
|
708
|
+
}
|
|
709
|
+
/** A single OAuth2 flow. */
|
|
710
|
+
interface OAuthFlowObject {
|
|
711
|
+
authorizationUrl?: string;
|
|
712
|
+
tokenUrl?: string;
|
|
713
|
+
refreshUrl?: string;
|
|
714
|
+
/** Available scopes → description. */
|
|
715
|
+
scopes: Record<string, string>;
|
|
716
|
+
}
|
|
717
|
+
/** The OAuth2 flows supported by an {@link OAuth2SecurityScheme}. */
|
|
718
|
+
interface OAuthFlowsObject {
|
|
719
|
+
implicit?: OAuthFlowObject;
|
|
720
|
+
password?: OAuthFlowObject;
|
|
721
|
+
clientCredentials?: OAuthFlowObject;
|
|
722
|
+
authorizationCode?: OAuthFlowObject;
|
|
723
|
+
}
|
|
724
|
+
/** OAuth2 authentication. */
|
|
725
|
+
interface OAuth2SecurityScheme extends SecuritySchemeBase {
|
|
726
|
+
type: "oauth2";
|
|
727
|
+
flows: OAuthFlowsObject;
|
|
728
|
+
}
|
|
729
|
+
/** OpenID Connect Discovery. */
|
|
730
|
+
interface OpenIdConnectSecurityScheme extends SecuritySchemeBase {
|
|
731
|
+
type: "openIdConnect";
|
|
732
|
+
openIdConnectUrl: string;
|
|
733
|
+
}
|
|
734
|
+
/** OpenAPI 3.1 Security Scheme Object (discriminated on `type`). */
|
|
735
|
+
type SecurityScheme = ApiKeySecurityScheme | HttpSecurityScheme | MutualTlsSecurityScheme | OAuth2SecurityScheme | OpenIdConnectSecurityScheme;
|
|
736
|
+
/**
|
|
737
|
+
* A single Security Requirement Object: maps a scheme name (a key of
|
|
738
|
+
* {@link OpenAPIConfig.securitySchemes}) to the list of required scopes
|
|
739
|
+
* (empty `[]` for `http` / `apiKey`).
|
|
740
|
+
*/
|
|
741
|
+
type SecurityRequirement = Record<string, string[]>;
|
|
742
|
+
/** OpenAPI configuration on the server. */
|
|
743
|
+
interface OpenAPIConfig {
|
|
744
|
+
/** Path served by the JSON spec (e.g. `/openapi.json`). Default: `/openapi.json`. */
|
|
745
|
+
path?: string;
|
|
746
|
+
/** Path serving the documentation UI. Set to `false` to disable. Default: `/docs`. */
|
|
747
|
+
docsPath?: string | false;
|
|
748
|
+
/** OpenAPI document info. */
|
|
749
|
+
info: OpenAPIInfo;
|
|
750
|
+
/** Optional servers list for the spec. */
|
|
751
|
+
servers?: {
|
|
752
|
+
url: string;
|
|
753
|
+
description?: string;
|
|
754
|
+
}[];
|
|
755
|
+
/**
|
|
756
|
+
* Reusable security schemes, keyed by name. The keys are referenced from
|
|
757
|
+
* {@link OpenAPIConfig.security} / per-route `security`.
|
|
758
|
+
*
|
|
759
|
+
* @example
|
|
760
|
+
* ```ts
|
|
761
|
+
* securitySchemes: {
|
|
762
|
+
* bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "Firebase JWT" },
|
|
763
|
+
* }
|
|
764
|
+
* ```
|
|
765
|
+
*/
|
|
766
|
+
securitySchemes?: Record<string, SecurityScheme>;
|
|
767
|
+
/**
|
|
768
|
+
* Default security requirement applied to every operation. Each entry maps a
|
|
769
|
+
* scheme name (a key of {@link OpenAPIConfig.securitySchemes}) to its scopes.
|
|
770
|
+
*
|
|
771
|
+
* @example `security: [{ bearerAuth: [] }]`
|
|
772
|
+
*/
|
|
773
|
+
security?: SecurityRequirement[];
|
|
774
|
+
/**
|
|
775
|
+
* Hono middleware(s) guarding **only** the docs UI and JSON spec endpoints
|
|
776
|
+
* (not the API routes). Use a raw middleware for a custom flow, or the
|
|
777
|
+
* built-in {@link firebaseBearerAuth} / {@link basicAuth} helpers.
|
|
778
|
+
*
|
|
779
|
+
* @example
|
|
780
|
+
* ```ts
|
|
781
|
+
* import { firebaseBearerAuth } from "@lpdjs/firestore-repo-service/servers/hono";
|
|
782
|
+
* openapi: { info, docsAuth: firebaseBearerAuth({ getAuth }) }
|
|
783
|
+
* ```
|
|
784
|
+
*
|
|
785
|
+
* For a full login form + session cookie (like the admin server), pass the
|
|
786
|
+
* {@link DocsAuthExtension} returned by `firebaseDocsAuth({ ... })` instead.
|
|
787
|
+
*/
|
|
788
|
+
docsAuth?: MiddlewareHandler | MiddlewareHandler[] | DocsAuthExtension;
|
|
789
|
+
}
|
|
790
|
+
/** Options consumed by the {@link HonoServer} constructor. */
|
|
791
|
+
interface HonoServerOptions<TEnv extends Env = Env> {
|
|
792
|
+
/**
|
|
793
|
+
* API tag — only routes whose `api` matches this value are mounted.
|
|
794
|
+
* If omitted, every route in the registry is mounted.
|
|
795
|
+
*/
|
|
796
|
+
api?: string;
|
|
797
|
+
/** Pre-resolved route registry (typically the codegen output). */
|
|
798
|
+
routes: AnyRouteDef[];
|
|
799
|
+
/** URL prefix mounted before every route path. Default: `""`. */
|
|
800
|
+
basePath?: string;
|
|
801
|
+
/** Hono middlewares applied to every route (after the built-ins). */
|
|
802
|
+
middlewares?: MiddlewareHandler<TEnv>[];
|
|
803
|
+
/**
|
|
804
|
+
* Alias for `middlewares` — global middlewares applied to every route.
|
|
805
|
+
* If both are provided, `globalMiddlewares` is appended after `middlewares`.
|
|
806
|
+
*/
|
|
807
|
+
globalMiddlewares?: MiddlewareHandler<TEnv>[];
|
|
808
|
+
/**
|
|
809
|
+
* If `true`, the server validates the value returned by every handler
|
|
810
|
+
* against the route's `output` schema and rejects mismatches with a 500
|
|
811
|
+
* response. Useful in dev / staging. Default: `false`.
|
|
812
|
+
*/
|
|
813
|
+
validateOutput?: boolean;
|
|
814
|
+
/** Enable verbose logging of mounted routes at startup. Default: `false`. */
|
|
815
|
+
verbose?: boolean;
|
|
816
|
+
/** OpenAPI configuration. Omit to disable. */
|
|
817
|
+
openapi?: OpenAPIConfig;
|
|
818
|
+
/** Custom 404 handler. */
|
|
819
|
+
notFound?: (c: Context<TEnv>) => Response | Promise<Response>;
|
|
820
|
+
/** Custom error handler. */
|
|
821
|
+
onError?: (err: unknown, c: Context<TEnv>) => Response | Promise<Response>;
|
|
822
|
+
/**
|
|
823
|
+
* Cross-cutting interceptor wrapping every handler call.
|
|
824
|
+
* Ideal for response envelopes, business-error mapping, tracing.
|
|
825
|
+
*
|
|
826
|
+
* Pass a bare {@link RouteInterceptor} function, or an
|
|
827
|
+
* {@link InterceptorConfig} (`{ output?, errors?, handler }`) so the
|
|
828
|
+
* generated OpenAPI spec documents the wrapped responses.
|
|
829
|
+
*/
|
|
830
|
+
interceptor?: InterceptorOption<TEnv>;
|
|
831
|
+
/**
|
|
832
|
+
* Cross-cutting error strategy applied to every uncaught error and injected
|
|
833
|
+
* into every handler / interceptor context. See {@link ErrorHandler}.
|
|
834
|
+
*
|
|
835
|
+
* Typically shared across APIs — pass it once to `createApiRegistry` via
|
|
836
|
+
* `{ services, errorHandler }`; this per-API field overrides it.
|
|
837
|
+
*/
|
|
838
|
+
errorHandler?: ErrorHandler<TEnv>;
|
|
839
|
+
/**
|
|
840
|
+
* Structured {@link Logger} injected into every handler / interceptor /
|
|
841
|
+
* error-handler context. Extend the package's `BaseLogger` to route to your
|
|
842
|
+
* sink. Typically shared via `createApiRegistry({ services, logger })`; this
|
|
843
|
+
* per-API field overrides it.
|
|
844
|
+
*/
|
|
845
|
+
logger?: Logger;
|
|
846
|
+
/**
|
|
847
|
+
* Global DI services container (see {@link createServices}).
|
|
848
|
+
*
|
|
849
|
+
* When provided:
|
|
850
|
+
* - a middleware is installed automatically so the built-in `ctx`
|
|
851
|
+
* service resolves to the current request via `AsyncLocalStorage`;
|
|
852
|
+
* - `services` is passed into every handler and the interceptor.
|
|
853
|
+
*
|
|
854
|
+
* The same container instance should be shared across every API of your
|
|
855
|
+
* project — declare it once and pass it to {@link createApiRegistry}.
|
|
856
|
+
*/
|
|
857
|
+
services?: AnyServicesContainer;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
export { type AnyServicesContainer as A, type BasicAuthOptions as B, type OAuthFlowObject as C, type DecodedBearerToken as D, type ErrorHandler as E, type FirebaseBearerAuthOptions as F, type OAuthFlowsObject as G, type HonoServerOptions as H, type InterceptorConfig as I, type OpenAPIInfo as J, type OpenIdConnectSecurityScheme as K, type Logger as L, type MutualTlsSecurityScheme as M, type RouteInput as N, type OpenAPIConfig as O, type PayloadSource as P, type RouteInterceptor as Q, type RouteDef as R, type ServicesOf as S, type RouteModuleDefault as T, type RouteOutput as U, ValidationError as V, type RoutesUnion as W, type SecurityRequirement as X, type SecurityScheme as Y, type SecuritySchemeBase as Z, type HttpMethod as a, type RouteHandler as b, type AnyRouteDef as c, type ErrorHandlerContext as d, basicAuth as e, firebaseBearerAuth as f, firebaseDocsAuth as g, type FirebaseBearerAuthLike as h, isDocsAuthExtension as i, type FirebaseDocsAuthOptions as j, type DocsAuthExtension as k, type DocsAuthRoute as l, defineRoutes as m, createServices as n, createRequestContextMiddleware as o, type RequestContext as p, type ServiceProvider as q, type ServiceProviderMap as r, type ServicesContainer as s, type ApiKeySecurityScheme as t, type HttpSecurityScheme as u, type InterceptorErrorResponse as v, withRequestContext as w, type InterceptorOption as x, type InterceptorOutput as y, type OAuth2SecurityScheme as z };
|