@revenexx/app-sdk 0.7.2 → 0.8.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.
@@ -46,12 +46,70 @@ interface Page<T = Row> {
46
46
  limit?: number;
47
47
  offset?: number;
48
48
  }
49
+ /**
50
+ * One event the App may fire itself — a `manifest.events.emits[]` entry
51
+ * declared `trigger: "app"`. Generated into the App's client alongside the
52
+ * entity descriptors.
53
+ */
54
+ interface EventDescriptor {
55
+ /** Vendor-scoped topic the platform publishes, e.g. `revenexx.inventories.stock.low`. */
56
+ topic: string;
57
+ /** The declared example payload, as it appears in the tenant's event catalog. */
58
+ sample?: Row;
59
+ /** Optional JSON Schema for `data`, from the manifest's `data_schema`. */
60
+ schema?: Record<string, unknown>;
61
+ }
62
+ /** Per-emit options. Everything here is optional; `data` carries the payload. */
63
+ interface EmitOptions {
64
+ /**
65
+ * The resource this event is about, so a realtime consumer can address one
66
+ * row instead of a collection. An opaque channel segment
67
+ * (`[A-Za-z0-9][A-Za-z0-9_-]{0,63}`), never a transformed id — the platform
68
+ * rejects an out-of-class value rather than reshaping it. Omit for an event
69
+ * that addresses a collection.
70
+ */
71
+ topicId?: string | null;
72
+ /** Free-form metadata. The platform adds `source`, `vendor` and `app`. */
73
+ metadata?: Row;
74
+ /**
75
+ * Idempotency key. An App has no transaction — every call is its own request
76
+ * — so a process can die between its write and its emit. Pass a
77
+ * deterministic id and the retry is a no-op instead of a duplicate on the
78
+ * bus. Omit it for an event nothing will ever re-attempt.
79
+ */
80
+ id?: string;
81
+ }
82
+ /** What the platform answers: the event's id and the topic it went out on. */
83
+ interface EmitResult {
84
+ id: string;
85
+ topic: string;
86
+ }
87
+ /** The routine to call and which declared event is being fired. */
88
+ interface EmitTarget {
89
+ /** The generated per-App routine, e.g. `revenexx__inventories__emit`. */
90
+ fn: string;
91
+ /** The declared event name, e.g. `stock.low`. */
92
+ name: string;
93
+ descriptor: EventDescriptor;
94
+ }
95
+ /** One recorded emit. Only the `mock` adapter keeps these. */
96
+ interface EmittedEvent {
97
+ event: string;
98
+ topic: string;
99
+ data: Row;
100
+ options: EmitOptions;
101
+ result: EmitResult;
102
+ }
49
103
  /**
50
104
  * The data-plane contract. Implement this to add a new backend (e.g. GraphQL,
51
105
  * a local SQLite file) and register it with `registerAdapter`.
52
106
  *
53
107
  * `page` is optional: adapters that can report a total (PostgREST `count=exact`,
54
108
  * an in-memory store) implement it; others fall back to `list` only.
109
+ *
110
+ * `emit` and `emitted` are optional for the same reason — an adapter that
111
+ * cannot reach the event bus simply does not implement them, and the entity
112
+ * client says so rather than pretending the event went out.
55
113
  */
