@sachitv/avro-typescript 0.4.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.
Files changed (163) hide show
  1. package/esm/_dnt.polyfills.d.ts +11 -0
  2. package/esm/_dnt.polyfills.js +15 -0
  3. package/esm/avro_reader.d.ts +156 -0
  4. package/esm/avro_reader.js +201 -0
  5. package/esm/avro_writer.d.ts +75 -0
  6. package/esm/avro_writer.js +105 -0
  7. package/esm/internal/collections/array_utils.d.ts +4 -0
  8. package/esm/internal/collections/array_utils.js +18 -0
  9. package/esm/internal/collections/circular_buffer.d.ts +48 -0
  10. package/esm/internal/collections/circular_buffer.js +129 -0
  11. package/esm/internal/crypto/md5.d.ts +12 -0
  12. package/esm/internal/crypto/md5.js +158 -0
  13. package/esm/internal/varint.d.ts +6 -0
  14. package/esm/internal/varint.js +30 -0
  15. package/esm/mod.d.ts +77 -0
  16. package/esm/mod.js +73 -0
  17. package/esm/package.json +3 -0
  18. package/esm/rpc/definitions/message_definition.d.ts +34 -0
  19. package/esm/rpc/definitions/message_definition.js +105 -0
  20. package/esm/rpc/definitions/protocol_definitions.d.ts +197 -0
  21. package/esm/rpc/definitions/protocol_definitions.js +1 -0
  22. package/esm/rpc/message_endpoint/base.d.ts +43 -0
  23. package/esm/rpc/message_endpoint/base.js +81 -0
  24. package/esm/rpc/message_endpoint/emitter.d.ts +96 -0
  25. package/esm/rpc/message_endpoint/emitter.js +245 -0
  26. package/esm/rpc/message_endpoint/helpers.d.ts +37 -0
  27. package/esm/rpc/message_endpoint/helpers.js +68 -0
  28. package/esm/rpc/message_endpoint/listener.d.ts +37 -0
  29. package/esm/rpc/message_endpoint/listener.js +212 -0
  30. package/esm/rpc/protocol/frame_assembler.d.ts +11 -0
  31. package/esm/rpc/protocol/frame_assembler.js +77 -0
  32. package/esm/rpc/protocol/protocol_helpers.d.ts +59 -0
  33. package/esm/rpc/protocol/protocol_helpers.js +123 -0
  34. package/esm/rpc/protocol/transports/fetch.d.ts +9 -0
  35. package/esm/rpc/protocol/transports/fetch.js +30 -0
  36. package/esm/rpc/protocol/transports/in_memory.d.ts +27 -0
  37. package/esm/rpc/protocol/transports/in_memory.js +125 -0
  38. package/esm/rpc/protocol/transports/transport_helpers.d.ts +118 -0
  39. package/esm/rpc/protocol/transports/transport_helpers.js +112 -0
  40. package/esm/rpc/protocol/transports/websocket.d.ts +9 -0
  41. package/esm/rpc/protocol/transports/websocket.js +102 -0
  42. package/esm/rpc/protocol/wire_format/framing.d.ts +44 -0
  43. package/esm/rpc/protocol/wire_format/framing.js +74 -0
  44. package/esm/rpc/protocol/wire_format/handshake.d.ts +110 -0
  45. package/esm/rpc/protocol/wire_format/handshake.js +239 -0
  46. package/esm/rpc/protocol/wire_format/messages.d.ts +192 -0
  47. package/esm/rpc/protocol/wire_format/messages.js +175 -0
  48. package/esm/rpc/protocol/wire_format/metadata.d.ts +44 -0
  49. package/esm/rpc/protocol/wire_format/metadata.js +74 -0
  50. package/esm/rpc/protocol_core.d.ts +121 -0
  51. package/esm/rpc/protocol_core.js +285 -0
  52. package/esm/schemas/base_type.d.ts +41 -0
  53. package/esm/schemas/base_type.js +49 -0
  54. package/esm/schemas/complex/array_type.d.ts +100 -0
  55. package/esm/schemas/complex/array_type.js +299 -0
  56. package/esm/schemas/complex/enum_type.d.ts +81 -0
  57. package/esm/schemas/complex/enum_type.js +217 -0
  58. package/esm/schemas/complex/fixed_type.d.ts +99 -0
  59. package/esm/schemas/complex/fixed_type.js +208 -0
  60. package/esm/schemas/complex/map_type.d.ts +97 -0
  61. package/esm/schemas/complex/map_type.js +290 -0
  62. package/esm/schemas/complex/named_type.d.ts +30 -0
  63. package/esm/schemas/complex/named_type.js +57 -0
  64. package/esm/schemas/complex/record_type.d.ts +165 -0
  65. package/esm/schemas/complex/record_type.js +547 -0
  66. package/esm/schemas/complex/resolve_names.d.ts +32 -0
  67. package/esm/schemas/complex/resolve_names.js +85 -0
  68. package/esm/schemas/complex/union_type.d.ts +116 -0
  69. package/esm/schemas/complex/union_type.js +392 -0
  70. package/esm/schemas/error.d.ts +31 -0
  71. package/esm/schemas/error.js +67 -0
  72. package/esm/schemas/json.d.ts +6 -0
  73. package/esm/schemas/json.js +35 -0
  74. package/esm/schemas/logical/decimal_logical_type.d.ts +49 -0
  75. package/esm/schemas/logical/decimal_logical_type.js +145 -0
  76. package/esm/schemas/logical/duration_logical_type.d.ts +66 -0
  77. package/esm/schemas/logical/duration_logical_type.js +112 -0
  78. package/esm/schemas/logical/logical_type.d.ts +138 -0
  79. package/esm/schemas/logical/logical_type.js +240 -0
  80. package/esm/schemas/logical/temporal_logical_types.d.ts +215 -0
  81. package/esm/schemas/logical/temporal_logical_types.js +364 -0
  82. package/esm/schemas/logical/uuid_logical_type.d.ts +63 -0
  83. package/esm/schemas/logical/uuid_logical_type.js +146 -0
  84. package/esm/schemas/primitive/boolean_type.d.ts +49 -0
  85. package/esm/schemas/primitive/boolean_type.js +75 -0
  86. package/esm/schemas/primitive/bytes_type.d.ts +49 -0
  87. package/esm/schemas/primitive/bytes_type.js +136 -0
  88. package/esm/schemas/primitive/double_type.d.ts +38 -0
  89. package/esm/schemas/primitive/double_type.js +98 -0
  90. package/esm/schemas/primitive/fixed_size_base_type.d.ts +28 -0
  91. package/esm/schemas/primitive/fixed_size_base_type.js +33 -0
  92. package/esm/schemas/primitive/float_type.d.ts +38 -0
  93. package/esm/schemas/primitive/float_type.js +88 -0
  94. package/esm/schemas/primitive/int_type.d.ts +31 -0
  95. package/esm/schemas/primitive/int_type.js +63 -0
  96. package/esm/schemas/primitive/long_type.d.ts +36 -0
  97. package/esm/schemas/primitive/long_type.js +95 -0
  98. package/esm/schemas/primitive/null_type.d.ts +45 -0
  99. package/esm/schemas/primitive/null_type.js +71 -0
  100. package/esm/schemas/primitive/primitive_type.d.ts +17 -0
  101. package/esm/schemas/primitive/primitive_type.js +27 -0
  102. package/esm/schemas/primitive/string_type.d.ts +34 -0
  103. package/esm/schemas/primitive/string_type.js +81 -0
  104. package/esm/schemas/resolver.d.ts +25 -0
  105. package/esm/schemas/resolver.js +25 -0
  106. package/esm/schemas/type.d.ts +101 -0
  107. package/esm/schemas/type.js +6 -0
  108. package/esm/serialization/avro_constants.d.ts +13 -0
  109. package/esm/serialization/avro_constants.js +29 -0
  110. package/esm/serialization/avro_file_parser.d.ts +68 -0
  111. package/esm/serialization/avro_file_parser.js +191 -0
  112. package/esm/serialization/avro_file_writer.d.ts +63 -0
  113. package/esm/serialization/avro_file_writer.js +235 -0
  114. package/esm/serialization/buffers/blob_readable_buffer.d.ts +53 -0
  115. package/esm/serialization/buffers/blob_readable_buffer.js +80 -0
  116. package/esm/serialization/buffers/buffer.d.ts +37 -0
  117. package/esm/serialization/buffers/buffer.js +1 -0
  118. package/esm/serialization/buffers/in_memory_buffer.d.ts +121 -0
  119. package/esm/serialization/buffers/in_memory_buffer.js +206 -0
  120. package/esm/serialization/clamp.d.ts +10 -0
  121. package/esm/serialization/clamp.js +19 -0
  122. package/esm/serialization/compare_bytes.d.ts +9 -0
  123. package/esm/serialization/compare_bytes.js +45 -0
  124. package/esm/serialization/conversion.d.ts +8 -0
  125. package/esm/serialization/conversion.js +15 -0
  126. package/esm/serialization/decoders/decoder.d.ts +16 -0
  127. package/esm/serialization/decoders/decoder.js +1 -0
  128. package/esm/serialization/decoders/deflate_decoder.d.ts +15 -0
  129. package/esm/serialization/decoders/deflate_decoder.js +26 -0
  130. package/esm/serialization/decoders/null_decoder.d.ts +12 -0
  131. package/esm/serialization/decoders/null_decoder.js +13 -0
  132. package/esm/serialization/encoders/deflate_encoder.d.ts +15 -0
  133. package/esm/serialization/encoders/deflate_encoder.js +26 -0
  134. package/esm/serialization/encoders/encoder.d.ts +16 -0
  135. package/esm/serialization/encoders/encoder.js +1 -0
  136. package/esm/serialization/encoders/null_encoder.d.ts +12 -0
  137. package/esm/serialization/encoders/null_encoder.js +13 -0
  138. package/esm/serialization/manipulate_bytes.d.ts +6 -0
  139. package/esm/serialization/manipulate_bytes.js +13 -0
  140. package/esm/serialization/read_uint_le.d.ts +4 -0
  141. package/esm/serialization/read_uint_le.js +14 -0
  142. package/esm/serialization/streams/fixed_size_stream_readable_buffer_adapter.d.ts +52 -0
  143. package/esm/serialization/streams/fixed_size_stream_readable_buffer_adapter.js +129 -0
  144. package/esm/serialization/streams/forward_only_stream_readable_buffer_adapter.d.ts +36 -0
  145. package/esm/serialization/streams/forward_only_stream_readable_buffer_adapter.js +114 -0
  146. package/esm/serialization/streams/stream_readable_buffer.d.ts +41 -0
  147. package/esm/serialization/streams/stream_readable_buffer.js +64 -0
  148. package/esm/serialization/streams/stream_readable_buffer_adapter.d.ts +38 -0
  149. package/esm/serialization/streams/stream_readable_buffer_adapter.js +105 -0
  150. package/esm/serialization/streams/stream_writable_buffer.d.ts +42 -0
  151. package/esm/serialization/streams/stream_writable_buffer.js +64 -0
  152. package/esm/serialization/streams/stream_writable_buffer_adapter.d.ts +36 -0
  153. package/esm/serialization/streams/stream_writable_buffer_adapter.js +65 -0
  154. package/esm/serialization/streams/streams.d.ts +29 -0
  155. package/esm/serialization/streams/streams.js +1 -0
  156. package/esm/serialization/tap.d.ts +427 -0
  157. package/esm/serialization/tap.js +605 -0
  158. package/esm/serialization/text_encoding.d.ts +12 -0
  159. package/esm/serialization/text_encoding.js +14 -0
  160. package/esm/type/create_type.d.ts +54 -0
  161. package/esm/type/create_type.js +401 -0
  162. package/package.json +33 -0
  163. package/sachitv-avro-typescript-0.4.0.tgz +0 -0
