@azure/schema-registry-json 1.0.1-alpha.20250620.1 → 1.0.1-alpha.20250722.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.
@@ -34,12 +34,15 @@ export class JsonSchemaSerializer {
34
34
  * Usually this is a SchemaRegistryClient instance.
35
35
  */
36
36
  constructor(client, options) {
37
- this.cacheIdByDefinition = new LRUCache(cacheOptions);
38
- this.cacheById = new LRUCache(cacheOptions);
39
37
  this.registry = client;
40
- this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
41
- this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
38
+ this.schemaGroup = options?.groupName;
39
+ this.messageAdapter = options?.messageAdapter;
42
40
  }
41
+ schemaGroup;
42
+ registry;
43
+ messageAdapter;
44
+ cacheIdByDefinition = new LRUCache(cacheOptions);
45
+ cacheById = new LRUCache(cacheOptions);
43
46
  /**
44
47
  * serializes the value parameter according to the input schema and creates a message
45
48
  * with the serialized data.
@@ -84,7 +87,7 @@ export class JsonSchemaSerializer {
84
87
  const schemaId = getSchemaId(contentType);
85
88
  const schema = await this.getSchemaById(schemaId);
86
89
  const returnedMessage = wrapError(() => JSON.parse(decoder.decode(data)), `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`);
87
- const validate = options === null || options === void 0 ? void 0 : options.validateCallback;
90
+ const validate = options?.validateCallback;
88
91
  if (validate) {
89
92
  wrapError(() => validate(returnedMessage, schema), `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`);
90
93
  }
@@ -152,7 +155,7 @@ function getSchemaId(contentType) {
152
155
  return contentTypeParts[1];
153
156
  }
154
157
  function convertMessage(message, adapter) {
155
- const messageConsumer = adapter === null || adapter === void 0 ? void 0 : adapter.consume;
158
+ const messageConsumer = adapter?.consume;
156
159
  if (messageConsumer) {
157
160
  return messageConsumer(message);
158
161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":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AAC,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;IAC1F,CAAC;IACD,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,4BAA4B,gBAAgB,CAAC,CAAC,CAAC,mEAAmE,YAAY,QAAQ,CACvI,CAAC;IACJ,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
1
+ {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,gBAA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CACb,4BAA4B,gBAAgB,CAAC,CAAC,CAAC,mEAAmE,YAAY,QAAQ,CACvI,CAAC;IACJ,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,EAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
@@ -37,12 +37,15 @@ class JsonSchemaSerializer {
37
37
  * Usually this is a SchemaRegistryClient instance.
38
38
  */
39
39
  constructor(client, options) {
40
- this.cacheIdByDefinition = new lru_cache_1.LRUCache(cacheOptions);
41
- this.cacheById = new lru_cache_1.LRUCache(cacheOptions);
42
40
  this.registry = client;
43
- this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
44
- this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
41
+ this.schemaGroup = options?.groupName;
42
+ this.messageAdapter = options?.messageAdapter;
45
43
  }
44
+ schemaGroup;
45
+ registry;
46
+ messageAdapter;
47
+ cacheIdByDefinition = new lru_cache_1.LRUCache(cacheOptions);
48
+ cacheById = new lru_cache_1.LRUCache(cacheOptions);
46
49
  /**
47
50
  * serializes the value parameter according to the input schema and creates a message
48
51
  * with the serialized data.
@@ -87,7 +90,7 @@ class JsonSchemaSerializer {
87
90
  const schemaId = getSchemaId(contentType);
88
91
  const schema = await this.getSchemaById(schemaId);
89
92
  const returnedMessage = (0, errors_js_1.wrapError)(() => JSON.parse(decoder.decode(data)), `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`);
90
- const validate = options === null || options === void 0 ? void 0 : options.validateCallback;
93
+ const validate = options?.validateCallback;
91
94
  if (validate) {
92
95
  (0, errors_js_1.wrapError)(() => validate(returnedMessage, schema), `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`);
93
96
  }
@@ -156,7 +159,7 @@ function getSchemaId(contentType) {
156
159
  return contentTypeParts[1];
157
160
  }
158
161
  function convertMessage(message, adapter) {
159
- const messageConsumer = adapter === null || adapter === void 0 ? void 0 : adapter.consume;
162
+ const messageConsumer = adapter?.consume;
160
163
  if (messageConsumer) {
161
164
  return messageConsumer(message);
162
165
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AASlC,4DAA4D;AAC5D,6CAAgD;AAChD,2CAAwD;AACxD,yCAAqC;AAErC,2CAAqC;AAErC,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAalC,SAAS,eAAe,CAAC,MAAc;IACrC,OAAO,IAAA,qBAAS,EACd,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EACxB,oCAAoC,MAAM,mCAAmC,CAC9E,CAAC;AACJ,CAAC;AAED,MA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AAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
1
+ {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AASlC,4DAA4D;AAC5D,6CAAgD;AAChD,2CAAwD;AACxD,yCAAqC;AAErC,2CAAqC;AAErC,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAalC,SAAS,eAAe,CAAC,MAAc;IACrC,OAAO,IAAA,qBAAS,EACd,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EACxB,oCAAoC,MAAM,mCAAmC,CAC9E,CAAC;AACJ,CAAC;AAED,MAAM,YAAY,GAA0C;IAC1D,GAAG,EAAE,GAAG;IACR;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC,SAAS;IACzB,eAAe,EAAE,CAAC,MAAW,EAAE,GAAW,EAAE,EAAE;QAC5C,OAAO,GAAG,CAAC,MAAM,CAAC;IACpB,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,MAAa,oBAAoB;IAC/B;;;;;OAKG;IACH,YAAY,MAAsB,EAAE,O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C","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
@@ -1,11 +1,11 @@
1
- // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
- // It should be published with your NPM package. It should not be tracked by Git.
3
- {
4
- "tsdocVersion": "0.12",
5
- "toolPackages": [
6
- {
7
- "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.52.8"
9
- }
10
- ]
11
- }
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.52.8"
9
+ }
10
+ ]
11
+ }
@@ -34,12 +34,15 @@ export class JsonSchemaSerializer {
34
34
  * Usually this is a SchemaRegistryClient instance.
35
35
  */
36
36
  constructor(client, options) {
37
- this.cacheIdByDefinition = new LRUCache(cacheOptions);
38
- this.cacheById = new LRUCache(cacheOptions);
39
37
  this.registry = client;
40
- this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
41
- this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
38
+ this.schemaGroup = options?.groupName;
39
+ this.messageAdapter = options?.messageAdapter;
42
40
  }
41
+ schemaGroup;
42
+ registry;
43
+ messageAdapter;
44
+ cacheIdByDefinition = new LRUCache(cacheOptions);
45
+ cacheById = new LRUCache(cacheOptions);
43
46
  /**
44
47
  * serializes the value parameter according to the input schema and creates a message
45
48
  * with the serialized data.
@@ -84,7 +87,7 @@ export class JsonSchemaSerializer {
84
87
  const schemaId = getSchemaId(contentType);
85
88
  const schema = await this.getSchemaById(schemaId);
86
89
  const returnedMessage = wrapError(() => JSON.parse(decoder.decode(data)), `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`);
87
- const validate = options === null || options === void 0 ? void 0 : options.validateCallback;
90
+ const validate = options?.validateCallback;
88
91
  if (validate) {
89
92
  wrapError(() => validate(returnedMessage, schema), `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`);
90
93
  }
@@ -152,7 +155,7 @@ function getSchemaId(contentType) {
152
155
  return contentTypeParts[1];
153
156
  }
154
157
  function convertMessage(message, adapter) {
155
- const messageConsumer = adapter === null || adapter === void 0 ? void 0 : adapter.consume;
158
+ const messageConsumer = adapter?.consume;
156
159
  if (messageConsumer) {
157
160
  return messageConsumer(message);
158
161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAalC,SAAS,eAAe,CAAC,MAAc;IACrC,OAAO,SAAS,CACd,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EACxB,oCAAoC,MAAM,mCAAmC,CAC9E,CAAC;AACJ,CAAC;AAED,MAAM,YAAY,GAA0C;IAC1D,GAAG,EAAE,GAAG;IACR;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC,SAAS;IACzB,eAAe,EAAE,CAAC,MAAW,EAAE,GAAW,EAAE,EAAE;QAC5C,OAAO,GAAG,CAAC,MAAM,CAAC;IACpB,CAAC;CACF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AAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
1
+ {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAalC,SAAS,eAAe,CAAC,MAAc;IACrC,OAAO,SAAS,CACd,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,EACxB,oCAAoC,MAAM,mCAAmC,CAC9E,CAAC;AACJ,CAAC;AAED,MAAM,YAAY,GAA0C;IAC1D,GAAG,EAAE,GAAG;IACR;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC,SAAS;IACzB,eAAe,EAAE,CAAC,MAAW,EAAE,GAAW,EAAE,EAAE;QAC5C,OAAO,GAAG,CAAC,MAAM,CAAC;IACpB,CAAC;CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,OAAO,oBAAoB;IAC/B;;;;;OAKG;IACH,YAAY,MAAsB,EAAE,OAA+C;QACjF,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC;QACvB,IAAI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,IAAI,CAAC,mBAAmB,CAAC,cAAc,EAAE,CAC1J,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,SAAS,WAAW,CAAC,WAAmB;IACtC,MAAM,gBAAgB,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAChD,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;IAC1F,CAAC;IACD,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,4BAA4B,gBAAgB,CAAC,CAAC,CAAC,mEAAmE,YAAY,QAAQ,CACvI,CAAC;IACJ,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,EAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
@@ -34,12 +34,15 @@ export class JsonSchemaSerializer {
34
34
  * Usually this is a SchemaRegistryClient instance.
35
35
  */
36
36
  constructor(client, options) {
37
- this.cacheIdByDefinition = new LRUCache(cacheOptions);
38
- this.cacheById = new LRUCache(cacheOptions);
39
37
  this.registry = client;
40
- this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
41
- this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
38
+ this.schemaGroup = options?.groupName;
39
+ this.messageAdapter = options?.messageAdapter;
42
40
  }
41
+ schemaGroup;
42
+ registry;
43
+ messageAdapter;
44
+ cacheIdByDefinition = new LRUCache(cacheOptions);
45
+ cacheById = new LRUCache(cacheOptions);
43
46
  /**
44
47
  * serializes the value parameter according to the input schema and creates a message
45
48
  * with the serialized data.
@@ -84,7 +87,7 @@ export class JsonSchemaSerializer {
84
87
  const schemaId = getSchemaId(contentType);
85
88
  const schema = await this.getSchemaById(schemaId);
86
89
  const returnedMessage = wrapError(() => JSON.parse(decoder.decode(data)), `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`);
87
- const validate = options === null || options === void 0 ? void 0 : options.validateCallback;
90
+ const validate = options?.validateCallback;
88
91
  if (validate) {
89
92
  wrapError(() => validate(returnedMessage, schema), `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`);
90
93
  }
@@ -152,7 +155,7 @@ function getSchemaId(contentType) {
152
155
  return contentTypeParts[1];
153
156
  }
154
157
  function convertMessage(message, adapter) {
155
- const messageConsumer = adapter === null || adapter === void 0 ? void 0 : adapter.consume;
158
+ const messageConsumer = adapter?.consume;
156
159
  if (messageConsumer) {
157
160
  return messageConsumer(message);
158
161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;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AY,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,4BAA4B,gBAAgB,CAAC,CAAC,CAAC,mEAAmE,YAAY,QAAQ,CACvI,CAAC;IACJ,CAAC;IACD,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
1
+ {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,W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C;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC;IAElC,MAAM,eAAe,GAAG,OAAO,EAAE,OAAO,CAAC;IACzC,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,OAAO,OAAO,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport type {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models.js\";\nimport type { SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { KnownSchemaFormats } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility.js\";\nimport { errorWithCause, wrapError } from \"./errors.js\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger.js\";\n\nconst jsonMimeType = \"application/json\";\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\ninterface CacheEntry {\n /** Schema ID */\n id: string;\n /** Schema string */\n schema: string;\n}\ninterface SchemaObject {\n id?: string;\n $id?: string;\n $schema?: string;\n}\nfunction getSchemaObject(schema: string): SchemaObject {\n return wrapError(\n () => JSON.parse(schema),\n `Parsing Json schema failed:\\n\\n\\t${schema}\\n\\nSee 'cause' for more details.`,\n );\n}\n\nconst cacheOptions: LRUCacheOptions<string, any, unknown> = {\n max: 128,\n /**\n * This is needed in order to specify `sizeCalculation` but we do not intend\n * to limit the size just yet.\n */\n maxSize: Number.MAX_VALUE,\n sizeCalculation: (_value: any, key: string) => {\n return key.length;\n },\n};\n\n/**\n * Json serializer that obtains schemas from a schema registry and does not\n * pack schemas into its payloads.\n */\nexport class JsonSchemaSerializer<MessageT = MessageContent> {\n /**\n * Creates a new serializer.\n *\n * @param client - Schema Registry where schemas are registered and obtained.\n * Usually this is a SchemaRegistryClient instance.\n */\n constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>) {\n this.registry = client;\n this.schemaGroup = options?.groupName;\n this.messageAdapter = options?.messageAdapter;\n }\n\n private readonly schemaGroup?: string;\n private readonly registry: SchemaRegistry;\n private readonly messageAdapter?: MessageAdapter<MessageT>;\n private readonly cacheIdByDefinition = new LRUCache<string, string>(cacheOptions);\n private readonly cacheById = new LRUCache<string, string>(cacheOptions);\n\n /**\n * serializes the value parameter according to the input schema and creates a message\n * with the serialized data.\n *\n * @param value - The value to serialize.\n * @param schema - The Json schema to use.\n * @returns A new message with the serialized value. The structure of message is\n * constrolled by the message factory option.\n * @throws {@link Error}\n * Thrown if the schema can not be parsed or the value does not match the schema.\n */\n async serialize(value: unknown, schema: string): Promise<MessageT> {\n const entry = await this.getSchemaByDefinition(schema);\n const data = wrapError(\n () => encoder.encode(JSON.stringify(value)),\n `Json serialization failed. See 'cause' for more details. Schema ID: ${entry.id}`,\n );\n const contentType = `${jsonMimeType}+${entry.id}`;\n return this.messageAdapter\n ? this.messageAdapter.produce({\n contentType,\n data,\n })\n : /**\n * If no message consumer was provided, then a MessageContent will be\n * returned. This should work because the MessageT type parameter defaults\n * to MessageContent.\n */\n ({\n data,\n contentType,\n } as MessageContent as unknown as MessageT);\n }\n\n /**\n * Deserializes the payload of the message using the schema ID in the content type\n * field if no schema was provided.\n *\n * @param message - The message with the payload to be deserialized.\n * @returns The deserialized value.\n * @throws {@link Error}\n * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.\n */\n async deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T> {\n const { data, contentType } = convertMessage(message, this.messageAdapter);\n const schemaId = getSchemaId(contentType);\n const schema = await this.getSchemaById(schemaId);\n const returnedMessage = wrapError(\n () => JSON.parse(decoder.decode(data)),\n `Json deserialization failed with schema ID (${schemaId}). See 'cause' for more details.`,\n );\n const validate = options?.validateCallback;\n if (validate) {\n wrapError(\n () => validate(returnedMessage, schema),\n `Json validation failed. See 'cause' for more details. Schema ID: ${schemaId}`,\n );\n }\n return returnedMessage as T;\n }\n\n private async getSchemaById(schemaId: string): Promise<string> {\n const cached = this.cacheById.get(schemaId);\n if (cached) {\n return cached;\n }\n const schemaResponse = await this.registry.getSchema(schemaId);\n if (!schemaResponse) {\n throw new Error(`Schema with ID '${schemaId}' not found.`);\n }\n\n if (!schemaResponse.properties.format.match(/^json$/i)) {\n throw new Error(\n `Schema with ID '${schemaResponse.properties.id}' has format '${schemaResponse.properties.format}', not 'json'.`,\n );\n }\n return this.cache(schemaResponse.definition, schemaId).schema;\n }\n\n private async getSchemaByDefinition(definition: string): Promise<CacheEntry> {\n const schemaId = this.cacheIdByDefinition.get(definition);\n if (schemaId) {\n return { id: schemaId, schema: definition };\n }\n if (!this.schemaGroup) {\n throw new Error(\n \"Schema group must have been specified in the constructor options when the client was created in order to serialize.\",\n );\n }\n const schemaObj = getSchemaObject(definition);\n const description: SchemaDescription = {\n groupName: this.schemaGroup,\n name: getSchemaName(schemaObj),\n format: KnownSchemaFormats.Json,\n definition,\n };\n let id: string;\n\n try {\n id = (await this.registry.getSchemaProperties(description)).id;\n } catch (e) {\n if ((e as any).statusCode === 404) {\n throw errorWithCause(\n `Schema '${description.name}' not found in registry group '${description.groupName}', or not found to have matching definition.`,\n e as Error,\n );\n } else {\n throw e;\n }\n }\n\n return this.cache(definition, id);\n }\n\n private cache(schema: string, id: string): CacheEntry {\n const entry = { schema, id };\n this.cacheIdByDefinition.set(schema, id);\n this.cacheById.set(id, schema);\n logger.verbose(\n `Cache entry added or updated. Total number of entries: ${this.cacheIdByDefinition.size}; Total schema length ${this.cacheIdByDefinition.calculatedSize}`,\n );\n return entry;\n }\n}\n\nfunction getSchemaId(contentType: string): string {\n const contentTypeParts = contentType.split(\"+\");\n if (contentTypeParts.length !== 2) {\n throw new Error(\"Content type was not in the expected format of MIME type + schema ID\");\n }\n if (contentTypeParts[0] !== jsonMimeType) {\n throw new Error(\n `Received content of type ${contentTypeParts[0]} but an json serializer may only be used on content that is of '${jsonMimeType}' type`,\n );\n }\n return contentTypeParts[1];\n}\n\nfunction convertMessage<MessageT>(\n message: MessageT,\n adapter?: MessageAdapter<MessageT>,\n): MessageContent {\n const messageConsumer = adapter?.consume;\n if (messageConsumer) {\n return messageConsumer(message);\n } else if (isMessageContent(message)) {\n return message;\n } else {\n throw new Error(\n `Expected either a message adapter to be provided to the serializer or the input message to have data and contentType fields`,\n );\n }\n}\n\nfunction getSchemaName(schema: SchemaObject): string {\n const id = schema.$id || schema.id;\n if (!id) {\n throw new Error(\"Schema must have an ID.\");\n }\n return id;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azure/schema-registry-json",
3
- "version": "1.0.1-alpha.20250620.1",
3
+ "version": "1.0.1-alpha.20250722.1",
4
4
  "description": "Schema Registry JSON Serializer Library with typescript type definitions for node.js and browser.",
5
5
  "sdk-type": "client",
6
6
  "main": "./dist/commonjs/index.js",
@@ -59,7 +59,7 @@
59
59
  "dependencies": {
60
60
  "@azure/logger": "^1.1.4",
61
61
  "@azure/schema-registry": "^1.3.0",
62
- "lru-cache": "^10.2.0",
62
+ "lru-cache": "^11.1.0",
63
63
  "tslib": "^2.8.1"
64
64
  },
65
65
  "devDependencies": {
@@ -86,7 +86,7 @@
86
86
  },
87
87
  "type": "module",
88
88
  "tshy": {
89
- "project": "./tsconfig.src.json",
89
+ "project": "../../../tsconfig.src.build.json",
90
90
  "exports": {
91
91
  "./package.json": "./package.json",
92
92
  ".": "./src/index.ts"