@ultimabase/http 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +4 -2
  3. package/dist/address.d.ts +9 -0
  4. package/dist/address.d.ts.map +1 -0
  5. package/dist/address.js +63 -0
  6. package/dist/app.d.ts +43 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/app.js +200 -0
  9. package/dist/client.d.ts +9 -0
  10. package/dist/client.d.ts.map +1 -0
  11. package/dist/client.js +31 -0
  12. package/dist/index.d.ts +39 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +89 -0
  15. package/dist/internal.d.ts +5 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +2 -0
  18. package/dist/pages.d.ts +60 -0
  19. package/dist/pages.d.ts.map +1 -0
  20. package/dist/pages.js +124 -0
  21. package/dist/request.d.ts +5 -0
  22. package/dist/request.d.ts.map +1 -0
  23. package/dist/request.js +26 -0
  24. package/dist/server.d.ts +15 -0
  25. package/dist/server.d.ts.map +1 -0
  26. package/dist/server.js +73 -0
  27. package/dist/transport.d.ts +32 -0
  28. package/dist/transport.d.ts.map +1 -0
  29. package/dist/transport.js +55 -0
  30. package/dist/upgrade.d.ts +25 -0
  31. package/dist/upgrade.d.ts.map +1 -0
  32. package/dist/upgrade.js +63 -0
  33. package/dist/validate.d.ts +44 -0
  34. package/dist/validate.d.ts.map +1 -0
  35. package/dist/validate.js +36 -0
  36. package/package.json +44 -3
  37. package/src/address.ts +74 -0
  38. package/src/app.ts +263 -0
  39. package/src/client.ts +38 -0
  40. package/src/index.ts +133 -0
  41. package/src/internal.ts +29 -0
  42. package/src/pages.ts +200 -0
  43. package/src/request.ts +40 -0
  44. package/src/server.ts +90 -0
  45. package/src/transport.ts +84 -0
  46. package/src/upgrade.ts +105 -0
  47. package/src/validate.ts +96 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # @ultimabase/http
