@azure/eventgrid-namespaces 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.
Files changed (40) hide show
  1. package/README.md +45 -19
  2. package/dist/index.js +403 -196
  3. package/dist/index.js.map +1 -1
  4. package/dist-esm/src/cadl-generated/EventGridClient.js +20 -28
  5. package/dist-esm/src/cadl-generated/EventGridClient.js.map +1 -1
  6. package/dist-esm/src/cadl-generated/api/EventGridContext.js +2 -2
  7. package/dist-esm/src/cadl-generated/api/EventGridContext.js.map +1 -1
  8. package/dist-esm/src/cadl-generated/api/operations.js +25 -29
  9. package/dist-esm/src/cadl-generated/api/operations.js.map +1 -1
  10. package/dist-esm/src/cadl-generated/index.js.map +1 -1
  11. package/dist-esm/src/cadl-generated/models/index.js.map +1 -1
  12. package/dist-esm/src/cadl-generated/models/models.js.map +1 -1
  13. package/dist-esm/src/cadl-generated/models/options.js.map +1 -1
  14. package/dist-esm/src/cadl-generated/rest/clientDefinitions.js.map +1 -1
  15. package/dist-esm/src/cadl-generated/rest/eventGridClient.js +9 -9
  16. package/dist-esm/src/cadl-generated/rest/eventGridClient.js.map +1 -1
  17. package/dist-esm/src/cadl-generated/rest/isUnexpected.js.map +1 -1
  18. package/dist-esm/src/cadl-generated/rest/models.js.map +1 -1
  19. package/dist-esm/src/cadl-generated/rest/parameters.js.map +1 -1
  20. package/dist-esm/src/cloudEventDistrubtedTracingEnricherPolicy.js +53 -0
  21. package/dist-esm/src/cloudEventDistrubtedTracingEnricherPolicy.js.map +1 -0
  22. package/dist-esm/src/consumer.js +73 -0
  23. package/dist-esm/src/consumer.js.map +1 -0
  24. package/dist-esm/src/eventGridNamespacesPublishBinaryMode.js.map +1 -1
  25. package/dist-esm/src/eventGridReceiverClient.js +98 -0
  26. package/dist-esm/src/eventGridReceiverClient.js.map +1 -0
  27. package/dist-esm/src/eventGridSenderClient.js +72 -0
  28. package/dist-esm/src/eventGridSenderClient.js.map +1 -0
  29. package/dist-esm/src/index.js +3 -1
  30. package/dist-esm/src/index.js.map +1 -1
  31. package/dist-esm/src/models.js +3 -3
  32. package/dist-esm/src/models.js.map +1 -1
  33. package/dist-esm/src/util.js +155 -0
  34. package/dist-esm/src/util.js.map +1 -0
  35. package/package.json +10 -10
  36. package/types/eventgrid-namespaces.d.ts +127 -97
  37. package/dist-esm/src/constants.js +0 -5
  38. package/dist-esm/src/constants.js.map +0 -1
  39. package/dist-esm/src/eventGridNamespacesClient.js +0 -147
  40. package/dist-esm/src/eventGridNamespacesClient.js.map +0 -1
