@webiny/api-websockets 6.6.0-alpha.0 → 6.6.0-alpha.10

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.
@@ -5,6 +5,7 @@ export interface IWebsocketsConnectionRegistryData {
5
5
  tenant: string;
6
6
  connectedOn: string;
7
7
  endpoint: string;
8
+ owner?: string;
8
9
  }
9
10
  export interface IWebsocketsConnectionRegistryRegisterParams {
10
11
  connectionId: string;
@@ -12,6 +13,7 @@ export interface IWebsocketsConnectionRegistryRegisterParams {
12
13
  identity: IWebsocketsIdentity;
13
14
  endpoint: string;
14
15
  connectedOn: string;
16
+ owner?: string;
15
17
  }
16
18
  export interface IWebsocketsConnectionRegistryUnregisterParams {
17
19
  connectionId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"features/ConnectionRegistry/abstractions.js","sources":["../../../src/features/ConnectionRegistry/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { IWebsocketsIdentity } from \"~/types.js\";\n\nexport interface IWebsocketsConnectionRegistryData {\n connectionId: string;\n identity: IWebsocketsIdentity;\n tenant: string;\n connectedOn: string;\n endpoint: string;\n}\n\nexport interface IWebsocketsConnectionRegistryRegisterParams {\n connectionId: string;\n tenant: string;\n identity: IWebsocketsIdentity;\n endpoint: string;\n connectedOn: string;\n}\n\nexport interface IWebsocketsConnectionRegistryUnregisterParams {\n connectionId: string;\n}\n\nexport interface IWebsocketsConnectionRegistry {\n register(\n event: IWebsocketsConnectionRegistryRegisterParams\n ): Promise<IWebsocketsConnectionRegistryData>;\n unregister(event: IWebsocketsConnectionRegistryUnregisterParams): Promise<void>;\n\n listViaConnections(connections: string[]): Promise<IWebsocketsConnectionRegistryData[]>;\n listViaIdentity(identity: string): Promise<IWebsocketsConnectionRegistryData[]>;\n listViaTenant(tenant: string): Promise<IWebsocketsConnectionRegistryData[]>;\n listAll(): Promise<IWebsocketsConnectionRegistryData[]>;\n\n updateLastSeen(connectionId: string): Promise<void>;\n listStale(olderThan: Date): Promise<IWebsocketsConnectionRegistryData[]>;\n}\n\nexport const ConnectionRegistry =\n createAbstraction<IWebsocketsConnectionRegistry>(\"ConnectionRegistry\");\n\nexport namespace ConnectionRegistry {\n export type Interface = IWebsocketsConnectionRegistry;\n export type Identity = IWebsocketsIdentity;\n export type Data = IWebsocketsConnectionRegistryData;\n export type RegisterParams = IWebsocketsConnectionRegistryRegisterParams;\n export type UnregisterParams = IWebsocketsConnectionRegistryUnregisterParams;\n}\n"],"names":["ConnectionRegistry","createAbstraction"],"mappings":";AAsCO,MAAMA,qBACTC,kBAAiD"}
1
+ {"version":3,"file":"features/ConnectionRegistry/abstractions.js","sources":["../../../src/features/ConnectionRegistry/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { IWebsocketsIdentity } from \"~/types.js\";\n\nexport interface IWebsocketsConnectionRegistryData {\n connectionId: string;\n identity: IWebsocketsIdentity;\n tenant: string;\n connectedOn: string;\n endpoint: string;\n /*\n * The process holding the live socket, on a server that runs several processes. Absent where\n * one service holds every socket (API Gateway on AWS) and on rows written before it existed.\n */\n owner?: string;\n}\n\nexport interface IWebsocketsConnectionRegistryRegisterParams {\n connectionId: string;\n tenant: string;\n identity: IWebsocketsIdentity;\n endpoint: string;\n connectedOn: string;\n owner?: string;\n}\n\nexport interface IWebsocketsConnectionRegistryUnregisterParams {\n connectionId: string;\n}\n\nexport interface IWebsocketsConnectionRegistry {\n register(\n event: IWebsocketsConnectionRegistryRegisterParams\n ): Promise<IWebsocketsConnectionRegistryData>;\n unregister(event: IWebsocketsConnectionRegistryUnregisterParams): Promise<void>;\n\n listViaConnections(connections: string[]): Promise<IWebsocketsConnectionRegistryData[]>;\n listViaIdentity(identity: string): Promise<IWebsocketsConnectionRegistryData[]>;\n listViaTenant(tenant: string): Promise<IWebsocketsConnectionRegistryData[]>;\n listAll(): Promise<IWebsocketsConnectionRegistryData[]>;\n\n updateLastSeen(connectionId: string): Promise<void>;\n listStale(olderThan: Date): Promise<IWebsocketsConnectionRegistryData[]>;\n}\n\nexport const ConnectionRegistry =\n createAbstraction<IWebsocketsConnectionRegistry>(\"ConnectionRegistry\");\n\nexport namespace ConnectionRegistry {\n export type Interface = IWebsocketsConnectionRegistry;\n export type Identity = IWebsocketsIdentity;\n export type Data = IWebsocketsConnectionRegistryData;\n export type RegisterParams = IWebsocketsConnectionRegistryRegisterParams;\n export type UnregisterParams = IWebsocketsConnectionRegistryUnregisterParams;\n}\n"],"names":["ConnectionRegistry","createAbstraction"],"mappings":";AA4CO,MAAMA,qBACTC,kBAAiD"}
@@ -2,12 +2,14 @@ import { Result } from "@webiny/feature/api";
2
2
  import type { GenericRecord } from "@webiny/api/types.js";
3
3
  import { WebsocketsListConnectionsUseCase } from "../../features/ListConnections/abstractions.js";
4
4
  import { WebsocketsTransport } from "../../transport/index.js";
5
+ import { Logger } from "@webiny/api-core/features/logger/index.js";
5
6
  import { WebsocketsSendToIdentityUseCase } from "./abstractions.js";
6
7
  import type { WebsocketsError } from "../../features/shared/errors.js";
7
8
  declare class SendToIdentityUseCaseImpl implements WebsocketsSendToIdentityUseCase.Interface {
8
9
  private readonly listConnections;
9
10
  private readonly transport;
10
- constructor(listConnections: WebsocketsListConnectionsUseCase.Interface, transport: WebsocketsTransport.Interface);
11
+ private readonly logger;
12
+ constructor(listConnections: WebsocketsListConnectionsUseCase.Interface, transport: WebsocketsTransport.Interface, logger: Logger.Interface);
11
13
  execute<T extends GenericRecord = GenericRecord>(identity: WebsocketsSendToIdentityUseCase.Identity, data: WebsocketsSendToIdentityUseCase.Data<T>): Promise<Result<void, WebsocketsError>>;
12
14
  }
13
15
  export declare const SendToIdentityUseCase: typeof SendToIdentityUseCaseImpl & {
@@ -1,12 +1,14 @@
1
1
  import { Result } from "@webiny/feature/api";
2
2
  import { WebsocketsListConnectionsUseCase } from "../ListConnections/abstractions.js";
3
3
  import { WebsocketsTransport } from "../../transport/index.js";
4
+ import { Logger } from "@webiny/api-core/features/logger/index.js";
4
5
  import { WebsocketsSendToIdentityUseCase } from "./abstractions.js";
5
6
  import { WebsocketServiceError } from "../shared/errors.js";
6
7
  class SendToIdentityUseCaseImpl {
7
- constructor(listConnections, transport){
8
+ constructor(listConnections, transport, logger){
8
9
  this.listConnections = listConnections;
9
10
  this.transport = transport;
11
+ this.logger = logger;
10
12
  }
11
13
  async execute(identity, data) {
12
14
  const result = await this.listConnections.execute({
@@ -15,6 +17,10 @@ class SendToIdentityUseCaseImpl {
15
17
  }
16
18
  });
17
19
  if (result.isFail()) return Result.fail(result.error);
20
+ if (0 === result.value.length) this.logger.warn({
21
+ identityId: identity.id,
22
+ action: data.action
23
+ }, "No websocket connections found for identity; message not sent.");
18
24
  try {
19
25
  await this.transport.send(result.value, data);
20
26
  } catch (error) {
@@ -27,7 +33,8 @@ const SendToIdentityUseCase = WebsocketsSendToIdentityUseCase.createImplementati
27
33
  implementation: SendToIdentityUseCaseImpl,
28
34
  dependencies: [
29
35
  WebsocketsListConnectionsUseCase,
30
- WebsocketsTransport
36
+ WebsocketsTransport,
37
+ Logger
31
38
  ]
32
39
  });
33
40
  export { SendToIdentityUseCase };
@@ -1 +1 @@
1
- {"version":3,"file":"features/SendToIdentity/SendToIdentityUseCase.js","sources":["../../../src/features/SendToIdentity/SendToIdentityUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport { WebsocketsListConnectionsUseCase } from \"~/features/ListConnections/abstractions.js\";\nimport { WebsocketsTransport } from \"~/transport/index.js\";\nimport { WebsocketsSendToIdentityUseCase } from \"./abstractions.js\";\nimport type { WebsocketsError } from \"~/features/shared/errors.js\";\nimport { WebsocketServiceError } from \"~/features/shared/errors.js\";\n\nclass SendToIdentityUseCaseImpl implements WebsocketsSendToIdentityUseCase.Interface {\n public constructor(\n private readonly listConnections: WebsocketsListConnectionsUseCase.Interface,\n private readonly transport: WebsocketsTransport.Interface\n ) {}\n\n public async execute<T extends GenericRecord = GenericRecord>(\n identity: WebsocketsSendToIdentityUseCase.Identity,\n data: WebsocketsSendToIdentityUseCase.Data<T>\n ): Promise<Result<void, WebsocketsError>> {\n const result = await this.listConnections.execute({\n where: {\n identityId: identity.id\n }\n });\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n try {\n await this.transport.send<T>(result.value, data);\n } catch (error) {\n return Result.fail(new WebsocketServiceError(error as Error));\n }\n\n return Result.ok();\n }\n}\n\nexport const SendToIdentityUseCase = WebsocketsSendToIdentityUseCase.createImplementation({\n implementation: SendToIdentityUseCaseImpl,\n dependencies: [WebsocketsListConnectionsUseCase, WebsocketsTransport]\n});\n"],"names":["SendToIdentityUseCaseImpl","listConnections","transport","identity","data","result","Result","error","WebsocketServiceError","SendToIdentityUseCase","WebsocketsSendToIdentityUseCase","WebsocketsListConnectionsUseCase","WebsocketsTransport"],"mappings":";;;;;AAQA,MAAMA;IACF,YACqBC,eAA2D,EAC3DC,SAAwC,CAC3D;aAFmBD,eAAe,GAAfA;aACAC,SAAS,GAATA;IAClB;IAEH,MAAa,QACTC,QAAkD,EAClDC,IAA6C,EACP;QACtC,MAAMC,SAAS,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC;YAC9C,OAAO;gBACH,YAAYF,SAAS,EAAE;YAC3B;QACJ;QAEA,IAAIE,OAAO,MAAM,IACb,OAAOC,OAAO,IAAI,CAACD,OAAO,KAAK;QAGnC,IAAI;YACA,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAIA,OAAO,KAAK,EAAED;QAC/C,EAAE,OAAOG,OAAO;YACZ,OAAOD,OAAO,IAAI,CAAC,IAAIE,sBAAsBD;QACjD;QAEA,OAAOD,OAAO,EAAE;IACpB;AACJ;AAEO,MAAMG,wBAAwBC,gCAAgC,oBAAoB,CAAC;IACtF,gBAAgBV;IAChB,cAAc;QAACW;QAAkCC;KAAoB;AACzE"}
1
+ {"version":3,"file":"features/SendToIdentity/SendToIdentityUseCase.js","sources":["../../../src/features/SendToIdentity/SendToIdentityUseCase.ts"],"sourcesContent":["import { Result } from \"@webiny/feature/api\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport { WebsocketsListConnectionsUseCase } from \"~/features/ListConnections/abstractions.js\";\nimport { WebsocketsTransport } from \"~/transport/index.js\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.js\";\nimport { WebsocketsSendToIdentityUseCase } from \"./abstractions.js\";\nimport type { WebsocketsError } from \"~/features/shared/errors.js\";\nimport { WebsocketServiceError } from \"~/features/shared/errors.js\";\n\nclass SendToIdentityUseCaseImpl implements WebsocketsSendToIdentityUseCase.Interface {\n public constructor(\n private readonly listConnections: WebsocketsListConnectionsUseCase.Interface,\n private readonly transport: WebsocketsTransport.Interface,\n private readonly logger: Logger.Interface\n ) {}\n\n public async execute<T extends GenericRecord = GenericRecord>(\n identity: WebsocketsSendToIdentityUseCase.Identity,\n data: WebsocketsSendToIdentityUseCase.Data<T>\n ): Promise<Result<void, WebsocketsError>> {\n const result = await this.listConnections.execute({\n where: {\n identityId: identity.id\n }\n });\n\n if (result.isFail()) {\n return Result.fail(result.error);\n }\n\n if (result.value.length === 0) {\n // Not an error for the caller (the user may simply have no tab open), but without this\n // an identity mismatch between sender and connection is indistinguishable from success.\n this.logger.warn(\n { identityId: identity.id, action: data.action },\n \"No websocket connections found for identity; message not sent.\"\n );\n }\n\n try {\n await this.transport.send<T>(result.value, data);\n } catch (error) {\n return Result.fail(new WebsocketServiceError(error as Error));\n }\n\n return Result.ok();\n }\n}\n\nexport const SendToIdentityUseCase = WebsocketsSendToIdentityUseCase.createImplementation({\n implementation: SendToIdentityUseCaseImpl,\n dependencies: [WebsocketsListConnectionsUseCase, WebsocketsTransport, Logger]\n});\n"],"names":["SendToIdentityUseCaseImpl","listConnections","transport","logger","identity","data","result","Result","error","WebsocketServiceError","SendToIdentityUseCase","WebsocketsSendToIdentityUseCase","WebsocketsListConnectionsUseCase","WebsocketsTransport","Logger"],"mappings":";;;;;;AASA,MAAMA;IACF,YACqBC,eAA2D,EAC3DC,SAAwC,EACxCC,MAAwB,CAC3C;aAHmBF,eAAe,GAAfA;aACAC,SAAS,GAATA;aACAC,MAAM,GAANA;IAClB;IAEH,MAAa,QACTC,QAAkD,EAClDC,IAA6C,EACP;QACtC,MAAMC,SAAS,MAAM,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC;YAC9C,OAAO;gBACH,YAAYF,SAAS,EAAE;YAC3B;QACJ;QAEA,IAAIE,OAAO,MAAM,IACb,OAAOC,OAAO,IAAI,CAACD,OAAO,KAAK;QAGnC,IAAIA,AAAwB,MAAxBA,OAAO,KAAK,CAAC,MAAM,EAGnB,IAAI,CAAC,MAAM,CAAC,IAAI,CACZ;YAAE,YAAYF,SAAS,EAAE;YAAE,QAAQC,KAAK,MAAM;QAAC,GAC/C;QAIR,IAAI;YACA,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CAAIC,OAAO,KAAK,EAAED;QAC/C,EAAE,OAAOG,OAAO;YACZ,OAAOD,OAAO,IAAI,CAAC,IAAIE,sBAAsBD;QACjD;QAEA,OAAOD,OAAO,EAAE;IACpB;AACJ;AAEO,MAAMG,wBAAwBC,gCAAgC,oBAAoB,CAAC;IACtF,gBAAgBX;IAChB,cAAc;QAACY;QAAkCC;QAAqBC;KAAO;AACjF"}
@@ -1,6 +1,7 @@
1
1
  import { GraphQLSchemaBuilder } from "@webiny/api-graphql/features/GraphQLSchemaBuilder/abstractions.js";
2
2
  import { CoreGraphQLSchemaFactory } from "@webiny/api-graphql/graphql/abstractions.core.js";
3
3
  declare class WebsocketsGraphQL implements CoreGraphQLSchemaFactory.Interface {
4
+ getSchemaKey: () => string;
4
5
  execute(builder: GraphQLSchemaBuilder.Interface): Promise<GraphQLSchemaBuilder.Interface>;
5
6
  }
6
7
  export declare const WebsocketsGraphQLFactory: typeof WebsocketsGraphQL & {
@@ -1,3 +1,4 @@
1
+ import { staticSchemaKey } from "@webiny/api-graphql/graphql/staticSchemaKey.js";
1
2
  import { CoreGraphQLSchemaFactory } from "@webiny/api-graphql/graphql/abstractions.core.js";
2
3
  import { ErrorResponse, Response } from "@webiny/api-graphql/responses.js";
3
4
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
@@ -182,6 +183,9 @@ class WebsocketsGraphQL {
182
183
  });
183
184
  return builder;
184
185
  }
186
+ constructor(){
187
+ this.getSchemaKey = staticSchemaKey("api-websockets/WebsocketsGraphQL");
188
+ }
185
189
  }
186
190
  const WebsocketsGraphQLFactory = CoreGraphQLSchemaFactory.createImplementation({
187
191
  dependencies: [],
@@ -1 +1 @@
1
- {"version":3,"file":"graphql/WebsocketsGraphQLFactory.js","sources":["../../src/graphql/WebsocketsGraphQLFactory.ts"],"sourcesContent":["import { GraphQLSchemaBuilder } from \"@webiny/api-graphql/features/GraphQLSchemaBuilder/abstractions.js\";\nimport { CoreGraphQLSchemaFactory } from \"@webiny/api-graphql/graphql/abstractions.core.js\";\nimport { ErrorResponse, Response } from \"@webiny/api-graphql/responses.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { NotAuthorizedError } from \"@webiny/api-core/features/security/shared/index.js\";\nimport { WebsocketsListConnectionsUseCase } from \"~/features/ListConnections/abstractions.js\";\nimport { WebsocketsDisconnectUseCase } from \"~/features/Disconnect/abstractions.js\";\nimport type { WebsocketsPermission } from \"~/types.js\";\n\ninterface IDisconnectConnectionsArgs {\n connections: string[];\n}\n\ninterface IDisconnectIdentityArgs {\n identityId: string;\n}\n\ninterface IDisconnectTenantArgs {\n tenant: string;\n}\n\nconst checkPermissions = async (identityContext: IdentityContext.Interface): Promise<void> => {\n const permissions = await identityContext.getPermissions<WebsocketsPermission>(\"websockets\");\n\n if (permissions.length === 0) {\n throw new NotAuthorizedError();\n }\n};\n\nclass WebsocketsGraphQL implements CoreGraphQLSchemaFactory.Interface {\n public async execute(\n builder: GraphQLSchemaBuilder.Interface\n ): Promise<GraphQLSchemaBuilder.Interface> {\n builder.addTypeDefs(`\n type WebsocketsIdentity {\n id: String!\n type: String\n displayName: String\n }\n\n type WebsocketsConnection {\n connectionId: String!\n endpoint: String!\n identity: WebsocketsIdentity!\n connectedOn: DateTime!\n tenant: String!\n }\n\n type WebsocketsError {\n message: String!\n code: String!\n data: JSON\n }\n\n type WebsocketsListConnectionsResponse {\n data: [WebsocketsConnection!]\n error: WebsocketsError\n }\n\n input WebsocketsListConnectionsWhereInput {\n identityId: String\n tenant: String\n }\n\n type WebsocketsDisconnectResponse {\n data: [WebsocketsConnection!]\n error: WebsocketsError\n }\n\n type WebsocketsQuery {\n _empty: String\n }\n\n type WebsocketsMutation {\n _empty: String\n }\n\n extend type Query {\n websockets: WebsocketsQuery\n }\n\n extend type Mutation {\n websockets: WebsocketsMutation\n }\n\n extend type WebsocketsQuery {\n listConnections(\n where: WebsocketsListConnectionsWhereInput\n ): WebsocketsListConnectionsResponse!\n }\n\n extend type WebsocketsMutation {\n disconnect(connections: [String!]!): WebsocketsDisconnectResponse!\n disconnectIdentity(identityId: String!): WebsocketsDisconnectResponse!\n disconnectTenant(tenant: String!): WebsocketsDisconnectResponse!\n disconnectAll: WebsocketsDisconnectResponse!\n }\n `);\n\n builder.addResolver({\n path: \"Query.websockets\",\n resolver: () => {\n return async () => {\n return {};\n };\n }\n });\n\n builder.addResolver({\n path: \"Mutation.websockets\",\n resolver: () => {\n return async () => {\n return {};\n };\n }\n });\n\n builder.addResolver<WebsocketsListConnectionsUseCase.Params>({\n path: \"WebsocketsQuery.listConnections\",\n dependencies: [IdentityContext, WebsocketsListConnectionsUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n listConnections: WebsocketsListConnectionsUseCase.Interface\n ) => {\n return async ({ args }: { args: WebsocketsListConnectionsUseCase.Params }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await listConnections.execute(args);\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectConnectionsArgs>({\n path: \"WebsocketsMutation.disconnect\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectConnectionsArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n connections: args.connections\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectIdentityArgs>({\n path: \"WebsocketsMutation.disconnectIdentity\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectIdentityArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n identityId: args.identityId\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectTenantArgs>({\n path: \"WebsocketsMutation.disconnectTenant\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectTenantArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n tenant: args.tenant\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver({\n path: \"WebsocketsMutation.disconnectAll\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async () => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute();\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n return builder;\n }\n}\n\nexport const WebsocketsGraphQLFactory = CoreGraphQLSchemaFactory.createImplementation({\n dependencies: [],\n implementation: WebsocketsGraphQL\n});\n"],"names":["checkPermissions","identityContext","permissions","NotAuthorizedError","WebsocketsGraphQL","builder","IdentityContext","WebsocketsListConnectionsUseCase","listConnections","args","result","ErrorResponse","Response","ex","WebsocketsDisconnectUseCase","disconnect","WebsocketsGraphQLFactory","CoreGraphQLSchemaFactory"],"mappings":";;;;;;AAqBA,MAAMA,mBAAmB,OAAOC;IAC5B,MAAMC,cAAc,MAAMD,gBAAgB,cAAc,CAAuB;IAE/E,IAAIC,AAAuB,MAAvBA,YAAY,MAAM,EAClB,MAAM,IAAIC;AAElB;AAEA,MAAMC;IACF,MAAa,QACTC,OAAuC,EACA;QACvCA,QAAQ,WAAW,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAgErB,CAAC;QAEDA,QAAQ,WAAW,CAAC;YAChB,MAAM;YACN,UAAU,IACC,UACI,EAAC;QAGpB;QAEAA,QAAQ,WAAW,CAAC;YAChB,MAAM;YACN,UAAU,IACC,UACI,EAAC;QAGpB;QAEAA,QAAQ,WAAW,CAA0C;YACzD,MAAM;YACN,cAAc;gBAACC;gBAAiBC;aAAiC;YACjE,UAAU,CACNN,iBACAO,kBAEO,OAAO,EAAEC,IAAI,EAAqD;oBACrE,IAAI;wBACA,MAAMT,iBAAiBC;wBAEvB,MAAMS,SAAS,MAAMF,gBAAgB,OAAO,CAACC;wBAE7C,IAAIC,OAAO,MAAM,IACb,OAAO,IAAIC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AAW,OAAO,CAAC;4BACpC,OAAO;gCACH,QAAQN,KAAK,MAAM;4BACvB;wBACJ;wBAEA,IAAIC,OAAO,MAAM,IACb,OAAO,IAAIC,cAAcD,OAAO,KAAK;wBAGzC,OAAO,IAAIE,SAASF,OAAO,KAAK;oBACpC,EAAE,OAAOG,IAAI;wBACT,OAAO,IAAIF,cAAcE;oBAC7B;gBACJ;QAER;QAEAR,QAAQ,WAAW,CAAC;YAChB,MAAM;YACN,cAAc;gBAACC;gBAAiBQ;aAA4B;YAC5D,UAAU,CACNb,iBACAc,aAEO;oBACH,IAAI;wBACA,MAAMf,iBAAiBC;wBAEvB,MAAMS,SAAS,MAAMK,WAAW,OAAO;wBAEvC,IAAIL,OAAO,MAAM,IACb,OAAO,IAAIC,cAAcD,OAAO,KAAK;wBAGzC,OAAO,IAAIE,SAASF,OAAO,KAAK;oBACpC,EAAE,OAAOG,IAAI;wBACT,OAAO,IAAIF,cAAcE;oBAC7B;gBACJ;QAER;QAEA,OAAOR;IACX;AACJ;AAEO,MAAMW,2BAA2BC,yBAAyB,oBAAoB,CAAC;IAClF,cAAc,EAAE;IAChB,gBAAgBb;AACpB"}
1
+ {"version":3,"file":"graphql/WebsocketsGraphQLFactory.js","sources":["../../src/graphql/WebsocketsGraphQLFactory.ts"],"sourcesContent":["import { GraphQLSchemaBuilder } from \"@webiny/api-graphql/features/GraphQLSchemaBuilder/abstractions.js\";\nimport { staticSchemaKey } from \"@webiny/api-graphql/graphql/staticSchemaKey.js\";\nimport { CoreGraphQLSchemaFactory } from \"@webiny/api-graphql/graphql/abstractions.core.js\";\nimport { ErrorResponse, Response } from \"@webiny/api-graphql/responses.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { NotAuthorizedError } from \"@webiny/api-core/features/security/shared/index.js\";\nimport { WebsocketsListConnectionsUseCase } from \"~/features/ListConnections/abstractions.js\";\nimport { WebsocketsDisconnectUseCase } from \"~/features/Disconnect/abstractions.js\";\nimport type { WebsocketsPermission } from \"~/types.js\";\n\ninterface IDisconnectConnectionsArgs {\n connections: string[];\n}\n\ninterface IDisconnectIdentityArgs {\n identityId: string;\n}\n\ninterface IDisconnectTenantArgs {\n tenant: string;\n}\n\nconst checkPermissions = async (identityContext: IdentityContext.Interface): Promise<void> => {\n const permissions = await identityContext.getPermissions<WebsocketsPermission>(\"websockets\");\n\n if (permissions.length === 0) {\n throw new NotAuthorizedError();\n }\n};\n\nclass WebsocketsGraphQL implements CoreGraphQLSchemaFactory.Interface {\n public getSchemaKey = staticSchemaKey(\"api-websockets/WebsocketsGraphQL\");\n\n public async execute(\n builder: GraphQLSchemaBuilder.Interface\n ): Promise<GraphQLSchemaBuilder.Interface> {\n builder.addTypeDefs(`\n type WebsocketsIdentity {\n id: String!\n type: String\n displayName: String\n }\n\n type WebsocketsConnection {\n connectionId: String!\n endpoint: String!\n identity: WebsocketsIdentity!\n connectedOn: DateTime!\n tenant: String!\n }\n\n type WebsocketsError {\n message: String!\n code: String!\n data: JSON\n }\n\n type WebsocketsListConnectionsResponse {\n data: [WebsocketsConnection!]\n error: WebsocketsError\n }\n\n input WebsocketsListConnectionsWhereInput {\n identityId: String\n tenant: String\n }\n\n type WebsocketsDisconnectResponse {\n data: [WebsocketsConnection!]\n error: WebsocketsError\n }\n\n type WebsocketsQuery {\n _empty: String\n }\n\n type WebsocketsMutation {\n _empty: String\n }\n\n extend type Query {\n websockets: WebsocketsQuery\n }\n\n extend type Mutation {\n websockets: WebsocketsMutation\n }\n\n extend type WebsocketsQuery {\n listConnections(\n where: WebsocketsListConnectionsWhereInput\n ): WebsocketsListConnectionsResponse!\n }\n\n extend type WebsocketsMutation {\n disconnect(connections: [String!]!): WebsocketsDisconnectResponse!\n disconnectIdentity(identityId: String!): WebsocketsDisconnectResponse!\n disconnectTenant(tenant: String!): WebsocketsDisconnectResponse!\n disconnectAll: WebsocketsDisconnectResponse!\n }\n `);\n\n builder.addResolver({\n path: \"Query.websockets\",\n resolver: () => {\n return async () => {\n return {};\n };\n }\n });\n\n builder.addResolver({\n path: \"Mutation.websockets\",\n resolver: () => {\n return async () => {\n return {};\n };\n }\n });\n\n builder.addResolver<WebsocketsListConnectionsUseCase.Params>({\n path: \"WebsocketsQuery.listConnections\",\n dependencies: [IdentityContext, WebsocketsListConnectionsUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n listConnections: WebsocketsListConnectionsUseCase.Interface\n ) => {\n return async ({ args }: { args: WebsocketsListConnectionsUseCase.Params }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await listConnections.execute(args);\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectConnectionsArgs>({\n path: \"WebsocketsMutation.disconnect\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectConnectionsArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n connections: args.connections\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectIdentityArgs>({\n path: \"WebsocketsMutation.disconnectIdentity\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectIdentityArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n identityId: args.identityId\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver<IDisconnectTenantArgs>({\n path: \"WebsocketsMutation.disconnectTenant\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async ({ args }: { args: IDisconnectTenantArgs }) => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute({\n where: {\n tenant: args.tenant\n }\n });\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n builder.addResolver({\n path: \"WebsocketsMutation.disconnectAll\",\n dependencies: [IdentityContext, WebsocketsDisconnectUseCase],\n resolver: (\n identityContext: IdentityContext.Interface,\n disconnect: WebsocketsDisconnectUseCase.Interface\n ) => {\n return async () => {\n try {\n await checkPermissions(identityContext);\n\n const result = await disconnect.execute();\n\n if (result.isFail()) {\n return new ErrorResponse(result.error);\n }\n\n return new Response(result.value);\n } catch (ex) {\n return new ErrorResponse(ex);\n }\n };\n }\n });\n\n return builder;\n }\n}\n\nexport const WebsocketsGraphQLFactory = CoreGraphQLSchemaFactory.createImplementation({\n dependencies: [],\n implementation: WebsocketsGraphQL\n});\n"],"names":["checkPermissions","identityContext","permissions","NotAuthorizedError","WebsocketsGraphQL","builder","IdentityContext","WebsocketsListConnectionsUseCase","listConnections","args","result","ErrorResponse","Response","ex","WebsocketsDisconnectUseCase","disconnect","staticSchemaKey","WebsocketsGraphQLFactory","CoreGraphQLSchemaFactory"],"mappings":";;;;;;;AAsBA,MAAMA,mBAAmB,OAAOC;IAC5B,MAAMC,cAAc,MAAMD,gBAAgB,cAAc,CAAuB;IAE/E,IAAIC,AAAuB,MAAvBA,YAAY,MAAM,EAClB,MAAM,IAAIC;AAElB;AAEA,MAAMC;IAGF,MAAa,QACTC,OAAuC,EACA;QACvCA,QAAQ,WAAW,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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
  if (!event.body) return {};
3
- if ("object" == typeof event.body) return event.body;
4
- if ("string" == typeof event.body) try {
3
+ else if ("object" == typeof event.body) return event.body;
4
+ else if ("string" == typeof event.body) try {
5
5
  return JSON.parse(event.body);
6
6
  } catch (ex) {
7
7
  console.log(ex.message);
@@ -1 +1 @@
1
- {"version":3,"file":"handler/headers.js","sources":["../../src/handler/headers.ts"],"sourcesContent":["import type { IWebsocketsEventData, IWebsocketsIncomingEvent } from \"~/handler/types.js\";\n\nconst getEventBody = (event: IWebsocketsIncomingEvent): IWebsocketsEventData => {\n if (!event.body) {\n return {};\n } else if (typeof event.body === \"object\") {\n return event.body;\n } else if (typeof event.body === \"string\") {\n try {\n return JSON.parse(event.body);\n } catch (ex) {\n console.log(ex.message);\n return {};\n }\n }\n console.log(\"Unexpected event.body type:\", typeof event.body);\n return {};\n};\n\nconst getToken = (body: IWebsocketsEventData, event: IWebsocketsIncomingEvent): string | null => {\n return body?.token || event.queryStringParameters?.token || null;\n};\n\nconst getTenant = (body: IWebsocketsEventData, event: IWebsocketsIncomingEvent): string => {\n return body?.tenant || event.queryStringParameters?.tenant || \"root\";\n};\n\nconst getEndpoint = (event: IWebsocketsIncomingEvent): string => {\n // The API Gateway Management API endpoint used to post messages back to a connection. It MUST be\n // the real WS API endpoint (https://<domainName>/<stage>); \"manage\" was a placeholder that made\n // every server→client send() target an invalid endpoint and silently fail.\n const rc = event.requestContext;\n if (rc?.domainName && rc?.stage) {\n return `https://${rc.domainName}/${rc.stage}`;\n }\n return \"manage\";\n};\n\nexport const getEventValues = (event: IWebsocketsIncomingEvent) => {\n const body = getEventBody(event);\n\n const token = getToken(body, event);\n const tenant = getTenant(body, event);\n return {\n tenant,\n token,\n endpoint: getEndpoint(event)\n };\n};\n"],"names":["getEventBody","event","JSON","ex","console","getToken","body","getTenant","getEndpoint","rc","getEventValues","token","tenant"],"mappings":"AAEA,MAAMA,eAAe,CAACC;IAClB,IAAI,CAACA,MAAM,IAAI,EACX,OAAO,CAAC;IACL,IAAI,AAAsB,YAAtB,OAAOA,MAAM,IAAI,EACxB,OAAOA,MAAM,IAAI;IACd,IAAI,AAAsB,YAAtB,OAAOA,MAAM,IAAI,EACxB,IAAI;QACA,OAAOC,KAAK,KAAK,CAACD,MAAM,IAAI;IAChC,EAAE,OAAOE,IAAI;QACTC,QAAQ,GAAG,CAACD,GAAG,OAAO;QACtB,OAAO,CAAC;IACZ;IAEJC,QAAQ,GAAG,CAAC,+BAA+B,OAAOH,MAAM,IAAI;IAC5D,OAAO,CAAC;AACZ;AAEA,MAAMI,WAAW,CAACC,MAA4BL,QACnCK,MAAM,SAASL,MAAM,qBAAqB,EAAE,SAAS;AAGhE,MAAMM,YAAY,CAACD,MAA4BL,QACpCK,MAAM,UAAUL,MAAM,qBAAqB,EAAE,UAAU;AAGlE,MAAMO,cAAc,CAACP;IAIjB,MAAMQ,KAAKR,MAAM,cAAc;IAC/B,IAAIQ,IAAI,cAAcA,IAAI,OACtB,OAAO,CAAC,QAAQ,EAAEA,GAAG,UAAU,CAAC,CAAC,EAAEA,GAAG,KAAK,EAAE;IAEjD,OAAO;AACX;AAEO,MAAMC,iBAAiB,CAACT;IAC3B,MAAMK,OAAON,aAAaC;IAE1B,MAAMU,QAAQN,SAASC,MAAML;IAC7B,MAAMW,SAASL,UAAUD,MAAML;IAC/B,OAAO;QACHW;QACAD;QACA,UAAUH,YAAYP;IAC1B;AACJ"}
1
+ {"version":3,"file":"handler/headers.js","sources":["../../src/handler/headers.ts"],"sourcesContent":["import type { IWebsocketsEventData, IWebsocketsIncomingEvent } from \"~/handler/types.js\";\n\nconst getEventBody = (event: IWebsocketsIncomingEvent): IWebsocketsEventData => {\n if (!event.body) {\n return {};\n } else if (typeof event.body === \"object\") {\n return event.body;\n } else if (typeof event.body === \"string\") {\n try {\n return JSON.parse(event.body);\n } catch (ex) {\n console.log(ex.message);\n return {};\n }\n }\n console.log(\"Unexpected event.body type:\", typeof event.body);\n return {};\n};\n\nconst getToken = (body: IWebsocketsEventData, event: IWebsocketsIncomingEvent): string | null => {\n return body?.token || event.queryStringParameters?.token || null;\n};\n\nconst getTenant = (body: IWebsocketsEventData, event: IWebsocketsIncomingEvent): string => {\n return body?.tenant || event.queryStringParameters?.tenant || \"root\";\n};\n\nconst getEndpoint = (event: IWebsocketsIncomingEvent): string => {\n // The API Gateway Management API endpoint used to post messages back to a connection. It MUST be\n // the real WS API endpoint (https://<domainName>/<stage>); \"manage\" was a placeholder that made\n // every server→client send() target an invalid endpoint and silently fail.\n const rc = event.requestContext;\n if (rc?.domainName && rc?.stage) {\n return `https://${rc.domainName}/${rc.stage}`;\n }\n return \"manage\";\n};\n\nexport const getEventValues = (event: IWebsocketsIncomingEvent) => {\n const body = getEventBody(event);\n\n const token = getToken(body, event);\n const tenant = getTenant(body, event);\n return {\n tenant,\n token,\n endpoint: getEndpoint(event)\n };\n};\n"],"names":["getEventBody","event","JSON","ex","console","getToken","body","getTenant","getEndpoint","rc","getEventValues","token","tenant"],"mappings":"AAEA,MAAMA,eAAe,CAACC;IAClB,IAAI,CAACA,MAAM,IAAI,EACX,OAAO,CAAC;SACL,IAAI,AAAsB,YAAtB,OAAOA,MAAM,IAAI,EACxB,OAAOA,MAAM,IAAI;SACd,IAAI,AAAsB,YAAtB,OAAOA,MAAM,IAAI,EACxB,IAAI;QACA,OAAOC,KAAK,KAAK,CAACD,MAAM,IAAI;IAChC,EAAE,OAAOE,IAAI;QACTC,QAAQ,GAAG,CAACD,GAAG,OAAO;QACtB,OAAO,CAAC;IACZ;IAEJC,QAAQ,GAAG,CAAC,+BAA+B,OAAOH,MAAM,IAAI;IAC5D,OAAO,CAAC;AACZ;AAEA,MAAMI,WAAW,CAACC,MAA4BL,QACnCK,MAAM,SAASL,MAAM,qBAAqB,EAAE,SAAS;AAGhE,MAAMM,YAAY,CAACD,MAA4BL,QACpCK,MAAM,UAAUL,MAAM,qBAAqB,EAAE,UAAU;AAGlE,MAAMO,cAAc,CAACP;IAIjB,MAAMQ,KAAKR,MAAM,cAAc;IAC/B,IAAIQ,IAAI,cAAcA,IAAI,OACtB,OAAO,CAAC,QAAQ,EAAEA,GAAG,UAAU,CAAC,CAAC,EAAEA,GAAG,KAAK,EAAE;IAEjD,OAAO;AACX;AAEO,MAAMC,iBAAiB,CAACT;IAC3B,MAAMK,OAAON,aAAaC;IAE1B,MAAMU,QAAQN,SAASC,MAAML;IAC7B,MAAMW,SAASL,UAAUD,MAAML;IAC/B,OAAO;QACHW;QACAD;QACA,UAAUH,YAAYP;IAC1B;AACJ"}
@@ -1,15 +1,5 @@
1
- import type { IWebsocketsEventValidator } from "../validator/index.js";
2
- import type { IWebsocketsResponse } from "../response/index.js";
3
- import type { APIGatewayProxyResult, Context as LambdaContext } from "@webiny/aws-sdk/types/index.js";
4
1
  import type { GenericRecord } from "@webiny/api/types.js";
5
2
  import type { PartialDeep } from "type-fest";
6
- export interface HandlerCallable {
7
- (event: IWebsocketsIncomingEvent, context: LambdaContext): Promise<APIGatewayProxyResult>;
8
- }
9
- export interface HandlerParams {
10
- validator?: IWebsocketsEventValidator;
11
- response?: IWebsocketsResponse;
12
- }
13
3
  export declare enum WebsocketsEventRoute {
14
4
  connect = "$connect",
15
5
  disconnect = "$disconnect",
@@ -1 +1 @@
1
- {"version":3,"file":"handler/types.js","sources":["../../src/handler/types.ts"],"sourcesContent":["import type { IWebsocketsEventValidator } from \"~/validator/index.js\";\nimport type { IWebsocketsResponse } from \"~/response/index.js\";\nimport type {\n APIGatewayProxyResult,\n Context as LambdaContext\n} from \"@webiny/aws-sdk/types/index.js\";\nimport type { GenericRecord } from \"@webiny/api/types.js\";\nimport type { PartialDeep } from \"type-fest\";\n\nexport interface HandlerCallable {\n (event: IWebsocketsIncomingEvent, context: LambdaContext): Promise<APIGatewayProxyResult>;\n}\n\nexport interface HandlerParams {\n validator?: IWebsocketsEventValidator;\n response?: IWebsocketsResponse;\n}\n\nexport enum WebsocketsEventRoute {\n connect = \"$connect\",\n disconnect = \"$disconnect\",\n default = \"$default\"\n}\n\nexport interface IWebsocketsEventData {\n token?: string;\n tenant?: string;\n messageId?: string;\n action?: string;\n data?: GenericRecord;\n}\n\nexport enum WebsocketsEventRequestContextEventType {\n message = \"MESSAGE\",\n connect = \"CONNECT\",\n disconnect = \"DISCONNECT\"\n}\n\nexport interface IWebsocketsEventRequestContext {\n connectionId: string;\n connectedAt: number;\n domainName: string;\n eventType: WebsocketsEventRequestContextEventType;\n routeKey: WebsocketsEventRoute | string;\n stage: string;\n}\n\nexport interface IWebsocketsEventHeaders {\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 IWebsocketsEventQueryStringParameters {\n tenant?: string;\n token?: string;\n}\n\nexport interface IWebsocketsEvent<T extends IWebsocketsEventData = IWebsocketsEventData> {\n headers?: IWebsocketsEventHeaders;\n queryStringParameters?: IWebsocketsEventQueryStringParameters;\n requestContext: IWebsocketsEventRequestContext;\n body?: T;\n}\n\nexport interface IWebsocketsIncomingEvent extends PartialDeep<Omit<IWebsocketsEvent, \"body\">> {\n body?: string | GenericRecord;\n}\n"],"names":["WebsocketsEventRoute","WebsocketsEventRequestContextEventType"],"mappings":"AAkBO,IAAKA,6BAAoBA,WAAAA,GAAAA,SAApBA,oBAAoB;;;;WAApBA;;AAcL,IAAKC,+CAAsCA,WAAAA,GAAAA,SAAtCA,sCAAsC;;;;WAAtCA"}
1
+ {"version":3,"file":"handler/types.js","sources":["../../src/handler/types.ts"],"sourcesContent":["import 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 interface IWebsocketsEventData {\n token?: string;\n tenant?: string;\n messageId?: string;\n action?: string;\n data?: GenericRecord;\n}\n\nexport enum WebsocketsEventRequestContextEventType {\n message = \"MESSAGE\",\n connect = \"CONNECT\",\n disconnect = \"DISCONNECT\"\n}\n\nexport interface IWebsocketsEventRequestContext {\n connectionId: string;\n connectedAt: number;\n domainName: string;\n eventType: WebsocketsEventRequestContextEventType;\n routeKey: WebsocketsEventRoute | string;\n stage: string;\n}\n\nexport interface IWebsocketsEventHeaders {\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 IWebsocketsEventQueryStringParameters {\n tenant?: string;\n token?: string;\n}\n\nexport interface IWebsocketsEvent<T extends IWebsocketsEventData = IWebsocketsEventData> {\n headers?: IWebsocketsEventHeaders;\n queryStringParameters?: IWebsocketsEventQueryStringParameters;\n requestContext: IWebsocketsEventRequestContext;\n body?: T;\n}\n\nexport interface IWebsocketsIncomingEvent extends PartialDeep<Omit<IWebsocketsEvent, \"body\">> {\n body?: string | GenericRecord;\n}\n"],"names":["WebsocketsEventRoute","WebsocketsEventRequestContextEventType"],"mappings":"AAGO,IAAKA,6BAAoBA,WAAAA,GAAAA,SAApBA,oBAAoB;;;;WAApBA;;AAcL,IAAKC,+CAAsCA,WAAAA,GAAAA,SAAtCA,sCAAsC;;;;WAAtCA"}
package/index.d.ts CHANGED
@@ -7,4 +7,3 @@ export { WebsocketsRouteHandler } from "./features/Routes/abstractions.js";
7
7
  export type { IWebsocketsRouteHandler, IWebsocketsRouteHandlerParams } from "./features/Routes/abstractions.js";
8
8
  export type * from "./types.js";
9
9
  export { WebsocketsFeature } from "./WebsocketsFeature.js";
10
- export { WebSocketLambdaHandler } from "./WebSocketLambdaHandler.js";
package/index.js CHANGED
@@ -5,4 +5,3 @@ export * from "./registry/index.js";
5
5
  export * from "./features/ConnectionRegistry/abstractions.js";
6
6
  export { WebsocketsRouteHandler } from "./features/Routes/abstractions.js";
7
7
  export { WebsocketsFeature } from "./WebsocketsFeature.js";
8
- export { WebSocketLambdaHandler } from "./WebSocketLambdaHandler.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-websockets",
3
- "version": "6.6.0-alpha.0",
3
+ "version": "6.6.0-alpha.10",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,30 +16,27 @@
16
16
  },
17
17
  "license": "MIT",
18
18
  "dependencies": {
19
- "@webiny/api": "6.6.0-alpha.0",
20
- "@webiny/api-core": "6.6.0-alpha.0",
21
- "@webiny/api-graphql": "6.6.0-alpha.0",
22
- "@webiny/error": "6.6.0-alpha.0",
23
- "@webiny/event-handler-aws": "6.6.0-alpha.0",
24
- "@webiny/event-handler-core": "6.6.0-alpha.0",
25
- "@webiny/feature": "6.6.0-alpha.0",
26
- "@webiny/handler": "6.6.0-alpha.0",
27
- "type-fest": "5.8.0"
19
+ "@webiny/api": "6.6.0-alpha.10",
20
+ "@webiny/api-core": "6.6.0-alpha.10",
21
+ "@webiny/api-graphql": "6.6.0-alpha.10",
22
+ "@webiny/error": "6.6.0-alpha.10",
23
+ "@webiny/feature": "6.6.0-alpha.10",
24
+ "@webiny/handler": "6.6.0-alpha.10",
25
+ "type-fest": "5.10.0"
28
26
  },
29
27
  "devDependencies": {
30
- "@webiny/api-core-testing": "6.6.0-alpha.0",
31
- "@webiny/api-graphql": "6.6.0-alpha.0",
32
- "@webiny/api-headless-cms": "6.6.0-alpha.0",
33
- "@webiny/aws-sdk": "6.6.0-alpha.0",
34
- "@webiny/build-tools": "6.6.0-alpha.0",
35
- "@webiny/di": "1.0.2",
36
- "@webiny/project-utils": "6.6.0-alpha.0",
37
- "@webiny/wcp": "6.6.0-alpha.0",
28
+ "@webiny/api-core-testing": "6.6.0-alpha.10",
29
+ "@webiny/api-graphql": "6.6.0-alpha.10",
30
+ "@webiny/api-headless-cms": "6.6.0-alpha.10",
31
+ "@webiny/build-tools": "6.6.0-alpha.10",
32
+ "@webiny/di": "2.0.0",
33
+ "@webiny/event-handler-core": "6.6.0-alpha.10",
34
+ "@webiny/wcp": "6.6.0-alpha.10",
38
35
  "graphql": "16.14.2",
39
36
  "rimraf": "6.1.3",
40
- "type-fest": "5.8.0",
37
+ "type-fest": "5.10.0",
41
38
  "typescript": "7.0.2",
42
- "vitest": "4.1.10"
39
+ "vitest": "5.0.5"
43
40
  },
44
41
  "publishConfig": {
45
42
  "access": "public"
@@ -96,7 +96,7 @@ class WebsocketsRunner {
96
96
  async respond(params) {
97
97
  const { connectionId, endpoint, eventType, result, messageId } = params;
98
98
  if ("message" !== eventType) return;
99
- if (!connectionId || !endpoint) {
99
+ else if (!connectionId || !endpoint) {
100
100
  const message = "No connectionId or endpoint.";
101
101
  const data = {
102
102
  connectionId,
@@ -1 +1 @@
1
- {"version":3,"file":"runner/WebsocketsRunner.js","sources":["../../src/runner/WebsocketsRunner.ts"],"sourcesContent":["import WebinyError from \"@webiny/error\";\nimport type {\n IWebsocketsEvent,\n IWebsocketsEventContext,\n IWebsocketsEventData,\n WebsocketsRoute,\n WebsocketsEventType,\n Context\n} from \"~/types.js\";\nimport { ConnectionRegistry } from \"~/features/ConnectionRegistry/abstractions.js\";\nimport type { IWebsocketsRunner } from \"./abstractions/WebsocketsRunner.js\";\nimport type { IWebsocketsRunnerResponse } from \"./abstractions/WebsocketsRunner.js\";\nimport { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\nimport { middleware } from \"~/utils/middleware.js\";\nimport { WebsocketsResponse } from \"~/response/index.js\";\nimport { WebsocketsTransport } from \"~/transport/index.js\";\nimport { WebsocketsSendToConnectionsUseCase } from \"~/features/SendToConnections/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/abstractions.js\";\n\ntype MiddlewareParams = Pick<WebsocketsRouteHandler.Params, \"event\" | \"registry\" | \"container\">;\n\ninterface IWebsocketsRunnerRespondParams extends Pick<\n IWebsocketsEventContext,\n \"connectionId\" | \"endpoint\" | \"eventType\"\n> {\n messageId?: string;\n result: WebsocketsResponse.OkResult | WebsocketsResponse.ErrorResult;\n}\n\nexport class WebsocketsRunner implements IWebsocketsRunner {\n private readonly context: Context;\n private readonly registry: ConnectionRegistry.Interface;\n private readonly response: WebsocketsResponse.Interface;\n private readonly sendToConnections: WebsocketsSendToConnectionsUseCase.Interface;\n\n public constructor(context: Context, response: WebsocketsResponse.Interface) {\n this.context = context;\n this.registry = context.container.resolve(ConnectionRegistry);\n this.response = response;\n this.sendToConnections = context.container.resolve(WebsocketsSendToConnectionsUseCase);\n }\n\n public async run<T extends IWebsocketsEventData = IWebsocketsEventData>(\n event: IWebsocketsEvent<T>\n ): Promise<IWebsocketsRunnerResponse> {\n let result: WebsocketsResponse.OkResult | WebsocketsResponse.ErrorResult;\n try {\n result = await this.executeRoute(event);\n } catch (ex) {\n result = this.response.error({\n message: `Route \"${event.context.route}\" action failed.`,\n error: {\n message: ex.message,\n code: ex.code,\n data: ex.data,\n stack: ex.stack\n }\n });\n }\n try {\n await this.respond({\n connectionId: event.context.connectionId,\n endpoint: event.context.endpoint,\n eventType: event.context.eventType,\n messageId: event.body?.messageId,\n result\n });\n return result;\n } catch (ex) {\n return this.response.error({\n message: \"Failed to respond to the request.\",\n error: {\n message: ex.message,\n code: ex.code,\n data: {\n ...ex.data,\n result\n },\n stack: ex.stack\n }\n });\n }\n }\n\n private getRouteHandlers(route: WebsocketsRoute | string): WebsocketsRouteHandler.Interface[] {\n const handlers = this.context.container\n .resolveAll(WebsocketsRouteHandler)\n .filter(handler => handler.route === route);\n if (handlers.length === 0) {\n throw new WebinyError(\n `There are no handlers for the route: ${route}.`,\n \"NO_ROUTE_HANDLERS\",\n {\n route\n }\n );\n }\n return handlers;\n }\n\n private async executeRoute(event: IWebsocketsEvent): Promise<IWebsocketsRunnerResponse> {\n const handlers = this.getRouteHandlers(event.context.route).reverse();\n\n const getTenant = () => {\n const tenant = this.context.container.resolve(TenantContext).getTenant();\n return tenant?.id || null;\n };\n\n const getIdentity = (): ConnectionRegistry.Identity | null => {\n const identity = this.context.container.resolve(IdentityContext).getIdentity();\n return identity || null;\n };\n\n const action = middleware<MiddlewareParams, IWebsocketsRunnerResponse>(\n handlers.map(handler => {\n return async (params, next) => {\n return handler.run({\n registry: params.registry,\n event: params.event,\n container: params.container,\n getTenant,\n getIdentity,\n response: this.response,\n next\n });\n };\n })\n );\n\n const result = await action({\n event,\n registry: this.registry,\n container: this.context.container\n });\n if (result) {\n return result;\n }\n const message = \"No response from the route action.\";\n return this.response.error({\n message,\n error: {\n message,\n code: \"NO_RESPONSE\"\n },\n statusCode: 404\n });\n }\n\n private async respond(params: IWebsocketsRunnerRespondParams): Promise<void> {\n const { connectionId, endpoint, eventType, result, messageId } = params;\n if (eventType !== \"message\") {\n return;\n } else if (!connectionId || !endpoint) {\n const message = \"No connectionId or endpoint.\";\n const data = {\n connectionId,\n endpoint\n };\n console.error(message, JSON.stringify(data));\n throw new WebinyError(message, \"GENERAL_ERROR\", data);\n }\n const connection: WebsocketsTransport.SendConnection = {\n connectionId,\n endpoint\n };\n\n const dataToSend = {\n ...result,\n messageId\n };\n await this.sendToConnections.execute([connection], dataToSend);\n }\n}\n\nexport namespace WebsocketsRunner {\n export type Event<T extends IWebsocketsEventData = IWebsocketsEventData> = IWebsocketsEvent<T>;\n export type EventData = IWebsocketsEventData;\n export type EventContext = IWebsocketsEventContext;\n export type EventType = WebsocketsEventType;\n export type Route = WebsocketsRoute;\n export type Response = IWebsocketsRunnerResponse;\n}\n"],"names":["WebsocketsRunner","context","response","ConnectionRegistry","WebsocketsSendToConnectionsUseCase","event","result","ex","route","handlers","WebsocketsRouteHandler","handler","WebinyError","getTenant","tenant","TenantContext","getIdentity","identity","IdentityContext","action","middleware","params","next","message","connectionId","endpoint","eventType","messageId","data","console","JSON","connection","dataToSend"],"mappings":";;;;;;;AA8BO,MAAMA;IAMT,YAAmBC,OAAgB,EAAEC,QAAsC,CAAE;QACzE,IAAI,CAAC,OAAO,GAAGD;QACf,IAAI,CAAC,QAAQ,GAAGA,QAAQ,SAAS,CAAC,OAAO,CAACE;QAC1C,IAAI,CAAC,QAAQ,GAAGD;QAChB,IAAI,CAAC,iBAAiB,GAAGD,QAAQ,SAAS,CAAC,OAAO,CAACG;IACvD;IAEA,MAAa,IACTC,KAA0B,EACQ;QAClC,IAAIC;QACJ,IAAI;YACAA,SAAS,MAAM,IAAI,CAAC,YAAY,CAACD;QACrC,EAAE,OAAOE,IAAI;YACTD,SAAS,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;gBACzB,SAAS,CAAC,OAAO,EAAED,MAAM,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC;gBACxD,OAAO;oBACH,SAASE,GAAG,OAAO;oBACnB,MAAMA,GAAG,IAAI;oBACb,MAAMA,GAAG,IAAI;oBACb,OAAOA,GAAG,KAAK;gBACnB;YACJ;QACJ;QACA,IAAI;YACA,MAAM,IAAI,CAAC,OAAO,CAAC;gBACf,cAAcF,MAAM,OAAO,CAAC,YAAY;gBACxC,UAAUA,MAAM,OAAO,CAAC,QAAQ;gBAChC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AAQ;oBACvBM;gBACJ;QAKZ,MAAMhB,SAAS,MAAMa,OAAO;YACxBd;YACA,UAAU,IAAI,CAAC,QAAQ;YACvB,WAAW,IAAI,CAAC,OAAO,CAAC,SAAS;QACrC;QACA,IAAIC,QACA,OAAOA;QAEX,MAAMiB,UAAU;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YACvBA;YACA,OAAO;gBACHA;gBACA,MAAM;YACV;YACA,YAAY;QAChB;IACJ;IAEA,MAAc,QAAQF,MAAsC,EAAiB;QACzE,MAAM,EAAEG,YAAY,EAAEC,QAAQ,EAAEC,SAAS,EAAEpB,MAAM,EAAEqB,SAAS,EAAE,GAAGN;QACjE,IAAIK,AAAc,cAAdA,WACA;QACG,IAAI,CAACF,gBAAgB,CAACC,UAAU;YACnC,MAAMF,UAAU;YAChB,MAAMK,OAAO;gBACTJ;gBACAC;YACJ;YACAI,QAAQ,KAAK,CAACN,SAASO,KAAK,SAAS,CAACF;YACtC,MAAM,IAAIhB,MAAYW,SAAS,iBAAiBK;QACpD;QACA,MAAMG,aAAiD;YACnDP;YACAC;QACJ;QAEA,MAAMO,aAAa;YACf,GAAG1B,MAAM;YACTqB;QACJ;QACA,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC;YAACI;SAAW,EAAEC;IACvD;AACJ"}
1
+ {"version":3,"file":"runner/WebsocketsRunner.js","sources":["../../src/runner/WebsocketsRunner.ts"],"sourcesContent":["import WebinyError from \"@webiny/error\";\nimport type {\n IWebsocketsEvent,\n IWebsocketsEventContext,\n IWebsocketsEventData,\n WebsocketsRoute,\n WebsocketsEventType,\n Context\n} from \"~/types.js\";\nimport { ConnectionRegistry } from \"~/features/ConnectionRegistry/abstractions.js\";\nimport type { IWebsocketsRunner } from \"./abstractions/WebsocketsRunner.js\";\nimport type { IWebsocketsRunnerResponse } from \"./abstractions/WebsocketsRunner.js\";\nimport { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\nimport { middleware } from \"~/utils/middleware.js\";\nimport { WebsocketsResponse } from \"~/response/index.js\";\nimport { WebsocketsTransport } from \"~/transport/index.js\";\nimport { WebsocketsSendToConnectionsUseCase } from \"~/features/SendToConnections/abstractions.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/abstractions.js\";\n\ntype MiddlewareParams = Pick<WebsocketsRouteHandler.Params, \"event\" | \"registry\" | \"container\">;\n\ninterface IWebsocketsRunnerRespondParams extends Pick<\n IWebsocketsEventContext,\n \"connectionId\" | \"endpoint\" | \"eventType\"\n> {\n messageId?: string;\n result: WebsocketsResponse.OkResult | WebsocketsResponse.ErrorResult;\n}\n\nexport class WebsocketsRunner implements IWebsocketsRunner {\n private readonly context: Context;\n private readonly registry: ConnectionRegistry.Interface;\n private readonly response: WebsocketsResponse.Interface;\n private readonly sendToConnections: WebsocketsSendToConnectionsUseCase.Interface;\n\n public constructor(context: Context, response: WebsocketsResponse.Interface) {\n this.context = context;\n this.registry = context.container.resolve(ConnectionRegistry);\n this.response = response;\n this.sendToConnections = context.container.resolve(WebsocketsSendToConnectionsUseCase);\n }\n\n public async run<T extends IWebsocketsEventData = IWebsocketsEventData>(\n event: IWebsocketsEvent<T>\n ): Promise<IWebsocketsRunnerResponse> {\n let result: WebsocketsResponse.OkResult | WebsocketsResponse.ErrorResult;\n try {\n result = await this.executeRoute(event);\n } catch (ex) {\n result = this.response.error({\n message: `Route \"${event.context.route}\" action failed.`,\n error: {\n message: ex.message,\n code: ex.code,\n data: ex.data,\n stack: ex.stack\n }\n });\n }\n try {\n await this.respond({\n connectionId: event.context.connectionId,\n endpoint: event.context.endpoint,\n eventType: event.context.eventType,\n messageId: event.body?.messageId,\n result\n });\n return result;\n } catch (ex) {\n return this.response.error({\n message: \"Failed to respond to the request.\",\n error: {\n message: ex.message,\n code: ex.code,\n data: {\n ...ex.data,\n result\n },\n stack: ex.stack\n }\n });\n }\n }\n\n private getRouteHandlers(route: WebsocketsRoute | string): WebsocketsRouteHandler.Interface[] {\n const handlers = this.context.container\n .resolveAll(WebsocketsRouteHandler)\n .filter(handler => handler.route === route);\n if (handlers.length === 0) {\n throw new WebinyError(\n `There are no handlers for the route: ${route}.`,\n \"NO_ROUTE_HANDLERS\",\n {\n route\n }\n );\n }\n return handlers;\n }\n\n private async executeRoute(event: IWebsocketsEvent): Promise<IWebsocketsRunnerResponse> {\n const handlers = this.getRouteHandlers(event.context.route).reverse();\n\n const getTenant = () => {\n const tenant = this.context.container.resolve(TenantContext).getTenant();\n return tenant?.id || null;\n };\n\n const getIdentity = (): ConnectionRegistry.Identity | null => {\n const identity = this.context.container.resolve(IdentityContext).getIdentity();\n return identity || null;\n };\n\n const action = middleware<MiddlewareParams, IWebsocketsRunnerResponse>(\n handlers.map(handler => {\n return async (params, next) => {\n return handler.run({\n registry: params.registry,\n event: params.event,\n container: params.container,\n getTenant,\n getIdentity,\n response: this.response,\n next\n });\n };\n })\n );\n\n const result = await action({\n event,\n registry: this.registry,\n container: this.context.container\n });\n if (result) {\n return result;\n }\n const message = \"No response from the route action.\";\n return this.response.error({\n message,\n error: {\n message,\n code: \"NO_RESPONSE\"\n },\n statusCode: 404\n });\n }\n\n private async respond(params: IWebsocketsRunnerRespondParams): Promise<void> {\n const { connectionId, endpoint, eventType, result, messageId } = params;\n if (eventType !== \"message\") {\n return;\n } else if (!connectionId || !endpoint) {\n const message = \"No connectionId or endpoint.\";\n const data = {\n connectionId,\n endpoint\n };\n console.error(message, JSON.stringify(data));\n throw new WebinyError(message, \"GENERAL_ERROR\", data);\n }\n const connection: WebsocketsTransport.SendConnection = {\n connectionId,\n endpoint\n };\n\n const dataToSend = {\n ...result,\n messageId\n };\n await this.sendToConnections.execute([connection], dataToSend);\n }\n}\n\nexport namespace WebsocketsRunner {\n export type Event<T extends IWebsocketsEventData = IWebsocketsEventData> = IWebsocketsEvent<T>;\n export type EventData = IWebsocketsEventData;\n export type EventContext = IWebsocketsEventContext;\n export type EventType = WebsocketsEventType;\n export type Route = WebsocketsRoute;\n export type Response = IWebsocketsRunnerResponse;\n}\n"],"names":["WebsocketsRunner","context","response","ConnectionRegistry","WebsocketsSendToConnectionsUseCase","event","result","ex","route","handlers","WebsocketsRouteHandler","handler","WebinyError","getTenant","tenant","TenantContext","getIdentity","identity","IdentityContext","action","middleware","params","next","message","connectionId","endpoint","eventType","messageId","data","console","JSON","connection","dataToSend"],"mappings":";;;;;;;AA8BO,MAAMA;IAMT,YAAmBC,OAAgB,EAAEC,QAAsC,CAAE;QACzE,IAAI,CAAC,OAAO,GAAGD;QACf,IAAI,CAAC,QAAQ,GAAGA,QAAQ,SAAS,CAAC,OAAO,CAACE;QAC1C,IAAI,CAAC,QAAQ,GAAGD;QAChB,IAAI,CAAC,iBAAiB,GAAGD,QAAQ,SAAS,CAAC,OAAO,CAACG;IACvD;IAEA,MAAa,IACTC,KAA0B,EACQ;QAClC,IAAIC;QACJ,IAAI;YACAA,SAAS,MAAM,IAAI,CAAC,YAAY,CAACD;QACrC,EAAE,OAAOE,IAAI;YACTD,SAAS,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;gBACzB,SAAS,CAAC,OAAO,EAAED,MAAM,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC;gBACxD,OAAO;oBACH,SAASE,GAAG,OAAO;oBACnB,MAAMA,GAAG,IAAI;oBACb,MAAMA,GAAG,IAAI;oBACb,OAAOA,GAAG,KAAK;gBACnB;YACJ;QACJ;QACA,IAAI;YACA,MAAM,IAAI,CAAC,OAAO,CAAC;gBACf,cAAcF,MAAM,OAAO,CAAC,YAAY;gBACxC,UAAUA,MAAM,OAAO,CAAC,QAAQ;gBAChC,WAAWA,MAAM,OAAO,CAAC,SAAS;gBAClC,WAAWA,MAAM,IAAI,EAAE;gBACvBC;YACJ;YACA,OAAOA;QACX,EAAE,OAAOC,IAAI;YACT,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;gBACv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EX,MAAMiB,UAAU;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YACvBA;YACA,OAAO;gBACHA;gBACA,MAAM;YACV;YACA,YAAY;QAChB;IACJ;IAEA,MAAc,QAAQF,MAAsC,EAAiB;QACzE,MAAM,EAAEG,YAAY,EAAEC,QAAQ,EAAEC,SAAS,EAAEpB,MAAM,EAAEqB,SAAS,EAAE,GAAGN;QACjE,IAAIK,AAAc,cAAdA,WACA;aACG,IAAI,CAACF,gBAAgB,CAACC,UAAU;YACnC,MAAMF,UAAU;YAChB,MAAMK,OAAO;gBACTJ;gBACAC;YACJ;YACAI,QAAQ,KAAK,CAACN,SAASO,KAAK,SAAS,CAACF;YACtC,MAAM,IAAIhB,MAAYW,SAAS,iBAAiBK;QACpD;QACA,MAAMG,aAAiD;YACnDP;YACAC;QACJ;QAEA,MAAMO,aAAa;YACf,GAAG1B,MAAM;YACTqB;QACJ;QACA,MAAM,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC;YAACI;SAAW,EAAEC;IACvD;AACJ"}
@@ -11,7 +11,7 @@ const websocketsRouteConnect = {
11
11
  if (!tenant) return response.error({
12
12
  message: "Missing tenant."
13
13
  });
14
- if (!identity) return response.error({
14
+ else if (!identity) return response.error({
15
15
  message: "Missing identity."
16
16
  });
17
17
  await registry.register({
@@ -1 +1 @@
1
- {"version":3,"file":"runner/routes/connect.js","sources":["../../../src/runner/routes/connect.ts"],"sourcesContent":["import type { WebsocketsRoute } from \"~/types.js\";\nimport type { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\n\nconst CONNECT: WebsocketsRoute = \"connect\";\n\nconst getConnectedOn = (connectedAt?: number) => {\n if (!connectedAt) {\n return new Date().toISOString();\n }\n return new Date(connectedAt).toISOString();\n};\n\nexport const websocketsRouteConnect: WebsocketsRouteHandler.Interface = {\n route: CONNECT,\n async run({ registry, event, response, getTenant, getIdentity }) {\n const tenant = getTenant();\n const identity = getIdentity();\n if (!tenant) {\n return response.error({\n message: \"Missing tenant.\"\n });\n } else if (!identity) {\n return response.error({\n message: \"Missing identity.\"\n });\n }\n\n await registry.register({\n identity: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n connectionId: event.context.connectionId,\n tenant,\n endpoint: event.context.endpoint,\n connectedOn: getConnectedOn(event.context.connectedAt)\n });\n\n return response.ok();\n }\n};\n"],"names":["CONNECT","getConnectedOn","connectedAt","Date","websocketsRouteConnect","registry","event","response","getTenant","getIdentity","tenant","identity"],"mappings":"AAGA,MAAMA,UAA2B;AAEjC,MAAMC,iBAAiB,CAACC;IACpB,IAAI,CAACA,aACD,OAAO,IAAIC,OAAO,WAAW;IAEjC,OAAO,IAAIA,KAAKD,aAAa,WAAW;AAC5C;AAEO,MAAME,yBAA2D;IACpE,OAAOJ;IACP,MAAM,KAAI,EAAEK,QAAQ,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,SAAS,EAAEC,WAAW,EAAE;QAC3D,MAAMC,SAASF;QACf,MAAMG,WAAWF;QACjB,IAAI,CAACC,QACD,OAAOH,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QACG,IAAI,CAACI,UACR,OAAOJ,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QAGJ,MAAMF,SAAS,QAAQ,CAAC;YACpB,UAAU;gBACN,IAAIM,SAAS,EAAE;gBACf,aAAaA,SAAS,WAAW;gBACjC,MAAMA,SAAS,IAAI;YACvB;YACA,cAAcL,MAAM,OAAO,CAAC,YAAY;YACxCI;YACA,UAAUJ,MAAM,OAAO,CAAC,QAAQ;YAChC,aAAaL,eAAeK,MAAM,OAAO,CAAC,WAAW;QACzD;QAEA,OAAOC,SAAS,EAAE;IACtB;AACJ"}
1
+ {"version":3,"file":"runner/routes/connect.js","sources":["../../../src/runner/routes/connect.ts"],"sourcesContent":["import type { WebsocketsRoute } from \"~/types.js\";\nimport type { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\n\nconst CONNECT: WebsocketsRoute = \"connect\";\n\nconst getConnectedOn = (connectedAt?: number) => {\n if (!connectedAt) {\n return new Date().toISOString();\n }\n return new Date(connectedAt).toISOString();\n};\n\nexport const websocketsRouteConnect: WebsocketsRouteHandler.Interface = {\n route: CONNECT,\n async run({ registry, event, response, getTenant, getIdentity }) {\n const tenant = getTenant();\n const identity = getIdentity();\n if (!tenant) {\n return response.error({\n message: \"Missing tenant.\"\n });\n } else if (!identity) {\n return response.error({\n message: \"Missing identity.\"\n });\n }\n\n await registry.register({\n identity: {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n },\n connectionId: event.context.connectionId,\n tenant,\n endpoint: event.context.endpoint,\n connectedOn: getConnectedOn(event.context.connectedAt)\n });\n\n return response.ok();\n }\n};\n"],"names":["CONNECT","getConnectedOn","connectedAt","Date","websocketsRouteConnect","registry","event","response","getTenant","getIdentity","tenant","identity"],"mappings":"AAGA,MAAMA,UAA2B;AAEjC,MAAMC,iBAAiB,CAACC;IACpB,IAAI,CAACA,aACD,OAAO,IAAIC,OAAO,WAAW;IAEjC,OAAO,IAAIA,KAAKD,aAAa,WAAW;AAC5C;AAEO,MAAME,yBAA2D;IACpE,OAAOJ;IACP,MAAM,KAAI,EAAEK,QAAQ,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,SAAS,EAAEC,WAAW,EAAE;QAC3D,MAAMC,SAASF;QACf,MAAMG,WAAWF;QACjB,IAAI,CAACC,QACD,OAAOH,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;aACG,IAAI,CAACI,UACR,OAAOJ,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QAGJ,MAAMF,SAAS,QAAQ,CAAC;YACpB,UAAU;gBACN,IAAIM,SAAS,EAAE;gBACf,aAAaA,SAAS,WAAW;gBACjC,MAAMA,SAAS,IAAI;YACvB;YACA,cAAcL,MAAM,OAAO,CAAC,YAAY;YACxCI;YACA,UAAUJ,MAAM,OAAO,CAAC,QAAQ;YAChC,aAAaL,eAAeK,MAAM,OAAO,CAAC,WAAW;QACzD;QAEA,OAAOC,SAAS,EAAE;IACtB;AACJ"}
@@ -7,7 +7,7 @@ const websocketsRouteDefault = {
7
7
  if (!tenant) return response.error({
8
8
  message: "Missing tenant."
9
9
  });
10
- if (!identity) return response.error({
10
+ else if (!identity) return response.error({
11
11
  message: "Missing identity."
12
12
  });
13
13
  return response.ok();
@@ -1 +1 @@
1
- {"version":3,"file":"runner/routes/default.js","sources":["../../../src/runner/routes/default.ts"],"sourcesContent":["import type { WebsocketsRoute } from \"~/types.js\";\nimport type { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\n\nconst DEFAULT: WebsocketsRoute = \"default\";\n\nexport const websocketsRouteDefault: WebsocketsRouteHandler.Interface = {\n route: DEFAULT,\n async run({ response, getIdentity, getTenant }) {\n const tenant = getTenant();\n const identity = getIdentity();\n if (!tenant) {\n return response.error({\n message: \"Missing tenant.\"\n });\n } else if (!identity) {\n return response.error({\n message: \"Missing identity.\"\n });\n }\n\n return response.ok();\n }\n};\n"],"names":["DEFAULT","websocketsRouteDefault","response","getIdentity","getTenant","tenant","identity"],"mappings":"AAGA,MAAMA,UAA2B;AAE1B,MAAMC,yBAA2D;IACpE,OAAOD;IACP,MAAM,KAAI,EAAEE,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAE;QAC1C,MAAMC,SAASD;QACf,MAAME,WAAWH;QACjB,IAAI,CAACE,QACD,OAAOH,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QACG,IAAI,CAACI,UACR,OAAOJ,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QAGJ,OAAOA,SAAS,EAAE;IACtB;AACJ"}
1
+ {"version":3,"file":"runner/routes/default.js","sources":["../../../src/runner/routes/default.ts"],"sourcesContent":["import type { WebsocketsRoute } from \"~/types.js\";\nimport type { WebsocketsRouteHandler } from \"~/features/Routes/abstractions.js\";\n\nconst DEFAULT: WebsocketsRoute = \"default\";\n\nexport const websocketsRouteDefault: WebsocketsRouteHandler.Interface = {\n route: DEFAULT,\n async run({ response, getIdentity, getTenant }) {\n const tenant = getTenant();\n const identity = getIdentity();\n if (!tenant) {\n return response.error({\n message: \"Missing tenant.\"\n });\n } else if (!identity) {\n return response.error({\n message: \"Missing identity.\"\n });\n }\n\n return response.ok();\n }\n};\n"],"names":["DEFAULT","websocketsRouteDefault","response","getIdentity","getTenant","tenant","identity"],"mappings":"AAGA,MAAMA,UAA2B;AAE1B,MAAMC,yBAA2D;IACpE,OAAOD;IACP,MAAM,KAAI,EAAEE,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAE;QAC1C,MAAMC,SAASD;QACf,MAAME,WAAWH;QACjB,IAAI,CAACE,QACD,OAAOH,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;aACG,IAAI,CAACI,UACR,OAAOJ,SAAS,KAAK,CAAC;YAClB,SAAS;QACb;QAGJ,OAAOA,SAAS,EAAE;IACtB;AACJ"}
@@ -1,22 +0,0 @@
1
- import type { Container } from "@webiny/feature/api";
2
- import { WebSocketEventHandler } from "@webiny/event-handler-aws/abstractions/handlers/WebSocketEventHandler.js";
3
- import type { IWebSocketEvent } from "@webiny/event-handler-aws/eventTypes/WebSocketEventType.js";
4
- import type { IAuthenticationContext } from "@webiny/api-core/features/security/authentication/AuthenticationContext/abstractions.js";
5
- import type { IIdentityContext } from "@webiny/api-core/features/security/IdentityContext/abstractions.js";
6
- import type { ITenantContext } from "@webiny/api-core/features/tenancy/TenantContext/abstractions.js";
7
- import type { IGetTenantByIdUseCase } from "@webiny/api-core/features/tenancy/GetTenantById/abstractions.js";
8
- import type { EventContext, NextFunction } from "@webiny/event-handler-core";
9
- import type { APIGatewayProxyResult } from "@webiny/aws-sdk/types/index.js";
10
- declare class WebSocketLambdaHandlerImpl implements WebSocketEventHandler.Interface {
11
- private container;
12
- private authCtx;
13
- private identityCtx;
14
- private tenantCtx;
15
- private getTenantById;
16
- constructor(container: Container, authCtx: IAuthenticationContext, identityCtx: IIdentityContext, tenantCtx: ITenantContext, getTenantById: IGetTenantByIdUseCase);
17
- execute(eventCtx: EventContext<IWebSocketEvent>, _next: NextFunction): Promise<APIGatewayProxyResult>;
18
- }
19
- export declare const WebSocketLambdaHandler: typeof WebSocketLambdaHandlerImpl & {
20
- __abstraction: import("@webiny/di").Abstraction<import("@webiny/event-handler-aws/abstractions/handlers/WebSocketEventHandler.js").IWebSocketEventHandler>;
21
- };
22
- export {};
@@ -1,87 +0,0 @@
1
- import { WebSocketEventHandler } from "@webiny/event-handler-aws/abstractions/handlers/WebSocketEventHandler.js";
2
- import { RequestContainer } from "@webiny/event-handler-core";
3
- import { AuthenticationContext } from "@webiny/api-core/features/security/authentication/AuthenticationContext/index.js";
4
- import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
5
- import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
6
- import { GetTenantByIdUseCase } from "@webiny/api-core/features/tenancy/GetTenantById/index.js";
7
- import { WebsocketsRunner } from "./runner/index.js";
8
- import { WebsocketsResponse } from "./response/index.js";
9
- import { getEventValues } from "./handler/headers.js";
10
- import { WebsocketsEventRequestContextEventType, WebsocketsEventRoute } from "./handler/types.js";
11
- const toWebsocketsEvent = (raw, endpoint)=>{
12
- const rc = raw.requestContext ?? {};
13
- const eventTypeMap = {
14
- [WebsocketsEventRequestContextEventType.message]: "message",
15
- [WebsocketsEventRequestContextEventType.connect]: "connect",
16
- [WebsocketsEventRequestContextEventType.disconnect]: "disconnect"
17
- };
18
- const routeMap = {
19
- [WebsocketsEventRoute.connect]: "connect",
20
- [WebsocketsEventRoute.disconnect]: "disconnect",
21
- [WebsocketsEventRoute["default"]]: "default"
22
- };
23
- const routeKey = rc.routeKey;
24
- const route = routeMap[routeKey ?? ""] ?? "default";
25
- return {
26
- headers: raw.headers,
27
- context: {
28
- connectionId: rc.connectionId ?? "",
29
- connectedAt: rc.connectedAt ?? 0,
30
- host: rc.domainName ?? "",
31
- eventType: eventTypeMap[rc.eventType ?? ""] ?? "message",
32
- route,
33
- endpoint
34
- },
35
- body: "string" == typeof raw.body ? (()=>{
36
- try {
37
- return JSON.parse(raw.body);
38
- } catch {
39
- return {};
40
- }
41
- })() : raw.body
42
- };
43
- };
44
- class WebSocketLambdaHandlerImpl {
45
- constructor(container, authCtx, identityCtx, tenantCtx, getTenantById){
46
- this.container = container;
47
- this.authCtx = authCtx;
48
- this.identityCtx = identityCtx;
49
- this.tenantCtx = tenantCtx;
50
- this.getTenantById = getTenantById;
51
- }
52
- async execute(eventCtx, _next) {
53
- const ctx = {
54
- container: this.container
55
- };
56
- const raw = eventCtx.event;
57
- const { token, tenant, endpoint } = getEventValues(raw);
58
- const identity = await this.authCtx.authenticate(token ?? "");
59
- this.identityCtx.setIdentity(identity);
60
- const tenantResult = await this.getTenantById.execute(tenant);
61
- if (tenantResult.isOk()) this.tenantCtx.setTenant(tenantResult.value);
62
- const response = this.container.resolve(WebsocketsResponse);
63
- const runner = new WebsocketsRunner(ctx, response);
64
- const event = toWebsocketsEvent(raw, endpoint);
65
- const result = await runner.run(event);
66
- return {
67
- statusCode: result.statusCode,
68
- headers: {
69
- "sec-websocket-protocol": "webiny-ws-v1"
70
- },
71
- body: ""
72
- };
73
- }
74
- }
75
- const WebSocketLambdaHandler = WebSocketEventHandler.createImplementation({
76
- implementation: WebSocketLambdaHandlerImpl,
77
- dependencies: [
78
- RequestContainer,
79
- AuthenticationContext,
80
- IdentityContext,
81
- TenantContext,
82
- GetTenantByIdUseCase
83
- ]
84
- });
85
- export { WebSocketLambdaHandler };
86
-
87
- //# sourceMappingURL=WebSocketLambdaHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"WebSocketLambdaHandler.js","sources":["../src/WebSocketLambdaHandler.ts"],"sourcesContent":["import type { Container } from \"@webiny/feature/api\";\nimport { WebSocketEventHandler } from \"@webiny/event-handler-aws/abstractions/handlers/WebSocketEventHandler.js\";\nimport type { IWebSocketEvent } from \"@webiny/event-handler-aws/eventTypes/WebSocketEventType.js\";\nimport { RequestContainer } from \"@webiny/event-handler-core\";\nimport { AuthenticationContext } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { GetTenantByIdUseCase } from \"@webiny/api-core/features/tenancy/GetTenantById/index.js\";\nimport type { IAuthenticationContext } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/abstractions.js\";\nimport type { IIdentityContext } from \"@webiny/api-core/features/security/IdentityContext/abstractions.js\";\nimport type { ITenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/abstractions.js\";\nimport type { IGetTenantByIdUseCase } from \"@webiny/api-core/features/tenancy/GetTenantById/abstractions.js\";\nimport type { EventContext, NextFunction } from \"@webiny/event-handler-core\";\nimport type { APIGatewayProxyResult } from \"@webiny/aws-sdk/types/index.js\";\nimport { WebsocketsRunner } from \"~/runner/index.js\";\nimport { WebsocketsResponse } from \"~/response/index.js\";\nimport type { Context, IWebsocketsEvent, WebsocketsEventType, WebsocketsRoute } from \"~/types.js\";\nimport { getEventValues } from \"~/handler/headers.js\";\nimport type { IWebsocketsIncomingEvent } from \"~/handler/types.js\";\nimport { WebsocketsEventRequestContextEventType, WebsocketsEventRoute } from \"~/handler/types.js\";\n\nconst toWebsocketsEvent = (raw: IWebsocketsIncomingEvent, endpoint: string): IWebsocketsEvent => {\n const rc = raw.requestContext ?? {};\n const eventTypeMap: Record<string, WebsocketsEventType> = {\n [WebsocketsEventRequestContextEventType.message]: \"message\",\n [WebsocketsEventRequestContextEventType.connect]: \"connect\",\n [WebsocketsEventRequestContextEventType.disconnect]: \"disconnect\"\n };\n // AWS delivers routeKey as \"$connect\"/\"$disconnect\"/\"$default\"; route handlers register under the\n // un-prefixed WebsocketsRoute (\"connect\"/\"disconnect\"/\"default\"). Without this map the runner\n // matches the raw \"$connect\" and finds no handler (\"There are no handlers for the route: $connect\").\n const routeMap: Record<string, WebsocketsRoute> = {\n [WebsocketsEventRoute.connect]: \"connect\",\n [WebsocketsEventRoute.disconnect]: \"disconnect\",\n [WebsocketsEventRoute.default]: \"default\"\n };\n const routeKey = rc.routeKey as string | undefined;\n const route = routeMap[routeKey ?? \"\"] ?? \"default\";\n return {\n headers: raw.headers as Record<string, string> | undefined,\n context: {\n connectionId: rc.connectionId ?? \"\",\n connectedAt: rc.connectedAt ?? 0,\n host: rc.domainName ?? \"\",\n eventType: eventTypeMap[rc.eventType ?? \"\"] ?? \"message\",\n route,\n endpoint\n },\n body:\n typeof raw.body === \"string\"\n ? (() => {\n try {\n return JSON.parse(raw.body as string);\n } catch {\n return {};\n }\n })()\n : (raw.body as any)\n };\n};\n\nclass WebSocketLambdaHandlerImpl implements WebSocketEventHandler.Interface {\n constructor(\n private container: Container,\n private authCtx: IAuthenticationContext,\n private identityCtx: IIdentityContext,\n private tenantCtx: ITenantContext,\n private getTenantById: IGetTenantByIdUseCase\n ) {}\n\n async execute(\n eventCtx: EventContext<IWebSocketEvent>,\n _next: NextFunction\n ): Promise<APIGatewayProxyResult> {\n // Route handlers and all websockets services are resolved from the DI container;\n // the runner only needs `container` on the context object.\n const ctx: Record<string, any> = { container: this.container };\n\n const raw = eventCtx.event as IWebsocketsIncomingEvent;\n const { token, tenant, endpoint } = getEventValues(raw);\n\n const identity = await this.authCtx.authenticate(token ?? \"\");\n this.identityCtx.setIdentity(identity);\n\n const tenantResult = await this.getTenantById.execute(tenant);\n if (tenantResult.isOk()) {\n this.tenantCtx.setTenant(tenantResult.value);\n }\n\n const response = this.container.resolve(WebsocketsResponse);\n const runner = new WebsocketsRunner(ctx as Context, response);\n const event = toWebsocketsEvent(raw, endpoint);\n const result = await runner.run(event);\n\n return {\n statusCode: result.statusCode,\n headers: { \"sec-websocket-protocol\": \"webiny-ws-v1\" },\n body: \"\"\n };\n }\n}\n\nexport const WebSocketLambdaHandler = WebSocketEventHandler.createImplementation({\n implementation: WebSocketLambdaHandlerImpl,\n dependencies: [\n RequestContainer,\n AuthenticationContext,\n IdentityContext,\n TenantContext,\n GetTenantByIdUseCase\n ]\n});\n"],"names":["toWebsocketsEvent","raw","endpoint","rc","eventTypeMap","WebsocketsEventRequestContextEventType","routeMap","WebsocketsEventRoute","routeKey","route","JSON","WebSocketLambdaHandlerImpl","container","authCtx","identityCtx","tenantCtx","getTenantById","eventCtx","_next","ctx","token","tenant","getEventValues","identity","tenantResult","response","WebsocketsResponse","runner","WebsocketsRunner","event","result","WebSocketLambdaHandler","WebSocketEventHandler","RequestContainer","AuthenticationContext","IdentityContext","TenantContext","GetTenantByIdUseCase"],"mappings":";;;;;;;;;;AAqBA,MAAMA,oBAAoB,CAACC,KAA+BC;IACtD,MAAMC,KAAKF,IAAI,cAAc,IAAI,CAAC;IAClC,MAAMG,eAAoD;QACtD,CAACC,uCAAuC,OAAO,CAAC,EAAE;QAClD,CAACA,uCAAuC,OAAO,CAAC,EAAE;QAClD,CAACA,uCAAuC,UAAU,CAAC,EAAE;IACzD;IAIA,MAAMC,WAA4C;QAC9C,CAACC,qBAAqB,OAAO,CAAC,EAAE;QAChC,CAACA,qBAAqB,UAAU,CAAC,EAAE;QACnC,CAACA,oBAAoB,CAApBA,UAA4B,CAAC,EAAE;IACpC;IACA,MAAMC,WAAWL,GAAG,QAAQ;IAC5B,MAAMM,QAAQH,QAAQ,CAACE,YAAY,GAAG,IAAI;IAC1C,OAAO;QACH,SAASP,IAAI,OAAO;QACpB,SAAS;YACL,cAAcE,GAAG,YAAY,IAAI;YACjC,aAAaA,GAAG,WAAW,IAAI;YAC/B,MAAMA,GAAG,UAAU,IAAI;YACvB,WAAWC,YAAY,CAACD,GAAG,SAAS,IAAI,GAAG,IAAI;YAC/CM;YACAP;QACJ;QACA,MACI,AAAoB,YAApB,OAAOD,IAAI,IAAI,GACR,AAAC;YACE,IAAI;gBACA,OAAOS,KAAK,KAAK,CAACT,IAAI,IAAI;YAC9B,EAAE,OAAM;gBACJ,OAAO,CAAC;YACZ;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