@azure/web-pubsub-express 1.0.6-alpha.20240528.1 → 1.0.6-alpha.20240815.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/commonjs/cloudEventsDispatcher.d.ts +15 -0
  2. package/dist/commonjs/cloudEventsDispatcher.d.ts.map +1 -0
  3. package/dist/commonjs/cloudEventsDispatcher.js +281 -0
  4. package/dist/commonjs/cloudEventsDispatcher.js.map +1 -0
  5. package/dist/commonjs/cloudEventsProtocols.d.ts +238 -0
  6. package/dist/commonjs/cloudEventsProtocols.d.ts.map +1 -0
  7. package/dist/commonjs/cloudEventsProtocols.js +5 -0
  8. package/dist/commonjs/cloudEventsProtocols.js.map +1 -0
  9. package/dist/commonjs/index.d.ts +3 -0
  10. package/dist/commonjs/index.d.ts.map +1 -0
  11. package/dist/{index.js → commonjs/index.js} +2 -2
  12. package/dist/commonjs/index.js.map +1 -0
  13. package/dist/commonjs/logger.d.ts +7 -0
  14. package/dist/commonjs/logger.d.ts.map +1 -0
  15. package/dist/commonjs/logger.js +13 -0
  16. package/dist/commonjs/logger.js.map +1 -0
  17. package/dist/commonjs/package.json +3 -0
  18. package/dist/commonjs/tsdoc-metadata.json +11 -0
  19. package/dist/commonjs/utils.d.ts +6 -0
  20. package/dist/commonjs/utils.d.ts.map +1 -0
  21. package/dist/commonjs/utils.js +59 -0
  22. package/dist/commonjs/utils.js.map +1 -0
  23. package/dist/commonjs/webPubSubEventHandler.d.ts +47 -0
  24. package/dist/commonjs/webPubSubEventHandler.d.ts.map +1 -0
  25. package/dist/commonjs/webPubSubEventHandler.js +78 -0
  26. package/dist/commonjs/webPubSubEventHandler.js.map +1 -0
  27. package/dist/esm/cloudEventsDispatcher.d.ts +15 -0
  28. package/dist/esm/cloudEventsDispatcher.d.ts.map +1 -0
  29. package/{dist-esm/src → dist/esm}/cloudEventsDispatcher.js +3 -3
  30. package/dist/esm/cloudEventsDispatcher.js.map +1 -0
  31. package/dist/esm/cloudEventsProtocols.d.ts +238 -0
  32. package/dist/esm/cloudEventsProtocols.d.ts.map +1 -0
  33. package/dist/esm/index.d.ts +3 -0
  34. package/dist/esm/index.d.ts.map +1 -0
  35. package/dist/esm/index.js +5 -0
  36. package/{dist-esm/src → dist/esm}/index.js.map +1 -1
  37. package/dist/esm/logger.d.ts +7 -0
  38. package/dist/esm/logger.d.ts.map +1 -0
  39. package/dist/esm/package.json +3 -0
  40. package/dist/esm/utils.d.ts +6 -0
  41. package/dist/esm/utils.d.ts.map +1 -0
  42. package/{dist-esm/src → dist/esm}/utils.js.map +1 -1
  43. package/dist/esm/webPubSubEventHandler.d.ts +47 -0
  44. package/dist/esm/webPubSubEventHandler.d.ts.map +1 -0
  45. package/{dist-esm/src → dist/esm}/webPubSubEventHandler.js +1 -1
  46. package/dist/esm/webPubSubEventHandler.js.map +1 -0
  47. package/package.json +43 -28
  48. package/dist/index.js.map +0 -1
  49. package/dist-esm/samples-dev/server.js +0 -32
  50. package/dist-esm/samples-dev/server.js.map +0 -1
  51. package/dist-esm/src/cloudEventsDispatcher.js.map +0 -1
  52. package/dist-esm/src/index.js +0 -5
  53. package/dist-esm/src/webPubSubEventHandler.js.map +0 -1
  54. package/dist-esm/test/connect.spec.js +0 -179
  55. package/dist-esm/test/connect.spec.js.map +0 -1
  56. package/dist-esm/test/connected.spec.js +0 -85
  57. package/dist-esm/test/connected.spec.js.map +0 -1
  58. package/dist-esm/test/ctor.spec.js +0 -27
  59. package/dist-esm/test/ctor.spec.js.map +0 -1
  60. package/dist-esm/test/disconnected.spec.js +0 -85
  61. package/dist-esm/test/disconnected.spec.js.map +0 -1
  62. package/dist-esm/test/user.spec.js +0 -300
  63. package/dist-esm/test/user.spec.js.map +0 -1
  64. package/dist-esm/test/validate.spec.js +0 -51
  65. package/dist-esm/test/validate.spec.js.map +0 -1
  66. /package/{dist-esm/src → dist/esm}/cloudEventsProtocols.js +0 -0
  67. /package/{dist-esm/src → dist/esm}/cloudEventsProtocols.js.map +0 -0
  68. /package/{dist-esm/src → dist/esm}/logger.js +0 -0
  69. /package/{dist-esm/src → dist/esm}/logger.js.map +0 -0
  70. /package/{dist-esm/src → dist/esm}/utils.js +0 -0
  71. /package/{types → dist}/web-pubsub-express.d.ts +0 -0
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Response of the connect event.
3
+ */
4
+ export interface ConnectResponse {
5
+ /**
6
+ * Set the groups the connection would like to join.
7
+ */
8
+ groups?: string[];
9
+ /**
10
+ * Set the roles the connection belongs to.
11
+ */
12
+ roles?: string[];
13
+ /**
14
+ * Set the userId for the connection.
15
+ */
16
+ userId?: string;
17
+ /**
18
+ * Set the subprotocol for the connection to complete WebSocket handshake.
19
+ */
20
+ subprotocol?: string;
21
+ }
22
+ /**
23
+ * The connection context representing the client WebSocket connection.
24
+ */
25
+ export interface ConnectionContext {
26
+ /**
27
+ * The hub the connection belongs to.
28
+ */
29
+ hub: string;
30
+ /**
31
+ * The Id of the connection.
32
+ */
33
+ connectionId: string;
34
+ /**
35
+ * The event name of this CloudEvents request.
36
+ */
37
+ eventName: string;
38
+ /**
39
+ * The origin this CloudEvents request comes from.
40
+ */
41
+ origin: string;
42
+ /**
43
+ * The user id of the connection.
44
+ */
45
+ userId?: string;
46
+ /**
47
+ * The subprotocol of this connection.
48
+ */
49
+ subprotocol?: string;
50
+ /**
51
+ * Get the additional states for the connection, such states are perserved throughout the lifetime of the connection.
52
+ */
53
+ states: Record<string, any>;
54
+ }
55
+ /**
56
+ * Request for the connect event.
57
+ */
58
+ export interface ConnectRequest {
59
+ /**
60
+ * The context of current CloudEvents request.
61
+ */
62
+ context: ConnectionContext;
63
+ /**
64
+ * The claims that the client WebSocket connection has when it connects.
65
+ */
66
+ claims?: Record<string, string[]>;
67
+ /**
68
+ * The query that the client WebSocket connection has when it connects.
69
+ * @deprecated Please use queries instead.
70
+ */
71
+ query?: Record<string, string[]>;
72
+ /**
73
+ * The queries that the client WebSocket connection has when it connects.
74
+ */
75
+ queries?: Record<string, string[]>;
76
+ /**
77
+ * The headers that the client WebSocket connection has when it connects.
78
+ */
79
+ headers?: Record<string, string[]>;
80
+ /**
81
+ * The subprotocols that the client WebSocket connection uses to do handshake.
82
+ */
83
+ subprotocols?: string[];
84
+ /**
85
+ * The client certificate info that the client WebSocket connection uses to connect.
86
+ */
87
+ clientCertificates?: Certificate[];
88
+ }
89
+ /**
90
+ * The client certificate.
91
+ */
92
+ export interface Certificate {
93
+ /**
94
+ * The thumbprint of the certificate.
95
+ */
96
+ thumbprint: string;
97
+ }
98
+ /**
99
+ * Request for the connected event.
100
+ */
101
+ export interface ConnectedRequest {
102
+ /**
103
+ * The context of current CloudEvents request.
104
+ */
105
+ context: ConnectionContext;
106
+ }
107
+ /**
108
+ * Request for the user event.
109
+ */
110
+ export type UserEventRequest = {
111
+ /**
112
+ * The context of current CloudEvents request.
113
+ */
114
+ context: ConnectionContext;
115
+ /**
116
+ * The content data.
117
+ */
118
+ data: string;
119
+ /**
120
+ * The type of the data.
121
+ */
122
+ dataType: "text";
123
+ } | {
124
+ /**
125
+ * The context of current CloudEvents request.
126
+ */
127
+ context: ConnectionContext;
128
+ /**
129
+ * The content data, when data type is `json`, the data is the result of JSON.parse, so the type of the data depends on user scenarios
130
+ */
131
+ data: unknown;
132
+ /**
133
+ * The type of the data.
134
+ */
135
+ dataType: "json";
136
+ } | {
137
+ /**
138
+ * The context of current CloudEvents request.
139
+ */
140
+ context: ConnectionContext;
141
+ /**
142
+ * The content data.
143
+ */
144
+ data: ArrayBuffer;
145
+ /**
146
+ * The type of the data.
147
+ */
148
+ dataType: "binary";
149
+ };
150
+ /**
151
+ * Request for the disconnected event.
152
+ */
153
+ export interface DisconnectedRequest {
154
+ /**
155
+ * The context of current CloudEvents request.
156
+ */
157
+ context: ConnectionContext;
158
+ /**
159
+ * The reason that the connection disconnects.
160
+ */
161
+ reason?: string;
162
+ }
163
+ /**
164
+ * The handler to set connect event response
165
+ */
166
+ export interface ConnectResponseHandler {
167
+ /**
168
+ * Set the state of the connection
169
+ * @param name - The name of the state
170
+ * @param value - The value of the state
171
+ */
172
+ setState(name: string, value: unknown): void;
173
+ /**
174
+ * Return success response to the service.
175
+ * @param response - The response for the connect event.
176
+ */
177
+ success(response?: ConnectResponse): void;
178
+ /**
179
+ * Return failed response and the service will reject the client WebSocket connection.
180
+ * @param code - Code can be 400 user error, 401 unauthorized and 500 server error.
181
+ * @param detail - The detail of the error.
182
+ */
183
+ fail(code: 400 | 401 | 500, detail?: string): void;
184
+ }
185
+ /**
186
+ * The handler to set user event response
187
+ */
188
+ export interface UserEventResponseHandler {
189
+ /**
190
+ * Set the state of the connection
191
+ * @param name - The name of the state
192
+ * @param value - The value of the state
193
+ */
194
+ setState(name: string, value: unknown): void;
195
+ /**
196
+ * Return success response with data to be delivered to the client WebSocket connection.
197
+ * @param data - The payload data to be returned to the client. Stringify the message if it is a JSON object.
198
+ * @param dataType - The type of the payload data.
199
+ */
200
+ success(data?: string | ArrayBuffer, dataType?: "binary" | "text" | "json"): void;
201
+ /**
202
+ * Return failed response and the service will close the client WebSocket connection.
203
+ * @param code - Code can be 400 user error, 401 unauthorized and 500 server error.
204
+ * @param detail - The detail of the error.
205
+ */
206
+ fail(code: 400 | 401 | 500, detail?: string): void;
207
+ }
208
+ /**
209
+ * The options for the CloudEvents handler.
210
+ */
211
+ export interface WebPubSubEventHandlerOptions {
212
+ /**
213
+ * Custom serving path for the path of the CloudEvents handler.
214
+ */
215
+ path?: string;
216
+ /**
217
+ * Handle 'connect' event, the service waits for the response to proceed.
218
+ */
219
+ handleConnect?: (connectRequest: ConnectRequest, connectResponse: ConnectResponseHandler) => void;
220
+ /**
221
+ * Handle user events, the service waits for the response to proceed.
222
+ */
223
+ handleUserEvent?: (userEventRequest: UserEventRequest, userEventResponse: UserEventResponseHandler) => void;
224
+ /**
225
+ * Event trigger for "connected" unblocking event. This is an unblocking event and the service does not wait for the response.
226
+ */
227
+ onConnected?: (connectedRequest: ConnectedRequest) => void;
228
+ /**
229
+ *
230
+ * Event triggers for "disconnected" unblocking event. This is an unblocking event and the service does not wait for the response.
231
+ */
232
+ onDisconnected?: (disconnectedRequest: DisconnectedRequest) => void;
233
+ /**
234
+ * If not specified, by default allow all the endpoints, otherwise only allow specified endpoints
235
+ */
236
+ allowedEndpoints?: string[];
237
+ }
238
+ //# sourceMappingURL=cloudEventsProtocols.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudEventsProtocols.d.ts","sourceRoot":"","sources":["../../src/cloudEventsProtocols.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,EAAE,iBAAiB,CAAC;IAC3B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAClC;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,C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.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,cAAc,2BAA2B,CAAC"}
@@ -0,0 +1,5 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT license.
3
+ export { WebPubSubEventHandler } from "./webPubSubEventHandler.js";
4
+ export * from "./cloudEventsProtocols.js";
5
+ //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,cAAc,wBAAwB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nexport { WebPubSubEventHandler } from \"./webPubSubEventHandler\";\n\nexport * from \"./cloudEventsProtocols\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAEnE,cAAc,2BAA2B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nexport { WebPubSubEventHandler } from \"./webPubSubEventHandler.js\";\n\nexport * from \"./cloudEventsProtocols.js\";\n"]}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The \@azure/logger configuration for this package.
3
+ *
4
+ * @internal
5
+ */
6
+ export declare const logger: import("@azure/logger").AzureLogger;
7
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,eAAO,MAAM,MAAM,qCAA2C,CAAC"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,6 @@
1
+ import { IncomingMessage } from "node:http";
2
+ export declare function toBase64JsonString(obj: Record<string, any>): string;
3
+ export declare function fromBase64JsonString(base64String: string | undefined): Record<string, any>;
4
+ export declare function getHttpHeader(req: IncomingMessage, key: string): string | undefined;
5
+ export declare function readRequestBody(req: IncomingMessage): Promise<Buffer>;
6
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAM5C,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAEnE;AAED,wBAAgB,oBAAoB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAa1F;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAcnF;AAED,wBAAgB,eAAe,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,SAAS,YAAY,CAAC,GAAQ;IAC5B,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,GAAwB;IACzD,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAA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C,EAAE,CAAC,KAAK,EAAE;YACZ,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACrC,OAAO,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,0BAA0B;QAC1B,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG;YAC3B,kEAAkE;YAClE,MAAM,CAAC,GAAG,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { IncomingMessage } from \"http\";\n\nfunction isJsonObject(obj: any): boolean {\n return obj && typeof obj === \"object\" && !Array.isArray(obj);\n}\n\nexport function toBase64JsonString(obj: Record<string, any>): string {\n return Buffer.from(JSON.stringify(obj)).toString(\"base64\");\n}\n\nexport function fromBase64JsonString(base64String: string | undefined): Record<string, any> {\n if (base64String === undefined) {\n return {};\n }\n\n try {\n const buf = Buffer.from(base64String, \"base64\").toString();\n const parsed = JSON.parse(buf);\n return isJsonObject(parsed) ? parsed : {};\n } catch (e: any) {\n console.warn(\"Unexpected state format:\" + e);\n return {};\n }\n}\n\nexport function getHttpHeader(req: IncomingMessage, key: string): string | undefined {\n if (!key) return undefined;\n\n // According to https://nodejs.org/api/http.html#http_class_http_incomingmessage, header names are always lower-cased\n const value = req.headers[key.toLowerCase()];\n\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\") {\n return value;\n }\n\n return value[0];\n}\n\nexport function readRequestBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise(function (resolve, reject) {\n const chunks: any = [];\n req.on(\"data\", function (chunk) {\n chunks.push(chunk);\n });\n req.on(\"end\", function () {\n const buffer = Buffer.concat(chunks);\n resolve(buffer);\n });\n // reject on request error\n req.on(\"error\", function (err) {\n // This is not a \"Second reject\", just a different sort of failure\n reject(err);\n });\n });\n}\n"]}
1
+ {"version":3,"file":"utils.js","s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,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,GAAoB;IAClD,OAAO,IAAI,OAAO,CAAC,UAAU,OAAO,EAAE,MAAM;QAC1C,MAAM,MAAM,GAAQ,EAAE,CAAC;QACvB,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK;YAC5B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE;YACZ,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACrC,OAAO,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,0BAA0B;QAC1B,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,UAAU,GAAG;YAC3B,kEAAkE;YAClE,MAAM,CAAC,GAAG,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { IncomingMessage } from \"node:http\";\n\nfunction isJsonObject(obj: any): boolean {\n return obj && typeof obj === \"object\" && !Array.isArray(obj);\n}\n\nexport function toBase64JsonString(obj: Record<string, any>): string {\n return Buffer.from(JSON.stringify(obj)).toString(\"base64\");\n}\n\nexport function fromBase64JsonString(base64String: string | undefined): Record<string, any> {\n if (base64String === undefined) {\n return {};\n }\n\n try {\n const buf = Buffer.from(base64String, \"base64\").toString();\n const parsed = JSON.parse(buf);\n return isJsonObject(parsed) ? parsed : {};\n } catch (e: any) {\n console.warn(\"Unexpected state format:\" + e);\n return {};\n }\n}\n\nexport function getHttpHeader(req: IncomingMessage, key: string): string | undefined {\n if (!key) return undefined;\n\n // According to https://nodejs.org/api/http.html#http_class_http_incomingmessage, header names are always lower-cased\n const value = req.headers[key.toLowerCase()];\n\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\") {\n return value;\n }\n\n return value[0];\n}\n\nexport function readRequestBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise(function (resolve, reject) {\n const chunks: any = [];\n req.on(\"data\", function (chunk) {\n chunks.push(chunk);\n });\n req.on(\"end\", function () {\n const buffer = Buffer.concat(chunks);\n resolve(buffer);\n });\n // reject on request error\n req.on(\"error\", function (err) {\n // This is not a \"Second reject\", just a different sort of failure\n reject(err);\n });\n });\n}\n"]}
@@ -0,0 +1,47 @@
1
+ import express from "express-serve-static-core";
2
+ import { WebPubSubEventHandlerOptions } from "./cloudEventsProtocols.js";
3
+ /**
4
+ * The handler to handle incoming CloudEvents messages
5
+ */
6
+ export declare class WebPubSubEventHandler {
7
+ private hub;
8
+ /**
9
+ * The path this CloudEvents handler listens to
10
+ */
11
+ readonly path: string;
12
+ private _cloudEventsHandler;
13
+ /**
14
+ * Creates an instance of a WebPubSubEventHandler for handling incoming CloudEvents messages.
15
+ *
16
+ * Example usage:
17
+ * ```ts
18
+ * import express from "express";
19
+ * import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
20
+ * const endpoint = "https://xxxx.webpubsubdev.azure.com"
21
+ * const handler = new WebPubSubEventHandler('chat', {
22
+ * handleConnect: (req, res) => {
23
+ * console.log(JSON.stringify(req));
24
+ * return {};
25
+ * },
26
+ * onConnected: req => {
27
+ * console.log(JSON.stringify(req));
28
+ * },
29
+ * handleUserEvent: (req, res) => {
30
+ * console.log(JSON.stringify(req));
31
+ * res.success("Hey " + req.data, req.dataType);
32
+ * };
33
+ * allowedEndpoints: [ endpoint ]
34
+ * },
35
+ * });
36
+ * ```
37
+ *
38
+ * @param hub - The name of the hub to listen to
39
+ * @param options - Options to configure the event handler
40
+ */
41
+ constructor(hub: string, options?: WebPubSubEventHandlerOptions);
42
+ /**
43
+ * Get the middleware to process the CloudEvents requests
44
+ */
45
+ getMiddleware(): express.RequestHandler;
46
+ }
47
+ //# sourceMappingURL=webPubSubEventHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webPubSubEventHandler.d.ts","sourceRoot":"","sources":["../../src/webPubSubEventHandler.ts"],"names":[],"mappings":"AAGA,OAAO,OAAO,MAAM,2BAA2B,CAAC;AAGhD,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AAEzE;;GAEG;AACH,qBAAa,qBAAqB;IAqC9B,OAAO,CAAC,GAAG;IApCb;;OAEG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAC;IAE7B,OAAO,CAAC,mBAAmB,CAAwB;IAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;gBAEO,GAAG,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE,4BAA4B;IAOxC;;OAEG;IACI,aAAa,IAAI,OAAO,CAAC,cAAc;CA+B/C"}
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT license.
3
- import { CloudEventsDispatcher } from "./cloudEventsDispatcher";
3
+ import { CloudEventsDispatcher } from "./cloudEventsDispatcher.js";
4
4
  /**
5
5
  * The handler to handle incoming CloudEvents messages
6
6
  */
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webPubSubEventHandler.js","sourceRoot":"","sources":["../../src/webPubSubEventHandler.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAIlC,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AAGnE;;GAEG;AACH,MAAM,OAAO,qBAAqB;IAQhC;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,YACU,GAAW,EACnB,OAAsC;;QAD9B,QAAG,GAAH,GAAG,CAAQ;QAGnB,MAAM,IAAI,GAAG,CAAC,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,mCAAI,uBAAuB,GAAG,GAAG,CAAC,CAAC,WAAW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sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport express from \"express-serve-static-core\";\n\nimport { CloudEventsDispatcher } from \"./cloudEventsDispatcher.js\";\nimport { WebPubSubEventHandlerOptions } from \"./cloudEventsProtocols.js\";\n\n/**\n * The handler to handle incoming CloudEvents messages\n */\nexport class WebPubSubEventHandler {\n /**\n * The path this CloudEvents handler listens to\n */\n public readonly path: string;\n\n private _cloudEventsHandler: CloudEventsDispatcher;\n\n /**\n * Creates an instance of a WebPubSubEventHandler for handling incoming CloudEvents messages.\n *\n * Example usage:\n * ```ts\n * import express from \"express\";\n * import { WebPubSubEventHandler } from \"@azure/web-pubsub-express\";\n * const endpoint = \"https://xxxx.webpubsubdev.azure.com\"\n * const handler = new WebPubSubEventHandler('chat', {\n * handleConnect: (req, res) => {\n * console.log(JSON.stringify(req));\n * return {};\n * },\n * onConnected: req => {\n * console.log(JSON.stringify(req));\n * },\n * handleUserEvent: (req, res) => {\n * console.log(JSON.stringify(req));\n * res.success(\"Hey \" + req.data, req.dataType);\n * };\n * allowedEndpoints: [ endpoint ]\n * },\n * });\n * ```\n *\n * @param hub - The name of the hub to listen to\n * @param options - Options to configure the event handler\n */\n constructor(\n private hub: string,\n options?: WebPubSubEventHandlerOptions,\n ) {\n const path = (options?.path ?? `/api/webpubsub/hubs/${hub}/`).toLowerCase();\n this.path = path.endsWith(\"/\") ? path : path + \"/\";\n this._cloudEventsHandler = new CloudEventsDispatcher(this.hub, options);\n }\n\n /**\n * Get the middleware to process the CloudEvents requests\n */\n public getMiddleware(): express.RequestHandler {\n return async (\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n ): Promise<void> => {\n // Request originalUrl can contain query while baseUrl + path not\n let requestUrl = (req.baseUrl + req.path).toLowerCase();\n\n // normalize the Url\n requestUrl = requestUrl.endsWith(\"/\") ? requestUrl : requestUrl + \"/\";\n if (requestUrl.startsWith(this.path)) {\n if (req.method === \"OPTIONS\") {\n if (this._cloudEventsHandler.handlePreflight(req, res)) {\n return;\n }\n } else if (req.method === \"POST\") {\n try {\n if (await this._cloudEventsHandler.handleRequest(req, res)) {\n return;\n }\n } catch (err: any) {\n next(err);\n return;\n }\n }\n }\n\n next();\n };\n }\n}\n"]}
package/package.json CHANGED
@@ -1,23 +1,20 @@
1
1
  {
2
2
  "name": "@azure/web-pubsub-express",
3
- "version": "1.0.6-alpha.20240528.1",
3
+ "version": "1.0.6-alpha.20240815.1",
4
4
  "description": "Azure Web PubSub CloudEvents handlers",
5
5
  "sdk-type": "client",
6
- "main": "dist/index.js",
7
- "module": "dist-esm/src/index.js",
8
- "types": "types/web-pubsub-express.d.ts",
9
6
  "scripts": {
10
7
  "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
11
8
  "build:browser": "echo \"Browser is not supported.\" && exit 0",
12
- "build:node": "tsc -p . && dev-tool run bundle --browser-test=false",
9
+ "build:node": "tshy",
13
10
  "build:samples": "echo Obsolete.",
14
- "build:test": "tsc -p . && dev-tool run bundle --browser-test=false",
15
- "build": "npm run clean && tsc -p . && dev-tool run bundle --browser-test=false && dev-tool run extract-api",
11
+ "build:test": "tshy",
12
+ "build": "npm run clean && tshy && dev-tool run bundle --browser-test=false && dev-tool run extract-api",
16
13
  "check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
17
14
  "format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
18
15
  "clean": "rimraf --glob dist dist-esm test-dist temp types *.tgz *.log",
19
16
  "execute:samples": "dev-tool samples run samples-dev",
20
- "extract-api": "tsc -p . && dev-tool run extract-api",
17
+ "extract-api": "tshy && dev-tool run extract-api",
21
18
  "integration-test:browser": "echo \"Browser is not supported.\" && exit 0",
22
19
  "integration-test:node": "echo skipped",
23
20
  "integration-test": "npm run integration-test:node && npm run integration-test:browser",
@@ -28,14 +25,11 @@
28
25
  "test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node",
29
26
  "test": "npm run build:test && npm run unit-test && npm run integration-test",
30
27
  "unit-test:browser": "echo \"Browser is not supported.\" && exit 0",
31
- "unit-test:node": "dev-tool run test:node-ts-input --no-test-proxy",
28
+ "unit-test:node": "dev-tool run test:vitest --no-test-proxy",
32
29
  "unit-test": "npm run unit-test:node && npm run unit-test:browser"
33
30
  },
34
31
  "files": [
35
32
  "dist/",
36
- "dist-esm/",
37
- "types/web-pubsub-express.d.ts",
38
- "types/web-pubsub-express.d.ts.map",
39
33
  "README.md",
40
34
  "LICENSE"
41
35
  ],
@@ -55,38 +49,59 @@
55
49
  "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/web-pubsub/web-pubsub-express/README.md",
56
50
  "sideEffects": false,
57
51
  "dependencies": {
58
- "tslib": "^2.2.0",
59
- "@azure/logger": "^1.0.0"
52
+ "@azure/logger": "^1.1.2",
53
+ "tslib": "^2.6.2"
60
54
  },
61
55
  "devDependencies": {
62
56
  "@azure/dev-tool": ">=1.0.0-alpha <1.0.0-alphb",
63
- "@azure/eslint-plugin-azure-sdk": "^3.0.0",
57
+ "@azure/eslint-plugin-azure-sdk": ">=3.0.0-alpha <3.0.0-alphb",
64
58
  "@microsoft/api-extractor": "^7.31.1",
65
- "@types/chai": "^4.1.6",
66
59
  "@types/express": "^4.16.0",
67
60
  "@types/express-serve-static-core": "^4.17.19",
68
61
  "@types/jsonwebtoken": "^9.0.0",
69
- "@types/mocha": "^10.0.0",
70
62
  "@types/node": "^18.0.0",
71
- "@types/sinon": "^17.0.0",
72
- "chai": "^4.2.0",
73
- "cross-env": "^7.0.2",
63
+ "@vitest/browser": "^2.0.5",
64
+ "@vitest/coverage-istanbul": "^2.0.5",
74
65
  "dotenv": "^16.0.0",
75
66
  "eslint": "^8.0.0",
76
67
  "express": "^4.16.3",
77
- "mocha": "^10.0.0",
78
- "nyc": "^15.1.0",
79
- "puppeteer": "^22.2.0",
80
68
  "rimraf": "^5.0.5",
81
- "sinon": "^17.0.0",
82
- "source-map-support": "^0.5.9",
83
- "typescript": "~5.4.5",
84
- "ts-node": "^10.0.0"
69
+ "tshy": "^2.0.0",
70
+ "typescript": "~5.5.3",
71
+ "vitest": "^2.0.5"
85
72
  },
86
73
  "//sampleConfiguration": {
87
74
  "productName": "Azure Web PubSub CloudEvents Handlers for Express",
88
75
  "productSlugs": [
89
76
  "azure"
90
77
  ]
91
- }
78
+ },
79
+ "tshy": {
80
+ "exports": {
81
+ "./package.json": "./package.json",
82
+ ".": "./src/index.ts"
83
+ },
84
+ "dialects": [
85
+ "esm",
86
+ "commonjs"
87
+ ],
88
+ "selfLink": false
89
+ },
90
+ "exports": {
91
+ "./package.json": "./package.json",
92
+ ".": {
93
+ "import": {
94
+ "types": "./dist/esm/index.d.ts",
95
+ "default": "./dist/esm/index.js"
96
+ },
97
+ "require": {
98
+ "types": "./dist/commonjs/index.d.ts",
99
+ "default": "./dist/commonjs/index.js"
100
+ }
101
+ }
102
+ },
103
+ "main": "./dist/commonjs/index.js",
104
+ "types": "./dist/commonjs/index.d.ts",
105
+ "type": "module",
106
+ "module": "./dist/esm/index.js"
92
107
  }
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":["../src/utils.ts","../src/logger.ts","../src/cloudEventsDispatcher.ts","../src/webPubSubEventHandler.ts"],"sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { IncomingMessage } from \"http\";\n\nfunction isJsonObject(obj: any): boolean {\n return obj && typeof obj === \"object\" && !Array.isArray(obj);\n}\n\nexport function toBase64JsonString(obj: Record<string, any>): string {\n return Buffer.from(JSON.stringify(obj)).toString(\"base64\");\n}\n\nexport function fromBase64JsonString(base64String: string | undefined): Record<string, any> {\n if (base64String === undefined) {\n return {};\n }\n\n try {\n const buf = Buffer.from(base64String, \"base64\").toString();\n const parsed = JSON.parse(buf);\n return isJsonObject(parsed) ? parsed : {};\n } catch (e: any) {\n console.warn(\"Unexpected state format:\" + e);\n return {};\n }\n}\n\nexport function getHttpHeader(req: IncomingMessage, key: string): string | undefined {\n if (!key) return undefined;\n\n // According to https://nodejs.org/api/http.html#http_class_http_incomingmessage, header names are always lower-cased\n const value = req.headers[key.toLowerCase()];\n\n if (value === undefined) {\n return undefined;\n }\n if (typeof value === \"string\") {\n return value;\n }\n\n return value[0];\n}\n\nexport function readRequestBody(req: IncomingMessage): Promise<Buffer> {\n return new Promise(function (resolve, reject) {\n const chunks: any = [];\n req.on(\"data\", function (chunk) {\n chunks.push(chunk);\n });\n req.on(\"end\", function () {\n const buffer = Buffer.concat(chunks);\n resolve(buffer);\n });\n // reject on request error\n req.on(\"error\", function (err) {\n // This is not a \"Second reject\", just a different sort of failure\n reject(err);\n });\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 this package.\n *\n * @internal\n */\nexport const logger = createClientLogger(\"web-pubsub-express\");\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as utils from \"./utils\";\nimport { IncomingMessage, ServerResponse } from \"http\";\nimport { URL } from \"url\";\nimport { logger } from \"./logger\";\n\nimport {\n ConnectRequest,\n ConnectResponse,\n ConnectedRequest,\n ConnectionContext,\n ConnectResponseHandler,\n DisconnectedRequest,\n UserEventRequest,\n UserEventResponseHandler,\n WebPubSubEventHandlerOptions,\n} from \"./cloudEventsProtocols\";\n\nenum EventType {\n Connect,\n Connected,\n Disconnected,\n UserEvent,\n}\n\nfunction getConnectResponseHandler(\n connectRequest: ConnectRequest,\n response: ServerResponse,\n): ConnectResponseHandler {\n const states: Record<string, any> = connectRequest.context.states;\n let modified = false;\n const handler = {\n setState(name: string, value: unknown): void {\n states[name] = value;\n modified = true;\n },\n success(res?: ConnectResponse): void {\n response.statusCode = 200;\n if (modified) {\n response.setHeader(\"ce-connectionState\", utils.toBase64JsonString(states));\n }\n if (res === undefined) {\n response.end();\n } else {\n response.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n response.end(JSON.stringify(res));\n }\n },\n fail(code: 400 | 401 | 500, detail?: string): void {\n response.statusCode = code;\n response.end(detail ?? \"\");\n },\n };\n\n return handler;\n}\n\nfunction getUserEventResponseHandler(\n userRequest: UserEventRequest,\n response: ServerResponse,\n): UserEventResponseHandler {\n const states: Record<string, any> = userRequest.context.states;\n let modified = false;\n const handler = {\n setState(name: string, value: unknown): void {\n modified = true;\n states[name] = value;\n },\n success(data?: string | ArrayBuffer, dataType?: \"binary\" | \"text\" | \"json\"): void {\n response.statusCode = 200;\n if (modified) {\n response.setHeader(\"ce-connectionState\", utils.toBase64JsonString(states));\n }\n\n switch (dataType) {\n case \"json\":\n response.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n break;\n case \"text\":\n response.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n break;\n default:\n response.setHeader(\"Content-Type\", \"application/octet-stream\");\n break;\n }\n response.end(data ?? \"\");\n },\n fail(code: 400 | 401 | 500, detail?: string): void {\n response.statusCode = code;\n response.end(detail ?? \"\");\n },\n };\n return handler;\n}\n\nfunction getContext(request: IncomingMessage, origin: string): ConnectionContext {\n const context = {\n signature: utils.getHttpHeader(request, \"ce-signature\"),\n userId: utils.getHttpHeader(request, \"ce-userid\"),\n hub: utils.getHttpHeader(request, \"ce-hub\")!,\n connectionId: utils.getHttpHeader(request, \"ce-connectionid\")!,\n eventName: utils.getHttpHeader(request, \"ce-eventname\")!,\n origin: origin,\n states: utils.fromBase64JsonString(utils.getHttpHeader(request, \"ce-connectionstate\")),\n };\n\n // TODO: validation\n return context;\n}\n\nfunction tryGetWebPubSubEvent(req: IncomingMessage): EventType | undefined {\n // check ce-type to see if it is a valid WebPubSub CloudEvent request\n const prefix = \"azure.webpubsub.\";\n const connect = \"azure.webpubsub.sys.connect\";\n const connected = \"azure.webpubsub.sys.connected\";\n const disconnectd = \"azure.webpubsub.sys.disconnected\";\n const userPrefix = \"azure.webpubsub.user.\";\n const type = utils.getHttpHeader(req, \"ce-type\");\n if (!type?.startsWith(prefix)) {\n return undefined;\n }\n if (type.startsWith(userPrefix)) {\n return EventType.UserEvent;\n }\n switch (type) {\n case connect:\n return EventType.Connect;\n case connected:\n return EventType.Connected;\n case disconnectd:\n return EventType.Disconnected;\n default:\n return undefined;\n }\n}\n\nfunction isWebPubSubRequest(req: IncomingMessage): boolean {\n return utils.getHttpHeader(req, \"ce-awpsversion\") !== undefined;\n}\n\nasync function readUserEventRequest(\n request: IncomingMessage,\n origin: string,\n): Promise<UserEventRequest | undefined> {\n const contentTypeheader = utils.getHttpHeader(request, \"content-type\");\n if (contentTypeheader === undefined) {\n return undefined;\n }\n\n const contentType = contentTypeheader.split(\";\")[0].trim();\n\n switch (contentType) {\n case \"application/octet-stream\":\n return {\n context: getContext(request, origin),\n data: await utils.readRequestBody(request),\n dataType: \"binary\",\n };\n case \"application/json\":\n return {\n context: getContext(request, origin),\n data: JSON.parse((await utils.readRequestBody(request)).toString()),\n dataType: \"json\",\n };\n case \"text/plain\":\n return {\n context: getContext(request, origin),\n data: (await utils.readRequestBody(request)).toString(),\n dataType: \"text\",\n };\n default:\n return undefined;\n }\n}\n\nasync function readSystemEventRequest<T extends { context: ConnectionContext }>(\n request: IncomingMessage,\n origin: string,\n): Promise<T> {\n const body = (await utils.readRequestBody(request)).toString();\n const parsedRequest = JSON.parse(body) as T;\n parsedRequest.context = getContext(request, origin);\n return parsedRequest;\n}\n\n/**\n * @internal\n */\nexport class CloudEventsDispatcher {\n private readonly _allowAll: boolean = true;\n private readonly _allowedOrigins: Array<string> = [];\n constructor(\n private hub: string,\n private eventHandler?: WebPubSubEventHandlerOptions,\n ) {\n if (Array.isArray(eventHandler)) {\n throw new Error(\"Unexpected WebPubSubEventHandlerOptions\");\n }\n if (eventHandler?.allowedEndpoints !== undefined) {\n this._allowedOrigins = eventHandler.allowedEndpoints.map((endpoint) =>\n new URL(endpoint).host.toLowerCase(),\n );\n this._allowAll = false;\n }\n }\n\n public handlePreflight(req: IncomingMessage, res: ServerResponse): boolean {\n if (!isWebPubSubRequest(req)) {\n return false;\n }\n const origin = utils.getHttpHeader(req, \"webhook-request-origin\");\n\n if (origin === undefined) {\n logger.warning(\"Expecting webhook-request-origin header.\");\n res.statusCode = 400;\n } else if (this._allowAll) {\n res.setHeader(\"WebHook-Allowed-Origin\", \"*\");\n } else {\n // service to do the check\n res.setHeader(\"WebHook-Allowed-Origin\", this._allowedOrigins);\n }\n\n res.end();\n return true;\n }\n\n public async handleRequest(request: IncomingMessage, response: ServerResponse): Promise<boolean> {\n if (!isWebPubSubRequest(request)) {\n return false;\n }\n\n // check if it is a valid WebPubSub cloud events\n const origin = utils.getHttpHeader(request, \"webhook-request-origin\");\n if (origin === undefined) {\n return false;\n }\n\n const eventType = tryGetWebPubSubEvent(request);\n if (eventType === undefined) {\n return false;\n }\n\n // check if hub matches\n const hub = utils.getHttpHeader(request, \"ce-hub\");\n if (hub?.toUpperCase() !== this.hub.toUpperCase()) {\n return false;\n }\n\n // No need to read body if handler is not specified\n switch (eventType) {\n case EventType.Connect:\n if (!this.eventHandler?.handleConnect) {\n response.end();\n return true;\n }\n break;\n case EventType.Connected:\n if (!this.eventHandler?.onConnected) {\n response.end();\n return true;\n }\n break;\n case EventType.Disconnected:\n if (!this.eventHandler?.onDisconnected) {\n response.end();\n return true;\n }\n break;\n case EventType.UserEvent:\n if (!this.eventHandler?.handleUserEvent) {\n response.end();\n return true;\n }\n break;\n default:\n logger.warning(`Unknown EventType ${eventType}`);\n return false;\n }\n\n switch (eventType) {\n case EventType.Connect: {\n const connectRequest = await readSystemEventRequest<ConnectRequest>(request, origin);\n // service passes out query property, assign it to queries\n connectRequest.queries = connectRequest.query;\n logger.verbose(connectRequest);\n\n this.eventHandler.handleConnect!(\n connectRequest,\n getConnectResponseHandler(connectRequest, response),\n );\n return true;\n }\n case EventType.Connected: {\n // for unblocking events, we responds to the service as early as possible\n response.end();\n const connectedRequest = await readSystemEventRequest<ConnectedRequest>(request, origin);\n logger.verbose(connectedRequest);\n this.eventHandler.onConnected!(connectedRequest);\n return true;\n }\n case EventType.Disconnected: {\n // for unblocking events, we responds to the service as early as possible\n response.end();\n const disconnectedRequest = await readSystemEventRequest<DisconnectedRequest>(\n request,\n origin,\n );\n logger.verbose(disconnectedRequest);\n this.eventHandler.onDisconnected!(disconnectedRequest);\n return true;\n }\n case EventType.UserEvent: {\n const userRequest = await readUserEventRequest(request, origin);\n if (userRequest === undefined) {\n logger.warning(\n `Unsupported content type ${utils.getHttpHeader(request, \"content-type\")}`,\n );\n return false;\n }\n logger.verbose(userRequest);\n this.eventHandler.handleUserEvent!(\n userRequest,\n getUserEventResponseHandler(userRequest, response),\n );\n return true;\n }\n default:\n logger.warning(`Unknown EventType ${eventType}`);\n return false;\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport express from \"express-serve-static-core\";\n\nimport { CloudEventsDispatcher } from \"./cloudEventsDispatcher\";\nimport { WebPubSubEventHandlerOptions } from \"./cloudEventsProtocols\";\n\n/**\n * The handler to handle incoming CloudEvents messages\n */\nexport class WebPubSubEventHandler {\n /**\n * The path this CloudEvents handler listens to\n */\n public readonly path: string;\n\n private _cloudEventsHandler: CloudEventsDispatcher;\n\n /**\n * Creates an instance of a WebPubSubEventHandler for handling incoming CloudEvents messages.\n *\n * Example usage:\n * ```ts\n * import express from \"express\";\n * import { WebPubSubEventHandler } from \"@azure/web-pubsub-express\";\n * const endpoint = \"https://xxxx.webpubsubdev.azure.com\"\n * const handler = new WebPubSubEventHandler('chat', {\n * handleConnect: (req, res) => {\n * console.log(JSON.stringify(req));\n * return {};\n * },\n * onConnected: req => {\n * console.log(JSON.stringify(req));\n * },\n * handleUserEvent: (req, res) => {\n * console.log(JSON.stringify(req));\n * res.success(\"Hey \" + req.data, req.dataType);\n * };\n * allowedEndpoints: [ endpoint ]\n * },\n * });\n * ```\n *\n * @param hub - The name of the hub to listen to\n * @param options - Options to configure the event handler\n */\n constructor(\n private hub: string,\n options?: WebPubSubEventHandlerOptions,\n ) {\n const path = (options?.path ?? `/api/webpubsub/hubs/${hub}/`).toLowerCase();\n this.path = path.endsWith(\"/\") ? path : path + \"/\";\n this._cloudEventsHandler = new CloudEventsDispatcher(this.hub, options);\n }\n\n /**\n * Get the middleware to process the CloudEvents requests\n */\n public getMiddleware(): express.RequestHandler {\n return async (\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n ): Promise<void> => {\n // Request originalUrl can contain query while baseUrl + path not\n let requestUrl = (req.baseUrl + req.path).toLowerCase();\n\n // normalize the Url\n requestUrl = requestUrl.endsWith(\"/\") ? requestUrl : requestUrl + \"/\";\n if (requestUrl.startsWith(this.path)) {\n if (req.method === \"OPTIONS\") {\n if (this._cloudEventsHandler.handlePreflight(req, res)) {\n return;\n }\n } else if (req.method === \"POST\") {\n try {\n if (await this._cloudEventsHandler.handleRequest(req, res)) {\n return;\n }\n } catch (err: any) {\n next(err);\n return;\n }\n }\n }\n\n next();\n };\n }\n}\n"],"names":["createClientLogger","utils.toBase64JsonString","utils.getHttpHeader","utils.fromBase64JsonString","utils.readRequestBody","URL"],"mappings":";;;;;;;AAAA;AACA;AAIA,SAAS,YAAY,CAAC,GAAQ,EAAA;AAC5B,IAAA,OAAO,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC/D,CAAC;AAEK,SAAU,kBAAkB,CAAC,GAAwB,EAAA;AACzD,IAAA,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAC7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AM,KAAK,MAAM,EAAE;AAChC,oBAAA,IAAI;AACF,wBAAA,IAAI,MAAM,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE;4BAC1D,OAAO;yBACR;qBACF;oBAAC,OAAO,GAAQ,EAAE;wBACjB,IAAI,CAAC,GAAG,CAAC,CAAC;wBACV,OAAO;qBACR;iBACF;aACF;AAED,YAAA,IAAI,EAAE,CAAC;AACT,SAAC,CAAC;KACH;AACF;;;;"}
@@ -1,32 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- /**
4
- * @summary Demonstrates handling Web PubSub CloudEvents with Express
5
- */
6
- import { WebPubSubEventHandler } from "@azure/web-pubsub-express";
7
- import express from "express";
8
- const handler = new WebPubSubEventHandler("chat", {
9
- handleConnect(req, res) {
10
- console.log(req);
11
- // You can set the state for the connection, it lasts throughout the lifetime of the connection
12
- res.setState("calledTime", 1);
13
- res.success();
14
- // or fail
15
- // res.fail(401);
16
- },
17
- onConnected(connectedRequest) {
18
- console.log(connectedRequest);
19
- },
20
- handleUserEvent(req, res) {
21
- var calledTime = req.context.states.calledTime++;
22
- console.log(calledTime);
23
- // You can also set the state here
24
- res.setState("calledTime", calledTime);
25
- res.success("Hello", "text");
26
- },
27
- allowedEndpoints: ["https://xxx.webpubsub.azure.com"],
28
- });
29
- const app = express();
30
- app.use(handler.getMiddleware());
31
- app.listen(3000, () => console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`));
32
- //# sourceMappingURL=server.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../samples-dev/server.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,MAAM,OAAO,GAAG,IAAI,qBAAqB,CAAC,MAAM,EAAE;IAChD,aAAa,CAAC,GAAG,EAAE,GAAG;QACpB,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACjB,+FAA+F;QAC/F,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC;QAC9B,GAAG,CAAC,OAAO,EAAE,CAAC;QACd,UAAU;QACV,iBAAiB;IACnB,CAAC;IACD,WAAW,CAAC,gBAAgB;QAC1B,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAChC,CAAC;IACD,eAAe,CAAC,GAAG,EAAE,GAAG;QACtB,IAAI,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACjD,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACxB,kCAAkC;QAClC,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACvC,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC/B,CAAC;IACD,gBAAgB,EAAE,CAAC,iCAAiC,CAAC;CACtD,CAAC,CAAC;AAEH,MAAM,GAAG,GAAG,OAAO,EAAE,CAAC;AAEtB,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;AAEjC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,GAAG,EAAE,CACpB,OAAO,CAAC,GAAG,CAAC,0DAA0D,OAAO,CAAC,IAAI,EAAE,CAAC,CACtF,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @summary Demonstrates handling Web PubSub CloudEvents with Express\n */\n\nimport { WebPubSubEventHandler } from \"@azure/web-pubsub-express\";\nimport express from \"express\";\n\nconst handler = new WebPubSubEventHandler(\"chat\", {\n handleConnect(req, res) {\n console.log(req);\n // You can set the state for the connection, it lasts throughout the lifetime of the connection\n res.setState(\"calledTime\", 1);\n res.success();\n // or fail\n // res.fail(401);\n },\n onConnected(connectedRequest) {\n console.log(connectedRequest);\n },\n handleUserEvent(req, res) {\n var calledTime = req.context.states.calledTime++;\n console.log(calledTime);\n // You can also set the state here\n res.setState(\"calledTime\", calledTime);\n res.success(\"Hello\", \"text\");\n },\n allowedEndpoints: [\"https://xxx.webpubsub.azure.com\"],\n});\n\nconst app = express();\n\napp.use(handler.getMiddleware());\n\napp.listen(3000, () =>\n console.log(`Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`),\n);\n"]}