@azure/schema-registry-json 1.0.0-beta.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,7 @@ npm install @azure/schema-registry-json
31
31
 
32
32
  ## Key concepts
33
33
 
34
- ### JsonSerializer
34
+ ### JsonSchemaSerializer
35
35
 
36
36
  Provides API to serialize to and deserialize from JSON wrapped in a message
37
37
  with a content type field containing the schema ID. Uses
@@ -63,41 +63,48 @@ adapters for their message types.
63
63
  const { DefaultAzureCredential } = require("@azure/identity");
64
64
  const { createEventDataAdapter } = require("@azure/event-hubs");
65
65
  const { SchemaRegistryClient } = require("@azure/schema-registry");
66
- const { JsonSerializer } = require("@azure/schema-registry-json");
67
-
68
- const client = new SchemaRegistryClient(
69
- "<fully qualified namespace>",
70
- new DefaultAzureCredential()
71
- );
72
- const serializer = new JsonSerializer(client, {
73
- groupName: "<group>",
74
- messageAdapter: createEventDataAdapter(),
75
- });
76
-
77
- // Example Json schema
78
- const schema = JSON.stringify({
79
- $schema: "http://json-schema.org/draft-04/schema#",
80
- $id: "person",
81
- title: "Student",
82
- description: "A student in the class",
83
- type: "object",
84
- properties: {
85
- name: {
86
- type: "string",
87
- description: "The name of the student",
66
+ const { JsonSchemaSerializer } = require("@azure/schema-registry-json");
67
+
68
+ async function main(){
69
+ const client = new SchemaRegistryClient(
70
+ "<fully qualified namespace>",
71
+ new DefaultAzureCredential()
72
+ );
73
+ const serializer = new JsonSchemaSerializer(client, {
74
+ groupName: "<group>",
75
+ messageAdapter: createEventDataAdapter(),
76
+ });
77
+
78
+ // Example Json schema
79
+ const schema = JSON.stringify({
80
+ $schema: "http://json-schema.org/draft-04/schema#",
81
+ $id: "person",
82
+ title: "Student",
83
+ description: "A student in the class",
84
+ type: "object",
85
+ properties: {
86
+ name: {
87
+ type: "string",
88
+ description: "The name of the student",
89
+ },
88
90
  },
89
- },
90
- required: ["name"]
91
- });
91
+ required: ["name"]
92
+ });
92
93
 
93
- // Example value that matches the Json schema above
94
- const value = { name: "Bob" };
94
+ // Example value that matches the Json schema above
95
+ const value = { name: "Bob" };
95
96
 
96
- // Serialize value to a message
97
- const message = await serializer.serialize(value, schema);
97
+ // Serialize value to a message
98
+ const message = await serializer.serialize(value, schema);
99
+
100
+ // Deserialize a message to value
101
+ const deserializedValue = await serializer.deserialize(message);
102
+ }
103
+
104
+ main().catch((err) => {
105
+ console.error("The sample encountered an error:", err);
106
+ });
98
107
 
99
- // Deserialize a message to value
100
- const deserializedValue = await serializer.deserialize(message);
101
108
  ```
102
109
 
103
110
  The serializer doesn't check whether the deserialized value matches the schema
package/dist/index.js CHANGED
@@ -3,22 +3,18 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var schemaRegistry = require('@azure/schema-registry');
6
- var LRUCache = require('lru-cache');
6
+ var lruCache = require('lru-cache');
7
7
  var logger$1 = require('@azure/logger');
8
8
 
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var LRUCache__default = /*#__PURE__*/_interopDefaultLegacy(LRUCache);
12
-
13
9
  // Copyright (c) Microsoft Corporation.
14
- // Licensed under the MIT license.
10
+ // Licensed under the MIT License.
15
11
  function isMessageContent(message) {
16
12
  const castMessage = message;
17
13
  return castMessage.data !== undefined && castMessage.contentType !== undefined;
18
14
  }
19
15
 
20
16
  // Copyright (c) Microsoft Corporation.
21
- // Licensed under the MIT license.
17
+ // Licensed under the MIT License.
22
18
  /** @internal */
23
19
  function wrapError(f, message) {
24
20
  let result;
@@ -41,12 +37,14 @@ function errorWithCause(message, cause) {
41
37
  }
42
38
 
43
39
  // Copyright (c) Microsoft Corporation.
40
+ // Licensed under the MIT License.
44
41
  /**
45
42
  * The \@azure/logger configuration for the schema-registry-json package.
46
43
  */
47
44
  const logger = logger$1.createClientLogger("schema-registry-json");
48
45
 
49
46
  // Copyright (c) Microsoft Corporation.
47
+ // Licensed under the MIT License.
50
48
  const jsonMimeType = "application/json";
51
49
  const encoder = new TextEncoder();
52
50
  const decoder = new TextDecoder();
@@ -68,7 +66,7 @@ const cacheOptions = {
68
66
  * Json serializer that obtains schemas from a schema registry and does not
69
67
  * pack schemas into its payloads.
70
68
  */
71
- class JsonSerializer {
69
+ class JsonSchemaSerializer {
72
70
  /**
73
71
  * Creates a new serializer.
74
72
  *
@@ -76,8 +74,8 @@ class JsonSerializer {
76
74
  * Usually this is a SchemaRegistryClient instance.
77
75
  */
78
76
  constructor(client, options) {
79
- this.cacheIdByDefinition = new LRUCache__default["default"](cacheOptions);
80
- this.cacheById = new LRUCache__default["default"](cacheOptions);
77
+ this.cacheIdByDefinition = new lruCache.LRUCache(cacheOptions);
78
+ this.cacheById = new lruCache.LRUCache(cacheOptions);
81
79
  this.registry = client;
82
80
  this.schemaGroup = options === null || options === void 0 ? void 0 : options.groupName;
83
81
  this.messageAdapter = options === null || options === void 0 ? void 0 : options.messageAdapter;
@@ -213,5 +211,5 @@ function getSchemaName(schema) {
213
211
  return id;
214
212
  }
215
213
 
216
- exports.JsonSerializer = JsonSerializer;
214
+ exports.JsonSchemaSerializer = JsonSchemaSerializer;
217
215
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/utility.ts","../src/errors.ts","../src/logger.ts","../src/jsonSerializer.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MessageContent } from \"./models\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/** @internal */\nexport function wrapError<T>(f: () => T, message: string): T {\n let result: T;\n try {\n result = f();\n } catch (cause) {\n throw errorWithCause(message, cause as Error);\n }\n return result;\n}\n\n/** @internal */\nexport function errorWithCause(message: string, cause: Error): Error {\n return new Error(\n message,\n // TS v4.6 and below do not yet recognize the cause option in the Error constructor\n // see https://medium.com/ovrsea/power-up-your-node-js-debugging-and-error-handling-with-the-new-error-cause-feature-4136c563126a\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n { cause }\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DeserializeOptions,\n JsonSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport { KnownSchemaFormats, SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport LRUCache from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\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> = {\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 JsonSerializer<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?: JsonSerializerOptions<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(message: MessageT, options?: DeserializeOptions): Promise<unknown> {\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;\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"],"names":["createClientLogger","LRUCache","KnownSchemaFormats"],"mappings":";;;;;;;;;;;;AAAA;AACA;AAIM,SAAU,gBAAgB,CAAC,OAAgB,EAAA;IAC/C,MAAM,WAAW,GAAG,OAAyB,CAAC;IAC9C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS,CAAC;AACjF;;ACRA;AACA;AAEA;AACgB,SAAA,SAAS,CAAI,CAAU,EAAE,OAAe,EAAA;AACtD,IAAA,IAAI,MAAS,CAAC;IACd,IAAI;QACF,MAAM,GAAG,CAAC,EAAE,CAAC;AACd,KAAA;AAAC,IAAA,OAAO,KAAK,EAAE;AACd,QAAA,MAAM,cAAc,CAAC,OAAO,EAAE,KAAc,CAAC,CAAC;AAC/C,KAAA;AACD,IAAA,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;AACgB,SAAA,cAAc,CAAC,OAAe,EAAE,KAAY,EAAA;IAC1D,OAAO,IAAI,KAAK,CACd,OAAO;;;;;IAKP,EAAE,KAAK,EAAE,CACV,CAAC;AACJ;;ACxBA;AAKA;;AAEG;AACI,MAAM,MAAM,GAAGA,2BAAkB,CAAC,sBAAsB,CAAC;;ACRhE;AAgBA,MAAM,YAAY,GAAG,kBAAkB,CAAC;AACxC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,OA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CAAC,EAAE;AACjC,QAAA,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;AACzF,KAAA;AACD,IAAA,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE;AACxC,QAAA,MAAM,IAAI,KAAK,CACb,CAAA,yBAAA,EAA4B,gBAAgB,CAAC,CAAC,CAAC,CAAmE,gEAAA,EAAA,YAAY,CAAQ,MAAA,CAAA,CACvI,CAAC;AACH,KAAA;AACD,IAAA,OAAO,gBAAgB,CAAC,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,cAAc,CACrB,OAAiB,EACjB,OAAkC,EAAA;IAElC,MAAM,eAAe,GAAG,OAAO,KAAA,IAAA,IAAP,OAAO,KAAP,KAAA,CAAA,GAAA,KAAA,CAAA,GAAA,OAAO,CAAE,OAAO,CAAC;AACzC,IAAA,IAAI,eAAe,EAAE;AACnB,QAAA,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;AACjC,KAAA;AAAM,SAAA,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE;AACpC,QAAA,OAAO,OAAO,CAAC;AAChB,KAAA;AAAM,SAAA;AACL,QAAA,MAAM,IAAI,KAAK,CACb,CAAA,2HAAA,CAA6H,CAC9H,CAAC;AACH,KAAA;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB,EAAA;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE;AACP,QAAA,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;AAC5C,KAAA;AACD,IAAA,OAAO,EAAE,CAAC;AACZ;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/utility.ts","../src/errors.ts","../src/logger.ts","../src/jsonSchemaSerializer.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MessageContent } from \"./models\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/** @internal */\nexport function wrapError<T>(f: () => T, message: string): T {\n let result: T;\n try {\n result = f();\n } catch (cause) {\n throw errorWithCause(message, cause as Error);\n }\n return result;\n}\n\n/** @internal */\nexport function errorWithCause(message: string, cause: Error): Error {\n return new Error(\n message,\n // TS v4.6 and below do not yet recognize the cause option in the Error constructor\n // see https://medium.com/ovrsea/power-up-your-node-js-debugging-and-error-handling-with-the-new-error-cause-feature-4136c563126a\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n { cause },\n );\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport { KnownSchemaFormats, SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\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"],"names":["createClientLogger","LRUCache","KnownSchemaFormats"],"mappings":";;;;;;;;AAAA;AACA;AAIM,SAAU,gBAAgB,CAAC,OAAgB,EAAA;IAC/C,MAAM,WAAW,GAAG,OAAyB,CAAC;IAC9C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS,CAAC;AACjF;;ACRA;AACA;AAEA;AACgB,SAAA,SAAS,CAAI,CAAU,EAAE,OAAe,EAAA;AACtD,IAAA,IAAI,MAAS,CAAC;AACd,IAAA,IAAI;QACF,MAAM,GAAG,CAAC,EAAE,CAAC;KACd;IAAC,OAAO,KAAK,EAAE;AACd,QAAA,MAAM,cAAc,CAAC,OAAO,EAAE,KAAc,CAAC,CAAC;KAC/C;AACD,IAAA,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;AACgB,SAAA,cAAc,CAAC,OAAe,EAAE,K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+1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  /** @internal */
4
4
  export function wrapError(f, message) {
5
5
  let result;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,gBAAgB;AAChB,MAAM,UAAU,SAAS,CAAI,CAAU,EAAE,OAAe;IACtD,IAAI,MAAS,CAAC;IACd,IAAI;QACF,MAAM,GAAG,CAAC,EAAE,CAAC;KACd;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,cAAc,CAAC,OAAO,EAAE,KAAc,CAAC,CAAC;KAC/C;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,KAAY;IAC1D,OAAO,IAAI,KAAK,CACd,OAAO;IACP,mFAAmF;IACnF,iIAAiI;IACjI,6DAA6D;IAC7D,aAAa;IACb,EAAE,KAAK,EAAE,CACV,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/** @internal */\nexport function wrapError<T>(f: () => T, message: string): T {\n let result: T;\n try {\n result = f();\n } catch (cause) {\n throw errorWithCause(message, cause as Error);\n }\n return result;\n}\n\n/** @internal */\nexport function errorWithCause(message: string, cause: Error): Error {\n return new Error(\n message,\n // TS v4.6 and below do not yet recognize the cause option in the Error constructor\n // see https://medium.com/ovrsea/power-up-your-node-js-debugging-and-error-handling-with-the-new-error-cause-feature-4136c563126a\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n { cause }\n );\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,gBAAgB;AAChB,MAAM,UAAU,SAAS,CAAI,CAAU,EAAE,OAAe;IACtD,IAAI,MAAS,CAAC;IACd,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,EAAE,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,cAAc,CAAC,OAAO,EAAE,KAAc,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,KAAY;IAC1D,OAAO,IAAI,KAAK,CACd,OAAO;IACP,mFAAmF;IACnF,iIAAiI;IACjI,6DAA6D;IAC7D,aAAa;IACb,EAAE,KAAK,EAAE,CACV,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/** @internal */\nexport function wrapError<T>(f: () => T, message: string): T {\n let result: T;\n try {\n result = f();\n } catch (cause) {\n throw errorWithCause(message, cause as Error);\n }\n return result;\n}\n\n/** @internal */\nexport function errorWithCause(message: string, cause: Error): Error {\n return new Error(\n message,\n // TS v4.6 and below do not yet recognize the cause option in the Error constructor\n // see https://medium.com/ovrsea/power-up-your-node-js-debugging-and-error-handling-with-the-new-error-cause-feature-4136c563126a\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n { cause },\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
3
- export { JsonSerializer } from "./jsonSerializer";
2
+ // Licensed under the MIT License.
3
+ export { JsonSchemaSerializer } from "./jsonSchemaSerializer";
4
4
  export * from "./models";
5
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,cAAc,UAAU,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { JsonSerializer } from \"./jsonSerializer\";\n\nexport * from \"./models\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAE9D,cAAc,UAAU,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport { JsonSchemaSerializer } from \"./jsonSchemaSerializer\";\n\nexport * from \"./models\";\n"]}
@@ -1,9 +1,9 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { KnownSchemaFormats } from "@azure/schema-registry";
4
4
  import { isMessageContent } from "./utility";
5
5
  import { errorWithCause, wrapError } from "./errors";
6
- import LRUCache from "lru-cache";
6
+ import { LRUCache } from "lru-cache";
7
7
  import { logger } from "./logger";
8
8
  const jsonMimeType = "application/json";
9
9
  const encoder = new TextEncoder();
@@ -26,7 +26,7 @@ const cacheOptions = {
26
26
  * Json serializer that obtains schemas from a schema registry and does not
27
27
  * pack schemas into its payloads.
28
28
  */
29
- export class JsonSerializer {
29
+ export class JsonSchemaSerializer {
30
30
  /**
31
31
  * Creates a new serializer.
32
32
  *
@@ -170,4 +170,4 @@ function getSchemaName(schema) {
170
170
  }
171
171
  return id;
172
172
  }
173
- //# sourceMappingURL=jsonSerializer.js.map
173
+ //# sourceMappingURL=jsonSchemaSerializer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jsonSchemaSerializer.js","sourceRoot":"","sources":["../../src/jsonSchemaSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAQlC,OAAO,EAAE,kBAAkB,EAAqC,MAAM,wBAAwB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM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,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 {\n DeserializeOptions,\n JsonSchemaSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport { KnownSchemaFormats, SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport { LRUCache } from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\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,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  import { createClientLogger } from "@azure/logger";
4
4
  /**
5
5
  * The \@azure/logger configuration for the schema-registry-json package.
@@ -1 +1 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n"]}
1
+ {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { createClientLogger } from \"@azure/logger\";\n\n/**\n * The \\@azure/logger configuration for the schema-registry-json package.\n */\nexport const logger = createClientLogger(\"schema-registry-json\");\n"]}
@@ -1,4 +1,4 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  export {};
4
4
  //# sourceMappingURL=models.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * A message that contains binary data and a content type.\n */\nexport interface MessageContent {\n /**\n * The message's binary data\n */\n data: Uint8Array;\n /**\n * The message's content type\n */\n contentType: string;\n}\n\n/**\n * MessageAdapter is an interface that converts to/from a concrete message type\n * to a MessageContent\n */\nexport interface MessageAdapter<MessageT> {\n /**\n * defines how to create a message from a payload and a content type\n */\n produce: (messageContent: MessageContent) => MessageT;\n /**\n * defines how to access the payload and the content type of a message\n */\n consume: (message: MessageT) => MessageContent;\n}\n\n/**\n * Options for Schema\n */\nexport interface JsonSerializerOptions<MessageT> {\n /**\n * The group name to be used when registering/looking up a schema. Must be specified\n * if `serialize` will be called.\n */\n groupName?: string;\n /**\n * Message Adapter enables the serializer to produce and consume custom messages.\n */\n messageAdapter?: MessageAdapter<MessageT>;\n}\n\n/**\n * The options to the deserialize method.\n */\nexport interface DeserializeOptions {\n /**\n * Validate the value against the schema. Raise an error if the validation is not successful.\n */\n validateCallback?: (value: unknown, schema: string) => void;\n}\n"]}
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * A message that contains binary data and a content type.\n */\nexport interface MessageContent {\n /**\n * The message's binary data\n */\n data: Uint8Array;\n /**\n * The message's content type\n */\n contentType: string;\n}\n\n/**\n * MessageAdapter is an interface that converts to/from a concrete message type\n * to a MessageContent\n */\nexport interface MessageAdapter<MessageT> {\n /**\n * defines how to create a message from a payload and a content type\n */\n produce: (messageContent: MessageContent) => MessageT;\n /**\n * defines how to access the payload and the content type of a message\n */\n consume: (message: MessageT) => MessageContent;\n}\n\n/**\n * Options for Schema\n */\nexport interface JsonSchemaSerializerOptions<MessageT> {\n /**\n * The group name to be used when registering/looking up a schema. Must be specified\n * if `serialize` will be called.\n */\n groupName?: string;\n /**\n * Message Adapter enables the serializer to produce and consume custom messages.\n */\n messageAdapter?: MessageAdapter<MessageT>;\n}\n\n/**\n * The options to the deserialize method.\n */\nexport interface DeserializeOptions {\n /**\n * Validate the value against the schema. Raise an error if the validation is not successful.\n */\n validateCallback?: (value: unknown, schema: string) => void;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT license.
2
+ // Licensed under the MIT License.
3
3
  export function isMessageContent(message) {
4
4
  const castMessage = message;
5
5
  return castMessage.data !== undefined && castMessage.contentType !== undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAC/C,MAAM,WAAW,GAAG,OAAyB,CAAC;IAC9C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS,CAAC;AACjF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { MessageContent } from \"./models\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n"]}
1
+ {"version":3,"file":"utility.js","sourceRoot":"","sources":["../../src/utility.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,MAAM,UAAU,gBAAgB,CAAC,OAAgB;IAC/C,MAAM,WAAW,GAAG,OAAyB,CAAC;IAC9C,OAAO,WAAW,CAAC,IAAI,KAAK,SAAS,IAAI,WAAW,CAAC,WAAW,KAAK,SAAS,CAAC;AACjF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { MessageContent } from \"./models\";\n\nexport function isMessageContent(message: unknown): message is MessageContent {\n const castMessage = message as MessageContent;\n return castMessage.data !== undefined && castMessage.contentType !== undefined;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azure/schema-registry-json",
3
- "version": "1.0.0-beta.1",
3
+ "version": "1.0.0",
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/index.js",
@@ -8,21 +8,22 @@
8
8
  "types": "types/schema-registry-json.d.ts",
9
9
  "scripts": {
10
10
  "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
11
- "build:browser": "tsc -p . && rollup -c rollup.test.config.js 2>&1",
12
- "build:node": "tsc -p . && dev-tool run bundle --browser-test=false",
11
+ "bundle": "tsc -p . && dev-tool run bundle --polyfill-node false --inject-node-polyfills true --ignore-missing-node-builtins true",
12
+ "build:browser": "npm run bundle",
13
+ "build:node": "npm run bundle",
13
14
  "build:samples": "echo Obsolete.",
14
- "build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1",
15
- "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local",
16
- "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
17
- "clean": "rimraf dist dist-* temp types *.tgz *.log",
15
+ "build:test": "npm run bundle",
16
+ "build": "npm run clean && npm run bundle && dev-tool run extract-api",
17
+ "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
18
+ "clean": "rimraf --glob dist dist-* temp types *.tgz *.log",
18
19
  "execute:samples": "dev-tool samples run samples-dev",
19
- "extract-api": "tsc -p . && api-extractor run --local",
20
- "format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
20
+ "extract-api": "tsc -p . && dev-tool run extract-api",
21
+ "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
21
22
  "integration-test:browser": "dev-tool run test:browser",
22
23
  "integration-test:node": "dev-tool run test:node-js-input -- --timeout 5000000 'dist-esm/test/**/*.spec.js'",
23
24
  "integration-test": "npm run integration-test:node && npm run integration-test:browser",
24
- "lint:fix": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js --fix --fix-type [problem,suggestion]",
25
- "lint": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js",
25
+ "lint:fix": "eslint package.json api-extractor.json README.md src test --fix --fix-type [problem,suggestion]",
26
+ "lint": "eslint package.json api-extractor.json README.md src test",
26
27
  "pack": "npm pack 2>&1",
27
28
  "test:browser": "npm run build:test && npm run unit-test:browser && npm run integration-test:browser",
28
29
  "test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node",
@@ -40,7 +41,7 @@
40
41
  ],
41
42
  "repository": "github:Azure/azure-sdk-for-js",
42
43
  "engines": {
43
- "node": ">=14.0.0"
44
+ "node": ">=18.0.0"
44
45
  },
45
46
  "keywords": [
46
47
  "azure",
@@ -68,8 +69,8 @@
68
69
  },
69
70
  "dependencies": {
70
71
  "@azure/logger": "^1.0.0",
71
- "@azure/schema-registry": "1.3.0-beta.1",
72
- "lru-cache": "^7.4.1",
72
+ "@azure/schema-registry": "^1.3.0",
73
+ "lru-cache": "^10.2.0",
73
74
  "tslib": "^2.2.0"
74
75
  },
75
76
  "devDependencies": {
@@ -77,20 +78,17 @@
77
78
  "@azure/dev-tool": "^1.0.0",
78
79
  "@azure/eslint-plugin-azure-sdk": "^3.0.0",
79
80
  "@azure/event-hubs": "^5.8.0",
80
- "@azure/identity": "^2.0.1",
81
- "@azure/test-utils": "^1.0.0",
81
+ "@azure/identity": "^4.0.1",
82
+ "@azure-tools/test-utils": "^1.0.1",
82
83
  "@azure-tools/test-credential": "^1.0.0",
83
84
  "@azure-tools/test-recorder": "^3.0.0",
84
85
  "@microsoft/api-extractor": "^7.31.1",
85
- "@rollup/plugin-commonjs": "^24.0.0",
86
- "@rollup/plugin-inject": "^5.0.0",
87
- "@types/ajv": "^1.0.0",
88
- "@types/mocha": "^7.0.2",
89
- "@types/node": "^16.0.0",
86
+ "@types/mocha": "^10.0.0",
87
+ "@types/node": "^18.0.0",
90
88
  "ajv": "^8.12.0",
91
89
  "cross-env": "^7.0.2",
92
90
  "dotenv": "^16.0.0",
93
- "eslint": "^8.0.0",
91
+ "eslint": "^9.9.0",
94
92
  "karma": "^6.2.0",
95
93
  "karma-chrome-launcher": "^3.0.0",
96
94
  "karma-coverage": "^2.0.0",
@@ -102,14 +100,10 @@
102
100
  "karma-mocha": "^2.0.1",
103
101
  "karma-mocha-reporter": "^2.2.5",
104
102
  "karma-sourcemap-loader": "^0.3.8",
105
- "karma-source-map-support": "~1.4.0",
106
- "mocha": "^7.1.1",
107
- "mocha-junit-reporter": "^2.0.0",
108
- "nyc": "^15.0.0",
109
- "prettier": "^2.5.1",
110
- "rimraf": "^3.0.0",
111
- "rollup": "^2.0.0",
112
- "source-map-support": "^0.5.9",
113
- "typescript": "~5.0.0"
103
+ "mocha": "^10.0.0",
104
+ "nyc": "^17.0.0",
105
+ "rimraf": "^5.0.5",
106
+ "typescript": "~5.5.3",
107
+ "ts-node": "^10.0.0"
114
108
  }
115
109
  }
@@ -14,14 +14,14 @@ export declare interface DeserializeOptions {
14
14
  * Json serializer that obtains schemas from a schema registry and does not
15
15
  * pack schemas into its payloads.
16
16
  */
17
- export declare class JsonSerializer<MessageT = MessageContent> {
17
+ export declare class JsonSchemaSerializer<MessageT = MessageContent> {
18
18
  /**
19
19
  * Creates a new serializer.
20
20
  *
21
21
  * @param client - Schema Registry where schemas are registered and obtained.
22
22
  * Usually this is a SchemaRegistryClient instance.
23
23
  */
24
- constructor(client: SchemaRegistry, options?: JsonSerializerOptions<MessageT>);
24
+ constructor(client: SchemaRegistry, options?: JsonSchemaSerializerOptions<MessageT>);
25
25
  private readonly schemaGroup?;
26
26
  private readonly registry;
27
27
  private readonly messageAdapter?;
@@ -48,7 +48,7 @@ export declare class JsonSerializer<MessageT = MessageContent> {
48
48
  * @throws {@link Error}
49
49
  * Thrown if the deserialization failed, e.g. because reader and writer schemas are incompatible.
50
50
  */
51
- deserialize(message: MessageT, options?: DeserializeOptions): Promise<unknown>;
51
+ deserialize<T>(message: MessageT, options?: DeserializeOptions): Promise<T>;
52
52
  private getSchemaById;
53
53
  private getSchemaByDefinition;
54
54
  private cache;
@@ -57,7 +57,7 @@ export declare class JsonSerializer<MessageT = MessageContent> {
57
57
  /**
58
58
  * Options for Schema
59
59
  */
60
- export declare interface JsonSerializerOptions<MessageT> {
60
+ export declare interface JsonSchemaSerializerOptions<MessageT> {
61
61
  /**
62
62
  * The group name to be used when registering/looking up a schema. Must be specified
63
63
  * if `serialize` will be called.
@@ -1 +0,0 @@
1
- {"version":3,"file":"jsonSerializer.js","sourceRoot":"","sources":["../../src/jsonSerializer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAQlC,OAAO,EAAE,kBAAkB,EAAqC,MAAM,wBAAwB,CAAC;AAC/F,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,QAAQ,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,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,GAAiC;IACjD,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,cAAc;IACzB;;;;;OAKG;IACH,YAAY,MAAsB,EAAE,OAAyC;QAS5D,wBAAmB,GAAG,IAAI,QAAQ,CAAiB,YAAY,CAAC,CAAC;QACjE,cAAS,GAAG,IAAI,QAAQ,CAAiB,YAAY,CAAC,CAAC;QAT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AAG,CAAC,CAAC;IAChD,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,sEAAsE,CAAC,CAAC;KACzF;IACD,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK,YAAY,EAAE;QACxC,MAAM,IAAI,KAAK,CACb,4BAA4B,gBAAgB,CAAC,CAAC,CAAC,mEAAmE,YAAY,QAAQ,CACvI,CAAC;KACH;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;QACnB,OAAO,eAAe,CAAC,OAAO,CAAC,CAAC;KACjC;SAAM,IAAI,gBAAgB,CAAC,OAAO,CAAC,EAAE;QACpC,OAAO,OAAO,CAAC;KAChB;SAAM;QACL,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;KACH;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAoB;IACzC,MAAM,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,EAAE,CAAC;IACnC,IAAI,CAAC,EAAE,EAAE;QACP,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;KAC5C;IACD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n DeserializeOptions,\n JsonSerializerOptions,\n MessageAdapter,\n MessageContent,\n} from \"./models\";\nimport { KnownSchemaFormats, SchemaDescription, SchemaRegistry } from \"@azure/schema-registry\";\nimport { isMessageContent } from \"./utility\";\nimport { errorWithCause, wrapError } from \"./errors\";\nimport LRUCache from \"lru-cache\";\nimport LRUCacheOptions = LRUCache.Options;\nimport { logger } from \"./logger\";\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> = {\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 JsonSerializer<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?: JsonSerializerOptions<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(message: MessageT, options?: DeserializeOptions): Promise<unknown> {\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;\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"]}