@@ -0,0 +1,73 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { createSerializer } from "@azure/core-client";
4
+ import { cloudEventReservedPropertyNames } from "./models";
5
+ import { CloudEvent as CloudEventMapper, parseAndWrap, validateCloudEventEvent } from "./util";
6
+ const serializer = createSerializer();
7
+ /**
8
+ * EventGridDeserializer is used to aid in processing events delivered by EventGrid. It can deserialize a JSON encoded payload
9
+ * of either a single event or batch of events as well as be used to convert the result of `JSON.parse` into an
10
+ * `EventGridEvent` or `CloudEvent` like object.
11
+ *
12
+ * Unlike normal JSON deseralization, EventGridDeserializer does some additional conversions:
13
+ *
14
+ * - The consumer parses the event time property into a `Date` object, for ease of use.
15
+ * - When deserializing an event in the CloudEvent schema, if the event contains binary data, it is base64 decoded
16
+ * and returned as an instance of the `Uint8Array` type.
17
+ */
18
+ export class EventGridDeserializer {
19
+ async deserializeCloudEvents(encodedEvents) {
20
+ const decodedArray = parseAndWrap(encodedEvents);
21
+ const events = [];
22
+ for (const o of decodedArray) {
23
+ validateCloudEventEvent(o);
24
+ // Check that the required fields are present and of the correct type and the optional fields are missing
25
+ // or of the correct type.
26
+ const deserialized = serializer.deserialize(CloudEventMapper, o, "");
27
+ const modelEvent = {
28
+ specversion: deserialized.specversion,
29
+ id: deserialized.id,
30
+ source: deserialized.source,
31
+ type: deserialized.type,
32
+ };
33
+ if (deserialized.datacontenttype !== undefined) {
34
+ modelEvent.datacontenttype = deserialized.datacontenttype;
35
+ }
36
+ if (deserialized.dataschema !== undefined) {
37
+ modelEvent.dataschema = deserialized.dataschema;
38
+ }
39
+ if (deserialized.subject !== undefined) {
40
+ modelEvent.subject = deserialized.subject;
41
+ }
42
+ if (deserialized.time !== undefined) {
43
+ modelEvent.time = deserialized.time;
44
+ }
45
+ if (deserialized.data !== undefined) {
46
+ modelEvent.data = deserialized.data;
47
+ }
48
+ // If the data the event represents binary, it is encoded as base64 text in a different property on the event and we need to transform it.
49
+ if (deserialized.dataBase64 !== undefined) {
50
+ if (deserialized.data !== undefined) {
51
+ throw new TypeError("event contains both a data and data_base64 field");
52
+ }
53
+ if (!(deserialized.dataBase64 instanceof Uint8Array)) {
54
+ throw new TypeError("event data_base64 property is not an instance of Uint8Array");
55
+ }
56
+ modelEvent.data = deserialized.dataBase64;
57
+ }
58
+ // Build the "extensionsAttributes" property bag by removing all known top level properties.
59
+ const extensionAttributes = Object.assign({}, deserialized);
60
+ for (const propName of cloudEventReservedPropertyNames) {
61
+ delete extensionAttributes[propName];
62
+ }
63
+ delete extensionAttributes.dataBase64;
64
+ // If any properties remain, copy them to the model.
65
+ if (Object.keys(extensionAttributes).length > 0) {
66
+ modelEvent.extensionAttributes = extensionAttributes;
67
+ }
68
+ events.push(modelEvent);
69
+ }
70
+ return events;
71
+ }
72
+ }
73
+ //# sourceMappingURL=consumer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consumer.js","sourceRoot":"","sources":["../../src/consumer.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAc,+BAA+B,EAAE,MAAM,UAAU,CAAC;AACvE,OAAO,EAAE,UAAU,IAAI,gBAAgB,EAAE,YAAY,EAAE,uBAAuB,EAAE,MAAM,QAAQ,CAAC;AAE/F,MAAM,UAAU,GAAG,gBAA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AI,YAAY,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;gBAC1C,IAAI,YAAY,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;oBACpC,MAAM,IAAI,SAAS,CAAC,kDAAkD,CAAC,CAAC;gBAC1E,CAAC;gBAED,IAAI,CAAC,CAAC,YAAY,CAAC,UAAU,YAAY,UAAU,CAAC,EAAE,CAAC;oBACrD,MAAM,IAAI,SAAS,CAAC,6DAA6D,CAAC,CAAC;gBACrF,CAAC;gBAED,UAAU,CAAC,IAAI,GAAG,YAAY,CAAC,UAAU,CAAC;YAC5C,CAAC;YAED,4FAA4F;YAC5F,MAAM,mBAAmB,qBAAQ,YAAY,CAAE,CAAC;YAChD,KAAK,MAAM,QAAQ,IAAI,+BAA+B,EAAE,CAAC;gBACvD,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;YACvC,CAAC;YACD,OAAO,mBAAmB,CAAC,UAAU,CAAC;YAEtC,oDAAoD;YACpD,IAAI,MAAM,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAChD,UAAU,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;YACvD,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,UAAiC,CAAC,CAAC;QACjD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createSerializer } from \"@azure/core-client\";\nimport { CloudEvent, cloudEventReservedPropertyNames } from \"./models\";\nimport { CloudEvent as CloudEventMapper, parseAndWrap, validateCloudEventEvent } from \"./util\";\n\nconst serializer = createSerializer();\n\n/**\n * EventGridDeserializer is used to aid in processing events delivered by EventGrid. It can deserialize a JSON encoded payload\n * of either a single event or batch of events as well as be used to convert the result of `JSON.parse` into an\n * `EventGridEvent` or `CloudEvent` like object.\n *\n * Unlike normal JSON deseralization, EventGridDeserializer does some additional conversions:\n *\n * - The consumer parses the event time property into a `Date` object, for ease of use.\n * - When deserializing an event in the CloudEvent schema, if the event contains binary data, it is base64 decoded\n * and returned as an instance of the `Uint8Array` type.\n */\nexport class EventGridDeserializer {\n /**\n * Deserializes events encoded in the Cloud Events 1.0 schema.\n *\n * @param encodedEvents - the JSON encoded representation of either a single event or an array of\n * events, encoded in the Cloud Events 1.0 Schema.\n */\n public async deserializeCloudEvents(encodedEvents: string): Promise<CloudEvent<unknown>[]>;\n\n /**\n * Deserializes events encoded in the Cloud Events 1.0 schema.\n *\n * @param encodedEvents - an object representing a single event, encoded in the Cloud Events 1.0 schema.\n */\n public async deserializeCloudEvents(\n encodedEvents: Record<string, unknown>,\n ): Promise<CloudEvent<unknown>[]>;\n public async deserializeCloudEvents(\n encodedEvents: string | Record<string, unknown>,\n ): Promise<CloudEvent<unknown>[]> {\n const decodedArray = parseAndWrap(encodedEvents);\n\n const events: CloudEvent<unknown>[] = [];\n\n for (const o of decodedArray) {\n validateCloudEventEvent(o);\n\n // Check that the required fields are present and of the correct type and the optional fields are missing\n // or of the correct type.\n\n const deserialized = serializer.deserialize(CloudEventMapper, o, \"\");\n const modelEvent: Record<string, any> = {\n specversion: deserialized.specversion,\n id: deserialized.id,\n source: deserialized.source,\n type: deserialized.type,\n };\n\n if (deserialized.datacontenttype !== undefined) {\n modelEvent.datacontenttype = deserialized.datacontenttype;\n }\n\n if (deserialized.dataschema !== undefined) {\n modelEvent.dataschema = deserialized.dataschema;\n }\n\n if (deserialized.subject !== undefined) {\n modelEvent.subject = deserialized.subject;\n }\n\n if (deserialized.time !== undefined) {\n modelEvent.time = deserialized.time;\n }\n\n if (deserialized.data !== undefined) {\n modelEvent.data = deserialized.data;\n }\n\n // If the data the event represents binary, it is encoded as base64 text in a different property on the event and we need to transform it.\n if (deserialized.dataBase64 !== undefined) {\n if (deserialized.data !== undefined) {\n throw new TypeError(\"event contains both a data and data_base64 field\");\n }\n\n if (!(deserialized.dataBase64 instanceof Uint8Array)) {\n throw new TypeError(\"event data_base64 property is not an instance of Uint8Array\");\n }\n\n modelEvent.data = deserialized.dataBase64;\n }\n\n // Build the \"extensionsAttributes\" property bag by removing all known top level properties.\n const extensionAttributes = { ...deserialized };\n for (const propName of cloudEventReservedPropertyNames) {\n delete extensionAttributes[propName];\n }\n delete extensionAttributes.dataBase64;\n\n // If any properties remain, copy them to the model.\n if (Object.keys(extensionAttributes).length > 0) {\n modelEvent.extensionAttributes = extensionAttributes;\n }\n\n events.push(modelEvent as CloudEvent<unknown>);\n }\n\n return events;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"eventGridNamespacesPublishBinaryMode.js","sourceRoot":"","sources":["../../src/eventGridNamespacesPublishBinaryMode.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,YAAY,GAIb,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAoB,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAGhG,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAe,EACf,SAAiB,EACjB,KAAiB,EACjB,UAAoC,EAAE,cAAc,EAAE,EAAE,EAAE;IAE1D,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC1F,OAAO,6BAA6B,CAAC,MAAM,CAAC,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,MAAuE;IAEvE,IAAI,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QACzB,MAAM,MAAM,CAAC,IAAI,CAAC;IACpB,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAe,EACf,SAAiB,EACjB,KAAiB,EACjB,UAAoC,EAAE,cAAc,EAAE,EAAE,EAAE;;IAE1D,MAAM,O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AAO,EACP,IAAI,EAAE;YACJ,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI;YACJ,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,IAAI,EAAE,MAAA,KAAK,CAAC,IAAI,0CAAE,WAAW,EAAE;YAC/B,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,IACD,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n isUnexpected,\n EventGridContext as Client,\n PublishCloudEvent200Response,\n PublishCloudEventDefaultResponse,\n} from \"./cadl-generated/rest/index\";\nimport { StreamableMethod, operationOptionsToRequestParameters } from \"@azure-rest/core-client\";\nimport { PublishCloudEventOptions } from \"./cadl-generated/models/options\";\nimport { RawHttpHeadersInput } from \"@azure/core-rest-pipeline\";\nimport { Buffer } from \"buffer\";\nimport { CloudEvent } from \"./cadl-generated\";\n\nexport async function publishCloudEventInBinaryMode(\n context: Client,\n topicName: string,\n event: CloudEvent,\n options: PublishCloudEventOptions = { requestOptions: {} },\n): Promise<Record<string, any>> {\n const result = await _publishCloudEventSendBinaryMode(context, topicName, event, options);\n return _publishCloudEventDeserialize(result);\n}\n\nexport async function _publishCloudEventDeserialize(\n result: PublishCloudEvent200Response | PublishCloudEventDefaultResponse,\n): Promise<Record<string, any>> {\n if (isUnexpected(result)) {\n throw result.body;\n }\n\n return result.body;\n}\n\nexport function _publishCloudEventSendBinaryMode(\n context: Client,\n topicName: string,\n event: CloudEvent,\n options: PublishCloudEventOptions = { requestOptions: {} },\n): StreamableMethod<PublishCloudEvent200Response | PublishCloudEventDefaultResponse> {\n const headers: RawHttpHeadersInput = {\n \"ce-id\": event.id,\n \"ce-source\": event.source,\n \"ce-type\": event.type,\n \"ce-specversion\": event.specversion,\n };\n\n if (event.time) {\n headers[\"ce-time\"] = event.time.toISOString();\n }\n\n if (event.dataschema) {\n headers[\"ce-dataschema\"] = event.dataschema;\n }\n\n if (event.datacontenttype) {\n headers[\"ce-datacontenttype\"] = event.datacontenttype;\n }\n\n if (event.subject) {\n headers[\"ce-subject\"] = event.subject;\n }\n\n let data: any;\n if (event.data) {\n // If data is already encoded\n if (Buffer.isBuffer(event.data)) {\n data = event.data;\n } else {\n throw new Error(`CloudEvent data must be binary when in binary mode.`);\n }\n } else {\n if (event.dataBase64) {\n data = event.dataBase64;\n }\n }\n\n return context.path(\"/topics/{topicName}:publish\", topicName).post({\n ...operationOptionsToRequestParameters(options),\n contentType: (options.contentType as any) ?? \"application/cloudevents+json; charset=utf-8\",\n headers,\n body: {\n id: event.id,\n source: event.source,\n data,\n type: event.type,\n time: event.time?.toISOString(),\n specversion: event.specversion,\n dataschema: event.dataschema,\n datacontenttype: event.datacontenttype,\n subject: event.subject,\n },\n });\n}\n"]}
1
+ {"version":3,"file":"eventGridNamespacesPublishBinaryMode.js","sourceRoot":"","sources":["../../src/eventGridNamespacesPublishBinaryMode.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EACL,YAAY,GAIb,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAoB,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAGhG,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAe,EACf,SAAiB,EACjB,KAAiB,EACjB,UAA2C,EAAE,cAAc,EAAE,EAAE,EAAE;IAEjE,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;IAC1F,OAAO,6BAA6B,CAAC,MAAM,CAAC,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B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N,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;YACrB,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC;QAC1B,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC,IAAI,CAAC,6BAA6B,EAAE,SAAS,CAAC,CAAC,IAAI,iCAC7D,mCAAmC,CAAC,OAAO,CAAC,KAC/C,WAAW,EAAE,MAAC,OAAO,CAAC,WAAmB,mCAAI,6CAA6C,EAC1F,OAAO,EACP,IAAI,EAAE;YACJ,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,IAAI;YACJ,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,IAAI,EAAE,MAAA,KAAK,CAAC,IAAI,0CAAE,WAAW,EAAE;YAC/B,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,OAAO,EAAE,KAAK,CAAC,OAAO;SACvB,IACD,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n isUnexpected,\n EventGridContext as Client,\n PublishCloudEvent200Response,\n PublishCloudEventDefaultResponse,\n} from \"./cadl-generated/rest/index\";\nimport { StreamableMethod, operationOptionsToRequestParameters } from \"@azure-rest/core-client\";\nimport { PublishCloudEventOptionalParams } from \"./cadl-generated/models/options\";\nimport { RawHttpHeadersInput } from \"@azure/core-rest-pipeline\";\nimport { Buffer } from \"buffer\";\nimport { CloudEvent } from \"./cadl-generated\";\n\nexport async function publishCloudEventInBinaryMode(\n context: Client,\n topicName: string,\n event: CloudEvent,\n options: PublishCloudEventOptionalParams = { requestOptions: {} },\n): Promise<Record<string, any>> {\n const result = await _publishCloudEventSendBinaryMode(context, topicName, event, options);\n return _publishCloudEventDeserialize(result);\n}\n\nexport async function _publishCloudEventDeserialize(\n result: PublishCloudEvent200Response | PublishCloudEventDefaultResponse,\n): Promise<Record<string, any>> {\n if (isUnexpected(result)) {\n throw result.body;\n }\n\n return result.body;\n}\n\nexport function _publishCloudEventSendBinaryMode(\n context: Client,\n topicName: string,\n event: CloudEvent,\n options: PublishCloudEventOptionalParams = { requestOptions: {} },\n): StreamableMethod<PublishCloudEvent200Response | PublishCloudEventDefaultResponse> {\n const headers: RawHttpHeadersInput = {\n \"ce-id\": event.id,\n \"ce-source\": event.source,\n \"ce-type\": event.type,\n \"ce-specversion\": event.specversion,\n };\n\n if (event.time) {\n headers[\"ce-time\"] = event.time.toISOString();\n }\n\n if (event.dataschema) {\n headers[\"ce-dataschema\"] = event.dataschema;\n }\n\n if (event.datacontenttype) {\n headers[\"ce-datacontenttype\"] = event.datacontenttype;\n }\n\n if (event.subject) {\n headers[\"ce-subject\"] = event.subject;\n }\n\n let data: any;\n if (event.data) {\n // If data is already encoded\n if (Buffer.isBuffer(event.data)) {\n data = event.data;\n } else {\n throw new Error(`CloudEvent data must be binary when in binary mode.`);\n }\n } else {\n if (event.dataBase64) {\n data = event.dataBase64;\n }\n }\n\n return context.path(\"/topics/{topicName}:publish\", topicName).post({\n ...operationOptionsToRequestParameters(options),\n contentType: (options.contentType as any) ?? \"application/cloudevents+json; charset=utf-8\",\n headers,\n body: {\n id: event.id,\n source: event.source,\n data,\n type: event.type,\n time: event.time?.toISOString(),\n specversion: event.specversion,\n dataschema: event.dataschema,\n datacontenttype: event.datacontenttype,\n subject: event.subject,\n },\n });\n}\n"]}
@@ -0,0 +1,98 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { EventGridClient as EventGridClientGenerated } from "./cadl-generated/EventGridClient";
4
+ import { cloudEventDistributedTracingEnricherPolicy } from "./cloudEventDistrubtedTracingEnricherPolicy";
5
+ import { tracingPolicyName } from "@azure/core-rest-pipeline";
6
+ import { uint8ArrayToString } from "@azure/core-util";
7
+ /**
8
+ * Event Grid Namespaces Client
9
+ */
10
+ export class EventGridReceiverClient {
11
+ /** Azure Messaging EventGrid Client */
12
+ constructor(endpoint, credential, topicName, subscriptionName, options = {}) {
13
+ this._client = new EventGridClientGenerated(endpoint, credential, options);
14
+ this._topicName = topicName;
15
+ this._subscriptionName = subscriptionName;
16
+ this._client.pipeline.addPolicy(cloudEventDistributedTracingEnricherPolicy(), {
17
+ afterPolicies: [tracingPolicyName],
18
+ });
19
+ }
20
+ /**
21
+ * Receive Batch of Cloud Events from the Event Subscription.
22
+ *
23
+ * @param options - Options to receive
24
+ *
25
+ */
26
+ async receiveEvents(options = { requestOptions: {} }) {
27
+ const result = await this._client.receiveCloudEvents(this._topicName, this._subscriptionName, options);
28
+ const modifiedResult = {
29
+ details: result.details.map((receiveDetails) => {
30
+ const cloudEvent = {
31
+ type: receiveDetails.event.type,
32
+ source: receiveDetails.event.source,
33
+ id: receiveDetails.event.id,
34
+ time: receiveDetails.event.time,
35
+ dataSchema: receiveDetails.event.dataschema,
36
+ dataContentType: receiveDetails.event.datacontenttype,
37
+ subject: receiveDetails.event.subject,
38
+ specVersion: receiveDetails.event.specversion,
39
+ data: receiveDetails.event.data
40
+ ? receiveDetails.event.data
41
+ : receiveDetails.event.dataBase64
42
+ ? uint8ArrayToString(receiveDetails.event.dataBase64, "base64")
43
+ : undefined,
44
+ };
45
+ return {
46
+ brokerProperties: receiveDetails.brokerProperties,
47
+ event: cloudEvent,
48
+ };
49
+ }),
50
+ };
51
+ return modifiedResult;
52
+ }
53
+ /**
54
+ * Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least one
55
+ * event is successfully acknowledged. The response body will include the set of successfully acknowledged
56
+ * lockTokens, along with other failed lockTokens with their corresponding error information. Successfully
57
+ * acknowledged events will no longer be available to any consumer.
58
+ *
59
+ * @param lockTokens - Lock Tokens
60
+ * @param options - Options to Acknowledge
61
+ *
62
+ */
63
+ acknowledgeEvents(lockTokens, options = { requestOptions: {} }) {
64
+ return this._client.acknowledgeCloudEvents(this._topicName, this._subscriptionName, lockTokens, options);
65
+ }
66
+ /**
67
+ * Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is
68
+ * successfully released. The response body will include the set of successfully released lockTokens, along
69
+ * with other failed lockTokens with their corresponding error information.
70
+ *
71
+ * @param lockTokens - Lock Tokens
72
+ * @param options - Options to release
73
+ *
74
+ */
75
+ releaseEvents(lockTokens, options = { requestOptions: {} }) {
76
+ return this._client.releaseCloudEvents(this._topicName, this._subscriptionName, lockTokens, Object.assign(Object.assign({}, options), { releaseDelayInSeconds: options.releaseDelay }));
77
+ }
78
+ /**
79
+ * Reject batch of Cloud Events.
80
+ *
81
+ * @param lockTokens - Lock Tokens
82
+ * @param options - Options to reject
83
+ *
84
+ */
85
+ rejectEvents(lockTokens, options = { requestOptions: {} }) {
86
+ return this._client.rejectCloudEvents(this._topicName, this._subscriptionName, lockTokens, options);
87
+ }
88
+ /**
89
+ * Renew lock for batch of Cloud Events.
90
+ *
91
+ * @param lockTokens - Lock Tokens
92
+ * @param options - Options to renew
93
+ */
94
+ renewEventLocks(lockTokens, options = { requestOptions: {} }) {
95
+ return this._client.renewCloudEventLocks(this._topicName, this._subscriptionName, lockTokens, options);
96
+ }
97
+ }
98
+ //# sourceMappingURL=eventGridReceiverClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventGridReceiverClient.js","sourceRoot":"","sources":["../../src/eventGridReceiverClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AASlC,OAAO,EAAE,eAAe,IAAI,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAW/F,OAAO,EAAE,0CAA0C,EAAE,MAAM,6CAA6C,CAAC;AACzG,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD;;GAEG;AACH,MAAM,OAAO,uBAAuB;IAKlC,uCAAuC;IACvC,YACE,QAAgB,EAChB,UAAgD,EAChD,SAAiB,EACjB,gBAAw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,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureKeyCredential, TokenCredential } from \"@azure/core-auth\";\nimport {\n AcknowledgeResult,\n ReleaseResult,\n RejectResult,\n RenewLocksResult,\n} from \"./cadl-generated/models\";\nimport { EventGridClient as EventGridClientGenerated } from \"./cadl-generated/EventGridClient\";\nimport {\n CloudEvent,\n ReceiveResult,\n AcknowledgeEventsOptions,\n ReleaseEventsOptions,\n RejectEventsOptions,\n RenewEventLocksOptions,\n EventGridReceiverClientOptions,\n ReceiveEventsOptions,\n} from \"./models\";\nimport { cloudEventDistributedTracingEnricherPolicy } from \"./cloudEventDistrubtedTracingEnricherPolicy\";\nimport { tracingPolicyName } from \"@azure/core-rest-pipeline\";\nimport { uint8ArrayToString } from \"@azure/core-util\";\n\n/**\n * Event Grid Namespaces Client\n */\nexport class EventGridReceiverClient {\n private _client: EventGridClientGenerated;\n private _topicName: string;\n private _subscriptionName: string;\n\n /** Azure Messaging EventGrid Client */\n constructor(\n endpoint: string,\n credential: AzureKeyCredential | TokenCredential,\n topicName: string,\n subscriptionName: string,\n options: EventGridReceiverClientOptions = {},\n ) {\n this._client = new EventGridClientGenerated(endpoint, credential, options);\n this._topicName = topicName;\n this._subscriptionName = subscriptionName;\n this._client.pipeline.addPolicy(cloudEventDistributedTracingEnricherPolicy(), {\n afterPolicies: [tracingPolicyName],\n });\n }\n\n /**\n * Receive Batch of Cloud Events from the Event Subscription.\n *\n * @param options - Options to receive\n *\n */\n async receiveEvents<T>(\n options: ReceiveEventsOptions = { requestOptions: {} },\n ): Promise<ReceiveResult<T>> {\n const result = await this._client.receiveCloudEvents(\n this._topicName,\n this._subscriptionName,\n options,\n );\n\n const modifiedResult: ReceiveResult<T> = {\n details: result.details.map((receiveDetails) => {\n const cloudEvent: CloudEvent<T> = {\n type: receiveDetails.event.type,\n source: receiveDetails.event.source,\n id: receiveDetails.event.id,\n time: receiveDetails.event.time,\n dataSchema: receiveDetails.event.dataschema,\n dataContentType: receiveDetails.event.datacontenttype,\n subject: receiveDetails.event.subject,\n specVersion: receiveDetails.event.specversion,\n data: receiveDetails.event.data\n ? (receiveDetails.event.data as T)\n : receiveDetails.event.dataBase64\n ? (uint8ArrayToString(receiveDetails.event.dataBase64, \"base64\") as T)\n : undefined,\n };\n return {\n brokerProperties: receiveDetails.brokerProperties,\n event: cloudEvent,\n };\n }),\n };\n\n return modifiedResult;\n }\n\n /**\n * Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least one\n * event is successfully acknowledged. The response body will include the set of successfully acknowledged\n * lockTokens, along with other failed lockTokens with their corresponding error information. Successfully\n * acknowledged events will no longer be available to any consumer.\n *\n * @param lockTokens - Lock Tokens\n * @param options - Options to Acknowledge\n *\n */\n acknowledgeEvents(\n lockTokens: string[],\n options: AcknowledgeEventsOptions = { requestOptions: {} },\n ): Promise<AcknowledgeResult> {\n return this._client.acknowledgeCloudEvents(\n this._topicName,\n this._subscriptionName,\n lockTokens,\n options,\n );\n }\n\n /**\n * Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one event is\n * successfully released. The response body will include the set of successfully released lockTokens, along\n * with other failed lockTokens with their corresponding error information.\n *\n * @param lockTokens - Lock Tokens\n * @param options - Options to release\n *\n */\n releaseEvents(\n lockTokens: string[],\n options: ReleaseEventsOptions = { requestOptions: {} },\n ): Promise<ReleaseResult> {\n return this._client.releaseCloudEvents(this._topicName, this._subscriptionName, lockTokens, {\n ...options,\n releaseDelayInSeconds: options.releaseDelay,\n });\n }\n\n /**\n * Reject batch of Cloud Events.\n *\n * @param lockTokens - Lock Tokens\n * @param options - Options to reject\n *\n */\n rejectEvents(\n lockTokens: string[],\n options: RejectEventsOptions = { requestOptions: {} },\n ): Promise<RejectResult> {\n return this._client.rejectCloudEvents(\n this._topicName,\n this._subscriptionName,\n lockTokens,\n options,\n );\n }\n\n /**\n * Renew lock for batch of Cloud Events.\n *\n * @param lockTokens - Lock Tokens\n * @param options - Options to renew\n */\n renewEventLocks(\n lockTokens: string[],\n options: RenewEventLocksOptions = { requestOptions: {} },\n ): Promise<RenewLocksResult> {\n return this._client.renewCloudEventLocks(\n this._topicName,\n this._subscriptionName,\n lockTokens,\n options,\n );\n }\n}\n"]}
@@ -0,0 +1,72 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ import { randomUUID } from "@azure/core-util";
4
+ import { EventGridClient as EventGridClientGenerated } from "./cadl-generated/EventGridClient";
5
+ import { cloudEventReservedPropertyNames, } from "./models";
6
+ import { cloudEventDistributedTracingEnricherPolicy } from "./cloudEventDistrubtedTracingEnricherPolicy";
7
+ import { tracingPolicyName } from "@azure/core-rest-pipeline";
8
+ /**
9
+ * Event Grid Namespaces Client
10
+ */
11
+ export class EventGridSenderClient {
12
+ /** Azure Messaging EventGrid Client */
13
+ constructor(endpoint, credential, topicName, options = {}) {
14
+ this._client = new EventGridClientGenerated(endpoint, credential, options);
15
+ this._topicName = topicName;
16
+ this._client.pipeline.addPolicy(cloudEventDistributedTracingEnricherPolicy(), {
17
+ afterPolicies: [tracingPolicyName],
18
+ });
19
+ }
20
+ /**
21
+ * Publish Cloud Events to namespace topic. In case of success, the server responds with an HTTP 200
22
+ * status code with an empty JSON object in response. Otherwise, the server can return various error codes.
23
+ * For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message
24
+ * is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for
25
+ * internal server error.
26
+ *
27
+ * @param events - Events to publish
28
+ * @param options - Options to publish
29
+ *
30
+ */
31
+ async sendEvents(events, options = { requestOptions: {} }) {
32
+ if (Array.isArray(events)) {
33
+ const eventsWireModel = [];
34
+ for (const individualevent of events) {
35
+ eventsWireModel.push(convertCloudEventToModelType(individualevent));
36
+ }
37
+ await this._client.publishCloudEvents(this._topicName, eventsWireModel, options);
38
+ }
39
+ else {
40
+ const cloudEventWireModel = convertCloudEventToModelType(events);
41
+ await this._client.publishCloudEvent(this._topicName, cloudEventWireModel, options);
42
+ }
43
+ }
44
+ }
45
+ export function convertCloudEventToModelType(event) {
46
+ var _a, _b, _c, _d, _e;
47
+ if (event.extensionAttributes) {
48
+ for (const propName in event.extensionAttributes) {
49
+ // Per the cloud events spec: "CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set"
50
+ // they also can not match an existing defined property name.
51
+ if (!/^[a-z0-9]*$/.test(propName) ||
52
+ cloudEventReservedPropertyNames.indexOf(propName) !== -1) {
53
+ throw new Error(`invalid extension attribute name: ${propName}`);
54
+ }
55
+ }
56
+ }
57
+ const converted = Object.assign({ specversion: (_a = event.specVersion) !== null && _a !== void 0 ? _a : "1.0", type: event.type, source: event.source, id: (_b = event.id) !== null && _b !== void 0 ? _b : randomUUID(), time: (_c = event.time) !== null && _c !== void 0 ? _c : new Date(), subject: event.subject, dataschema: event.dataSchema, datacontenttype: event.dataContentType }, ((_d = event.extensionAttributes) !== null && _d !== void 0 ? _d : []));
58
+ if (event.data instanceof Uint8Array) {
59
+ if (!event.dataContentType) {
60
+ throw new Error("a data content type must be provided when sending an event with binary data");
61
+ }
62
+ converted.datacontenttype = event.dataContentType;
63
+ converted.dataBase64 = event.data;
64
+ }
65
+ else {
66
+ converted.datacontenttype =
67
+ (_e = event.dataContentType) !== null && _e !== void 0 ? _e : "application/cloudevents+json; charset=utf-8";
68
+ converted.data = event.data;
69
+ }
70
+ return converted;
71
+ }
72
+ //# sourceMappingURL=eventGridSenderClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventGridSenderClient.js","sourceRoot":"","sources":["../../src/eventGridSenderClient.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,eAAe,IAAI,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAGL,+BAA+B,GAEhC,MAAM,UAAU,CAAC;AAClB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OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AzureKeyCredential, TokenCredential } from \"@azure/core-auth\";\nimport { CloudEvent as CloudEventWireModel } from \"./cadl-generated/models\";\nimport { randomUUID } from \"@azure/core-util\";\nimport { EventGridClient as EventGridClientGenerated } from \"./cadl-generated/EventGridClient\";\nimport {\n SendEventsOptions,\n CloudEvent,\n cloudEventReservedPropertyNames,\n EventGridSenderClientOptions,\n} from \"./models\";\nimport { cloudEventDistributedTracingEnricherPolicy } from \"./cloudEventDistrubtedTracingEnricherPolicy\";\nimport { tracingPolicyName } from \"@azure/core-rest-pipeline\";\n\n/**\n * Event Grid Namespaces Client\n */\nexport class EventGridSenderClient {\n private _client: EventGridClientGenerated;\n private _topicName: string;\n\n /** Azure Messaging EventGrid Client */\n constructor(\n endpoint: string,\n credential: AzureKeyCredential | TokenCredential,\n topicName: string,\n options: EventGridSenderClientOptions = {},\n ) {\n this._client = new EventGridClientGenerated(endpoint, credential, options);\n this._topicName = topicName;\n this._client.pipeline.addPolicy(cloudEventDistributedTracingEnricherPolicy(), {\n afterPolicies: [tracingPolicyName],\n });\n }\n\n /**\n * Publish Cloud Events to namespace topic. In case of success, the server responds with an HTTP 200\n * status code with an empty JSON object in response. Otherwise, the server can return various error codes.\n * For example, 401: which indicates authorization failure, 403: which indicates quota exceeded or message\n * is too large, 410: which indicates that specific topic is not found, 400: for bad request, and 500: for\n * internal server error.\n *\n * @param events - Events to publish\n * @param options - Options to publish\n *\n */\n async sendEvents<T>(\n events: CloudEvent<T>[] | CloudEvent<T>,\n options: SendEventsOptions = { requestOptions: {} },\n ): Promise<void> {\n if (Array.isArray(events)) {\n const eventsWireModel: Array<CloudEventWireModel> = [];\n for (const individualevent of events) {\n eventsWireModel.push(convertCloudEventToModelType(individualevent));\n }\n await this._client.publishCloudEvents(this._topicName, eventsWireModel, options);\n } else {\n const cloudEventWireModel: CloudEventWireModel = convertCloudEventToModelType(events);\n await this._client.publishCloudEvent(this._topicName, cloudEventWireModel, options);\n }\n }\n}\n\nexport function convertCloudEventToModelType<T>(event: CloudEvent<T>): CloudEventWireModel {\n if (event.extensionAttributes) {\n for (const propName in event.extensionAttributes) {\n // Per the cloud events spec: \"CloudEvents attribute names MUST consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set\"\n // they also can not match an existing defined property name.\n\n if (\n !/^[a-z0-9]*$/.test(propName) ||\n cloudEventReservedPropertyNames.indexOf(propName) !== -1\n ) {\n throw new Error(`invalid extension attribute name: ${propName}`);\n }\n }\n }\n\n const converted: CloudEventWireModel = {\n specversion: event.specVersion ?? \"1.0\",\n type: event.type,\n source: event.source,\n id: event.id ?? randomUUID(),\n time: event.time ?? new Date(),\n subject: event.subject,\n dataschema: event.dataSchema,\n datacontenttype: event.dataContentType,\n ...(event.extensionAttributes ?? []),\n };\n\n if (event.data instanceof Uint8Array) {\n if (!event.dataContentType) {\n throw new Error(\n \"a data content type must be provided when sending an event with binary data\",\n );\n }\n\n converted.datacontenttype = event.dataContentType;\n converted.dataBase64 = event.data;\n } else {\n converted.datacontenttype =\n event.dataContentType ?? \"application/cloudevents+json; charset=utf-8\";\n converted.data = event.data;\n }\n\n return converted;\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
3
  export { AzureKeyCredential } from "@azure/core-auth";
