@hypequery/serve 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/package.json +9 -9
  3. package/dist/adapters/fetch.d.ts +0 -3
  4. package/dist/adapters/fetch.d.ts.map +0 -1
  5. package/dist/adapters/fetch.js +0 -26
  6. package/dist/adapters/node.d.ts +0 -8
  7. package/dist/adapters/node.d.ts.map +0 -1
  8. package/dist/adapters/node.js +0 -105
  9. package/dist/adapters/utils.d.ts +0 -39
  10. package/dist/adapters/utils.d.ts.map +0 -1
  11. package/dist/adapters/utils.js +0 -114
  12. package/dist/adapters/vercel.d.ts +0 -7
  13. package/dist/adapters/vercel.d.ts.map +0 -1
  14. package/dist/adapters/vercel.js +0 -13
  15. package/dist/auth.d.ts +0 -14
  16. package/dist/auth.d.ts.map +0 -1
  17. package/dist/auth.js +0 -37
  18. package/dist/builder.d.ts +0 -3
  19. package/dist/builder.d.ts.map +0 -1
  20. package/dist/builder.js +0 -41
  21. package/dist/client-config.d.ts +0 -44
  22. package/dist/client-config.d.ts.map +0 -1
  23. package/dist/client-config.js +0 -53
  24. package/dist/dev.d.ts +0 -9
  25. package/dist/dev.d.ts.map +0 -1
  26. package/dist/dev.js +0 -24
  27. package/dist/docs-ui.d.ts +0 -3
  28. package/dist/docs-ui.d.ts.map +0 -1
  29. package/dist/docs-ui.js +0 -34
  30. package/dist/endpoint.d.ts +0 -5
  31. package/dist/endpoint.d.ts.map +0 -1
  32. package/dist/endpoint.js +0 -59
  33. package/dist/index.d.ts +0 -13
  34. package/dist/index.d.ts.map +0 -1
  35. package/dist/index.js +0 -12
  36. package/dist/openapi.d.ts +0 -3
  37. package/dist/openapi.d.ts.map +0 -1
  38. package/dist/openapi.js +0 -189
  39. package/dist/pipeline.d.ts +0 -72
  40. package/dist/pipeline.d.ts.map +0 -1
  41. package/dist/pipeline.js +0 -317
  42. package/dist/query-logger.d.ts +0 -65
  43. package/dist/query-logger.d.ts.map +0 -1
  44. package/dist/query-logger.js +0 -91
  45. package/dist/router.d.ts +0 -13
  46. package/dist/router.d.ts.map +0 -1
  47. package/dist/router.js +0 -56
  48. package/dist/server.d.ts +0 -9
  49. package/dist/server.d.ts.map +0 -1
  50. package/dist/server.js +0 -191
  51. package/dist/tenant.d.ts +0 -35
  52. package/dist/tenant.d.ts.map +0 -1
  53. package/dist/tenant.js +0 -49
  54. package/dist/type-tests/builder.test-d.d.ts +0 -13
  55. package/dist/type-tests/builder.test-d.d.ts.map +0 -1
  56. package/dist/type-tests/builder.test-d.js +0 -20
  57. package/dist/types.d.ts +0 -373
  58. package/dist/types.d.ts.map +0 -1
  59. package/dist/types.js +0 -1
  60. package/dist/utils.d.ts +0 -4
  61. package/dist/utils.d.ts.map +0 -1
  62. package/dist/utils.js +0 -16
