@ultimabase/http 0.0.0-stage → 0.1.1

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 +19 -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/src/request.ts ADDED
@@ -0,0 +1,40 @@
1
+ // What each route's context holds (D-106, D-108): the caller, and a body
2
+ // that, when it is not the JSON or the form it claims, is the client's error.
3
+ import type { Context } from 'hono'
4
+ import { HTTPException } from 'hono/http-exception'
5
+ import type { Caller } from 'ultimabase'
6
+ import type { HttpEnv } from './app.ts'
7
+
8
+ /** `c.req[method]`, its parsing failure, `parsing`, a 400. */
9
+ function malformed(
10
+ c: Context<HttpEnv>,
11
+ method: 'json' | 'formData' | 'parseBody',
12
+ parsing: typeof SyntaxError | typeof TypeError,
13
+ message: string,
14
+ ): void {
15
+ const read: (...args: never[]) => Promise<unknown> = c.req[method].bind(c.req)
16
+ Object.defineProperty(c.req, method, {
17
+ value: async (...args: never[]) => {
18
+ try {
19
+ return await read(...args)
20
+ } catch (error) {
21
+ if (!(error instanceof parsing)) throw error
22
+ throw new HTTPException(400, { message, cause: error })
23
+ }
24
+ },
25
+ })
26
+ }
27
+
28
+ export function hold(
29
+ c: Context<HttpEnv>,
30
+ caller: Caller,
31
+ address: string,
32
+ ): void {
33
+ c.set('caller', caller)
34
+ c.set('address', address)
35
+ // Only parsing the body throws these here, not the server's code.
36
+ malformed(c, 'json', SyntaxError, 'Malformed JSON in request body')
37
+ const form = 'Malformed form data in request body'
38
+ malformed(c, 'formData', TypeError, form)
39
+ malformed(c, 'parseBody', TypeError, form)
40
+ }
package/src/server.ts ADDED
@@ -0,0 +1,90 @@
1
+ // The port the server listens on, and its listening (D-106).
2
+ import type { Server } from 'node:http'
3
+ import { createServer } from 'node:http'
4
+ import type { Duplex } from 'node:stream'
5
+ import { getRequestListener } from '@hono/node-server'
6
+ import type { Logger } from 'ultimabase'
7
+ import { Refused } from 'ultimabase'
8
+
9
+ /** The `port` option, then `PORT`, then 3000. */
10
+ export function portOf(option: number | undefined): number {
11
+ const given = option ?? process.env['PORT']
12
+ if (given === undefined || given === '') return 3000
13
+ // Digits only: `Number` would also read ' ', '0x1F90' or '1e3'.
14
+ const port =
15
+ typeof given === 'number' || /^\d+$/.test(given)
16
+ ? Number(given)
17
+ : Number.NaN
18
+ if (Number.isInteger(port) && port >= 0 && port <= 65_535) return port
19
+ const name = option === undefined ? 'PORT' : 'port'
20
+ throw new Refused(`${name} is ${given}, not a port between 0 and 65535.`)
21
+ }
22
+
23
+ export async function listening(server: Server, port: number): Promise<number> {
24
+ await new Promise<void>((done, fail) => {
25
+ const refused = (error: Error) => {
26
+ const code: unknown = Reflect.get(error, 'code')
27
+ fail(
28
+ code === 'EADDRINUSE'
29
+ ? new Error(
30
+ `Port ${port} is in use: stop the process that holds it, or set PORT.`,
31
+ { cause: error },
32
+ )
33
+ : error,
34
+ )
35
+ }
36
+ server.once('error', refused)
37
+ server.listen(port, () => {
38
+ server.off('error', refused)
39
+ done()
40
+ })
41
+ })
42
+ const address = server.address()
43
+ return typeof address === 'object' && address !== null ? address.port : port
44
+ }
45
+
46
+ /** A Node server for `fetch`, Hono's handler. */
47
+ export function serverOf(
48
+ fetch: Parameters<typeof getRequestListener>[0],
49
+ ): Server {
50
+ const listener = getRequestListener(fetch)
51
+ const server = createServer((request, response) => {
52
+ // A request running when `stop` began leaves its connection idle after
53
+ // its response: close it, rather than wait for the client to.
54
+ response.once('finish', () => {
55
+ if (!server.listening) server.closeIdleConnections()
56
+ })
57
+ void listener(request, response)
58
+ })
59
+ return server
60
+ }
61
+
62
+ /** How long `stop` waits for running requests: a stream never ends. */
63
+ const grace = 10_000
64
+
65
+ /**
66
+ * Stops accepting connections, then waits for running requests and the
67
+ * sockets plugins took (D-59), 10 seconds at most (D-106).
68
+ */
69
+ export async function closed(
70
+ server: Server,
71
+ logger: Logger,
72
+ taken: ReadonlySet<Duplex>,
73
+ ): Promise<void> {
74
+ let cutting: NodeJS.Timeout | undefined
75
+ await new Promise<void>((done, fail) => {
76
+ server.close((error) => {
77
+ clearTimeout(cutting)
78
+ if (error === undefined) done()
79
+ else fail(error)
80
+ })
81
+ server.closeIdleConnections()
82
+ cutting = setTimeout(() => {
83
+ logger.warn(
84
+ `Stopped ${grace / 1000} s after stop began: closed the requests still running.`,
85
+ )
86
+ server.closeAllConnections()
87
+ for (const socket of taken) socket.destroy()
88
+ }, grace)
89
+ })
90
+ }
@@ -0,0 +1,84 @@
1
+ // What REST and GraphQL share besides pages (D-129, D-139): their errors as
2
+ // D-106 sends them, a model's names and fields, and a schema's JSON Schema.
3
+ import type { ExposedVirtual, SchemaField, SchemaModel } from 'ultimabase'
4
+ import { InvalidQuery, PublicError, Refused } from 'ultimabase'
5
+
6
+ /** An argument, a parameter or a body of the client's that the API refuses. */
7
+ export const badInput = (message: string, cause?: unknown): Error =>
8
+ new PublicError('BAD_USER_INPUT', message, { cause })
9
+
10
+ /**
11
+ * Runs a kernel query. The arguments come from the client's request, so
12
+ * one the kernel refuses is the client's error, not the server's.
13
+ */
14
+ export async function run<T>(query: () => Promise<T>): Promise<T> {
15
+ try {
16
+ return await query()
17
+ } catch (error) {
18
+ if (error instanceof InvalidQuery) {
19
+ throw new PublicError('BAD_USER_INPUT', error.message, {
20
+ details: { path: error.path },
21
+ cause: error,
22
+ })
23
+ }
24
+ throw error
25
+ }
26
+ }
27
+
28
+ /** `post` → `posts`, `category` → `categories`, `box` → `boxes`. */
29
+ export function plural(name: string): string {
30
+ if (/[^aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`
31
+ if (/(?:s|x|z|ch|sh)$/i.test(name)) return `${name}es`
32
+ return `${name}s`
33
+ }
34
+
35
+ /** A model a transport serves, with its fields' read rules. */
36
+ export type Served = {
37
+ readonly model: SchemaModel
38
+ readonly exposed: {
39
+ readonly readRules: { readonly [field: string]: 'private' | 'rule' }
40
+ readonly virtuals: readonly ExposedVirtual[]
41
+ }
42
+ }
43
+
44
+ /** The fields a client reads: no `private` one, for Master too (D-44). */
45
+ export const readable = (served: Served): readonly SchemaField[] =>
46
+ served.model.fields.filter(
47
+ (field) => served.exposed.readRules[field.name] !== 'private',
48
+ )
49
+
50
+ /** The virtual fields a client reads, as `readable` (D-151). */
51
+ export const readableVirtuals = (served: Served): readonly ExposedVirtual[] =>
52
+ served.exposed.virtuals.filter(
53
+ (virtual) => served.exposed.readRules[virtual.name] !== 'private',
54
+ )
55
+
56
+ /** A JSON Schema, or one of its nodes. */
57
+ export type Node = { readonly [key: string]: unknown }
58
+
59
+ export const isNode = (value: unknown): value is Node =>
60
+ typeof value === 'object' && value !== null && !Array.isArray(value)
61
+
62
+ /** A schema's JSON Schema, or startup stops naming `where` (D-45). */
63
+ export function jsonSchemaOf(
64
+ schema: object,
65
+ side: 'input' | 'output',
66
+ where: string,
67
+ ): Node {
68
+ const standard: unknown = Reflect.get(schema, '~standard')
69
+ const exporter = isNode(standard) ? standard['jsonSchema'] : undefined
70
+ const exported = isNode(exporter) ? exporter[side] : undefined
71
+ if (typeof exported !== 'function') {
72
+ throw new Refused(`${where} has no standard JSON Schema export.`)
73
+ }
74
+ try {
75
+ const node: unknown = Reflect.apply(exported, exporter, [
76
+ { target: 'draft-2020-12' },
77
+ ])
78
+ if (isNode(node)) return node
79
+ } catch (error) {
80
+ const reason = error instanceof Error ? error.message : String(error)
81
+ throw new Refused(`${where}: ${reason}.`, { cause: error })
82
+ }
83
+ throw new Refused(`${where}'s JSON Schema is not an object.`)
84
+ }
package/src/upgrade.ts ADDED
@@ -0,0 +1,105 @@
1
+ // WebSocket upgrades (D-154): a plugin takes a path's. One from an origin
2
+ // CORS does not allow is refused before any caller is read, so another site
3
+ // cannot open a socket with its visitor's cookies.
4
+ import type { IncomingMessage, Server } from 'node:http'
5
+ import { STATUS_CODES } from 'node:http'
6
+ import type { Duplex } from 'node:stream'
7
+ import type { Logger } from 'ultimabase'
8
+
9
+ /**
10
+ * An upgrade a plugin takes: Node's request, its socket and first bytes, as
11
+ * `ws`'s `handleUpgrade` reads them, the request `identify` reads and the
12
+ * client's address, as `proxies` reads it (D-116).
13
+ */
14
+ export interface Upgrade {
15
+ readonly request: Request
16
+ readonly address: string
17
+ readonly incoming: IncomingMessage
18
+ readonly socket: Duplex
19
+ readonly head: Buffer
20
+ }
21
+
22
+ /** Takes an upgrade on its path; the socket is the plugin's from then on. */
23
+ export type Accept = (upgrade: Upgrade) => void
24
+
25
+ /** Answers `status` with an error as D-72 sends it, then closes the socket. */
26
+ function refuse(
27
+ socket: Duplex,
28
+ status: number,
29
+ code: string,
30
+ message: string,
31
+ ): void {
32
+ const body = JSON.stringify({ code, message })
33
+ socket.end(
34
+ [
35
+ `HTTP/1.1 ${status} ${STATUS_CODES[status] ?? ''}`,
36
+ 'connection: close',
37
+ 'content-type: application/json',
38
+ `content-length: ${Buffer.byteLength(body)}`,
39
+ '',
40
+ body,
41
+ ].join('\r\n'),
42
+ )
43
+ }
44
+
45
+ /** The request `incoming` is, without a body; `undefined` for no valid URL. */
46
+ function requestOf(incoming: IncomingMessage): Request | undefined {
47
+ const { host } = incoming.headers
48
+ const target = incoming.url ?? ''
49
+ const url = `http://${host ?? ''}${target}`
50
+ if (host === undefined || !target.startsWith('/') || !URL.canParse(url)) {
51
+ return undefined
52
+ }
53
+ const headers = new Headers()
54
+ const raw = incoming.rawHeaders
55
+ for (let index = 0; index + 1 < raw.length; index += 2) {
56
+ headers.append(raw[index] ?? '', raw[index + 1] ?? '')
57
+ }
58
+ return new Request(url, { headers })
59
+ }
60
+
61
+ /**
62
+ * Hands each upgrade to its path's plugin, past the origin check; returns
63
+ * the sockets taken and still open, which `stop` closes at its end.
64
+ */
65
+ export function upgrading(
66
+ server: Server,
67
+ accepts: ReadonlyMap<string, Accept>,
68
+ allows: (origin: string) => boolean,
69
+ addressOf: (env: { readonly incoming: IncomingMessage }) => string,
70
+ logger: Logger,
71
+ ): ReadonlySet<Duplex> {
72
+ const open = new Set<Duplex>()
73
+ server.on('upgrade', (incoming: IncomingMessage, socket: Duplex, head) => {
74
+ // A client that leaves mid-answer must not stop the server.
75
+ socket.on('error', () => socket.destroy())
76
+ const request = requestOf(incoming)
77
+ if (request === undefined) {
78
+ return refuse(socket, 400, 'BAD_REQUEST', 'The upgrade has no URL.')
79
+ }
80
+ const { origin, pathname } = new URL(request.url)
81
+ const accept = accepts.get(pathname)
82
+ if (accept === undefined) {
83
+ return refuse(socket, 404, 'NOT_FOUND', `No upgrade at ${pathname}.`)
84
+ }
85
+ const from = incoming.headers.origin
86
+ if (from !== undefined && from !== origin && !allows(from)) {
87
+ return refuse(
88
+ socket,
89
+ 403,
90
+ 'ACCESS_DENIED',
91
+ 'A WebSocket from another origin is refused.',
92
+ )
93
+ }
94
+ open.add(socket)
95
+ socket.once('close', () => open.delete(socket))
96
+ try {
97
+ const address = addressOf({ incoming })
98
+ accept({ request, address, incoming, socket, head })
99
+ } catch (error) {
100
+ logger.error({ err: error }, 'An upgrade failed.')
101
+ refuse(socket, 500, 'INTERNAL', 'Internal error.')
102
+ }
103
+ })
104
+ return open
105
+ }
@@ -0,0 +1,96 @@
1
+ // `validate(target, schema)` (D-108): a part of the request checked by a
2
+ // Standard Schema, which the route reads, typed, as `c.req.valid(target)`.
3
+ import type { Env, MiddlewareHandler, ValidationTargets } from 'hono'
4
+ import { HTTPException } from 'hono/http-exception'
5
+ import { validator } from 'hono/validator'
6
+ import type { Issue } from 'ultimabase'
7
+ import { PublicError } from 'ultimabase'
8
+
9
+ type Segment = PropertyKey | { readonly key: PropertyKey }
10
+
11
+ /**
12
+ * Standard Schema (standardschema.dev), the part read here. Its
13
+ * specification asks for the interface to be copied, not imported.
14
+ */
15
+ export interface StandardSchema {
16
+ readonly '~standard': {
17
+ readonly validate: (value: unknown) => Result | Promise<Result>
18
+ readonly types?: { readonly input: unknown } | undefined
19
+ }
20
+ }
21
+ type Result =
22
+ | { readonly value: unknown; readonly issues?: undefined }
23
+ | {
24
+ readonly issues: readonly {
25
+ readonly message: string
26
+ readonly path?: readonly Segment[] | undefined
27
+ }[]
28
+ }
29
+
30
+ /** What the schema returns for a value it accepts. */
31
+ type Output<S extends StandardSchema> = Extract<
32
+ Awaited<ReturnType<S['~standard']['validate']>>,
33
+ { readonly value: unknown }
34
+ >['value']
35
+
36
+ /** What the schema takes, `unknown` when it declares no types. */
37
+ type Input<S extends StandardSchema> = NonNullable<
38
+ S['~standard']['types']
39
+ >['input']
40
+
41
+ /** What a route reads with `c.req.valid(target)`, and a client sends. */
42
+ type Validated<T extends keyof ValidationTargets, S extends StandardSchema> = {
43
+ readonly in: {
44
+ readonly [K in T]: K extends 'json' ? Input<S> : NonNullable<Input<S>>
45
+ }
46
+ readonly out: { readonly [K in T]: Output<S> }
47
+ }
48
+
49
+ // Hono's own test: a body it does not take as JSON, it validates as `{}`.
50
+ const json = /^application\/([a-z-.]+\+)?json(;\s*[a-zA-Z0-9-]+=([^;]+))*$/i
51
+
52
+ const keyOf = (segment: Segment): string | number => {
53
+ const key = typeof segment === 'object' ? segment.key : segment
54
+ return typeof key === 'symbol' ? String(key) : key
55
+ }
56
+
57
+ /** Refuses the request with the issues the schema reports, as the kernel does. */
58
+ export const validate = <
59
+ T extends keyof ValidationTargets,
60
+ S extends StandardSchema,
61
+ >(
62
+ target: T,
63
+ schema: S,
64
+ ): MiddlewareHandler<Env, string, Validated<T, S>> => {
65
+ const check = async (value: unknown): Promise<unknown> => {
66
+ const result = await schema['~standard'].validate(value)
67
+ if (result.issues === undefined) return result.value
68
+ const issues: Issue[] = result.issues.map((issue) => ({
69
+ path: (issue.path ?? []).map(keyOf),
70
+ message: issue.message,
71
+ }))
72
+ throw new PublicError('VALIDATION_FAILED', 'Invalid data.', {
73
+ details: { issues },
74
+ })
75
+ }
76
+ // Hono infers the value from `check`; the schema gives its type.
77
+ const validating = validator<
78
+ unknown,
79
+ string,
80
+ string,
81
+ T,
82
+ string,
83
+ typeof check,
84
+ Validated<T, S>,
85
+ Env
86
+ >(target, check)
87
+ if (target !== 'json') return validating
88
+ return async (c, next) => {
89
+ if (!json.test(c.req.header('content-type') ?? '')) {
90
+ throw new HTTPException(415, {
91
+ message: 'The body is not JSON: send content-type: application/json.',
92
+ })
93
+ }
94
+ return validating(c, next)
95
+ }
96
+ }