@hypequery/serve 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/fetch.d.ts +3 -0
- package/dist/adapters/fetch.d.ts.map +1 -0
- package/dist/adapters/fetch.js +26 -0
- package/dist/adapters/node.d.ts +8 -0
- package/dist/adapters/node.d.ts.map +1 -0
- package/dist/adapters/node.js +105 -0
- package/dist/adapters/utils.d.ts +39 -0
- package/dist/adapters/utils.d.ts.map +1 -0
- package/dist/adapters/utils.js +114 -0
- package/dist/adapters/vercel.d.ts +7 -0
- package/dist/adapters/vercel.d.ts.map +1 -0
- package/dist/adapters/vercel.js +13 -0
- package/dist/auth.d.ts +192 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +221 -0
- package/dist/builder.d.ts +3 -0
- package/dist/builder.d.ts.map +1 -0
- package/dist/builder.js +56 -0
- package/dist/client-config.d.ts +44 -0
- package/dist/client-config.d.ts.map +1 -0
- package/dist/client-config.js +53 -0
- package/dist/dev.d.ts +9 -0
- package/dist/dev.d.ts.map +1 -0
- package/dist/dev.js +30 -0
- package/dist/docs-ui.d.ts +3 -0
- package/dist/docs-ui.d.ts.map +1 -0
- package/dist/docs-ui.js +34 -0
- package/dist/endpoint.d.ts +5 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +65 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/openapi.d.ts +3 -0
- package/dist/openapi.d.ts.map +1 -0
- package/dist/openapi.js +205 -0
- package/dist/pipeline.d.ts +77 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +424 -0
- package/dist/query-logger.d.ts +65 -0
- package/dist/query-logger.d.ts.map +1 -0
- package/dist/query-logger.js +91 -0
- package/dist/router.d.ts +13 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +56 -0
- package/dist/server/builder.d.ts +7 -0
- package/dist/server/builder.d.ts.map +1 -0
- package/dist/server/builder.js +73 -0
- package/dist/server/define-serve.d.ts +3 -0
- package/dist/server/define-serve.d.ts.map +1 -0
- package/dist/server/define-serve.js +88 -0
- package/dist/server/execute-query.d.ts +8 -0
- package/dist/server/execute-query.d.ts.map +1 -0
- package/dist/server/execute-query.js +39 -0
- package/dist/server/index.d.ts +6 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +5 -0
- package/dist/server/init-serve.d.ts +8 -0
- package/dist/server/init-serve.d.ts.map +1 -0
- package/dist/server/init-serve.js +18 -0
- package/dist/server/mapper.d.ts +3 -0
- package/dist/server/mapper.d.ts.map +1 -0
- package/dist/server/mapper.js +30 -0
- package/dist/tenant.d.ts +35 -0
- package/dist/tenant.d.ts.map +1 -0
- package/dist/tenant.js +49 -0
- package/dist/type-tests/builder.test-d.d.ts +13 -0
- package/dist/type-tests/builder.test-d.d.ts.map +1 -0
- package/dist/type-tests/builder.test-d.js +20 -0
- package/dist/types.d.ts +514 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +4 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +16 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../src/adapters/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAc,YAAY,EAAgB,MAAM,aAAa,CAAC;AAQxF,eAAO,MAAM,kBAAkB,GAAI,SAAS,YAAY,KAAG,YA4B1D,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { normalizeHeaders, parseQueryParams, parseRequestBody, serializeResponseBody, } from "./utils.js";
|
|
2
|
+
export const createFetchHandler = (handler) => {
|
|
3
|
+
return async (request) => {
|
|
4
|
+
const url = new URL(request.url);
|
|
5
|
+
const headers = normalizeHeaders(request.headers);
|
|
6
|
+
const contentType = headers["content-type"];
|
|
7
|
+
const serveRequest = {
|
|
8
|
+
method: (request.method ?? "GET").toUpperCase(),
|
|
9
|
+
path: url.pathname,
|
|
10
|
+
query: parseQueryParams(url.searchParams),
|
|
11
|
+
headers,
|
|
12
|
+
body: await parseRequestBody(request, contentType),
|
|
13
|
+
raw: request,
|
|
14
|
+
};
|
|
15
|
+
const response = await handler(serveRequest);
|
|
16
|
+
const responseHeaders = {
|
|
17
|
+
"content-type": "application/json; charset=utf-8",
|
|
18
|
+
...response.headers,
|
|
19
|
+
};
|
|
20
|
+
const body = serializeResponseBody(response.body);
|
|
21
|
+
return new Response(body, {
|
|
22
|
+
status: response.status,
|
|
23
|
+
headers: responseHeaders,
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type IncomingMessage, type ServerResponse } from "http";
|
|
2
|
+
import type { ServeHandler, StartServerOptions } from "../types.js";
|
|
3
|
+
export declare const createNodeHandler: (handler: ServeHandler) => (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
4
|
+
export declare const startNodeServer: (handler: ServeHandler, options?: StartServerOptions) => Promise<{
|
|
5
|
+
server: import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
|
|
6
|
+
stop: () => Promise<void>;
|
|
7
|
+
}>;
|
|
8
|
+
//# sourceMappingURL=node.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/adapters/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,MAAM,CAAC;AAG/E,OAAO,KAAK,EAEV,YAAY,EAGZ,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAyErB,eAAO,MAAM,iBAAiB,GAAI,SAAS,YAAY,MACvC,KAAK,eAAe,EAAE,KAAK,cAAc,kBASxD,CAAC;AAEF,eAAO,MAAM,eAAe,GAC1B,SAAS,YAAY,EACrB,UAAS,kBAAuB;;;EA8CjC,CAAC"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createServer } from "http";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { normalizeHeaders, parseQueryParams, parseRequestBody, serializeResponseBody, } from "./utils.js";
|
|
4
|
+
const readRequestBody = async (req) => {
|
|
5
|
+
const chunks = [];
|
|
6
|
+
for await (const chunk of req) {
|
|
7
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
8
|
+
}
|
|
9
|
+
return Buffer.concat(chunks);
|
|
10
|
+
};
|
|
11
|
+
const buildServeRequest = async (req) => {
|
|
12
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
13
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
14
|
+
const bodyBuffer = await readRequestBody(req);
|
|
15
|
+
const headers = normalizeHeaders(req.headers);
|
|
16
|
+
const contentType = headers["content-type"] ?? headers["Content-Type"];
|
|
17
|
+
const body = await parseRequestBody(bodyBuffer, contentType);
|
|
18
|
+
return {
|
|
19
|
+
method,
|
|
20
|
+
path: url.pathname,
|
|
21
|
+
query: parseQueryParams(url.searchParams),
|
|
22
|
+
headers,
|
|
23
|
+
body,
|
|
24
|
+
raw: req,
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const sendResponse = (res, response) => {
|
|
28
|
+
res.statusCode = response.status;
|
|
29
|
+
const headers = response.headers ?? {};
|
|
30
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
31
|
+
if (value !== undefined) {
|
|
32
|
+
res.setHeader(key, value);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (!res.hasHeader("content-type")) {
|
|
36
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
37
|
+
}
|
|
38
|
+
const serialized = serializeResponseBody(response.body);
|
|
39
|
+
res.end(serialized);
|
|
40
|
+
};
|
|
41
|
+
const sendError = (res, error) => {
|
|
42
|
+
const payload = error && typeof error === "object" && "status" in error
|
|
43
|
+
? error
|
|
44
|
+
: {
|
|
45
|
+
status: 500,
|
|
46
|
+
body: {
|
|
47
|
+
error: {
|
|
48
|
+
type: "INTERNAL_SERVER_ERROR",
|
|
49
|
+
message: error instanceof Error ? error.message : "Unexpected error",
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
sendResponse(res, payload);
|
|
54
|
+
};
|
|
55
|
+
export const createNodeHandler = (handler) => {
|
|
56
|
+
return async (req, res) => {
|
|
57
|
+
try {
|
|
58
|
+
const request = await buildServeRequest(req);
|
|
59
|
+
const response = await handler(request);
|
|
60
|
+
sendResponse(res, response);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
sendError(res, error);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
export const startNodeServer = async (handler, options = {}) => {
|
|
68
|
+
const listener = createNodeHandler(handler);
|
|
69
|
+
const server = createServer(listener);
|
|
70
|
+
const port = options.port ?? 3000;
|
|
71
|
+
const hostname = options.hostname ?? "0.0.0.0";
|
|
72
|
+
const onAbort = () => {
|
|
73
|
+
server.close();
|
|
74
|
+
};
|
|
75
|
+
if (options.signal) {
|
|
76
|
+
if (options.signal.aborted) {
|
|
77
|
+
server.close();
|
|
78
|
+
throw new Error("Start signal already aborted");
|
|
79
|
+
}
|
|
80
|
+
options.signal.addEventListener("abort", onAbort, { once: true });
|
|
81
|
+
}
|
|
82
|
+
server.listen(port, hostname);
|
|
83
|
+
await once(server, "listening");
|
|
84
|
+
if (!options.quiet) {
|
|
85
|
+
const address = server.address();
|
|
86
|
+
const display = typeof address === "object" && address
|
|
87
|
+
? `${address.address}:${address.port}`
|
|
88
|
+
: `${hostname}:${port}`;
|
|
89
|
+
console.log(`hypequery serve listening on ${display}`);
|
|
90
|
+
}
|
|
91
|
+
const stop = () => new Promise((resolve, reject) => {
|
|
92
|
+
server.close((err) => {
|
|
93
|
+
if (err) {
|
|
94
|
+
reject(err);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
resolve();
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
return {
|
|
102
|
+
server,
|
|
103
|
+
stop,
|
|
104
|
+
};
|
|
105
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared utilities for HTTP adapters (Node.js, Fetch API, etc.)
|
|
3
|
+
* These functions eliminate code duplication across different adapter implementations.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Normalizes headers from various sources into a consistent format.
|
|
7
|
+
* Handles both Node.js IncomingMessage headers and Web API Headers.
|
|
8
|
+
*
|
|
9
|
+
* @param headers - Headers from Node.js (Record with string | string[]) or Web Headers
|
|
10
|
+
* @returns Normalized headers as Record<string, string | undefined>
|
|
11
|
+
*/
|
|
12
|
+
export declare function normalizeHeaders(headers: Record<string, string | string[] | undefined> | Headers): Record<string, string | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* Parses URL search parameters into a structured query object.
|
|
15
|
+
* Handles multiple values for the same parameter by creating arrays.
|
|
16
|
+
*
|
|
17
|
+
* @param searchParams - URLSearchParams instance
|
|
18
|
+
* @returns Query parameters with support for arrays
|
|
19
|
+
*/
|
|
20
|
+
export declare function parseQueryParams(searchParams: URLSearchParams): Record<string, string | string[] | undefined>;
|
|
21
|
+
/**
|
|
22
|
+
* Parses request body based on content type.
|
|
23
|
+
* Supports Node.js Buffer and Web API Request.
|
|
24
|
+
*
|
|
25
|
+
* @param input - Buffer (Node.js) or Request (Web API)
|
|
26
|
+
* @param contentType - Content-Type header value
|
|
27
|
+
* @returns Parsed body (JSON object, string, ArrayBuffer, or undefined)
|
|
28
|
+
*/
|
|
29
|
+
export declare function parseRequestBody(input: Buffer | Request, contentType?: string): Promise<unknown>;
|
|
30
|
+
/**
|
|
31
|
+
* Serializes response body to string based on content type.
|
|
32
|
+
* Handles JSON serialization and string passthrough.
|
|
33
|
+
*
|
|
34
|
+
* @param body - Response body (any type)
|
|
35
|
+
* @param contentType - Content-Type header value
|
|
36
|
+
* @returns Serialized body as string
|
|
37
|
+
*/
|
|
38
|
+
export declare function serializeResponseBody(body: unknown): string;
|
|
39
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/adapters/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,GAAG,OAAO,GAC/D,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAoBpC;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,YAAY,EAAE,eAAe,GAC5B,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAc/C;AAED;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,MAAM,GAAG,OAAO,EACvB,WAAW,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,OAAO,CAAC,CAuClB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,OAAO,GACZ,MAAM,CAQR"}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared utilities for HTTP adapters (Node.js, Fetch API, etc.)
|
|
3
|
+
* These functions eliminate code duplication across different adapter implementations.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Normalizes headers from various sources into a consistent format.
|
|
7
|
+
* Handles both Node.js IncomingMessage headers and Web API Headers.
|
|
8
|
+
*
|
|
9
|
+
* @param headers - Headers from Node.js (Record with string | string[]) or Web Headers
|
|
10
|
+
* @returns Normalized headers as Record<string, string | undefined>
|
|
11
|
+
*/
|
|
12
|
+
export function normalizeHeaders(headers) {
|
|
13
|
+
const normalized = {};
|
|
14
|
+
if (headers instanceof Headers || (typeof Headers !== 'undefined' && headers instanceof Headers)) {
|
|
15
|
+
// Web API Headers
|
|
16
|
+
headers.forEach((value, key) => {
|
|
17
|
+
normalized[key] = value;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
// Node.js headers (Record<string, string | string[] | undefined>)
|
|
22
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
normalized[key] = value.join(", ");
|
|
25
|
+
}
|
|
26
|
+
else if (typeof value === "string") {
|
|
27
|
+
normalized[key] = value;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return normalized;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Parses URL search parameters into a structured query object.
|
|
35
|
+
* Handles multiple values for the same parameter by creating arrays.
|
|
36
|
+
*
|
|
37
|
+
* @param searchParams - URLSearchParams instance
|
|
38
|
+
* @returns Query parameters with support for arrays
|
|
39
|
+
*/
|
|
40
|
+
export function parseQueryParams(searchParams) {
|
|
41
|
+
const params = {};
|
|
42
|
+
for (const [key, value] of searchParams.entries()) {
|
|
43
|
+
if (params[key] === undefined) {
|
|
44
|
+
params[key] = value;
|
|
45
|
+
}
|
|
46
|
+
else if (Array.isArray(params[key])) {
|
|
47
|
+
params[key].push(value);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
params[key] = [params[key], value];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return params;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Parses request body based on content type.
|
|
57
|
+
* Supports Node.js Buffer and Web API Request.
|
|
58
|
+
*
|
|
59
|
+
* @param input - Buffer (Node.js) or Request (Web API)
|
|
60
|
+
* @param contentType - Content-Type header value
|
|
61
|
+
* @returns Parsed body (JSON object, string, ArrayBuffer, or undefined)
|
|
62
|
+
*/
|
|
63
|
+
export async function parseRequestBody(input, contentType) {
|
|
64
|
+
// Node.js Buffer handling
|
|
65
|
+
if (Buffer.isBuffer(input)) {
|
|
66
|
+
if (!input.length) {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (contentType && contentType.includes("application/json")) {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(input.toString("utf8"));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// If JSON parsing fails, return as string
|
|
75
|
+
return input.toString("utf8");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// Non-JSON content
|
|
79
|
+
return input.length ? input.toString("utf8") : undefined;
|
|
80
|
+
}
|
|
81
|
+
// Web API Request handling
|
|
82
|
+
if (!contentType) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
if (contentType.includes("application/json")) {
|
|
86
|
+
try {
|
|
87
|
+
return await input.json();
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (contentType.includes("text/")) {
|
|
94
|
+
return await input.text();
|
|
95
|
+
}
|
|
96
|
+
// Binary data (images, files, etc.)
|
|
97
|
+
return await input.arrayBuffer();
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Serializes response body to string based on content type.
|
|
101
|
+
* Handles JSON serialization and string passthrough.
|
|
102
|
+
*
|
|
103
|
+
* @param body - Response body (any type)
|
|
104
|
+
* @param contentType - Content-Type header value
|
|
105
|
+
* @returns Serialized body as string
|
|
106
|
+
*/
|
|
107
|
+
export function serializeResponseBody(body) {
|
|
108
|
+
// If already a string, pass through as-is
|
|
109
|
+
if (typeof body === "string") {
|
|
110
|
+
return body;
|
|
111
|
+
}
|
|
112
|
+
// Otherwise, JSON stringify for JSON content-type or default
|
|
113
|
+
return JSON.stringify(body ?? null);
|
|
114
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ServeHandler } from "../types.js";
|
|
2
|
+
type VercelEdgeHandler = (request: Request) => Promise<Response>;
|
|
3
|
+
type VercelNodeHandler = (req: unknown, res: unknown) => Promise<void> | void;
|
|
4
|
+
export declare const createVercelEdgeHandler: (handler: ServeHandler) => VercelEdgeHandler;
|
|
5
|
+
export declare const createVercelNodeHandler: (handler: ServeHandler) => VercelNodeHandler;
|
|
6
|
+
export {};
|
|
7
|
+
//# sourceMappingURL=vercel.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vercel.d.ts","sourceRoot":"","sources":["../../src/adapters/vercel.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,KAAK,iBAAiB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjE,KAAK,iBAAiB,GAAG,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAE9E,eAAO,MAAM,uBAAuB,GAAI,SAAS,YAAY,KAAG,iBAG/D,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAAI,SAAS,YAAY,KAAG,iBAM/D,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createFetchHandler } from "./fetch.js";
|
|
2
|
+
import { createNodeHandler } from "./node.js";
|
|
3
|
+
export const createVercelEdgeHandler = (handler) => {
|
|
4
|
+
const fetchHandler = createFetchHandler(handler);
|
|
5
|
+
return async (request) => fetchHandler(request);
|
|
6
|
+
};
|
|
7
|
+
export const createVercelNodeHandler = (handler) => {
|
|
8
|
+
const nodeHandler = createNodeHandler(handler);
|
|
9
|
+
return async (req, res) => {
|
|
10
|
+
// Vercel's Node runtime passes standard Node req/res objects.
|
|
11
|
+
await nodeHandler(req, res);
|
|
12
|
+
};
|
|
13
|
+
};
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import type { AuthContext, AuthContextWithRoles, AuthContextWithScopes, AuthStrategy, ServeMiddleware, ServeRequest } from "./types.js";
|
|
2
|
+
export interface ApiKeyStrategyOptions<TAuth extends AuthContext = AuthContext> {
|
|
3
|
+
header?: string;
|
|
4
|
+
queryParam?: string;
|
|
5
|
+
validate: (key: string, request: ServeRequest) => Promise<TAuth | null> | TAuth | null;
|
|
6
|
+
}
|
|
7
|
+
export declare const createApiKeyStrategy: <TAuth extends AuthContext = AuthContext>(options: ApiKeyStrategyOptions<TAuth>) => AuthStrategy<TAuth>;
|
|
8
|
+
export interface BearerTokenStrategyOptions<TAuth extends AuthContext = AuthContext> {
|
|
9
|
+
header?: string;
|
|
10
|
+
prefix?: string;
|
|
11
|
+
validate: (token: string, request: ServeRequest) => Promise<TAuth | null> | TAuth | null;
|
|
12
|
+
}
|
|
13
|
+
export declare const createBearerTokenStrategy: <TAuth extends AuthContext = AuthContext>(options: BearerTokenStrategyOptions<TAuth>) => AuthStrategy<TAuth>;
|
|
14
|
+
/**
|
|
15
|
+
* Result of an authorization check.
|
|
16
|
+
* Returns { ok: true } if authorization succeeds, or { ok: false, missing } with details.
|
|
17
|
+
*/
|
|
18
|
+
export type AuthorizationResult = {
|
|
19
|
+
ok: true;
|
|
20
|
+
} | {
|
|
21
|
+
ok: false;
|
|
22
|
+
missing: string[];
|
|
23
|
+
reason: 'MISSING_ROLE' | 'MISSING_SCOPE';
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Check if the authenticated user has at least one of the required roles (OR semantics).
|
|
27
|
+
*
|
|
28
|
+
* @param auth - The auth context from the request
|
|
29
|
+
* @param requiredRoles - Array of role names, any one of which grants access
|
|
30
|
+
* @returns { ok: true } if user has a role, or { ok: false, missing, reason } with details
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* const result = checkRoleAuthorization(auth, ['admin', 'editor']);
|
|
35
|
+
* if (!result.ok) {
|
|
36
|
+
* console.log('Missing roles:', result.missing); // ['admin', 'editor'] (all required)
|
|
37
|
+
* }
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare const checkRoleAuthorization: (auth: AuthContext | null, requiredRoles: string[]) => AuthorizationResult;
|
|
41
|
+
/**
|
|
42
|
+
* Check if the authenticated user has all of the required scopes (AND semantics).
|
|
43
|
+
*
|
|
44
|
+
* @param auth - The auth context from the request
|
|
45
|
+
* @param requiredScopes - Array of scope names, all of which are required
|
|
46
|
+
* @returns { ok: true } if user has all scopes, or { ok: false, missing, reason } with details
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const result = checkScopeAuthorization(auth, ['read:metrics', 'write:metrics']);
|
|
51
|
+
* if (!result.ok) {
|
|
52
|
+
* console.log('Missing scopes:', result.missing); // ['read:metrics', 'write:metrics'] (all required)
|
|
53
|
+
* }
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export declare const checkScopeAuthorization: (auth: AuthContext | null, requiredScopes: string[]) => AuthorizationResult;
|
|
57
|
+
/**
|
|
58
|
+
* Middleware that requires the user to be authenticated.
|
|
59
|
+
* Returns 401 if no auth context is present.
|
|
60
|
+
*
|
|
61
|
+
* @deprecated Use `query.requireAuth()` instead for per-endpoint authentication.
|
|
62
|
+
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
63
|
+
* See: https://hypequery.com/docs/serve/authentication#middleware-helpers
|
|
64
|
+
*
|
|
65
|
+
* Use this as a global middleware via `api.use(requireAuthMiddleware())`.
|
|
66
|
+
* For per-query guards, prefer `query.requireAuth()`.
|
|
67
|
+
*/
|
|
68
|
+
export declare const requireAuthMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>() => ServeMiddleware<any, any, TContext, TAuth>;
|
|
69
|
+
/**
|
|
70
|
+
* Middleware that requires the user to have at least one of the specified roles.
|
|
71
|
+
* Returns 403 if the user lacks the required role.
|
|
72
|
+
*
|
|
73
|
+
* @deprecated Use `query.requireRole(...)` instead for per-endpoint authorization.
|
|
74
|
+
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
75
|
+
* See: https://hypequery.com/docs/serve/authentication#middleware-helpers
|
|
76
|
+
*
|
|
77
|
+
* Use this as a global or per-query middleware via `api.use(requireRoleMiddleware('admin'))`.
|
|
78
|
+
* For per-query guards, prefer `query.requireRole('admin')`.
|
|
79
|
+
*/
|
|
80
|
+
export declare const requireRoleMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>(...roles: string[]) => ServeMiddleware<any, any, TContext, TAuth>;
|
|
81
|
+
/**
|
|
82
|
+
* Middleware that requires the user to have all of the specified scopes.
|
|
83
|
+
* Returns 403 if the user lacks a required scope.
|
|
84
|
+
*
|
|
85
|
+
* @deprecated Use `query.requireScope(...)` instead for per-endpoint authorization.
|
|
86
|
+
* This middleware is kept for complex use cases where guards aren't suitable.
|
|
87
|
+
* See: https://hypequery.com/docs/serve/authentication#middleware-helpers
|
|
88
|
+
*
|
|
89
|
+
* Use this as a global or per-query middleware via `api.use(requireScopeMiddleware('read:metrics'))`.
|
|
90
|
+
* For per-query guards, prefer `query.requireScope('read:metrics')`.
|
|
91
|
+
*/
|
|
92
|
+
export declare const requireScopeMiddleware: <TContext extends Record<string, unknown> = Record<string, unknown>, TAuth extends AuthContext = AuthContext>(...scopes: string[]) => ServeMiddleware<any, any, TContext, TAuth>;
|
|
93
|
+
/**
|
|
94
|
+
* Configuration options for creating a typed auth system.
|
|
95
|
+
* Enables compile-time safety for roles and scopes.
|
|
96
|
+
*/
|
|
97
|
+
export interface CreateAuthSystemOptions<TRoles extends string = string, TScopes extends string = string> {
|
|
98
|
+
/**
|
|
99
|
+
* List of valid roles for your application.
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* roles: ['admin', 'editor', 'viewer'] as const
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
roles?: readonly TRoles[];
|
|
106
|
+
/**
|
|
107
|
+
* List of valid scopes for your application.
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* scopes: ['read:metrics', 'write:metrics', 'delete:metrics'] as const
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
scopes?: readonly TScopes[];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Result type from createAuthSystem.
|
|
117
|
+
* Combines role and scope constraints into a single auth context type.
|
|
118
|
+
*/
|
|
119
|
+
export type TypedAuthContext<TRoles extends string, TScopes extends string> = AuthContextWithRoles<TRoles> & AuthContextWithScopes<TScopes>;
|
|
120
|
+
/**
|
|
121
|
+
* Creates a typed auth system with compile-time role and scope safety.
|
|
122
|
+
*
|
|
123
|
+
* This helper provides:
|
|
124
|
+
* - Type-safe auth context (combines AuthContextWithRoles and AuthContextWithScopes)
|
|
125
|
+
* - A `useAuth` wrapper for auth strategies
|
|
126
|
+
* - Helper to extract the typed auth type
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* import { createAuthSystem, defineServe, query } from '@hypequery/serve';
|
|
131
|
+
*
|
|
132
|
+
* // Define your roles and scopes up front
|
|
133
|
+
* const { useAuth, TypedAuth } = createAuthSystem({
|
|
134
|
+
* roles: ['admin', 'editor', 'viewer'] as const,
|
|
135
|
+
* scopes: ['read:metrics', 'write:metrics', 'delete:metrics'] as const,
|
|
136
|
+
* });
|
|
137
|
+
*
|
|
138
|
+
* // Extract the typed auth type for use with defineServe
|
|
139
|
+
* type AppAuth = TypedAuth;
|
|
140
|
+
*
|
|
141
|
+
* const api = defineServe<AppAuth>({
|
|
142
|
+
* auth: useAuth(jwtStrategy),
|
|
143
|
+
* queries: {
|
|
144
|
+
* adminOnly: query.requireRole('admin').query(async ({ ctx }) => {
|
|
145
|
+
* // ✅ TypeScript autocomplete for 'admin'
|
|
146
|
+
* // ❌ Compile error on typo like 'admn'
|
|
147
|
+
* return { secret: true };
|
|
148
|
+
* }),
|
|
149
|
+
* writeData: query.requireScope('write:metrics').query(async ({ ctx }) => {
|
|
150
|
+
* // ✅ TypeScript autocomplete for 'write:metrics'
|
|
151
|
+
* return { success: true };
|
|
152
|
+
* }),
|
|
153
|
+
* },
|
|
154
|
+
* });
|
|
155
|
+
* ```
|
|
156
|
+
*/
|
|
157
|
+
export declare const createAuthSystem: <TRoles extends string = string, TScopes extends string = string>(options?: CreateAuthSystemOptions<TRoles, TScopes>) => {
|
|
158
|
+
/**
|
|
159
|
+
* Type-safe wrapper for auth strategies.
|
|
160
|
+
* Ensures the strategy returns auth context with the correct role/scope types.
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```ts
|
|
164
|
+
* const jwtStrategy: AuthStrategy<AppAuth> = async ({ request }) => {
|
|
165
|
+
* const token = request.headers.authorization?.slice(7);
|
|
166
|
+
* const payload = await verifyJwt(token);
|
|
167
|
+
* return {
|
|
168
|
+
* userId: payload.sub,
|
|
169
|
+
* roles: payload.roles, // ✅ Type-checked against ['admin', 'editor', 'viewer']
|
|
170
|
+
* scopes: payload.scopes, // ✅ Type-checked against ['read:metrics', 'write:metrics']
|
|
171
|
+
* };
|
|
172
|
+
* };
|
|
173
|
+
*
|
|
174
|
+
* const api = defineServe<AppAuth>({
|
|
175
|
+
* auth: useAuth(jwtStrategy),
|
|
176
|
+
* // ...
|
|
177
|
+
* });
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
useAuth: <TAuth extends AuthContext>(strategy: AuthStrategy<TAuth>) => AuthStrategy<TAuth>;
|
|
181
|
+
/**
|
|
182
|
+
* The combined typed auth context type.
|
|
183
|
+
* Use this to type your defineServe generic parameter.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```ts
|
|
187
|
+
* type AppAuth = typeof TypedAuth;
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
TypedAuth: TypedAuthContext<TRoles, TScopes>;
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"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"}
|