@webiny/api-websockets-aws 0.0.0-unstable.0d717d18dd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Webiny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @webiny/api-websockets-aws
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -0,0 +1,53 @@
1
+ import type { WebsocketsRunner } from "@webiny/api-websockets/exports/api.js";
2
+ import type { GenericRecord } from "@webiny/api/types.js";
3
+ import type { PartialDeep } from "type-fest";
4
+ export declare enum WebsocketsEventRoute {
5
+ connect = "$connect",
6
+ disconnect = "$disconnect",
7
+ default = "$default"
8
+ }
9
+ export declare enum WebsocketsEventRequestContextEventType {
10
+ message = "MESSAGE",
11
+ connect = "CONNECT",
12
+ disconnect = "DISCONNECT"
13
+ }
14
+ export interface IAwsWebsocketsEventRequestContext {
15
+ connectionId: string;
16
+ connectedAt: number;
17
+ domainName: string;
18
+ eventType: WebsocketsEventRequestContextEventType;
19
+ routeKey: WebsocketsEventRoute | string;
20
+ stage: string;
21
+ }
22
+ export interface IAwsWebsocketsEventHeaders {
23
+ "Accept-Encoding"?: string;
24
+ "Accept-Language"?: string;
25
+ "Cache-Control"?: string;
26
+ Host?: string;
27
+ Origin?: string;
28
+ Pragma?: string;
29
+ "Sec-WebSocket-Extensions"?: string;
30
+ "Sec-WebSocket-Key"?: string;
31
+ "Sec-WebSocket-Version"?: string;
32
+ "Sec-WebSocket-Protocol"?: string;
33
+ "User-Agent"?: string;
34
+ "X-Amzn-Trace-Id"?: string;
35
+ "X-Forwarded-For"?: string;
36
+ "X-Forwarded-Port"?: `${number}`;
37
+ "X-Forwarded-Proto"?: "https" | "http";
38
+ ["x-tenant"]?: string;
39
+ ["x-webiny-cms-endpoint"]?: string;
40
+ }
41
+ export interface IAwsWebsocketsEventQueryStringParameters {
42
+ tenant?: string;
43
+ token?: string;
44
+ }
45
+ export interface IAwsWebsocketsEvent<T extends WebsocketsRunner.EventData = WebsocketsRunner.EventData> {
46
+ headers?: IAwsWebsocketsEventHeaders;
47
+ queryStringParameters?: IAwsWebsocketsEventQueryStringParameters;
48
+ requestContext: IAwsWebsocketsEventRequestContext;
49
+ body?: T;
50
+ }
51
+ export interface IAwsWebsocketsIncomingEvent extends PartialDeep<Omit<IAwsWebsocketsEvent, "body">> {
52
+ body?: string | GenericRecord;
53
+ }
@@ -0,0 +1,15 @@
1
+ var types_WebsocketsEventRoute = /*#__PURE__*/ function(WebsocketsEventRoute) {
2
+ WebsocketsEventRoute["connect"] = "$connect";
3
+ WebsocketsEventRoute["disconnect"] = "$disconnect";
4
+ WebsocketsEventRoute["default"] = "$default";
5
+ return WebsocketsEventRoute;
6
+ }({});
7
+ var types_WebsocketsEventRequestContextEventType = /*#__PURE__*/ function(WebsocketsEventRequestContextEventType) {
8
+ WebsocketsEventRequestContextEventType["message"] = "MESSAGE";
9
+ WebsocketsEventRequestContextEventType["connect"] = "CONNECT";
10
+ WebsocketsEventRequestContextEventType["disconnect"] = "DISCONNECT";
11
+ return WebsocketsEventRequestContextEventType;
12
+ }({});
13
+ export { types_WebsocketsEventRequestContextEventType as WebsocketsEventRequestContextEventType, types_WebsocketsEventRoute as WebsocketsEventRoute };
14
+
15
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler/types.js","sources":["../../src/handler/types.ts"],"sourcesContent":["import type { WebsocketsRunner } from \"@webiny/api-websockets/exports/api.js\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport type { PartialDeep } from \"type-fest\";\n\nexport enum WebsocketsEventRoute {\n connect = \"$connect\",\n disconnect = \"$disconnect\",\n default = \"$default\"\n}\n\nexport enum WebsocketsEventRequestContextEventType {\n message = \"MESSAGE\",\n connect = \"CONNECT\",\n disconnect = \"DISCONNECT\"\n}\n\nexport interface IAwsWebsocketsEventRequestContext {\n connectionId: string;\n connectedAt: number;\n domainName: string;\n eventType: WebsocketsEventRequestContextEventType;\n routeKey: WebsocketsEventRoute | string;\n stage: string;\n}\n\nexport interface IAwsWebsocketsEventHeaders {\n \"Accept-Encoding\"?: string;\n \"Accept-Language\"?: string;\n \"Cache-Control\"?: string;\n Host?: string;\n Origin?: string;\n Pragma?: string;\n \"Sec-WebSocket-Extensions\"?: string;\n \"Sec-WebSocket-Key\"?: string;\n \"Sec-WebSocket-Version\"?: string;\n \"Sec-WebSocket-Protocol\"?: string;\n \"User-Agent\"?: string;\n \"X-Amzn-Trace-Id\"?: string;\n \"X-Forwarded-For\"?: string;\n \"X-Forwarded-Port\"?: `${number}`;\n \"X-Forwarded-Proto\"?: \"https\" | \"http\";\n [\"x-tenant\"]?: string;\n [\"x-webiny-cms-endpoint\"]?: string;\n}\n\nexport interface IAwsWebsocketsEventQueryStringParameters {\n tenant?: string;\n token?: string;\n}\n\nexport interface IAwsWebsocketsEvent<\n T extends WebsocketsRunner.EventData = WebsocketsRunner.EventData\n> {\n headers?: IAwsWebsocketsEventHeaders;\n queryStringParameters?: IAwsWebsocketsEventQueryStringParameters;\n requestContext: IAwsWebsocketsEventRequestContext;\n body?: T;\n}\n\nexport interface IAwsWebsocketsIncomingEvent extends PartialDeep<\n Omit<IAwsWebsocketsEvent, \"body\">\n> {\n body?: string | GenericRecord;\n}\n"],"names":["WebsocketsEventRoute","WebsocketsEventRequestContextEventType"],"mappings":"AAIO,IAAKA,6BAAoBA,WAAAA,GAAAA,SAApBA,oBAAoB;;;;WAApBA;;AAML,IAAKC,+CAAsCA,WAAAA,GAAAA,SAAtCA,sCAAsC;;;;WAAtCA"}
package/index.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { AwsWebsocketsTransport } from "./transport/AwsWebsocketsTransport.js";
2
+ export declare const WebsocketsAwsFeature: {
3
+ name: string;
4
+ register(container: import("@webiny/di").Container): void;
5
+ };
6
+ /** @deprecated use WebsocketsAwsFeature.register(container) */
7
+ export declare const createAwsWebsockets: () => never[];
package/index.js ADDED
@@ -0,0 +1,15 @@
1
+ import { createFeature } from "@webiny/feature/api";
2
+ import { AwsWebsocketsTransport } from "./transport/AwsWebsocketsTransport.js";
3
+ const WebsocketsAwsFeature = createFeature({
4
+ name: "WebsocketsAws",
5
+ register (container) {
6
+ container.register(AwsWebsocketsTransport);
7
+ }
8
+ });
9
+ const createAwsWebsockets = ()=>{
10
+ console.warn("[api-websockets-aws] createAwsWebsockets() is deprecated. Use WebsocketsAwsFeature.register(container) instead.");
11
+ return [];
12
+ };
13
+ export { AwsWebsocketsTransport, WebsocketsAwsFeature, createAwsWebsockets };
14
+
15
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { AwsWebsocketsTransport } from \"~/transport/AwsWebsocketsTransport.js\";\n\nexport { AwsWebsocketsTransport } from \"~/transport/AwsWebsocketsTransport.js\";\n\nexport const WebsocketsAwsFeature = createFeature({\n name: \"WebsocketsAws\",\n register(container) {\n container.register(AwsWebsocketsTransport);\n }\n});\n\n/** @deprecated use WebsocketsAwsFeature.register(container) */\nexport const createAwsWebsockets = () => {\n console.warn(\n \"[api-websockets-aws] createAwsWebsockets() is deprecated. Use WebsocketsAwsFeature.register(container) instead.\"\n );\n return [];\n};\n"],"names":["WebsocketsAwsFeature","createFeature","container","AwsWebsocketsTransport","createAwsWebsockets","console"],"mappings":";;AAKO,MAAMA,uBAAuBC,cAAc;IAC9C,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;IACvB;AACJ;AAGO,MAAMC,sBAAsB;IAC/BC,QAAQ,IAAI,CACR;IAEJ,OAAO,EAAE;AACb"}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@webiny/api-websockets-aws",
3
+ "version": "0.0.0-unstable.0d717d18dd",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/webiny/webiny-js.git"
8
+ },
9
+ "description": "AWS Lambda handler and API Gateway transport for @webiny/api-websockets",
10
+ "contributors": [
11
+ "Bruno Zorić <bruno@webiny.com>"
12
+ ],
13
+ "exports": {
14
+ "./*": "./*",
15
+ ".": "./index.js"
16
+ },
17
+ "license": "MIT",
18
+ "dependencies": {
19
+ "@webiny/api": "0.0.0-unstable.0d717d18dd",
20
+ "@webiny/api-websockets": "0.0.0-unstable.0d717d18dd",
21
+ "@webiny/aws-sdk": "0.0.0-unstable.0d717d18dd",
22
+ "@webiny/feature": "0.0.0-unstable.0d717d18dd",
23
+ "@webiny/handler": "0.0.0-unstable.0d717d18dd",
24
+ "@webiny/utils": "0.0.0-unstable.0d717d18dd",
25
+ "type-fest": "5.8.0",
26
+ "zod": "4.4.3"
27
+ },
28
+ "devDependencies": {
29
+ "@webiny/api-core": "0.0.0-unstable.0d717d18dd",
30
+ "@webiny/api-core-testing": "0.0.0-unstable.0d717d18dd",
31
+ "@webiny/api-graphql": "0.0.0-unstable.0d717d18dd",
32
+ "@webiny/api-headless-cms": "0.0.0-unstable.0d717d18dd",
33
+ "@webiny/build-tools": "0.0.0-unstable.0d717d18dd",
34
+ "@webiny/di": "1.0.2",
35
+ "@webiny/event-handler-core": "0.0.0-unstable.0d717d18dd",
36
+ "@webiny/project-utils": "0.0.0-unstable.0d717d18dd",
37
+ "@webiny/wcp": "0.0.0-unstable.0d717d18dd",
38
+ "graphql": "16.14.2",
39
+ "rimraf": "6.1.3",
40
+ "type-fest": "5.8.0",
41
+ "typescript": "7.0.2",
42
+ "vitest": "4.1.10"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "webiny": {
48
+ "publishFrom": "dist"
49
+ }
50
+ }
@@ -0,0 +1,12 @@
1
+ import { WebsocketsTransport } from "@webiny/api-websockets/exports/api.js";
2
+ import type { GenericRecord } from "@webiny/api/types.js";
3
+ declare class AwsWebsocketsTransportImpl implements WebsocketsTransport.Interface {
4
+ private readonly clients;
5
+ send<T extends GenericRecord = GenericRecord>(connections: WebsocketsTransport.SendConnection[], data: WebsocketsTransport.SendData<T>): Promise<void>;
6
+ disconnect(connections: WebsocketsTransport.DisconnectConnection[]): Promise<void>;
7
+ private getClient;
8
+ }
9
+ export declare const AwsWebsocketsTransport: typeof AwsWebsocketsTransportImpl & {
10
+ __abstraction: import("@webiny/di").Abstraction<import("@webiny/api-websockets/transport").IWebsocketsTransport>;
11
+ };
12
+ export {};
@@ -0,0 +1,48 @@
1
+ import { ApiGatewayManagementApiClient, DeleteConnectionCommand, PostToConnectionCommand } from "@webiny/aws-sdk/client-apigatewaymanagementapi/index.js";
2
+ import { WebsocketsTransport } from "@webiny/api-websockets/exports/api.js";
3
+ class AwsWebsocketsTransportImpl {
4
+ async send(connections, data) {
5
+ for (const connection of connections)try {
6
+ const client = this.getClient(connection.endpoint);
7
+ const command = new PostToConnectionCommand({
8
+ ConnectionId: connection.connectionId,
9
+ Data: JSON.stringify(data)
10
+ });
11
+ await client.send(command);
12
+ } catch (ex) {
13
+ console.error(`Failed to send message to connection "${connection.connectionId}". Check logs for more information.`);
14
+ console.log(ex);
15
+ }
16
+ }
17
+ async disconnect(connections) {
18
+ for (const connection of connections)try {
19
+ const client = this.getClient(connection.endpoint);
20
+ const command = new DeleteConnectionCommand({
21
+ ConnectionId: connection.connectionId
22
+ });
23
+ await client.send(command);
24
+ } catch (ex) {
25
+ console.error(`Failed to disconnect connection "${connection.connectionId}". Check logs for more information.`);
26
+ console.log(ex);
27
+ }
28
+ }
29
+ getClient(endpoint) {
30
+ const client = this.clients.get(endpoint);
31
+ if (client) return client;
32
+ const newClient = new ApiGatewayManagementApiClient({
33
+ endpoint
34
+ });
35
+ this.clients.set(endpoint, newClient);
36
+ return newClient;
37
+ }
38
+ constructor(){
39
+ this.clients = new Map();
40
+ }
41
+ }
42
+ const AwsWebsocketsTransport = WebsocketsTransport.createImplementation({
43
+ implementation: AwsWebsocketsTransportImpl,
44
+ dependencies: []
45
+ });
46
+ export { AwsWebsocketsTransport };
47
+
48
+ //# sourceMappingURL=AwsWebsocketsTransport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport/AwsWebsocketsTransport.js","sources":["../../src/transport/AwsWebsocketsTransport.ts"],"sourcesContent":["import {\n ApiGatewayManagementApiClient,\n DeleteConnectionCommand,\n PostToConnectionCommand\n} from \"@webiny/aws-sdk/client-apigatewaymanagementapi/index.js\";\nimport { WebsocketsTransport } from \"@webiny/api-websockets/exports/api.js\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\n\nclass AwsWebsocketsTransportImpl implements WebsocketsTransport.Interface {\n private readonly clients = new Map<string, ApiGatewayManagementApiClient>();\n\n public async send<T extends GenericRecord = GenericRecord>(\n connections: WebsocketsTransport.SendConnection[],\n data: WebsocketsTransport.SendData<T>\n ): Promise<void> {\n for (const connection of connections) {\n try {\n const client = this.getClient(connection.endpoint);\n\n const command = new PostToConnectionCommand({\n ConnectionId: connection.connectionId,\n Data: JSON.stringify(data)\n });\n await client.send(command);\n } catch (ex) {\n console.error(\n `Failed to send message to connection \"${connection.connectionId}\". Check logs for more information.`\n );\n console.log(ex);\n }\n }\n }\n\n public async disconnect(connections: WebsocketsTransport.DisconnectConnection[]) {\n for (const connection of connections) {\n try {\n const client = this.getClient(connection.endpoint);\n const command = new DeleteConnectionCommand({\n ConnectionId: connection.connectionId\n });\n await client.send(command);\n } catch (ex) {\n console.error(\n `Failed to disconnect connection \"${connection.connectionId}\". Check logs for more information.`\n );\n console.log(ex);\n }\n }\n }\n\n private getClient(endpoint: string): ApiGatewayManagementApiClient {\n const client = this.clients.get(endpoint);\n if (client) {\n return client;\n }\n const newClient = new ApiGatewayManagementApiClient({\n endpoint\n });\n this.clients.set(endpoint, newClient);\n return newClient;\n }\n}\n\nexport const AwsWebsocketsTransport = WebsocketsTransport.createImplementation({\n implementation: AwsWebsocketsTransportImpl,\n dependencies: []\n});\n"],"names":["AwsWebsocketsTransportImpl","connections","data","connection","client","command","PostToConnectionCommand","JSON","ex","console","DeleteConnectionCommand","endpoint","newClient","ApiGatewayManagementApiClient","Map","AwsWebsocketsTransport","WebsocketsTransport"],"mappings":";;AAQA,MAAMA;IAGF,MAAa,KACTC,WAAiD,EACjDC,IAAqC,EACxB;QACb,KAAK,MAAMC,cAAcF,YACrB,IAAI;YACA,MAAMG,SAAS,IAAI,CAAC,SAAS,CAACD,WAAW,QAAQ;YAEjD,MAAME,UAAU,IAAIC,wBAAwB;gBACxC,cAAcH,WAAW,YAAY;gBACrC,MAAMI,KAAK,SAAS,CAACL;YACzB;YACA,MAAME,OAAO,IAAI,CAACC;QACtB,EAAE,OAAOG,IAAI;YACTC,QAAQ,KAAK,CACT,CAAC,sCAAsC,EAAEN,WAAW,YAAY,CAAC,mCAAmC,CAAC;YAEzGM,QAAQ,GAAG,CAACD;QAChB;IAER;IAEA,MAAa,WAAWP,WAAuD,EAAE;QAC7E,KAAK,MAAME,cAAcF,YACrB,IAAI;YACA,MAAMG,SAAS,IAAI,CAAC,SAAS,CAACD,WAAW,QAAQ;YACjD,MAAME,UAAU,IAAIK,wBAAwB;gBACxC,cAAcP,WAAW,YAAY;YACzC;YACA,MAAMC,OAAO,IAAI,CAACC;QACtB,EAAE,OAAOG,IAAI;YACTC,QAAQ,KAAK,CACT,CAAC,iCAAiC,EAAEN,WAAW,YAAY,CAAC,mCAAmC,CAAC;YAEpGM,QAAQ,GAAG,CAACD;QAChB;IAER;IAEQ,UAAUG,QAAgB,EAAiC;QAC/D,MAAMP,SAAS,IAAI,CAAC,OAAO,CAAC,GAAG,CAACO;QAChC,IAAIP,QACA,OAAOA;QAEX,MAAMQ,YAAY,IAAIC,8BAA8B;YAChDF;QACJ;QACA,IAAI,CAAC,OAAO,CAAC,GAAG,CAACA,UAAUC;QAC3B,OAAOA;IACX;;aAnDiB,OAAO,GAAG,IAAIE;;AAoDnC;AAEO,MAAMC,yBAAyBC,oBAAoB,oBAAoB,CAAC;IAC3E,gBAAgBhB;IAChB,cAAc,EAAE;AACpB"}
@@ -0,0 +1,4 @@
1
+ import { WebsocketsEventValidator, WebsocketsRunner } from "@webiny/api-websockets/exports/api.js";
2
+ export declare class AwsWebsocketsEventValidator implements WebsocketsEventValidator.Interface {
3
+ validate<T extends WebsocketsRunner.EventData = WebsocketsRunner.EventData>(input: unknown): Promise<WebsocketsRunner.Event<T>>;
4
+ }
@@ -0,0 +1,87 @@
1
+ import zod from "zod";
2
+ import { WebsocketsEventRequestContextEventType } from "../handler/types.js";
3
+ import { createZodError } from "@webiny/utils";
4
+ const eventTypeMap = {
5
+ [WebsocketsEventRequestContextEventType.message]: "message",
6
+ [WebsocketsEventRequestContextEventType.connect]: "connect",
7
+ [WebsocketsEventRequestContextEventType.disconnect]: "disconnect"
8
+ };
9
+ const routeKeyMap = {
10
+ $connect: "connect",
11
+ $disconnect: "disconnect",
12
+ $default: "default"
13
+ };
14
+ const validation = zod.object({
15
+ headers: zod.looseObject({}).optional(),
16
+ requestContext: zod.object({
17
+ connectionId: zod.string(),
18
+ stage: zod.string(),
19
+ connectedAt: zod.number(),
20
+ domainName: zod.string(),
21
+ eventType: zod["enum"]([
22
+ WebsocketsEventRequestContextEventType.connect,
23
+ WebsocketsEventRequestContextEventType.message,
24
+ WebsocketsEventRequestContextEventType.disconnect
25
+ ]),
26
+ routeKey: zod.string()
27
+ }),
28
+ body: zod.string().transform((value, context)=>{
29
+ if (!value) return;
30
+ try {
31
+ return JSON.parse(value);
32
+ } catch (ex) {
33
+ console.error(`Failed body validation: ${ex.message}`);
34
+ console.log(`Body: ${value}`);
35
+ context.addIssue({
36
+ path: [],
37
+ message: `Invalid JSON: ${ex.message}`,
38
+ code: zod.ZodIssueCode.custom,
39
+ fatal: true
40
+ });
41
+ }
42
+ }).optional()
43
+ }).superRefine((output, context)=>{
44
+ if (output.requestContext.eventType !== WebsocketsEventRequestContextEventType.message) return;
45
+ if (output.body) return;
46
+ context.addIssue({
47
+ path: [
48
+ "body"
49
+ ],
50
+ message: "There must be a body defined when having a message event.",
51
+ code: zod.ZodIssueCode.custom,
52
+ fatal: true
53
+ });
54
+ });
55
+ const bodyValidation = zod.looseObject({
56
+ token: zod.string(),
57
+ tenant: zod.string(),
58
+ messageId: zod.string().nullish(),
59
+ action: zod.string(),
60
+ data: zod.looseObject({}).nullish()
61
+ }).optional();
62
+ class AwsWebsocketsEventValidator {
63
+ async validate(input) {
64
+ const result = await validation.safeParseAsync(input);
65
+ if (!result.success) throw createZodError(result.error);
66
+ const bodyResult = await bodyValidation.safeParseAsync(result.data.body);
67
+ if (!bodyResult.success) throw createZodError(bodyResult.error);
68
+ const rc = result.data.requestContext;
69
+ return {
70
+ headers: result.data.headers,
71
+ context: {
72
+ connectionId: rc.connectionId,
73
+ connectedAt: rc.connectedAt,
74
+ host: rc.domainName,
75
+ eventType: eventTypeMap[rc.eventType],
76
+ route: routeKeyMap[rc.routeKey] || rc.routeKey,
77
+ endpoint: `https://${rc.domainName}/${rc.stage}`
78
+ },
79
+ body: {
80
+ ...bodyResult.data || {}
81
+ }
82
+ };
83
+ }
84
+ }
85
+ export { AwsWebsocketsEventValidator };
86
+
87
+ //# sourceMappingURL=AwsWebsocketsEventValidator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator/AwsWebsocketsEventValidator.js","sources":["../../src/validator/AwsWebsocketsEventValidator.ts"],"sourcesContent":["import zod from \"zod\";\nimport { WebsocketsEventValidator, WebsocketsRunner } from \"@webiny/api-websockets/exports/api.js\";\nimport { WebsocketsEventRequestContextEventType } from \"~/handler/types.js\";\nimport { createZodError } from \"@webiny/utils\";\n\nconst eventTypeMap: Record<WebsocketsEventRequestContextEventType, WebsocketsRunner.EventType> = {\n [WebsocketsEventRequestContextEventType.message]: \"message\",\n [WebsocketsEventRequestContextEventType.connect]: \"connect\",\n [WebsocketsEventRequestContextEventType.disconnect]: \"disconnect\"\n};\n\nconst routeKeyMap: Record<string, string> = {\n $connect: \"connect\",\n $disconnect: \"disconnect\",\n $default: \"default\"\n};\n\nconst validation = zod\n .object({\n headers: zod.looseObject({}).optional(),\n requestContext: zod.object({\n connectionId: zod.string(),\n stage: zod.string(),\n connectedAt: zod.number(),\n domainName: zod.string(),\n eventType: zod.enum([\n WebsocketsEventRequestContextEventType.connect,\n WebsocketsEventRequestContextEventType.message,\n WebsocketsEventRequestContextEventType.disconnect\n ]),\n routeKey: zod.string()\n }),\n body: zod\n .string()\n .transform<WebsocketsRunner.EventData>((value, context) => {\n if (!value) {\n return undefined;\n }\n try {\n return JSON.parse(value);\n } catch (ex) {\n console.error(`Failed body validation: ${ex.message}`);\n console.log(`Body: ${value}`);\n context.addIssue({\n path: [],\n message: `Invalid JSON: ${ex.message}`,\n code: zod.ZodIssueCode.custom,\n fatal: true\n });\n }\n })\n .optional()\n })\n .superRefine((output, context) => {\n if (output.requestContext.eventType !== WebsocketsEventRequestContextEventType.message) {\n return;\n } else if (output.body) {\n return;\n }\n context.addIssue({\n path: [\"body\"],\n message: \"There must be a body defined when having a message event.\",\n code: zod.ZodIssueCode.custom,\n fatal: true\n });\n });\n\nconst bodyValidation = zod\n .looseObject({\n token: zod.string(),\n tenant: zod.string(),\n messageId: zod.string().nullish(),\n action: zod.string(),\n data: zod.looseObject({}).nullish()\n })\n .optional();\n\nexport class AwsWebsocketsEventValidator implements WebsocketsEventValidator.Interface {\n public async validate<T extends WebsocketsRunner.EventData = WebsocketsRunner.EventData>(\n input: unknown\n ): Promise<WebsocketsRunner.Event<T>> {\n const result = await validation.safeParseAsync(input);\n if (!result.success) {\n throw createZodError(result.error);\n }\n const bodyResult = await bodyValidation.safeParseAsync(result.data.body);\n if (!bodyResult.success) {\n throw createZodError(bodyResult.error);\n }\n\n const rc = result.data.requestContext;\n\n return {\n headers: result.data.headers as Record<string, string>,\n context: {\n connectionId: rc.connectionId,\n connectedAt: rc.connectedAt,\n host: rc.domainName,\n eventType: eventTypeMap[rc.eventType as WebsocketsEventRequestContextEventType],\n route: routeKeyMap[rc.routeKey] || rc.routeKey,\n endpoint: `https://${rc.domainName}/${rc.stage}`\n },\n body: {\n ...((bodyResult.data || {}) as T)\n }\n };\n }\n}\n"],"names":["eventTypeMap","WebsocketsEventRequestContextEventType","routeKeyMap","validation","zod","value","context","JSON","ex","console","output","bodyValidation","AwsWebsocketsEventValidator","input","result","createZodError","bodyResult","rc"],"mappings":";;;AAKA,MAAMA,eAA2F;IAC7F,CAACC,uCAAuC,OAAO,CAAC,EAAE;IAClD,CAACA,uCAAuC,OAAO,CAAC,EAAE;IAClD,CAACA,uCAAuC,UAAU,CAAC,EAAE;AACzD;AAEA,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