@superblocksteam/sdk 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.json CHANGED
@@ -27,6 +27,9 @@
27
27
  "@typescript-eslint/no-unsafe-return": "off",
28
28
  "@typescript-eslint/no-unsafe-member-access": "off",
29
29
  "@typescript-eslint/restrict-template-expressions": "off",
30
+ "@typescript-eslint/no-unsafe-assignment": "off",
31
+ "@typescript-eslint/no-unsafe-argument": "off",
32
+ "@typescript-eslint/no-unsafe-call": "off",
30
33
  "import/order": [
31
34
  "error",
32
35
  {
package/dist/client.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ComponentEvent, LocalGitRepoState, SuperblocksResourceType } from "@superblocksteam/util";
2
+ import { RemoteCommitDto, UserMeDto } from "./types";
2
3
  export type ViewMode = "export-deployed" | "export-latest" | "export-live";
3
4
  export interface UploadFile {
4
5
  name: string;
@@ -63,7 +64,7 @@ export declare function fetchApis(cliVersion: string, token: string, superblocks
63
64
  export declare function validateGitSetup(cliVersion: string, resourceId: string, resourceType: SuperblocksResourceType, event: ComponentEvent, localGitRepoState: LocalGitRepoState, token: string, superblocksBaseUrl: string, injectedHeaders?: Record<string, string>): Promise<{
64
65
  branchName: string | null;
65
66
  }>;
66
- export declare function registerComponents(cliVersion: string, applicationId: string, componentConfigs: Record<string, any>, token: string, superblocksBaseUrl: string, branch: string | null, injectedHeaders?: Record<string, string>): Promise<any>;
67
+ export declare function registerComponents(cliVersion: string, applicationId: string, componentConfigs: Record<string, any>, token: string, superblocksBaseUrl: string, branch: string | null, injectedHeaders: Record<string, string>): Promise<any>;
67
68
  export declare function uploadComponents({ cliVersion, applicationId, componentConfigs, files, token, superblocksBaseUrl, branch, }: {
68
69
  cliVersion: string;
69
70
  applicationId: string;
@@ -72,8 +73,8 @@ export declare function uploadComponents({ cliVersion, applicationId, componentC
72
73
  token: string;
73
74
  superblocksBaseUrl: string;
74
75
  branch: string | null;
75
- }): Promise<any>;
76
- export declare function fetchCurrentUser(cliVersion: string, token: string, superblocksBaseUrl: string): Promise<any>;
76
+ }): Promise<void>;
77
+ export declare function fetchCurrentUser(cliVersion: string, token: string, superblocksBaseUrl: string): Promise<UserMeDto>;
77
78
  export declare function pushApplication({ cliVersion, applicationId, token, superblocksBaseUrl, applicationConfig, branch, injectedHeaders, }: {
78
79
  cliVersion: string;
79
80
  applicationId: string;
@@ -82,7 +83,7 @@ export declare function pushApplication({ cliVersion, applicationId, token, supe
82
83
  branch: string;
83
84
  injectedHeaders: Record<string, string>;
84
85
  applicationConfig: PushApplicationWithCommitConfig;
85
- }): Promise<ApplicationWrapper | undefined>;
86
+ }): Promise<RemoteCommitDto | undefined>;
86
87
  export declare function pushApi({ cliVersion, apiId, token, superblocksBaseUrl, apiConfig, branch, injectedHeaders, }: {
87
88
  cliVersion: string;
88
89
  apiId: string;
package/dist/client.js CHANGED
@@ -1,13 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.pushApi = exports.pushApplication = exports.fetchCurrentUser = exports.uploadComponents = exports.registerComponents = exports.validateGitSetup = exports.fetchApis = exports.fetchApi = exports.fetchApplications = exports.fetchApplicationWithComponents = exports.fetchApplicationBranches = exports.fetchApplication = void 0;
4
- const fs = require("fs");
4
+ const tslib_1 = require("tslib");
5
+ const fs = tslib_1.__importStar(require("fs"));
5
6
  const util_1 = require("@superblocksteam/util");
6
- const axios_1 = require("axios");
7
- const FormData = require("form-data");
7
+ const axios_1 = tslib_1.__importStar(require("axios"));
8
+ const form_data_1 = tslib_1.__importDefault(require("form-data"));
8
9
  const lodash_1 = require("lodash");
9
10
  const errors_1 = require("./errors");
10
- const BASE_BUCKETEER_URL = "api/v1";
11
+ const flag_1 = require("./flag");
12
+ const socket_1 = require("./socket");
13
+ const types_1 = require("./types");
14
+ const utils_1 = require("./utils");
15
+ const BASE_BUCKETEER_URL = "api";
11
16
  const BASE_SERVER_PUBLIC_API_URL = "api/v1/public";
12
17
  const SUPERBLOCKS_MAX_FILE_SIZE_MB = 10;
13
18
  const CLI_VERSION_HEADER = "x-superblocks-cli-version";
@@ -91,7 +96,7 @@ async function fetchApplicationWithComponents({ cliVersion, applicationId, branc
91
96
  const bucketeerBaseUrl = (0, util_1.getBucketeerUrlFromSuperblocksUrl)(superblocksBaseUrl);
92
97
  // fetch files from bucketeer
93
98
  const branchPath = branch ? `/branches/${encodeURIComponent(branch)}` : "";
94
- const componentFileURL = new URL(`${BASE_BUCKETEER_URL}/components/${applicationId}${branchPath}?commit=${commitId}&viewMode=${viewMode}`, bucketeerBaseUrl).toString();
99
+ const componentFileURL = new URL(`${BASE_BUCKETEER_URL}/v1/components/${applicationId}${branchPath}?commit=${commitId}&viewMode=${viewMode}`, bucketeerBaseUrl).toString();
95
100
  try {
96
101
  const config = {
97
102
  method: "get",
@@ -244,18 +249,39 @@ async function registerComponents(cliVersion, applicationId, componentConfigs, t
244
249
  var _a, _b, _c, _d, _e, _f, _g;
245
250
  try {
246
251
  const branchPath = branch ? `/branches/${encodeURIComponent(branch)}` : "";
247
- const config = {
248
- method: "put",
249
- url: new URL(`${BASE_SERVER_PUBLIC_API_URL}/application/${applicationId}${branchPath}/components`, superblocksBaseUrl).toString(),
250
- headers: {
251
- Authorization: "Bearer " + token,
252
- [CLI_VERSION_HEADER]: cliVersion,
253
- ...injectedHeaders,
254
- },
255
- data: { components: componentConfigs },
256
- };
257
- const response = await (0, axios_1.default)(config);
258
- return response.data;
252
+ const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
253
+ const organization = userMe.organizations[0];
254
+ if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
255
+ const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
256
+ const socket = await (0, socket_1.connectToISocketRPCServer)({
257
+ agentUrls,
258
+ superblocksBaseUrl,
259
+ token,
260
+ });
261
+ const resp = await socket.call.v1.public.application.component.register({
262
+ applicationId,
263
+ branchName: branch || "",
264
+ cliVersion: cliVersion,
265
+ componentEvent: injectedHeaders[util_1.COMPONENT_EVENT_HEADER],
266
+ components: componentConfigs,
267
+ });
268
+ socket.close();
269
+ return resp.data;
270
+ }
271
+ else {
272
+ const config = {
273
+ method: "put",
274
+ url: new URL(`${BASE_SERVER_PUBLIC_API_URL}/application/${applicationId}${branchPath}/components`, superblocksBaseUrl).toString(),
275
+ headers: {
276
+ Authorization: "Bearer " + token,
277
+ [CLI_VERSION_HEADER]: cliVersion,
278
+ ...injectedHeaders,
279
+ },
280
+ data: { components: componentConfigs },
281
+ };
282
+ const response = await (0, axios_1.default)(config);
283
+ return response.data;
284
+ }
259
285
  }
260
286
  catch (e) {
261
287
  if (e instanceof axios_1.AxiosError) {
@@ -292,9 +318,9 @@ async function uploadComponents({ cliVersion, applicationId, componentConfigs, f
292
318
  srcFiles,
293
319
  buildFiles,
294
320
  });
295
- const postURL = new URL(`${BASE_BUCKETEER_URL}/components/upload`, bucketeerBaseUrl).toString();
321
+ const postURL = new URL(`${BASE_BUCKETEER_URL}/v2/components/upload`, bucketeerBaseUrl).toString();
296
322
  let totalFileSizeMB = 0;
297
- const formData = new FormData();
323
+ const formData = new form_data_1.default();
298
324
  formData.append("format", formatJSON);
299
325
  uploadFiles.forEach((uploadFile) => {
300
326
  const uploadFileStats = fs.statSync(uploadFile.filename);
@@ -320,8 +346,34 @@ You can reduce your component bundle size by uploading static assets to a separa
320
346
  ...formHeaders,
321
347
  },
322
348
  };
323
- const response = await axios_1.default.post(postURL, formData, config);
324
- return response.data;
349
+ const uploadResponse = await axios_1.default.post(postURL, formData, config);
350
+ const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
351
+ const organization = userMe.organizations[0];
352
+ const signingRequired = organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap);
353
+ let agentUrls = [];
354
+ if (signingRequired) {
355
+ agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
356
+ }
357
+ const socket = await (0, socket_1.connectToISocketRPCServer)({
358
+ agentUrls,
359
+ superblocksBaseUrl,
360
+ token,
361
+ });
362
+ try {
363
+ await socket.call.v1.public.application.component.update({
364
+ applicationId,
365
+ branchName: branch !== null && branch !== void 0 ? branch : undefined,
366
+ srcFiles: srcFiles.map((file) => file.filename),
367
+ buildFiles: buildFiles.map((file) => file.filename),
368
+ registeredComponents: componentConfigs,
369
+ cliVersion,
370
+ componentBaseUrl: uploadResponse.data.componentBaseUrl,
371
+ signingRequired,
372
+ });
373
+ }
374
+ finally {
375
+ socket.close();
376
+ }
325
377
  }
326
378
  catch (e) {
327
379
  if (e instanceof axios_1.AxiosError && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.status) === 413) {
@@ -358,7 +410,7 @@ async function fetchCurrentUser(cliVersion, token, superblocksBaseUrl) {
358
410
  },
359
411
  };
360
412
  const response = await (0, axios_1.default)(config);
361
- return response.data.data.user;
413
+ return response.data.data;
362
414
  }
363
415
  catch (e) {
364
416
  let message;
@@ -378,17 +430,40 @@ async function pushApplication({ cliVersion, applicationId, token, superblocksBa
378
430
  const serverURL = new URL(`${BASE_SERVER_PUBLIC_API_URL}/applications/${applicationId}/branches/${encodeURIComponent(branch)}/push`, superblocksBaseUrl);
379
431
  let serverResponse;
380
432
  try {
381
- const config = {
382
- method: "post",
383
- url: serverURL.toString(),
384
- headers: {
385
- Authorization: "Bearer " + token,
386
- [CLI_VERSION_HEADER]: cliVersion,
387
- ...injectedHeaders,
388
- },
389
- data: applicationConfig,
390
- };
391
- serverResponse = await (0, axios_1.default)(config);
433
+ const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
434
+ const organization = userMe.organizations[0];
435
+ if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
436
+ const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
437
+ const socket = await (0, socket_1.connectToISocketRPCServer)({
438
+ agentUrls,
439
+ superblocksBaseUrl,
440
+ token,
441
+ });
442
+ const resp = await socket.call.v1.public.application.pushCommit({
443
+ applicationId,
444
+ apis: applicationConfig.apis,
445
+ application: applicationConfig.application,
446
+ branchName: branch,
447
+ commitId: applicationConfig.commitId,
448
+ commitMessage: applicationConfig.commitMessage,
449
+ page: applicationConfig.page,
450
+ });
451
+ socket.close();
452
+ return resp.data;
453
+ }
454
+ else {
455
+ const config = {
456
+ method: "post",
457
+ url: serverURL.toString(),
458
+ headers: {
459
+ Authorization: "Bearer " + token,
460
+ [CLI_VERSION_HEADER]: cliVersion,
461
+ ...injectedHeaders,
462
+ },
463
+ data: applicationConfig,
464
+ };
465
+ serverResponse = await (0, axios_1.default)(config);
466
+ }
392
467
  }
393
468
  catch (e) {
394
469
  if (axios_1.default.isAxiosError(e)) {
@@ -412,17 +487,38 @@ async function pushApi({ cliVersion, apiId, token, superblocksBaseUrl, apiConfig
412
487
  const serverURL = new URL(`${BASE_SERVER_PUBLIC_API_URL}/apis/${apiId}/branches/${encodeURIComponent(branch)}/push`, superblocksBaseUrl);
413
488
  let serverResponse;
414
489
  try {
415
- const config = {
416
- method: "post",
417
- url: serverURL.toString(),
418
- headers: {
419
- Authorization: "Bearer " + token,
420
- [CLI_VERSION_HEADER]: cliVersion,
421
- ...injectedHeaders,
422
- },
423
- data: apiConfig,
424
- };
425
- serverResponse = await (0, axios_1.default)(config);
490
+ const userMe = await fetchCurrentUser(cliVersion, token, superblocksBaseUrl);
491
+ const organization = userMe.organizations[0];
492
+ if (organization.agentType == types_1.AgentType.ONPREMISE && (0, flag_1.signingEnabled)(userMe.flagBootstrap)) {
493
+ const agentUrls = (0, utils_1.getAgentUrls)(userMe.agents, organization.agentType);
494
+ const socket = await (0, socket_1.connectToISocketRPCServer)({
495
+ agentUrls,
496
+ superblocksBaseUrl,
497
+ token,
498
+ });
499
+ const resp = await socket.call.v1.public.api.pushCommit({
500
+ apiId,
501
+ apiPb: apiConfig.apiPb,
502
+ branchName: branch,
503
+ commitId: apiConfig.commitId,
504
+ commitMessage: apiConfig.commitMessage,
505
+ });
506
+ socket.close();
507
+ return resp.data;
508
+ }
509
+ else {
510
+ const config = {
511
+ method: "post",
512
+ url: serverURL.toString(),
513
+ headers: {
514
+ Authorization: "Bearer " + token,
515
+ [CLI_VERSION_HEADER]: cliVersion,
516
+ ...injectedHeaders,
517
+ },
518
+ data: apiConfig,
519
+ };
520
+ serverResponse = await (0, axios_1.default)(config);
521
+ }
426
522
  }
427
523
  catch (e) {
428
524
  if (axios_1.default.isAxiosError(e)) {
package/dist/flag.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { FlagBootstrap } from "./types";
2
+ export declare const signingEnabled: (flags: FlagBootstrap) => boolean;
package/dist/flag.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.signingEnabled = void 0;
4
+ const signingEnabled = (flags) => {
5
+ var _a;
6
+ return (_a = flags["ui.enable-resource-signing"]) !== null && _a !== void 0 ? _a : false;
7
+ };
8
+ exports.signingEnabled = signingEnabled;
package/dist/sdk.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ComponentEvent, LocalGitRepoState, SuperblocksResourceType } from "@superblocksteam/util";
2
- import { ViewMode, PushApplicationWithCommitConfig, PushApiWithCommitConfig } from "./client";
2
+ import { PushApiWithCommitConfig, PushApplicationWithCommitConfig, ViewMode } from "./client";
3
3
  export * from "./errors";
4
4
  export declare class SuperblocksSdk {
5
5
  token: string;
@@ -27,15 +27,15 @@ export declare class SuperblocksSdk {
27
27
  validateGitSetup(resourceId: string, resourceType: SuperblocksResourceType, event: ComponentEvent, localGitRepoState: LocalGitRepoState, injectedHeaders?: Record<string, string>): Promise<{
28
28
  branchName: string | null;
29
29
  }>;
30
- registerComponents(applicationId: string, componentConfigs: Record<string, any>, branch: string | null, injectedHeaders?: Record<string, string>): Promise<any>;
31
- uploadComponents(applicationId: string, componentConfigs: Record<string, any>, files: string[], branch: string | null): Promise<any>;
32
- fetchCurrentUser(): Promise<any>;
30
+ registerComponents(applicationId: string, componentConfigs: Record<string, any>, branch: string | null, injectedHeaders: Record<string, string>): Promise<any>;
31
+ uploadComponents(applicationId: string, componentConfigs: Record<string, any>, files: string[], branch: string | null): Promise<void>;
32
+ fetchCurrentUser(): Promise<import("./types").UserMeDto>;
33
33
  pushApplication({ applicationId, applicationConfig, branch, headers, }: {
34
34
  applicationId: string;
35
35
  applicationConfig: PushApplicationWithCommitConfig;
36
36
  branch: string;
37
37
  headers?: Record<string, string>;
38
- }): Promise<import("./client").ApplicationWrapper | undefined>;
38
+ }): Promise<import("./types").RemoteCommitDto | undefined>;
39
39
  pushApi({ apiId, apiConfig, branch, headers, }: {
40
40
  apiId: string;
41
41
  apiConfig: PushApiWithCommitConfig;
@@ -0,0 +1,105 @@
1
+ import { ApiToSign, ApiToVerify, AppToSign, AppToVerify, MethodHandlers, RemoteCommitDto, Signature } from "../types";
2
+ type MethodSchema<Params, Response> = (params: Params) => Promise<Response>;
3
+ export interface ClientMethods {
4
+ v1: {
5
+ signing: {
6
+ signApplication: MethodSchema<{
7
+ branchName: string;
8
+ toSign: AppToSign;
9
+ }, {
10
+ signature: Signature;
11
+ }>;
12
+ signApis: MethodSchema<{
13
+ branchName: string;
14
+ toSign: ApiToSign[];
15
+ }, {
16
+ signatures: Signature[];
17
+ }>;
18
+ verifyApplication: MethodSchema<{
19
+ branchName: string;
20
+ toVerify: AppToVerify;
21
+ }, {
22
+ ok: boolean;
23
+ }>;
24
+ verifyApi: MethodSchema<{
25
+ branchName: string;
26
+ toVerify: ApiToVerify[];
27
+ }, {
28
+ ok: boolean;
29
+ }>;
30
+ };
31
+ };
32
+ }
33
+ type ServerMethodSchema<Params, Response> = MethodSchema<Params, ResponseDto<Response>>;
34
+ type ResponseDto<T> = {
35
+ responseMeta: ResponseMeta;
36
+ data: T;
37
+ };
38
+ export type ResponseMeta = {
39
+ status: number;
40
+ success: boolean;
41
+ error?: APIResponseError;
42
+ };
43
+ type APIResponseError = {
44
+ code: number;
45
+ message: string;
46
+ };
47
+ export interface ServerMethods {
48
+ v1: {
49
+ echo: MethodSchema<{
50
+ message: string;
51
+ }, {
52
+ message: string;
53
+ }>;
54
+ public: {
55
+ application: {
56
+ component: {
57
+ register: ServerMethodSchema<{
58
+ applicationId: string;
59
+ branchName: string;
60
+ cliVersion: string;
61
+ componentEvent: string;
62
+ components: Record<string, unknown>;
63
+ }, {
64
+ success: boolean;
65
+ }>;
66
+ update: ServerMethodSchema<{
67
+ applicationId: string;
68
+ branchName?: string;
69
+ srcFiles: string[];
70
+ buildFiles: string[];
71
+ registeredComponents: Record<string, unknown>;
72
+ cliVersion: string | undefined;
73
+ componentBaseUrl: string;
74
+ signingRequired: boolean;
75
+ }, {
76
+ success: boolean;
77
+ }>;
78
+ };
79
+ pushCommit: ServerMethodSchema<{
80
+ applicationId: string;
81
+ branchName: string;
82
+ commitId: string;
83
+ commitMessage: string;
84
+ application: Record<string, unknown>;
85
+ page: Record<string, unknown>;
86
+ apis: Record<string, unknown>[];
87
+ }, RemoteCommitDto>;
88
+ };
89
+ api: {
90
+ pushCommit: ServerMethodSchema<{
91
+ apiId: string;
92
+ branchName: string;
93
+ commitId: string;
94
+ commitMessage: string;
95
+ apiPb: Record<string, unknown>;
96
+ }, RemoteCommitDto>;
97
+ };
98
+ };
99
+ };
100
+ }
101
+ export declare function createRequestHandlers({ agentUrls, token, }: {
102
+ token: string;
103
+ agentUrls: string[];
104
+ }): MethodHandlers<ClientMethods, ServerMethods, unknown>;
105
+ export {};
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRequestHandlers = void 0;
4
+ const signing_1 = require("./signing");
5
+ function createRequestHandlers({ agentUrls, token, }) {
6
+ const requestHandlers = {
7
+ v1: {
8
+ signing: {
9
+ signApplication: [
10
+ async ({ branchName, toSign, }) => {
11
+ const signature = await (0, signing_1.signResource)({
12
+ agentUrls,
13
+ token: token,
14
+ branchName,
15
+ resource: {
16
+ literal: {
17
+ data: toSign.rootHash,
18
+ },
19
+ },
20
+ });
21
+ return { signature: signature };
22
+ },
23
+ ],
24
+ signApis: [
25
+ async ({ branchName, toSign, }) => {
26
+ const signatures = [];
27
+ for (const { apiPb } of toSign) {
28
+ const signature = await (0, signing_1.signResource)({
29
+ agentUrls,
30
+ token: token,
31
+ branchName,
32
+ resource: { api: apiPb },
33
+ });
34
+ signatures.push(signature);
35
+ }
36
+ return { signatures };
37
+ },
38
+ ],
39
+ verifyApplication: [
40
+ async ({ branchName, toVerify, }) => {
41
+ try {
42
+ await (0, signing_1.verifyResources)({
43
+ agentUrls,
44
+ token,
45
+ branchName,
46
+ resources: [
47
+ {
48
+ literal: {
49
+ data: toVerify.rootHash,
50
+ signature: toVerify.signature,
51
+ },
52
+ },
53
+ ],
54
+ });
55
+ return { ok: true };
56
+ }
57
+ catch {
58
+ return { ok: false };
59
+ }
60
+ },
61
+ ],
62
+ verifyApi: [
63
+ async ({ branchName, toVerify, }) => {
64
+ try {
65
+ await (0, signing_1.verifyResources)({
66
+ agentUrls,
67
+ token,
68
+ branchName,
69
+ resources: toVerify.map(({ apiPb }) => ({
70
+ api: apiPb,
71
+ })),
72
+ });
73
+ return { ok: true };
74
+ }
75
+ catch {
76
+ return { ok: false };
77
+ }
78
+ },
79
+ ],
80
+ },
81
+ },
82
+ };
83
+ return requestHandlers;
84
+ }
85
+ exports.createRequestHandlers = createRequestHandlers;
@@ -0,0 +1,27 @@
1
+ /// <reference types="ws" />
2
+ import WebSocket from "isomorphic-ws";
3
+ import { ServerMethods } from "./handlers";
4
+ export type StdISocketRPCClient = ISocketClient<ServerMethods>;
5
+ export declare function connectToISocketRPCServer({ superblocksBaseUrl, agentUrls, token, }: {
6
+ superblocksBaseUrl: string;
7
+ agentUrls: string[];
8
+ token: string;
9
+ }): Promise<StdISocketRPCClient>;
10
+ export declare function connectISocket<CallableMethods, ImplementedMethods, RequestContext = never>(wsUrl: string, authorization: string | undefined, requestHandlers: MethodHandlers<ImplementedMethods, CallableMethods, RequestContext>): Promise<ISocketClient<CallableMethods>>;
11
+ export declare function connectWebSocket(wsUrl: string): Promise<WebSocket>;
12
+ type MethodHandler<Params, Result, PeerMethods, RequestContext> = (params: Params, peer: ISocketClient<PeerMethods>, ctx: RequestContext) => Promise<Result>;
13
+ type MiddlewareHandler<Params, PeerMethods, RequestContext> = (params: Params, peerAuthorization: string | undefined, peer: ISocketClient<PeerMethods>, ctx: RequestContext) => Promise<void>;
14
+ type MethodHandlers<Methods, PeerMethods, RequestContext> = {
15
+ [Key in keyof Methods]: Methods[Key] extends (params: infer Params) => Promise<infer Result> ? [
16
+ ...middlewareHandlers: MiddlewareHandler<Params, PeerMethods, RequestContext>[],
17
+ handler: MethodHandler<Params, Result, PeerMethods, RequestContext>
18
+ ] : Methods[Key] extends Record<string, unknown> ? MethodHandlers<Methods[Key], PeerMethods, RequestContext> : never;
19
+ };
20
+ type ISocketClientMethodCall<Methods> = {
21
+ [Key in keyof Methods]: Methods[Key] extends (params: infer P) => Promise<infer R> ? (params: P) => Promise<R> : Methods[Key] extends Record<string, unknown> ? ISocketClientMethodCall<Methods[Key]> : never;
22
+ };
23
+ type ISocketClient<Methods> = {
24
+ close: () => void;
25
+ call: ISocketClientMethodCall<Methods>;
26
+ };
27
+ export {};
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectWebSocket = exports.connectISocket = exports.connectToISocketRPCServer = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const isomorphic_ws_1 = tslib_1.__importDefault(require("isomorphic-ws"));
6
+ const handlers_1 = require("./handlers");
7
+ const socket_1 = require("./socket");
8
+ async function connectToISocketRPCServer({ superblocksBaseUrl, agentUrls, token, }) {
9
+ const requestHandlers = (0, handlers_1.createRequestHandlers)({
10
+ agentUrls,
11
+ token,
12
+ });
13
+ const authorization = `Bearer ${token}`;
14
+ const wsUrl = new URL("api/v1/rpc-ws", superblocksBaseUrl);
15
+ if (wsUrl.protocol === "http:") {
16
+ wsUrl.protocol = "ws:";
17
+ }
18
+ else if (wsUrl.protocol === "https:") {
19
+ wsUrl.protocol = "wss:";
20
+ }
21
+ if (wsUrl.host === "localhost:3000") {
22
+ wsUrl.host = "127.0.0.1:8080";
23
+ }
24
+ else if (wsUrl.hostname === "localhost") {
25
+ wsUrl.hostname = "127.0.0.1";
26
+ }
27
+ return await connectISocket(wsUrl.href, authorization, requestHandlers);
28
+ }
29
+ exports.connectToISocketRPCServer = connectToISocketRPCServer;
30
+ // a subclass of ISocket that sends an auth token on the first request
31
+ // this is useful for client-side sockets that need to authenticate
32
+ // TODO(george): if we start using this for long-lived connections, we should add a way to refresh the token
33
+ class ISocketWithClientAuth extends socket_1.ISocket {
34
+ constructor(ws, authorization, requestHandlers) {
35
+ super(ws, requestHandlers);
36
+ this.hasSentAuth = false;
37
+ this.authorization = authorization;
38
+ }
39
+ // override `request` from the base class to send `authorization` when appropriate
40
+ async request(method, params) {
41
+ // only send `authorization` on the first request
42
+ const authorization = this.hasSentAuth ? undefined : this.authorization;
43
+ const result = await super.request(method, params, authorization);
44
+ this.hasSentAuth = true;
45
+ return result;
46
+ }
47
+ }
48
+ async function connectISocket(wsUrl, authorization, requestHandlers) {
49
+ const ws = await connectWebSocket(wsUrl);
50
+ const isocket = new ISocketWithClientAuth(ws, authorization, requestHandlers);
51
+ return (0, socket_1.createISocketClient)(isocket);
52
+ }
53
+ exports.connectISocket = connectISocket;
54
+ function connectWebSocket(wsUrl) {
55
+ return new Promise((resolve, reject) => {
56
+ const ws = new isomorphic_ws_1.default(wsUrl);
57
+ ws.addEventListener("open", () => {
58
+ // Resolve the promise with the WebSocket instance when the connection is open
59
+ resolve(ws);
60
+ });
61
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
62
+ // @ts-ignore
63
+ ws.addEventListener("error", (error) => {
64
+ // Reject the promise if there's an error
65
+ reject(error);
66
+ });
67
+ });
68
+ }
69
+ exports.connectWebSocket = connectWebSocket;
@@ -0,0 +1,13 @@
1
+ import { ApiResource, GenericResource, Signature } from "../types";
2
+ export declare function signResource({ token, branchName, resource, agentUrls, }: {
3
+ token: string;
4
+ branchName: string;
5
+ resource: ApiResource | GenericResource;
6
+ agentUrls: string[];
7
+ }): Promise<Signature>;
8
+ export declare function verifyResources({ agentUrls, token, branchName, resources, }: {
9
+ resources: Array<GenericResource | ApiResource>;
10
+ token: string;
11
+ branchName: string;
12
+ agentUrls: string[];
13
+ }): Promise<void>;