2
+
3
+ ## 0.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0e885c4: The first release: the kernel, its adapters, transports and plugins, the testing helpers and the starter.
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [0e885c4]
12
+ - ultimabase@0.1.0
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @ultimabase/http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The HTTP server of an UltimaBase application. GraphQL, REST, auth and files mount their routes on it, and the application adds its own with Hono; each route reads its caller and acts as it.
4
+
5
+ Documentation: [HTTP](https://ultimabase.dev/docs/http).
@@ -0,0 +1,9 @@
1
+ import type { Logger } from 'ultimabase';
2
+ /** The `proxies` option, a whole number; 0 by default. */
3
+ export declare function proxiesOf(option: number | undefined): number;
4
+ /**
5
+ * Reads the address of the Node connection a request's `env` holds, `''`
6
+ * without one, or the one `proxies` proxies forwarded.
7
+ */
8
+ export declare function addresses(proxies: number, logger: Logger): (env: unknown) => string;
9
+ //# sourceMappingURL=address.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../src/address.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAyBxC,0DAA0D;AAC1D,wBAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAM5D;AAED;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACZ,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CA4B1B"}
@@ -0,0 +1,63 @@
1
+ // A client's address (D-113, D-116): the connection's, or the one the
2
+ // proxies in front of the server forwarded.
3
+ import { IncomingMessage } from 'node:http';
4
+ import { BlockList, isIP } from 'node:net';
5
+ import { Refused } from 'ultimabase';
6
+ // Where a proxy in front of the server connects from.
7
+ const nearby = new BlockList();
8
+ for (const [network, prefix] of [
9
+ ['127.0.0.0', 8],
10
+ ['10.0.0.0', 8],
11
+ ['172.16.0.0', 12],
12
+ ['192.168.0.0', 16],
13
+ ['100.64.0.0', 10],
14
+ ]) {
15
+ nearby.addSubnet(network, prefix, 'ipv4');
16
+ }
17
+ for (const [network, prefix] of [
18
+ ['::1', 128],
19
+ ['fc00::', 7],
20
+ ['fe80::', 10],
21
+ ]) {
22
+ nearby.addSubnet(network, prefix, 'ipv6');
23
+ }
24
+ const isNearby = (address) => nearby.check(address, isIP(address) === 4 ? 'ipv4' : 'ipv6');
25
+ /** The `proxies` option, a whole number; 0 by default. */
26
+ export function proxiesOf(option) {
27
+ const proxies = option ?? 0;
28
+ if (Number.isInteger(proxies) && proxies >= 0)
29
+ return proxies;
30
+ throw new Refused(`proxies is ${proxies}, not a whole number of proxies in front of the server.`);
31
+ }
32
+ /**
33
+ * Reads the address of the Node connection a request's `env` holds, `''`
34
+ * without one, or the one `proxies` proxies forwarded.
35
+ */
36
+ export function addresses(proxies, logger) {
37
+ let warned = false;
38
+ return (env) => {
39
+ const incoming = typeof env === 'object' && env !== null
40
+ ? Reflect.get(env, 'incoming')
41
+ : undefined;
42
+ if (!(incoming instanceof IncomingMessage))
43
+ return '';
44
+ const connection = incoming.socket.remoteAddress ?? '';
45
+ const forwarded = incoming.headersDistinct['x-forwarded-for'];
46
+ if (forwarded === undefined)
47
+ return connection;
48
+ if (proxies === 0) {
49
+ if (!warned && isNearby(connection)) {
50
+ warned = true;
51
+ logger.warn(`A request came through a proxy (X-Forwarded-For) but httpPlugin({ proxies }) is not set: every client counts as ${connection}. Set it to the number of proxies in front of the server.`);
52
+ }
53
+ return connection;
54
+ }
55
+ // Each proxy appended the address it saw: the client's is n from the
56
+ // right. With fewer, the client went around a proxy and wrote them.
57
+ const entries = forwarded
58
+ .flatMap((header) => header.split(','))
59
+ .map((entry) => entry.trim());
60
+ const entry = entries.at(-proxies) ?? '';
61
+ return entries.length < proxies || isIP(entry) === 0 ? connection : entry;
62
+ };
63
+ }
package/dist/app.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { Hono } from 'hono';
2
+ import type { Caller, Logger } from 'ultimabase';
3
+ /**
4
+ * What a route's context holds: `c.var.caller` (D-106) and `c.var.address`,
5
+ * the client's, `''` when unknown (D-113, D-116).
6
+ */
7
+ export type HttpEnv = {
8
+ Variables: {
9
+ caller: Caller;
10
+ address: string;
11
+ };
12
+ };
13
+ /** Routes the application writes, read by `httpPlugin({ routes })`. */
14
+ export type Routes = Hono<HttpEnv>;
15
+ /** Routes a plugin mounted; `bodyLimit: false` when they read their own body (D-153). */
16
+ export interface Mounted {
17
+ readonly routes: Routes;
18
+ readonly bodyLimit: boolean;
19
+ }
20
+ /** What `httpPlugin` takes (D-66, D-106). */
21
+ export interface HttpOptions {
22
+ /** Mounted at the root, in their order. */
23
+ readonly routes?: readonly Routes[];
24
+ /** The origins a browser may call from; local ones outside production. */
25
+ readonly cors?: readonly string[];
26
+ /** Then `PORT`, then 3000. */
27
+ readonly port?: number;
28
+ /** In bytes; 1 MB by default. */
29
+ readonly bodyLimit?: number;
30
+ /** In front of the server, which then reads the client's address from `X-Forwarded-For`; 0 by default (D-116). */
31
+ readonly proxies?: number;
32
+ }
33
+ /**
34
+ * Whether a browser may call from `origin`, with its cookies: a listed one,
35
+ * or a local one outside production. Reads `NODE_ENV` once.
36
+ */
37
+ export declare function allowing(options: HttpOptions): (origin: string) => boolean;
38
+ /**
39
+ * Reads `NODE_ENV` once, when the application starts. The application's
40
+ * routes come before those plugins mounted (D-107).
41
+ */
42
+ export declare function appOf(options: HttpOptions, mounted: readonly Mounted[], identify: (request: Request) => Promise<Caller>, logger: Logger): Hono<HttpEnv>;
43
+ //# sourceMappingURL=app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings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 +1,200 @@
1
+ // The Hono application `httpPlugin` serves (D-66, D-106): no caching, CORS,
2
+ // forms from other origins, the body limit, each request's caller, the
3
+ // routes, and errors as D-72 sends them.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { STATUS_CODES } from 'node:http';
6
+ import { Hono } from 'hono';
7
+ import { bodyLimit } from 'hono/body-limit';
8
+ import { cors } from 'hono/cors';
9
+ import { HTTPException } from 'hono/http-exception';
10
+ import { getPath } from 'hono/utils/url';
11
+ import { isLocalHost, PublicError } from 'ultimabase';
12
+ import { addresses, proxiesOf } from './address.js';
13
+ import { hold } from './request.js';
14
+ const statuses = new Map([
15
+ ['ACCESS_DENIED', 403],
16
+ ['NOT_FOUND', 404],
17
+ ['VALIDATION_FAILED', 400],
18
+ ['UNIQUE_VIOLATION', 409],
19
+ ['RELATION_RESTRICTED', 409],
20
+ ['UNAUTHENTICATED', 401],
21
+ ['INVALID_CREDENTIALS', 401],
22
+ ['TOO_MANY_ATTEMPTS', 429],
23
+ ['INTERNAL', 500],
24
+ ]);
25
+ /** Hono's way to refuse a request, with its status (D-108). */
26
+ function refused(error, c) {
27
+ if (error.res !== undefined)
28
+ return error.getResponse();
29
+ const name = STATUS_CODES[error.status];
30
+ const code = name === undefined
31
+ ? `HTTP_${error.status}`
32
+ : name.toUpperCase().replaceAll(/[^A-Z0-9]+/g, '_');
33
+ const message = error.message === '' ? (name ?? code) : error.message;
34
+ return c.json({ code, message }, error.status);
35
+ }
36
+ /** A `PublicError` as is; any other error masked, logged with its id. */
37
+ function failed(error, c, logger) {
38
+ // The client left: its request failed, not the server (499, as nginx).
39
+ if (c.req.raw.signal.aborted)
40
+ return new Response(null, { status: 499 });
41
+ if (error instanceof HTTPException)
42
+ return refused(error, c);
43
+ if (error instanceof PublicError) {
44
+ const { code, message, details } = error;
45
+ // An application's own code is a client error (D-72).
46
+ const status = statuses.get(code) ?? 400;
47
+ // Its details say when to retry, in seconds (D-113).
48
+ if (code === 'TOO_MANY_ATTEMPTS' &&
49
+ typeof details === 'object' &&
50
+ details !== null) {
51
+ const wait = Reflect.get(details, 'retryAfter');
52
+ if (typeof wait === 'number')
53
+ c.header('retry-after', String(wait));
54
+ }
55
+ return details === undefined
56
+ ? c.json({ code, message }, status)
57
+ : c.json({ code, message, details }, status);
58
+ }
59
+ const correlationId = randomUUID();
60
+ logger.error({ correlationId, err: error }, 'A request failed.');
61
+ return c.json({ code: 'INTERNAL', message: 'Internal error.', correlationId }, 500);
62
+ }
63
+ /** A local host over `http:`, on any port. */
64
+ function isLocal(origin) {
65
+ if (!URL.canParse(origin))
66
+ return false;
67
+ const { protocol, hostname } = new URL(origin);
68
+ return protocol === 'http:' && isLocalHost(hostname);
69
+ }
70
+ /**
71
+ * Whether a browser may call from `origin`, with its cookies: a listed one,
72
+ * or a local one outside production. Reads `NODE_ENV` once.
73
+ */
74
+ export function allowing(options) {
75
+ const listed = options.cors ?? [];
76
+ const local = process.env['NODE_ENV'] !== 'production';
77
+ return (origin) => listed.includes(origin) || (local && isLocal(origin));
78
+ }
79
+ const safe = new Set(['GET', 'HEAD', 'OPTIONS']);
80
+ /** What an HTML form sends, `text/plain` when it names none. */
81
+ const form = /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i;
82
+ /**
83
+ * Hono's path, with control characters left encoded: a route never matches
84
+ * one, and the development log cannot print one (D-108).
85
+ */
86
+ const pathOf = (request) => getPath(request).replaceAll(/[\p{Cc}\u2028\u2029]/gu, (char) => encodeURIComponent(char));
87
+ /**
88
+ * Reads `NODE_ENV` once, when the application starts. The application's
89
+ * routes come before those plugins mounted (D-107).
90
+ */
91
+ export function appOf(options, mounted, identify, logger) {
92
+ const local = process.env['NODE_ENV'] !== 'production';
93
+ const allows = allowing(options);
94
+ const maxSize = options.bodyLimit ?? 1024 * 1024;
95
+ const addressOf = addresses(proxiesOf(options.proxies), logger);
96
+ const app = new Hono({ getPath: pathOf });
97
+ // A response may hold the caller's data: no cache keeps one, errors
98
+ // included, unless its route says otherwise (D-106).
99
+ app.use(async (c, next) => {
100
+ await next();
101
+ if (!c.res.headers.has('cache-control'))
102
+ c.header('cache-control', 'no-store');
103
+ });
104
+ // Each request once answered, outside production (D-108).
105
+ if (local) {
106
+ app.use(async (c, next) => {
107
+ const began = performance.now();
108
+ await next();
109
+ const ms = Math.round(performance.now() - began);
110
+ logger.info(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);
111
+ });
112
+ }
113
+ // Hono's `onError` receives only an `Error`; any other value thrown ends
114
+ // here, answered as one.
115
+ app.use(async (c, next) => {
116
+ try {
117
+ await next();
118
+ }
119
+ catch (error) {
120
+ c.res = failed(error, c, logger);
121
+ }
122
+ });
123
+ const allowed = (origin) => (allows(origin) ? origin : null);
124
+ // An allowed origin sends its cookies, as auth's session (D-112).
125
+ const preflight = cors({ origin: allowed, credentials: true });
126
+ app.use(async (c, next) => {
127
+ // Hono's `cors` answers every OPTIONS: a route's own runs, unless the
128
+ // request is a preflight.
129
+ const asked = c.req.header('access-control-request-method');
130
+ if (c.req.method !== 'OPTIONS' || asked !== undefined) {
131
+ return preflight(c, next);
132
+ }
133
+ await next();
134
+ const origin = allowed(c.req.header('origin') ?? '');
135
+ if (origin !== null) {
136
+ c.header('access-control-allow-origin', origin);
137
+ c.header('access-control-allow-credentials', 'true');
138
+ }
139
+ c.header('vary', 'Origin', { append: true });
140
+ });
141
+ // A browser sends a form to any site, with that site's cookies, and no
142
+ // CORS check stops it: a form from a browser, which names its origin or
143
+ // its site, or with cookies, comes from an allowed origin (D-106). Without
144
+ // cookies, another site's form would sign its visitor in to its own
145
+ // account. A webhook sends neither header, nor cookies.
146
+ app.use(async (c, next) => {
147
+ const origin = c.req.header('origin');
148
+ const site = c.req.header('sec-fetch-site');
149
+ if (!safe.has(c.req.method) &&
150
+ form.test(c.req.header('content-type') ?? 'text/plain') &&
151
+ (c.req.header('cookie') !== undefined ||
152
+ origin !== undefined ||
153
+ site !== undefined) &&
154
+ site !== 'same-origin' &&
155
+ origin !== new URL(c.req.url).origin &&
156
+ allowed(origin ?? '') === null) {
157
+ throw new PublicError('ACCESS_DENIED', 'A form from another origin is refused.');
158
+ }
159
+ await next();
160
+ });
161
+ const limit = bodyLimit({
162
+ maxSize,
163
+ onError: (c) => c.json({
164
+ code: 'PAYLOAD_TOO_LARGE',
165
+ message: `The body is over ${maxSize} bytes.`,
166
+ }, 413),
167
+ });
168
+ // The routes of the mounts that read their own body, by method: their
169
+ // `use` and `all` match any request, so they never lift the limit (D-153).
170
+ const unlimited = new Hono();
171
+ for (const mount of mounted.filter((each) => !each.bodyLimit)) {
172
+ for (const { method, path } of mount.routes.routes) {
173
+ if (method !== 'ALL')
174
+ unlimited.on(method, path, (c) => c.body(null));
175
+ }
176
+ }
177
+ app.use(async (c, next) => {
178
+ const [matched] = unlimited.router.match(c.req.method, c.req.path);
179
+ if (matched.length > 0)
180
+ await next();
181
+ else
182
+ return limit(c, next);
183
+ });
184
+ app.use(async (c, next) => {
185
+ hold(c, await identify(c.req.raw), addressOf(c.env));
186
+ await next();
187
+ });
188
+ for (const routes of [
189
+ ...(options.routes ?? []),
190
+ ...mounted.map((mount) => mount.routes),
191
+ ]) {
192
+ app.route('/', routes);
193
+ }
194
+ app.notFound((c) => c.json({
195
+ code: 'NOT_FOUND',
196
+ message: `No route matches ${c.req.method} ${c.req.path}.`,
197
+ }, 404));
198
+ app.onError((error, c) => failed(error, c, logger));
199
+ return app;
200
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context } from 'hono';
2
+ import type { Client } from 'ultimabase';
3
+ import type { HttpEnv } from './app.ts';
4
+ /** The client of `c`'s request, and `sent`, which adds its cookies. */
5
+ export declare function clientOf(c: Context<HttpEnv>): {
6
+ readonly client: Client;
7
+ readonly sent: (response: Response) => Response;
8
+ };
9
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAEnC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,UAAU,CAAA;AAEvC,uEAAuE;AACvE,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG;IAC9C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,QAAQ,CAAA;CAC/C,CA0BA"}
package/dist/client.js ADDED
@@ -0,0 +1,31 @@
1
+ import { generateCookie, getCookie } from 'hono/cookie';
2
+ /** The client of `c`'s request, and `sent`, which adds its cookies. */
3
+ export function clientOf(c) {
4
+ const cookies = [];
5
+ return {
6
+ client: {
7
+ address: c.var.address,
8
+ cookies: {
9
+ get: (name) => getCookie(c, name),
10
+ set: (name, value, options) => {
11
+ cookies.push(generateCookie(name, value, options));
12
+ },
13
+ clear: (name, options) => {
14
+ cookies.push(generateCookie(name, '', { ...options, maxAge: 0 }));
15
+ },
16
+ },
17
+ },
18
+ // A route may return a Response Hono's `c.header` never reaches.
19
+ sent: (response) => {
20
+ if (cookies.length === 0)
21
+ return response;
22
+ const headers = new Headers(response.headers);
23
+ for (const cookie of cookies)
24
+ headers.append('set-cookie', cookie);
25
+ return new Response(response.body, {
26
+ status: response.status,
27
+ headers,
28
+ });
29
+ },
30
+ };
31
+ }
@@ -0,0 +1,39 @@
1
+ import type { PluginOf, PluginTypes } from 'ultimabase';
2
+ import type { HttpOptions, Routes } from './app.ts';
3
+ import type { Accept } from './upgrade.ts';
4
+ export type { HttpEnv, HttpOptions, Routes } from './app.ts';
5
+ export type { Accept, Upgrade } from './upgrade.ts';
6
+ export { clientOf } from './client.ts';
7
+ export type { StandardSchema } from './validate.ts';
8
+ export { validate } from './validate.ts';
9
+ /** What the HTTP plugin offers other plugins (D-107). */
10
+ export interface HttpApi {
11
+ /**
12
+ * Adds routes after the application's; call it from your `api`. With
13
+ * `bodyLimit: false`, they read their own body (D-153).
14
+ */
15
+ mount(routes: Routes, options?: {
16
+ readonly bodyLimit?: false;
17
+ }): void;
18
+ /**
19
+ * Takes the WebSocket upgrades of `path`, once their origin is one CORS
20
+ * allows; call it from your `api` (D-154).
21
+ */
22
+ upgrade(path: string, accept: Accept): void;
23
+ /** Where the server listens, `http://localhost:3000`, once it started. */
24
+ url(): string;
25
+ }
26
+ /** The HTTP plugin's types (D-57). */
27
+ export interface Http extends PluginTypes {
28
+ readonly name: 'http';
29
+ readonly appOptions: HttpOptions;
30
+ readonly api: HttpApi;
31
+ }
32
+ /** The application's HTTP server (D-66, D-106). */
33
+ export declare const httpPlugin: PluginOf<Http>;
34
+ /**
35
+ * Routes whose context holds the request's caller, `c.var.caller`: the
36
+ * anonymous one when no application read it, as in `routes().request(…)`.
37
+ */
38
+ export declare const routes: () => Routes;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAU,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAG/D,OAAO,KAAK,EAAW,WAAW,EAAW,MAAM,EAAE,MAAM,UAAU,CAAA;AAKrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAG1C,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAC5D,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AACtC,YAAY,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,yDAAyD;AACzD,MAAM,WAAW,OAAO;IACvB;;;OAGG;IACH,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,SAAS,CAAC,EAAE,KAAK,CAAA;KAAE,GAAG,IAAI,CAAA;IACrE;;;OAGG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3C,0EAA0E;IAC1E,GAAG,IAAI,MAAM,CAAA;CACb;AAED,sCAAsC;AACtC,MAAM,WAAW,IAAK,SAAQ,WAAW;IACxC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,UAAU,EAAE,WAAW,CAAA;IAChC,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAA;CACrB;AA4ED,mDAAmD;AACnD,eAAO,MAAM,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAe,CAAA;AAIrD;;;GAGG;AACH,eAAO,MAAM,MAAM,QAAO,MAIvB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ import { Hono } from 'hono';
2
+ import { definePlugin } from 'ultimabase';
3
+ import manifest from '../package.json' with { type: 'json' };
4
+ import { addresses, proxiesOf } from './address.js';
5
+ import { allowing, appOf } from './app.js';
6
+ import { hold } from './request.js';
7
+ import { closed, listening, portOf, serverOf } from './server.js';
8
+ import { upgrading } from './upgrade.js';
9
+ export { clientOf } from './client.js';
10
+ export { validate } from './validate.js';
11
+ // Each running application's server and mounted routes, by the context its
12
+ // plugin received.
13
+ const servers = new WeakMap();
14
+ const mounts = new WeakMap();
15
+ const upgrades = new WeakMap();
16
+ const taken = new WeakMap();
17
+ const urls = new WeakMap();
18
+ const http = definePlugin({
19
+ name: 'http',
20
+ manifest,
21
+ api: (context) => {
22
+ const mounted = [];
23
+ const accepts = new Map();
24
+ mounts.set(context, mounted);
25
+ upgrades.set(context, accepts);
26
+ const building = (what) => {
27
+ if (mounts.has(context))
28
+ return;
29
+ throw new Error(`The HTTP server is running: ${what} from your plugin's api.`);
30
+ };
31
+ return {
32
+ mount: (routes, mountOptions) => {
33
+ building('mount routes');
34
+ mounted.push({ routes, bodyLimit: mountOptions?.bodyLimit ?? true });
35
+ },
36
+ upgrade: (path, accept) => {
37
+ building('take upgrades');
38
+ if (accepts.has(path)) {
39
+ throw new Error(`Two plugins take the upgrades of ${path}.`);
40
+ }
41
+ accepts.set(path, accept);
42
+ },
43
+ url: () => {
44
+ const url = urls.get(context);
45
+ if (url === undefined) {
46
+ throw new Error("The HTTP server is not running: read its url from your plugin's start.");
47
+ }
48
+ return url;
49
+ },
50
+ };
51
+ },
52
+ start: async (context) => {
53
+ const { options, identify, logger } = context;
54
+ const port = portOf(options.port);
55
+ const app = appOf(options, mounts.get(context) ?? [], identify, logger);
56
+ mounts.delete(context);
57
+ const server = serverOf(app.fetch);
58
+ const accepts = upgrades.get(context) ?? new Map();
59
+ const addressOf = addresses(proxiesOf(options.proxies), logger);
60
+ taken.set(context, upgrading(server, accepts, allowing(options), addressOf, logger));
61
+ const bound = await listening(server, port);
62
+ servers.set(context, server);
63
+ const url = `http://localhost:${bound}`;
64
+ urls.set(context, url);
65
+ logger.info(`Listening on ${url}.`);
66
+ },
67
+ // Stops accepting connections, then waits for running requests (D-59, D-106).
68
+ stop: async (context) => {
69
+ const { logger } = context;
70
+ const server = servers.get(context);
71
+ if (server === undefined)
72
+ return;
73
+ servers.delete(context);
74
+ urls.delete(context);
75
+ await closed(server, logger, taken.get(context) ?? new Set());
76
+ },
77
+ });
78
+ /** The application's HTTP server (D-66, D-106). */
79
+ export const httpPlugin = http.plugin;
80
+ const anonymous = { kind: 'anonymous' };
81
+ /**
82
+ * Routes whose context holds the request's caller, `c.var.caller`: the
83
+ * anonymous one when no application read it, as in `routes().request(…)`.
84
+ */
85
+ export const routes = () => new Hono().use(async (c, next) => {
86
+ if (!('caller' in c.var))
87
+ hold(c, anonymous, '');
88
+ await next();
89
+ });
@@ -0,0 +1,5 @@
1
+ export type { Args, At, Change, Limits, Page, Pagination, Relay, } from './pages.ts';
2
+ export { applied, connection, pageArgs, pageOf, rowOf, rowsOf, } from './pages.ts';
3
+ export type { Node, Served } from './transport.ts';
4
+ export { badInput, isNode, jsonSchemaOf, plural, readable, readableVirtuals, run, } from './transport.ts';
5
+ //# sourceMappingURL=internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../src/internal.ts"],"names":[],"mappings":"AAEA,YAAY,EACX,IAAI,EACJ,EAAE,EACF,MAAM,EACN,MAAM,EACN,IAAI,EACJ,UAAU,EACV,KAAK,GACL,MAAM,YAAY,CAAA;AACnB,OAAO,EACN,OAAO,EACP,UAAU,EACV,QAAQ,EACR,MAAM,EACN,KAAK,EACL,MAAM,GACN,MAAM,YAAY,CAAA;AACnB,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAClD,OAAO,EACN,QAAQ,EACR,MAAM,EACN,YAAY,EACZ,MAAM,EACN,QAAQ,EACR,gBAAgB,EAChB,GAAG,GACH,MAAM,gBAAgB,CAAA"}
@@ -0,0 +1,2 @@
1
+ export { applied, connection, pageArgs, pageOf, rowOf, rowsOf, } from './pages.js';
2
+ export { badInput, isNode, jsonSchemaOf, plural, readable, readableVirtuals, run, } from './transport.js';
@@ -0,0 +1,60 @@
1
+ import type { Row } from 'ultimabase';
2
+ /** A list's arguments, as the client wrote them. */
3
+ export type Args = {
4
+ readonly [key: string]: unknown;
5
+ };
6
+ /** Where an argument was written: `first`, or `include.posts.first`. */
7
+ export type At = (name: string) => string;
8
+ /** A transport's `pagination` setting (D-55). */
9
+ export type Pagination = 'connection' | 'list';
10
+ /** A model's limits: the rows a list returns by default, and at most. */
11
+ export type Limits = {
12
+ readonly take: number;
13
+ readonly maxTake: number;
14
+ readonly model: {
15
+ readonly name: string;
16
+ };
17
+ };
18
+ /** A Relay page: the rows asked for and its direction. */
19
+ export type Relay = {
20
+ readonly size: number | undefined;
21
+ readonly backward: boolean;
22
+ };
23
+ /** A list's kernel read, and its Relay page unless `pagination: 'list'`. */
24
+ export type Page = {
25
+ readonly read: Args;
26
+ readonly relay: Relay | undefined;
27
+ };
28
+ /** The page a list's arguments ask for. */
29
+ export declare const pageOf: (pagination: Pagination, limits: Limits, args: Args, master: boolean, at?: At) => Page;
30
+ /** The page arguments of each pagination. */
31
+ export declare const pageArgs: (pagination: Pagination) => readonly string[];
32
+ export type Connection<N> = {
33
+ readonly edges: readonly {
34
+ readonly cursor: string;
35
+ readonly node: N;
36
+ }[];
37
+ readonly pageInfo: {
38
+ readonly hasNextPage: boolean;
39
+ readonly hasPreviousPage: boolean;
40
+ readonly startCursor: string | null;
41
+ readonly endCursor: string | null;
42
+ };
43
+ };
44
+ /** The rows of a Relay read, without the one read to look ahead. */
45
+ export declare function connection<N>(rows: readonly Row[], page: Relay, node: (row: Row) => N): Connection<N>;
46
+ /** A row's relation as the kernel returned it. */
47
+ export declare function rowsOf(value: unknown): readonly Row[];
48
+ export declare const rowOf: (value: unknown) => Row | undefined;
49
+ /** A live read's change (D-154): a row that left, or one placed after another. */
50
+ export type Change<R> = {
51
+ readonly remove: string;
52
+ } | {
53
+ readonly upsert: R;
54
+ readonly after: string | null;
55
+ };
56
+ /** `window` once a live read's `changes` are applied, in their order. */
57
+ export declare function applied<T extends {
58
+ readonly id: string;
59
+ }, R>(window: readonly T[], changes: readonly Change<R>[], kept: (upsert: R) => T): T[];
60
+ //# sourceMappingURL=pages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pages.d.ts","sourceRoot":"","sources":["../src/pages.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAA;AAIrC,oDAAoD;AACpD,MAAM,MAAM,IAAI,GAAG;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,CAAA;AAEtD,wEAAwE;AACxE,MAAM,MAAM,EAAE,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MA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