arvo-core 2.0.7 → 2.0.9

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.
@@ -4,14 +4,29 @@ import { ArvoErrorSchema } from '../schema';
4
4
  import { ArvoSemanticVersion } from '../types';
5
5
  import { VersionedArvoContract } from './VersionedArvoContract';
6
6
  /**
7
- * ArvoContract class represents a contract with defined input and output schemas.
8
- * It provides methods for validating inputs and outputs based on the contract's specifications.
9
- * An event handler can be bound to it so the this contract may impose the types
10
- * on inputs and outputs of it
7
+ * Represents a contract with defined input and output schemas for event-driven architectures.
8
+ * The ArvoContract class provides type-safe validation and versioning capabilities for event handling,
9
+ * ensuring consistency in message passing between different parts of the system.
11
10
  *
12
- * @template TUri - The URI of the contract
13
- * @template TType - The accept type, defaults to string.
14
- * @template TVersion - The contract versions
11
+ * @template TUri - The URI identifier for the contract, must be a string type
12
+ * @template TType - The accept type for the contract, must be a string type
13
+ * @template TVersions - Record of versioned schemas defining contract structure per version
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const contract = createArvoContract({
18
+ * uri: '#/my/service/data',
19
+ * type: 'com.process.data',
20
+ * versions: {
21
+ * '1.0.0': {
22
+ * accepts: z.object({ data: z.string() }),
23
+ * emits: {
24
+ * 'data.processed': z.object({ result: z.string() })
25
+ * }
26
+ * }
27
+ * }
28
+ * });
29
+ * ```
15
30
  */
