@agentbadge/database 0.6.4 → 0.6.5

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.
@@ -8398,6 +8398,13 @@
8398
8398
  "columns": [
8399
8399
  "eventSeq"
8400
8400
  ]
8401
+ },
8402
+ {
8403
+ "columns": [
8404
+ "entityType",
8405
+ "entityId",
8406
+ "prevHash"
8407
+ ]
8401
8408
  }
8402
8409
  ]
8403
8410
  },
@@ -11797,7 +11804,7 @@
11797
11804
  "kind": "postgres-schema"
11798
11805
  }
11799
11806
  },
11800
- "storageHash": "54c2a5b26f1b3d894327cc5f3d46ddf6c1586d5fde50c92a2bd6b1ff0ceda73b"
11807
+ "storageHash": "0c1bc30f48fbd4d9e6e1fa4cd5f16a99f2a9ea4811eb1ec19947290e2112a455"
11801
11808
  },
11802
11809
  "execution": {
11803
11810
  "executionHash": "e71791f5422317f7461d372987109bdfee010244722f6deabdeb567fe4aa3538",
@@ -1,5 +1,6 @@
1
1
  import type { PrismaDb } from "./event-repository.js";
2
2
  import type { AgreementStatusPatch, CommerceAgreementInsert, CommerceAgreementRow, CommerceAgreementStore, CommerceEvidenceInsert, CommerceEvidenceRow, CommerceEvidenceStore, CommerceEventInsert, CommerceEventRow, CommerceEventStore, CommerceOfferInsert, CommerceOfferRow, CommerceOfferStore, CommercePaymentInsert, CommercePaymentRow, CommercePaymentStore, CommerceStores, CommerceSubmissionInsert, CommerceSubmissionRow, CommerceSubmissionStore, CommerceTaskInsert, CommerceTaskRow, CommerceTaskStore, PaymentStatusPatch, SubmissionStatusPatch } from "./commerce-store.js";
3
+ export declare const isUniqueViolation: (err: unknown) => boolean;
3
4
  export declare class CommerceTaskRepository implements CommerceTaskStore {
4
5
  private readonly db;
5
6
  constructor(db: PrismaDb);
@@ -9,6 +10,7 @@ export declare class CommerceTaskRepository implements CommerceTaskStore {
9
10
  list(opts?: {
10
11
  status?: string;
11
12
  buyerWallet?: string;
13
+ visibleTo?: string;
12
14
  limit?: number;
13
15
  }): Promise<CommerceTaskRow[]>;
14
16
  applyStatus(id: string, expectedFrom: string, to: string): Promise<CommerceTaskRow | null>;
@@ -1,3 +1,16 @@
1
+ export const isUniqueViolation = (err) => typeof err === "object" &&
2
+ err !== null &&
3
+ err.sqlState === "23505";
4
+ async function catchUnique(p) {
5
+ try {
6
+ return await p;
7
+ }
8
+ catch (err) {
9
+ if (isUniqueViolation(err))
10
+ return null;
11
+ throw err;
12
+ }
13
+ }
1
14
  const dec = (v) => String(v);
2
15
  const decOrNull = (v) => v === null || v === undefined ? null : String(v);
3
16
  const numOrNull = (v) => v === null || v === undefined ? null : Number(v);
@@ -111,7 +124,7 @@ export class CommerceTaskRepository {
111
124
  async create(t) {
112
125
  if (await this.getById(t.id))
113
126
  return null;
114
- const row = await this.orm.create({
127
+ const row = await catchUnique(this.orm.create({
115
128
  id: t.id,
116
129
  buyerWallet: t.buyerWallet,
117
130
  buyerAgentId: t.buyerAgentId ?? null,
@@ -127,8 +140,8 @@ export class CommerceTaskRepository {
127
140
  : null,
128
141
  status: t.status,
129
142
  payload: t.payload,
130
- });
131
- return toTaskRow(row);
143
+ }));
144
+ return row ? toTaskRow(row) : null;
132
145
  }
133
146
  async getById(id) {
134
147
  const r = await this.orm.where({ id }).first();
@@ -145,9 +158,17 @@ export class CommerceTaskRepository {
145
158
  else if (opts?.buyerWallet !== undefined) {
146
159
  q = q.where({ buyerWallet: opts.buyerWallet });
147
160
  }
148
- if (opts?.limit !== undefined)
149
- q = q.limit(opts.limit);
150
- return (await q.all()).map(toTaskRow);
161
+ const need = opts?.limit !== undefined ? opts.limit : undefined;
162
+ if (need !== undefined)
163
+ q = q.limit(need * 4);
164
+ let rows = (await q.all()).map(toTaskRow);
165
+ if (opts?.visibleTo !== undefined) {
166
+ const viewer = opts.visibleTo;
167
+ rows = rows.filter((r) => r.status !== "DRAFT" || r.buyerWallet === viewer);
168
+ }
169
+ if (need !== undefined)
170
+ rows = rows.slice(0, need);
171
+ return rows;
151
172
  }
152
173
  async applyStatus(id, expectedFrom, to) {
153
174
  const row = await this.orm
@@ -167,7 +188,7 @@ export class CommerceOfferRepository {
167
188
  async create(o) {
168
189
  if (await this.getById(o.id))
169
190
  return null;
170
- const row = await this.orm.create({
191
+ const row = await catchUnique(this.orm.create({
171
192
  id: o.id,
172
193
  taskId: o.taskId,
173
194
  providerWallet: o.providerWallet,
@@ -178,8 +199,8 @@ export class CommerceOfferRepository {
178
199
  proposal: o.proposal,
179
200
  status: o.status,
180
201
  payload: o.payload,
181
- });
182
- return toOfferRow(row);
202
+ }));
203
+ return row ? toOfferRow(row) : null;
183
204
  }
184
205
  async getById(id) {
185
206
  const r = await this.orm.where({ id }).first();
@@ -214,7 +235,7 @@ export class CommerceAgreementRepository {
214
235
  return null;
215
236
  if (await this.getByOfferId(a.offerId))
216
237
  return null;
217
- const row = await this.orm.create({
238
+ const row = await catchUnique(this.orm.create({
218
239
  id: a.id,
219
240
  taskId: a.taskId,
220
241
  offerId: a.offerId,
@@ -228,8 +249,8 @@ export class CommerceAgreementRepository {
228
249
  ? BigInt(a.completedAtMs)
229
250
  : null,
230
251
  payload: a.payload,
231
- });
232
- return toAgreementRow(row);
252
+ }));
253
+ return row ? toAgreementRow(row) : null;
233
254
  }
234
255
  async getById(id) {
235
256
  const r = await this.orm.where({ id }).first();
@@ -268,7 +289,7 @@ export class CommerceSubmissionRepository {
268
289
  async create(s) {
269
290
  if (await this.getById(s.id))
270
291
  return null;
271
- const row = await this.orm.create({
292
+ const row = await catchUnique(this.orm.create({
272
293
  id: s.id,
273
294
  agreementId: s.agreementId,
274
295
  providerWallet: s.providerWallet,
@@ -281,8 +302,8 @@ export class CommerceSubmissionRepository {
281
302
  ? BigInt(s.reviewedAtMs)
282
303
  : null,
283
304
  payload: s.payload,
284
- });
285
- return toSubmissionRow(row);
305
+ }));
306
+ return row ? toSubmissionRow(row) : null;
286
307
  }
287
308
  async getById(id) {
288
309
  const r = await this.orm.where({ id }).first();
@@ -323,7 +344,7 @@ export class CommerceEvidenceRepository {
323
344
  async append(e) {
324
345
  if (await this.getById(e.id))
325
346
  return null;
326
- const row = await this.orm.create({
347
+ const row = await catchUnique(this.orm.create({
327
348
  id: e.id,
328
349
  submissionId: e.submissionId ?? null,
329
350
  agreementId: e.agreementId ?? null,
@@ -333,8 +354,8 @@ export class CommerceEvidenceRepository {
333
354
  content: e.content ?? null,
334
355
  metadata: e.metadata ?? null,
335
356
  payload: e.payload,
336
- });
337
- return toEvidenceRow(row);
357
+ }));
358
+ return row ? toEvidenceRow(row) : null;
338
359
  }
339
360
  async getById(id) {
340
361
  const r = await this.orm.where({ id }).first();
@@ -366,7 +387,7 @@ export class CommerceEventRepository {
366
387
  async append(e) {
367
388
  if (await this.getById(e.id))
368
389
  return null;
369
- const row = await this.orm.create({
390
+ const row = await catchUnique(this.orm.create({
370
391
  id: e.id,
371
392
  entityType: e.entityType,
372
393
  entityId: e.entityId,
@@ -375,8 +396,8 @@ export class CommerceEventRepository {
375
396
  prevHash: e.prevHash,
376
397
  hash: e.hash,
377
398
  payload: e.payload,
378
- });
379
- return toEventRow(row);
399
+ }));
400
+ return row ? toEventRow(row) : null;
380
401
  }
381
402
  async getById(id) {
382
403
  const r = await this.orm.where({ id }).first();
@@ -419,7 +440,7 @@ export class CommercePaymentRepository {
419
440
  return null;
420
441
  if (await this.getByAgreement(p.agreementId))
421
442
  return null;
422
- const row = await this.orm.create({
443
+ const row = await catchUnique(this.orm.create({
423
444
  id: p.id,
424
445
  agreementId: p.agreementId,
425
446
  mode: p.mode ?? "RECORD_ONLY",
@@ -439,8 +460,8 @@ export class CommercePaymentRepository {
439
460
  : null,
440
461
  note: p.note ?? null,
441
462
  payload: p.payload,
442
- });
443
- return toPaymentRow(row);
463
+ }));
464
+ return row ? toPaymentRow(row) : null;
444
465
  }
445
466
  async getById(id) {
446
467
  const r = await this.orm.where({ id }).first();
@@ -474,19 +495,34 @@ export class CommercePaymentRepository {
474
495
  ...(patch?.paymentId !== undefined
475
496
  ? { paymentId: patch.paymentId }
476
497
  : {}),
498
+ ...(patch?.amount !== undefined ? { amount: patch.amount } : {}),
477
499
  ...(patch?.note !== undefined ? { note: patch.note } : {}),
478
500
  });
479
501
  return row ? toPaymentRow(row) : null;
480
502
  }
481
503
  }
482
504
  export function createPrismaCommerceStores(db) {
483
- return {
484
- tasks: new CommerceTaskRepository(db),
485
- offers: new CommerceOfferRepository(db),
486
- agreements: new CommerceAgreementRepository(db),
487
- submissions: new CommerceSubmissionRepository(db),
488
- evidence: new CommerceEvidenceRepository(db),
489
- events: new CommerceEventRepository(db),
490
- payments: new CommercePaymentRepository(db),
491
- };
505
+ const bundle = (client) => ({
506
+ tasks: new CommerceTaskRepository(client),
507
+ offers: new CommerceOfferRepository(client),
508
+ agreements: new CommerceAgreementRepository(client),
509
+ submissions: new CommerceSubmissionRepository(client),
510
+ evidence: new CommerceEvidenceRepository(client),
511
+ events: new CommerceEventRepository(client),
512
+ payments: new CommercePaymentRepository(client),
513
+ atomic: outerAtomic,
514
+ });
515
+ async function outerAtomic(fn) {
516
+ for (let attempt = 0;; attempt++) {
517
+ try {
518
+ return await db.transaction((tx) => fn(bundle(tx)));
519
+ }
520
+ catch (err) {
521
+ if (attempt === 0 && isUniqueViolation(err))
522
+ continue;
523
+ throw err;
524
+ }
525
+ }
526
+ }
527
+ return bundle(db);
492
528
  }
@@ -22,6 +22,7 @@ export interface CommerceTaskStore {
22
22
  list(opts?: {
23
23
  status?: string;
24
24
  buyerWallet?: string;
25
+ visibleTo?: string;
25
26
  limit?: number;
26
27
  }): Promise<CommerceTaskRow[]>;
27
28
  applyStatus(id: string, expectedFrom: string, to: string): Promise<CommerceTaskRow | null>;
@@ -165,6 +166,7 @@ export interface CommercePaymentRow extends CommercePaymentInsert {
165
166
  updatedAt: string;
166
167
  }
167
168
  export interface PaymentStatusPatch {
169
+ amount?: string;
168
170
  recordedBy?: string;
169
171
  recordedAtMs?: number;
170
172
  verifiedBy?: string;
@@ -186,6 +188,7 @@ export interface CommerceStores {
186
188
  evidence: CommerceEvidenceStore;
187
189
  events: CommerceEventStore;
188
190
  payments: CommercePaymentStore;
191
+ atomic<R>(fn: (stores: CommerceStores) => Promise<R>): Promise<R>;
189
192
  }
190
193
  export declare class InMemoryCommerceTaskStore implements CommerceTaskStore {
191
194
  private readonly rows;
@@ -194,6 +197,7 @@ export declare class InMemoryCommerceTaskStore implements CommerceTaskStore {
194
197
  list(opts?: {
195
198
  status?: string;
196
199
  buyerWallet?: string;
200
+ visibleTo?: string;
197
201
  limit?: number;
198
202
  }): Promise<CommerceTaskRow[]>;
199
203
  applyStatus(id: string, expectedFrom: string, to: string): Promise<CommerceTaskRow | null>;
@@ -23,7 +23,10 @@ export class InMemoryCommerceTaskStore {
23
23
  }
24
24
  async list(opts) {
25
25
  let out = [...this.rows.values()].filter((r) => (opts?.status === undefined || r.status === opts.status) &&
26
- (opts?.buyerWallet === undefined || r.buyerWallet === opts.buyerWallet));
26
+ (opts?.buyerWallet === undefined || r.buyerWallet === opts.buyerWallet) &&
27
+ (opts?.visibleTo === undefined ||
28
+ r.status !== "DRAFT" ||
29
+ r.buyerWallet === opts.visibleTo));
27
30
  out = out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
28
31
  if (opts?.limit !== undefined)
29
32
  out = out.slice(0, opts.limit);
@@ -283,6 +286,7 @@ export class InMemoryCommercePaymentStore {
283
286
  ...row,
284
287
  status: to,
285
288
  ...(patch?.recordedBy !== undefined ? { recordedBy: patch.recordedBy } : {}),
289
+ ...(patch?.amount !== undefined ? { amount: patch.amount } : {}),
286
290
  ...(patch?.recordedAtMs !== undefined
287
291
  ? { recordedAtMs: patch.recordedAtMs }
288
292
  : {}),
@@ -298,14 +302,36 @@ export class InMemoryCommercePaymentStore {
298
302
  return next;
299
303
  }
300
304
  }
305
+ function cloneRows(value) {
306
+ if (value === null || typeof value !== "object")
307
+ return value;
308
+ return structuredClone(value);
309
+ }
310
+ function cloneStore(store) {
311
+ return new Proxy(store, {
312
+ get(target, prop, receiver) {
313
+ const value = Reflect.get(target, prop, receiver);
314
+ if (typeof value !== "function")
315
+ return value;
316
+ return async (...args) => cloneRows(await value.apply(target, args));
317
+ },
318
+ });
319
+ }
301
320
  export function createInMemoryCommerceStores() {
302
- return {
303
- tasks: new InMemoryCommerceTaskStore(),
304
- offers: new InMemoryCommerceOfferStore(),
305
- agreements: new InMemoryCommerceAgreementStore(),
306
- submissions: new InMemoryCommerceSubmissionStore(),
307
- evidence: new InMemoryCommerceEvidenceStore(),
308
- events: new InMemoryCommerceEventStore(),
309
- payments: new InMemoryCommercePaymentStore(),
321
+ let tail = Promise.resolve();
322
+ const stores = {
323
+ tasks: cloneStore(new InMemoryCommerceTaskStore()),
324
+ offers: cloneStore(new InMemoryCommerceOfferStore()),
325
+ agreements: cloneStore(new InMemoryCommerceAgreementStore()),
326
+ submissions: cloneStore(new InMemoryCommerceSubmissionStore()),
327
+ evidence: cloneStore(new InMemoryCommerceEvidenceStore()),
328
+ events: cloneStore(new InMemoryCommerceEventStore()),
329
+ payments: cloneStore(new InMemoryCommercePaymentStore()),
330
+ atomic: async (fn) => {
331
+ const run = tail.then(() => fn(stores));
332
+ tail = run.catch(() => { });
333
+ return run;
334
+ },
310
335
  };
336
+ return stores;
311
337
  }
@@ -11,6 +11,7 @@ export declare class EventRepository extends Repository<Event, EventCreate, Even
11
11
  limit?: number;
12
12
  offset?: number;
13
13
  type?: string;
14
+ since?: string;
14
15
  }): Promise<Event[]>;
15
16
  create(data: EventCreate): Promise<Event>;
16
17
  update(id: string, data: EventUpdate): Promise<Event | null>;
@@ -1,4 +1,16 @@
1
+ import { param } from "@prisma/orm-postgres/relational-core/expression";
1
2
  import { Repository } from "../repository.js";
3
+ const EVENT_ROW_SPEC = {
4
+ id: "pg/text@1",
5
+ type: "pg/text@1",
6
+ payload: "pg/json@1",
7
+ source: { codecId: "pg/text@1", nullable: true },
8
+ wallet: { codecId: "pg/text@1", nullable: true },
9
+ venueId: { codecId: "pg/text@1", nullable: true },
10
+ at: { codecId: "pg/int8@1", nullable: true },
11
+ createdAt: "pg/timestamptz-string@1",
12
+ updatedAt: "pg/timestamptz-string@1",
13
+ };
2
14
  export class EventRepository extends Repository {
3
15
  db;
4
16
  constructor(db) {
@@ -9,9 +21,25 @@ export class EventRepository extends Repository {
9
21
  return this.db.orm.public.Event.where({ id }).first();
10
22
  }
11
23
  async list(opts) {
24
+ const type = opts?.type;
25
+ const since = opts?.since;
26
+ if (since !== undefined) {
27
+ const limit = param(opts?.limit ?? 100_000, { codecId: "pg/int4@1" });
28
+ const offset = param(opts?.offset ?? 0, { codecId: "pg/int4@1" });
29
+ const sinceParam = param(since, { codecId: "pg/timestamptz-string@1" });
30
+ const plan = type !== undefined
31
+ ? this.db.raw.sql `SELECT "id","type","payload","source","wallet","venueId","at","createdAt","updatedAt" FROM "event" WHERE "type" = ${param(type, { codecId: "pg/text@1" })} AND "createdAt" >= ${sinceParam} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`
32
+ .returnsRow(EVENT_ROW_SPEC)
33
+ .build()
34
+ : this.db.raw.sql `SELECT "id","type","payload","source","wallet","venueId","at","createdAt","updatedAt" FROM "event" WHERE "createdAt" >= ${sinceParam} ORDER BY "createdAt" DESC LIMIT ${limit} OFFSET ${offset}`
35
+ .returnsRow(EVENT_ROW_SPEC)
36
+ .build();
37
+ const rows = await this.db.runtime().query(plan);
38
+ return rows;
39
+ }
12
40
  let q = this.db.orm.public.Event.orderBy((e) => e.createdAt.desc());
13
- if (opts?.type !== undefined) {
14
- q = q.where({ type: opts.type });
41
+ if (type !== undefined) {
42
+ q = q.where({ type });
15
43
  }
16
44
  if (opts?.offset !== undefined)
17
45
  q = q.offset(opts.offset);
package/dist/store.d.ts CHANGED
@@ -16,6 +16,7 @@ export interface Store {
16
16
  limit?: number;
17
17
  offset?: number;
18
18
  type?: string;
19
+ since?: string;
19
20
  }): Promise<Event[]>;
20
21
  create(data: EventCreate): Promise<Event>;
21
22
  update(id: string, data: EventUpdate): Promise<Event | null>;
@@ -28,6 +29,7 @@ export declare class InMemoryStore implements Store {
28
29
  limit?: number;
29
30
  offset?: number;
30
31
  type?: string;
32
+ since?: string;
31
33
  }): Promise<Event[]>;
32
34
  create(data: EventCreate): Promise<Event>;
33
35
  update(id: string, data: EventUpdate): Promise<Event | null>;
package/dist/store.js CHANGED
@@ -9,6 +9,9 @@ export class InMemoryStore {
9
9
  if (opts?.type !== undefined) {
10
10
  all = all.filter((e) => e.type === opts.type);
11
11
  }
12
+ if (opts?.since !== undefined) {
13
+ all = all.filter((e) => e.createdAt >= opts.since);
14
+ }
12
15
  const offset = opts?.offset ?? 0;
13
16
  const limit = opts?.limit ?? all.length;
14
17
  return all.slice(offset, offset + limit);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentbadge/database",
3
- "version": "0.6.4",
3
+ "version": "0.6.5",
4
4
  "description": "Shared database layer for AgentBadge — Prisma ORM 8 client, repositories, store abstraction",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",