4
- export { EventGridNamespacesClient as EventGridClient } from "./eventGridNamespacesClient";
4
+ export { EventGridSenderClient } from "./eventGridSenderClient";
5
+ export { EventGridReceiverClient } from "./eventGridReceiverClient";
6
+ export { EventGridDeserializer } from "./consumer";
5
7
  //# 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,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAoBtD,OAAO,EAAE,yBAAyB,IAAI,eAAe,EAAE,MAAM,6BAA6B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureKeyCredential } from \"@azure/core-auth\";\n\nexport {\n ReceiveResult,\n ReceiveDetails,\n BrokerProperties,\n AcknowledgeResult,\n FailedLockToken,\n ReleaseResult,\n RejectResult,\n PublishCloudEventsOptions,\n ReceiveCloudEventsOptions,\n AcknowledgeCloudEventsOptions,\n ReleaseCloudEventsOptions,\n RejectCloudEventsOptions,\n ReleaseDelay,\n RenewCloudEventLocksOptions,\n RenewCloudEventLocksResult,\n} from \"./cadl-generated/models\";\n\nexport { EventGridNamespacesClient as EventGridClient } from \"./eventGridNamespacesClient\";\n\nexport { EventGridClientOptions } from \"./cadl-generated\";\n\nexport { PublishResultOutput } from \"./cadl-generated/rest\";\n\nexport { OperationOptions } from \"@azure-rest/core-client\";\n\nexport { CloudEvent, PublishCloudEventOptions } from \"./models\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAkBtD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAqBpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { AzureKeyCredential } from \"@azure/core-auth\";\n\nexport {\n BrokerProperties,\n AcknowledgeResult,\n FailedLockToken,\n ReleaseResult,\n RejectResult,\n ReleaseDelay,\n RenewLocksResult,\n AcknowledgeCloudEventsOptionalParams as AcknowledgeEventsOptionalParams,\n ReceiveCloudEventsOptionalParams as ReceiveEventsOptionalParams,\n RejectCloudEventsOptionalParams as RejectEventsOptionalParams,\n RenewCloudEventLocksOptionalParams as RenewEventLocksOptionalParams,\n PublishCloudEventsOptionalParams as SendEventsOptionalParams,\n PublishCloudEventOptionalParams as SendEventOptionalParams,\n} from \"./cadl-generated/models\";\n\nexport { EventGridSenderClient } from \"./eventGridSenderClient\";\n\nexport { EventGridReceiverClient } from \"./eventGridReceiverClient\";\n\nexport { EventGridClientOptions } from \"./cadl-generated\";\n\nexport { OperationOptions } from \"@azure-rest/core-client\";\n\nexport {\n CloudEvent,\n SendEventsOptions,\n ReceiveResult,\n ReceiveDetails,\n ReceiveEventsOptions,\n AcknowledgeEventsOptions,\n ReleaseEventsOptions,\n RejectEventsOptions,\n RenewEventLocksOptions,\n EventGridSenderClientOptions,\n EventGridReceiverClientOptions,\n KnownReleaseDelay,\n} from \"./models\";\n\nexport { EventGridDeserializer } from \"./consumer\";\n"]}
