eventsourcingdb 1.8.1 → 1.8.2

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/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 26.3.1
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("node:crypto");c=s(c);let l=require("testcontainers");var u=class{specversion;id;time;#e;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:t,time:n,timeFromServer:r,source:i,subject:a,type:o,datacontenttype:s,data:c,hash:l,predecessorhash:u,traceparent:d,tracestate:f,signature:p}){this.specversion=e,this.id=t,this.time=n,this.#e=r,this.source=i,this.subject=a,this.type=o,this.datacontenttype=s,this.data=c,this.hash=l,this.predecessorhash=u,this.traceparent=d,this.tracestate=f,this.signature=p}verifyHash(){let e=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#e}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,t=c.default.createHash(`sha256`).update(e).digest(`hex`),n=c.default.createHash(`sha256`).update(JSON.stringify(this.data)).digest(`hex`);if(c.default.createHash(`sha256`).update(`${t}${n}`).digest(`hex`)!==this.hash)throw Error(`Failed to verify hash.`)}verifySignature(e){if(this.signature===null)throw Error(`Signature must not be null.`);this.verifyHash();let t=`esdb:signature:v1:`;if(!this.signature.startsWith(t))throw Error(`Signature must start with '${t}'`);let n=this.signature.slice(18),r=Buffer.from(n,`hex`),i=Buffer.from(this.hash,`utf8`);if(!c.default.verify(null,i,e,r))throw Error(`Signature verification failed.`)}};const d=e=>new u({specversion:e.specversion,id:e.id,time:new Date(e.time),timeFromServer:e.time,source:e.source,subject:e.subject,type:e.type,datacontenttype:e.datacontenttype,data:e.data,hash:e.hash,predecessorhash:e.predecessorhash,traceparent:e.traceparent,tracestate:e.tracestate,signature:e.signature}),f=e=>!(typeof e!=`object`||!e||Array.isArray(e)),p=(e,t)=>{if(!f(e))return!1;for(let n of Object.keys(t)){let r=t[n],i=e[n];if(typeof r==`function`){if(!r(i))return!1;continue}if(!f(i)||!p(i,r))return!1}return!0},m=e=>typeof e==`string`,h=e=>e===null||typeof e==`string`,g=e=>e===void 0||typeof e==`string`,_=e=>p(e,{specversion:m,id:m,time:m,source:m,subject:m,type:m,datacontenttype:m,data:f,hash:m,predecessorhash:m,traceparent:g,tracestate:g,signature:h}),v=e=>{let t=e.headers.get(`Server`);return!(!t||!t.startsWith(`EventSourcingDB/`))},y=async function*(e,t){let n=e.getReader(),r=new TextDecoder(`utf-8`),i=``,a=()=>{n.cancel().catch(()=>{})};if(t.aborted){await n.cancel().catch(()=>{});return}t.addEventListener(`abort`,a);try{for(;!t.aborted;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.indexOf(`
2
+ `);for(;a!==-1;){let e=i.slice(0,a).trim();i=i.slice(a+1),e&&(yield JSON.parse(e)),a=i.indexOf(`
3
+ `)}}}finally{t.removeEventListener(`abort`,a),await n.cancel().catch(()=>{})}},b=e=>p(e,{type:e=>e===`event`,payload:{specversion:m,id:m,time:m,source:m,subject:m,type:m,datacontenttype:m,data:f,hash:m,predecessorhash:m,traceparent:g,tracestate:g,signature:h}}),x=e=>p(e,{type:e=>e===`error`,payload:{error:m}}),S=e=>typeof e==`boolean`,C=e=>p(e,{type:e=>e===`eventType`,payload:{eventType:m,isPhantom:S}}),w=e=>p(e,{type:e=>e===`heartbeat`}),T=e=>p(e,{type:e=>e===`row`,payload:e=>e!==void 0}),E=e=>p(e,{type:e=>e===`subject`,payload:{subject:m}});var D=class{#e;#t;#n(e){return new URL(e,this.#e).toString()}constructor(e,t){this.#e=e,this.#t=t}async ping(){let e=this.#n(`/api/v1/ping`),t=await fetch(e,{method:`get`});if(!v(t))throw Error(`Server must be EventSourcingDB.`);if(t.status!==200)throw Error(`Failed to ping, got HTTP status code '${t.status}', expected '200'.`);let n=await t.json();if(!p(n,{type:m}))throw Error(`Failed to parse response.`);if(n.type!==`io.eventsourcingdb.api.ping-received`)throw Error(`Failed to ping.`)}async verifyApiToken(){let e=this.#n(`/api/v1/verify-api-token`),t=await fetch(e,{method:`post`,headers:{authorization:`Bearer ${this.#t}`}});if(!v(t))throw Error(`Server must be EventSourcingDB.`);if(t.status!==200)throw Error(`Failed to verify API token, got HTTP status code '${t.status}', expected '200'.`);let n=await t.json();if(!p(n,{type:m}))throw Error(`Failed to parse response.`);if(n.type!==`io.eventsourcingdb.api.api-token-verified`)throw Error(`Failed to verify API token.`)}async writeEvents(e,t=[]){let n=this.#n(`/api/v1/write-events`),r=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({events:e,preconditions:t})});if(!v(r))throw Error(`Server must be EventSourcingDB.`);if(r.status!==200)throw Error(`Failed to write events, got HTTP status code '${r.status}', expected '200'.`);let i=await r.json();if(!Array.isArray(i))throw Error(`Failed to parse response.`);return i.map(e=>{if(!_(e))throw Error(`Failed to parse response item.`);return d(e)})}readEvents(e,t,n){let r=this.#n(`/api/v1/read-events`),i=this.#t;return(async function*(){let a=new AbortController,o=n??a.signal,s=!n,c;if(n&&!n.aborted){let e=()=>a.abort();n.addEventListener(`abort`,e,{once:!0}),c=()=>n.removeEventListener(`abort`,e)}try{let n=await fetch(r,{method:`post`,headers:{authorization:`Bearer ${i}`,"content-type":`application/json`},body:JSON.stringify({subject:e,options:t}),signal:o});if(!v(n)){let e=n.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(n.status!==200)throw Error(`Failed to read events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw Error(`Failed to read events.`);for await(let e of y(n.body,o)){if(x(e))throw Error(`${e.payload.error}.`);if(b(e)){yield d(e.payload);continue}throw Error(`Failed to read events.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{c&&c(),s&&a.abort()}})()}runEventQlQuery(e,t){let n=this.#n(`/api/v1/run-eventql-query`),r=this.#t;return(async function*(){let i=new AbortController,a=t??i.signal,o=!t,s;if(t&&!t.aborted){let e=()=>i.abort();t.addEventListener(`abort`,e,{once:!0}),s=()=>t.removeEventListener(`abort`,e)}try{let t=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${r}`,"content-type":`application/json`},body:JSON.stringify({query:e}),signal:a});if(!v(t)){let e=t.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(t.status!==200)throw Error(`Failed to run EventQL query, got HTTP status code '${t.status}', expected '200'.`);if(!t.body)throw Error(`Failed to run EventQL query.`);for await(let e of y(t.body,a))if(!w(e)){if(x(e))throw Error(`${e.payload.error}.`);if(T(e)){yield e.payload;continue}throw Error(`Failed to run EventQL query.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{s&&s(),o&&i.abort()}})()}observeEvents(e,t,n){let r=this.#n(`/api/v1/observe-events`),i=this.#t;return(async function*(){let a=new AbortController,o=n??a.signal,s=!n,c;if(n&&!n.aborted){let e=()=>a.abort();n.addEventListener(`abort`,e,{once:!0}),c=()=>n.removeEventListener(`abort`,e)}try{let n=await fetch(r,{method:`post`,headers:{authorization:`Bearer ${i}`,"content-type":`application/json`},body:JSON.stringify({subject:e,options:t}),signal:o});if(!v(n)){let e=n.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(n.status!==200)throw Error(`Failed to observe events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw Error(`Failed to observe events.`);for await(let e of y(n.body,o))if(!w(e)){if(x(e))throw Error(`${e.payload.error}.`);if(b(e)){yield d(e.payload);continue}throw Error(`Failed to observe events.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{c&&c(),s&&a.abort()}})()}async registerEventSchema(e,t){let n=this.#n(`/api/v1/register-event-schema`),r=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({eventType:e,schema:t})});if(!v(r))throw Error(`Server must be EventSourcingDB.`);if(r.status!==200)throw Error(`Failed to register event schema, got HTTP status code '${r.status}', expected '200'.`)}readSubjects(e,t){let n=this.#n(`/api/v1/read-subjects`),r=this.#t;return(async function*(){let i=new AbortController,a=t??i.signal,o=!t,s;if(t&&!t.aborted){let e=()=>i.abort();t.addEventListener(`abort`,e,{once:!0}),s=()=>t.removeEventListener(`abort`,e)}try{let t=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${r}`,"content-type":`application/json`},body:JSON.stringify({baseSubject:e}),signal:a});if(!v(t)){let e=t.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(t.status!==200)throw Error(`Failed to read subjects, got HTTP status code '${t.status}', expected '200'.`);if(!t.body)throw Error(`Failed to read subjects.`);for await(let e of y(t.body,a)){if(x(e))throw Error(`${e.payload.error}.`);if(E(e)){yield e.payload.subject;continue}throw Error(`Failed to read subjects.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{s&&s(),o&&i.abort()}})()}async readEventType(e){let t=this.#n(`/api/v1/read-event-type`),n=await fetch(t,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({eventType:e})});if(!v(n))throw Error(`Server must be EventSourcingDB.`);if(n.status!==200)throw Error(`Failed to read event type, got HTTP status code '${n.status}', expected '200'.`);let r=await n.json();if(!p(r,{eventType:m,isPhantom:S}))throw Error(`Failed to parse response.`);return r}readEventTypes(e){let t=this.#n(`/api/v1/read-event-types`),n=this.#t;return(async function*(){let r=new AbortController,i=e??r.signal,a=!e,o;if(e&&!e.aborted){let t=()=>r.abort();e.addEventListener(`abort`,t,{once:!0}),o=()=>e.removeEventListener(`abort`,t)}try{let e=await fetch(t,{method:`post`,headers:{authorization:`Bearer ${n}`},signal:i});if(!v(e)){let t=e.headers.get(`Server`);throw Error(t?`Server must be EventSourcingDB, got Server header: '${t}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(e.status!==200)throw Error(`Failed to read event types, got HTTP status code '${e.status}', expected '200'.`);if(!e.body)throw Error(`Failed to read event types.`);for await(let t of y(e.body,i))if(!w(t)){if(x(t))throw Error(`${t.payload.error}.`);if(C(t)){yield t.payload;continue}throw Error(`Failed to read event types.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{o&&o(),a&&r.abort()}})()}},O=class{#e=`thenativeweb/eventsourcingdb`;#t=`latest`;#n=3e3;#r=`secret`;#i;#a;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#r=e,this}withSigningKey(){let{privateKey:e}=c.default.generateKeyPairSync(`ed25519`);return this.#i=e,this}withPort(e){return this.#n=e,this}async start(){let e=[`run`,`--api-token`,this.#r,`--data-directory-temporary`,`--http-enabled`,`--https-enabled=false`],t=[];this.#i!==void 0&&(e.push(`--signing-key-file`),e.push(`/etc/esdb/signing-key.pem`),t.push({content:this.#i.export({format:`pem`,type:`pkcs8`}),target:`/etc/esdb/signing-key.pem`,mode:511})),this.#a=await new l.GenericContainer(`${this.#e}:${this.#t}`).withExposedPorts(this.#n).withCommand(e).withCopyContentToContainer(t).withWaitStrategy(l.Wait.forHttp(`/api/v1/ping`,this.#n).withStartupTimeout(1e4)).start()}getHost(){if(this.#a===void 0)throw Error(`Container must be running.`);return this.#a.getHost()}getMappedPort(){if(this.#a===void 0)throw Error(`Container must be running.`);return this.#a.getMappedPort(this.#n)}getBaseUrl(){if(this.#a===void 0)throw Error(`Container must be running.`);let e=this.getHost(),t=this.getMappedPort();return new URL(`http://${e}:${t}`)}getApiToken(){return this.#r}getSigningKey(){if(this.#i===void 0)throw Error(`Signing key not set.`);return this.#i}getVerificationKey(){if(this.#i===void 0)throw Error(`Signing key not set.`);return c.default.createPublicKey(this.#i)}isRunning(){return this.#a!==void 0}async stop(){this.#a!==void 0&&(await this.#a.stop(),this.#a=void 0)}getClient(){return new D(this.getBaseUrl(),this.getApiToken())}};const k=e=>({type:`isEventQlQueryTrue`,payload:{query:e}}),A=(e,t)=>({type:`isSubjectOnEventId`,payload:{subject:e,eventId:t}}),j=e=>({type:`isSubjectPopulated`,payload:{subject:e}}),M=e=>({type:`isSubjectPristine`,payload:{subject:e}});exports.Client=D,exports.Container=O,exports.isEventQlQueryTrue=k,exports.isSubjectOnEventId=A,exports.isSubjectPopulated=j,exports.isSubjectPristine=M;
@@ -0,0 +1,182 @@
1
+ import crypto from "node:crypto";
2
+
3
+ //#region src/Event.d.ts
4
+ declare class Event {
5
+ #private;
6
+ specversion: string;
7
+ id: string;
8
+ time: Date;
9
+ source: string;
10
+ subject: string;
11
+ type: string;
12
+ datacontenttype: string;
13
+ data: Record<string, unknown>;
14
+ hash: string;
15
+ predecessorhash: string;
16
+ traceparent?: string;
17
+ tracestate?: string;
18
+ signature: string | null;
19
+ constructor({
20
+ specversion,
21
+ id,
22
+ time,
23
+ timeFromServer,
24
+ source,
25
+ subject,
26
+ type,
27
+ datacontenttype,
28
+ data,
29
+ hash,
30
+ predecessorhash,
31
+ traceparent,
32
+ tracestate,
33
+ signature
34
+ }: {
35
+ specversion: string;
36
+ id: string;
37
+ time: Date;
38
+ timeFromServer: string;
39
+ source: string;
40
+ subject: string;
41
+ type: string;
42
+ datacontenttype: string;
43
+ data: Record<string, unknown>;
44
+ hash: string;
45
+ predecessorhash: string;
46
+ traceparent?: string;
47
+ tracestate?: string;
48
+ signature: string | null;
49
+ });
50
+ verifyHash(): void;
51
+ verifySignature(verificationKey: crypto.KeyObject): void;
52
+ }
53
+ //#endregion
54
+ //#region src/EventCandidate.d.ts
55
+ interface EventCandidate {
56
+ source: string;
57
+ subject: string;
58
+ type: string;
59
+ data: Record<string, unknown>;
60
+ traceparent?: string;
61
+ tracestate?: string;
62
+ }
63
+ //#endregion
64
+ //#region src/EventType.d.ts
65
+ interface EventType {
66
+ eventType: string;
67
+ isPhantom: boolean;
68
+ schema?: Record<string, unknown>;
69
+ }
70
+ //#endregion
71
+ //#region src/Bound.d.ts
72
+ type BoundType = 'inclusive' | 'exclusive';
73
+ interface Bound {
74
+ id: string;
75
+ type: BoundType;
76
+ }
77
+ //#endregion
78
+ //#region src/ObserveEventsOptions.d.ts
79
+ type ObserveIfEventIsMissing = 'read-everything' | 'wait-for-event';
80
+ interface ObserveFromLatestEvent {
81
+ subject: string;
82
+ type: string;
83
+ ifEventIsMissing: ObserveIfEventIsMissing;
84
+ }
85
+ interface ObserveEventsOptions {
86
+ recursive: boolean;
87
+ lowerBound?: Bound;
88
+ fromLatestEvent?: ObserveFromLatestEvent;
89
+ }
90
+ //#endregion
91
+ //#region src/Precondition.d.ts
92
+ interface IsSubjectPristinePrecondition {
93
+ subject: string;
94
+ }
95
+ interface IsSubjectPopulatedPrecondition {
96
+ subject: string;
97
+ }
98
+ interface IsSubjectOnEventIdPrecondition {
99
+ subject: string;
100
+ eventId: string;
101
+ }
102
+ interface IsEventQlQueryTruePrecondition {
103
+ query: string;
104
+ }
105
+ type Precondition = {
106
+ type: 'isSubjectPristine';
107
+ payload: IsSubjectPristinePrecondition;
108
+ } | {
109
+ type: 'isSubjectOnEventId';
110
+ payload: IsSubjectOnEventIdPrecondition;
111
+ } | {
112
+ type: 'isSubjectPopulated';
113
+ payload: IsSubjectPopulatedPrecondition;
114
+ } | {
115
+ type: 'isEventQlQueryTrue';
116
+ payload: IsEventQlQueryTruePrecondition;
117
+ };
118
+ //#endregion
119
+ //#region src/ReadEventsOptions.d.ts
120
+ type Order = 'chronological' | 'antichronological';
121
+ type ReadIfEventIsMissing = 'read-nothing' | 'read-everything';
122
+ interface ReadFromLatestEvent {
123
+ subject: string;
124
+ type: string;
125
+ ifEventIsMissing: ReadIfEventIsMissing;
126
+ }
127
+ interface ReadEventsOptions {
128
+ recursive: boolean;
129
+ order?: Order;
130
+ lowerBound?: Bound;
131
+ upperBound?: Bound;
132
+ fromLatestEvent?: ReadFromLatestEvent;
133
+ }
134
+ //#endregion
135
+ //#region src/Client.d.ts
136
+ declare class Client {
137
+ #private;
138
+ constructor(url: URL, apiToken: string);
139
+ ping(): Promise<void>;
140
+ verifyApiToken(): Promise<void>;
141
+ writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
142
+ readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
143
+ runEventQlQuery(query: string, signal?: AbortSignal): AsyncGenerator<unknown, void, void>;
144
+ observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
145
+ registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
146
+ readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
147
+ readEventType(eventType: string): Promise<EventType>;
148
+ readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
149
+ }
150
+ //#endregion
151
+ //#region src/Container.d.ts
152
+ declare class Container {
153
+ #private;
154
+ withImageTag(tag: string): this;
155
+ withApiToken(token: string): this;
156
+ withSigningKey(): this;
157
+ withPort(port: number): this;
158
+ start(): Promise<void>;
159
+ getHost(): string;
160
+ getMappedPort(): number;
161
+ getBaseUrl(): URL;
162
+ getApiToken(): string;
163
+ getSigningKey(): crypto.KeyObject;
164
+ getVerificationKey(): crypto.KeyObject;
165
+ isRunning(): boolean;
166
+ stop(): Promise<void>;
167
+ getClient(): Client;
168
+ }
169
+ //#endregion
170
+ //#region src/isEventQlQueryTrue.d.ts
171
+ declare const isEventQlQueryTrue: (query: string) => Precondition;
172
+ //#endregion
173
+ //#region src/isSubjectOnEventId.d.ts
174
+ declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
175
+ //#endregion
176
+ //#region src/isSubjectPopulated.d.ts
177
+ declare const isSubjectPopulated: (subject: string) => Precondition;
178
+ //#endregion
179
+ //#region src/isSubjectPristine.d.ts
180
+ declare const isSubjectPristine: (subject: string) => Precondition;
181
+ //#endregion
182
+ export { Client, Container, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
package/dist/index.d.mts CHANGED
@@ -1,10 +1,41 @@
1
- import crypto from 'node:crypto';
1
+ import crypto from "node:crypto";
2
2
 
3
+ //#region src/Event.d.ts
3
4
  declare class Event {
4
- #private;
5
+ #private;
6
+ specversion: string;
7
+ id: string;
8
+ time: Date;
9
+ source: string;
10
+ subject: string;
11
+ type: string;
12
+ datacontenttype: string;
13
+ data: Record<string, unknown>;
14
+ hash: string;
15
+ predecessorhash: string;
16
+ traceparent?: string;
17
+ tracestate?: string;
18
+ signature: string | null;
19
+ constructor({
20
+ specversion,
21
+ id,
22
+ time,
23
+ timeFromServer,
24
+ source,
25
+ subject,
26
+ type,
27
+ datacontenttype,
28
+ data,
29
+ hash,
30
+ predecessorhash,
31
+ traceparent,
32
+ tracestate,
33
+ signature
34
+ }: {
5
35
  specversion: string;
6
36
  id: string;
7
37
  time: Date;
38
+ timeFromServer: string;
8
39
  source: string;
9
40
  subject: string;
10
41
  type: string;
@@ -15,140 +46,137 @@ declare class Event {
15
46
  traceparent?: string;
16
47
  tracestate?: string;
17
48
  signature: string | null;
18
- constructor({ specversion, id, time, timeFromServer, source, subject, type, datacontenttype, data, hash, predecessorhash, traceparent, tracestate, signature, }: {
19
- specversion: string;
20
- id: string;
21
- time: Date;
22
- timeFromServer: string;
23
- source: string;
24
- subject: string;
25
- type: string;
26
- datacontenttype: string;
27
- data: Record<string, unknown>;
28
- hash: string;
29
- predecessorhash: string;
30
- traceparent?: string;
31
- tracestate?: string;
32
- signature: string | null;
33
- });
34
- verifyHash(): void;
35
- verifySignature(verificationKey: crypto.KeyObject): void;
49
+ });
50
+ verifyHash(): void;
51
+ verifySignature(verificationKey: crypto.KeyObject): void;
36
52
  }
37
-
53
+ //#endregion
54
+ //#region src/EventCandidate.d.ts
38
55
  interface EventCandidate {
39
- source: string;
40
- subject: string;
41
- type: string;
42
- data: Record<string, unknown>;
43
- traceparent?: string;
44
- tracestate?: string;
56
+ source: string;
57
+ subject: string;
58
+ type: string;
59
+ data: Record<string, unknown>;
60
+ traceparent?: string;
61
+ tracestate?: string;
45
62
  }
46
-
63
+ //#endregion
64
+ //#region src/EventType.d.ts
47
65
  interface EventType {
48
- eventType: string;
49
- isPhantom: boolean;
50
- schema?: Record<string, unknown>;
66
+ eventType: string;
67
+ isPhantom: boolean;
68
+ schema?: Record<string, unknown>;
51
69
  }
52
-
70
+ //#endregion
71
+ //#region src/Bound.d.ts
53
72
  type BoundType = 'inclusive' | 'exclusive';
54
73
  interface Bound {
55
- id: string;
56
- type: BoundType;
74
+ id: string;
75
+ type: BoundType;
57
76
  }
58
-
77
+ //#endregion
78
+ //#region src/ObserveEventsOptions.d.ts
59
79
  type ObserveIfEventIsMissing = 'read-everything' | 'wait-for-event';
60
80
  interface ObserveFromLatestEvent {
61
- subject: string;
62
- type: string;
63
- ifEventIsMissing: ObserveIfEventIsMissing;
81
+ subject: string;
82
+ type: string;
83
+ ifEventIsMissing: ObserveIfEventIsMissing;
64
84
  }
65
85
  interface ObserveEventsOptions {
66
- recursive: boolean;
67
- lowerBound?: Bound;
68
- fromLatestEvent?: ObserveFromLatestEvent;
86
+ recursive: boolean;
87
+ lowerBound?: Bound;
88
+ fromLatestEvent?: ObserveFromLatestEvent;
69
89
  }
70
-
90
+ //#endregion
91
+ //#region src/Precondition.d.ts
71
92
  interface IsSubjectPristinePrecondition {
72
- subject: string;
93
+ subject: string;
73
94
  }
74
95
  interface IsSubjectPopulatedPrecondition {
75
- subject: string;
96
+ subject: string;
76
97
  }
77
98
  interface IsSubjectOnEventIdPrecondition {
78
- subject: string;
79
- eventId: string;
99
+ subject: string;
100
+ eventId: string;
80
101
  }
81
102
  interface IsEventQlQueryTruePrecondition {
82
- query: string;
103
+ query: string;
83
104
  }
84
105
  type Precondition = {
85
- type: 'isSubjectPristine';
86
- payload: IsSubjectPristinePrecondition;
106
+ type: 'isSubjectPristine';
107
+ payload: IsSubjectPristinePrecondition;
87
108
  } | {
88
- type: 'isSubjectOnEventId';
89
- payload: IsSubjectOnEventIdPrecondition;
109
+ type: 'isSubjectOnEventId';
110
+ payload: IsSubjectOnEventIdPrecondition;
90
111
  } | {
91
- type: 'isSubjectPopulated';
92
- payload: IsSubjectPopulatedPrecondition;
112
+ type: 'isSubjectPopulated';
113
+ payload: IsSubjectPopulatedPrecondition;
93
114
  } | {
94
- type: 'isEventQlQueryTrue';
95
- payload: IsEventQlQueryTruePrecondition;
115
+ type: 'isEventQlQueryTrue';
116
+ payload: IsEventQlQueryTruePrecondition;
96
117
  };
97
-
118
+ //#endregion
119
+ //#region src/ReadEventsOptions.d.ts
98
120
  type Order = 'chronological' | 'antichronological';
99
121
  type ReadIfEventIsMissing = 'read-nothing' | 'read-everything';
100
122
  interface ReadFromLatestEvent {
101
- subject: string;
102
- type: string;
103
- ifEventIsMissing: ReadIfEventIsMissing;
123
+ subject: string;
124
+ type: string;
125
+ ifEventIsMissing: ReadIfEventIsMissing;
104
126
  }
105
127
  interface ReadEventsOptions {
106
- recursive: boolean;
107
- order?: Order;
108
- lowerBound?: Bound;
109
- upperBound?: Bound;
110
- fromLatestEvent?: ReadFromLatestEvent;
128
+ recursive: boolean;
129
+ order?: Order;
130
+ lowerBound?: Bound;
131
+ upperBound?: Bound;
132
+ fromLatestEvent?: ReadFromLatestEvent;
111
133
  }
112
-
134
+ //#endregion
135
+ //#region src/Client.d.ts
113
136
  declare class Client {
114
- #private;
115
- constructor(url: URL, apiToken: string);
116
- ping(): Promise<void>;
117
- verifyApiToken(): Promise<void>;
118
- writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
119
- readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
120
- runEventQlQuery(query: string, signal?: AbortSignal): AsyncGenerator<unknown, void, void>;
121
- observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
122
- registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
123
- readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
124
- readEventType(eventType: string): Promise<EventType>;
125
- readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
137
+ #private;
138
+ constructor(url: URL, apiToken: string);
139
+ ping(): Promise<void>;
140
+ verifyApiToken(): Promise<void>;
141
+ writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
142
+ readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
143
+ runEventQlQuery(query: string, signal?: AbortSignal): AsyncGenerator<unknown, void, void>;
144
+ observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
145
+ registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
146
+ readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
147
+ readEventType(eventType: string): Promise<EventType>;
148
+ readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
126
149
  }
127
-
150
+ //#endregion
151
+ //#region src/Container.d.ts
128
152
  declare class Container {
129
- #private;
130
- withImageTag(tag: string): this;
131
- withApiToken(token: string): this;
132
- withSigningKey(): this;
133
- withPort(port: number): this;
134
- start(): Promise<void>;
135
- getHost(): string;
136
- getMappedPort(): number;
137
- getBaseUrl(): URL;
138
- getApiToken(): string;
139
- getSigningKey(): crypto.KeyObject;
140
- getVerificationKey(): crypto.KeyObject;
141
- isRunning(): boolean;
142
- stop(): Promise<void>;
143
- getClient(): Client;
153
+ #private;
154
+ withImageTag(tag: string): this;
155
+ withApiToken(token: string): this;
156
+ withSigningKey(): this;
157
+ withPort(port: number): this;
158
+ start(): Promise<void>;
159
+ getHost(): string;
160
+ getMappedPort(): number;
161
+ getBaseUrl(): URL;
162
+ getApiToken(): string;
163
+ getSigningKey(): crypto.KeyObject;
164
+ getVerificationKey(): crypto.KeyObject;
165
+ isRunning(): boolean;
166
+ stop(): Promise<void>;
167
+ getClient(): Client;
144
168
  }
145
-
169
+ //#endregion
170
+ //#region src/isEventQlQueryTrue.d.ts
146
171
  declare const isEventQlQueryTrue: (query: string) => Precondition;
147
-
172
+ //#endregion
173
+ //#region src/isSubjectOnEventId.d.ts
148
174
  declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
149
-
175
+ //#endregion
176
+ //#region src/isSubjectPopulated.d.ts
150
177
  declare const isSubjectPopulated: (subject: string) => Precondition;
151
-
178
+ //#endregion
179
+ //#region src/isSubjectPristine.d.ts
152
180
  declare const isSubjectPristine: (subject: string) => Precondition;
153
-
154
- export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
181
+ //#endregion
182
+ export { Client, Container, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
package/dist/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
- import g from"crypto";var S=class{specversion;id;time;#n;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:r,time:o,timeFromServer:s,source:c,subject:d,type:u,datacontenttype:a,data:n,hash:i,predecessorhash:h,traceparent:A,tracestate:H,signature:F}){this.specversion=e,this.id=r,this.time=o,this.#n=s,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=n,this.hash=i,this.predecessorhash=h,this.traceparent=A,this.tracestate=H,this.signature=F}verifyHash(){let e=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#n}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=g.createHash("sha256").update(e).digest("hex"),o=g.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(g.createHash("sha256").update(`${r}${o}`).digest("hex")!==this.hash)throw new Error("Failed to verify hash.")}verifySignature(e){if(this.signature===null)throw new Error("Signature must not be null.");this.verifyHash();let r="esdb:signature:v1:";if(!this.signature.startsWith(r))throw new Error(`Signature must start with '${r}'`);let o=this.signature.slice(r.length),s=Buffer.from(o,"hex"),c=Buffer.from(this.hash,"utf8");if(!g.verify(null,c,e,s))throw new Error("Signature verification failed.")}};var E=t=>new S({specversion:t.specversion,id:t.id,time:new Date(t.time),timeFromServer:t.time,source:t.source,subject:t.subject,type:t.type,datacontenttype:t.datacontenttype,data:t.data,hash:t.hash,predecessorhash:t.predecessorhash,traceparent:t.traceparent,tracestate:t.tracestate,signature:t.signature});var y=t=>!(t===null||typeof t!="object"||Array.isArray(t));var f=(t,e)=>{if(!y(t))return!1;for(let r of Object.keys(e)){let o=e[r],s=t[r];if(typeof o=="function"){if(!o(s))return!1;continue}if(!y(s)||!f(s,o))return!1}return!0};var p=t=>typeof t=="string";var T=t=>t===null||typeof t=="string";var l=t=>t===void 0||typeof t=="string";var O=t=>f(t,{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:l,tracestate:l,signature:T});var m=t=>{let e=t.headers.get("Server");return!(!e||!e.startsWith("EventSourcingDB/"))};var v=async function*(t,e){let r=t.getReader(),o=new TextDecoder("utf-8"),s="",c=()=>{r.cancel().catch(()=>{})};if(e.aborted){await r.cancel().catch(()=>{});return}e.addEventListener("abort",c);try{for(;!e.aborted;){let{done:d,value:u}=await r.read();if(d)break;s+=o.decode(u,{stream:!0});let a;for(;a=s.indexOf(`
2
- `),a!==-1;){let n=s.slice(0,a).trim();s=s.slice(a+1),n&&(yield JSON.parse(n))}}}finally{e.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var P=t=>f(t,{type:e=>e==="event",payload:{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:l,tracestate:l,signature:T}});var b=t=>f(t,{type:e=>e==="error",payload:{error:p}});var j=t=>typeof t=="boolean";var C=t=>f(t,{type:e=>e==="eventType",payload:{eventType:p,isPhantom:j}});var k=t=>f(t,{type:e=>e==="heartbeat"});var B=t=>f(t,{type:e=>e==="row",payload:e=>e!==void 0});var $=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var w=class{#n;#t;#e(e){return new URL(e,this.#n).toString()}constructor(e,r){this.#n=e,this.#t=r}async ping(){let e=this.#e("/api/v1/ping"),r=await fetch(e,{method:"get"});if(!m(r))throw new Error("Server must be EventSourcingDB.");if(r.status!==200)throw new Error(`Failed to ping, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!f(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let e=this.#e("/api/v1/verify-api-token"),r=await fetch(e,{method:"post",headers:{authorization:`Bearer ${this.#t}`}});if(!m(r))throw new Error("Server must be EventSourcingDB.");if(r.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!f(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(e,r=[]){let o=this.#e("/api/v1/write-events"),s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({events:e,preconditions:r})});if(!m(s))throw new Error("Server must be EventSourcingDB.");if(s.status!==200)throw new Error(`Failed to write events, got HTTP status code '${s.status}', expected '200'.`);let c=await s.json();if(!Array.isArray(c))throw new Error("Failed to parse response.");return c.map(u=>{if(!O(u))throw new Error("Failed to parse response item.");return E(u)})}readEvents(e,r,o){let s=this.#e("/api/v1/read-events"),c=this.#t;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let i=()=>d.abort();o.addEventListener("abort",i,{once:!0}),n=()=>o.removeEventListener("abort",i)}try{let i=await fetch(s,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:e,options:r}),signal:u});if(!m(i)){let h=i.headers.get("Server");throw h?new Error(`Server must be EventSourcingDB, got Server header: '${h}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(i.status!==200)throw new Error(`Failed to read events, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to read events.");for await(let h of v(i.body,u)){if(b(h))throw new Error(`${h.payload.error}.`);if(P(h)){yield E(h.payload);continue}throw new Error("Failed to read events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{n&&n(),a&&d.abort()}})()}runEventQlQuery(e,r){let o=this.#e("/api/v1/run-eventql-query"),s=this.#t;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let n=()=>c.abort();r.addEventListener("abort",n,{once:!0}),a=()=>r.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(n)){let i=n.headers.get("Server");throw i?new Error(`Server must be EventSourcingDB, got Server header: '${i}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(n.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to run EventQL query.");for await(let i of v(n.body,d))if(!k(i)){if(b(i))throw new Error(`${i.payload.error}.`);if(B(i)){yield i.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,o){let s=this.#e("/api/v1/observe-events"),c=this.#t;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let i=()=>d.abort();o.addEventListener("abort",i,{once:!0}),n=()=>o.removeEventListener("abort",i)}try{let i=await fetch(s,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:e,options:r}),signal:u});if(!m(i)){let h=i.headers.get("Server");throw h?new Error(`Server must be EventSourcingDB, got Server header: '${h}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(i.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to observe events.");for await(let h of v(i.body,u))if(!k(h)){if(b(h))throw new Error(`${h.payload.error}.`);if(P(h)){yield E(h.payload);continue}throw new Error("Failed to observe events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{n&&n(),a&&d.abort()}})()}async registerEventSchema(e,r){let o=this.#e("/api/v1/register-event-schema"),s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({eventType:e,schema:r})});if(!m(s))throw new Error("Server must be EventSourcingDB.");if(s.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${s.status}', expected '200'.`)}readSubjects(e,r){let o=this.#e("/api/v1/read-subjects"),s=this.#t;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let n=()=>c.abort();r.addEventListener("abort",n,{once:!0}),a=()=>r.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(n)){let i=n.headers.get("Server");throw i?new Error(`Server must be EventSourcingDB, got Server header: '${i}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(n.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to read subjects.");for await(let i of v(n.body,d)){if(b(i))throw new Error(`${i.payload.error}.`);if($(i)){yield i.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}async readEventType(e){let r=this.#e("/api/v1/read-event-type"),o=await fetch(r,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({eventType:e})});if(!m(o))throw new Error("Server must be EventSourcingDB.");if(o.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${o.status}', expected '200'.`);let s=await o.json();if(!f(s,{eventType:p,isPhantom:j}))throw new Error("Failed to parse response.");return s}readEventTypes(e){let r=this.#e("/api/v1/read-event-types"),o=this.#t;return(async function*(){let s=new AbortController,c=e??s.signal,d=!e,u;if(e&&!e.aborted){let a=()=>s.abort();e.addEventListener("abort",a,{once:!0}),u=()=>e.removeEventListener("abort",a)}try{let a=await fetch(r,{method:"post",headers:{authorization:`Bearer ${o}`},signal:c});if(!m(a)){let n=a.headers.get("Server");throw n?new Error(`Server must be EventSourcingDB, got Server header: '${n}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let n of v(a.body,c))if(!k(n)){if(b(n))throw new Error(`${n.payload.error}.`);if(C(n)){yield n.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&s.abort()}})()}};import R from"crypto";import{GenericContainer as D,Wait as L}from"testcontainers";var x=class{#n="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#o;#r;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#i=e,this}withSigningKey(){let{privateKey:e}=R.generateKeyPairSync("ed25519");return this.#o=e,this}withPort(e){return this.#e=e,this}async start(){let e=["run","--api-token",this.#i,"--data-directory-temporary","--http-enabled","--https-enabled=false"],r=[];this.#o!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#o.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new D(`${this.#n}:${this.#t}`).withExposedPorts(this.#e).withCommand(e).withCopyContentToContainer(r).withWaitStrategy(L.forHttp("/api/v1/ping",this.#e).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#e)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let e=this.getHost(),r=this.getMappedPort();return new URL(`http://${e}:${r}`)}getApiToken(){return this.#i}getSigningKey(){if(this.#o===void 0)throw new Error("Signing key not set.");return this.#o}getVerificationKey(){if(this.#o===void 0)throw new Error("Signing key not set.");return R.createPublicKey(this.#o)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new w(this.getBaseUrl(),this.getApiToken())}};var K=t=>({type:"isEventQlQueryTrue",payload:{query:t}});var N=(t,e)=>({type:"isSubjectOnEventId",payload:{subject:t,eventId:e}});var U=t=>({type:"isSubjectPopulated",payload:{subject:t}});var G=t=>({type:"isSubjectPristine",payload:{subject:t}});export{w as Client,x as Container,K as isEventQlQueryTrue,N as isSubjectOnEventId,U as isSubjectPopulated,G as isSubjectPristine};
1
+ import e from"node:crypto";import{GenericContainer as t,Wait as n}from"testcontainers";var r=class{specversion;id;time;#e;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:t,time:n,timeFromServer:r,source:i,subject:a,type:o,datacontenttype:s,data:c,hash:l,predecessorhash:u,traceparent:d,tracestate:f,signature:p}){this.specversion=e,this.id=t,this.time=n,this.#e=r,this.source=i,this.subject=a,this.type=o,this.datacontenttype=s,this.data=c,this.hash=l,this.predecessorhash=u,this.traceparent=d,this.tracestate=f,this.signature=p}verifyHash(){let t=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#e}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,n=e.createHash(`sha256`).update(t).digest(`hex`),r=e.createHash(`sha256`).update(JSON.stringify(this.data)).digest(`hex`);if(e.createHash(`sha256`).update(`${n}${r}`).digest(`hex`)!==this.hash)throw Error(`Failed to verify hash.`)}verifySignature(t){if(this.signature===null)throw Error(`Signature must not be null.`);this.verifyHash();let n=`esdb:signature:v1:`;if(!this.signature.startsWith(n))throw Error(`Signature must start with '${n}'`);let r=this.signature.slice(18),i=Buffer.from(r,`hex`),a=Buffer.from(this.hash,`utf8`);if(!e.verify(null,a,t,i))throw Error(`Signature verification failed.`)}};const i=e=>new r({specversion:e.specversion,id:e.id,time:new Date(e.time),timeFromServer:e.time,source:e.source,subject:e.subject,type:e.type,datacontenttype:e.datacontenttype,data:e.data,hash:e.hash,predecessorhash:e.predecessorhash,traceparent:e.traceparent,tracestate:e.tracestate,signature:e.signature}),a=e=>!(typeof e!=`object`||!e||Array.isArray(e)),o=(e,t)=>{if(!a(e))return!1;for(let n of Object.keys(t)){let r=t[n],i=e[n];if(typeof r==`function`){if(!r(i))return!1;continue}if(!a(i)||!o(i,r))return!1}return!0},s=e=>typeof e==`string`,c=e=>e===null||typeof e==`string`,l=e=>e===void 0||typeof e==`string`,u=e=>o(e,{specversion:s,id:s,time:s,source:s,subject:s,type:s,datacontenttype:s,data:a,hash:s,predecessorhash:s,traceparent:l,tracestate:l,signature:c}),d=e=>{let t=e.headers.get(`Server`);return!(!t||!t.startsWith(`EventSourcingDB/`))},f=async function*(e,t){let n=e.getReader(),r=new TextDecoder(`utf-8`),i=``,a=()=>{n.cancel().catch(()=>{})};if(t.aborted){await n.cancel().catch(()=>{});return}t.addEventListener(`abort`,a);try{for(;!t.aborted;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.indexOf(`
2
+ `);for(;a!==-1;){let e=i.slice(0,a).trim();i=i.slice(a+1),e&&(yield JSON.parse(e)),a=i.indexOf(`
3
+ `)}}}finally{t.removeEventListener(`abort`,a),await n.cancel().catch(()=>{})}},p=e=>o(e,{type:e=>e===`event`,payload:{specversion:s,id:s,time:s,source:s,subject:s,type:s,datacontenttype:s,data:a,hash:s,predecessorhash:s,traceparent:l,tracestate:l,signature:c}}),m=e=>o(e,{type:e=>e===`error`,payload:{error:s}}),h=e=>typeof e==`boolean`,g=e=>o(e,{type:e=>e===`eventType`,payload:{eventType:s,isPhantom:h}}),_=e=>o(e,{type:e=>e===`heartbeat`}),v=e=>o(e,{type:e=>e===`row`,payload:e=>e!==void 0}),y=e=>o(e,{type:e=>e===`subject`,payload:{subject:s}});var b=class{#e;#t;#n(e){return new URL(e,this.#e).toString()}constructor(e,t){this.#e=e,this.#t=t}async ping(){let e=this.#n(`/api/v1/ping`),t=await fetch(e,{method:`get`});if(!d(t))throw Error(`Server must be EventSourcingDB.`);if(t.status!==200)throw Error(`Failed to ping, got HTTP status code '${t.status}', expected '200'.`);let n=await t.json();if(!o(n,{type:s}))throw Error(`Failed to parse response.`);if(n.type!==`io.eventsourcingdb.api.ping-received`)throw Error(`Failed to ping.`)}async verifyApiToken(){let e=this.#n(`/api/v1/verify-api-token`),t=await fetch(e,{method:`post`,headers:{authorization:`Bearer ${this.#t}`}});if(!d(t))throw Error(`Server must be EventSourcingDB.`);if(t.status!==200)throw Error(`Failed to verify API token, got HTTP status code '${t.status}', expected '200'.`);let n=await t.json();if(!o(n,{type:s}))throw Error(`Failed to parse response.`);if(n.type!==`io.eventsourcingdb.api.api-token-verified`)throw Error(`Failed to verify API token.`)}async writeEvents(e,t=[]){let n=this.#n(`/api/v1/write-events`),r=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({events:e,preconditions:t})});if(!d(r))throw Error(`Server must be EventSourcingDB.`);if(r.status!==200)throw Error(`Failed to write events, got HTTP status code '${r.status}', expected '200'.`);let a=await r.json();if(!Array.isArray(a))throw Error(`Failed to parse response.`);return a.map(e=>{if(!u(e))throw Error(`Failed to parse response item.`);return i(e)})}readEvents(e,t,n){let r=this.#n(`/api/v1/read-events`),a=this.#t;return(async function*(){let o=new AbortController,s=n??o.signal,c=!n,l;if(n&&!n.aborted){let e=()=>o.abort();n.addEventListener(`abort`,e,{once:!0}),l=()=>n.removeEventListener(`abort`,e)}try{let n=await fetch(r,{method:`post`,headers:{authorization:`Bearer ${a}`,"content-type":`application/json`},body:JSON.stringify({subject:e,options:t}),signal:s});if(!d(n)){let e=n.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(n.status!==200)throw Error(`Failed to read events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw Error(`Failed to read events.`);for await(let e of f(n.body,s)){if(m(e))throw Error(`${e.payload.error}.`);if(p(e)){yield i(e.payload);continue}throw Error(`Failed to read events.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{l&&l(),c&&o.abort()}})()}runEventQlQuery(e,t){let n=this.#n(`/api/v1/run-eventql-query`),r=this.#t;return(async function*(){let i=new AbortController,a=t??i.signal,o=!t,s;if(t&&!t.aborted){let e=()=>i.abort();t.addEventListener(`abort`,e,{once:!0}),s=()=>t.removeEventListener(`abort`,e)}try{let t=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${r}`,"content-type":`application/json`},body:JSON.stringify({query:e}),signal:a});if(!d(t)){let e=t.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(t.status!==200)throw Error(`Failed to run EventQL query, got HTTP status code '${t.status}', expected '200'.`);if(!t.body)throw Error(`Failed to run EventQL query.`);for await(let e of f(t.body,a))if(!_(e)){if(m(e))throw Error(`${e.payload.error}.`);if(v(e)){yield e.payload;continue}throw Error(`Failed to run EventQL query.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{s&&s(),o&&i.abort()}})()}observeEvents(e,t,n){let r=this.#n(`/api/v1/observe-events`),a=this.#t;return(async function*(){let o=new AbortController,s=n??o.signal,c=!n,l;if(n&&!n.aborted){let e=()=>o.abort();n.addEventListener(`abort`,e,{once:!0}),l=()=>n.removeEventListener(`abort`,e)}try{let n=await fetch(r,{method:`post`,headers:{authorization:`Bearer ${a}`,"content-type":`application/json`},body:JSON.stringify({subject:e,options:t}),signal:s});if(!d(n)){let e=n.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(n.status!==200)throw Error(`Failed to observe events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw Error(`Failed to observe events.`);for await(let e of f(n.body,s))if(!_(e)){if(m(e))throw Error(`${e.payload.error}.`);if(p(e)){yield i(e.payload);continue}throw Error(`Failed to observe events.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{l&&l(),c&&o.abort()}})()}async registerEventSchema(e,t){let n=this.#n(`/api/v1/register-event-schema`),r=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({eventType:e,schema:t})});if(!d(r))throw Error(`Server must be EventSourcingDB.`);if(r.status!==200)throw Error(`Failed to register event schema, got HTTP status code '${r.status}', expected '200'.`)}readSubjects(e,t){let n=this.#n(`/api/v1/read-subjects`),r=this.#t;return(async function*(){let i=new AbortController,a=t??i.signal,o=!t,s;if(t&&!t.aborted){let e=()=>i.abort();t.addEventListener(`abort`,e,{once:!0}),s=()=>t.removeEventListener(`abort`,e)}try{let t=await fetch(n,{method:`post`,headers:{authorization:`Bearer ${r}`,"content-type":`application/json`},body:JSON.stringify({baseSubject:e}),signal:a});if(!d(t)){let e=t.headers.get(`Server`);throw Error(e?`Server must be EventSourcingDB, got Server header: '${e}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(t.status!==200)throw Error(`Failed to read subjects, got HTTP status code '${t.status}', expected '200'.`);if(!t.body)throw Error(`Failed to read subjects.`);for await(let e of f(t.body,a)){if(m(e))throw Error(`${e.payload.error}.`);if(y(e)){yield e.payload.subject;continue}throw Error(`Failed to read subjects.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{s&&s(),o&&i.abort()}})()}async readEventType(e){let t=this.#n(`/api/v1/read-event-type`),n=await fetch(t,{method:`post`,headers:{authorization:`Bearer ${this.#t}`,"content-type":`application/json`},body:JSON.stringify({eventType:e})});if(!d(n))throw Error(`Server must be EventSourcingDB.`);if(n.status!==200)throw Error(`Failed to read event type, got HTTP status code '${n.status}', expected '200'.`);let r=await n.json();if(!o(r,{eventType:s,isPhantom:h}))throw Error(`Failed to parse response.`);return r}readEventTypes(e){let t=this.#n(`/api/v1/read-event-types`),n=this.#t;return(async function*(){let r=new AbortController,i=e??r.signal,a=!e,o;if(e&&!e.aborted){let t=()=>r.abort();e.addEventListener(`abort`,t,{once:!0}),o=()=>e.removeEventListener(`abort`,t)}try{let e=await fetch(t,{method:`post`,headers:{authorization:`Bearer ${n}`},signal:i});if(!d(e)){let t=e.headers.get(`Server`);throw Error(t?`Server must be EventSourcingDB, got Server header: '${t}'.`:`Server must be EventSourcingDB, but Server header is missing.`)}if(e.status!==200)throw Error(`Failed to read event types, got HTTP status code '${e.status}', expected '200'.`);if(!e.body)throw Error(`Failed to read event types.`);for await(let t of f(e.body,i))if(!_(t)){if(m(t))throw Error(`${t.payload.error}.`);if(g(t)){yield t.payload;continue}throw Error(`Failed to read event types.`)}}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}finally{o&&o(),a&&r.abort()}})()}},x=class{#e=`thenativeweb/eventsourcingdb`;#t=`latest`;#n=3e3;#r=`secret`;#i;#a;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#r=e,this}withSigningKey(){let{privateKey:t}=e.generateKeyPairSync(`ed25519`);return this.#i=t,this}withPort(e){return this.#n=e,this}async start(){let e=[`run`,`--api-token`,this.#r,`--data-directory-temporary`,`--http-enabled`,`--https-enabled=false`],r=[];this.#i!==void 0&&(e.push(`--signing-key-file`),e.push(`/etc/esdb/signing-key.pem`),r.push({content:this.#i.export({format:`pem`,type:`pkcs8`}),target:`/etc/esdb/signing-key.pem`,mode:511})),this.#a=await new t(`${this.#e}:${this.#t}`).withExposedPorts(this.#n).withCommand(e).withCopyContentToContainer(r).withWaitStrategy(n.forHttp(`/api/v1/ping`,this.#n).withStartupTimeout(1e4)).start()}getHost(){if(this.#a===void 0)throw Error(`Container must be running.`);return this.#a.getHost()}getMappedPort(){if(this.#a===void 0)throw Error(`Container must be running.`);return this.#a.getMappedPort(this.#n)}getBaseUrl(){if(this.#a===void 0)throw Error(`Container must be running.`);let e=this.getHost(),t=this.getMappedPort();return new URL(`http://${e}:${t}`)}getApiToken(){return this.#r}getSigningKey(){if(this.#i===void 0)throw Error(`Signing key not set.`);return this.#i}getVerificationKey(){if(this.#i===void 0)throw Error(`Signing key not set.`);return e.createPublicKey(this.#i)}isRunning(){return this.#a!==void 0}async stop(){this.#a!==void 0&&(await this.#a.stop(),this.#a=void 0)}getClient(){return new b(this.getBaseUrl(),this.getApiToken())}};const S=e=>({type:`isEventQlQueryTrue`,payload:{query:e}}),C=(e,t)=>({type:`isSubjectOnEventId`,payload:{subject:e,eventId:t}}),w=e=>({type:`isSubjectPopulated`,payload:{subject:e}}),T=e=>({type:`isSubjectPristine`,payload:{subject:e}});export{b as Client,x as Container,S as isEventQlQueryTrue,C as isSubjectOnEventId,w as isSubjectPopulated,T as isSubjectPristine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eventsourcingdb",
3
- "version": "1.8.1",
3
+ "version": "1.8.2",
4
4
  "description": "The official JavaScript client SDK for EventSourcingDB.",
5
5
  "author": {
6
6
  "name": "the native web GmbH",
@@ -8,25 +8,31 @@
8
8
  },
9
9
  "exports": {
10
10
  ".": {
11
- "import": "./dist/index.mjs",
12
- "require": "./dist/index.js"
11
+ "import": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
13
19
  }
14
20
  },
15
- "types": "./dist/index.d.ts",
21
+ "types": "./dist/index.d.cts",
16
22
  "dependencies": {
17
- "testcontainers": "11.10.0"
23
+ "testcontainers": "12.0.4"
18
24
  },
19
25
  "devDependencies": {
20
- "@biomejs/biome": "2.3.8",
21
- "@types/node": "24.10.1",
22
- "get-port": "7.1.0",
23
- "tsup": "8.5.1",
24
- "tsx": "4.21.0",
25
- "typescript": "5.9.3"
26
+ "@biomejs/biome": "2.5.2",
27
+ "@types/node": "25.9.3",
28
+ "get-port": "7.2.0",
29
+ "tsdown": "0.22.3",
30
+ "tsx": "4.22.5",
31
+ "typescript": "6.0.3"
26
32
  },
27
33
  "scripts": {
28
34
  "analyze": "npx tsc --noEmit && npx biome check --error-on-warnings .",
29
- "build": "npx tsc --noEmit && npx tsup --clean --dts --format cjs,esm --minify --out-dir=./dist/ ./src/index.ts",
35
+ "build": "npx tsc --noEmit && npx tsdown --format cjs,esm --dts --minify --out-dir ./dist ./src/index.ts",
30
36
  "format": "npx biome check --write .",
31
37
  "qa": "npm run analyze && npm run test",
32
38
  "test": "node --test --import tsx \"./src/**/*.test.ts\""
package/dist/index.d.ts DELETED
@@ -1,154 +0,0 @@
1
- import crypto from 'node:crypto';
2
-
3
- declare class Event {
4
- #private;
5
- specversion: string;
6
- id: string;
7
- time: Date;
8
- source: string;
9
- subject: string;
10
- type: string;
11
- datacontenttype: string;
12
- data: Record<string, unknown>;
13
- hash: string;
14
- predecessorhash: string;
15
- traceparent?: string;
16
- tracestate?: string;
17
- signature: string | null;
18
- constructor({ specversion, id, time, timeFromServer, source, subject, type, datacontenttype, data, hash, predecessorhash, traceparent, tracestate, signature, }: {
19
- specversion: string;
20
- id: string;
21
- time: Date;
22
- timeFromServer: string;
23
- source: string;
24
- subject: string;
25
- type: string;
26
- datacontenttype: string;
27
- data: Record<string, unknown>;
28
- hash: string;
29
- predecessorhash: string;
30
- traceparent?: string;
31
- tracestate?: string;
32
- signature: string | null;
33
- });
34
- verifyHash(): void;
35
- verifySignature(verificationKey: crypto.KeyObject): void;
36
- }
37
-
38
- interface EventCandidate {
39
- source: string;
40
- subject: string;
41
- type: string;
42
- data: Record<string, unknown>;
43
- traceparent?: string;
44
- tracestate?: string;
45
- }
46
-
47
- interface EventType {
48
- eventType: string;
49
- isPhantom: boolean;
50
- schema?: Record<string, unknown>;
51
- }
52
-
53
- type BoundType = 'inclusive' | 'exclusive';
54
- interface Bound {
55
- id: string;
56
- type: BoundType;
57
- }
58
-
59
- type ObserveIfEventIsMissing = 'read-everything' | 'wait-for-event';
60
- interface ObserveFromLatestEvent {
61
- subject: string;
62
- type: string;
63
- ifEventIsMissing: ObserveIfEventIsMissing;
64
- }
65
- interface ObserveEventsOptions {
66
- recursive: boolean;
67
- lowerBound?: Bound;
68
- fromLatestEvent?: ObserveFromLatestEvent;
69
- }
70
-
71
- interface IsSubjectPristinePrecondition {
72
- subject: string;
73
- }
74
- interface IsSubjectPopulatedPrecondition {
75
- subject: string;
76
- }
77
- interface IsSubjectOnEventIdPrecondition {
78
- subject: string;
79
- eventId: string;
80
- }
81
- interface IsEventQlQueryTruePrecondition {
82
- query: string;
83
- }
84
- type Precondition = {
85
- type: 'isSubjectPristine';
86
- payload: IsSubjectPristinePrecondition;
87
- } | {
88
- type: 'isSubjectOnEventId';
89
- payload: IsSubjectOnEventIdPrecondition;
90
- } | {
91
- type: 'isSubjectPopulated';
92
- payload: IsSubjectPopulatedPrecondition;
93
- } | {
94
- type: 'isEventQlQueryTrue';
95
- payload: IsEventQlQueryTruePrecondition;
96
- };
97
-
98
- type Order = 'chronological' | 'antichronological';
99
- type ReadIfEventIsMissing = 'read-nothing' | 'read-everything';
100
- interface ReadFromLatestEvent {
101
- subject: string;
102
- type: string;
103
- ifEventIsMissing: ReadIfEventIsMissing;
104
- }
105
- interface ReadEventsOptions {
106
- recursive: boolean;
107
- order?: Order;
108
- lowerBound?: Bound;
109
- upperBound?: Bound;
110
- fromLatestEvent?: ReadFromLatestEvent;
111
- }
112
-
113
- declare class Client {
114
- #private;
115
- constructor(url: URL, apiToken: string);
116
- ping(): Promise<void>;
117
- verifyApiToken(): Promise<void>;
118
- writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
119
- readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
120
- runEventQlQuery(query: string, signal?: AbortSignal): AsyncGenerator<unknown, void, void>;
121
- observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
122
- registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
123
- readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
124
- readEventType(eventType: string): Promise<EventType>;
125
- readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
126
- }
127
-
128
- declare class Container {
129
- #private;
130
- withImageTag(tag: string): this;
131
- withApiToken(token: string): this;
132
- withSigningKey(): this;
133
- withPort(port: number): this;
134
- start(): Promise<void>;
135
- getHost(): string;
136
- getMappedPort(): number;
137
- getBaseUrl(): URL;
138
- getApiToken(): string;
139
- getSigningKey(): crypto.KeyObject;
140
- getVerificationKey(): crypto.KeyObject;
141
- isRunning(): boolean;
142
- stop(): Promise<void>;
143
- getClient(): Client;
144
- }
145
-
146
- declare const isEventQlQueryTrue: (query: string) => Precondition;
147
-
148
- declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
149
-
150
- declare const isSubjectPopulated: (subject: string) => Precondition;
151
-
152
- declare const isSubjectPristine: (subject: string) => Precondition;
153
-
154
- export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";var Q=Object.create;var S=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var W=(t,e)=>{for(var r in e)S(t,r,{get:e[r],enumerable:!0})},$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of M(e))!q.call(t,i)&&i!==r&&S(t,i,{get:()=>e[i],enumerable:!(n=z(e,i))||n.enumerable});return t};var R=(t,e,r)=>(r=t!=null?Q(V(t)):{},$(e||!t||!t.__esModule?S(r,"default",{value:t,enumerable:!0}):r,t)),_=t=>$(S({},"__esModule",{value:!0}),t);var X={};W(X,{Client:()=>w,Container:()=>P,isEventQlQueryTrue:()=>K,isSubjectOnEventId:()=>N,isSubjectPopulated:()=>U,isSubjectPristine:()=>G});module.exports=_(X);var g=R(require("crypto")),E=class{specversion;id;time;#n;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:r,time:n,timeFromServer:i,source:c,subject:d,type:u,datacontenttype:a,data:o,hash:s,predecessorhash:h,traceparent:O,tracestate:I,signature:J}){this.specversion=e,this.id=r,this.time=n,this.#n=i,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=o,this.hash=s,this.predecessorhash=h,this.traceparent=O,this.tracestate=I,this.signature=J}verifyHash(){let e=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#n}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=g.default.createHash("sha256").update(e).digest("hex"),n=g.default.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(g.default.createHash("sha256").update(`${r}${n}`).digest("hex")!==this.hash)throw new Error("Failed to verify hash.")}verifySignature(e){if(this.signature===null)throw new Error("Signature must not be null.");this.verifyHash();let r="esdb:signature:v1:";if(!this.signature.startsWith(r))throw new Error(`Signature must start with '${r}'`);let n=this.signature.slice(r.length),i=Buffer.from(n,"hex"),c=Buffer.from(this.hash,"utf8");if(!g.default.verify(null,c,e,i))throw new Error("Signature verification failed.")}};var T=t=>new E({specversion:t.specversion,id:t.id,time:new Date(t.time),timeFromServer:t.time,source:t.source,subject:t.subject,type:t.type,datacontenttype:t.datacontenttype,data:t.data,hash:t.hash,predecessorhash:t.predecessorhash,traceparent:t.traceparent,tracestate:t.tracestate,signature:t.signature});var y=t=>!(t===null||typeof t!="object"||Array.isArray(t));var f=(t,e)=>{if(!y(t))return!1;for(let r of Object.keys(e)){let n=e[r],i=t[r];if(typeof n=="function"){if(!n(i))return!1;continue}if(!y(i)||!f(i,n))return!1}return!0};var p=t=>typeof t=="string";var j=t=>t===null||typeof t=="string";var l=t=>t===void 0||typeof t=="string";var H=t=>f(t,{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:l,tracestate:l,signature:j});var m=t=>{let e=t.headers.get("Server");return!(!e||!e.startsWith("EventSourcingDB/"))};var v=async function*(t,e){let r=t.getReader(),n=new TextDecoder("utf-8"),i="",c=()=>{r.cancel().catch(()=>{})};if(e.aborted){await r.cancel().catch(()=>{});return}e.addEventListener("abort",c);try{for(;!e.aborted;){let{done:d,value:u}=await r.read();if(d)break;i+=n.decode(u,{stream:!0});let a;for(;a=i.indexOf(`
2
- `),a!==-1;){let o=i.slice(0,a).trim();i=i.slice(a+1),o&&(yield JSON.parse(o))}}}finally{e.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var C=t=>f(t,{type:e=>e==="event",payload:{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:l,tracestate:l,signature:j}});var b=t=>f(t,{type:e=>e==="error",payload:{error:p}});var k=t=>typeof t=="boolean";var F=t=>f(t,{type:e=>e==="eventType",payload:{eventType:p,isPhantom:k}});var A=t=>f(t,{type:e=>e==="heartbeat"});var D=t=>f(t,{type:e=>e==="row",payload:e=>e!==void 0});var L=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var w=class{#n;#t;#e(e){return new URL(e,this.#n).toString()}constructor(e,r){this.#n=e,this.#t=r}async ping(){let e=this.#e("/api/v1/ping"),r=await fetch(e,{method:"get"});if(!m(r))throw new Error("Server must be EventSourcingDB.");if(r.status!==200)throw new Error(`Failed to ping, got HTTP status code '${r.status}', expected '200'.`);let n=await r.json();if(!f(n,{type:p}))throw new Error("Failed to parse response.");if(n.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let e=this.#e("/api/v1/verify-api-token"),r=await fetch(e,{method:"post",headers:{authorization:`Bearer ${this.#t}`}});if(!m(r))throw new Error("Server must be EventSourcingDB.");if(r.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${r.status}', expected '200'.`);let n=await r.json();if(!f(n,{type:p}))throw new Error("Failed to parse response.");if(n.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(e,r=[]){let n=this.#e("/api/v1/write-events"),i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({events:e,preconditions:r})});if(!m(i))throw new Error("Server must be EventSourcingDB.");if(i.status!==200)throw new Error(`Failed to write events, got HTTP status code '${i.status}', expected '200'.`);let c=await i.json();if(!Array.isArray(c))throw new Error("Failed to parse response.");return c.map(u=>{if(!H(u))throw new Error("Failed to parse response item.");return T(u)})}readEvents(e,r,n){let i=this.#e("/api/v1/read-events"),c=this.#t;return(async function*(){let d=new AbortController,u=n??d.signal,a=!n,o;if(n&&!n.aborted){let s=()=>d.abort();n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:e,options:r}),signal:u});if(!m(s)){let h=s.headers.get("Server");throw h?new Error(`Server must be EventSourcingDB, got Server header: '${h}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(s.status!==200)throw new Error(`Failed to read events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read events.");for await(let h of v(s.body,u)){if(b(h))throw new Error(`${h.payload.error}.`);if(C(h)){yield T(h.payload);continue}throw new Error("Failed to read events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{o&&o(),a&&d.abort()}})()}runEventQlQuery(e,r){let n=this.#e("/api/v1/run-eventql-query"),i=this.#t;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let o=()=>c.abort();r.addEventListener("abort",o,{once:!0}),a=()=>r.removeEventListener("abort",o)}try{let o=await fetch(n,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(o)){let s=o.headers.get("Server");throw s?new Error(`Server must be EventSourcingDB, got Server header: '${s}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(o.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${o.status}', expected '200'.`);if(!o.body)throw new Error("Failed to run EventQL query.");for await(let s of v(o.body,d))if(!A(s)){if(b(s))throw new Error(`${s.payload.error}.`);if(D(s)){yield s.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;throw o}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,n){let i=this.#e("/api/v1/observe-events"),c=this.#t;return(async function*(){let d=new AbortController,u=n??d.signal,a=!n,o;if(n&&!n.aborted){let s=()=>d.abort();n.addEventListener("abort",s,{once:!0}),o=()=>n.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:e,options:r}),signal:u});if(!m(s)){let h=s.headers.get("Server");throw h?new Error(`Server must be EventSourcingDB, got Server header: '${h}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(s.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to observe events.");for await(let h of v(s.body,u))if(!A(h)){if(b(h))throw new Error(`${h.payload.error}.`);if(C(h)){yield T(h.payload);continue}throw new Error("Failed to observe events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{o&&o(),a&&d.abort()}})()}async registerEventSchema(e,r){let n=this.#e("/api/v1/register-event-schema"),i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({eventType:e,schema:r})});if(!m(i))throw new Error("Server must be EventSourcingDB.");if(i.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${i.status}', expected '200'.`)}readSubjects(e,r){let n=this.#e("/api/v1/read-subjects"),i=this.#t;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let o=()=>c.abort();r.addEventListener("abort",o,{once:!0}),a=()=>r.removeEventListener("abort",o)}try{let o=await fetch(n,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(o)){let s=o.headers.get("Server");throw s?new Error(`Server must be EventSourcingDB, got Server header: '${s}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(o.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${o.status}', expected '200'.`);if(!o.body)throw new Error("Failed to read subjects.");for await(let s of v(o.body,d)){if(b(s))throw new Error(`${s.payload.error}.`);if(L(s)){yield s.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;throw o}finally{a&&a(),u&&c.abort()}})()}async readEventType(e){let r=this.#e("/api/v1/read-event-type"),n=await fetch(r,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"content-type":"application/json"},body:JSON.stringify({eventType:e})});if(!m(n))throw new Error("Server must be EventSourcingDB.");if(n.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${n.status}', expected '200'.`);let i=await n.json();if(!f(i,{eventType:p,isPhantom:k}))throw new Error("Failed to parse response.");return i}readEventTypes(e){let r=this.#e("/api/v1/read-event-types"),n=this.#t;return(async function*(){let i=new AbortController,c=e??i.signal,d=!e,u;if(e&&!e.aborted){let a=()=>i.abort();e.addEventListener("abort",a,{once:!0}),u=()=>e.removeEventListener("abort",a)}try{let a=await fetch(r,{method:"post",headers:{authorization:`Bearer ${n}`},signal:c});if(!m(a)){let o=a.headers.get("Server");throw o?new Error(`Server must be EventSourcingDB, got Server header: '${o}'.`):new Error("Server must be EventSourcingDB, but Server header is missing.")}if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let o of v(a.body,c))if(!A(o)){if(b(o))throw new Error(`${o.payload.error}.`);if(F(o)){yield o.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&i.abort()}})()}};var B=R(require("crypto")),x=require("testcontainers");var P=class{#n="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#o;#r;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#i=e,this}withSigningKey(){let{privateKey:e}=B.default.generateKeyPairSync("ed25519");return this.#o=e,this}withPort(e){return this.#e=e,this}async start(){let e=["run","--api-token",this.#i,"--data-directory-temporary","--http-enabled","--https-enabled=false"],r=[];this.#o!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#o.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new x.GenericContainer(`${this.#n}:${this.#t}`).withExposedPorts(this.#e).withCommand(e).withCopyContentToContainer(r).withWaitStrategy(x.Wait.forHttp("/api/v1/ping",this.#e).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#e)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let e=this.getHost(),r=this.getMappedPort();return new URL(`http://${e}:${r}`)}getApiToken(){return this.#i}getSigningKey(){if(this.#o===void 0)throw new Error("Signing key not set.");return this.#o}getVerificationKey(){if(this.#o===void 0)throw new Error("Signing key not set.");return B.default.createPublicKey(this.#o)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new w(this.getBaseUrl(),this.getApiToken())}};var K=t=>({type:"isEventQlQueryTrue",payload:{query:t}});var N=(t,e)=>({type:"isSubjectOnEventId",payload:{subject:t,eventId:e}});var U=t=>({type:"isSubjectPopulated",payload:{subject:t}});var G=t=>({type:"isSubjectPristine",payload:{subject:t}});0&&(module.exports={Client,Container,isEventQlQueryTrue,isSubjectOnEventId,isSubjectPopulated,isSubjectPristine});