eventsourcingdb 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +22 -0
- package/LICENSE.md +9 -0
- package/README.md +3 -0
- package/dist/index.d.mts +161 -0
- package/dist/index.d.ts +161 -0
- package/dist/index.js +2 -0
- package/dist/index.mjs +2 -0
- package/package.json +48 -0
package/.editorconfig
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# top-most EditorConfig file
|
|
2
|
+
root = true
|
|
3
|
+
|
|
4
|
+
[*]
|
|
5
|
+
charset = utf-8
|
|
6
|
+
end_of_line = lf
|
|
7
|
+
indent_size = 2
|
|
8
|
+
indent_style = tab
|
|
9
|
+
insert_final_newline = true
|
|
10
|
+
trim_trailing_whitespace = true
|
|
11
|
+
|
|
12
|
+
[*.json]
|
|
13
|
+
indent_size = 2
|
|
14
|
+
indent_style = space
|
|
15
|
+
|
|
16
|
+
[*.md]
|
|
17
|
+
indent_size = 2
|
|
18
|
+
indent_style = space
|
|
19
|
+
|
|
20
|
+
[*.yml]
|
|
21
|
+
indent_size = 2
|
|
22
|
+
indent_style = space
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 the native web GmbH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { ResponseType, AxiosResponse } from 'axios';
|
|
3
|
+
|
|
4
|
+
declare class CustomError extends Error {
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
declare class CancelationError extends CustomError {
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface ClientConfiguration {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
timeoutMilliseconds: number;
|
|
13
|
+
accessToken: string;
|
|
14
|
+
protocolVersion: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface ClientOptions {
|
|
18
|
+
timeoutMilliseconds?: number;
|
|
19
|
+
accessToken: string;
|
|
20
|
+
protocolVersion?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type UnknownObject = Partial<Record<string, unknown>>;
|
|
24
|
+
|
|
25
|
+
declare class EventCandidate {
|
|
26
|
+
readonly data: Record<string, unknown>;
|
|
27
|
+
readonly source: string;
|
|
28
|
+
readonly subject: string;
|
|
29
|
+
readonly type: string;
|
|
30
|
+
readonly traceParent?: string;
|
|
31
|
+
readonly traceState?: string;
|
|
32
|
+
constructor(source: string, subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string);
|
|
33
|
+
validate(): void;
|
|
34
|
+
toJSON(): Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
declare class EventContext {
|
|
38
|
+
readonly source: string;
|
|
39
|
+
readonly subject: string;
|
|
40
|
+
readonly type: string;
|
|
41
|
+
readonly specVersion: string;
|
|
42
|
+
readonly id: string;
|
|
43
|
+
readonly time: Date;
|
|
44
|
+
readonly dataContentType: string;
|
|
45
|
+
readonly predecessorHash: string;
|
|
46
|
+
readonly traceParent?: string;
|
|
47
|
+
readonly traceState?: string;
|
|
48
|
+
protected constructor(source: string, subject: string, type: string, specVersion: string, id: string, time: Date, dataContentType: string, predecessorHash: string, traceParent?: string, traceState?: string);
|
|
49
|
+
static parse(unknownObject: UnknownObject): EventContext;
|
|
50
|
+
toJSON(): Record<string, unknown>;
|
|
51
|
+
toString(): string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare class Event extends EventContext {
|
|
55
|
+
readonly data: Record<string, unknown>;
|
|
56
|
+
private constructor();
|
|
57
|
+
static parse(unknownObject: UnknownObject): Event;
|
|
58
|
+
toJSON(): Record<string, unknown>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface StoreItem {
|
|
62
|
+
event: Event;
|
|
63
|
+
hash: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface ObserveEventsOptions {
|
|
67
|
+
recursive: boolean;
|
|
68
|
+
lowerBoundId?: string;
|
|
69
|
+
fromLatestEvent?: ObserveFromLatestEvent;
|
|
70
|
+
}
|
|
71
|
+
interface ObserveFromLatestEvent {
|
|
72
|
+
subject: string;
|
|
73
|
+
type: string;
|
|
74
|
+
ifEventIsMissing: 'read-everything' | 'wait-for-event';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface EventType {
|
|
78
|
+
eventType: string;
|
|
79
|
+
isPhantom: boolean;
|
|
80
|
+
schema?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface ReadEventsOptions {
|
|
84
|
+
recursive: boolean;
|
|
85
|
+
order?: Order;
|
|
86
|
+
lowerBoundId?: string;
|
|
87
|
+
upperBoundId?: string;
|
|
88
|
+
fromLatestEvent?: ReadFromLatestEvent;
|
|
89
|
+
}
|
|
90
|
+
type Order = 'chronological' | 'antichronological';
|
|
91
|
+
interface ReadFromLatestEvent {
|
|
92
|
+
subject: string;
|
|
93
|
+
type: string;
|
|
94
|
+
ifEventIsMissing: 'read-nothing' | 'read-everything';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface ReadSubjectsOptions {
|
|
98
|
+
baseSubject: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
type Precondition = {
|
|
102
|
+
type: 'isSubjectPristine';
|
|
103
|
+
payload: IsSubjectPristinePrecondition;
|
|
104
|
+
} | {
|
|
105
|
+
type: 'isSubjectOnEventId';
|
|
106
|
+
payload: IsSubjectOnEventIdPrecondition;
|
|
107
|
+
};
|
|
108
|
+
interface IsSubjectPristinePrecondition {
|
|
109
|
+
subject: string;
|
|
110
|
+
}
|
|
111
|
+
interface IsSubjectOnEventIdPrecondition {
|
|
112
|
+
subject: string;
|
|
113
|
+
eventId: string;
|
|
114
|
+
}
|
|
115
|
+
declare const isSubjectPristine: (payload: IsSubjectPristinePrecondition) => Precondition;
|
|
116
|
+
declare const isSubjectOnEventId: (payload: IsSubjectOnEventIdPrecondition) => Precondition;
|
|
117
|
+
|
|
118
|
+
type ResponseDataType<TResponseType extends ResponseType> = TResponseType extends 'arraybuffer' ? ArrayBuffer : TResponseType extends 'blob' ? Blob : TResponseType extends 'document' ? unknown : TResponseType extends 'json' ? unknown : TResponseType extends 'text' ? string : TResponseType extends 'stream' ? Readable : never;
|
|
119
|
+
type Response<TResponseType extends ResponseType> = AxiosResponse<ResponseDataType<TResponseType>, unknown>;
|
|
120
|
+
declare class HttpClient {
|
|
121
|
+
private readonly databaseClient;
|
|
122
|
+
constructor(dbClient: Client);
|
|
123
|
+
private getDefaultRequestConfig;
|
|
124
|
+
private static setContentType;
|
|
125
|
+
private static setAuthorization;
|
|
126
|
+
private static setResponseType;
|
|
127
|
+
validateProtocolVersion(httpStatusCode: number, headers: Record<string, unknown>): void;
|
|
128
|
+
post<TResponseType extends ResponseType>(options: {
|
|
129
|
+
path: string;
|
|
130
|
+
responseType: TResponseType;
|
|
131
|
+
requestBody: string;
|
|
132
|
+
abortController?: AbortController;
|
|
133
|
+
}): Promise<Response<TResponseType>>;
|
|
134
|
+
get<TResponseType extends ResponseType>(options: {
|
|
135
|
+
path: string;
|
|
136
|
+
responseType: TResponseType;
|
|
137
|
+
abortController?: AbortController;
|
|
138
|
+
withAuthorization?: boolean;
|
|
139
|
+
}): Promise<Response<TResponseType>>;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
declare class Client {
|
|
143
|
+
readonly configuration: ClientConfiguration;
|
|
144
|
+
readonly httpClient: HttpClient;
|
|
145
|
+
constructor(baseUrl: string, options: ClientOptions);
|
|
146
|
+
observeEvents(abortController: AbortController, subject: string, options: ObserveEventsOptions): AsyncGenerator<StoreItem, void, void>;
|
|
147
|
+
ping(): Promise<void>;
|
|
148
|
+
readEvents(abortController: AbortController, subject: string, options: ReadEventsOptions): AsyncGenerator<StoreItem, void, void>;
|
|
149
|
+
readEventTypes(abortController: AbortController): AsyncGenerator<EventType, void, void>;
|
|
150
|
+
readSubjects(abortController: AbortController, options: ReadSubjectsOptions): AsyncGenerator<string, void, void>;
|
|
151
|
+
registerEventSchema(eventType: string, schema: string | object): Promise<void>;
|
|
152
|
+
writeEvents(eventCandidates: EventCandidate[], preconditions?: Precondition[]): Promise<EventContext[]>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
declare class Source {
|
|
156
|
+
readonly source: string;
|
|
157
|
+
constructor(source: string);
|
|
158
|
+
newEvent(subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string): EventCandidate;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { CancelationError, Client, type ClientConfiguration, Event, EventCandidate, type ObserveEventsOptions, type ObserveFromLatestEvent, type Precondition, type ReadEventsOptions, type ReadFromLatestEvent, type ReadSubjectsOptions, Source, type StoreItem, isSubjectOnEventId, isSubjectPristine };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { ResponseType, AxiosResponse } from 'axios';
|
|
3
|
+
|
|
4
|
+
declare class CustomError extends Error {
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
declare class CancelationError extends CustomError {
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface ClientConfiguration {
|
|
11
|
+
baseUrl: string;
|
|
12
|
+
timeoutMilliseconds: number;
|
|
13
|
+
accessToken: string;
|
|
14
|
+
protocolVersion: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface ClientOptions {
|
|
18
|
+
timeoutMilliseconds?: number;
|
|
19
|
+
accessToken: string;
|
|
20
|
+
protocolVersion?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type UnknownObject = Partial<Record<string, unknown>>;
|
|
24
|
+
|
|
25
|
+
declare class EventCandidate {
|
|
26
|
+
readonly data: Record<string, unknown>;
|
|
27
|
+
readonly source: string;
|
|
28
|
+
readonly subject: string;
|
|
29
|
+
readonly type: string;
|
|
30
|
+
readonly traceParent?: string;
|
|
31
|
+
readonly traceState?: string;
|
|
32
|
+
constructor(source: string, subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string);
|
|
33
|
+
validate(): void;
|
|
34
|
+
toJSON(): Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
declare class EventContext {
|
|
38
|
+
readonly source: string;
|
|
39
|
+
readonly subject: string;
|
|
40
|
+
readonly type: string;
|
|
41
|
+
readonly specVersion: string;
|
|
42
|
+
readonly id: string;
|
|
43
|
+
readonly time: Date;
|
|
44
|
+
readonly dataContentType: string;
|
|
45
|
+
readonly predecessorHash: string;
|
|
46
|
+
readonly traceParent?: string;
|
|
47
|
+
readonly traceState?: string;
|
|
48
|
+
protected constructor(source: string, subject: string, type: string, specVersion: string, id: string, time: Date, dataContentType: string, predecessorHash: string, traceParent?: string, traceState?: string);
|
|
49
|
+
static parse(unknownObject: UnknownObject): EventContext;
|
|
50
|
+
toJSON(): Record<string, unknown>;
|
|
51
|
+
toString(): string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare class Event extends EventContext {
|
|
55
|
+
readonly data: Record<string, unknown>;
|
|
56
|
+
private constructor();
|
|
57
|
+
static parse(unknownObject: UnknownObject): Event;
|
|
58
|
+
toJSON(): Record<string, unknown>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface StoreItem {
|
|
62
|
+
event: Event;
|
|
63
|
+
hash: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface ObserveEventsOptions {
|
|
67
|
+
recursive: boolean;
|
|
68
|
+
lowerBoundId?: string;
|
|
69
|
+
fromLatestEvent?: ObserveFromLatestEvent;
|
|
70
|
+
}
|
|
71
|
+
interface ObserveFromLatestEvent {
|
|
72
|
+
subject: string;
|
|
73
|
+
type: string;
|
|
74
|
+
ifEventIsMissing: 'read-everything' | 'wait-for-event';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface EventType {
|
|
78
|
+
eventType: string;
|
|
79
|
+
isPhantom: boolean;
|
|
80
|
+
schema?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface ReadEventsOptions {
|
|
84
|
+
recursive: boolean;
|
|
85
|
+
order?: Order;
|
|
86
|
+
lowerBoundId?: string;
|
|
87
|
+
upperBoundId?: string;
|
|
88
|
+
fromLatestEvent?: ReadFromLatestEvent;
|
|
89
|
+
}
|
|
90
|
+
type Order = 'chronological' | 'antichronological';
|
|
91
|
+
interface ReadFromLatestEvent {
|
|
92
|
+
subject: string;
|
|
93
|
+
type: string;
|
|
94
|
+
ifEventIsMissing: 'read-nothing' | 'read-everything';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface ReadSubjectsOptions {
|
|
98
|
+
baseSubject: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
type Precondition = {
|
|
102
|
+
type: 'isSubjectPristine';
|
|
103
|
+
payload: IsSubjectPristinePrecondition;
|
|
104
|
+
} | {
|
|
105
|
+
type: 'isSubjectOnEventId';
|
|
106
|
+
payload: IsSubjectOnEventIdPrecondition;
|
|
107
|
+
};
|
|
108
|
+
interface IsSubjectPristinePrecondition {
|
|
109
|
+
subject: string;
|
|
110
|
+
}
|
|
111
|
+
interface IsSubjectOnEventIdPrecondition {
|
|
112
|
+
subject: string;
|
|
113
|
+
eventId: string;
|
|
114
|
+
}
|
|
115
|
+
declare const isSubjectPristine: (payload: IsSubjectPristinePrecondition) => Precondition;
|
|
116
|
+
declare const isSubjectOnEventId: (payload: IsSubjectOnEventIdPrecondition) => Precondition;
|
|
117
|
+
|
|
118
|
+
type ResponseDataType<TResponseType extends ResponseType> = TResponseType extends 'arraybuffer' ? ArrayBuffer : TResponseType extends 'blob' ? Blob : TResponseType extends 'document' ? unknown : TResponseType extends 'json' ? unknown : TResponseType extends 'text' ? string : TResponseType extends 'stream' ? Readable : never;
|
|
119
|
+
type Response<TResponseType extends ResponseType> = AxiosResponse<ResponseDataType<TResponseType>, unknown>;
|
|
120
|
+
declare class HttpClient {
|
|
121
|
+
private readonly databaseClient;
|
|
122
|
+
constructor(dbClient: Client);
|
|
123
|
+
private getDefaultRequestConfig;
|
|
124
|
+
private static setContentType;
|
|
125
|
+
private static setAuthorization;
|
|
126
|
+
private static setResponseType;
|
|
127
|
+
validateProtocolVersion(httpStatusCode: number, headers: Record<string, unknown>): void;
|
|
128
|
+
post<TResponseType extends ResponseType>(options: {
|
|
129
|
+
path: string;
|
|
130
|
+
responseType: TResponseType;
|
|
131
|
+
requestBody: string;
|
|
132
|
+
abortController?: AbortController;
|
|
133
|
+
}): Promise<Response<TResponseType>>;
|
|
134
|
+
get<TResponseType extends ResponseType>(options: {
|
|
135
|
+
path: string;
|
|
136
|
+
responseType: TResponseType;
|
|
137
|
+
abortController?: AbortController;
|
|
138
|
+
withAuthorization?: boolean;
|
|
139
|
+
}): Promise<Response<TResponseType>>;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
declare class Client {
|
|
143
|
+
readonly configuration: ClientConfiguration;
|
|
144
|
+
readonly httpClient: HttpClient;
|
|
145
|
+
constructor(baseUrl: string, options: ClientOptions);
|
|
146
|
+
observeEvents(abortController: AbortController, subject: string, options: ObserveEventsOptions): AsyncGenerator<StoreItem, void, void>;
|
|
147
|
+
ping(): Promise<void>;
|
|
148
|
+
readEvents(abortController: AbortController, subject: string, options: ReadEventsOptions): AsyncGenerator<StoreItem, void, void>;
|
|
149
|
+
readEventTypes(abortController: AbortController): AsyncGenerator<EventType, void, void>;
|
|
150
|
+
readSubjects(abortController: AbortController, options: ReadSubjectsOptions): AsyncGenerator<string, void, void>;
|
|
151
|
+
registerEventSchema(eventType: string, schema: string | object): Promise<void>;
|
|
152
|
+
writeEvents(eventCandidates: EventCandidate[], preconditions?: Precondition[]): Promise<EventContext[]>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
declare class Source {
|
|
156
|
+
readonly source: string;
|
|
157
|
+
constructor(source: string);
|
|
158
|
+
newEvent(subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string): EventCandidate;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { CancelationError, Client, type ClientConfiguration, Event, EventCandidate, type ObserveEventsOptions, type ObserveFromLatestEvent, type Precondition, type ReadEventsOptions, type ReadFromLatestEvent, type ReadSubjectsOptions, Source, type StoreItem, isSubjectOnEventId, isSubjectPristine };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var ut=Object.create;var O=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var wt=(r,t)=>{for(var e in t)O(r,e,{get:t[e],enumerable:!0})},L=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!ht.call(r,n)&&n!==e&&O(r,n,{get:()=>t[n],enumerable:!(s=lt(t,n))||s.enumerable});return r};var J=(r,t,e)=>(e=r!=null?ut(yt(r)):{},L(t||!r||!r.__esModule?O(e,"default",{value:r,enumerable:!0}):e,r)),gt=r=>L(O({},"__esModule",{value:!0}),r);var St={};wt(St,{CancelationError:()=>h,Client:()=>F,Event:()=>w,EventCandidate:()=>j,Source:()=>N,isSubjectOnEventId:()=>mt,isSubjectPristine:()=>dt});module.exports=gt(St);var d=class extends Error{};var h=class extends d{};var q=r=>({baseUrl:r,timeoutMilliseconds:1e4,accessToken:"",protocolVersion:"1.0.0"});var $=require("http-status-codes");var l=r=>typeof r=="object"&&!Array.isArray(r)&&r!==null;var a=class extends d{};var k="[0-9A-Za-z_-]+",bt=new RegExp(`^/(${k}/)*(${k}/?)?$`,"u"),v=r=>{if(!bt.test(r))throw new a(`Failed to validate subject: '${r}' must be an absolute, slash-separated path.`)};var Et=/^[0-9A-Za-z_-]{2,}\.(?:[0-9A-Za-z_-]+\.)+[0-9A-Za-z_-]+$/u,y=r=>{if(!Et.test(r))throw new a(`Failed to validate type: '${r}' must be a reverse domain name.`)};var E=class r{source;subject;type;specVersion;id;time;dataContentType;predecessorHash;traceParent;traceState;constructor(t,e,s,n,p,o,i,R,D,U){this.source=t,this.subject=e,this.type=s,this.specVersion=n,this.id=p,this.time=o,this.dataContentType=i,this.predecessorHash=R,this.traceParent=D,this.traceState=U}static parse(t){if(typeof t.source!="string")throw new a(`Failed to parse source '${t.source}' to string.`);if(typeof t.subject!="string")throw new a(`Failed to parse subject '${t.subject}' to string.`);if(v(t.subject),typeof t.type!="string")throw new a(`Failed to parse type '${t.type}' to string.`);if(y(t.type),typeof t.specversion!="string")throw new a(`Failed to parse specVersion '${t.specversion}' to string.`);if(typeof t.id!="string")throw new a(`Failed to parse id '${t.id}' to string.`);if(typeof t.time!="string")throw new a(`Failed to parse time '${t.time}' to Date.`);let e=new Date(t.time);if(e.toString()==="Invalid Date")throw new a(`Failed to parse time '${t.time}' to Date.`);if(typeof t.datacontenttype!="string")throw new a(`Failed to parse dataContentType '${t.datacontenttype}' to string.`);if(typeof t.predecessorhash!="string")throw new a(`Failed to parse predecessorHash '${t.predecessorhash}' to string.`);if(t.traceparent!==void 0&&typeof t.traceparent!="string")throw new a(`Failed to parse traceparent '${t.traceparent}' to string.`);if(t.tracestate!==void 0&&typeof t.tracestate!="string")throw new a(`Failed to parse tracestate '${t.tracestate}' to string.`);return new r(t.source,t.subject,t.type,t.specversion,t.id,e,t.datacontenttype,t.predecessorhash,t.traceparent,t.tracestate)}toJSON(){return{specversion:this.specVersion,id:this.id,time:this.time.toISOString(),source:this.source,subject:this.subject,type:this.type,datacontenttype:this.dataContentType,predecessorhash:this.predecessorHash,traceparent:this.traceParent,tracestate:this.traceState}}toString(){return JSON.stringify(this)}};var w=class r extends E{data;constructor(t,e,s,n,p,o,i,R,D,U,ft){super(e,s,n,p,o,i,R,D,U,ft),this.data=t}static parse(t){let e=E.parse(t);if(!l(t.data))throw new Error(`Failed to parse data '${t.data}' to object.`);return new r(t.data,e.source,e.subject,e.type,e.specVersion,e.id,e.time,e.dataContentType,e.predecessorHash,e.traceParent,e.traceState)}toJSON(){return{...super.toJSON(),data:this.data}}};var f=class extends d{constructor(t){super(`Internal error occurred: ${t}`)}};var u=class extends d{constructor(t,e){super(`Parameter '${t}' is invalid: ${e}`)}};var c=class extends d{constructor(t){super(`Server error occurred: ${t}`)}};var H=r=>typeof r=="object"&&typeof r.then=="function";function m(r,t){try{let e=r();return H(e)?e.catch(s=>{let n;s instanceof Error?n=s:n=new f(s);try{let p=t(n);return H(p)?p.then(()=>Promise.reject(new f("onError did not throw."))).catch(o=>{let i;return o instanceof Error?i=o:i=new f(o),Promise.reject(i)}):Promise.reject(n)}catch(p){let o;return p instanceof Error?o=p:o=new f(p),Promise.reject(o)}}):e}catch(e){throw e instanceof Error&&t(e),new f(e)}}var G=require("axios"),M=J(require("stream-to-async-iterator"));var z=require("string_decoder"),I=class{textBuffer;decoder;constructor(t){this.textBuffer="",this.decoder=new z.StringDecoder(t)}write(t){this.textBuffer+=this.decoder.write(t);let e=[],s=0;for(let n=0;n<this.textBuffer.length;n++){if(this.textBuffer[n]!==`
|
|
2
|
+
`)continue;let o=this.textBuffer.slice(s,n);s=n+1,e.push(o)}return this.textBuffer=this.textBuffer.slice(s),e}};var g=async function*(r){let t=new I("utf-8");try{for await(let e of new M.default(r)){let s=t.write(e);for(let n of s)yield JSON.parse(n)}}catch(e){throw e instanceof G.CanceledError?new h:new c("Failed to read response.")}};var C=r=>l(r)&&r.type==="heartbeat";var P=r=>{if(!l(r)||r.type!=="item")return!1;let{payload:t}=r;return l(t)&&l(t.event)&&typeof t.hash=="string"};var b=r=>{if(!l(r)||r.type!=="error")return!1;let{payload:t}=r;return l(t)&&typeof t.error=="string"};var Ct=/^\d+$/u,T=r=>Ct.test(r);var K=r=>{if(r.lowerBoundId!==void 0&&!T(r.lowerBoundId))throw new a("ObserveEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.lowerBoundId!==void 0&&r.fromLatestEvent!==void 0)throw new a("ObserveEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;t!==void 0&&m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ObserveEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})};var Z=async function*(r,t,e,s){await m(()=>v(e),i=>{if(i instanceof a)throw new u("subject",i.message)}),await m(()=>{K(s)},i=>{if(i instanceof a)throw new u("options",i.message)});let n=m(()=>JSON.stringify({subject:e,options:s}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/observe-events",requestBody:n,responseType:"stream",abortController:t}),i=>{throw i instanceof d?i:new f(i)});if(p.status!==$.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${(0,$.getReasonPhrase)(p.status)}.`);let o=p.data;for await(let i of g(o))if(!C(i)){if(b(i))throw new c(`${i.payload.error}.`);if(P(i)){yield{event:w.parse(i.payload.event),hash:i.payload.hash};continue}throw new c(`Failed to observe events, an unexpected stream item was received: '${JSON.stringify(i)}'.`)}};var X=async r=>{if((await m(async()=>r.httpClient.get({path:"/api/ping",responseType:"text",withAuthorization:!1}),e=>{if(e instanceof d)throw e;new f(e)})).data!=="OK")throw new c("Received unexpected response.")};var _=require("http-status-codes");var Y=r=>!(!l(r)||r.type!=="eventType");var Q=async function*(r,t){let e=await m(async()=>r.httpClient.post({path:"/api/read-event-types",requestBody:"",responseType:"stream",abortController:t}),n=>{throw n instanceof d?n:new f(n)});if(e.status!==_.StatusCodes.OK)throw new c(`Unexpected response status: ${e.status} ${e.statusText}.`);let s=e.data;for await(let n of g(s))if(!C(n)){if(b(n))throw new c(`${n.payload.error}.`);if(Y(n)){yield n.payload;continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(n)}'.`)}};var tt=require("http-status-codes");var W=r=>{if(r.lowerBoundId!==void 0&&!T(r.lowerBoundId))throw new a("ReadEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.upperBoundId!==void 0&&!T(r.upperBoundId))throw new a("ReadEventsOptions are invalid: upperBoundId must be 0 or greater.");if(r.fromLatestEvent!==void 0){if(r.lowerBoundId!==void 0)throw new a("ReadEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ReadEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})}};var et=async function*(r,t,e,s){m(()=>v(e),i=>{if(i instanceof a)throw new u("subject",i.message)}),m(()=>{W(s)},i=>{if(i instanceof a)throw new u("options",i.message)});let n=m(()=>JSON.stringify({subject:e,options:s}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/read-events",requestBody:n,responseType:"stream",abortController:t}),i=>{throw i instanceof d?i:new f(i)});if(p.status!==tt.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}.`);let o=p.data;for await(let i of g(o))if(!C(i)){if(b(i))throw new c(`${i.payload.error}.`);if(P(i)){yield{event:w.parse(i.payload.event),hash:i.payload.hash};continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(i)}'.`)}};var A=require("http-status-codes");var rt=r=>{v(r.baseSubject)};var ot=r=>{if(!l(r)||r.type!=="subject")return!1;let{payload:t}=r;return l(t)&&typeof t.subject=="string"};var nt=async function*(r,t,e){await m(()=>{rt(e)},o=>{if(o instanceof a)throw new u("options",o.message)});let s=m(()=>JSON.stringify(e),o=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),n=await m(async()=>r.httpClient.post({path:"/api/read-subjects",requestBody:s,responseType:"stream",abortController:t}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==A.StatusCodes.OK)throw new c(`Unexpected response status: ${n.status} ${(0,A.getReasonPhrase)(n.status)}.`);let p=n.data;for await(let o of g(p)){if(b(o))throw new c(o.payload.error);if(ot(o)){yield o.payload.subject;continue}throw new c(`Failed to read subjects, an unexpected stream item was received: '${JSON.stringify(o)}'.`)}};var st=require("http-status-codes");var it=async(r,t,e)=>{m(()=>y(t),o=>{if(o instanceof a)throw new u("eventType",o.message)});let s=e;typeof e=="object"&&(s=JSON.stringify(e));let n=JSON.stringify({eventType:t,schema:s}),p=await m(async()=>r.httpClient.post({path:"/api/register-event-schema",requestBody:n,responseType:"text"}),o=>{throw o instanceof d?o:new f(o)});if(p.status!==st.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}: ${p.data}.`)};var at=require("http-status-codes");var pt=async(r,t,e)=>{if(t.length===0)throw new u("eventCandidates","eventCandidates must contain at least one EventCandidate.");for(let o of t)m(()=>{o.validate()},i=>{if(i instanceof a)throw new u("eventCandidates",i.message)});let s=JSON.stringify({events:t,preconditions:e}),n=await m(async()=>r.httpClient.post({path:"/api/write-events",requestBody:s,responseType:"json"}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==at.StatusCodes.OK)throw new c(`Unexpected response status: ${n.status} ${n.statusText}.`);if(!Array.isArray(n.data))throw new c(`Failed to parse response '${n.data}' to array.`);let p=n.data;return m(()=>p.map(o=>E.parse(o)),o=>{throw o instanceof a?new c(o.message):new f(o)})};var x=require("axios"),V=J(require("axios")),ct=require("http-status-codes");var S=class extends d{constructor(t){super(`Client error occurred: ${t}`)}};var B=class r{databaseClient;constructor(t){this.databaseClient=t}getDefaultRequestConfig(t=!0){let e={baseURL:this.databaseClient.configuration.baseUrl,timeout:this.databaseClient.configuration.timeoutMilliseconds,headers:{"X-EventSourcingDB-Protocol-Version":this.databaseClient.configuration.protocolVersion},validateStatus:()=>!0};return t&&this.databaseClient.configuration.accessToken!==void 0&&(e=r.setAuthorization(e,this.databaseClient.configuration.accessToken)),e}static setContentType(t,e){return{...t,headers:{...t.headers,"Content-Type":e}}}static setAuthorization(t,e){return{...t,headers:{...t.headers,authorization:`Bearer ${e}`}}}static setResponseType(t,e){return{...t,responseType:e}}validateProtocolVersion(t,e){if(t!==ct.StatusCodes.UNPROCESSABLE_ENTITY)return;let s=e["x-eventsourcingdb-protocol-version"];throw s===void 0&&(s="unknown version"),new S(`Protocol version mismatch, server '${s}', client '${this.databaseClient.configuration.protocolVersion}.'`)}async post(t){let e=this.getDefaultRequestConfig();e=r.setContentType(e,"application/json"),e=r.setResponseType(e,t.responseType);let s=V.default.create(e),p=(t.abortController??new AbortController).signal;try{let o=await s.post(t.path,t.requestBody,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return o}catch(o){throw o instanceof d?o:o instanceof x.CanceledError?new h:o instanceof x.AxiosError?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}async get(t){let e=this.getDefaultRequestConfig(t.withAuthorization);e=r.setResponseType(e,t.responseType);let s=V.default.create(e),p=(t.abortController??new AbortController).signal;try{let o=await s.get(t.path,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return this.validateProtocolVersion(o.status,o.headers),o}catch(o){throw o instanceof d?o:o instanceof x.CanceledError?new h:o instanceof x.AxiosError?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}};var F=class{configuration;httpClient;constructor(t,e){this.configuration={...q(t),...e},this.httpClient=new B(this)}observeEvents(t,e,s){return Z(this,t,e,s)}async ping(){await X(this)}readEvents(t,e,s){return et(this,t,e,s)}readEventTypes(t){return Q(this,t)}readSubjects(t,e){return nt(this,t,e)}async registerEventSchema(t,e){return await it(this,t,e)}async writeEvents(t,e=[]){return await pt(this,t,e)}};var j=class{data;source;subject;type;traceParent;traceState;constructor(t,e,s,n,p,o){this.data=n,this.source=t,this.subject=e,this.type=s,this.traceParent=p,this.traceState=o}validate(){if(v(this.subject),y(this.type),this.traceState!==void 0&&this.traceParent===void 0)throw new a("Failed to validate trace state: trace parent must be set if trace state is set.")}toJSON(){return{data:this.data,source:this.source,subject:this.subject,type:this.type,traceparent:this.traceParent,tracestate:this.traceState}}};var N=class{source;constructor(t){this.source=t}newEvent(t,e,s,n,p){return new j(this.source,t,e,s,n,p)}};var dt=r=>({type:"isSubjectPristine",payload:r}),mt=r=>({type:"isSubjectOnEventId",payload:r});0&&(module.exports={CancelationError,Client,Event,EventCandidate,Source,isSubjectOnEventId,isSubjectPristine});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var d=class extends Error{};var h=class extends d{};var F=r=>({baseUrl:r,timeoutMilliseconds:1e4,accessToken:"",protocolVersion:"1.0.0"});import{StatusCodes as st,getReasonPhrase as it}from"http-status-codes";var l=r=>typeof r=="object"&&!Array.isArray(r)&&r!==null;var a=class extends d{};var N="[0-9A-Za-z_-]+",W=new RegExp(`^/(${N}/)*(${N}/?)?$`,"u"),v=r=>{if(!W.test(r))throw new a(`Failed to validate subject: '${r}' must be an absolute, slash-separated path.`)};var tt=/^[0-9A-Za-z_-]{2,}\.(?:[0-9A-Za-z_-]+\.)+[0-9A-Za-z_-]+$/u,y=r=>{if(!tt.test(r))throw new a(`Failed to validate type: '${r}' must be a reverse domain name.`)};var b=class r{source;subject;type;specVersion;id;time;dataContentType;predecessorHash;traceParent;traceState;constructor(t,e,i,n,p,o,s,x,P,$){this.source=t,this.subject=e,this.type=i,this.specVersion=n,this.id=p,this.time=o,this.dataContentType=s,this.predecessorHash=x,this.traceParent=P,this.traceState=$}static parse(t){if(typeof t.source!="string")throw new a(`Failed to parse source '${t.source}' to string.`);if(typeof t.subject!="string")throw new a(`Failed to parse subject '${t.subject}' to string.`);if(v(t.subject),typeof t.type!="string")throw new a(`Failed to parse type '${t.type}' to string.`);if(y(t.type),typeof t.specversion!="string")throw new a(`Failed to parse specVersion '${t.specversion}' to string.`);if(typeof t.id!="string")throw new a(`Failed to parse id '${t.id}' to string.`);if(typeof t.time!="string")throw new a(`Failed to parse time '${t.time}' to Date.`);let e=new Date(t.time);if(e.toString()==="Invalid Date")throw new a(`Failed to parse time '${t.time}' to Date.`);if(typeof t.datacontenttype!="string")throw new a(`Failed to parse dataContentType '${t.datacontenttype}' to string.`);if(typeof t.predecessorhash!="string")throw new a(`Failed to parse predecessorHash '${t.predecessorhash}' to string.`);if(t.traceparent!==void 0&&typeof t.traceparent!="string")throw new a(`Failed to parse traceparent '${t.traceparent}' to string.`);if(t.tracestate!==void 0&&typeof t.tracestate!="string")throw new a(`Failed to parse tracestate '${t.tracestate}' to string.`);return new r(t.source,t.subject,t.type,t.specversion,t.id,e,t.datacontenttype,t.predecessorhash,t.traceparent,t.tracestate)}toJSON(){return{specversion:this.specVersion,id:this.id,time:this.time.toISOString(),source:this.source,subject:this.subject,type:this.type,datacontenttype:this.dataContentType,predecessorhash:this.predecessorHash,traceparent:this.traceParent,tracestate:this.traceState}}toString(){return JSON.stringify(this)}};var E=class r extends b{data;constructor(t,e,i,n,p,o,s,x,P,$,Q){super(e,i,n,p,o,s,x,P,$,Q),this.data=t}static parse(t){let e=b.parse(t);if(!l(t.data))throw new Error(`Failed to parse data '${t.data}' to object.`);return new r(t.data,e.source,e.subject,e.type,e.specVersion,e.id,e.time,e.dataContentType,e.predecessorHash,e.traceParent,e.traceState)}toJSON(){return{...super.toJSON(),data:this.data}}};var f=class extends d{constructor(t){super(`Internal error occurred: ${t}`)}};var u=class extends d{constructor(t,e){super(`Parameter '${t}' is invalid: ${e}`)}};var c=class extends d{constructor(t){super(`Server error occurred: ${t}`)}};var D=r=>typeof r=="object"&&typeof r.then=="function";function m(r,t){try{let e=r();return D(e)?e.catch(i=>{let n;i instanceof Error?n=i:n=new f(i);try{let p=t(n);return D(p)?p.then(()=>Promise.reject(new f("onError did not throw."))).catch(o=>{let s;return o instanceof Error?s=o:s=new f(o),Promise.reject(s)}):Promise.reject(n)}catch(p){let o;return p instanceof Error?o=p:o=new f(p),Promise.reject(o)}}):e}catch(e){throw e instanceof Error&&t(e),new f(e)}}import{CanceledError as rt}from"axios";import ot from"stream-to-async-iterator";import{StringDecoder as et}from"node:string_decoder";var T=class{textBuffer;decoder;constructor(t){this.textBuffer="",this.decoder=new et(t)}write(t){this.textBuffer+=this.decoder.write(t);let e=[],i=0;for(let n=0;n<this.textBuffer.length;n++){if(this.textBuffer[n]!==`
|
|
2
|
+
`)continue;let o=this.textBuffer.slice(i,n);i=n+1,e.push(o)}return this.textBuffer=this.textBuffer.slice(i),e}};var w=async function*(r){let t=new T("utf-8");try{for await(let e of new ot(r)){let i=t.write(e);for(let n of i)yield JSON.parse(n)}}catch(e){throw e instanceof rt?new h:new c("Failed to read response.")}};var C=r=>l(r)&&r.type==="heartbeat";var O=r=>{if(!l(r)||r.type!=="item")return!1;let{payload:t}=r;return l(t)&&l(t.event)&&typeof t.hash=="string"};var g=r=>{if(!l(r)||r.type!=="error")return!1;let{payload:t}=r;return l(t)&&typeof t.error=="string"};var nt=/^\d+$/u,j=r=>nt.test(r);var U=r=>{if(r.lowerBoundId!==void 0&&!j(r.lowerBoundId))throw new a("ObserveEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.lowerBoundId!==void 0&&r.fromLatestEvent!==void 0)throw new a("ObserveEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;t!==void 0&&m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ObserveEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})};var V=async function*(r,t,e,i){await m(()=>v(e),s=>{if(s instanceof a)throw new u("subject",s.message)}),await m(()=>{U(i)},s=>{if(s instanceof a)throw new u("options",s.message)});let n=m(()=>JSON.stringify({subject:e,options:i}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/observe-events",requestBody:n,responseType:"stream",abortController:t}),s=>{throw s instanceof d?s:new f(s)});if(p.status!==st.OK)throw new c(`Unexpected response status: ${p.status} ${it(p.status)}.`);let o=p.data;for await(let s of w(o))if(!C(s)){if(g(s))throw new c(`${s.payload.error}.`);if(O(s)){yield{event:E.parse(s.payload.event),hash:s.payload.hash};continue}throw new c(`Failed to observe events, an unexpected stream item was received: '${JSON.stringify(s)}'.`)}};var L=async r=>{if((await m(async()=>r.httpClient.get({path:"/api/ping",responseType:"text",withAuthorization:!1}),e=>{if(e instanceof d)throw e;new f(e)})).data!=="OK")throw new c("Received unexpected response.")};import{StatusCodes as at}from"http-status-codes";var J=r=>!(!l(r)||r.type!=="eventType");var q=async function*(r,t){let e=await m(async()=>r.httpClient.post({path:"/api/read-event-types",requestBody:"",responseType:"stream",abortController:t}),n=>{throw n instanceof d?n:new f(n)});if(e.status!==at.OK)throw new c(`Unexpected response status: ${e.status} ${e.statusText}.`);let i=e.data;for await(let n of w(i))if(!C(n)){if(g(n))throw new c(`${n.payload.error}.`);if(J(n)){yield n.payload;continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(n)}'.`)}};import{StatusCodes as pt}from"http-status-codes";var k=r=>{if(r.lowerBoundId!==void 0&&!j(r.lowerBoundId))throw new a("ReadEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.upperBoundId!==void 0&&!j(r.upperBoundId))throw new a("ReadEventsOptions are invalid: upperBoundId must be 0 or greater.");if(r.fromLatestEvent!==void 0){if(r.lowerBoundId!==void 0)throw new a("ReadEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ReadEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})}};var H=async function*(r,t,e,i){m(()=>v(e),s=>{if(s instanceof a)throw new u("subject",s.message)}),m(()=>{k(i)},s=>{if(s instanceof a)throw new u("options",s.message)});let n=m(()=>JSON.stringify({subject:e,options:i}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/read-events",requestBody:n,responseType:"stream",abortController:t}),s=>{throw s instanceof d?s:new f(s)});if(p.status!==pt.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}.`);let o=p.data;for await(let s of w(o))if(!C(s)){if(g(s))throw new c(`${s.payload.error}.`);if(O(s)){yield{event:E.parse(s.payload.event),hash:s.payload.hash};continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(s)}'.`)}};import{StatusCodes as ct,getReasonPhrase as dt}from"http-status-codes";var z=r=>{v(r.baseSubject)};var G=r=>{if(!l(r)||r.type!=="subject")return!1;let{payload:t}=r;return l(t)&&typeof t.subject=="string"};var M=async function*(r,t,e){await m(()=>{z(e)},o=>{if(o instanceof a)throw new u("options",o.message)});let i=m(()=>JSON.stringify(e),o=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),n=await m(async()=>r.httpClient.post({path:"/api/read-subjects",requestBody:i,responseType:"stream",abortController:t}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==ct.OK)throw new c(`Unexpected response status: ${n.status} ${dt(n.status)}.`);let p=n.data;for await(let o of w(p)){if(g(o))throw new c(o.payload.error);if(G(o)){yield o.payload.subject;continue}throw new c(`Failed to read subjects, an unexpected stream item was received: '${JSON.stringify(o)}'.`)}};import{StatusCodes as mt}from"http-status-codes";var K=async(r,t,e)=>{m(()=>y(t),o=>{if(o instanceof a)throw new u("eventType",o.message)});let i=e;typeof e=="object"&&(i=JSON.stringify(e));let n=JSON.stringify({eventType:t,schema:i}),p=await m(async()=>r.httpClient.post({path:"/api/register-event-schema",requestBody:n,responseType:"text"}),o=>{throw o instanceof d?o:new f(o)});if(p.status!==mt.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}: ${p.data}.`)};import{StatusCodes as ft}from"http-status-codes";var Z=async(r,t,e)=>{if(t.length===0)throw new u("eventCandidates","eventCandidates must contain at least one EventCandidate.");for(let o of t)m(()=>{o.validate()},s=>{if(s instanceof a)throw new u("eventCandidates",s.message)});let i=JSON.stringify({events:t,preconditions:e}),n=await m(async()=>r.httpClient.post({path:"/api/write-events",requestBody:i,responseType:"json"}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==ft.OK)throw new c(`Unexpected response status: ${n.status} ${n.statusText}.`);if(!Array.isArray(n.data))throw new c(`Failed to parse response '${n.data}' to array.`);let p=n.data;return m(()=>p.map(o=>b.parse(o)),o=>{throw o instanceof a?new c(o.message):new f(o)})};import{AxiosError as X,CanceledError as Y}from"axios";import _ from"axios";import{StatusCodes as ut}from"http-status-codes";var S=class extends d{constructor(t){super(`Client error occurred: ${t}`)}};var I=class r{databaseClient;constructor(t){this.databaseClient=t}getDefaultRequestConfig(t=!0){let e={baseURL:this.databaseClient.configuration.baseUrl,timeout:this.databaseClient.configuration.timeoutMilliseconds,headers:{"X-EventSourcingDB-Protocol-Version":this.databaseClient.configuration.protocolVersion},validateStatus:()=>!0};return t&&this.databaseClient.configuration.accessToken!==void 0&&(e=r.setAuthorization(e,this.databaseClient.configuration.accessToken)),e}static setContentType(t,e){return{...t,headers:{...t.headers,"Content-Type":e}}}static setAuthorization(t,e){return{...t,headers:{...t.headers,authorization:`Bearer ${e}`}}}static setResponseType(t,e){return{...t,responseType:e}}validateProtocolVersion(t,e){if(t!==ut.UNPROCESSABLE_ENTITY)return;let i=e["x-eventsourcingdb-protocol-version"];throw i===void 0&&(i="unknown version"),new S(`Protocol version mismatch, server '${i}', client '${this.databaseClient.configuration.protocolVersion}.'`)}async post(t){let e=this.getDefaultRequestConfig();e=r.setContentType(e,"application/json"),e=r.setResponseType(e,t.responseType);let i=_.create(e),p=(t.abortController??new AbortController).signal;try{let o=await i.post(t.path,t.requestBody,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return o}catch(o){throw o instanceof d?o:o instanceof Y?new h:o instanceof X?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}async get(t){let e=this.getDefaultRequestConfig(t.withAuthorization);e=r.setResponseType(e,t.responseType);let i=_.create(e),p=(t.abortController??new AbortController).signal;try{let o=await i.get(t.path,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return this.validateProtocolVersion(o.status,o.headers),o}catch(o){throw o instanceof d?o:o instanceof Y?new h:o instanceof X?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}};var A=class{configuration;httpClient;constructor(t,e){this.configuration={...F(t),...e},this.httpClient=new I(this)}observeEvents(t,e,i){return V(this,t,e,i)}async ping(){await L(this)}readEvents(t,e,i){return H(this,t,e,i)}readEventTypes(t){return q(this,t)}readSubjects(t,e){return M(this,t,e)}async registerEventSchema(t,e){return await K(this,t,e)}async writeEvents(t,e=[]){return await Z(this,t,e)}};var R=class{data;source;subject;type;traceParent;traceState;constructor(t,e,i,n,p,o){this.data=n,this.source=t,this.subject=e,this.type=i,this.traceParent=p,this.traceState=o}validate(){if(v(this.subject),y(this.type),this.traceState!==void 0&&this.traceParent===void 0)throw new a("Failed to validate trace state: trace parent must be set if trace state is set.")}toJSON(){return{data:this.data,source:this.source,subject:this.subject,type:this.type,traceparent:this.traceParent,tracestate:this.traceState}}};var B=class{source;constructor(t){this.source=t}newEvent(t,e,i,n,p){return new R(this.source,t,e,i,n,p)}};var lt=r=>({type:"isSubjectPristine",payload:r}),vt=r=>({type:"isSubjectOnEventId",payload:r});export{h as CancelationError,A as Client,E as Event,R as EventCandidate,B as Source,vt as isSubjectOnEventId,lt as isSubjectPristine};
|
package/package.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "eventsourcingdb",
|
|
3
|
+
"version": "0.9.1",
|
|
4
|
+
"description": "eventsourcingdb is the official client for EventSourcingDB.",
|
|
5
|
+
"contributors": [
|
|
6
|
+
{
|
|
7
|
+
"name": "the native web GmbH",
|
|
8
|
+
"email": "hello@thenativeweb.io"
|
|
9
|
+
}
|
|
10
|
+
],
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"axios": "1.8.4",
|
|
20
|
+
"http-status-codes": "2.3.0",
|
|
21
|
+
"stream-to-async-iterator": "1.0.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@biomejs/biome": "1.9.4",
|
|
25
|
+
"@types/express": "5.0.1",
|
|
26
|
+
"@types/node": "22.14.0",
|
|
27
|
+
"@types/shelljs": "0.8.15",
|
|
28
|
+
"express": "5.1.0",
|
|
29
|
+
"shelljs": "0.9.2",
|
|
30
|
+
"tsup": "8.4.0",
|
|
31
|
+
"tsx": "4.19.3",
|
|
32
|
+
"typescript": "5.8.2"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"analyze": "npx biome check .",
|
|
36
|
+
"build": "npx tsc --noEmit && npx tsup --clean --dts --format cjs,esm --minify --out-dir=./dist/ ./src/index.ts",
|
|
37
|
+
"format": "npx biome format --write .",
|
|
38
|
+
"qa": "npm run analyze && npm run test",
|
|
39
|
+
"test": "npm run test:unit && npm run test:integration",
|
|
40
|
+
"test:unit": "node --test --import tsx \"./test/unit/**/*.ts\"",
|
|
41
|
+
"test:integration": "node --test --import tsx \"./test/integration/**/*.ts\""
|
|
42
|
+
},
|
|
43
|
+
"repository": {
|
|
44
|
+
"type": "git",
|
|
45
|
+
"url": "git://github.com/thenativeweb/eventsourcingdb-client-javascript.git"
|
|
46
|
+
},
|
|
47
|
+
"license": "MIT"
|
|
48
|
+
}
|