@@ -1,12 +1,12 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
3
  export const cloudEventReservedPropertyNames = [
4
- "specversion",
4
+ "specVersion",
5
5
  "id",
6
6
  "source",
7
7
  "type",
8
- "datacontenttype",
9
- "dataschema",
8
+ "dataContentType",
9
+ "dataSchema",
10
10
  "subject",
11
11
  "time",
12
12
  "data",
@@ -1 +1 @@
1
- {"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AA0DlC,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,aAAa;IACb,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,iBAAiB;IACjB,YAAY;IACZ,SAAS;IACT,MAAM;IACN,MAAM;CACP,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationOptions } from \"@azure-rest/core-client\";\n\nexport interface PublishCloudEventOptions extends OperationOptions {\n /** binary mode */\n binaryMode?: boolean;\n\n /** content type */\n contentType?: string;\n}\n\n/**\n * An event in the Cloud Event 1.0 schema.\n */\nexport interface CloudEvent<T> {\n /**\n * Type of event related to the originating occurrence.\n */\n type: string;\n /**\n * Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event.\n */\n source: string;\n /**\n * An identifier for the event. The combination of id and source must be unique for each distinct event.\n */\n id: string;\n /**\n * The time the event was generated.\n */\n time?: Date;\n /**\n * Identifies the schema that data adheres to.\n */\n dataschema?: string;\n /**\n * Content type of data value.\n */\n datacontenttype?: string;\n /**\n * Event data specific to the event type.\n */\n data?: T;\n /**\n * This describes the subject of the event in the context of the event producer (identified by source).\n */\n subject?: string;\n /**\n * Additional context attributes for the event. The Cloud Event specification refers to these as \"extension attributes\".\n */\n extensionAttributes?: Record<string, unknown>;\n /**\n * The version of the CloudEvents specification which the event uses.\n */\n specversion?: string | \"1.0\";\n}\n\nexport const cloudEventReservedPropertyNames = [\n \"specversion\",\n \"id\",\n \"source\",\n \"type\",\n \"datacontenttype\",\n \"dataschema\",\n \"subject\",\n \"time\",\n \"data\",\n];\n"]}
1
+ {"version":3,"file":"models.js","sourceRoot":"","sources":["../../src/models.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAgIlC,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC7C,aAAa;IACb,IAAI;IACJ,QAAQ;IACR,MAAM;IACN,iBAAiB;IACjB,YAAY;IACZ,SAAS;IACT,MAAM;IACN,MAAM;CACP,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { OperationOptions } from \"@azure-rest/core-client\";\nimport {\n BrokerProperties,\n PublishCloudEventOptionalParams,\n ReceiveCloudEventsOptionalParams,\n AcknowledgeCloudEventsOptionalParams,\n RejectCloudEventsOptionalParams,\n RenewCloudEventLocksOptionalParams,\n EventGridClientOptions as EventGridOptions,\n ReleaseDelay,\n} from \"./cadl-generated\";\n\n/** Send Event Options */\nexport interface SendEventOptions extends OperationOptions {\n /** Content type */\n contentType?: string;\n\n /** Topic name */\n topicName?: string;\n}\n\n/** Event Grid Sender Client Options */\nexport interface EventGridSenderClientOptions extends EventGridOptions {}\n\n/** Event Grid Receiver Client Options */\nexport interface EventGridReceiverClientOptions extends EventGridOptions {}\n\n/** Send Events Options */\nexport interface SendEventsOptions extends PublishCloudEventOptionalParams {}\n\n/** Receive Events Options */\nexport interface ReceiveEventsOptions extends ReceiveCloudEventsOptionalParams {}\n\n/** Acknowledge Events Options */\nexport interface AcknowledgeEventsOptions extends AcknowledgeCloudEventsOptionalParams {}\n\n/** Release Events Options */\nexport interface ReleaseEventsOptions extends OperationOptions {\n /** Release events with the specified delay in seconds. */\n releaseDelay?: ReleaseDelay;\n}\n\n/** Reject Events Options */\nexport interface RejectEventsOptions extends RejectCloudEventsOptionalParams {}\n\n/** Renew Event Locks Options */\nexport interface RenewEventLocksOptions extends RenewCloudEventLocksOptionalParams {}\n\n/** Known values of {@link ReleaseDelay} that the service accepts. */\nexport const enum KnownReleaseDelay {\n /** Ten Minutes */\n TenMinutes = \"600\",\n\n /** One Minute */\n OneMinute = \"60\",\n\n /** Ten Seconds */\n TenSeconds = \"10\",\n\n /** One Hour */\n OneHour = \"3600\",\n\n /** No Delay */\n NoDelay = \"0\",\n}\n\n/** Receive operation details per Cloud Event. */\nexport interface ReceiveDetails<T> {\n /** The Event Broker details. */\n brokerProperties: BrokerProperties;\n /** Cloud Event details. */\n event: CloudEvent<T>;\n}\n\n/**\n * An event in the Cloud Event 1.0 schema.\n */\nexport interface CloudEvent<T> {\n /**\n * Type of event related to the originating occurrence.\n */\n type: string;\n /**\n * Identifies the context in which an event happened. The combination of id and source must be unique for each distinct event.\n */\n source: string;\n /**\n * An identifier for the event. The combination of id and source must be unique for each distinct event.\n */\n id: string;\n /**\n * The time the event was generated.\n */\n time?: Date;\n /**\n * Identifies the schema that data adheres to.\n */\n dataSchema?: string;\n /**\n * Content type of data value.\n */\n dataContentType?: string;\n /**\n * Event data specific to the event type.\n */\n data?: T;\n /**\n * This describes the subject of the event in the context of the event producer (identified by source).\n */\n subject?: string;\n /**\n * Additional context attributes for the event. The Cloud Event specification refers to these as \"extension attributes\".\n */\n extensionAttributes?: Record<string, unknown>;\n /**\n * The version of the CloudEvents specification which the event uses.\n */\n specVersion?: string | \"1.0\";\n}\n\n/** Details of the Receive operation response. */\nexport interface ReceiveResult<T> {\n /** Array of receive responses, one per cloud event. */\n details: ReceiveDetails<T>[];\n}\n\nexport const cloudEventReservedPropertyNames = [\n \"specVersion\",\n \"id\",\n \"source\",\n \"type\",\n \"dataContentType\",\n \"dataSchema\",\n \"subject\",\n \"time\",\n \"data\",\n];\n"]}
@@ -0,0 +1,155 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ /**
4
+ * Stringifies a Date object in the format expected by the Event Grid service, for use in a Shared Access Signiture.
5
+ *
6
+ * The service expects this time string to be in the same format as what is returned by the .NET DateTime.ToString
7
+ * method, using the "en-US" culture.
8
+ *
9
+ * This corresponds to the .NET format string: "M/d/yyyy h:mm:ss tt". For example, the date "June 5th, 2020, 12:09:03 PM"
10
+ * is represented as the string "6/5/2020 12:09:03 PM"
11
+ *
12
+ * The service expects a UTC time, so this method returns a string based on the UTC time of the provided Date.
13
+ *
14
+ * @param d - The Date object to convert to a string.
15
+ */
16
+ export function dateToServiceTimeString(d) {
17
+ const month = d.getUTCMonth() + 1; // getUTCMonth returns 0-11 not 1-12.
18
+ const day = d.getUTCDate();
19
+ const year = d.getUTCFullYear();
20
+ const hour = d.getUTCHours() === 0 || d.getUTCHours() === 12 ? 12 : d.getUTCHours() % 12; // getUTCHours returns 0-23, and we want this in 12 hour format.
21
+ const minute = d.getUTCMinutes().toString().padStart(2, "0");
22
+ const second = d.getUTCSeconds().toString().padStart(2, "0");
23
+ const am = d.getUTCHours() >= 12 ? "PM" : "AM";
24
+ return `${month}/${day}/${year} ${hour}:${minute}:${second} ${am}`;
25
+ }
26
+ /**
27
+ * Returns `true` if the credential object is like the KeyCredential interface (i.e. it has a
28
+ * key property).
29
+ *
30
+ * @param credential - The object to test
31
+ */
32
+ export function isKeyCredentialLike(o) {
33
+ const castO = o;
34
+ return castO.key !== undefined;
35
+ }
36
+ export function parseAndWrap(jsonStringOrObject) {
37
+ if (typeof jsonStringOrObject === "string") {
38
+ const o = JSON.parse(jsonStringOrObject);
39
+ if (Array.isArray(o)) {
40
+ return o;
41
+ }
42
+ else {
43
+ return [o];
44
+ }
45
+ }
46
+ if (Array.isArray(jsonStringOrObject)) {
47
+ return jsonStringOrObject;
48
+ }
49
+ else {
50
+ return [jsonStringOrObject];
51
+ }
52
+ }
53
+ const CLOUD_EVENT_1_0_SPEC_VERSION = "1.0";
54
+ export function validateCloudEventEvent(o) {
55
+ validateRequiredStringProperties(o, ["type", "source", "id", "specVersion"]);
56
+ validateOptionalStringProperties(o, ["time", "dataSchema", "dataContentType", "subject"]);
57
+ if (typeof o !== "object") {
58
+ throw new TypeError("event is not an object");
59
+ }
60
+ const castO = o;
61
+ if (castO.specVersion !== CLOUD_EVENT_1_0_SPEC_VERSION) {
62
+ throw new Error("event is not in the Cloud Event 1.0 schema");
63
+ }
64
+ }
65
+ function validateRequiredStringProperties(o, propertyNames) {
66
+ for (const propertyName of propertyNames) {
67
+ if (typeof o[propertyName] === "undefined") {
68
+ throw new Error(`event is missing required property '${propertyName}'`);
69
+ }
70
+ if (typeof o[propertyName] !== "string") {
71
+ throw new TypeError(`event property '${propertyName} should be a 'string', but is '${typeof o[propertyName]}'`);
72
+ }
73
+ }
74
+ }
75
+ function validateOptionalStringProperties(o, propertyNames) {
76
+ for (const propertyName of propertyNames) {
77
+ if (typeof o[propertyName] !== "undefined" && typeof o[propertyName] !== "string") {
78
+ throw new TypeError(`event property '${propertyName}' should be a 'string' but it is a '${typeof o[propertyName]}'`);
79
+ }
80
+ }
81
+ }
82
+ export const CloudEvent = {
83
+ type: {
84
+ name: "Composite",
85
+ className: "CloudEvent",
86
+ additionalProperties: { type: { name: "Object" } },
87
+ modelProperties: {
88
+ id: {
89
+ serializedName: "id",
90
+ required: true,
91
+ type: {
92
+ name: "String",
93
+ },
94
+ },
95
+ source: {
96
+ serializedName: "source",
97
+ required: true,
98
+ type: {
99
+ name: "String",
100
+ },
101
+ },
102
+ data: {
103
+ serializedName: "data",
104
+ type: {
105
+ name: "any",
106
+ },
107
+ },
108
+ dataBase64: {
109
+ serializedName: "data_base64",
110
+ type: {
111
+ name: "ByteArray",
112
+ },
113
+ },
114
+ type: {
115
+ serializedName: "type",
116
+ required: true,
117
+ type: {
118
+ name: "String",
119
+ },
120
+ },
121
+ time: {
122
+ serializedName: "time",
123
+ type: {
124
+ name: "DateTime",
125
+ },
126
+ },
127
+ specversion: {
128
+ serializedName: "specversion",
129
+ required: true,
130
+ type: {
131
+ name: "String",
132
+ },
133
+ },
134
+ dataschema: {
135
+ serializedName: "dataschema",
136
+ type: {
137
+ name: "String",
138
+ },
139
+ },
140
+ datacontenttype: {
141
+ serializedName: "datacontenttype",
142
+ type: {
143
+ name: "String",
144
+ },
145
+ },
146
+ subject: {
147
+ serializedName: "subject",
148
+ type: {
149
+ name: "String",
150
+ },
151
+ },
152
+ },
153
+ },
154
+ };
155
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAKlC;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,uBAAuB,CAAC,CAAO;IAC7C,MAAM,KAAK,GAAG,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,CAAC,qCAAqC;IACxE,MAAM,GAAG,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC;IAC3B,MAAM,IAAI,GAAG,CAAC,CAAC,cAAc,EAAE,CAAC;IAEhC,MAAM,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CA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;iBACf;aACF;YACD,OAAO,EAAE;gBACP,cAAc,EAAE,SAAS;gBACzB,IAAI,EAAE;oBACJ,IAAI,EAAE,QAAQ;iBACf;aACF;SACF;KACF;CACF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { KeyCredential } from \"@azure/core-auth\";\nimport { CompositeMapper } from \"@azure/core-client\";\n\n/**\n * Stringifies a Date object in the format expected by the Event Grid service, for use in a Shared Access Signiture.\n *\n * The service expects this time string to be in the same format as what is returned by the .NET DateTime.ToString\n * method, using the \"en-US\" culture.\n *\n * This corresponds to the .NET format string: \"M/d/yyyy h:mm:ss tt\". For example, the date \"June 5th, 2020, 12:09:03 PM\"\n * is represented as the string \"6/5/2020 12:09:03 PM\"\n *\n * The service expects a UTC time, so this method returns a string based on the UTC time of the provided Date.\n *\n * @param d - The Date object to convert to a string.\n */\nexport function dateToServiceTimeString(d: Date): string {\n const month = d.getUTCMonth() + 1; // getUTCMonth returns 0-11 not 1-12.\n const day = d.getUTCDate();\n const year = d.getUTCFullYear();\n\n const hour = d.getUTCHours() === 0 || d.getUTCHours() === 12 ? 12 : d.getUTCHours() % 12; // getUTCHours returns 0-23, and we want this in 12 hour format.\n const minute = d.getUTCMinutes().toString().padStart(2, \"0\");\n const second = d.getUTCSeconds().toString().padStart(2, \"0\");\n const am = d.getUTCHours() >= 12 ? \"PM\" : \"AM\";\n\n return `${month}/${day}/${year} ${hour}:${minute}:${second} ${am}`;\n}\n\n/**\n * Returns `true` if the credential object is like the KeyCredential interface (i.e. it has a\n * key property).\n *\n * @param credential - The object to test\n */\nexport function isKeyCredentialLike(o: unknown): o is KeyCredential {\n const castO = o as {\n key: unknown;\n };\n return castO.key !== undefined;\n}\n\nexport function parseAndWrap(jsonStringOrObject: string | Record<string, unknown>): any[] {\n if (typeof jsonStringOrObject === \"string\") {\n const o = JSON.parse(jsonStringOrObject);\n if (Array.isArray(o)) {\n return o;\n } else {\n return [o];\n }\n }\n\n if (Array.isArray(jsonStringOrObject)) {\n return jsonStringOrObject;\n } else {\n return [jsonStringOrObject];\n }\n}\n\nconst CLOUD_EVENT_1_0_SPEC_VERSION = \"1.0\";\n\nexport function validateCloudEventEvent(o: unknown): void {\n validateRequiredStringProperties(o, [\"type\", \"source\", \"id\", \"specVersion\"]);\n validateOptionalStringProperties(o, [\"time\", \"dataSchema\", \"dataContentType\", \"subject\"]);\n\n if (typeof o !== \"object\") {\n throw new TypeError(\"event is not an object\");\n }\n\n const castO = o as {\n specVersion: unknown;\n };\n\n if (castO.specVersion !== CLOUD_EVENT_1_0_SPEC_VERSION) {\n throw new Error(\"event is not in the Cloud Event 1.0 schema\");\n }\n}\n\nfunction validateRequiredStringProperties(o: any, propertyNames: string[]): void {\n for (const propertyName of propertyNames) {\n if (typeof o[propertyName] === \"undefined\") {\n throw new Error(`event is missing required property '${propertyName}'`);\n }\n\n if (typeof o[propertyName] !== \"string\") {\n throw new TypeError(\n `event property '${propertyName} should be a 'string', but is '${typeof o[propertyName]}'`,\n );\n }\n }\n}\n\nfunction validateOptionalStringProperties(o: any, propertyNames: string[]): void {\n for (const propertyName of propertyNames) {\n if (typeof o[propertyName] !== \"undefined\" && typeof o[propertyName] !== \"string\") {\n throw new TypeError(\n `event property '${propertyName}' should be a 'string' but it is a '${typeof o[\n propertyName\n ]}'`,\n );\n }\n }\n}\n\nexport const CloudEvent: CompositeMapper = {\n type: {\n name: \"Composite\",\n className: \"CloudEvent\",\n additionalProperties: { type: { name: \"Object\" } },\n modelProperties: {\n id: {\n serializedName: \"id\",\n required: true,\n type: {\n name: \"String\",\n },\n },\n source: {\n serializedName: \"source\",\n required: true,\n type: {\n name: \"String\",\n },\n },\n data: {\n serializedName: \"data\",\n type: {\n name: \"any\",\n },\n },\n dataBase64: {\n serializedName: \"data_base64\",\n type: {\n name: \"ByteArray\",\n },\n },\n type: {\n serializedName: \"type\",\n required: true,\n type: {\n name: \"String\",\n },\n },\n time: {\n serializedName: \"time\",\n type: {\n name: \"DateTime\",\n },\n },\n specversion: {\n serializedName: \"specversion\",\n required: true,\n type: {\n name: \"String\",\n },\n },\n dataschema: {\n serializedName: \"dataschema\",\n type: {\n name: \"String\",\n },\n },\n datacontenttype: {\n serializedName: \"datacontenttype\",\n type: {\n name: \"String\",\n },\n },\n subject: {\n serializedName: \"subject\",\n type: {\n name: \"String\",\n },\n },\n },\n },\n};\n"]}
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "sdk-type": "client",
4
4
  "author": "Microsoft Corporation",