56
114
  interface Adapter {
57
115
  readonly kind: string;
@@ -61,6 +119,9 @@ interface Adapter {
61
119
  update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
62
120
  remove(entity: Entity, id: string | number): Promise<void>;
63
121
  page?(entity: Entity, query?: Query): Promise<Page>;
122
+ emit?(target: EmitTarget, data: Row, options: EmitOptions): Promise<EmitResult>;
123
+ /** What this adapter recorded instead of publishing (mock only). */
124
+ emitted?(): EmittedEvent[];
64
125
  }
65
126
 
66
127
  /**
@@ -273,4 +334,4 @@ declare const badRequest: (message?: string, details?: unknown) => HttpError;
273
334
  declare const forbidden: (message?: string) => HttpError;
274
335
  declare const conflict: (message?: string) => HttpError;
275
336
 
276
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type Entity as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, DEFAULT_SETTINGS_ERROR_TTL_MS as a, DEFAULT_SETTINGS_TIMEOUT_MS as b, DEFAULT_SETTINGS_TTL_MS as c, type FilterOp as d, type HttpErrorOptions as e, type ReadOptions as f, type ResolvedSettings as g, type SettingsDefaults as h, type SettingsOptions as i, type SettingsReader as j, type SettingsSnapshot as k, type SettingsSource as l, createSettings as m, isHttpError as n, badRequest as o, conflict as p, forbidden as q, notFound as r };
337
+ export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type ResolvedSettings as l, type SettingsDefaults as m, type SettingsOptions as n, type SettingsReader as o, type SettingsSnapshot as p, type SettingsSource as q, createSettings as r, isHttpError as s, badRequest as t, conflict as u, forbidden as v, notFound as w };
@@ -46,12 +46,70 @@ interface Page<T = Row> {
46
46
  limit?: number;
47
47
  offset?: number;
48
48
  }
49
+ /**
50
+ * One event the App may fire itself — a `manifest.events.emits[]` entry
51
+ * declared `trigger: "app"`. Generated into the App's client alongside the
52
+ * entity descriptors.
53
+ */
54
+ interface EventDescriptor {
55
+ /** Vendor-scoped topic the platform publishes, e.g. `revenexx.inventories.stock.low`. */
56
+ topic: string;
57
+ /** The declared example payload, as it appears in the tenant's event catalog. */
58
+ sample?: Row;
59
+ /** Optional JSON Schema for `data`, from the manifest's `data_schema`. */
60
+ schema?: Record<string, unknown>;
61
+ }
62
+ /** Per-emit options. Everything here is optional; `data` carries the payload. */
63
+ interface EmitOptions {
64
+ /**
65
+ * The resource this event is about, so a realtime consumer can address one
66
+ * row instead of a collection. An opaque channel segment
67
+ * (`[A-Za-z0-9][A-Za-z0-9_-]{0,63}`), never a transformed id — the platform
68
+ * rejects an out-of-class value rather than reshaping it. Omit for an event
69
+ * that addresses a collection.
70
+ */
71
+ topicId?: string | null;
72
+ /** Free-form metadata. The platform adds `source`, `vendor` and `app`. */
73
+ metadata?: Row;
74
+ /**
75
+ * Idempotency key. An App has no transaction — every call is its own request
76
+ * — so a process can die between its write and its emit. Pass a
77
+ * deterministic id and the retry is a no-op instead of a duplicate on the
78
+ * bus. Omit it for an event nothing will ever re-attempt.
79
+ */
80
+ id?: string;
81
+ }
82
+ /** What the platform answers: the event's id and the topic it went out on. */
83
+ interface EmitResult {
84
+ id: string;
85
+ topic: string;
86
+ }
87
+ /** The routine to call and which declared event is being fired. */
88
+ interface EmitTarget {
89
+ /** The generated per-App routine, e.g. `revenexx__inventories__emit`. */
90
+ fn: string;
91
+ /** The declared event name, e.g. `stock.low`. */
92
+ name: string;
93
+ descriptor: EventDescriptor;
94
+ }
95
+ /** One recorded emit. Only the `mock` adapter keeps these. */
96
+ interface EmittedEvent {
97
+ event: string;
98
+ topic: string;
99
+ data: Row;
100
+ options: EmitOptions;
101
+ result: EmitResult;
102
+ }
49
103
  /**
50
104
  * The data-plane contract. Implement this to add a new backend (e.g. GraphQL,
51
105
  * a local SQLite file) and register it with `registerAdapter`.
52
106
  *
53
107
  * `page` is optional: adapters that can report a total (PostgREST `count=exact`,
54
108
  * an in-memory store) implement it; others fall back to `list` only.
109
+ *
110
+ * `emit` and `emitted` are optional for the same reason — an adapter that
111
+ * cannot reach the event bus simply does not implement them, and the entity
112
+ * client says so rather than pretending the event went out.
55
113
  */
56
114
  interface Adapter {
57
115
  readonly kind: string;
@@ -61,6 +119,9 @@ interface Adapter {
61
119
  update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
62
120
  remove(entity: Entity, id: string | number): Promise<void>;
63
121
  page?(entity: Entity, query?: Query): Promise<Page>;
122
+ emit?(target: EmitTarget, data: Row, options: EmitOptions): Promise<EmitResult>;
123
+ /** What this adapter recorded instead of publishing (mock only). */
124
+ emitted?(): EmittedEvent[];
64
125
  }
65
126
 
66
127
  /**
@@ -273,4 +334,4 @@ declare const badRequest: (message?: string, details?: unknown) => HttpError;
273
334
  declare const forbidden: (message?: string) => HttpError;
274
335
  declare const conflict: (message?: string) => HttpError;
275
336
 
276
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type Entity as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, DEFAULT_SETTINGS_ERROR_TTL_MS as a, DEFAULT_SETTINGS_TIMEOUT_MS as b, DEFAULT_SETTINGS_TTL_MS as c, type FilterOp as d, type HttpErrorOptions as e, type ReadOptions as f, type ResolvedSettings as g, type SettingsDefaults as h, type SettingsOptions as i, type SettingsReader as j, type SettingsSnapshot as k, type SettingsSource as l, createSettings as m, isHttpError as n, badRequest as o, conflict as p, forbidden as q, notFound as r };
337
+ export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type ResolvedSettings as l, type SettingsDefaults as m, type SettingsOptions as n, type SettingsReader as o, type SettingsSnapshot as p, type SettingsSource as q, createSettings as r, isHttpError as s, badRequest as t, conflict as u, forbidden as v, notFound as w };
package/dist/index.cjs CHANGED
@@ -177,6 +177,7 @@ function applyDefaults(entity, data) {
177
177
  }
178
178
  function createMockAdapter(seed = {}) {
179
179
  const store = /* @__PURE__ */ new Map();
180
+ const events = [];
180
181
  const tbl = (entity) => {
181
182
  let m = store.get(entity.name);
182
183
  if (!m) {
@@ -216,7 +217,37 @@ function createMockAdapter(seed = {}) {
216
217
  },
217
218
  async remove(entity, id) {
218
219
  tbl(entity).delete(id);
219
- }
220
+ },
221
+ /**
222
+ * Record instead of publish, so an App can assert what it fired without any
223
+ * infrastructure. The signature and the answer are the remote adapter's,
224
+ * deliberately: the expensive failure in this codebase is a test double
225
+ * that drifted from the real surface, so a test that passes here has to
226
+ * mean the same call works against Postgres.
227
+ *
228
+ * The declared name is NOT checked here — the client does that before it
229
+ * reaches any adapter, so mock and remote refuse a typo identically.
230
+ */
231
+ async emit(target, data = {}, options = {}) {
232
+ const result = {
233
+ id: options.id ?? `evt_${(0, import_node_crypto.randomUUID)().replace(/-/g, "")}`,
234
+ topic: target.descriptor.topic
235
+ };
236
+ if (!events.some((e) => e.result.id === result.id)) {
237
+ events.push({ event: target.name, topic: result.topic, data: { ...data }, options, result });
238
+ }
239
+ return result;
240
+ },
241
+ // Copied a level deep, not spread: an EmittedEvent nests `data`, `options`
242
+ // and `result`, so a shallow copy would hand callers the live payload and
243
+ // let one assertion rewrite what the next one reads.
244
+ emitted: () => events.map((e) => ({
245
+ event: e.event,
246
+ topic: e.topic,
247
+ data: { ...e.data },
248
+ options: { ...e.options },
249
+ result: { ...e.result }
250
+ }))
220
251
  };
221
252
  }
222
253
 
@@ -404,6 +435,42 @@ function createRemoteAdapter(config) {
404
435
  limit: query.limit,
405
436
  offset: query.offset
406
437
  };
438
+ },
439
+ /**
440
+ * Fire one of the App's own declared events, through the routine Baseline
441
+ * generated for it: `POST /rpc/{vendor}__{app}__emit`.
442
+ *
443
+ * Nothing about WHICH app is emitting travels in this request. The routine
444
+ * is per app, its topic prefix and its allowlist are literals, and only the
445
+ * app's Postgres role may execute it — so the same token that reaches the
446
+ * app's tables is the whole credential, and there is no argument through
447
+ * which another app's topic could be named.
448
+ *
449
+ * The argument names are the routine's, not ours: PostgREST maps the body's
450
+ * keys onto named parameters, so `topicId` becomes `topic_id` and `id`
451
+ * becomes `event_id` (a parameter called `id` would shadow the outbox
452
+ * column in the routine's own ON CONFLICT clause).
453
+ */
454
+ async emit(target, data = {}, options = {}) {
455
+ const { ok, status, text } = await send("POST", `/rpc/${target.fn}`, {
456
+ table: target.fn,
457
+ body: {
458
+ event: target.name,
459
+ data,
460
+ topic_id: options.topicId ?? null,
461
+ metadata: options.metadata ?? {},
462
+ event_id: options.id ?? null
463
+ }
464
+ });
465
+ if (!ok) throw postgrestError(status, text, { method: "POST", table: target.fn });
466
+ const answer = text ? JSON.parse(text) : null;
467
+ if (!answer?.id || !answer.topic) {
468
+ throw new HttpError(502, "the event service returned no event id", void 0, {
469
+ code: "emit_no_id",
470
+ serverDetail: { source: "postgrest", fn: target.fn, event: target.name, body: text }
471
+ });
472
+ }
473
+ return { id: answer.id, topic: answer.topic };
407
474
  }