16
31
  export default class ArvoContract<TUri extends string = string, TType extends string = string, TVersions extends Record<ArvoSemanticVersion, {
17
32
  accepts: z.ZodTypeAny;
@@ -24,30 +39,11 @@ export default class ArvoContract<TUri extends string = string, TType extends st
24
39
  private readonly _type;
25
40
  private readonly _versions;
26
41
  readonly description: string | null;
27
- /**
28
- * Creates an instance of ArvoContract.
29
- * @param params - The contract parameters.
30
- */
31
42
  constructor(params: IArvoContract<TUri, TType, TVersions>);
32
43
  /**
33
44
  * Gets the URI of the contract.
34
45
  */
35
46
  get uri(): TUri;
36
- /**
37
- * Creates a version-specific view of the contract, providing easy access to all
38
- * schemas and specifications for a particular semantic version.
39
- *
40
- * @template V - The semantic version to create a view for, must be a valid version in the contract
41
- *
42
- * @param ver - The semantic version string (e.g., "1.0.0")
43
- * @returns A VersionedArvoContract instance containing all specifications for the requested version
44
- *
45
- * The returned object provides a simpler, flatter structure compared to
46
- * accessing version-specific information through the main contract methods.
47
- *
48
- * @see {@link VersionedArvoContract} for the structure of the returned object
49
- */
50
- version<V extends ArvoSemanticVersion & keyof TVersions>(ver: V): VersionedArvoContract<typeof this, V>;
51
47
  /**
52
48
  * Get the type of the event the handler
53
49
  * bound to the contract accepts
@@ -57,20 +53,6 @@ export default class ArvoContract<TUri extends string = string, TType extends st
57
53
  * Gets the version of the contract
58
54
  */
59
55
  get versions(): TVersions;
60
- /**
61
- * Get the latest version of the contract
62
- */
63
- get latestVersion(): ArvoSemanticVersion;
64
- /**
65
- * Gets the type and schema of the event that the contact
66
- * bound handler listens to.
67
- */
68
- accepts<V extends ArvoSemanticVersion & keyof TVersions>(version: V): ArvoContractRecord<TType, TVersions[V]['accepts']>;
69
- /**
70
- * Gets all event types and schemas that can be emitted by the
71
- * contract bound handler.
72
- */
73
- emits<V extends ArvoSemanticVersion & keyof TVersions>(version: V): TVersions[V]['emits'];
74
56
  /**
75
57
  * Gets the system error event specification for this contract.
76
58
  * System errors follow a standardized format to handle exceptional conditions
@@ -86,33 +68,34 @@ export default class ArvoContract<TUri extends string = string, TType extends st
86
68
  * - Use a standardized schema across all contracts
87
69
  * - Can capture error details, messages, and stack traces
88
70
  * - Are version-independent (work the same across all contract versions)
89
- *
90
- * @see {@link ArvoErrorSchema} for the detailed error schema definition
91
- * @see {@link ArvoContractRecord} for the structure of the returned record
92
71
  */
93
72
  get systemError(): ArvoContractRecord<`sys.${TType}.error`, typeof ArvoErrorSchema>;
94
73
  /**
95
- * Validates the contract bound handler's input/ accept event against the
96
- * contract's accept schema.
97
- * @template U - The type of the input to validate.
98
- * @template V - The version to use
99
- * @param version - The version to use
100
- * @param type - The type of the input event.
101
- * @param input - The input data to validate.
102
- * @returns The validation result.
103
- * @throws If the accept type is not found in the contract.
74
+ * Retrieves a specific version of the contract or resolves special version identifiers.
75
+ *
76
+ * @template V - Type parameter constrained to valid semantic versions in TVersions
77
+ * @template S - Type parameter for special version identifiers
78
+ *
79
+ * @param option - Version identifier or special version string
80
+ * - Specific version (e.g., "1.0.0")
81
+ * - "latest" or "any" for the most recent version
82
+ * - "oldest" for the first version
83
+ *
84
+ * @returns A versioned contract instance with type-safe schemas
85
+ *
86
+ * @throws {Error} When an invalid or non-existent version is requested
104
87
  */
105
- validateAccepts<V extends ArvoSemanticVersion & keyof TVersions, U>(version: V, type: TType, input: U): z.SafeParseReturnType<any, any>;
88
+ version<V extends ArvoSemanticVersion & keyof TVersions, S extends 'any' | 'latest' | 'oldest'>(option: V | S): V extends ArvoSemanticVersion ? VersionedArvoContract<typeof this, V> : VersionedArvoContract<typeof this, ArvoSemanticVersion & keyof TVersions>;
106
89
  /**
107
- * Validates the contract bound handler's output/ emits against the
108
- * contract's emit schema.
109
- * @template U - The type of the output to validate.
110
- * @param type - The type of the output event.
111
- * @param output - The output data to validate.
112
- * @returns The validation result.
113
- * @throws If the emit type is not found in the contract.
90
+ * Retrieves version numbers in sorted order based on semantic versioning rules.
91
+ *
92
+ * @param ordering - Sort direction for versions
93
+ * - 'ASC' - Ascending order (oldest to newest)
94
+ * - 'DESC' - Descending order (newest to oldest)
95
+ *
96
+ * @returns Array of semantic versions sorted according to specified ordering
114
97
  */
115
- validateEmits<V extends ArvoSemanticVersion & keyof TVersions, E extends string & keyof TVersions[V]['emits'], U>(version: V, type: E, output: U): z.SafeParseReturnType<any, any>;
98
+ getSortedVersionNumbers(ordering: 'ASC' | 'DESC'): `${number}.${number}.${number}`[];
116
99
  /**
117
100
  * Exports the ArvoContract instance as a plain object conforming to the IArvoContract interface.
118
101
  * This method can be used to serialize the contract or to create a new instance with the same parameters.
@@ -1,34 +1,34 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  var zod_to_json_schema_1 = require("zod-to-json-schema");
15
4
  var schema_1 = require("../schema");
16
5
  var utils_1 = require("../utils");
17
6
  /**
18
- * ArvoContract class represents a contract with defined input and output schemas.
19
- * It provides methods for validating inputs and outputs based on the contract's specifications.
20
- * An event handler can be bound to it so the this contract may impose the types
21
- * on inputs and outputs of it
7
+ * Represents a contract with defined input and output schemas for event-driven architectures.
8
+ * The ArvoContract class provides type-safe validation and versioning capabilities for event handling,
9
+ * ensuring consistency in message passing between different parts of the system.
22
10
  *
23
- * @template TUri - The URI of the contract
24
- * @template TType - The accept type, defaults to string.
25
- * @template TVersion - The contract versions
11
+ * @template TUri - The URI identifier for the contract, must be a string type
12
+ * @template TType - The accept type for the contract, must be a string type
13
+ * @template TVersions - Record of versioned schemas defining contract structure per version
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const contract = createArvoContract({
18
+ * uri: '#/my/service/data',
19
+ * type: 'com.process.data',
20
+ * versions: {
21
+ * '1.0.0': {
22
+ * accepts: z.object({ data: z.string() }),
23
+ * emits: {
24
+ * 'data.processed': z.object({ result: z.string() })
25
+ * }
26
+ * }
27
+ * }
28
+ * });
29
+ * ```
26
30
  */
27
31
  var ArvoContract = /** @class */ (function () {
28
- /**
29
- * Creates an instance of ArvoContract.
30
- * @param params - The contract parameters.
31
- */
32
32
  function ArvoContract(params) {
33
33
  var _a;
34
34
  this._uri = params.uri;
@@ -36,7 +36,7 @@ var ArvoContract = /** @class */ (function () {
36
36
  this._versions = params.versions;
37
37
  this.description = (_a = params.description) !== null && _a !== void 0 ? _a : null;
38
38
  if (!Object.keys(this._versions).length) {
39
- throw new Error("A contract must have at least one version");
39
+ throw new Error("An ArvoContract (uri=".concat(this._uri, ") must have at least one version"));
40
40
  }
41
41
  }
42
42
  Object.defineProperty(ArvoContract.prototype, "uri", {
@@ -49,33 +49,6 @@ var ArvoContract = /** @class */ (function () {
49
49
  enumerable: false,
50
50
  configurable: true
51
51
  });
52
- /**
53
- * Creates a version-specific view of the contract, providing easy access to all
54
- * schemas and specifications for a particular semantic version.
55
- *
56
- * @template V - The semantic version to create a view for, must be a valid version in the contract
57
- *
58
- * @param ver - The semantic version string (e.g., "1.0.0")
59
- * @returns A VersionedArvoContract instance containing all specifications for the requested version
60
- *
61
- * The returned object provides a simpler, flatter structure compared to
62
- * accessing version-specific information through the main contract methods.
63
- *
64
- * @see {@link VersionedArvoContract} for the structure of the returned object
65
- */
66
- ArvoContract.prototype.version = function (ver) {
67
- return {
68
- uri: this._uri,
69
- description: this.description,
70
- version: ver,
71
- accepts: {
72
- type: this._type,
73
- schema: this._versions[ver].accepts,
74
- },
75
- systemError: this.systemError,
76
- emits: this._versions[ver].emits,
77
- };
78
- };
79
52
  Object.defineProperty(ArvoContract.prototype, "type", {
80
53
  /**
81
54
  * Get the type of the event the handler
@@ -97,35 +70,6 @@ var ArvoContract = /** @class */ (function () {
97
70
  enumerable: false,
98
71
  configurable: true
99
72
  });
100
- Object.defineProperty(ArvoContract.prototype, "latestVersion", {
101
- /**
102
- * Get the latest version of the contract
103
- */
104
- get: function () {
105
- return Object.keys(this._versions).sort(function (a, b) {
106
- return (0, utils_1.compareSemanticVersions)(b, a);
107
- })[0];
108
- },
109
- enumerable: false,
110
- configurable: true
111
- });
112
- /**
113
- * Gets the type and schema of the event that the contact
114
- * bound handler listens to.
115
- */
116
- ArvoContract.prototype.accepts = function (version) {
117
- return {
118
- type: this._type,
119
- schema: this._versions[version].accepts,
120
- };
121
- };
122
- /**
123
- * Gets all event types and schemas that can be emitted by the
124
- * contract bound handler.
125
- */
126
- ArvoContract.prototype.emits = function (version) {
127
- return __assign({}, this._versions[version].emits);
128
- };
129
73
  Object.defineProperty(ArvoContract.prototype, "systemError", {
130
74
  /**
131
75
  * Gets the system error event specification for this contract.
@@ -142,9 +86,6 @@ var ArvoContract = /** @class */ (function () {
142
86
  * - Use a standardized schema across all contracts
143
87
  * - Can capture error details, messages, and stack traces
144
88
  * - Are version-independent (work the same across all contract versions)
145
- *
146
- * @see {@link ArvoErrorSchema} for the detailed error schema definition
147
- * @see {@link ArvoContractRecord} for the structure of the returned record
148
89
  */
149
90
  get: function () {
150
91
  return {
@@ -156,38 +97,58 @@ var ArvoContract = /** @class */ (function () {
156
97
  configurable: true
157
98
  });
158
99
  /**
159
- * Validates the contract bound handler's input/ accept event against the
160
- * contract's accept schema.
161
- * @template U - The type of the input to validate.
162
- * @template V - The version to use
163
- * @param version - The version to use
164
- * @param type - The type of the input event.
165
- * @param input - The input data to validate.
166
- * @returns The validation result.
167
- * @throws If the accept type is not found in the contract.
100
+ * Retrieves a specific version of the contract or resolves special version identifiers.
101
+ *
102
+ * @template V - Type parameter constrained to valid semantic versions in TVersions
103
+ * @template S - Type parameter for special version identifiers
104
+ *
105
+ * @param option - Version identifier or special version string
106
+ * - Specific version (e.g., "1.0.0")
107
+ * - "latest" or "any" for the most recent version
108
+ * - "oldest" for the first version
109
+ *
110
+ * @returns A versioned contract instance with type-safe schemas
111
+ *
112
+ * @throws {Error} When an invalid or non-existent version is requested
168
113
  */
169
- ArvoContract.prototype.validateAccepts = function (version, type, input) {
170
- if (type !== this._type) {
171
- throw new Error("Accept type \"".concat(type, "\" for version \"").concat(version, "\" not found in contract \"").concat(this._uri, "\""));
114
+ ArvoContract.prototype.version = function (option) {
115
+ var resolvedVersion;
116
+ if (option === 'any' || option === 'latest') {
117
+ resolvedVersion = this.getSortedVersionNumbers('DESC')[0];
172
118
  }
173
- return this._versions[version].accepts.safeParse(input);
119
+ else if (option === 'oldest') {
120
+ resolvedVersion = this.getSortedVersionNumbers('ASC')[0];
121
+ }
122
+ else if (!this._versions[option]) {
123
+ throw new Error("The contract (uri=".concat(this._uri, ") does not have version=").concat(option));
124
+ }
125
+ else {
126
+ resolvedVersion = option;
127
+ }
128
+ return {
129
+ uri: this._uri,
130
+ description: this.description,
131
+ version: resolvedVersion,
132
+ accepts: {
133
+ type: this._type,
134
+ schema: this._versions[resolvedVersion].accepts,
135
+ },
136
+ systemError: this.systemError,
137
+ emits: this._versions[resolvedVersion].emits,
138
+ }; // needed due to TypeScript limitations with conditional types
174
139
  };
175
140
  /**
176
- * Validates the contract bound handler's output/ emits against the
177
- * contract's emit schema.
178
- * @template U - The type of the output to validate.
179
- * @param type - The type of the output event.
180
- * @param output - The output data to validate.
181
- * @returns The validation result.
182
- * @throws If the emit type is not found in the contract.
141
+ * Retrieves version numbers in sorted order based on semantic versioning rules.
142
+ *
143
+ * @param ordering - Sort direction for versions
144
+ * - 'ASC' - Ascending order (oldest to newest)
145
+ * - 'DESC' - Descending order (newest to oldest)
146
+ *
147
+ * @returns Array of semantic versions sorted according to specified ordering
183
148
  */
184
- ArvoContract.prototype.validateEmits = function (version, type, output) {
185
- var _a, _b, _c;
186
- var emit = (_c = (_b = (_a = this._versions) === null || _a === void 0 ? void 0 : _a[version]) === null || _b === void 0 ? void 0 : _b.emits) === null || _c === void 0 ? void 0 : _c[type];
187
- if (!emit) {
188
- throw new Error("Emit type \"".concat(type.toString(), "\" for version \"").concat(version, "\" not found in contract \"").concat(this._uri, "\""));
189
- }
190
- return emit.safeParse(output);
149
+ ArvoContract.prototype.getSortedVersionNumbers = function (ordering) {
150
+ var sorted = Object.keys(this._versions).sort(function (a, b) { return (0, utils_1.compareSemanticVersions)(b, a); });
151
+ return ordering === 'DESC' ? sorted : sorted.reverse();
191
152
  };
192
153
  /**
193
154
  * Exports the ArvoContract instance as a plain object conforming to the IArvoContract interface.
@@ -2,39 +2,86 @@ import ArvoEvent from '.';
2
2
  import { ArvoEventData, CloudEventExtension, CreateArvoEvent } from './types';
3
3
  import { ExecutionOpenTelemetryConfiguration } from '../OpenTelemetry/types';
4
4
  /**
5
- * Creates an ArvoEvent with the provided data and extensions.
5
+ * Creates a strongly-typed ArvoEvent with configurable telemetry options.
6
6
  *
7
- * This function creates a new ArvoEvent instance using the provided event data and optional extensions.
7
+ * @template TData - Event data type extending ArvoEventData
8
+ * @template TExtension - Cloud event extension type
9
+ * @template TType - String literal type for event type
8
10
  *
9
- * @template TData - The type of the event data, extending ArvoEventData.
10
- * @template TExtension - The type of the cloud event extension, extending CloudEventExtension.
11
- * @template TType - The type name of the event
11
+ * @param event - Event configuration and data
12
+ * @param [extensions] - Optional cloud event extensions
13
+ * @param [opentelemetry] - OpenTelemetry configuration with options:
14
+ * - disable - Completely disables telemetry if true
15
+ * - tracer - Custom OpenTelemetry tracer instance
12
16
  *
13
- * @param {CreateArvoEvent<TData>} event - The event data and metadata to create the ArvoEvent.
14
- * @param {TExtension} [extensions] - Optional cloud event extensions.
15
- * @param {ExecutionOpenTelemetryConfiguration} [opentelemetry] - Optional opentelemetry configuration object
17
+ * @returns ArvoEvent instance
16
18
  *
17
- * @returns {ArvoEvent<TData, TExtension>} The created ArvoEvent instance.
18
- *
19
- * @throws {Error} If there's an error during the creation process.
19
+ * @example
20
+ * ```typescript
21
+ * // With default telemetry
22
+ * const event = createArvoEvent({
23
+ * type: 'order.created',
24
+ * source: '/orders',
25
+ * subject: 'order-123',
26
+ * data: orderData
27
+ * });
20
28
  *
21
- * @remarks
22
- * - If no `id` is provided in the event object, a UUID v4 will be generated.
23
- * - If no `time` is provided, the current timestamp will be used.
24
- * - If no `datacontenttype` is provided, it defaults to `application/cloudevents+json;charset=UTF-8;profile=arvo`.
25
- * - If a non-compatible `datacontenttype` is provided, a warning will be logged to the span.
26
- * - The `source`, `subject`, `to`, `redirectto`, and `dataschema` fields are URI-encoded.
27
- * - If no `to` (null, undefined or empty string) is provided, then the `type` value is used by default
29
+ * // With disabled telemetry
30
+ * const event = createArvoEvent(
31
+ * {
32
+ * type: 'order.created',
33
+ * source: '/orders',
34
+ * subject: 'order-123',
35
+ * data: orderData
36
+ * },
37
+ * undefined,
38
+ * { disable: true }
39
+ * );
28
40
  *
29
- * @example
41
+ * // With custom tracer
30
42
  * const event = createArvoEvent(
31
43
  * {
32
- * type: 'com.example.event',
33
- * source: '/example/source',
34
- * subject: 'example-subject',
35
- * data: { key: 'value' }
44
+ * type: 'order.created',
45
+ * source: '/orders',
46
+ * subject: 'order-123',
47
+ * data: orderData
36
48
  * },
37
- * { customextension: 'value' },
49
+ * undefined,
50
+ * { tracer: customTracer }
38
51
  * );
52
+ * ```
53
+ *
54
+ * @remarks
55
+ * This function provides several key features:
56
+ *
57
+ * 1. **Type Safety**:
58
+ * - Ensures event data matches specified type
59
+ * - Validates extension structure
60
+ * - Provides type-safe event type strings
61
+ *
62
+ * 2. **Default Handling**:
63
+ * - Generates UUID if no ID provided
64
+ * - Sets current timestamp if no time provided
65
+ * - Uses default ArvoDataContentType if none specified
66
+ *
67
+ * 3. **URI Handling**:
68
+ * - Automatically encodes URI components (source, subject, to, redirectto, dataschema)
69
+ * - Validates URI format
70
+ *
71
+ * 4. **OpenTelemetry Integration**:
72
+ * - Creates spans for event creation
73
+ * - Tracks errors and warnings
74
+ * - Propagates trace context
75
+ *
76
+ * 5. **Validation**:
77
+ * - Checks data content type compatibility
78
+ * - Validates required fields
79
+ * - Ensures URI format correctness
80
+ *
81
+ * @see {@link ArvoEvent} For the structure of the created event
82
+ * @see {@link ArvoDataContentType} For supported content types
83
+ * @see {@link CloudEventExtension} For extension structure
39
84
  */
40
- export declare const createArvoEvent: <TData extends ArvoEventData, TExtension extends CloudEventExtension, TType extends string>(event: CreateArvoEvent<TData, TType>, extensions?: TExtension, opentelemetry?: ExecutionOpenTelemetryConfiguration) => ArvoEvent<TData, TExtension, TType>;
85
+ export declare const createArvoEvent: <TData extends ArvoEventData, TExtension extends CloudEventExtension, TType extends string>(event: CreateArvoEvent<TData, TType>, extensions?: TExtension, opentelemetry?: Partial<ExecutionOpenTelemetryConfiguration & {
86
+ disable: boolean;
87
+ }>) => ArvoEvent<TData, TExtension, TType>;
@@ -11,75 +11,144 @@ var utils_1 = require("../utils");
11
11
  var schema_1 = require("./schema");
12
12
  var uuid_1 = require("uuid");
13
13
  /**
14
- * Creates an ArvoEvent with the provided data and extensions.
14
+ * Internal generator function for creating ArvoEvent instances.
15
15
  *
16
- * This function creates a new ArvoEvent instance using the provided event data and optional extensions.
16
+ * @template TData - Type of the event data
17
+ * @template TExtension - Type of cloud event extensions
18
+ * @param {CreateArvoEvent<any, any>} event - The event configuration and data
19
+ * @param {any} extensions - Cloud event extensions
20
+ * @param {ReturnType<typeof currentOpenTelemetryHeaders>} otelHeaders - OpenTelemetry headers
21
+ * @returns {ArvoEvent<any, any, any>} A new ArvoEvent instance
17
22
  *
18
- * @template TData - The type of the event data, extending ArvoEventData.
19
- * @template TExtension - The type of the cloud event extension, extending CloudEventExtension.
20
- * @template TType - The type name of the event
21
- *
22
- * @param {CreateArvoEvent<TData>} event - The event data and metadata to create the ArvoEvent.
23
- * @param {TExtension} [extensions] - Optional cloud event extensions.
24
- * @param {ExecutionOpenTelemetryConfiguration} [opentelemetry] - Optional opentelemetry configuration object
23
+ * @remarks
24
+ * This function handles the actual creation of the ArvoEvent instance, including:
25
+ * - Generation of default values for optional fields
26
+ * - URI encoding of relevant fields
27
+ * - Validation of data content type
28
+ * - Integration with OpenTelemetry headers
29
+ * ```
30
+ */
31
+ var generator = function (event, extensions, otelHeaders) {
32
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
33
+ if (event.datacontenttype && event.datacontenttype !== schema_1.ArvoDataContentType) {
34
+ var warning = (0, utils_1.cleanString)("\n Warning! The provided datacontenttype(=".concat(event.datacontenttype, ")\n is not ArvoEvent compatible (=").concat(schema_1.ArvoDataContentType, "). There may \n be some limited functionality.\n "));
35
+ (0, OpenTelemetry_1.logToSpan)({
36
+ level: 'WARNING',
37
+ message: warning,
38
+ });
39
+ }
40
+ return new _1.default({
41
+ id: (_a = event.id) !== null && _a !== void 0 ? _a : (0, uuid_1.v4)(),
42
+ type: event.type,
43
+ accesscontrol: (_b = event.accesscontrol) !== null && _b !== void 0 ? _b : null,
44
+ executionunits: (_c = event.executionunits) !== null && _c !== void 0 ? _c : null,
45
+ traceparent: (_e = (_d = event.traceparent) !== null && _d !== void 0 ? _d : otelHeaders.traceparent) !== null && _e !== void 0 ? _e : null,
46
+ tracestate: (_g = (_f = event.tracestate) !== null && _f !== void 0 ? _f : otelHeaders.tracestate) !== null && _g !== void 0 ? _g : null,
47
+ datacontenttype: (_h = event.datacontenttype) !== null && _h !== void 0 ? _h : schema_1.ArvoDataContentType,
48
+ specversion: (_j = event.specversion) !== null && _j !== void 0 ? _j : '1.0',
49
+ time: (_k = event.time) !== null && _k !== void 0 ? _k : (0, utils_1.createTimestamp)(),
50
+ source: encodeURI(event.source),
51
+ subject: encodeURI(event.subject),
52
+ to: event.to ? encodeURI(event.to) : encodeURI(event.type),
53
+ redirectto: event.redirectto ? encodeURI(event.redirectto) : null,
54
+ dataschema: event.dataschema ? encodeURI(event.dataschema) : null,
55
+ }, event.data, extensions);
56
+ };
57
+ /**
58
+ * Creates a strongly-typed ArvoEvent with configurable telemetry options.
25
59
  *
26
- * @returns {ArvoEvent<TData, TExtension>} The created ArvoEvent instance.
60
+ * @template TData - Event data type extending ArvoEventData
61
+ * @template TExtension - Cloud event extension type
62
+ * @template TType - String literal type for event type
27
63
  *
28
- * @throws {Error} If there's an error during the creation process.
64
+ * @param event - Event configuration and data
65
+ * @param [extensions] - Optional cloud event extensions
66
+ * @param [opentelemetry] - OpenTelemetry configuration with options:
67
+ * - disable - Completely disables telemetry if true
68
+ * - tracer - Custom OpenTelemetry tracer instance
29
69
  *
30
- * @remarks
31
- * - If no `id` is provided in the event object, a UUID v4 will be generated.
32
- * - If no `time` is provided, the current timestamp will be used.
33
- * - If no `datacontenttype` is provided, it defaults to `application/cloudevents+json;charset=UTF-8;profile=arvo`.
34
- * - If a non-compatible `datacontenttype` is provided, a warning will be logged to the span.
35
- * - The `source`, `subject`, `to`, `redirectto`, and `dataschema` fields are URI-encoded.
36
- * - If no `to` (null, undefined or empty string) is provided, then the `type` value is used by default
70
+ * @returns ArvoEvent instance
37
71
  *
38
72
  * @example
73
+ * ```typescript
74
+ * // With default telemetry
75
+ * const event = createArvoEvent({
76
+ * type: 'order.created',
77
+ * source: '/orders',
78
+ * subject: 'order-123',
79
+ * data: orderData
80
+ * });
81
+ *
82
+ * // With disabled telemetry
83
+ * const event = createArvoEvent(
84
+ * {
85
+ * type: 'order.created',
86
+ * source: '/orders',
87
+ * subject: 'order-123',
88
+ * data: orderData
89
+ * },
90
+ * undefined,
91
+ * { disable: true }
92
+ * );
93
+ *
94
+ * // With custom tracer
39
95
  * const event = createArvoEvent(
40
96
  * {
41
- * type: 'com.example.event',
42
- * source: '/example/source',
43
- * subject: 'example-subject',
44
- * data: { key: 'value' }
97
+ * type: 'order.created',
98
+ * source: '/orders',
99
+ * subject: 'order-123',
100
+ * data: orderData
45
101
  * },
46
- * { customextension: 'value' },
102
+ * undefined,
103
+ * { tracer: customTracer }
47
104
  * );
105
+ * ```
106
+ *
107
+ * @remarks
108
+ * This function provides several key features:
109
+ *
110
+ * 1. **Type Safety**:
111
+ * - Ensures event data matches specified type
112
+ * - Validates extension structure
113
+ * - Provides type-safe event type strings
114
+ *
115
+ * 2. **Default Handling**:
116
+ * - Generates UUID if no ID provided
117
+ * - Sets current timestamp if no time provided
118
+ * - Uses default ArvoDataContentType if none specified
119
+ *
120
+ * 3. **URI Handling**:
121
+ * - Automatically encodes URI components (source, subject, to, redirectto, dataschema)
122
+ * - Validates URI format
123
+ *
124
+ * 4. **OpenTelemetry Integration**:
125
+ * - Creates spans for event creation
126
+ * - Tracks errors and warnings
127
+ * - Propagates trace context
128
+ *
129
+ * 5. **Validation**:
130
+ * - Checks data content type compatibility
131
+ * - Validates required fields
132
+ * - Ensures URI format correctness
133
+ *
134
+ * @see {@link ArvoEvent} For the structure of the created event
135
+ * @see {@link ArvoDataContentType} For supported content types
136
+ * @see {@link CloudEventExtension} For extension structure
48
137
  */
49
138
  var createArvoEvent = function (event, extensions, opentelemetry) {
50
- opentelemetry = opentelemetry !== null && opentelemetry !== void 0 ? opentelemetry : {
51
- tracer: (0, OpenTelemetry_1.fetchOpenTelemetryTracer)(),
52
- };
53
- var span = opentelemetry.tracer.startSpan("createArvoEvent<".concat(event.type, ">"), {});
139
+ var _a;
140
+ if (!(opentelemetry === null || opentelemetry === void 0 ? void 0 : opentelemetry.disable)) {
141
+ return generator(event, extensions, {
142
+ traceparent: null,
143
+ tracestate: null,
144
+ });
145
+ }
146
+ var tracer = (_a = opentelemetry === null || opentelemetry === void 0 ? void 0 : opentelemetry.tracer) !== null && _a !== void 0 ? _a : (0, OpenTelemetry_1.fetchOpenTelemetryTracer)();
147
+ var span = tracer.startSpan("createArvoEvent<".concat(event.type, ">"), {});
54
148
  return api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), function () {
55
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
56
149
  span.setStatus({ code: api_1.SpanStatusCode.OK });
57
- var otelHeaders = (0, OpenTelemetry_1.currentOpenTelemetryHeaders)();
58
150
  try {
59
- if (event.datacontenttype &&
60
- event.datacontenttype !== schema_1.ArvoDataContentType) {
61
- var warning = (0, utils_1.cleanString)("\n Warning! The provided datacontenttype(=".concat(event.datacontenttype, ")\n is not ArvoEvent compatible (=").concat(schema_1.ArvoDataContentType, "). There may \n be some limited functionality.\n "));
62
- (0, OpenTelemetry_1.logToSpan)({
63
- level: 'WARNING',
64
- message: warning,
65
- });
66
- }
67
- return new _1.default({
68
- id: (_a = event.id) !== null && _a !== void 0 ? _a : (0, uuid_1.v4)(),
69
- type: event.type,
70
- accesscontrol: (_b = event.accesscontrol) !== null && _b !== void 0 ? _b : null,
71
- executionunits: (_c = event.executionunits) !== null && _c !== void 0 ? _c : null,
72
- traceparent: (_e = (_d = event.traceparent) !== null && _d !== void 0 ? _d : otelHeaders.traceparent) !== null && _e !== void 0 ? _e : null,
73
- tracestate: (_g = (_f = event.tracestate) !== null && _f !== void 0 ? _f : otelHeaders.tracestate) !== null && _g !== void 0 ? _g : null,
74
- datacontenttype: (_h = event.datacontenttype) !== null && _h !== void 0 ? _h : schema_1.ArvoDataContentType,
75
- specversion: (_j = event.specversion) !== null && _j !== void 0 ? _j : '1.0',
76
- time: (_k = event.time) !== null && _k !== void 0 ? _k : (0, utils_1.createTimestamp)(),
77
- source: encodeURI(event.source),
78
- subject: encodeURI(event.subject),
79
- to: event.to ? encodeURI(event.to) : encodeURI(event.type),
80
- redirectto: event.redirectto ? encodeURI(event.redirectto) : null,
81
- dataschema: event.dataschema ? encodeURI(event.dataschema) : null,
82
- }, event.data, extensions);
151
+ return generator(event, extensions, (0, OpenTelemetry_1.currentOpenTelemetryHeaders)());
83
152
  }
84
153
  catch (error) {
85
154
  (0, OpenTelemetry_1.exceptionToSpan)(error);
@@ -93,7 +93,7 @@ var ArvoEventFactory = /** @class */ (function () {
93
93
  if (!validationResult.success) {
94
94
  throw new Error("Accept Event data validation failed: ".concat(validationResult.error.message));
95
95
  }
96
- return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { traceparent: (_b = (_a = event.traceparent) !== null && _a !== void 0 ? _a : otelHeaders.traceparent) !== null && _b !== void 0 ? _b : undefined, tracestate: (_d = (_c = event.tracestate) !== null && _c !== void 0 ? _c : otelHeaders.tracestate) !== null && _d !== void 0 ? _d : undefined, type: _this.contract.accepts.type, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(_this.contract.version), data: validationResult.data }), extensions, opentelemetry);
96
+ return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { traceparent: (_b = (_a = event.traceparent) !== null && _a !== void 0 ? _a : otelHeaders.traceparent) !== null && _b !== void 0 ? _b : undefined, tracestate: (_d = (_c = event.tracestate) !== null && _c !== void 0 ? _c : otelHeaders.tracestate) !== null && _d !== void 0 ? _d : undefined, type: _this.contract.accepts.type, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(_this.contract.version), data: validationResult.data }), extensions, { disable: true });
97
97
  }
98
98
  catch (error) {
99
99
  (0, OpenTelemetry_1.exceptionToSpan)(error);
@@ -147,7 +147,7 @@ var ArvoEventFactory = /** @class */ (function () {
147
147
  var msg = (_d = (_c = validationResult === null || validationResult === void 0 ? void 0 : validationResult.error) === null || _c === void 0 ? void 0 : _c.message) !== null && _d !== void 0 ? _d : "No contract available for ".concat(event.type);
148
148
  throw new Error("Emit Event data validation failed: ".concat(msg));
149
149
  }
150
- return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { traceparent: (_f = (_e = event.traceparent) !== null && _e !== void 0 ? _e : otelHeaders.traceparent) !== null && _f !== void 0 ? _f : undefined, tracestate: (_h = (_g = event.tracestate) !== null && _g !== void 0 ? _g : otelHeaders.tracestate) !== null && _h !== void 0 ? _h : undefined, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(_this.contract.version), data: validationResult.data }), extensions, opentelemetry);
150
+ return (0, helpers_1.createArvoEvent)(__assign(__assign({}, event), { traceparent: (_f = (_e = event.traceparent) !== null && _e !== void 0 ? _e : otelHeaders.traceparent) !== null && _f !== void 0 ? _f : undefined, tracestate: (_h = (_g = event.tracestate) !== null && _g !== void 0 ? _g : otelHeaders.tracestate) !== null && _h !== void 0 ? _h : undefined, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(_this.contract.version), data: validationResult.data }), extensions, { disable: true });
151
151
  }
152
152
  catch (error) {
153
153
  (0, OpenTelemetry_1.exceptionToSpan)(error);
@@ -200,7 +200,7 @@ var ArvoEventFactory = /** @class */ (function () {
200
200
  errorName: error.name,
201
201
  errorMessage: error.message,
202
202
  errorStack: (_e = error.stack) !== null && _e !== void 0 ? _e : null,
203
- }, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(ArvoOrchestrationSubject_1.default.WildCardMachineVersion) }), extensions, opentelemetry);
203
+ }, datacontenttype: schema_1.ArvoDataContentType, dataschema: "".concat(_this.contract.uri, "/").concat(ArvoOrchestrationSubject_1.default.WildCardMachineVersion) }), extensions, { disable: true });
204
204
  }
205
205
  catch (error) {
206
206
  (0, OpenTelemetry_1.exceptionToSpan)(error);
package/dist/types.d.ts CHANGED
@@ -129,12 +129,6 @@ type InferZodSchema<T> = T extends z.ZodTypeAny ? z.infer<T> : never;
129
129
  * // systemError: { ... inferred system error event type ... };
130
130
  * // }
131
131
  * ```
132
- *
133
- * @remarks
134
- * - All version keys must be valid {@link ArvoSemanticVersion} strings
135
- * - The contract must define at least one version
136
- * - Each version must specify both accepted and emitted event schemas
137
- * - System error handling is automatically included for all contracts
138
132
  */
139
133
  export type InferArvoContract<T extends ArvoContract<string, string, Record<ArvoSemanticVersion, {
140
134
  accepts: z.ZodTypeAny;
@@ -184,19 +178,6 @@ export type ArvoErrorType = z.infer<typeof ArvoErrorSchema>;
184
178
  * @property systemError - The fully resolved system error event type
185
179
  * @property emits - Record of all fully resolved emit event types
186
180
  *
187
- * This type utility:
188
- * - Transforms Zod schemas into their inferred TypeScript types
189
- * - Wraps all event types in the full ArvoEvent structure
190
- * - Preserves all event type relationships and constraints
191
- * - Includes OpenTelemetry and Arvo extensions
192
- * - Maintains type safety across all transformations
193
- *
194
- * Common use cases:
195
- * - Type-safe event handling in version-specific contexts
196
- * - Generating TypeScript interfaces for API documentation
197
- * - Validating event payload types at compile time
198
- * - Creating type-safe event factories
199
- *
200
181
  * @see {@link VersionedArvoContract} for the input contract structure
201
182
  * @see {@link InferArvoEvent} for the event inference utility
202
183
  * @see {@link ArvoEvent} for the base event structure
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arvo-core",
3
- "version": "2.0.7",
3
+ "version": "2.0.9",
4
4
  "description": "This core package contains all the core classes and components of the Arvo Event Driven System",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {