anygrest 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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +451 -2
  3. package/dist/src/app.d.ts +96 -0
  4. package/dist/src/app.js +819 -0
  5. package/dist/src/app.js.map +1 -0
  6. package/dist/src/auth/jwt.d.ts +138 -0
  7. package/dist/src/auth/jwt.js +478 -0
  8. package/dist/src/auth/jwt.js.map +1 -0
  9. package/dist/src/db/introspect/views.d.ts +62 -0
  10. package/dist/src/db/introspect/views.js +257 -0
  11. package/dist/src/db/introspect/views.js.map +1 -0
  12. package/dist/src/db/knex.d.ts +72 -0
  13. package/dist/src/db/knex.js +358 -0
  14. package/dist/src/db/knex.js.map +1 -0
  15. package/dist/src/db/pool-timers.d.ts +18 -0
  16. package/dist/src/db/pool-timers.js +8 -0
  17. package/dist/src/db/pool-timers.js.map +1 -0
  18. package/dist/src/db/schema.d.ts +306 -0
  19. package/dist/src/db/schema.js +1387 -0
  20. package/dist/src/db/schema.js.map +1 -0
  21. package/dist/src/db/session.d.ts +160 -0
  22. package/dist/src/db/session.js +399 -0
  23. package/dist/src/db/session.js.map +1 -0
  24. package/dist/src/db/sqlite.d.ts +7 -0
  25. package/dist/src/db/sqlite.js +16 -0
  26. package/dist/src/db/sqlite.js.map +1 -0
  27. package/dist/src/demo.d.ts +5 -0
  28. package/dist/src/demo.js +49 -0
  29. package/dist/src/demo.js.map +1 -0
  30. package/dist/src/errors/mssql.d.ts +10 -0
  31. package/dist/src/errors/mssql.js +53 -0
  32. package/dist/src/errors/mssql.js.map +1 -0
  33. package/dist/src/errors/oracle.d.ts +17 -0
  34. package/dist/src/errors/oracle.js +59 -0
  35. package/dist/src/errors/oracle.js.map +1 -0
  36. package/dist/src/errors.d.ts +84 -0
  37. package/dist/src/errors.js +444 -0
  38. package/dist/src/errors.js.map +1 -0
  39. package/dist/src/http/response.d.ts +229 -0
  40. package/dist/src/http/response.js +452 -0
  41. package/dist/src/http/response.js.map +1 -0
  42. package/dist/src/index.d.ts +13 -0
  43. package/dist/src/index.js +13 -0
  44. package/dist/src/index.js.map +1 -0
  45. package/dist/src/query/ast.d.ts +247 -0
  46. package/dist/src/query/ast.js +19 -0
  47. package/dist/src/query/ast.js.map +1 -0
  48. package/dist/src/query/parser.d.ts +219 -0
  49. package/dist/src/query/parser.js +2304 -0
  50. package/dist/src/query/parser.js.map +1 -0
  51. package/dist/src/query/request.d.ts +183 -0
  52. package/dist/src/query/request.js +1385 -0
  53. package/dist/src/query/request.js.map +1 -0
  54. package/dist/src/server.d.ts +1 -0
  55. package/dist/src/server.js +43 -0
  56. package/dist/src/server.js.map +1 -0
  57. package/dist/src/sql/filters.d.ts +103 -0
  58. package/dist/src/sql/filters.js +730 -0
  59. package/dist/src/sql/filters.js.map +1 -0
  60. package/dist/src/sql/matcher.d.ts +10 -0
  61. package/dist/src/sql/matcher.js +161 -0
  62. package/dist/src/sql/matcher.js.map +1 -0
  63. package/dist/src/sql/read.d.ts +83 -0
  64. package/dist/src/sql/read.js +1745 -0
  65. package/dist/src/sql/read.js.map +1 -0
  66. package/dist/src/sql/rowselect.d.ts +74 -0
  67. package/dist/src/sql/rowselect.js +120 -0
  68. package/dist/src/sql/rowselect.js.map +1 -0
  69. package/dist/src/sql/rpc-read.d.ts +231 -0
  70. package/dist/src/sql/rpc-read.js +887 -0
  71. package/dist/src/sql/rpc-read.js.map +1 -0
  72. package/dist/src/sql/rpc-types.d.ts +23 -0
  73. package/dist/src/sql/rpc-types.js +84 -0
  74. package/dist/src/sql/rpc-types.js.map +1 -0
  75. package/dist/src/sql/rpc.d.ts +47 -0
  76. package/dist/src/sql/rpc.js +214 -0
  77. package/dist/src/sql/rpc.js.map +1 -0
  78. package/dist/src/sql/select.d.ts +138 -0
  79. package/dist/src/sql/select.js +566 -0
  80. package/dist/src/sql/select.js.map +1 -0
  81. package/dist/src/sql/serialize.d.ts +47 -0
  82. package/dist/src/sql/serialize.js +231 -0
  83. package/dist/src/sql/serialize.js.map +1 -0
  84. package/dist/src/sql/values.d.ts +15 -0
  85. package/dist/src/sql/values.js +24 -0
  86. package/dist/src/sql/values.js.map +1 -0
  87. package/dist/src/sql/write-read.d.ts +83 -0
  88. package/dist/src/sql/write-read.js +202 -0
  89. package/dist/src/sql/write-read.js.map +1 -0
  90. package/dist/src/sql/write.d.ts +53 -0
  91. package/dist/src/sql/write.js +1205 -0
  92. package/dist/src/sql/write.js.map +1 -0
  93. package/package.json +88 -4
  94. package/sql/cockroachdb.sql +52 -0
  95. package/sql/mssql.sql +63 -0
  96. package/sql/mysql.sql +55 -0
  97. package/sql/oracle.sql +76 -0
  98. package/sql/postgres.sql +68 -0
  99. package/sql/redshift.sql +50 -0
@@ -0,0 +1,819 @@
1
+ import { Hono } from 'hono';
2
+ import { anonymousClaims, claimsWithRole, createJwtVerifier, decodeJwt, JwtAuthError, jwtRejected, jwtSecretMissing, jwtTokenRequired, requestRole, } from './auth/jwt.js';
3
+ import { unrefPoolInterval } from './db/pool-timers.js';
4
+ import { introspectSchema } from './db/schema.js';
5
+ import { parseCookies, sessionFor, supportsSessionContext, withRequestContext, } from './db/session.js';
6
+ import { AnygrestError, translateDbError } from './errors.js';
7
+ import { JSON_CONTENT_TYPE, SINGULAR_JSON_CONTENT_TYPE, TABLE_ALLOW, contentLocation, contentRangeH, contentTypeOf, csvResponse, finish, headResponse, infoResponse, jsonResponse, isPreflight, methodNotAllowed, negotiateMediaType, negotiatedByProfile, pageWindow, parseRangeHeader, rangeStatus, rpcAllow, tableAllow, JSON_MEDIA_TYPES, SCALAR_MEDIA_TYPES, stripNulls, } from './http/response.js';
8
+ import { QueryParseError } from './query/ast.js';
9
+ import { parsePrefer } from './query/parser.js';
10
+ import { legacyTargetNameWarning, legacyTargetNames, parseReadQuery, parseRequest, rawRequestPath, searchParamsOf, } from './query/request.js';
11
+ import { executeRead } from './sql/read.js';
12
+ import { callFunction } from './sql/rpc.js';
13
+ import { assertIdentifier } from './sql/select.js';
14
+ import { deleteRows, insertRows, replaceRows, updateRows } from './sql/write.js';
15
+ import { writeResponse } from './sql/write-read.js';
16
+ /**
17
+ * Builds a Hono application exposing the PostgREST-compatible REST API for the
18
+ * given database connection.
19
+ */
20
+ export async function createAnygrest(database, options = {}) {
21
+ // An idle connection pool must not keep short-lived processes alive.
22
+ database.knex.on('query', () => unrefPoolInterval(database.knex));
23
+ database.knex.on('query-response', () => unrefPoolInterval(database.knex));
24
+ let schema = await loadSchema(database, options);
25
+ unrefPoolInterval(database.knex);
26
+ const session = createSession(database, options);
27
+ const verifier = createVerifier(options.jwt);
28
+ const app = new Hono();
29
+ app.use('*', async (c, next) => {
30
+ // `errorResponse` needs the dialect to read `mssql`/`oracle` error numbers.
31
+ c.set('dialect', database.dialect);
32
+ // anygrest serves one schema, so `Content-Profile` is only sent when the
33
+ // request negotiated it with a profile header (`ApiRequest.hs:210-227`).
34
+ c.set('profile', negotiatedByProfile(c.req.method, c.req.raw.headers, [schema.schema]));
35
+ if (options.authenticate) {
36
+ const allowed = await options.authenticate(c.req.raw);
37
+ if (!allowed)
38
+ return errorResponse(c, jwtTokenRequired(), false);
39
+ }
40
+ // Resolve the token before routing so 401s never touch the database.
41
+ c.set('claims', authenticateRequest(c.req.raw, options.jwt, verifier));
42
+ c.set('schemaName', schema.schema);
43
+ await next();
44
+ // Every response carries the CORS policy, `Vary` and — when the request
45
+ // negotiated one — `Content-Profile`.
46
+ if (c.finalized)
47
+ c.res = finish(c.req.raw, c.res, protocolFor(c, schema, options));
48
+ });
49
+ // A CORS preflight is answered before the request reaches a route, so it
50
+ // never 401s (auth) or 404s (an unknown table or path).
51
+ app.use('*', async (c, next) => {
52
+ if (!isPreflight(c.req.raw))
53
+ return next();
54
+ return infoResponse(c.req.raw, TABLE_ALLOW, protocolFor(c, schema, options));
55
+ });
56
+ app.on(['GET', 'HEAD', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'], '/:table', async (c) => {
57
+ // The table is the first segment of the request path (`ApiRequest.hs:177-185`,
58
+ // `getResource [table]`), see `requestPathSegments`.
59
+ const [table = ''] = requestPathSegments(c.req.raw);
60
+ if (!session)
61
+ return handleRequest(c, database, schema, table, options, protocolFor(c, schema, options));
62
+ // PostgREST runs every request in a transaction and applies the request
63
+ // variables inside it, so the role switch and claims are request-local.
64
+ const context = buildRequestContext(c, options.jwt);
65
+ return withRequestContext(database.knex, session, context, (trx) => withDebugTrace(trx, options.debug === true, () => withPreRequest(trx, database.dialect, options.preRequest, () => handleRequest(c, { knex: trx, dialect: database.dialect }, schema, table, options, protocolFor(c, schema, options)))));
66
+ });
67
+ // Every method is routed: an unsupported one must reach `callFunction` to
68
+ // answer `405 PGRST101` (`ApiRequest.hs:183-196`), not Hono's 404.
69
+ app.all('/rpc/:name', async (c) => {
70
+ const [, name = ''] = requestPathSegments(c.req.raw);
71
+ if (!session)
72
+ return handleRpc(c, database, schema, name, protocolFor(c, schema, options));
73
+ const context = buildRequestContext(c, options.jwt);
74
+ return withRequestContext(database.knex, session, context, (trx) => withPreRequest(trx, database.dialect, options.preRequest, () => handleRpc(c, { knex: trx, dialect: database.dialect }, schema, name, protocolFor(c, schema, options))));
75
+ });
76
+ if (options.openapi !== false) {
77
+ app.get('/', (c) => jsonResponse(buildOpenApi(schema), { status: 200, headers: { 'content-type': JSON_CONTENT_TYPE } }));
78
+ }
79
+ // Hono's `c.json` sends a bare `application/json`; every JSON body here is the
80
+ // PostgREST one, with the charset and an explicit byte length.
81
+ //
82
+ // The root, `/<table>` and `/rpc/<name>` all have routes, so a request that
83
+ // reaches this handler has a path `getResource` cannot serve. The root is one
84
+ // of PostgREST's resources (`ApiRequest.hs:177-184`), but anygrest's router
85
+ // matches it itself, so what lands here is a depth-2-or-greater path — the
86
+ // `_ -> Left InvalidResourcePath` case — and it answers `PGRST125`
87
+ // (`Error.hs:124,171,198`).
88
+ app.notFound((c) => jsonResponse({ code: 'PGRST125', details: null, hint: null, message: 'Invalid path specified in request URL' }, { status: 404, headers: { 'content-type': JSON_CONTENT_TYPE } }));
89
+ app.onError((error, c) => errorResponse(c, error, options.debug === true));
90
+ return {
91
+ app,
92
+ get schema() {
93
+ return schema;
94
+ },
95
+ get schemaName() {
96
+ return schema.schema;
97
+ },
98
+ get openapi() {
99
+ return options.openapi === false ? null : buildOpenApi(schema);
100
+ },
101
+ async reload() {
102
+ schema = await loadSchema(database, options);
103
+ },
104
+ async close() {
105
+ await database.knex.destroy();
106
+ },
107
+ };
108
+ }
109
+ /**
110
+ * The segments of the request path, each percent-decoded on its own.
111
+ *
112
+ * wai splits the path *before* decoding it (`ApiRequest.hs:113` passes
113
+ * `pathInfo req` to `getResource`), so `/Escap3e%3B%20Workaround2` names one
114
+ * segment — the table `Escap3e; Workaround2` — and a `%2F` stays inside the name
115
+ * it was written in.
116
+ *
117
+ * The path itself comes from `rawRequestPath`: `new URL(request.url).pathname`
118
+ * is the wrong text to split, because the `URL` parser turns `%2F` into a
119
+ * separator and re-encodes what it does not allow. A path a server hands over
120
+ * already decoded (`/a b/c`) has no escape left to protect and splits at its
121
+ * `/` like any other.
122
+ *
123
+ * Only the table is read this way. The routes match on Hono's own decoded path
124
+ * (`/:table`, `/rpc/:name`), and the query string goes to `searchParamsOf`.
125
+ */
126
+ function requestPathSegments(request) {
127
+ const trimmed = rawRequestPath(request).replace(/^\/+/, '').replace(/\/+$/, '');
128
+ return trimmed === '' ? [] : trimmed.split('/').map(decodePathSegment);
129
+ }
130
+ /** One path segment: `%XX` read back alone, so a stray `%` cannot break the path. */
131
+ function decodePathSegment(segment) {
132
+ try {
133
+ return decodeURIComponent(segment);
134
+ }
135
+ catch {
136
+ return segment;
137
+ }
138
+ }
139
+ /** The media type an `Accept` header asks for on a table route. */
140
+ function responseMediaType(c) {
141
+ return negotiateMediaType(c.req.raw.headers.get('accept'), JSON_MEDIA_TYPES);
142
+ }
143
+ /**
144
+ * The protocol options of this request: a server that exposes more than one
145
+ * schema always names the negotiated one (`ApiRequest.hs:216`), a
146
+ * single-schema server only does so once the request asked for its profile.
147
+ */
148
+ function protocolFor(c, schema, options) {
149
+ return {
150
+ schemaName: schema.schema,
151
+ ...(options.cors ? { cors: options.cors } : {}),
152
+ negotiatedByProfile: c.get('profile') === true,
153
+ };
154
+ }
155
+ /**
156
+ * `debug: true` logs the SQL a transaction issues, which is what a failing
157
+ * request needs; the rows themselves are not logged. Knex shares the pool's
158
+ * event emitter with the transaction, so the listener sees only this request.
159
+ */
160
+ async function withDebugTrace(trx, enabled, work) {
161
+ const client = trx.client;
162
+ const on = client?.on;
163
+ const remove = client?.removeListener;
164
+ if (!enabled || typeof on !== 'function' || typeof remove !== 'function')
165
+ return work();
166
+ const listener = (value) => {
167
+ const { sql, bindings } = value;
168
+ console.error('[sql]', sql, bindings);
169
+ };
170
+ on.call(client, 'query', listener);
171
+ try {
172
+ return await work();
173
+ }
174
+ finally {
175
+ remove.call(client, 'query', listener);
176
+ }
177
+ }
178
+ /**
179
+ * Runs the configured `db-pre-request` hook inside the request transaction, so
180
+ * it sees the request variables and its error aborts the whole request.
181
+ *
182
+ * Engines that cannot call a function from a bare statement (MySQL, MariaDB,
183
+ * SQLite) skip the hook; PostgreSQL/CockroachDB and MS SQL take a source
184
+ * function, Oracle takes a PL/SQL procedure or a function.
185
+ */
186
+ async function withPreRequest(trx, dialect, name, work) {
187
+ if (!name)
188
+ return work();
189
+ const raw = trx.raw;
190
+ if (typeof raw !== 'function')
191
+ return work();
192
+ const routine = quoteRoutine(dialect, name);
193
+ let statement;
194
+ switch (dialect) {
195
+ case 'postgres':
196
+ case 'cockroachdb':
197
+ case 'redshift':
198
+ statement = `select * from ${routine}()`;
199
+ break;
200
+ case 'mssql':
201
+ statement = `exec ${routine}`;
202
+ break;
203
+ case 'oracle':
204
+ statement = `begin ${routine}; end;`;
205
+ break;
206
+ default:
207
+ statement = null;
208
+ }
209
+ if (statement === null)
210
+ return work();
211
+ try {
212
+ await raw.call(trx, statement);
213
+ }
214
+ catch (error) {
215
+ throw translateDbError(error, dialect);
216
+ }
217
+ return work();
218
+ }
219
+ /** Oracle stores unquoted names upper-case, so the hook is quoted the same way. */
220
+ function wrap(dialect, name) {
221
+ return dialect === 'oracle' ? `"${name.toUpperCase()}"` : `"${name}"`;
222
+ }
223
+ /**
224
+ * `db-pre-request` names a routine like PostgREST's `db-pre-request`, which is
225
+ * resolved through `search_path` (`test.load_safeupdate` in the spec fixtures).
226
+ * Each part is quoted on its own so a schema-qualified name is one identifier
227
+ * per part rather than one literal name.
228
+ */
229
+ function quoteRoutine(dialect, name) {
230
+ return name.split('.').map((part) => wrap(dialect, assertIdentifier(part))).join('.');
231
+ }
232
+ async function loadSchema(database, options) {
233
+ const schema = await introspectSchema(database.knex, database.dialect, { schema: options.context?.schema });
234
+ if (!options.tables)
235
+ return schema;
236
+ const predicate = typeof options.tables === 'function'
237
+ ? options.tables
238
+ : (table) => options.tables.includes(table.name);
239
+ for (const [name, table] of [...schema.tables]) {
240
+ if (!predicate(table))
241
+ schema.tables.delete(name);
242
+ }
243
+ for (const table of schema.tables.values()) {
244
+ table.forward = table.forward.filter((relation) => schema.tables.has(relation.targetTable));
245
+ table.reverse = table.reverse.filter((relation) => schema.tables.has(relation.sourceTable));
246
+ }
247
+ return schema;
248
+ }
249
+ async function handleRequest(c, database, schema, tableName, options, protocol) {
250
+ const table = schema.table(tableName);
251
+ const method = c.req.method.toUpperCase();
252
+ if (method === 'OPTIONS')
253
+ return tableInfo(c, database, schema, tableName, protocol);
254
+ if (!table)
255
+ throw AnygrestError.notFound(tableName, schema.schema);
256
+ if (method !== 'GET' && method !== 'HEAD' && !WRITE_METHODS.has(method)) {
257
+ throw methodNotAllowed(c.req.raw, tableAllow(schema, tableName));
258
+ }
259
+ // PostgREST parses the *raw* query string and decodes every name and value
260
+ // on its own (`QueryParams.hs:179`), so a pair with a stray `%` or a repeated
261
+ // `select` still reaches the parser as it was written.
262
+ const search = searchParamsOf(new URL(c.req.url).search);
263
+ try {
264
+ if (method === 'GET' || method === 'HEAD') {
265
+ assertProfile(c.req.raw.headers, schema.schema, 'accept-profile');
266
+ const query = parseReadQuery(tableName, search, c.req.raw.headers, schema);
267
+ rejectInvalidPreferences(query);
268
+ // With `url-use-legacy-target-names` off, naming an aliased embed by its
269
+ // relation name is `PGRST108` (`Plan.hs:1105-1108` `findLegacyUsage`).
270
+ if (options.urlUseLegacyTargetNames === false) {
271
+ const legacy = legacyTargetNames(query.select, query.embeddings ?? []);
272
+ if (legacy[0])
273
+ throw legacyTargetNameDisabled(legacy[0]);
274
+ }
275
+ // `Range` restricts the requested page exactly like `limit`/`offset`
276
+ // (PostgREST `ApiRequest.hs:230-246`), only for `GET`.
277
+ const range = parseRangeHeader(c.req.raw);
278
+ const paged = range.lower !== null || query.limit !== undefined || query.offset !== undefined;
279
+ const window = pageWindow(range, query.limit, query.offset);
280
+ const result = await executeRead(database, schema, tableName, query, {
281
+ maxRows: options.maxRows,
282
+ offset: window.offset,
283
+ ...(window.limit !== undefined ? { limit: window.limit } : {}),
284
+ ...(query.ambientFilters ? { ambientFilters: query.ambientFilters } : {}),
285
+ ...(query.ambientFilterPaths ? { ambientFilterPaths: query.ambientFilterPaths } : {}),
286
+ });
287
+ return readResponse(c, result, window.offset, paged, method === 'HEAD', {
288
+ legacyNames: legacyTargetNames(query.select, query.embeddings ?? []),
289
+ useLegacyTargetNames: options.urlUseLegacyTargetNames !== false,
290
+ });
291
+ }
292
+ assertProfile(c.req.raw.headers, schema.schema, 'content-profile');
293
+ const body = await readJsonBody(c);
294
+ const { mutation } = parseRequest(tableName, method, search, c.req.raw.headers, body, schema);
295
+ if (!mutation) {
296
+ throw methodNotAllowed(c.req.raw, tableAllow(schema, tableName));
297
+ }
298
+ rejectInvalidPreferences(mutation.base.prefer);
299
+ const query = {
300
+ table: tableName,
301
+ select: mutation.base.select,
302
+ filters: mutation.base.filters,
303
+ orders: mutation.base.orders,
304
+ missing: mutation.base.prefer.missing,
305
+ ...(mutation.base.prefer.count ? { count: mutation.base.prefer.count } : {}),
306
+ ...(mutation.base.limit !== undefined ? { limit: mutation.base.limit } : {}),
307
+ ...(mutation.base.offset !== undefined ? { offset: mutation.base.offset } : {}),
308
+ ...(mutation.base.embeddings.length > 0 ? { embeddings: mutation.base.embeddings } : {}),
309
+ ...(mutation.base.onConflict ? { onConflict: mutation.base.onConflict } : {}),
310
+ ...(mutation.base.columns && mutation.base.columns.length > 0
311
+ ? { columns: mutation.base.columns }
312
+ : {}),
313
+ };
314
+ const maximum = options.maxRows;
315
+ if (mutation.kind === 'insert') {
316
+ const result = await insertRows({ database, schema, ...(maximum !== undefined ? { maxRows: maximum } : {}) }, table, mutation.rows ?? [], query, mutation.base.prefer);
317
+ const status = mutation.base.prefer.resolution === 'merge-duplicates' ? 200 : 201;
318
+ return mutationResponse(c, result, mutation.base.prefer, status, responseMediaType(c));
319
+ }
320
+ if (mutation.kind === 'update') {
321
+ const result = await updateRows({ database, schema, ...(maximum !== undefined ? { maxRows: maximum } : {}) }, table, mutation.patch ?? {}, query, mutation.base.prefer,
322
+ // `Prefer: handling`/`max-affected` until g6 parses them.
323
+ c.req.raw.headers.get('prefer'));
324
+ return mutationResponse(c, result, mutation.base.prefer, 200, responseMediaType(c));
325
+ }
326
+ if (mutation.kind === 'replace') {
327
+ const result = await replaceRows({ database, schema, ...(maximum !== undefined ? { maxRows: maximum } : {}) }, table, mutation.rows ?? [], query, mutation.base.prefer);
328
+ // `201` when the row was inserted, `200` when it replaced one
329
+ // (`Response.hs:148-164`, the `PUT` arm).
330
+ const written = writeResponse({
331
+ kind: 'replace',
332
+ table,
333
+ prefer: mutation.base.prefer,
334
+ outcome: { rows: result.rows, count: result.count ?? null, created: result.created === true },
335
+ dialect: database.dialect,
336
+ search,
337
+ });
338
+ return mutationResponse(c, result, mutation.base.prefer, written.status, responseMediaType(c), written);
339
+ }
340
+ const result = await deleteRows({ database, schema, ...(maximum !== undefined ? { maxRows: maximum } : {}) }, table, query, mutation.base.prefer,
341
+ // `Prefer: handling`/`max-affected` until g6 parses them.
342
+ c.req.raw.headers.get('prefer'));
343
+ return mutationResponse(c, result, mutation.base.prefer, 200, responseMediaType(c));
344
+ }
345
+ catch (error) {
346
+ // The parser reports PostgREST error codes itself (`PGRST100`, `PGRST123`,
347
+ // `PGRST200`); anything else is a driver failure.
348
+ if (error instanceof AnygrestError)
349
+ throw error;
350
+ if (error instanceof QueryParseError) {
351
+ throw new AnygrestError(error.status, error.code, error.message, error.details);
352
+ }
353
+ throw translateDbError(error, database.dialect, tableName);
354
+ }
355
+ }
356
+ /**
357
+ * `handling=strict` refuses the tokens of `Prefer` PostgREST does not know:
358
+ * `400 PGRST122` with the invalid tokens joined in `details`
359
+ * (`ApiRequest.hs:122-125`, `Error.hs` `InvalidPreferences`). Without
360
+ * `handling=strict` they are ignored, which is the default.
361
+ */
362
+ function rejectInvalidPreferences(prefer) {
363
+ if (prefer.handling !== 'strict' || !prefer.invalidPreferences?.length)
364
+ return;
365
+ throw new AnygrestError(400, 'PGRST122', 'Invalid preferences given with handling=strict', `Invalid preferences: ${prefer.invalidPreferences.join(', ')}`);
366
+ }
367
+ /**
368
+ * The body of an `/rpc/:name` call: JSON is parsed, form-urlencoded is kept as a
369
+ * string for `callFunction` to read as arguments, and anything else is passed
370
+ * through as the bare text of a single unnamed argument (`RpcBody`).
371
+ */
372
+ async function rpcBody(contentType, text) {
373
+ if (text === null)
374
+ return null;
375
+ const media = (contentType ?? '').split(';')[0].trim().toLowerCase();
376
+ if (media === 'application/x-www-form-urlencoded')
377
+ return text;
378
+ if (media === 'text/plain' || (media !== '' && media !== 'application/json' && !media.endsWith('+json'))) {
379
+ return text;
380
+ }
381
+ if (text.trim() === '')
382
+ return {};
383
+ try {
384
+ return JSON.parse(text);
385
+ }
386
+ catch {
387
+ throw new AnygrestError(400, 'PGRST102', 'Failed to parse request body as JSON');
388
+ }
389
+ }
390
+ /**
391
+ * `GET|POST /rpc/:name` — calls a database function (Supabase `supabase.rpc()`).
392
+ */
393
+ async function handleRpc(c, database, schema, name, protocol) {
394
+ const method = c.req.method.toUpperCase();
395
+ // PostgREST answers `OPTIONS /rpc/:name` without calling the routine.
396
+ if (method === 'OPTIONS')
397
+ return infoResponse(c.req.raw, rpcAllow(schema, name), protocol);
398
+ const url = new URL(c.req.url);
399
+ const search = searchParamsOf(url.search);
400
+ // A routine call takes a JSON, form-urlencoded or bare text body
401
+ // (`callFunction` parses all three), so the raw text is passed through.
402
+ const contentType = c.req.raw.headers.get('content-type');
403
+ const preferHeader = parsePrefer(c.req.raw.headers.get('prefer'));
404
+ // A routine answers JSON only; an `Accept` naming any other type is a `406`
405
+ // (`Plan/Negotiate.hs`, `SchemaCache.hs:1005-1013`).
406
+ const mediaType = negotiateMediaType(c.req.raw.headers.get('accept'), SCALAR_MEDIA_TYPES);
407
+ const singular = mediaType === 'singular-json' || mediaType === 'singular-json-strip';
408
+ const text = method === 'POST' ? await c.req.text() : null;
409
+ const body = method === 'POST' ? await rpcBody(contentType, text) : null;
410
+ const result = await callFunction(database, schema, name, search, body, method, {
411
+ ...(contentType !== null ? { contentType } : {}),
412
+ ...(text !== null ? { text } : {}),
413
+ ...(preferHeader ? { count: preferHeader.count } : {}),
414
+ ...(singular ? { object: true } : {}),
415
+ });
416
+ // The `Content-Range` of a function result follows the same rule as a read
417
+ // (PostgREST `Response.hs` `CallReadPlan`), with the total the routine
418
+ // reports when `count=` was asked for.
419
+ // A table function's result is a page of a larger set, so it is a `206`; a
420
+ // scalar routine answers the whole result (`Response.hs` `CallReadPlan`).
421
+ const setReturning = !result.scalar && (result.total !== null || search.has('limit')
422
+ || search.has('offset'));
423
+ const status = setReturning ? 206 : 200;
424
+ const start = Number(search.get('offset') ?? 0);
425
+ const contentRange = contentRangeH(start, start + result.rows.length - 1, result.total ?? result.rows.length);
426
+ const headers = new Headers({
427
+ 'content-type': contentTypeOf(mediaType),
428
+ 'content-range': contentRange,
429
+ });
430
+ const payload = result.scalar ? scalarValue(result.rows[0]) : result.rows;
431
+ // A routine's body is a JSON document too, so `nulls=stripped` applies.
432
+ const stripped = mediaType === 'array-json-strip' || mediaType === 'singular-json-strip';
433
+ const response = jsonResponse(stripped ? stripNulls(payload) : payload, { status, headers });
434
+ return method === 'HEAD' ? headResponse(response) : response;
435
+ }
436
+ /** The `Allow` methods of a table route; any other method is a `PGRST117`. */
437
+ const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE']);
438
+ /**
439
+ * The PostgREST version anygrest answers as (`postgrest.cabal:3` `version: 17`),
440
+ * which the suite builds its `Warning: 299` agent from (`QuerySpec.hs:1340`).
441
+ */
442
+ const POSTGREST_VERSION = '17';
443
+ /**
444
+ * `PostgRESTvX.Y` for the `Warning: 299` agent, derived like `Version.hs`
445
+ * `prettyVersion`: the first two version components joined by `.`, plus
446
+ * ` (pre-release)` when there is only one component (`isPreRelease`). `App.hs:294`
447
+ * then drops every space, so a pre-release is `PostgRESTv17(pre-release)`.
448
+ */
449
+ function warningAgent(version) {
450
+ const parts = version.split('.');
451
+ const pretty = parts.length === 1 ? `${parts[0]} (pre-release)` : parts.slice(0, 2).join('.');
452
+ return `PostgRESTv${pretty.replaceAll(' ', '')}`;
453
+ }
454
+ const WARNING_AGENT = warningAgent(POSTGREST_VERSION);
455
+ /**
456
+ * `PGRST108` for a legacy target name when `url-use-legacy-target-names` is
457
+ * off (`Plan.hs:1105-1108` `findLegacyUsage`, `QuerySpec.hs:1960-1970`).
458
+ */
459
+ function legacyTargetNameDisabled(name) {
460
+ return new AnygrestError(400, 'PGRST108', `'${name.written}' is not an embedded resource in this request`, 'Target names are not allowed in filters if they have an alias', `Change '${name.written}' to '${name.alias}' in filters, orders or limits.`);
461
+ }
462
+ /**
463
+ * `OPTIONS /:table` — PostgREST's INFO answer (`Response.hs:238`): `200` with
464
+ * `Allow` and `Access-Control-Allow-Origin: *`, for any table name. An unknown
465
+ * table is a `404 PGRST205` once the schema cache is available.
466
+ */
467
+ async function tableInfo(c, database, schema, tableName, protocol) {
468
+ void database;
469
+ if (!schema.table(tableName))
470
+ throw AnygrestError.notFound(tableName, schema.schema);
471
+ return infoResponse(c.req.raw, tableAllow(schema, tableName), protocol);
472
+ }
473
+ /** A scalar function's single column, without its name. */
474
+ function scalarValue(row) {
475
+ if (!row)
476
+ return null;
477
+ const values = Object.values(row);
478
+ return values.length > 0 ? values[0] : null;
479
+ }
480
+ /**
481
+ * Builds the request state stored in the database. Without `jwt` options the
482
+ * connecting role is used and the claims are empty (PostgREST's anon request).
483
+ */
484
+ function buildRequestContext(c, jwt) {
485
+ const headers = headerObject(c.req.raw.headers);
486
+ const claims = c.get('claims') ?? {};
487
+ const requested = typeof claims.role === 'string' ? claims.role : undefined;
488
+ const role = requested ? (jwt?.roles?.[requested] ?? requested) : undefined;
489
+ const url = new URL(c.req.url);
490
+ const timezone = readTimezone(c.req.raw.headers.get('prefer'));
491
+ return {
492
+ claims: role ? claimsWithRole(claims, role) : claims,
493
+ role: role ?? undefined,
494
+ method: c.req.method.toUpperCase(),
495
+ path: `${url.pathname}${url.search}`,
496
+ headers,
497
+ cookies: parseCookies(headers),
498
+ ...(timezone ? { timezone } : {}),
499
+ };
500
+ }
501
+ function createSession(database, options) {
502
+ if (!supportsSessionContext(database.dialect))
503
+ return null;
504
+ return sessionFor(database.dialect, options.context ?? {});
505
+ }
506
+ function createVerifier(jwt) {
507
+ if (!jwt)
508
+ return null;
509
+ if (jwt.verifier)
510
+ return jwt.verifier;
511
+ // Without a secret or public key no token can be verified; requests that
512
+ // send one get PGRST300 (PostgREST's `JwtSecretMissing`) from
513
+ // `authenticateRequest`.
514
+ if (!jwt.secret && !jwt.publicKey)
515
+ return null;
516
+ return createJwtVerifier(verifierOptions(jwt));
517
+ }
518
+ /** The verifier settings for a `jwt` option (`jwt-aud`, `jwt-secret`, role claim). */
519
+ function verifierOptions(jwt) {
520
+ return {
521
+ ...(jwt.secret ? { secret: jwt.secret } : {}),
522
+ ...(jwt.publicKey ? { publicKey: jwt.publicKey } : {}),
523
+ ...(jwt.algorithms ? { algorithms: jwt.algorithms } : {}),
524
+ // `aud` is opt-in: enforced only when `jwt-aud` is configured (`Config.hs:79`).
525
+ ...(jwt.audience ? { audience: jwt.audience } : {}),
526
+ };
527
+ }
528
+ /**
529
+ * Returns the verified claims for the request, throwing the PostgREST errors
530
+ * for a request that lacks a JWT secret (PGRST300), a token (PGRST302) or a
531
+ * valid token (PGRST301/PGRST303). The claims always carry the role the request
532
+ * runs as (`request.jwt.claims.role`, `Auth/Jwt.hs:122-130`).
533
+ */
534
+ function authenticateRequest(request, jwt, verifier) {
535
+ if (!jwt)
536
+ return {};
537
+ const header = request.headers.get('authorization') ?? '';
538
+ const lower = header.toLowerCase();
539
+ if (!lower.startsWith('bearer')) {
540
+ // No bearer token (no header, or a non-Bearer scheme): anonymous request.
541
+ return anonymousClaims(jwt.anonymousRole, jwt.required);
542
+ }
543
+ // A bare `Authorization: Bearer` carries an empty token (`Auth/Jwt.hs:90`).
544
+ const token = header.trim().toLowerCase() === 'bearer' ? '' : header.slice(6).trim();
545
+ const claims = verifyToken(token, jwt, verifier);
546
+ const role = requestRole(claims, jwt.roleClaimKey ?? '$.role', jwt.anonymousRole);
547
+ return claimsWithRole(claims, role);
548
+ }
549
+ /**
550
+ * The verified claims of a token. Without a key no token can be verified, so
551
+ * any token is PGRST300 (`Auth/JwtCache.hs:62-63`). `jwt.required === false`
552
+ * is the legacy "do not require a token" switch: a rejected token then yields
553
+ * no claims (the request runs as the connecting role) instead of a 401.
554
+ */
555
+ function verifyToken(token, jwt, verifier) {
556
+ if (!verifier) {
557
+ if (jwt.required === false)
558
+ return {};
559
+ throw jwtSecretMissing();
560
+ }
561
+ // The custom verifier checks the signature (PostgREST's decoding and claim
562
+ // validation still apply); the built-in one verifies against secret/publicKey.
563
+ const result = decodeJwt(token, verifierOptions(jwt), jwt.verifier);
564
+ if ('error' in result) {
565
+ if (jwt.required === false)
566
+ return {};
567
+ throw jwtRejected(result.error);
568
+ }
569
+ return result.claims;
570
+ }
571
+ function headerObject(headers) {
572
+ const out = {};
573
+ headers.forEach((value, key) => {
574
+ out[key.toLowerCase()] = value;
575
+ });
576
+ return out;
577
+ }
578
+ function readTimezone(prefer) {
579
+ if (!prefer)
580
+ return undefined;
581
+ for (const part of prefer.split(',')) {
582
+ const [key, value] = part.split('=');
583
+ if (key?.trim().toLowerCase() === 'timezone' && value)
584
+ return value.trim();
585
+ }
586
+ return undefined;
587
+ }
588
+ async function readJsonBody(c) {
589
+ const method = c.req.method.toUpperCase();
590
+ if (method === 'GET' || method === 'HEAD' || method === 'DELETE' || method === 'OPTIONS')
591
+ return null;
592
+ const text = await c.req.text();
593
+ if (text.trim() === '')
594
+ return {};
595
+ try {
596
+ return JSON.parse(text);
597
+ }
598
+ catch {
599
+ throw new AnygrestError(400, 'PGRST102', 'Failed to parse request body as JSON');
600
+ }
601
+ }
602
+ /**
603
+ * Rejects a request that names another schema than the one this instance
604
+ * serves. Only PostgreSQL-style servers expose several, anygrest serves one;
605
+ * the header is optional and a matching value changes nothing.
606
+ */
607
+ function assertProfile(headers, served, name) {
608
+ const profile = headers.get(name);
609
+ if (profile === null || profile.trim() === '' || profile.trim() === served)
610
+ return;
611
+ throw AnygrestError.unknownProfile([served]);
612
+ }
613
+ function readResponse(c, result, offset, partial, head, legacy) {
614
+ // `Accept` decides the shape of a read (`Plan/Negotiate.hs`): JSON or one
615
+ // object, and a table read may also be `text/csv` (`Query/SqlFragment.hs:208`,
616
+ // the CSV handler `SchemaCache.hs:1005-1013` adds to every relation). No
617
+ // acceptable type is a `406 PGRST107`.
618
+ const mediaType = responseMediaType(c);
619
+ const single = mediaType === 'singular-json' || mediaType === 'singular-json-strip';
620
+ const csv = mediaType === 'csv';
621
+ const headers = new Headers({ 'content-type': contentTypeOf(mediaType) });
622
+ // A legacy target name (`tasks.order` on `the_tasks:tasks`) is allowed with a
623
+ // `Warning: 299` (`Plan.hs:1099-1108`, `Response.hs`); the config disables it.
624
+ const warning = legacy ? legacyTargetNameWarning(legacy.legacyNames, WARNING_AGENT) : undefined;
625
+ if (warning !== undefined)
626
+ headers.set('warning', warning);
627
+ // Every read carries `Content-Range`; it is only fully known with a count.
628
+ const { status, contentRange } = rangeStatus(offset, result.rows.length, result.count, partial);
629
+ headers.set('content-range', contentRange);
630
+ // `Content-Location` names the resource the page was read from
631
+ // (`Response.hs:69-77`), with the query string canonicalised.
632
+ const url = new URL(c.req.url);
633
+ headers.set('content-location', contentLocation(url.pathname, url.searchParams));
634
+ // `nulls=stripped` drops every `null` field before the document is written
635
+ // (`NullsStripSpec.hs`).
636
+ const rows = mediaType === 'array-json-strip' ? stripNulls(result.rows) : result.rows;
637
+ const response = csv
638
+ ? csvResponse(result.rows, { status, headers })
639
+ : single
640
+ ? result.rows.length === 0
641
+ ? jsonResponse(singularNoRows(), { status: 406, headers })
642
+ : result.rows.length > 1
643
+ ? jsonResponse(singularMultiple(result.rows.length), { status: 406, headers })
644
+ : jsonResponse(mediaType === 'singular-json-strip' ? stripNulls(result.rows[0]) : result.rows[0], { status, headers })
645
+ : jsonResponse(rows, { status, headers });
646
+ return head ? headResponse(response) : response;
647
+ }
648
+ function mutationResponse(c, result, prefer, status, mediaType = 'json', written) {
649
+ const head = c.req.method.toUpperCase() === 'HEAD';
650
+ const singular = mediaType === 'singular-json' || mediaType === 'singular-json-strip';
651
+ const csv = mediaType === 'csv';
652
+ // `nulls=stripped` drops every `null` field of the written rows too
653
+ // (`NullsStripSpec.hs`).
654
+ const rows = mediaType === 'array-json-strip' ? stripNulls(result.rows) : result.rows;
655
+ // The answer keeps the negotiated type even when no representation is sent.
656
+ const headers = new Headers({ 'content-type': contentTypeOf(mediaType) });
657
+ // A `PUT` decides its own status, headers and body (`write-read.ts`).
658
+ if (written) {
659
+ if (written.contentLocation)
660
+ headers.set('content-location', written.contentLocation);
661
+ if (written.location)
662
+ headers.set('location', written.location);
663
+ if (written.contentRange)
664
+ headers.set('content-range', written.contentRange);
665
+ if (written.preferenceApplied)
666
+ headers.set('preference-applied', written.preferenceApplied);
667
+ if (!written.sendBody)
668
+ return new Response(null, { status: written.status, headers });
669
+ const payload = singular ? result.rows[0] : rows;
670
+ const body = singular && mediaType === 'singular-json-strip' && payload !== undefined
671
+ ? stripNulls(payload)
672
+ : payload;
673
+ const response = csv
674
+ ? csvResponse(result.rows, { status: written.status, headers })
675
+ : jsonResponse(body ?? null, { status: written.status, headers });
676
+ return head ? headResponse(response) : response;
677
+ }
678
+ if (prefer.count) {
679
+ // PostgREST renders an empty range as `*` (e.g. `*/*` or `*/0`); a
680
+ // representation-less response (204) always has the empty range and reports
681
+ // the affected row count as its total.
682
+ const range = result.rows.length === 0 ? '*' : `0-${result.rows.length - 1}`;
683
+ const total = result.count === null ? '*' : String(result.count);
684
+ headers.set('content-range', `${range}/${total}`);
685
+ }
686
+ if (prefer.returnRepresentation)
687
+ headers.set('preference-applied', 'return=representation');
688
+ if (prefer.resolution) {
689
+ // PostgREST lists the resolved preference first:
690
+ // `resolution=merge-duplicates, return=representation`.
691
+ const applied = `resolution=${prefer.resolution}`;
692
+ const current = headers.get('preference-applied');
693
+ headers.set('preference-applied', current ? `${applied}, ${current}` : applied);
694
+ }
695
+ // PostgREST reads a singular `Accept` after the write too and answers with
696
+ // the single written row (`PGRST116` when there is none, `PGRST116` when
697
+ // several), even without `Prefer: return=representation`. A `text/csv`
698
+ // `Accept` renders the written rows as CSV.
699
+ const response = singular
700
+ ? result.rows.length === 0
701
+ ? jsonResponse(singularNoRows(), { status: 406, headers })
702
+ : result.rows.length > 1
703
+ ? jsonResponse(singularMultiple(result.rows.length), { status: 406, headers })
704
+ : jsonResponse(mediaType === 'singular-json-strip' ? stripNulls(result.rows[0]) : result.rows[0], { status, headers })
705
+ : prefer.returnRepresentation
706
+ ? csv
707
+ ? csvResponse(result.rows, { status, headers })
708
+ : jsonResponse(rows, { status, headers })
709
+ : new Response(null, { status: 204, headers });
710
+ return head ? headResponse(response) : response;
711
+ }
712
+ function singularNoRows() {
713
+ return {
714
+ code: 'PGRST116',
715
+ details: 'The result contains 0 rows',
716
+ hint: null,
717
+ message: 'Cannot coerce the result to a single JSON object',
718
+ };
719
+ }
720
+ function singularMultiple(rows) {
721
+ return {
722
+ code: 'PGRST116',
723
+ details: `The result contains ${rows} rows`,
724
+ hint: null,
725
+ message: 'Cannot coerce the result to a single JSON object',
726
+ };
727
+ }
728
+ function errorResponse(c, error, debug) {
729
+ if (error instanceof AnygrestError) {
730
+ // `Allow` on a 405, `Content-Range` on a 416, `WWW-Authenticate` on a 401
731
+ // (PostgREST `Error.hs`); the headers are post-processed so the protocol
732
+ // layer (`Vary`, CORS) still merges into them.
733
+ const headers = new Headers({ 'content-type': JSON_CONTENT_TYPE, ...error.headers });
734
+ const response = jsonResponse(error.toJSON(), { status: error.status, headers });
735
+ return c.req.method.toUpperCase() === 'HEAD' ? headResponse(response) : response;
736
+ }
737
+ // A query-string parse error carries PostgREST's own code and status
738
+ // (`PGRST100` and friends); the parser throws it before a handler wraps it
739
+ // (`/rpc/:name` parses its parameters in `callFunction`).
740
+ if (error instanceof QueryParseError || (error instanceof Error && error.name === 'QueryParseError')) {
741
+ const parseError = error;
742
+ const body = { code: parseError.code, details: parseError.details, hint: null, message: parseError.message };
743
+ return jsonResponse(body, { status: parseError.status, headers: { 'content-type': JSON_CONTENT_TYPE } });
744
+ }
745
+ if (debug)
746
+ console.error(error);
747
+ // A driver failure that escaped a handler is translated like any other, so a
748
+ // known SQLSTATE keeps its code and the statement is never echoed. Anything
749
+ // else is PostgREST's opaque 500 (`Error.hs:490-500`).
750
+ const translated = isDbError(error) ? translateDbError(error, dialectOf(c)) : null;
751
+ if (translated) {
752
+ return jsonResponse(translated.toJSON(), {
753
+ status: translated.status,
754
+ headers: { 'content-type': JSON_CONTENT_TYPE, ...translated.headers },
755
+ });
756
+ }
757
+ return jsonResponse({ code: 'PGRST500', details: null, hint: null, message: 'Internal server error' }, { status: 500, headers: { 'content-type': JSON_CONTENT_TYPE } });
758
+ }
759
+ /** True for an error that came from a driver/knex, not from anygrest itself. */
760
+ function isDbError(error) {
761
+ if (!error || typeof error !== 'object')
762
+ return false;
763
+ const err = error;
764
+ return (typeof err.code === 'string' ||
765
+ typeof err.errno === 'number' ||
766
+ typeof err.number === 'number' ||
767
+ typeof err.errorNum === 'number');
768
+ }
769
+ /** The dialect stashed on the context by the routing middleware. */
770
+ function dialectOf(c) {
771
+ return c.get('dialect') ?? 'postgres';
772
+ }
773
+ function buildOpenApi(schema) {
774
+ const properties = {};
775
+ const paths = {};
776
+ for (const table of schema.tables.values()) {
777
+ const columns = {};
778
+ for (const column of table.columns) {
779
+ columns[column.name] = {
780
+ type: mapOpenApiType(column.dataType),
781
+ ...(column.nullable ? { nullable: true } : {}),
782
+ };
783
+ }
784
+ properties[table.name] = {
785
+ type: 'object',
786
+ properties: columns,
787
+ required: table.columns.filter((column) => !column.nullable).map((column) => column.name),
788
+ };
789
+ paths[`/${table.name}`] = {
790
+ get: { operationId: `get${table.name}`, responses: { 200: { description: 'OK' } } },
791
+ post: { operationId: `post${table.name}`, responses: { 201: { description: 'Created' } } },
792
+ patch: { operationId: `patch${table.name}`, responses: { 204: { description: 'No Content' } } },
793
+ delete: { operationId: `delete${table.name}`, responses: { 204: { description: 'Deleted' } } },
794
+ };
795
+ }
796
+ return {
797
+ openapi: '3.0.3',
798
+ info: { title: 'anygrest', version: '0.1.0' },
799
+ paths,
800
+ components: { schemas: properties },
801
+ };
802
+ }
803
+ function mapOpenApiType(dataType) {
804
+ const type = (dataType ?? '').toLowerCase();
805
+ if (/int|serial/.test(type))
806
+ return 'integer';
807
+ if (/real|float|double|numeric|decimal/.test(type))
808
+ return 'number';
809
+ if (/bool/.test(type))
810
+ return 'boolean';
811
+ if (/json/.test(type))
812
+ return 'object';
813
+ if (/date|time/.test(type))
814
+ return 'string';
815
+ if (/blob|binary|bytea/.test(type))
816
+ return 'string';
817
+ return 'string';
818
+ }
819
+ //# sourceMappingURL=app.js.map