@revenexx/app-sdk 0.6.0 → 0.7.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.
- package/README.md +90 -0
- package/dist/chunk-2BOFXTTC.js +195 -0
- package/dist/chunk-2BOFXTTC.js.map +1 -0
- package/dist/errors-Co6JSseO.d.cts +276 -0
- package/dist/errors-Co6JSseO.d.ts +276 -0
- package/dist/index.cjs +213 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +41 -6
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +177 -11
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +41 -15
- package/dist/router/index.d.ts +41 -15
- package/dist/router/index.js +32 -7
- package/dist/router/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-WJ7QJ3NU.js +0 -41
- package/dist/chunk-WJ7QJ3NU.js.map +0 -1
- package/dist/errors-DrxYD96C.d.cts +0 -111
- package/dist/errors-DrxYD96C.d.ts +0 -111
package/dist/router/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Q as Query, R as Row, P as Page } from '../errors-
|
|
2
|
-
export { H as HttpError,
|
|
1
|
+
import { h as SettingsDefaults, f as ReadOptions, g as ResolvedSettings, k as SettingsSnapshot, j as SettingsReader, i as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-Co6JSseO.cjs';
|
|
2
|
+
export { D as DEFAULT_GATEWAY_ENDPOINT, a as DEFAULT_SETTINGS_ERROR_TTL_MS, b as DEFAULT_SETTINGS_TIMEOUT_MS, c as DEFAULT_SETTINGS_TTL_MS, H as HttpError, e as HttpErrorOptions, l as SettingsSource, o as badRequest, p as conflict, m as createSettings, q as forbidden, n as isHttpError, r as notFound } from '../errors-Co6JSseO.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Minimal HTTP router for revenexx App functions.
|
|
@@ -17,6 +17,7 @@ export { H as HttpError, b as HttpErrorOptions, c as badRequest, d as conflict,
|
|
|
17
17
|
* `/markets/{id}` regardless of registration order. Path templates use the
|
|
18
18
|
* same `{param}` syntax as manifest capability routes (`:param` also works).
|
|
19
19
|
*/
|
|
20
|
+
|
|
20
21
|
interface FnRequest {
|
|
21
22
|
method?: string;
|
|
22
23
|
path?: string;
|
|
@@ -39,7 +40,7 @@ interface FnContext {
|
|
|
39
40
|
error?: (message: string) => void;
|
|
40
41
|
}
|
|
41
42
|
/** Per-request context handed to route handlers. */
|
|
42
|
-
interface RouteContext {
|
|
43
|
+
interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {
|
|
43
44
|
/** Raw invocation context (escape hatch). */
|
|
44
45
|
ctx: FnContext;
|
|
45
46
|
req: FnRequest;
|
|
@@ -61,10 +62,18 @@ interface RouteContext {
|
|
|
61
62
|
log(message: string): void;
|
|
62
63
|
/** Respond with JSON. Returning `c.json(...)` ends the request. */
|
|
63
64
|
json(data: unknown, statusCode?: number): unknown;
|
|
65
|
+
/**
|
|
66
|
+
* This tenant's effective settings for the app, resolved for the request's
|
|
67
|
+
* market. Cached and fail-open — see `createSettings`. Available on every
|
|
68
|
+
* app; pass `settings` to `createApp` to declare defaults and get them typed.
|
|
69
|
+
*/
|
|
70
|
+
settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;
|
|
71
|
+
/** The same read, plus market/masked/provenance. */
|
|
72
|
+
settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;
|
|
64
73
|
}
|
|
65
|
-
type Handler = (c: RouteContext) => unknown | Promise<unknown>;
|
|
74
|
+
type Handler<D extends SettingsDefaults = SettingsDefaults> = (c: RouteContext<D>) => unknown | Promise<unknown>;
|
|
66
75
|
|
|
67
|
-
interface AppOptions {
|
|
76
|
+
interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {
|
|
68
77
|
/** App name reported on the built-in health route. */
|
|
69
78
|
name?: string;
|
|
70
79
|
/**
|
|
@@ -74,23 +83,40 @@ interface AppOptions {
|
|
|
74
83
|
health?: boolean;
|
|
75
84
|
/** Extra payload merged into the health response. */
|
|
76
85
|
healthExtra?: () => Record<string, unknown>;
|
|
86
|
+
/**
|
|
87
|
+
* App settings behind `c.settings()`. Pass the defaults your settings.json
|
|
88
|
+
* declares — they type the resolved object and are what the app runs on if
|
|
89
|
+
* the settings service is unreachable:
|
|
90
|
+
*
|
|
91
|
+
* createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })
|
|
92
|
+
*
|
|
93
|
+
* `app` defaults to this app's `name`. Pass a reader built with
|
|
94
|
+
* `createSettings` instead when you want to share it with code outside the
|
|
95
|
+
* router. Omit entirely and `c.settings()` still works — it just has no
|
|
96
|
+
* declared defaults to fall back on.
|
|
97
|
+
*/
|
|
98
|
+
settings?: Omit<SettingsOptions<D>, 'app'> & {
|
|
99
|
+
app?: string;
|
|
100
|
+
} | SettingsReader<D>;
|
|
77
101
|
}
|
|
78
|
-
interface App {
|
|
79
|
-
get(template: string, handler: Handler): App
|
|
80
|
-
post(template: string, handler: Handler): App
|
|
81
|
-
put(template: string, handler: Handler): App
|
|
82
|
-
patch(template: string, handler: Handler): App
|
|
83
|
-
delete(template: string, handler: Handler): App
|
|
84
|
-
on(method: string, template: string, handler: Handler): App
|
|
102
|
+
interface App<D extends SettingsDefaults = SettingsDefaults> {
|
|
103
|
+
get(template: string, handler: Handler<D>): App<D>;
|
|
104
|
+
post(template: string, handler: Handler<D>): App<D>;
|
|
105
|
+
put(template: string, handler: Handler<D>): App<D>;
|
|
106
|
+
patch(template: string, handler: Handler<D>): App<D>;
|
|
107
|
+
delete(template: string, handler: Handler<D>): App<D>;
|
|
108
|
+
on(method: string, template: string, handler: Handler<D>): App<D>;
|
|
85
109
|
/** Registered routes (e.g. for docs or the health response). */
|
|
86
110
|
routes(): {
|
|
87
111
|
method: string;
|
|
88
112
|
path: string;
|
|
89
113
|
}[];
|
|
114
|
+
/** The settings reader backing `c.settings()` (e.g. to clear its cache). */
|
|
115
|
+
settings: SettingsReader<D>;
|
|
90
116
|
/** Build the function entrypoint: `module.exports = app.handler()`. */
|
|
91
117
|
handler(): (context: FnContext) => Promise<unknown>;
|
|
92
118
|
}
|
|
93
|
-
declare function createApp(options?: AppOptions): App
|
|
119
|
+
declare function createApp<D extends SettingsDefaults = SettingsDefaults>(options?: AppOptions<D>): App<D>;
|
|
94
120
|
|
|
95
121
|
/**
|
|
96
122
|
* CRUD route mounting: wire a generated entity client to REST routes in one
|
|
@@ -151,6 +177,6 @@ interface CrudOptions {
|
|
|
151
177
|
/** Restrict which routes are mounted (default: all five). */
|
|
152
178
|
only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];
|
|
153
179
|
}
|
|
154
|
-
declare function mountCrud(app: App
|
|
180
|
+
declare function mountCrud<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: CrudOptions): App<D>;
|
|
155
181
|
|
|
156
|
-
export { type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, type RepoLike, type RouteContext, createApp, mountCrud };
|
|
182
|
+
export { type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, ReadOptions, type RepoLike, ResolvedSettings, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, createApp, mountCrud };
|
package/dist/router/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Q as Query, R as Row, P as Page } from '../errors-
|
|
2
|
-
export { H as HttpError,
|
|
1
|
+
import { h as SettingsDefaults, f as ReadOptions, g as ResolvedSettings, k as SettingsSnapshot, j as SettingsReader, i as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-Co6JSseO.js';
|
|
2
|
+
export { D as DEFAULT_GATEWAY_ENDPOINT, a as DEFAULT_SETTINGS_ERROR_TTL_MS, b as DEFAULT_SETTINGS_TIMEOUT_MS, c as DEFAULT_SETTINGS_TTL_MS, H as HttpError, e as HttpErrorOptions, l as SettingsSource, o as badRequest, p as conflict, m as createSettings, q as forbidden, n as isHttpError, r as notFound } from '../errors-Co6JSseO.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Minimal HTTP router for revenexx App functions.
|
|
@@ -17,6 +17,7 @@ export { H as HttpError, b as HttpErrorOptions, c as badRequest, d as conflict,
|
|
|
17
17
|
* `/markets/{id}` regardless of registration order. Path templates use the
|
|
18
18
|
* same `{param}` syntax as manifest capability routes (`:param` also works).
|
|
19
19
|
*/
|
|
20
|
+
|
|
20
21
|
interface FnRequest {
|
|
21
22
|
method?: string;
|
|
22
23
|
path?: string;
|
|
@@ -39,7 +40,7 @@ interface FnContext {
|
|
|
39
40
|
error?: (message: string) => void;
|
|
40
41
|
}
|
|
41
42
|
/** Per-request context handed to route handlers. */
|
|
42
|
-
interface RouteContext {
|
|
43
|
+
interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {
|
|
43
44
|
/** Raw invocation context (escape hatch). */
|
|
44
45
|
ctx: FnContext;
|
|
45
46
|
req: FnRequest;
|
|
@@ -61,10 +62,18 @@ interface RouteContext {
|
|
|
61
62
|
log(message: string): void;
|
|
62
63
|
/** Respond with JSON. Returning `c.json(...)` ends the request. */
|
|
63
64
|
json(data: unknown, statusCode?: number): unknown;
|
|
65
|
+
/**
|
|
66
|
+
* This tenant's effective settings for the app, resolved for the request's
|
|
67
|
+
* market. Cached and fail-open — see `createSettings`. Available on every
|
|
68
|
+
* app; pass `settings` to `createApp` to declare defaults and get them typed.
|
|
69
|
+
*/
|
|
70
|
+
settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;
|
|
71
|
+
/** The same read, plus market/masked/provenance. */
|
|
72
|
+
settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;
|
|
64
73
|
}
|
|
65
|
-
type Handler = (c: RouteContext) => unknown | Promise<unknown>;
|
|
74
|
+
type Handler<D extends SettingsDefaults = SettingsDefaults> = (c: RouteContext<D>) => unknown | Promise<unknown>;
|
|
66
75
|
|
|
67
|
-
interface AppOptions {
|
|
76
|
+
interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {
|
|
68
77
|
/** App name reported on the built-in health route. */
|
|
69
78
|
name?: string;
|
|
70
79
|
/**
|
|
@@ -74,23 +83,40 @@ interface AppOptions {
|
|
|
74
83
|
health?: boolean;
|
|
75
84
|
/** Extra payload merged into the health response. */
|
|
76
85
|
healthExtra?: () => Record<string, unknown>;
|
|
86
|
+
/**
|
|
87
|
+
* App settings behind `c.settings()`. Pass the defaults your settings.json
|
|
88
|
+
* declares — they type the resolved object and are what the app runs on if
|
|
89
|
+
* the settings service is unreachable:
|
|
90
|
+
*
|
|
91
|
+
* createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })
|
|
92
|
+
*
|
|
93
|
+
* `app` defaults to this app's `name`. Pass a reader built with
|
|
94
|
+
* `createSettings` instead when you want to share it with code outside the
|
|
95
|
+
* router. Omit entirely and `c.settings()` still works — it just has no
|
|
96
|
+
* declared defaults to fall back on.
|
|
97
|
+
*/
|
|
98
|
+
settings?: Omit<SettingsOptions<D>, 'app'> & {
|
|
99
|
+
app?: string;
|
|
100
|
+
} | SettingsReader<D>;
|
|
77
101
|
}
|
|
78
|
-
interface App {
|
|
79
|
-
get(template: string, handler: Handler): App
|
|
80
|
-
post(template: string, handler: Handler): App
|
|
81
|
-
put(template: string, handler: Handler): App
|
|
82
|
-
patch(template: string, handler: Handler): App
|
|
83
|
-
delete(template: string, handler: Handler): App
|
|
84
|
-
on(method: string, template: string, handler: Handler): App
|
|
102
|
+
interface App<D extends SettingsDefaults = SettingsDefaults> {
|
|
103
|
+
get(template: string, handler: Handler<D>): App<D>;
|
|
104
|
+
post(template: string, handler: Handler<D>): App<D>;
|
|
105
|
+
put(template: string, handler: Handler<D>): App<D>;
|
|
106
|
+
patch(template: string, handler: Handler<D>): App<D>;
|
|
107
|
+
delete(template: string, handler: Handler<D>): App<D>;
|
|
108
|
+
on(method: string, template: string, handler: Handler<D>): App<D>;
|
|
85
109
|
/** Registered routes (e.g. for docs or the health response). */
|
|
86
110
|
routes(): {
|
|
87
111
|
method: string;
|
|
88
112
|
path: string;
|
|
89
113
|
}[];
|
|
114
|
+
/** The settings reader backing `c.settings()` (e.g. to clear its cache). */
|
|
115
|
+
settings: SettingsReader<D>;
|
|
90
116
|
/** Build the function entrypoint: `module.exports = app.handler()`. */
|
|
91
117
|
handler(): (context: FnContext) => Promise<unknown>;
|
|
92
118
|
}
|
|
93
|
-
declare function createApp(options?: AppOptions): App
|
|
119
|
+
declare function createApp<D extends SettingsDefaults = SettingsDefaults>(options?: AppOptions<D>): App<D>;
|
|
94
120
|
|
|
95
121
|
/**
|
|
96
122
|
* CRUD route mounting: wire a generated entity client to REST routes in one
|
|
@@ -151,6 +177,6 @@ interface CrudOptions {
|
|
|
151
177
|
/** Restrict which routes are mounted (default: all five). */
|
|
152
178
|
only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];
|
|
153
179
|
}
|
|
154
|
-
declare function mountCrud(app: App
|
|
180
|
+
declare function mountCrud<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: CrudOptions): App<D>;
|
|
155
181
|
|
|
156
|
-
export { type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, type RepoLike, type RouteContext, createApp, mountCrud };
|
|
182
|
+
export { type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, ReadOptions, type RepoLike, ResolvedSettings, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, createApp, mountCrud };
|
package/dist/router/index.js
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
+
DEFAULT_GATEWAY_ENDPOINT,
|
|
3
|
+
DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
4
|
+
DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
5
|
+
DEFAULT_SETTINGS_TTL_MS,
|
|
6
|
+
EMPTY_UPDATE_MESSAGE,
|
|
2
7
|
HttpError,
|
|
3
8
|
badRequest,
|
|
4
9
|
conflict,
|
|
10
|
+
createSettings,
|
|
5
11
|
forbidden,
|
|
6
12
|
isHttpError,
|
|
7
|
-
notFound
|
|
8
|
-
|
|
13
|
+
notFound,
|
|
14
|
+
updateFields
|
|
15
|
+
} from "../chunk-2BOFXTTC.js";
|
|
9
16
|
import "../chunk-TUTGCI5D.js";
|
|
10
17
|
|
|
11
18
|
// src/router/router.ts
|
|
@@ -78,11 +85,19 @@ function parseQuery(req) {
|
|
|
78
85
|
return out;
|
|
79
86
|
}
|
|
80
87
|
for (const [k, v] of Object.entries(req.query ?? {})) {
|
|
81
|
-
|
|
82
|
-
|
|
88
|
+
const raw = typeof v === "string" ? v : v == null ? null : String(v);
|
|
89
|
+
if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);
|
|
83
90
|
}
|
|
84
91
|
return out;
|
|
85
92
|
}
|
|
93
|
+
function decodeComponent(value) {
|
|
94
|
+
try {
|
|
95
|
+
return decodeURIComponent(value.replace(/\+/g, " "));
|
|
96
|
+
} catch {
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
var isSettingsReader = (value) => typeof value.get === "function";
|
|
86
101
|
var tracer = trace.getTracer("@revenexx/app-sdk");
|
|
87
102
|
var headerGetter = {
|
|
88
103
|
keys: (carrier) => Object.keys(carrier ?? {}),
|
|
@@ -91,7 +106,9 @@ var headerGetter = {
|
|
|
91
106
|
function createApp(options = {}) {
|
|
92
107
|
const routes = [];
|
|
93
108
|
const health = options.health !== false;
|
|
109
|
+
const settings = options.settings && isSettingsReader(options.settings) ? options.settings : createSettings({ app: options.name, ...options.settings ?? {} });
|
|
94
110
|
const app = {
|
|
111
|
+
settings,
|
|
95
112
|
get: (t, h) => app.on("GET", t, h),
|
|
96
113
|
post: (t, h) => app.on("POST", t, h),
|
|
97
114
|
put: (t, h) => app.on("PUT", t, h),
|
|
@@ -186,7 +203,11 @@ function createApp(options = {}) {
|
|
|
186
203
|
contextToken,
|
|
187
204
|
header: (name) => headerOf(headers, name),
|
|
188
205
|
log,
|
|
189
|
-
json: (data, statusCode = 200) => res.json(data, statusCode)
|
|
206
|
+
json: (data, statusCode = 200) => res.json(data, statusCode),
|
|
207
|
+
// The market rides on the request, so a market-scoped setting
|
|
208
|
+
// resolves for the market this call is for — no argument needed.
|
|
209
|
+
settings: (readOptions) => settings.get(c, readOptions),
|
|
210
|
+
settingsSnapshot: (readOptions) => settings.load(c, readOptions)
|
|
190
211
|
};
|
|
191
212
|
return await matched.route.handler(c);
|
|
192
213
|
} catch (err) {
|
|
@@ -302,8 +323,7 @@ function mountCrud(app, repo, opts) {
|
|
|
302
323
|
if (enabled.has("update")) {
|
|
303
324
|
app.put(idTemplate, async (c) => {
|
|
304
325
|
const { id } = await fetchOwned(repo, c, opts);
|
|
305
|
-
|
|
306
|
-
if (fields.length === 0) throw new HttpError(400, "request body must contain at least one field to update");
|
|
326
|
+
if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE);
|
|
307
327
|
const patch = { ...c.body, ...parentWhere(c, opts.parent) };
|
|
308
328
|
return c.json(await repo.update(id, patch));
|
|
309
329
|
});
|
|
@@ -318,10 +338,15 @@ function mountCrud(app, repo, opts) {
|
|
|
318
338
|
return app;
|
|
319
339
|
}
|
|
320
340
|
export {
|
|
341
|
+
DEFAULT_GATEWAY_ENDPOINT,
|
|
342
|
+
DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
343
|
+
DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
344
|
+
DEFAULT_SETTINGS_TTL_MS,
|
|
321
345
|
HttpError,
|
|
322
346
|
badRequest,
|
|
323
347
|
conflict,
|
|
324
348
|
createApp,
|
|
349
|
+
createSettings,
|
|
325
350
|
forbidden,
|
|
326
351
|
isHttpError,
|
|
327
352
|
mountCrud,
|
package/dist/router/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/router/router.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n}\n\nexport type Handler = (c: RouteContext) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n for (const [k, v] of Object.entries(req.query ?? {})) {\n if (typeof v === 'string') out[k] = v;\n else if (v != null) out[k] = String(v);\n }\n return out;\n}\n\nexport interface AppOptions {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n}\n\nexport interface App {\n get(template: string, handler: Handler): App;\n post(template: string, handler: Handler): App;\n put(template: string, handler: Handler): App;\n patch(template: string, handler: Handler): App;\n delete(template: string, handler: Handler): App;\n on(method: string, template: string, handler: Handler): App;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp(options: AppOptions = {}): App {\n const routes: CompiledRoute[] = [];\n const health = options.health !== false;\n\n const app: App = {\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n };\n\n return await matched.route.handler(c);\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`);\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud(app: App, repo: RepoLike, opts: CrudOptions): App {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n if (opts.columns && k in opts.columns) where[k] = v;\n }\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. Passing it\n // through produced an empty PostgREST patch, which surfaced as a 500 with\n // a raw Node message (\"The first argument must be of type string or an\n // instance of Buffer … Received undefined\") — an internal serializer\n // fault reported as a server error for what is a malformed request. The\n // guard reads c.body, not the merged patch: with a nested parent the\n // merge always carries the FK, so the patch is never literally empty.\n const fields = c.body && typeof c.body === 'object' && !Array.isArray(c.body) ? Object.keys(c.body) : [];\n if (fields.length === 0) throw new HttpError(400, 'request body must contain at least one field to update');\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n"],"mappings":";;;;;;;;;;;AAiBA;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAgFP,IAAM,YAAY,CAAC,SAA2B,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAE5E,SAAS,gBAAgB,UAA6B;AACpD,SAAO,UAAU,QAAQ,EAAE,IAAI,CAAC,QAAQ;AACtC,UAAM,SAAS,iCAAiC,KAAK,GAAG;AACxD,QAAI,OAAQ,QAAO,EAAE,OAAO,OAAO,CAAC,EAAE;AACtC,QAAI,IAAI,WAAW,GAAG,KAAK,IAAI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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/router/router.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { createSettings } from '../settings.js';\nimport type {\n ReadOptions,\n ResolvedSettings,\n SettingsDefaults,\n SettingsOptions,\n SettingsReader,\n SettingsSnapshot,\n} from '../settings.js';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n /**\n * This tenant's effective settings for the app, resolved for the request's\n * market. Cached and fail-open — see `createSettings`. Available on every\n * app; pass `settings` to `createApp` to declare defaults and get them typed.\n */\n settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n}\n\nexport type Handler<D extends SettingsDefaults = SettingsDefaults> = (\n c: RouteContext<D>,\n) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute<D extends SettingsDefaults> {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler<D>;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n // The runtime hands `req.query` through UNDECODED — measured in production\n // against every one of the 13 apps after 0.6.0 shipped:\n //\n // GET /v1/customers/organizations?name=ACME%20GmbH\n // -> returned 0, filter {\"name\":\"ACME%20GmbH\"} (the row 'ACME GmbH' exists)\n //\n // 0.6.0 only decoded when the query rode on `req.path`, which this runtime\n // does not do, so the fix was inert. Decode here as well; each source is\n // still decoded exactly once, because the branch above returns.\n for (const [k, v] of Object.entries(req.query ?? {})) {\n const raw = typeof v === 'string' ? v : v == null ? null : String(v);\n if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);\n }\n return out;\n}\n\n/**\n * Percent-decode one query key or value, treating `+` as a space the way a\n * form-encoded query requires.\n *\n * Falls back to the input when it is not valid percent-encoding — a lone `%`\n * is a legitimate character in a search term, and throwing a URIError on it\n * would turn a harmless filter into a 500.\n */\nfunction decodeComponent(value: string): string {\n try {\n return decodeURIComponent(value.replace(/\\+/g, ' '));\n } catch {\n return value;\n }\n}\n\nexport interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n /**\n * App settings behind `c.settings()`. Pass the defaults your settings.json\n * declares — they type the resolved object and are what the app runs on if\n * the settings service is unreachable:\n *\n * createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })\n *\n * `app` defaults to this app's `name`. Pass a reader built with\n * `createSettings` instead when you want to share it with code outside the\n * router. Omit entirely and `c.settings()` still works — it just has no\n * declared defaults to fall back on.\n */\n settings?: Omit<SettingsOptions<D>, 'app'> & { app?: string } | SettingsReader<D>;\n}\n\nexport interface App<D extends SettingsDefaults = SettingsDefaults> {\n get(template: string, handler: Handler<D>): App<D>;\n post(template: string, handler: Handler<D>): App<D>;\n put(template: string, handler: Handler<D>): App<D>;\n patch(template: string, handler: Handler<D>): App<D>;\n delete(template: string, handler: Handler<D>): App<D>;\n on(method: string, template: string, handler: Handler<D>): App<D>;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** The settings reader backing `c.settings()` (e.g. to clear its cache). */\n settings: SettingsReader<D>;\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst isSettingsReader = <D extends SettingsDefaults>(\n value: NonNullable<AppOptions<D>['settings']>,\n): value is SettingsReader<D> => typeof (value as SettingsReader<D>).get === 'function';\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp<D extends SettingsDefaults = SettingsDefaults>(options: AppOptions<D> = {}): App<D> {\n const routes: CompiledRoute<D>[] = [];\n const health = options.health !== false;\n // The app knows its own name, so the settings reader does not have to be told\n // it. One reader per app, created once: the cache lives on it.\n const settings: SettingsReader<D> =\n options.settings && isSettingsReader(options.settings)\n ? options.settings\n : createSettings<D>({ app: options.name, ...(options.settings ?? {}) });\n\n const app: App<D> = {\n settings,\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute<D>; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext<D> = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n // The market rides on the request, so a market-scoped setting\n // resolves for the market this call is for — no argument needed.\n settings: (readOptions) => settings.get(c, readOptions),\n settingsSnapshot: (readOptions) => settings.load(c, readOptions),\n };\n\n return await matched.route.handler(c);\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\nimport { EMPTY_UPDATE_MESSAGE, updateFields } from '../patch.js';\nimport type { SettingsDefaults } from '../settings.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`);\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: CrudOptions,\n): App<D> {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n if (opts.columns && k in opts.columns) where[k] = v;\n }\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. The rule itself\n // lives in ../patch.ts and is enforced by the data client, so Apps that\n // hand-write their PUT handler get it too; this check stays because it is\n // the only one that can see the *body* rather than the merged patch —\n // with a nested parent the merge always carries the FK, so the patch is\n // never literally empty — and because it answers without a round trip.\n if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE);\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAmGP,IAAM,YAAY,CAAC,SAA2B,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAE5E,SAAS,gBAAgB,UAA6B;AACpD,SAAO,UAAU,QAAQ,EAAE,IAAI,CAAC,QAAQ;AACtC,UAAM,SAAS,iCAAiC,KAAK,GAAG;AACxD,QAAI,OAAQ,QAAO,EAAE,OAAO,OAAO,CAAC,EAAE;AACtC,QAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,EAAG,QAAO,EAAE,OAAO,IAAI,MAAM,CAAC,EAAE;AACxE,WAAO,EAAE,KAAK,IAAI;AAAA,EACpB,CAAC;AACH;AAEA,SAAS,cAAc,UAAqB,SAAkD;AAC5F,MAAI,SAAS,WAAW,QAAQ,OAAQ,QAAO;AAC/C,QAAM,SAAiC,CAAC;AACxC,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,IAAI,SAAS,CAAC;AACpB,QAAI,EAAE,MAAO,QAAO,EAAE,KAAK,IAAI,mBAAmB,QAAQ,CAAC,CAAE;AAAA,aACpD,EAAE,QAAQ,QAAQ,CAAC,EAAG,QAAO;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,SAAS,SAA6C,MAAsB;AACnF,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,SAAS,QAAQ,IAAI,KAAK,QAAQ,KAAK,YAAY,CAAC;AAC1D,MAAI,OAAO,WAAW,SAAU,QAAO;AACvC,QAAM,OAAO,KAAK,YAAY;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EAAE,MAAM,GAAG,YAAY,GAAG,KAAK,MAAM,EAAE;AACzD,aAAO,EAAE,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG,GAAG;AAAA,IAC5C,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ,IAAI,KAAK,GAAG;AACtB,QAAI,IAAI,YAAY,OAAO,MAAM;AAC/B,YAAM,EAAE,IAAI,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAC9C,aAAO,EAAE,KAAK,GAAG;AAAA,IACnB,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ,IAAI,QAAQ,GAAG;AACzB,QAAI,IAAI,YAAY,OAAO,MAAM;AAC/B,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAO7C,UAAI,aAAa,EAAE,IAAI,EAAE,WAAW,EAAG,OAAM,IAAI,UAAU,KAAK,oBAAoB;AAEpF,YAAM,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,GAAG,KAAK,MAAM,EAAE;AAC1D,aAAO,EAAE,KAAK,MAAM,KAAK,OAAO,IAAI,KAAK,CAAC;AAAA,IAC5C,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ,IAAI,QAAQ,GAAG;AACzB,QAAI,OAAO,YAAY,OAAO,MAAM;AAClC,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAC7C,YAAM,KAAK,OAAO,EAAE;AACpB,aAAO,EAAE,KAAK,EAAE,SAAS,MAAM,GAAG,CAAC;AAAA,IACrC,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["items"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@revenexx/app-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Typed data client + HTTP router for revenexx Apps. Swappable adapters (mock | remote | runtime) so the same App code runs against in-memory fixtures locally and the real data plane in production.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/dist/chunk-WJ7QJ3NU.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
// src/errors.ts
|
|
2
|
-
var HttpError = class extends Error {
|
|
3
|
-
status;
|
|
4
|
-
details;
|
|
5
|
-
code;
|
|
6
|
-
serverDetail;
|
|
7
|
-
/**
|
|
8
|
-
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
9
|
-
* bundles, so an error thrown by the data client and caught by the router is
|
|
10
|
-
* an instance of a *different* copy of this class — `instanceof` would be
|
|
11
|
-
* false. Everything checks this flag via `isHttpError` instead.
|
|
12
|
-
*/
|
|
13
|
-
__isHttpError = true;
|
|
14
|
-
constructor(status, message, details, options = {}) {
|
|
15
|
-
super(message);
|
|
16
|
-
this.name = "HttpError";
|
|
17
|
-
this.status = status;
|
|
18
|
-
if (details !== void 0) this.details = details;
|
|
19
|
-
if (options.code !== void 0) this.code = options.code;
|
|
20
|
-
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
function isHttpError(err) {
|
|
24
|
-
if (!err || typeof err !== "object") return false;
|
|
25
|
-
const e = err;
|
|
26
|
-
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
27
|
-
}
|
|
28
|
-
var notFound = (message = "not found") => new HttpError(404, message);
|
|
29
|
-
var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
|
|
30
|
-
var forbidden = (message = "forbidden") => new HttpError(403, message);
|
|
31
|
-
var conflict = (message = "conflict") => new HttpError(409, message);
|
|
32
|
-
|
|
33
|
-
export {
|
|
34
|
-
HttpError,
|
|
35
|
-
isHttpError,
|
|
36
|
-
notFound,
|
|
37
|
-
badRequest,
|
|
38
|
-
forbidden,
|
|
39
|
-
conflict
|
|
40
|
-
};
|
|
41
|
-
//# sourceMappingURL=chunk-WJ7QJ3NU.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\nexport const notFound = (message = 'not found'): HttpError => new HttpError(404, message);\nexport const badRequest = (message = 'bad request', details?: unknown): HttpError =>\n new HttpError(400, message, details);\nexport const forbidden = (message = 'forbidden'): HttpError => new HttpError(403, message);\nexport const conflict = (message = 'conflict'): HttpError => new HttpError(409, message);\n"],"mappings":";AA0BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAgB;AAAA,EAEzB,YAAY,QAAgB,SAAiB,SAAmB,UAA4B,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,QAAI,YAAY,OAAW,MAAK,UAAU;AAC1C,QAAI,QAAQ,SAAS,OAAW,MAAK,OAAO,QAAQ;AACpD,QAAI,QAAQ,iBAAiB,OAAW,MAAK,eAAe,QAAQ;AAAA,EACtE;AACF;AAGO,SAAS,YAAY,KAAgC;AAC1D,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI;AACV,SAAO,EAAE,kBAAkB,QAAS,EAAE,SAAS,eAAe,OAAO,EAAE,WAAW;AACpF;AAEO,IAAM,WAAW,CAAC,UAAU,gBAA2B,IAAI,UAAU,KAAK,OAAO;AACjF,IAAM,aAAa,CAAC,UAAU,eAAe,YAClD,IAAI,UAAU,KAAK,SAAS,OAAO;AAC9B,IAAM,YAAY,CAAC,UAAU,gBAA2B,IAAI,UAAU,KAAK,OAAO;AAClF,IAAM,WAAW,CAAC,UAAU,eAA0B,IAAI,UAAU,KAAK,OAAO;","names":[]}
|