@@ -0,0 +1,116 @@
1
+ import { BaseType } from "../base_type.js";
2
+ import { Resolver } from "../resolver.js";
3
+ import { type JSONType, Type } from "../type.js";
4
+ import { type ErrorHook } from "../error.js";
5
+ import { type ReadableTapLike, type WritableTapLike } from "../../serialization/tap.js";
6
+ /**
7
+ * Represents a wrapped value for a union type.
8
+ */
9
+ export type UnionWrappedValue = Record<string, unknown>;
10
+ /**
11
+ * Represents a value for a union type, which can be a wrapped value or null.
12
+ */
13
+ export type UnionValue = UnionWrappedValue | null;
14
+ /**
15
+ * Parameters for creating a UnionType.
16
+ */
17
+ export interface UnionTypeParams {
18
+ /** The types that make up the union. */
19
+ types: Type[];
20
+ }
21
+ /**
22
+ * Avro `union` type that supports values conforming to one of multiple schemas.
23
+ */
24
+ export declare class UnionType extends BaseType<UnionValue> {
25
+ #private;
26
+ /**
27
+ * Creates a new UnionType.
28
+ * @param params The union type parameters.
29
+ */
30
+ constructor(params: UnionTypeParams);
31
+ /**
32
+ * Gets the types in this union.
33
+ */
34
+ getTypes(): Type[];
35
+ /**
36
+ * Checks if the given value conforms to this union type.
37
+ * For null values, verifies if a null branch exists.
38
+ * For wrapped values, ensures it's an object with a single key matching a branch name,
39
+ * and validates the inner value against the corresponding branch type.
40
+ * @param value The value to check.
41
+ * @param errorHook Optional error hook for validation errors.
42
+ * @param path The current path for error reporting.
43
+ * @returns True if the value is valid, false otherwise.
44
+ */
45
+ check(value: unknown, errorHook?: ErrorHook, path?: string[]): boolean;
46
+ /**
47
+ * Serializes the union value to the writable tap.
48
+ * Writes the branch index as a long, followed by the branch value if not null.
49
+ * @param tap The writable tap to write to.
50
+ * @param value The union value to serialize.
51
+ */
52
+ write(tap: WritableTapLike, value: UnionValue): Promise<void>;
53
+ /**
54
+ * Deserializes a union value from the readable tap.
55
+ * Reads the branch index, and if not null, reads the branch value and wraps it in an object.
56
+ * @param tap The readable tap to read from.
57
+ * @returns The deserialized union value.
58
+ */
59
+ read(tap: ReadableTapLike): Promise<UnionValue>;
60
+ /**
61
+ * Skips over a union value in the readable tap.
62
+ * Reads the branch index and skips the branch value if not null.
63
+ * @param tap The readable tap to skip in.
64
+ */
65
+ skip(tap: ReadableTapLike): Promise<void>;
66
+ /**
67
+ * Converts the union value to an ArrayBuffer.
68
+ * Calculates the size needed for the index and branch value, then writes them to a new buffer.
69
+ * @param value The union value to convert.
70
+ * @returns The ArrayBuffer containing the serialized value.
71
+ */
72
+ toBuffer(value: UnionValue): Promise<ArrayBuffer>;
73
+ /**
74
+ * Creates a deep clone of the given value as a union value.
75
+ * Handles null values and wrapped objects by cloning the inner value using the branch type.
76
+ * @param value The value to clone.
77
+ * @returns The cloned union value.
78
+ */
79
+ cloneFromValue(value: unknown): UnionValue;
80
+ /**
81
+ * Compares two union values for ordering.
82
+ * First compares by branch index; if equal, compares the branch values using the branch type's compare method.
83
+ * @param val1 The first union value.
84
+ * @param val2 The second union value.
85
+ * @returns Negative if val1 < val2, zero if equal, positive if val1 > val2.
86
+ */
87
+ compare(val1: UnionValue, val2: UnionValue): number;
88
+ /**
89
+ * Generates a random union value.
90
+ * Selects a random branch and generates a random value for that branch, wrapping it appropriately.
91
+ * @returns A random union value.
92
+ */
93
+ random(): UnionValue;
94
+ /**
95
+ * Returns the JSON representation of the union type.
96
+ * An array of the JSON representations of each branch type.
97
+ * @returns The JSON type array.
98
+ */
99
+ toJSON(): JSONType;
100
+ /**
101
+ * Compares two serialized union values from taps for ordering.
102
+ * Reads the branch indices from both taps; if equal, compares the branch values using the branch type's match method.
103
+ * @param tap1 The first readable tap.
104
+ * @param tap2 The second readable tap.
105
+ * @returns Negative if tap1 < tap2, zero if equal, positive if tap1 > tap2.
106
+ */
107
+ match(tap1: ReadableTapLike, tap2: ReadableTapLike): Promise<number>;
108
+ /**
109
+ * Creates a resolver for schema evolution from the writer type to this union type.
110
+ * If the writer is also a union, creates resolvers for each branch.
111
+ * Otherwise, finds a compatible branch in this union and creates a resolver for it.
112
+ * @param writerType The writer type to resolve from.
113
+ * @returns A resolver for the union value.
114
+ */
115
+ createResolver(writerType: Type): Resolver<UnionValue>;
116
+ }
@@ -0,0 +1,392 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _UnionType_instances, _UnionType_types, _UnionType_branches, _UnionType_indices, _UnionType_resolveBranch, _UnionType_readBranchIndex, _UnionBranchResolver_branch, _UnionBranchResolver_branchResolver, _UnionFromUnionResolver_resolvers;
13
+ import { BaseType } from "../base_type.js";
14
+ import { NamedType } from "./named_type.js";
15
+ import { Resolver } from "../resolver.js";
16
+ import { Type } from "../type.js";
17
+ import { throwInvalidError } from "../error.js";
18
+ import { WritableTap, } from "../../serialization/tap.js";
19
+ import { bigIntToSafeNumber } from "../../serialization/conversion.js";
20
+ import { calculateVarintSize } from "../../internal/varint.js";
21
+ function isPlainObject(value) {
22
+ return typeof value === "object" && value !== null &&
23
+ !Array.isArray(value);
24
+ }
25
+ /** @internal */
26
+ /**
27
+ * Gets the branch name for a given type.
28
+ * @param type The type to get the name for.
29
+ * @returns The branch name.
30
+ * @internal
31
+ */
32
+ export function getBranchTypeName(type) {
33
+ if (type instanceof NamedType) {
34
+ return type.getFullName();
35
+ }
36
+ const schema = type.toJSON();
37
+ if (typeof schema === "string") {
38
+ return schema;
39
+ }
40
+ if (schema && typeof schema === "object") {
41
+ const maybeType = schema.type;
42
+ if (typeof maybeType === "string") {
43
+ return maybeType;
44
+ }
45
+ }
46
+ throw new Error("Unable to determine union branch name.");
47
+ }
48
+ /**
49
+ * Avro `union` type that supports values conforming to one of multiple schemas.
50
+ */
51
+ export class UnionType extends BaseType {
52
+ /**
53
+ * Creates a new UnionType.
54
+ * @param params The union type parameters.
55
+ */
56
+ constructor(params) {
57
+ super();
58
+ _UnionType_instances.add(this);
59
+ _UnionType_types.set(this, void 0);
60
+ _UnionType_branches.set(this, void 0);
61
+ _UnionType_indices.set(this, void 0);
62
+ const { types } = params;
63
+ if (!Array.isArray(types)) {
64
+ throw new Error("UnionType requires an array of branch types.");
65
+ }
66
+ if (types.length === 0) {
67
+ throw new Error("UnionType requires at least one branch type.");
68
+ }
69
+ __classPrivateFieldSet(this, _UnionType_types, [], "f");
70
+ __classPrivateFieldSet(this, _UnionType_branches, [], "f");
71
+ __classPrivateFieldSet(this, _UnionType_indices, new Map(), "f");
72
+ types.forEach((type, index) => {
73
+ if (!(type instanceof Type)) {
74
+ throw new Error("UnionType branches must be Avro types.");
75
+ }
76
+ if (type instanceof UnionType) {
77
+ throw new Error("Unions cannot be directly nested.");
78
+ }
79
+ const name = getBranchTypeName(type);
80
+ if (__classPrivateFieldGet(this, _UnionType_indices, "f").has(name)) {
81
+ throw new Error(`Duplicate union branch of type name: ${name}`);
82
+ }
83
+ const branch = {
84
+ type,
85
+ name,
86
+ isNull: name === "null",
87
+ };
88
+ __classPrivateFieldGet(this, _UnionType_types, "f").push(type);
89
+ __classPrivateFieldGet(this, _UnionType_branches, "f").push(branch);
90
+ __classPrivateFieldGet(this, _UnionType_indices, "f").set(name, index);
91
+ });
92
+ }
93
+ /**
94
+ * Gets the types in this union.
95
+ */
96
+ getTypes() {
97
+ return __classPrivateFieldGet(this, _UnionType_types, "f").slice();
98
+ }
99
+ /**
100
+ * Checks if the given value conforms to this union type.
101
+ * For null values, verifies if a null branch exists.
102
+ * For wrapped values, ensures it's an object with a single key matching a branch name,
103
+ * and validates the inner value against the corresponding branch type.
104
+ * @param value The value to check.
105
+ * @param errorHook Optional error hook for validation errors.
106
+ * @param path The current path for error reporting.
107
+ * @returns True if the value is valid, false otherwise.
108
+ */
109
+ check(value, errorHook, path = []) {
110
+ if (value === null) {
111
+ const hasNull = __classPrivateFieldGet(this, _UnionType_indices, "f").has("null");
112
+ if (!hasNull && errorHook) {
113
+ errorHook(path.slice(), value, this);
114
+ }
115
+ return hasNull;
116
+ }
117
+ if (!isPlainObject(value)) {
118
+ if (errorHook) {
119
+ errorHook(path.slice(), value, this);
120
+ }
121
+ return false;
122
+ }
123
+ const keys = Object.keys(value);
124
+ if (keys.length !== 1) {
125
+ if (errorHook) {
126
+ errorHook(path.slice(), value, this);
127
+ }
128
+ return false;
129
+ }
130
+ const key = keys[0];
131
+ // Handle the case where the key itself is "null", this should never validate.
132
+ if (key === "null") {
133
+ if (errorHook) {
134
+ errorHook(path.slice(), value, this);
135
+ }
136
+ return false;
137
+ }
138
+ const branchIndex = __classPrivateFieldGet(this, _UnionType_indices, "f").get(key);
139
+ if (branchIndex === undefined) {
140
+ if (errorHook) {
141
+ errorHook(path.slice(), value, this);
142
+ }
143
+ return false;
144
+ }
145
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[branchIndex];
146
+ const branchValue = value[key];
147
+ const branchPath = errorHook ? [...path, key] : undefined;
148
+ const isValid = branch.type.check(branchValue, errorHook, branchPath);
149
+ if (!isValid && errorHook) {
150
+ // Underlying type already invoked errorHook with extended path.
151
+ return false;
152
+ }
153
+ return isValid;
154
+ }
155
+ /**
156
+ * Serializes the union value to the writable tap.
157
+ * Writes the branch index as a long, followed by the branch value if not null.
158
+ * @param tap The writable tap to write to.
159
+ * @param value The union value to serialize.
160
+ */
161
+ async write(tap, value) {
162
+ const { index, branchValue } = __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_resolveBranch).call(this, value);
163
+ await tap.writeLong(BigInt(index));
164
+ if (branchValue !== undefined) {
165
+ await __classPrivateFieldGet(this, _UnionType_branches, "f")[index].type.write(tap, branchValue);
166
+ }
167
+ }
168
+ /**
169
+ * Deserializes a union value from the readable tap.
170
+ * Reads the branch index, and if not null, reads the branch value and wraps it in an object.
171
+ * @param tap The readable tap to read from.
172
+ * @returns The deserialized union value.
173
+ */
174
+ async read(tap) {
175
+ const index = await __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_readBranchIndex).call(this, tap);
176
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[index];
177
+ if (branch.isNull) {
178
+ return null;
179
+ }
180
+ const branchValue = await branch.type.read(tap);
181
+ return { [branch.name]: branchValue };
182
+ }
183
+ /**
184
+ * Skips over a union value in the readable tap.
185
+ * Reads the branch index and skips the branch value if not null.
186
+ * @param tap The readable tap to skip in.
187
+ */
188
+ async skip(tap) {
189
+ const index = await __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_readBranchIndex).call(this, tap);
190
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[index];
191
+ if (!branch.isNull) {
192
+ await branch.type.skip(tap);
193
+ }
194
+ }
195
+ /**
196
+ * Converts the union value to an ArrayBuffer.
197
+ * Calculates the size needed for the index and branch value, then writes them to a new buffer.
198
+ * @param value The union value to convert.
199
+ * @returns The ArrayBuffer containing the serialized value.
200
+ */
201
+ async toBuffer(value) {
202
+ const { index, branchValue } = __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_resolveBranch).call(this, value);
203
+ const indexSize = calculateVarintSize(index);
204
+ let totalSize = indexSize;
205
+ let branchBytes;
206
+ if (branchValue !== undefined) {
207
+ branchBytes = new Uint8Array(await __classPrivateFieldGet(this, _UnionType_branches, "f")[index].type.toBuffer(branchValue));
208
+ totalSize += branchBytes.byteLength;
209
+ }
210
+ const buffer = new ArrayBuffer(totalSize);
211
+ const tap = new WritableTap(buffer);
212
+ await tap.writeLong(BigInt(index));
213
+ if (branchBytes) {
214
+ await tap.writeFixed(branchBytes);
215
+ }
216
+ return buffer;
217
+ }
218
+ /**
219
+ * Creates a deep clone of the given value as a union value.
220
+ * Handles null values and wrapped objects by cloning the inner value using the branch type.
221
+ * @param value The value to clone.
222
+ * @returns The cloned union value.
223
+ */
224
+ cloneFromValue(value) {
225
+ if (value === null) {
226
+ if (!__classPrivateFieldGet(this, _UnionType_indices, "f").has("null")) {
227
+ throw new Error("Cannot clone null for a union without null branch.");
228
+ }
229
+ return null;
230
+ }
231
+ const { index, branchValue } = __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_resolveBranch).call(this, value);
232
+ if (branchValue === undefined) {
233
+ return null;
234
+ }
235
+ const cloned = __classPrivateFieldGet(this, _UnionType_branches, "f")[index].type.cloneFromValue(branchValue);
236
+ return { [__classPrivateFieldGet(this, _UnionType_branches, "f")[index].name]: cloned };
237
+ }
238
+ /**
239
+ * Compares two union values for ordering.
240
+ * First compares by branch index; if equal, compares the branch values using the branch type's compare method.
241
+ * @param val1 The first union value.
242
+ * @param val2 The second union value.
243
+ * @returns Negative if val1 < val2, zero if equal, positive if val1 > val2.
244
+ */
245
+ compare(val1, val2) {
246
+ const branch1 = __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_resolveBranch).call(this, val1);
247
+ const branch2 = __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_resolveBranch).call(this, val2);
248
+ if (branch1.index === branch2.index) {
249
+ if (branch1.branchValue === undefined) {
250
+ return 0;
251
+ }
252
+ return __classPrivateFieldGet(this, _UnionType_branches, "f")[branch1.index].type.compare(branch1.branchValue, branch2.branchValue);
253
+ }
254
+ return branch1.index < branch2.index ? -1 : 1;
255
+ }
256
+ /**
257
+ * Generates a random union value.
258
+ * Selects a random branch and generates a random value for that branch, wrapping it appropriately.
259
+ * @returns A random union value.
260
+ */
261
+ random() {
262
+ const index = Math.floor(Math.random() * __classPrivateFieldGet(this, _UnionType_branches, "f").length);
263
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[index];
264
+ if (branch.isNull) {
265
+ return null;
266
+ }
267
+ const value = branch.type.random();
268
+ return { [branch.name]: value };
269
+ }
270
+ /**
271
+ * Returns the JSON representation of the union type.
272
+ * An array of the JSON representations of each branch type.
273
+ * @returns The JSON type array.
274
+ */
275
+ toJSON() {
276
+ return __classPrivateFieldGet(this, _UnionType_types, "f").map((type) => type.toJSON());
277
+ }
278
+ /**
279
+ * Compares two serialized union values from taps for ordering.
280
+ * Reads the branch indices from both taps; if equal, compares the branch values using the branch type's match method.
281
+ * @param tap1 The first readable tap.
282
+ * @param tap2 The second readable tap.
283
+ * @returns Negative if tap1 < tap2, zero if equal, positive if tap1 > tap2.
284
+ */
285
+ async match(tap1, tap2) {
286
+ const idx1 = await __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_readBranchIndex).call(this, tap1);
287
+ const idx2 = await __classPrivateFieldGet(this, _UnionType_instances, "m", _UnionType_readBranchIndex).call(this, tap2);
288
+ if (idx1 === idx2) {
289
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[idx1];
290
+ if (branch.isNull) {
291
+ return 0;
292
+ }
293
+ return await branch.type.match(tap1, tap2);
294
+ }
295
+ return idx1 < idx2 ? -1 : 1;
296
+ }
297
+ /**
298
+ * Creates a resolver for schema evolution from the writer type to this union type.
299
+ * If the writer is also a union, creates resolvers for each branch.
300
+ * Otherwise, finds a compatible branch in this union and creates a resolver for it.
301
+ * @param writerType The writer type to resolve from.
302
+ * @returns A resolver for the union value.
303
+ */
304
+ createResolver(writerType) {
305
+ if (writerType instanceof UnionType) {
306
+ const branchResolvers = writerType.getTypes().map((branch) => this.createResolver(branch));
307
+ return new UnionFromUnionResolver(this, branchResolvers);
308
+ }
309
+ for (let i = 0; i < __classPrivateFieldGet(this, _UnionType_branches, "f").length; i++) {
310
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[i];
311
+ try {
312
+ const resolver = branch.type.createResolver(writerType);
313
+ return new UnionBranchResolver(this, branch, resolver);
314
+ }
315
+ catch {
316
+ // Continue searching for compatible branch.
317
+ }
318
+ }
319
+ return super.createResolver(writerType);
320
+ }
321
+ }
322
+ _UnionType_types = new WeakMap(), _UnionType_branches = new WeakMap(), _UnionType_indices = new WeakMap(), _UnionType_instances = new WeakSet(), _UnionType_resolveBranch = function _UnionType_resolveBranch(value) {
323
+ if (value === null) {
324
+ const index = __classPrivateFieldGet(this, _UnionType_indices, "f").get("null");
325
+ if (index === undefined) {
326
+ throwInvalidError([], value, this);
327
+ }
328
+ return { index, branchValue: undefined };
329
+ }
330
+ if (!isPlainObject(value)) {
331
+ throwInvalidError([], value, this);
332
+ }
333
+ const keys = Object.keys(value);
334
+ if (keys.length !== 1) {
335
+ throwInvalidError([], value, this);
336
+ }
337
+ const key = keys[0];
338
+ const branchIndex = __classPrivateFieldGet(this, _UnionType_indices, "f").get(key);
339
+ if (branchIndex === undefined) {
340
+ throwInvalidError([], value, this);
341
+ }
342
+ const branch = __classPrivateFieldGet(this, _UnionType_branches, "f")[branchIndex];
343
+ const branchValue = value[key];
344
+ if (!branch.isNull && branchValue === undefined) {
345
+ throwInvalidError([], value, this);
346
+ }
347
+ if (branch.isNull && branchValue !== undefined) {
348
+ throwInvalidError([], value, this);
349
+ }
350
+ return { index: branchIndex, branchValue };
351
+ }, _UnionType_readBranchIndex = async function _UnionType_readBranchIndex(tap) {
352
+ const indexBigInt = await tap.readLong();
353
+ const index = bigIntToSafeNumber(indexBigInt, "Union branch index");
354
+ if (index < 0 || index >= __classPrivateFieldGet(this, _UnionType_branches, "f").length) {
355
+ throw new Error(`Invalid union index: ${index}`);
356
+ }
357
+ return index;
358
+ };
359
+ class UnionBranchResolver extends Resolver {
360
+ constructor(reader, branch, branchResolver) {
361
+ super(reader);
362
+ _UnionBranchResolver_branch.set(this, void 0);
363
+ _UnionBranchResolver_branchResolver.set(this, void 0);
364
+ __classPrivateFieldSet(this, _UnionBranchResolver_branch, branch, "f");
365
+ __classPrivateFieldSet(this, _UnionBranchResolver_branchResolver, branchResolver, "f");
366
+ }
367
+ async read(tap) {
368
+ const resolvedValue = await __classPrivateFieldGet(this, _UnionBranchResolver_branchResolver, "f").read(tap);
369
+ if (__classPrivateFieldGet(this, _UnionBranchResolver_branch, "f").isNull) {
370
+ return null;
371
+ }
372
+ return { [__classPrivateFieldGet(this, _UnionBranchResolver_branch, "f").name]: resolvedValue };
373
+ }
374
+ }
375
+ _UnionBranchResolver_branch = new WeakMap(), _UnionBranchResolver_branchResolver = new WeakMap();
376
+ class UnionFromUnionResolver extends Resolver {
377
+ constructor(reader, resolvers) {
378
+ super(reader);
379
+ _UnionFromUnionResolver_resolvers.set(this, void 0);
380
+ __classPrivateFieldSet(this, _UnionFromUnionResolver_resolvers, resolvers, "f");
381
+ }
382
+ async read(tap) {
383
+ const indexBigInt = await tap.readLong();
384
+ const index = bigIntToSafeNumber(indexBigInt, "Union branch index");
385
+ const resolver = __classPrivateFieldGet(this, _UnionFromUnionResolver_resolvers, "f")[index];
386
+ if (!resolver) {
387
+ throw new Error(`Invalid union index: ${index}`);
388
+ }
389
+ return await resolver.read(tap);
390
+ }
391
+ }
392
+ _UnionFromUnionResolver_resolvers = new WeakMap();
@@ -0,0 +1,31 @@
1
+ import type { Type } from "./type.js";
2
+ /**
3
+ * Hook function for handling validation errors.
4
+ */
5
+ export type ErrorHook<T = unknown> = (path: string[], invalidValue: unknown, schemaType: Type<T>) => void;
6
+ /**
7
+ * Custom error class for Avro schema validation failures.
8
+ */
9
+ export declare class ValidationError<T = unknown> extends Error {
10
+ /** The path to the invalid value within the schema/data. */
11
+ readonly path: string[];
12
+ /** The value that failed validation. */
13
+ readonly value: unknown;
14
+ /** The schema type that rejected the value. */
15
+ readonly type: Type<T>;
16
+ /**
17
+ * Creates a new ValidationError.
18
+ * @param path The path to the invalid value.
19
+ * @param invalidValue The invalid value.
20
+ * @param schemaType The schema type.
21
+ */
22
+ constructor(path: string[], invalidValue: unknown, schemaType: Type<T>);
23
+ }
24
+ /**
25
+ * Throws a ValidationError for invalid values.
26
+ */
27
+ export declare function throwInvalidError<T = unknown>(path: string[], invalidValue: unknown, schemaType: Type<T>): never;
28
+ /**
29
+ * Renders a path array as a formatted tree string.
30
+ */
31
+ export declare function renderPathAsTree(path: string[]): string;
@@ -0,0 +1,67 @@
1
+ import { safeStringify } from "./json.js";
2
+ /**
3
+ * Custom error class for Avro schema validation failures.
4
+ */
5
+ export class ValidationError extends Error {
6
+ /**
7
+ * Creates a new ValidationError.
8
+ * @param path The path to the invalid value.
9
+ * @param invalidValue The invalid value.
10
+ * @param schemaType The schema type.
11
+ */
12
+ constructor(path, invalidValue, schemaType) {
13
+ const serializedValue = safeStringify(invalidValue);
14
+ const serializedJSON = safeStringify(schemaType.toJSON());
15
+ let message = `Invalid value: \'${serializedValue}\' for type: ${serializedJSON}`;
16
+ if (path.length > 0) {
17
+ message += ` at path: ${renderPathAsTree(path)}`;
18
+ }
19
+ super(message);
20
+ /** The path to the invalid value within the schema/data. */
21
+ Object.defineProperty(this, "path", {
22
+ enumerable: true,
23
+ configurable: true,
24
+ writable: true,
25
+ value: void 0
26
+ });
27
+ /** The value that failed validation. */
28
+ Object.defineProperty(this, "value", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ /** The schema type that rejected the value. */
35
+ Object.defineProperty(this, "type", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: void 0
40
+ });
41
+ this.name = "ValidationError";
42
+ this.path = path;
43
+ this.value = invalidValue;
44
+ this.type = schemaType;
45
+ }
46
+ }
47
+ /**
48
+ * Throws a ValidationError for invalid values.
49
+ */
50
+ export function throwInvalidError(path, invalidValue, schemaType) {
51
+ throw new ValidationError(path, invalidValue, schemaType);
52
+ }
53
+ /**
54
+ * Renders a path array as a formatted tree string.
55
+ */
56
+ export function renderPathAsTree(path) {
57
+ if (path.length === 0)
58
+ return "";
59
+ let result = path[0];
60
+ for (let i = 1; i < path.length; i++) {
61
+ result += "\n" + " ".repeat(i) + path[i];
62
+ }
63
+ if (path.length > 1) {
64
+ result = "\n" + result;
65
+ }
66
+ return result;
67
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Safely stringifies a value to JSON, handling BigInts and circular references.
3
+ * @param value The value to stringify.
4
+ * @returns The string representation.
5
+ */
6
+ export declare function safeStringify(value: unknown): string;
@@ -0,0 +1,35 @@
1
+ /** @internal */
2
+ export function _safeJSONStringify(obj, indent = 2) {
3
+ const cache = [];
4
+ const retVal = JSON.stringify(obj, (_key, value) => {
5
+ if (typeof value === "bigint")
6
+ return String(value);
7
+ if (typeof value === "object" && value !== null) {
8
+ if (cache.includes(value))
9
+ return "[Circular]";
10
+ cache.push(value);
11
+ }
12
+ return value;
13
+ }, indent);
14
+ cache.length = 0;
15
+ return retVal;
16
+ }
17
+ /**
18
+ * Safely stringifies a value to JSON, handling BigInts and circular references.
19
+ * @param value The value to stringify.
20
+ * @returns The string representation.
21
+ */
22
+ export function safeStringify(value) {
23
+ // Converts supported primitive values and complex objects into stable JSON
24
+ // while handling circular references and bigint values.
25
+ if (typeof value === "string" || typeof value === "bigint" ||
26
+ typeof value === "number" || typeof value === "boolean" || value === null ||
27
+ typeof value === "undefined") {
28
+ return String(value);
29
+ }
30
+ const jsonStr = _safeJSONStringify(value);
31
+ if (jsonStr === undefined) {
32
+ return String(value);
33
+ }
34
+ return `\n${jsonStr}\n`;
35
+ }