408
475
  };
409
476
  }
@@ -506,6 +573,32 @@ function entityClient(adapter, entity) {
506
573
  delete: guard("delete", (id) => adapter.remove(entity, id))
507
574
  };
508
575
  }
576
+ function eventsClient(adapter, config) {
577
+ const names = () => Object.keys(config.declared).sort().join(", ") || "(none)";
578
+ return {
579
+ declared: config.declared,
580
+ async emit(name, data = {}, options = {}) {
581
+ const descriptor = config.declared[name];
582
+ if (!descriptor) {
583
+ throw new Error(
584
+ `events.emit('${name}'): not declared by this app \u2014 add it to manifest.json events.emits[] with "trigger": "app". Declared: ${names()}`
585
+ );
586
+ }
587
+ if (!adapter.emit) {
588
+ throw new Error(`events.emit('${name}') is not supported by the '${adapter.kind}' adapter`);
589
+ }
590
+ return adapter.emit({ fn: config.fn, name, descriptor }, data, options);
591
+ },
592
+ emitted() {
593
+ if (!adapter.emitted) {
594
+ throw new Error(
595
+ `events.emitted() is only available on the 'mock' adapter \u2014 the '${adapter.kind}' adapter publishes for real`
596
+ );
597
+ }
598
+ return adapter.emitted();
599
+ }
600
+ };
601
+ }
509
602
  function createClient(config) {
510
603
  if (!config?.entities) throw new Error("app-sdk: createClient needs { adapter, entities }");
511
604
  const adapter = createAdapter(config);
@@ -513,6 +606,12 @@ function createClient(config) {
513
606
  for (const [name, def] of Object.entries(config.entities)) {
514
607
  db[name] = entityClient(adapter, { name, ...def });
515
608
  }
609
+ if (config.events?.fn) {
610
+ Object.defineProperty(db, "events", {
611
+ value: eventsClient(adapter, config.events),
612
+ enumerable: true
613
+ });
614
+ }
516
615
  return db;
517
616
  }
518
617