eventsourcingdb 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/dist/index.d.mts +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -78,6 +78,20 @@ const writtenEvents = await client.writeEvents([
|
|
|
78
78
|
]);
|
|
79
79
|
```
|
|
80
80
|
|
|
81
|
+
#### Using the `isSubjectPopulated` precondition
|
|
82
|
+
|
|
83
|
+
If you only want to write events in case a subject (such as `/books/42`) already has at least one event, import the `isSubjectPopulated` function and pass it as an array of preconditions in the second argument:
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
import { isSubjectPopulated } from 'eventsourcingdb';
|
|
87
|
+
|
|
88
|
+
const writtenEvents = await client.writeEvents([
|
|
89
|
+
// events
|
|
90
|
+
], [
|
|
91
|
+
isSubjectPopulated('/books/42')
|
|
92
|
+
]);
|
|
93
|
+
```
|
|
94
|
+
|
|
81
95
|
#### Using the `isSubjectOnEventId` precondition
|
|
82
96
|
|
|
83
97
|
If you only want to write events in case the last event of a subject (such as `/books/42`) has a specific ID (e.g., `0`), import the `isSubjectOnEventId` function and pass it as an array of preconditions in the second argument:
|
|
@@ -430,7 +444,7 @@ eventType = await client.readEventType("io.eventsourcingdb.library.book-acquired
|
|
|
430
444
|
To verify the integrity of an event, call the `verifyHash` function on the event instance. This recomputes the event's hash locally and compares it to the hash stored in the event. If the hashes differ, the function returns an error:
|
|
431
445
|
|
|
432
446
|
```typescript
|
|
433
|
-
event.
|
|
447
|
+
event.verifyHash();
|
|
434
448
|
```
|
|
435
449
|
|
|
436
450
|
*Note that this only verifies the hash. If you also want to verify the signature, you can skip this step and call `verifySignature` directly, which performs a hash verification internally.*
|
package/dist/index.d.mts
CHANGED
|
@@ -71,6 +71,9 @@ interface ObserveEventsOptions {
|
|
|
71
71
|
interface IsSubjectPristinePrecondition {
|
|
72
72
|
subject: string;
|
|
73
73
|
}
|
|
74
|
+
interface IsSubjectPopulatedPrecondition {
|
|
75
|
+
subject: string;
|
|
76
|
+
}
|
|
74
77
|
interface IsSubjectOnEventIdPrecondition {
|
|
75
78
|
subject: string;
|
|
76
79
|
eventId: string;
|
|
@@ -84,6 +87,9 @@ type Precondition = {
|
|
|
84
87
|
} | {
|
|
85
88
|
type: 'isSubjectOnEventId';
|
|
86
89
|
payload: IsSubjectOnEventIdPrecondition;
|
|
90
|
+
} | {
|
|
91
|
+
type: 'isSubjectPopulated';
|
|
92
|
+
payload: IsSubjectPopulatedPrecondition;
|
|
87
93
|
} | {
|
|
88
94
|
type: 'isEventQlQueryTrue';
|
|
89
95
|
payload: IsEventQlQueryTruePrecondition;
|
|
@@ -141,6 +147,8 @@ declare const isEventQlQueryTrue: (query: string) => Precondition;
|
|
|
141
147
|
|
|
142
148
|
declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
|
|
143
149
|
|
|
150
|
+
declare const isSubjectPopulated: (subject: string) => Precondition;
|
|
151
|
+
|
|
144
152
|
declare const isSubjectPristine: (subject: string) => Precondition;
|
|
145
153
|
|
|
146
|
-
export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPristine };
|
|
154
|
+
export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
|
package/dist/index.d.ts
CHANGED
|
@@ -71,6 +71,9 @@ interface ObserveEventsOptions {
|
|
|
71
71
|
interface IsSubjectPristinePrecondition {
|
|
72
72
|
subject: string;
|
|
73
73
|
}
|
|
74
|
+
interface IsSubjectPopulatedPrecondition {
|
|
75
|
+
subject: string;
|
|
76
|
+
}
|
|
74
77
|
interface IsSubjectOnEventIdPrecondition {
|
|
75
78
|
subject: string;
|
|
76
79
|
eventId: string;
|
|
@@ -84,6 +87,9 @@ type Precondition = {
|
|
|
84
87
|
} | {
|
|
85
88
|
type: 'isSubjectOnEventId';
|
|
86
89
|
payload: IsSubjectOnEventIdPrecondition;
|
|
90
|
+
} | {
|
|
91
|
+
type: 'isSubjectPopulated';
|
|
92
|
+
payload: IsSubjectPopulatedPrecondition;
|
|
87
93
|
} | {
|
|
88
94
|
type: 'isEventQlQueryTrue';
|
|
89
95
|
payload: IsEventQlQueryTruePrecondition;
|
|
@@ -141,6 +147,8 @@ declare const isEventQlQueryTrue: (query: string) => Precondition;
|
|
|
141
147
|
|
|
142
148
|
declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
|
|
143
149
|
|
|
150
|
+
declare const isSubjectPopulated: (subject: string) => Precondition;
|
|
151
|
+
|
|
144
152
|
declare const isSubjectPristine: (subject: string) => Precondition;
|
|
145
153
|
|
|
146
|
-
export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPristine };
|
|
154
|
+
export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPopulated, isSubjectPristine };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),a!==-1;){let n=i.slice(0,a).trim();i=i.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:j}});var b=t=>f(t,{type:e=>e==="error",payload:{error:p}});var A=t=>typeof t=="boolean";var F=t=>f(t,{type:e=>e==="eventType",payload:{eventType:p,isPhantom:A}});var O=t=>f(t,{type:e=>e==="heartbeat"});var D=t=>f(t,{type:e=>e==="row",payload:y});var L=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var g=class{#o;#t;#e(e){return new URL(e,this.#o).toString()}constructor(e,r){this.#o=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"),i=await fetch(o,{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,o){let i=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 s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.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(P(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{n&&n(),a&&d.abort()}})()}runEventQlQuery(e,r){let o=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 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 ${i}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(n)){let s=n.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(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 s of v(n.body,d))if(!O(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(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,o){let i=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 s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.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(!O(h)){if(b(h))throw new Error(`${h.payload.error}.`);if(P(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{n&&n(),a&&d.abort()}})()}async registerEventSchema(e,r){let o=this.#e("/api/v1/register-event-schema"),i=await fetch(o,{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 o=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 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 ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(n)){let s=n.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(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 s of v(n.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(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 i=await o.json();if(!f(i,{eventType:p,isPhantom:A}))throw new Error("Failed to parse response.");return i}readEventTypes(e){let r=this.#e("/api/v1/read-event-types"),o=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 ${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(!O(n)){if(b(n))throw new Error(`${n.payload.error}.`);if(F(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&&i.abort()}})()}};var B=R(require("crypto")),x=require("testcontainers");var k=class{#o="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#n;#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.#n=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.#n!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new x.GenericContainer(`${this.#o}:${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.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return B.default.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new g(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:"isSubjectPristine",payload:{subject:t}});0&&(module.exports={Client,Container,isEventQlQueryTrue,isSubjectOnEventId,isSubjectPristine});
|
|
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,o)=>{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:!(o=z(e,i))||o.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:()=>g,Container:()=>x,isEventQlQueryTrue:()=>K,isSubjectOnEventId:()=>N,isSubjectPopulated:()=>U,isSubjectPristine:()=>G});module.exports=_(X);var w=R(require("crypto")),E=class{specversion;id;time;#o;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:r,time:o,timeFromServer:i,source:c,subject:d,type:u,datacontenttype:a,data:n,hash:s,predecessorhash:h,traceparent:k,tracestate:I,signature:J}){this.specversion=e,this.id=r,this.time=o,this.#o=i,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=n,this.hash=s,this.predecessorhash=h,this.traceparent=k,this.tracestate=I,this.signature=J}verifyHash(){let e=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#o}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=w.default.createHash("sha256").update(e).digest("hex"),o=w.default.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(w.default.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),i=Buffer.from(o,"hex"),c=Buffer.from(this.hash,"utf8");if(!w.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 o=e[r],i=t[r];if(typeof o=="function"){if(!o(i))return!1;continue}if(!y(i)||!f(i,o))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(),o=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+=o.decode(u,{stream:!0});let a;for(;a=i.indexOf(`
|
|
2
|
+
`),a!==-1;){let n=i.slice(0,a).trim();i=i.slice(a+1),n&&(yield JSON.parse(n))}}}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 A=t=>typeof t=="boolean";var F=t=>f(t,{type:e=>e==="eventType",payload:{eventType:p,isPhantom:A}});var P=t=>f(t,{type:e=>e==="heartbeat"});var D=t=>f(t,{type:e=>e==="row",payload:y});var L=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var g=class{#o;#t;#e(e){return new URL(e,this.#o).toString()}constructor(e,r){this.#o=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"),i=await fetch(o,{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,o){let i=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 s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.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{n&&n(),a&&d.abort()}})()}runEventQlQuery(e,r){let o=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 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 ${i}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(n)){let s=n.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(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 s of v(n.body,d))if(!P(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(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,o){let i=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 s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.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(!P(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{n&&n(),a&&d.abort()}})()}async registerEventSchema(e,r){let o=this.#e("/api/v1/register-event-schema"),i=await fetch(o,{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 o=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 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 ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(n)){let s=n.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(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 s of v(n.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(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 i=await o.json();if(!f(i,{eventType:p,isPhantom:A}))throw new Error("Failed to parse response.");return i}readEventTypes(e){let r=this.#e("/api/v1/read-event-types"),o=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 ${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(!P(n)){if(b(n))throw new Error(`${n.payload.error}.`);if(F(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&&i.abort()}})()}};var B=R(require("crypto")),O=require("testcontainers");var x=class{#o="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#n;#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.#n=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.#n!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new O.GenericContainer(`${this.#o}:${this.#t}`).withExposedPorts(this.#e).withCommand(e).withCopyContentToContainer(r).withWaitStrategy(O.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.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return B.default.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new g(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});
|
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import w from"crypto";var
|
|
2
|
-
`),a!==-1;){let o=s.slice(0,a).trim();s=s.slice(a+1),o&&(yield JSON.parse(o))}}}finally{e.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var k=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 P=t=>f(t,{type:e=>e==="eventType",payload:{eventType:p,isPhantom:j}});var A=t=>f(t,{type:e=>e==="heartbeat"});var B=t=>f(t,{type:e=>e==="row",payload:y});var $=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var g=class{#o;#t;#e(e){return new URL(e,this.#o).toString()}constructor(e,r){this.#o=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"),s=await fetch(n,{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(!C(u))throw new Error("Failed to parse response item.");return S(u)})}readEvents(e,r,n){let s=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 i=()=>d.abort();n.addEventListener("abort",i,{once:!0}),o=()=>n.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(k(h)){yield S(h.payload);continue}throw new Error("Failed to read events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{o&&o(),a&&d.abort()}})()}runEventQlQuery(e,r){let n=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 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 ${s}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(o)){let i=o.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(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 i of v(o.body,d))if(!A(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(o){if(o instanceof DOMException&&o.name==="AbortError")return;throw o}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,n){let s=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 i=()=>d.abort();n.addEventListener("abort",i,{once:!0}),o=()=>n.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(!A(h)){if(b(h))throw new Error(`${h.payload.error}.`);if(k(h)){yield S(h.payload);continue}throw new Error("Failed to observe events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{o&&o(),a&&d.abort()}})()}async registerEventSchema(e,r){let n=this.#e("/api/v1/register-event-schema"),s=await fetch(n,{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 n=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 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 ${s}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(o)){let i=o.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(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 i of v(o.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(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 s=await n.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"),n=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 ${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(P(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&&s.abort()}})()}};import R from"crypto";import{GenericContainer as D,Wait as L}from"testcontainers";var x=class{#o="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#n;#r;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#i=e,this}withSigningKey(){let{privateKey:e}=R.generateKeyPairSync("ed25519");return this.#n=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.#n!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new D(`${this.#o}:${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.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return R.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new g(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:"isSubjectPristine",payload:{subject:t}});export{g as Client,x as Container,K as isEventQlQueryTrue,N as isSubjectOnEventId,U as isSubjectPristine};
|
|
1
|
+
import w from"crypto";var S=class{specversion;id;time;#o;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:e,id:r,time:n,timeFromServer:s,source:c,subject:d,type:u,datacontenttype:a,data:o,hash:i,predecessorhash:h,traceparent:P,tracestate:H,signature:F}){this.specversion=e,this.id=r,this.time=n,this.#o=s,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=o,this.hash=i,this.predecessorhash=h,this.traceparent=P,this.tracestate=H,this.signature=F}verifyHash(){let e=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#o}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=w.createHash("sha256").update(e).digest("hex"),n=w.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(w.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),s=Buffer.from(n,"hex"),c=Buffer.from(this.hash,"utf8");if(!w.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 n=e[r],s=t[r];if(typeof n=="function"){if(!n(s))return!1;continue}if(!y(s)||!f(s,n))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 k=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(),n=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+=n.decode(u,{stream:!0});let a;for(;a=s.indexOf(`
|
|
2
|
+
`),a!==-1;){let o=s.slice(0,a).trim();s=s.slice(a+1),o&&(yield JSON.parse(o))}}}finally{e.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var x=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 A=t=>f(t,{type:e=>e==="heartbeat"});var B=t=>f(t,{type:e=>e==="row",payload:y});var $=t=>f(t,{type:e=>e==="subject",payload:{subject:p}});var g=class{#o;#t;#e(e){return new URL(e,this.#o).toString()}constructor(e,r){this.#o=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"),s=await fetch(n,{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(!k(u))throw new Error("Failed to parse response item.");return E(u)})}readEvents(e,r,n){let s=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 i=()=>d.abort();n.addEventListener("abort",i,{once:!0}),o=()=>n.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(x(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{o&&o(),a&&d.abort()}})()}runEventQlQuery(e,r){let n=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 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 ${s}`,"content-type":"application/json"},body:JSON.stringify({query:e}),signal:d});if(!m(o)){let i=o.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(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 i of v(o.body,d))if(!A(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(o){if(o instanceof DOMException&&o.name==="AbortError")return;throw o}finally{a&&a(),u&&c.abort()}})()}observeEvents(e,r,n){let s=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 i=()=>d.abort();n.addEventListener("abort",i,{once:!0}),o=()=>n.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(!A(h)){if(b(h))throw new Error(`${h.payload.error}.`);if(x(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{o&&o(),a&&d.abort()}})()}async registerEventSchema(e,r){let n=this.#e("/api/v1/register-event-schema"),s=await fetch(n,{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 n=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 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 ${s}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:e}),signal:d});if(!m(o)){let i=o.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(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 i of v(o.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(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 s=await n.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"),n=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 ${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(C(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&&s.abort()}})()}};import R from"crypto";import{GenericContainer as D,Wait as L}from"testcontainers";var O=class{#o="thenativeweb/eventsourcingdb";#t="latest";#e=3e3;#i="secret";#n;#r;withImageTag(e){return this.#t=e,this}withApiToken(e){return this.#i=e,this}withSigningKey(){let{privateKey:e}=R.generateKeyPairSync("ed25519");return this.#n=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.#n!==void 0&&(e.push("--signing-key-file"),e.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new D(`${this.#o}:${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.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return R.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new g(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{g as Client,O as Container,K as isEventQlQueryTrue,N as isSubjectOnEventId,U as isSubjectPopulated,G as isSubjectPristine};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eventsourcingdb",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "The official JavaScript client SDK for EventSourcingDB.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "the native web GmbH",
|
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
"testcontainers": "11.7.1"
|
|
18
18
|
},
|
|
19
19
|
"devDependencies": {
|
|
20
|
-
"@biomejs/biome": "2.2.
|
|
21
|
-
"@types/node": "24.
|
|
20
|
+
"@biomejs/biome": "2.2.6",
|
|
21
|
+
"@types/node": "24.8.1",
|
|
22
22
|
"get-port": "7.1.0",
|
|
23
23
|
"tsup": "8.5.0",
|
|
24
24
|
"tsx": "4.20.6",
|