5
5
  "description": "An isomorphic client library for the Azure Event Grid service.",
6
- "version": "1.0.0-beta.1",
6
+ "version": "1.0.0",
7
7
  "keywords": [
8
8
  "node",
9
9
  "azure",
@@ -47,19 +47,19 @@
47
47
  "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
48
48
  "build:browser": "tsc -p . && dev-tool run bundle",
49
49
  "build:node": "tsc -p . && dev-tool run bundle",
50
- "build:samples": "echo Obsolete",
50
+ "build:samples": "dev-tool samples publish -f",
51
51
  "build:test": "tsc -p . && dev-tool run bundle",
52
- "build": "npm run clean && tsc -p . && dev-tool run bundle && api-extractor run --local",
52
+ "build": "npm run clean && tsc -p . && dev-tool run bundle && dev-tool run extract-api",
53
53
  "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
54
54
  "clean": "rimraf --glob dist dist-browser dist-esm dist-test temp types *.tgz *.log",
55
55
  "execute:samples": "dev-tool samples run samples-dev",
56
- "extract-api": "tsc -p . && api-extractor run --local",
56
+ "extract-api": "tsc -p . && dev-tool run extract-api",
57
57
  "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
58
58
  "integration-test:browser": "dev-tool run test:browser",
59
59
  "integration-test:node": "dev-tool run test:node-js-input -- --timeout 5000000 \"dist-esm/test/**/*.spec.js\"",
60
60
  "integration-test": "npm run integration-test:node && npm run integration-test:browser",
61
- "lint:fix": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js --fix --fix-type [problem,suggestion]",
62
- "lint": "eslint package.json api-extractor.json README.md src test --ext .ts,.javascript,.js",
61
+ "lint:fix": "eslint package.json api-extractor.json src test --ext .ts --ext .cts --ext .mts --fix --fix-type [problem,suggestion]",
62
+ "lint": "eslint package.json api-extractor.json src test --ext .ts --ext .cts --ext .mts",
63
63
  "pack": "npm pack 2>&1",
64
64
  "test:browser": "npm run clean && npm run build:test && npm run unit-test:browser",
65
65
  "test:node": "npm run clean && npm run build:test && npm run unit-test:node",
@@ -76,6 +76,7 @@
76
76
  "@azure-rest/core-client": "^1.3.1",
77
77
  "@azure/logger": "^1.0.0",
78
78
  "@azure/core-util": "^1.6.1",
79
+ "@azure/eventgrid": "^5.4.0",
79
80
  "buffer": "^6.0.0",
80
81
  "tslib": "^2.2.0"
81
82
  },
@@ -85,7 +86,7 @@
85
86
  "@azure/dev-tool": "^1.0.0",
86
87
  "@azure/eslint-plugin-azure-sdk": "^3.0.0",
87
88
  "@azure/service-bus": "^7.0.0",
88
- "@azure/test-utils": "^1.0.0",
89
+ "@azure-tools/test-utils": "^1.0.1",
89
90
  "@azure-tools/test-recorder": "^3.0.0",
90
91
  "@microsoft/api-extractor": "^7.31.1",
91
92
  "@types/chai": "^4.1.6",
@@ -109,12 +110,11 @@
109
110
  "karma-mocha-reporter": "^2.2.5",
110
111
  "karma-sourcemap-loader": "^0.3.8",
111
112
  "mocha": "^10.0.0",
112
- "c8": "^9.1.0",
113
- "prettier": "^2.5.1",
113
+ "nyc": "^15.1.0",
114
114
  "rimraf": "^5.0.5",
115
115
  "sinon": "^17.0.0",
116
116
  "source-map-support": "^0.5.9",
117
117
  "ts-node": "^10.0.0",
118
- "typescript": "~5.3.3"
118
+ "typescript": "~5.4.5"
119
119
  }
120
120
  }