package/dist/pipeline.js DELETED
@@ -1,317 +0,0 @@
1
- import { z } from 'zod';
2
- import { createTenantScope, warnTenantMisconfiguration } from './tenant.js';
3
- import { generateRequestId } from './utils.js';
4
- import { buildOpenApiDocument } from './openapi.js';
5
- import { buildDocsHtml } from './docs-ui.js';
6
- const safeInvokeHook = async (name, hook, payload) => {
7
- if (!hook)
8
- return;
9
- try {
10
- await hook(payload);
11
- }
12
- catch (error) {
13
- console.error(`[hypequery/serve] ${name} hook failed`, error);
14
- }
15
- };
16
- const createErrorResponse = (status, type, message, details) => ({
17
- status,
18
- body: { error: { type, message, ...(details ? { details } : {}) } },
19
- });
20
- const buildContextInput = (request) => {
21
- if (request.body !== undefined && request.body !== null) {
22
- return request.body;
23
- }
24
- if (request.query && Object.keys(request.query).length > 0) {
25
- return request.query;
26
- }
27
- return {};
28
- };
29
- const runMiddlewares = async (middlewares, ctx, handler) => {
30
- let current = handler;
31
- for (let i = middlewares.length - 1; i >= 0; i -= 1) {
32
- const middleware = middlewares[i];
33
- const next = current;
34
- current = () => middleware(ctx, next);
35
- }
36
- return current();
37
- };
38
- const authenticateRequest = async (strategies, request, metadata) => {
39
- for (const strategy of strategies) {
40
- const result = await strategy({ request, endpoint: metadata });
41
- if (result) {
42
- return result;
43
- }
44
- }
45
- return null;
46
- };
47
- const gatherAuthStrategies = (endpointStrategy, globalStrategies) => {
48
- const combined = [];
49
- if (endpointStrategy)
50
- combined.push(endpointStrategy);
51
- combined.push(...globalStrategies);
52
- return combined;
53
- };
54
- const computeRequiresAuth = (metadata, endpointStrategy, globalStrategies) => {
55
- if (typeof metadata.requiresAuth === 'boolean') {
56
- return metadata.requiresAuth;
57
- }
58
- if (endpointStrategy) {
59
- return true;
60
- }
61
- return globalStrategies.length > 0;
62
- };
63
- const validateInput = (schema, payload) => {
64
- if (!schema) {
65
- return { success: true, data: payload };
66
- }
67
- const result = schema.safeParse(payload);
68
- return result.success
69
- ? { success: true, data: result.data }
70
- : { success: false, error: result.error };
71
- };
72
- const cloneContext = (ctx) => (ctx ? { ...ctx } : {});
73
- const resolveContext = async (factory, request, auth) => {
74
- if (!factory) {
75
- return {};
76
- }
77
- if (typeof factory === 'function') {
78
- const value = await factory({ request, auth });
79
- return cloneContext(value);
80
- }
81
- return cloneContext(factory);
82
- };
83
- const resolveRequestId = (request, provided) => provided ?? request.headers['x-request-id'] ?? request.headers['x-trace-id'] ?? generateRequestId();
84
- export const executeEndpoint = async (options) => {
85
- const { endpoint, request, requestId: explicitRequestId, authStrategies, contextFactory, globalMiddlewares, tenantConfig, hooks = {}, additionalContext, } = options;
86
- const requestId = resolveRequestId(request, explicitRequestId);
87
- const locals = {};
88
- let cacheTtlMs = endpoint.cacheTtlMs ?? null;
89
- const setCacheTtl = (ttl) => {
90
- cacheTtlMs = ttl;
91
- };
92
- const context = {
93
- request,
94
- input: buildContextInput(request),
95
- auth: null,
96
- metadata: endpoint.metadata,
97
- locals,
98
- setCacheTtl,
99
- };
100
- const startedAt = Date.now();
101
- await safeInvokeHook('onRequestStart', hooks.onRequestStart, {
102
- requestId,
103
- queryKey: endpoint.key,
104
- metadata: endpoint.metadata,
105
- request,
106
- auth: context.auth,
107
- });
108
- try {
109
- const endpointAuth = endpoint.auth ?? null;
110
- const strategies = gatherAuthStrategies(endpointAuth, authStrategies ?? []);
111
- const requiresAuth = computeRequiresAuth(endpoint.metadata, endpointAuth, authStrategies ?? []);
112
- const metadataWithAuth = {
113
- ...endpoint.metadata,
114
- requiresAuth,
115
- };
116
- context.metadata = metadataWithAuth;
117
- const authContext = await authenticateRequest(strategies, request, metadataWithAuth);
118
- if (!authContext && requiresAuth) {
119
- await safeInvokeHook('onAuthFailure', hooks.onAuthFailure, {
120
- requestId,
121
- queryKey: endpoint.key,
122
- metadata: metadataWithAuth,
123
- request,
124
- auth: context.auth,
125
- reason: 'MISSING',
126
- });
127
- return createErrorResponse(401, 'UNAUTHORIZED', 'Authentication required', {
128
- reason: 'missing_credentials',
129
- strategies_attempted: strategies.length,
130
- endpoint: endpoint.metadata.path,
131
- });
132
- }
133
- context.auth = authContext;
134
- const resolvedContext = await resolveContext(contextFactory, request, authContext);
135
- Object.assign(context, resolvedContext, additionalContext);
136
- const activeTenantConfig = endpoint.tenant ?? tenantConfig;
137
- if (activeTenantConfig) {
138
- const tenantRequired = activeTenantConfig.required !== false;
139
- const tenantId = authContext ? activeTenantConfig.extract(authContext) : null;
140
- if (!tenantId && tenantRequired) {
141
- const errorMessage = activeTenantConfig.errorMessage ??
142
- 'Tenant context is required but could not be determined from authentication';
143
- await safeInvokeHook('onError', hooks.onError, {
144
- requestId,
145
- queryKey: endpoint.key,
146
- metadata: metadataWithAuth,
147
- request,
148
- auth: context.auth,
149
- durationMs: Date.now() - startedAt,
150
- error: new Error(errorMessage),
151
- });
152
- return createErrorResponse(403, 'UNAUTHORIZED', errorMessage, {
153
- reason: 'missing_tenant_context',
154
- tenant_required: true,
155
- });
156
- }
157
- if (tenantId) {
158
- context.tenantId = tenantId;
159
- const mode = activeTenantConfig.mode ?? 'manual';
160
- const column = activeTenantConfig.column;
161
- if (mode === 'auto-inject' && column) {
162
- const contextValues = context;
163
- for (const key of Object.keys(contextValues)) {
164
- const value = contextValues[key];
165
- if (value && typeof value === 'object' && 'table' in value && typeof value.table === 'function') {
166
- contextValues[key] = createTenantScope(value, {
167
- tenantId,
168
- column,
169
- });
170
- }
171
- }
172
- }
173
- else if (mode === 'manual') {
174
- warnTenantMisconfiguration({
175
- queryKey: endpoint.key,
176
- hasTenantConfig: true,
177
- hasTenantId: true,
178
- mode: 'manual',
179
- });
180
- }
181
- }
182
- else if (!tenantRequired) {
183
- warnTenantMisconfiguration({
184
- queryKey: endpoint.key,
185
- hasTenantConfig: true,
186
- hasTenantId: false,
187
- mode: activeTenantConfig.mode,
188
- });
189
- }
190
- }
191
- const validationResult = validateInput(endpoint.inputSchema, context.input);
192
- if (!validationResult.success) {
193
- await safeInvokeHook('onError', hooks.onError, {
194
- requestId,
195
- queryKey: endpoint.key,
196
- metadata: metadataWithAuth,
197
- request,
198
- auth: context.auth,
199
- durationMs: Date.now() - startedAt,
200
- error: validationResult.error,
201
- });
202
- return createErrorResponse(400, 'VALIDATION_ERROR', 'Request validation failed', {
203
- issues: validationResult.error.issues,
204
- });
205
- }
206
- context.input = validationResult.data;
207
- const pipeline = [
208
- ...(globalMiddlewares ?? []),
209
- ...endpoint.middlewares,
210
- ];
211
- const result = await runMiddlewares(pipeline, context, () => endpoint.handler(context));
212
- const headers = { ...(endpoint.defaultHeaders ?? {}) };
213
- if (typeof cacheTtlMs === 'number') {
214
- headers['cache-control'] = cacheTtlMs > 0 ? `public, max-age=${Math.floor(cacheTtlMs / 1000)}` : 'no-store';
215
- }
216
- const durationMs = Date.now() - startedAt;
217
- await safeInvokeHook('onRequestEnd', hooks.onRequestEnd, {
218
- requestId,
219
- queryKey: endpoint.key,
220
- metadata: metadataWithAuth,
221
- request,
222
- auth: context.auth,
223
- durationMs,
224
- result,
225
- });
226
- return {
227
- status: 200,
228
- headers,
229
- body: result,
230
- };
231
- }
232
- catch (error) {
233
- await safeInvokeHook('onError', hooks.onError, {
234
- requestId,
235
- queryKey: endpoint.key,
236
- metadata: context.metadata,
237
- request,
238
- auth: context.auth,
239
- durationMs: Date.now() - startedAt,
240
- error,
241
- });
242
- const message = error instanceof Error ? error.message : 'Unexpected error';
243
- return createErrorResponse(500, 'INTERNAL_SERVER_ERROR', message);
244
- }
245
- };
246
- export const createServeHandler = ({ router, globalMiddlewares, authStrategies, tenantConfig, contextFactory, hooks, }) => {
247
- return async (request) => {
248
- const endpoint = router.match(request.method, request.path);
249
- if (!endpoint) {
250
- return createErrorResponse(404, 'NOT_FOUND', `No endpoint registered for ${request.method} ${request.path}`);
251
- }
252
- return executeEndpoint({
253
- endpoint,
254
- request,
255
- authStrategies,
256
- contextFactory,
257
- globalMiddlewares,
258
- tenantConfig,
259
- hooks,
260
- });
261
- };
262
- };
263
- export const createOpenApiEndpoint = (path, getEndpoints, options) => {
264
- let cachedDocument = null;
265
- return {
266
- key: '__hypequery_openapi__',
267
- method: 'GET',
268
- inputSchema: undefined,
269
- outputSchema: z.any(),
270
- handler: async () => {
271
- if (!cachedDocument) {
272
- cachedDocument = buildOpenApiDocument(getEndpoints(), options);
273
- }
274
- return cachedDocument;
275
- },
276
- query: undefined,
277
- middlewares: [],
278
- auth: null,
279
- metadata: {
280
- path,
281
- method: 'GET',
282
- name: 'OpenAPI schema',
283
- summary: 'OpenAPI schema',
284
- description: 'Generated OpenAPI specification for the registered endpoints',
285
- tags: ['docs'],
286
- requiresAuth: false,
287
- deprecated: false,
288
- visibility: 'internal',
289
- },
290
- cacheTtlMs: null,
291
- };
292
- };
293
- export const createDocsEndpoint = (path, openapiPath, options) => ({
294
- key: '__hypequery_docs__',
295
- method: 'GET',
296
- inputSchema: undefined,
297
- outputSchema: z.string(),
298
- handler: async () => buildDocsHtml(openapiPath, options),
299
- query: undefined,
300
- middlewares: [],
301
- auth: null,
302
- metadata: {
303
- path,
304
- method: 'GET',
305
- name: 'Docs',
306
- summary: 'API documentation',
307
- description: 'Auto-generated documentation for your hypequery endpoints',
308
- tags: ['docs'],
309
- requiresAuth: false,
310
- deprecated: false,
311
- visibility: 'internal',
312
- },
313
- cacheTtlMs: null,
314
- defaultHeaders: {
315
- 'content-type': 'text/html; charset=utf-8',
316
- },
317
- });
@@ -1,65 +0,0 @@
1
- /**
2
- * Backend-agnostic query event logger for the serve layer.
3
- *
4
- * Fires for every endpoint execution regardless of the underlying
5
- * query backend (ClickHouse, BigQuery, mock data, etc.).
6
- */
7
- /**
8
- * Event emitted by the serve-layer query logger.
9
- */
10
- export interface ServeQueryEvent {
11
- requestId: string;
12
- endpointKey: string;
13
- path: string;
14
- method: string;
15
- status: 'started' | 'completed' | 'error';
16
- startTime: number;
17
- endTime?: number;
18
- durationMs?: number;
19
- input?: unknown;
20
- responseStatus?: number;
21
- error?: Error;
22
- result?: unknown;
23
- }
24
- /**
25
- * Callback for serve query events.
26
- */
27
- export type ServeQueryEventCallback = (event: ServeQueryEvent) => void;
28
- /**
29
- * Serve-layer query event emitter.
30
- *
31
- * Created per `defineServe()` call — not a singleton.
32
- * Emits events at the request lifecycle level so that dev tools,
33
- * logging, and analytics work with any query backend.
34
- */
35
- export declare class ServeQueryLogger {
36
- private listeners;
37
- /**
38
- * Subscribe to query events.
39
- * @returns Unsubscribe function.
40
- */
41
- on(callback: ServeQueryEventCallback): () => void;
42
- /**
43
- * Emit a query event to all listeners.
44
- */
45
- emit(event: ServeQueryEvent): void;
46
- /**
47
- * Number of active listeners.
48
- */
49
- get listenerCount(): number;
50
- /**
51
- * Remove all listeners.
52
- */
53
- removeAll(): void;
54
- }
55
- /**
56
- * Format a query event as a human-readable log line.
57
- * Returns null for 'started' events (only logs completions).
58
- */
59
- export declare function formatQueryEvent(event: ServeQueryEvent): string | null;
60
- /**
61
- * Format a query event as a structured JSON string for log aggregators.
62
- * Returns null for 'started' events (only logs completions).
63
- */
64
- export declare function formatQueryEventJSON(event: ServeQueryEvent): string | null;
65
- //# sourceMappingURL=query-logger.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-logger.d.ts","sourceRoot":"","sources":["../src/query-logger.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,SAAS,GAAG,WAAW,GAAG,OAAO,CAAC;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,CAAC;AAEvE;;;;;;GAMG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,SAAS,CAAsC;IAEvD;;;OAGG;IACH,EAAE,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,IAAI;IAOjD;;OAEG;IACH,IAAI,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI;IAUlC;;OAEG;IACH,IAAI,aAAa,IAAI,MAAM,CAE1B;IAED;;OAEG;IACH,SAAS,IAAI,IAAI;CAGlB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,GAAG,IAAI,CAYtE;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,GAAG,IAAI,CAiB1E"}
@@ -1,91 +0,0 @@
1
- /**
2
- * Backend-agnostic query event logger for the serve layer.
3
- *
4
- * Fires for every endpoint execution regardless of the underlying
5
- * query backend (ClickHouse, BigQuery, mock data, etc.).
6
- */
7
- /**
8
- * Serve-layer query event emitter.
9
- *
10
- * Created per `defineServe()` call — not a singleton.
11
- * Emits events at the request lifecycle level so that dev tools,
12
- * logging, and analytics work with any query backend.
13
- */
14
- export class ServeQueryLogger {
15
- constructor() {
16
- this.listeners = new Set();
17
- }
18
- /**
19
- * Subscribe to query events.
20
- * @returns Unsubscribe function.
21
- */
22
- on(callback) {
23
- this.listeners.add(callback);
24
- return () => {
25
- this.listeners.delete(callback);
26
- };
27
- }
28
- /**
29
- * Emit a query event to all listeners.
30
- */
31
- emit(event) {
32
- for (const listener of this.listeners) {
33
- try {
34
- listener(event);
35
- }
36
- catch {
37
- // Ignore listener errors
38
- }
39
- }
40
- }
41
- /**
42
- * Number of active listeners.
43
- */
44
- get listenerCount() {
45
- return this.listeners.size;
46
- }
47
- /**
48
- * Remove all listeners.
49
- */
50
- removeAll() {
51
- this.listeners.clear();
52
- }
53
- }
54
- /**
55
- * Format a query event as a human-readable log line.
56
- * Returns null for 'started' events (only logs completions).
57
- */
58
- export function formatQueryEvent(event) {
59
- if (event.status === 'started')
60
- return null;
61
- const status = event.status === 'completed' ? '✓' : '✗';
62
- const duration = event.durationMs != null ? `${event.durationMs}ms` : '?';
63
- const code = event.responseStatus ?? (event.status === 'error' ? 500 : 200);
64
- let line = ` ${status} ${event.method} ${event.path} → ${code} (${duration})`;
65
- if (event.status === 'error' && event.error) {
66
- line += ` — ${event.error.message}`;
67
- }
68
- return line;
69
- }
70
- /**
71
- * Format a query event as a structured JSON string for log aggregators.
72
- * Returns null for 'started' events (only logs completions).
73
- */
74
- export function formatQueryEventJSON(event) {
75
- if (event.status === 'started')
76
- return null;
77
- return JSON.stringify({
78
- level: event.status === 'error' ? 'error' : 'info',
79
- msg: `${event.method} ${event.path}`,
80
- requestId: event.requestId,
81
- endpoint: event.endpointKey,
82
- path: event.path,
83
- method: event.method,
84
- status: event.responseStatus ?? (event.status === 'error' ? 500 : 200),
85
- durationMs: event.durationMs,
86
- ...(event.status === 'error' && event.error
87
- ? { error: event.error.message }
88
- : {}),
89
- timestamp: new Date(event.endTime ?? event.startTime).toISOString(),
90
- });
91
- }
package/dist/router.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import type { EndpointRegistry, HttpMethod, ServeEndpoint } from "./types.js";
2
- export declare const normalizeRoutePath: (path: string) => string;
3
- export declare const applyBasePath: (basePath: string, path: string) => string;
4
- export declare class ServeRouter implements EndpointRegistry {
5
- private readonly basePath;
6
- private routes;
7
- constructor(basePath?: string);
8
- list(): ServeEndpoint<any, any, any, any, any>[];
9
- register(endpoint: ServeEndpoint<any, any, any, any>): void;
10
- match(method: HttpMethod, path: string): ServeEndpoint<any, any, any, any, any> | null;
11
- markRoutesRequireAuth(): void;
12
- }
13
- //# sourceMappingURL=router.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAI9E,eAAO,MAAM,kBAAkB,GAAI,MAAM,MAAM,WAG9C,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,UAAU,MAAM,EAAE,MAAM,MAAM,WAM3D,CAAC;AAEF,qBAAa,WAAY,YAAW,gBAAgB;IAGtC,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAFrC,OAAO,CAAC,MAAM,CAA2C;gBAE5B,QAAQ,SAAK;IAE1C,IAAI;IAIJ,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAuBpD,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM;IAStC,qBAAqB;CAetB"}
package/dist/router.js DELETED
@@ -1,56 +0,0 @@
1
- const trimSlashes = (value) => value.replace(/^\/+|\/+$/g, "");
2
- export const normalizeRoutePath = (path) => {
3
- const trimmed = trimSlashes(path || "/");
4
- return `/${trimmed}`.replace(/\/+/g, "/").replace(/\/$/, trimmed ? "" : "/");
5
- };
6
- export const applyBasePath = (basePath, path) => {
7
- const parts = [trimSlashes(basePath ?? ""), trimSlashes(path)]
8
- .filter(Boolean)
9
- .join("/");
10
- const combined = parts ? `/${parts}` : "/";
11
- return combined.replace(/\/+/g, "/").replace(/\/$/, combined === "/" ? "/" : "");
12
- };
13
- export class ServeRouter {
14
- constructor(basePath = "") {
15
- this.basePath = basePath;
16
- this.routes = [];
17
- }
18
- list() {
19
- return [...this.routes];
20
- }
21
- register(endpoint) {
22
- const path = endpoint.metadata.path || "/";
23
- const normalizedPath = applyBasePath(this.basePath, path);
24
- const method = endpoint.method;
25
- const existing = this.routes.find((route) => route.metadata.path === normalizedPath && route.method === method);
26
- if (existing) {
27
- throw new Error(`Route already registered for ${method} ${normalizedPath}`);
28
- }
29
- this.routes.push({
30
- ...endpoint,
31
- metadata: {
32
- ...endpoint.metadata,
33
- path: normalizedPath,
34
- method,
35
- },
36
- });
37
- }
38
- match(method, path) {
39
- const normalizedPath = normalizeRoutePath(path);
40
- return (this.routes.find((route) => route.method === method && route.metadata.path === normalizedPath) ?? null);
41
- }
42
- markRoutesRequireAuth() {
43
- this.routes = this.routes.map((route) => {
44
- if (route.metadata.requiresAuth === false) {
45
- return route;
46
- }
47
- return {
48
- ...route,
49
- metadata: {
50
- ...route.metadata,
51
- requiresAuth: true,
52
- },
53
- };
54
- });
55
- }
56
- }
package/dist/server.d.ts DELETED
@@ -1,9 +0,0 @@
1
- import type { AuthContext, ServeBuilder, ServeConfig, ServeContextFactory, ServeEndpointMap, ServeInitializer, ServeQueriesMap } from "./types.js";
2
- export declare const defineServe: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext, const TQueries extends ServeQueriesMap<TContext, TAuth> = ServeQueriesMap<TContext, TAuth>>(config: ServeConfig<TContext, TAuth, TQueries>) => ServeBuilder<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>;
3
- type InferInitializerContext<TFactory, TAuth extends AuthContext> = TFactory extends ServeContextFactory<infer TContext, TAuth> ? TContext : never;
4
- type ServeInitializerOptions<TFactory extends ServeContextFactory<any, TAuth>, TAuth extends AuthContext> = Omit<ServeConfig<InferInitializerContext<TFactory, TAuth>, TAuth, ServeQueriesMap<InferInitializerContext<TFactory, TAuth>, TAuth>>, "queries" | "context"> & {
5
- context: TFactory;
6
- };
7
- export declare const initServe: <TFactory extends ServeContextFactory<any, TAuth>, TAuth extends AuthContext = AuthContext>(options: ServeInitializerOptions<TFactory, TAuth>) => ServeInitializer<InferInitializerContext<TFactory, TAuth>, TAuth>;
8
- export {};
9
- //# sourceMappingURL=server.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EACV,WAAW,EAIX,YAAY,EACZ,WAAW,EACX,mBAAmB,EAEnB,gBAAgB,EAEhB,gBAAgB,EAIhB,eAAe,EAMhB,MAAM,YAAY,CAAC;AAWpB,eAAO,MAAM,WAAW,GACtB,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,KAAK,SAAS,WAAW,GAAG,WAAW,EACvC,KAAK,CAAC,QAAQ,SAAS,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,EAE1F,QAAQ,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,CAAC,KAC7C,YAAY,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,QAAQ,EAAE,KAAK,CAgL3E,CAAC;AA8BF,KAAK,uBAAuB,CAC1B,QAAQ,EACR,KAAK,SAAS,WAAW,IACvB,QAAQ,SAAS,mBAAmB,CAAC,MAAM,QAAQ,EAAE,KAAK,CAAC,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEnF,KAAK,uBAAuB,CAC1B,QAAQ,SAAS,mBAAmB,CAAC,GAAG,EAAE,KAAK,CAAC,EAChD,KAAK,SAAS,WAAW,IACvB,IAAI,CACN,WAAW,CACT,uBAAuB,CAAC,QAAQ,EAAE,KAAK,CAAC,EACxC,KAAK,EACL,eAAe,CAAC,uBAAuB,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,CACjE,EACD,SAAS,GAAG,SAAS,CACtB,GAAG;IAAE,OAAO,EAAE,QAAQ,CAAA;CAAE,CAAC;AAQ1B,eAAO,MAAM,SAAS,GACpB,QAAQ,SAAS,mBAAmB,CAAC,GAAG,EAAE,KAAK,CAAC,EAChD,KAAK,SAAS,WAAW,GAAG,WAAW,EACvC,SAAS,uBAAuB,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAG,gBAAgB,CACpE,uBAAuB,CAAC,QAAQ,EAAE,KAAK,CAAC,EACxC,KAAK,CAsBN,CAAC"}