libshv-js 3.23.3 → 3.25.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/dist/index.d.ts CHANGED
@@ -5,6 +5,6 @@ export * from './cpon';
5
5
  export * from './json';
6
6
  export * from './rpcmessage';
7
7
  export * from './rpcvalue';
8
- export * from './vue-shv';
9
8
  export * from './ws-client';
10
9
  export * from './zod';
10
+ export * from './zod-ws-client';
package/dist/index.js CHANGED
@@ -21,6 +21,6 @@ __exportStar(require("./cpon"), exports);
21
21
  __exportStar(require("./json"), exports);
22
22
  __exportStar(require("./rpcmessage"), exports);
23
23
  __exportStar(require("./rpcvalue"), exports);
24
- __exportStar(require("./vue-shv"), exports);
25
24
  __exportStar(require("./ws-client"), exports);
26
25
  __exportStar(require("./zod"), exports);
26
+ __exportStar(require("./zod-ws-client"), exports);
@@ -1,7 +1,6 @@
1
1
  import { type RpcMessage, type ErrorMap } from './rpcmessage';
2
2
  import { type RpcValue, type Null, type Int, type IMap, type ShvMap } from './rpcvalue';
3
3
  import { StringGetter } from './utils';
4
- import * as z from './zod';
5
4
  type SubscriptionCallback = (path: string, method: string, param?: RpcValue) => void;
6
5
  type ResultOrError<T = RpcValue> = T | Error;
7
6
  type Login = {
@@ -15,6 +14,7 @@ type Login = {
15
14
  type WsClientOptionsCommon = {
16
15
  logDebug: (...args: string[]) => void;
17
16
  wsUri: string;
17
+ parseMessage?: (rpcVal: RpcValue) => RpcMessage;
18
18
  };
19
19
  export declare class RequestHandler {
20
20
  options: {
@@ -28,8 +28,8 @@ export declare class RequestHandler {
28
28
  onProgressQuery?: () => number | Promise<number>;
29
29
  });
30
30
  }
31
- export declare const LsParamZod: z.ZodUnion<[z.ZodUndefined, z.ZodString]>;
32
- export declare const DirParamZod: z.ZodUnion<[z.ZodUnion<[z.ZodUndefined, z.ZodBoolean]>, z.ZodString]>;
31
+ export declare const validateLsParam: (param: RpcValue) => param is string | undefined;
32
+ export declare const validateDirParam: (param: RpcValue) => param is string | boolean | undefined;
33
33
  export type DirEntry = IMap<{
34
34
  [DIR_NAME]: string;
35
35
  [DIR_FLAGS]: number;
@@ -41,10 +41,10 @@ export type DirEntry = IMap<{
41
41
  }>;
42
42
  export type DirResult = DirEntry[];
43
43
  export type MethodHandler = {
44
- paramParser: z.ZodType<RpcValue>;
44
+ paramValidator?: (param: RpcValue) => boolean;
45
45
  handler: (shvPath: string, method: string, params: RpcValue, delay: (progress: number) => void) => Promise<RpcValue> | RpcValue | RequestHandler;
46
46
  };
47
- export type WsClientOptionsLogin = WsClientOptionsCommon & {
47
+ export type WsClientOptionsLogin<MethodHandlerType = MethodHandler> = WsClientOptionsCommon & {
48
48
  mountPoint?: string;
49
49
  login: Login;
50
50
  timeout?: number;
@@ -56,14 +56,14 @@ export type WsClientOptionsLogin = WsClientOptionsCommon & {
56
56
  ls: (shvPath: string) => string[] | Promise<string[]>;
57
57
  dirEntries: Array<{
58
58
  entry: DirEntry;
59
- } & MethodHandler>;
59
+ } & MethodHandlerType>;
60
60
  } | undefined;
61
61
  };
62
- type WsClientOptionsWorkflows = WsClientOptionsCommon & {
62
+ export type WsClientOptionsWorkflows = WsClientOptionsCommon & {
63
63
  onWorkflows: (workflows: RpcValue) => void;
64
64
  onWorkflowsFailed: () => void;
65
65
  };
66
- type WsClientOptions = WsClientOptionsLogin | WsClientOptionsWorkflows;
66
+ export type WsClientOptions<MethodHandlerType> = WsClientOptionsLogin<MethodHandlerType> | WsClientOptionsWorkflows;
67
67
  type LsResult = string[];
68
68
  export declare enum DirFlags {
69
69
  Reserved = 1,
@@ -215,7 +215,7 @@ declare class WsClient {
215
215
  private readonly websocket;
216
216
  private readonly options;
217
217
  private readonly timeout;
218
- constructor(options: WsClientOptions);
218
+ constructor(options: WsClientOptions<MethodHandler>);
219
219
  callRpcMethod(shvPath: '.broker/currentClient', method: 'accessGrantForMethodCall', params: [string, string], delayCallback?: (progress: number) => void): RpcRequestPromise<ResultOrError<string>>;
220
220
  callRpcMethod(shvPath: string | undefined, method: 'dir', params?: RpcValue, delayCallback?: (progress: number) => void): RpcRequestPromise<ResultOrError<DirResult>>;
221
221
  callRpcMethod(shvPath: string | undefined, method: 'ls', params?: RpcValue, delayCallback?: (progress: number) => void): RpcRequestPromise<ResultOrError<LsResult>>;
@@ -226,7 +226,7 @@ declare class WsClient {
226
226
  sendPing(): void;
227
227
  accessGrantForMethodCall(path: string, method: string): RpcRequestPromise<ResultOrError<string>>;
228
228
  close(): void;
229
- private logDebug;
229
+ protected logDebug(...args: string[]): void;
230
230
  private workflowsProcedure;
231
231
  private loginProcedure;
232
232
  }
package/dist/ws-client.js CHANGED
@@ -1,48 +1,19 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.WsClient = exports.NotImplemented = exports.UserIDRequired = exports.LoginRequired = exports.Unknown = exports.MethodCallException = exports.MethodCallCancelled = exports.MethodCallTimeout = exports.ParseError = exports.InternalError = exports.InvalidParams = exports.MethodNotFound = exports.InvalidRequest = exports.DIR_EXTRA = exports.DIR_SIGNALS = exports.DIR_ACCESS = exports.DIR_RESULT = exports.DIR_PARAM = exports.DIR_FLAGS = exports.DIR_NAME = exports.DirFlags = exports.DirParamZod = exports.LsParamZod = exports.RequestHandler = void 0;
3
+ exports.WsClient = exports.NotImplemented = exports.UserIDRequired = exports.LoginRequired = exports.Unknown = exports.MethodCallException = exports.MethodCallCancelled = exports.MethodCallTimeout = exports.ParseError = exports.InternalError = exports.InvalidParams = exports.MethodNotFound = exports.InvalidRequest = exports.DIR_EXTRA = exports.DIR_SIGNALS = exports.DIR_ACCESS = exports.DIR_RESULT = exports.DIR_PARAM = exports.DIR_FLAGS = exports.DIR_NAME = exports.DirFlags = exports.validateDirParam = exports.validateLsParam = exports.RequestHandler = void 0;
37
4
  const access_1 = require("./access");
38
5
  const chainpack_1 = require("./chainpack");
39
6
  const cpon_1 = require("./cpon");
40
7
  const rpcmessage_1 = require("./rpcmessage");
41
8
  const rpcvalue_1 = require("./rpcvalue");
42
9
  const utils_1 = require("./utils");
43
- const z = __importStar(require("./zod"));
44
10
  const DEFAULT_TIMEOUT = 5000;
45
11
  const DEFAULT_PING_INTERVAL = 30 * 1000;
12
+ const defaultParseMessage = (rpcVal) => {
13
+ // Assume rpcVal is a valid RpcMessage - no runtime validation
14
+ const rpcMsg = rpcVal;
15
+ return rpcMsg;
16
+ };
46
17
  const dataToRpcValue = (buff) => {
47
18
  const rd = new chainpack_1.ChainPackReader(buff);
48
19
  rd.readUIntData();
@@ -66,8 +37,10 @@ class RequestHandler {
66
37
  }
67
38
  }
68
39
  exports.RequestHandler = RequestHandler;
69
- exports.LsParamZod = z.undefined().or(z.string());
70
- exports.DirParamZod = z.undefined().or(z.boolean()).or(z.string());
40
+ const validateLsParam = (param) => param === undefined || typeof param === 'string';
41
+ exports.validateLsParam = validateLsParam;
42
+ const validateDirParam = (param) => param === undefined || typeof param === 'string' || typeof param === 'boolean';
43
+ exports.validateDirParam = validateDirParam;
71
44
  var DirFlags;
72
45
  (function (DirFlags) {
73
46
  DirFlags[DirFlags["Reserved"] = 1] = "Reserved";
@@ -251,7 +224,7 @@ class WsClient {
251
224
  case 'dir':
252
225
  return {
253
226
  entry: dirEntry,
254
- paramParser: exports.DirParamZod,
227
+ paramValidator: exports.validateDirParam,
255
228
  handler(_shvPath, _method, param) {
256
229
  const methodsResult = [dirEntry, lsEntry, ...methods.dirEntries.map(method => method.entry)];
257
230
  switch (true) {
@@ -267,7 +240,7 @@ class WsClient {
267
240
  case 'ls':
268
241
  return {
269
242
  entry: lsEntry,
270
- paramParser: exports.LsParamZod,
243
+ paramValidator: exports.validateLsParam,
271
244
  handler(shvPath) {
272
245
  return methods.ls(shvPath);
273
246
  },
@@ -285,11 +258,10 @@ class WsClient {
285
258
  return;
286
259
  }
287
260
  const requestParam = request.value[rpcmessage_1.RPC_MESSAGE_PARAMS];
288
- const parsedParam = methodDefinition.paramParser.safeParse(requestParam);
289
- if (!parsedParam.success) {
290
- throw new exports.InvalidParams(`Unexpected param for method ${methodName} on path '${shvPath}': ${(0, cpon_1.toCpon)(requestParam)}`);
261
+ if (methodDefinition.paramValidator !== undefined && !methodDefinition.paramValidator(requestParam)) {
262
+ throw new exports.InvalidParams(`Unexpected param '${shvPath}:${methodName}': ${(0, cpon_1.toCpon)(requestParam)}`);
291
263
  }
292
- let result = methodDefinition.handler(shvPath, methodName, parsedParam.data, sendDelay);
264
+ let result = methodDefinition.handler(shvPath, methodName, requestParam, sendDelay);
293
265
  if (result instanceof RequestHandler) {
294
266
  this.requestHandlers.set(requestId, result);
295
267
  result = result.options.result;
@@ -380,7 +352,8 @@ class WsClient {
380
352
  };
381
353
  this.websocket.addEventListener('message', async (evt) => {
382
354
  const rpcVal = dataToRpcValue(evt.data);
383
- const rpcMsg = rpcmessage_1.RpcMessageZod.parse(rpcVal);
355
+ const parseMessage = this.options.parseMessage ?? defaultParseMessage;
356
+ const rpcMsg = parseMessage(rpcVal);
384
357
  this.logDebug(`message received: ${(0, cpon_1.toCpon)(rpcMsg)}`);
385
358
  if ((0, rpcmessage_1.isSignal)(rpcMsg)) {
386
359
  handleSignal(rpcMsg);
@@ -0,0 +1,11 @@
1
+ import { WsClient, WsClientOptions } from './ws-client';
2
+ import { type RpcValue } from './rpcvalue';
3
+ import * as z from './zod';
4
+ export declare const LsParamZod: z.ZodUnion<[z.ZodUndefined, z.ZodString]>;
5
+ export declare const DirParamZod: z.ZodUnion<[z.ZodUnion<[z.ZodUndefined, z.ZodBoolean]>, z.ZodString]>;
6
+ export type ZodMethodHandler = {
7
+ paramParser: z.ZodType<RpcValue>;
8
+ handler: (shvPath: string, method: string, params: RpcValue, delay: (progress: number) => void) => Promise<RpcValue> | RpcValue | import('./ws-client').RequestHandler;
9
+ };
10
+ declare function createZodWsClient(options: WsClientOptions<ZodMethodHandler>): WsClient;
11
+ export { createZodWsClient };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DirParamZod = exports.LsParamZod = void 0;
37
+ exports.createZodWsClient = createZodWsClient;
38
+ const ws_client_1 = require("./ws-client");
39
+ const rpcmessage_1 = require("./rpcmessage");
40
+ const z = __importStar(require("./zod"));
41
+ exports.LsParamZod = z.undefined().or(z.string());
42
+ exports.DirParamZod = z.undefined().or(z.boolean()).or(z.string());
43
+ function createZodWsClient(options) {
44
+ const parseMessage = (rpcVal) => {
45
+ try {
46
+ return rpcmessage_1.RpcMessageZod.parse(rpcVal);
47
+ }
48
+ catch (error) {
49
+ console.error('RPC Message validation failed:', error);
50
+ throw error;
51
+ }
52
+ };
53
+ const convertedOptions = 'login' in options ? {
54
+ ...options,
55
+ parseMessage,
56
+ onRequest(shvPath) {
57
+ const zodHandlers = options.onRequest(shvPath);
58
+ if (zodHandlers === undefined) {
59
+ return;
60
+ }
61
+ return {
62
+ ls: zodHandlers.ls,
63
+ dirEntries: zodHandlers.dirEntries.map(zodHandler => ({
64
+ entry: zodHandler.entry,
65
+ paramValidator(param) {
66
+ const result = zodHandler.paramParser.safeParse(param);
67
+ if (!result.success) {
68
+ console.error(`Parameter validation failed for '${shvPath}:${zodHandler.entry[ws_client_1.DIR_NAME]}':`, result.error.message);
69
+ return false;
70
+ }
71
+ return true;
72
+ },
73
+ handler: zodHandler.handler,
74
+ })),
75
+ };
76
+ },
77
+ } : {
78
+ ...options,
79
+ parseMessage,
80
+ };
81
+ return new ws_client_1.WsClient(convertedOptions);
82
+ }
package/dist/zod.d.ts CHANGED
@@ -28,3 +28,4 @@ export declare const list: () => z.ZodArray<z.ZodLazy<z.ZodType<RpcValue>>>;
28
28
  export declare const rpcvalue: () => ZodType<RpcValue>;
29
29
  export declare const withMeta: <MetaSchema extends MetaMap, ValueSchema extends RpcValueType>(metaParser: ZodType<MetaSchema>, valueParser: ZodType<ValueSchema>) => z.ZodCustom<RpcValueWithMetaData<MetaSchema, ValueSchema>, RpcValueWithMetaData<MetaSchema, ValueSchema>>;
30
30
  export * from 'zod/v4';
31
+ export { z } from 'zod/v4';
package/dist/zod.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.withMeta = exports.rpcvalue = exports.list = exports.blob = exports.decimal = exports.double = exports.uint = exports.recmap = exports.metamap = exports.imap = exports.map = void 0;
17
+ exports.z = exports.withMeta = exports.rpcvalue = exports.list = exports.blob = exports.decimal = exports.double = exports.uint = exports.recmap = exports.metamap = exports.imap = exports.map = void 0;
18
18
  /* eslint-disable @typescript-eslint/no-explicit-any */
19
19
  const v4_1 = require("zod/v4");
20
20
  const rpcvalue_1 = require("./rpcvalue");
@@ -110,3 +110,5 @@ const withMeta = (metaParser, valueParser) => v4_1.z.custom().check(ctx => {
110
110
  });
111
111
  exports.withMeta = withMeta;
112
112
  __exportStar(require("zod/v4"), exports);
113
+ var v4_2 = require("zod/v4");
114
+ Object.defineProperty(exports, "z", { enumerable: true, get: function () { return v4_2.z; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "libshv-js",
3
- "version": "3.23.3",
3
+ "version": "3.25.0",
4
4
  "description": "Typescript implementation of libshv",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -34,14 +34,11 @@
34
34
  "./rpcmessage": "./dist/rpcmessage.js",
35
35
  "./rpcvalue": "./dist/rpcvalue.js",
36
36
  "./utils": "./dist/utils.js",
37
- "./vue-shv": "./dist/vue-shv.js",
38
37
  "./ws-client": "./dist/ws-client.js",
39
- "./zod": "./dist/zod.js"
38
+ "./zod": "./dist/zod.js",
39
+ "./zod-ws-client": "./dist/zod-ws-client.js"
40
40
  },
41
41
  "dependencies": {
42
- "@vueuse/core": "^13.5.0",
43
- "js-pkce": "^2.0.0",
44
- "vue": "^3.5.18",
45
42
  "zod": "^4.0.11"
46
43
  },
47
44
  "devDependencies": {
package/dist/vue-shv.d.ts DELETED
@@ -1,93 +0,0 @@
1
- import { ComputedRef, Ref } from 'vue';
2
- import { WsClient, WsClientOptionsLogin } from './ws-client';
3
- import PKCE from 'js-pkce';
4
- import * as z from './zod';
5
- import { type shvMapType } from './rpcvalue';
6
- import { RpcValue } from './rpcvalue';
7
- import { StringGetter } from './utils';
8
- type GlobalResourceOptions<ResourceType> = {
9
- shvPath: StringGetter;
10
- method: string;
11
- validator: z.ZodType<ResourceType>;
12
- signalName: string;
13
- signalHandler: (param: RpcValue, resource: Ref<ResourceType | undefined>, reinit: () => void) => void;
14
- };
15
- type VueShvOptions = {
16
- wsUri: StringGetter;
17
- onRequest: WsClientOptionsLogin['onRequest'];
18
- azureCodeRedirect?: string;
19
- mountPoint?: string;
20
- };
21
- type ShvLocalStorage = {
22
- azureAccessToken?: string;
23
- azureRedirectTo?: string;
24
- };
25
- type ShvSessionStorage = {
26
- shvLoginUser?: string;
27
- shvLoginPassword?: string;
28
- azureWorkflow?: z.infer<typeof OAuth2AzureWorkflowZod>;
29
- };
30
- declare const OAuth2AzureWorkflowZod: z.ZodCustom<{
31
- type: "oauth2-azure";
32
- authorizeUrl: string;
33
- tokenUrl: string;
34
- clientId: string;
35
- scopes: string | string[];
36
- } & {
37
- [shvMapType]: "map";
38
- }, {
39
- type: "oauth2-azure";
40
- authorizeUrl: string;
41
- tokenUrl: string;
42
- clientId: string;
43
- scopes: string | string[];
44
- } & {
45
- [shvMapType]: "map";
46
- }>;
47
- export declare enum LoginFailureReason {
48
- NoCredentials = 0,
49
- AzureTimedOut = 1,
50
- AzureUnsupported = 2,
51
- CouldntLogin = 3,
52
- LoggedOut = 4
53
- }
54
- type LoginFailure = {
55
- reason: LoginFailureReason;
56
- message?: string;
57
- };
58
- declare const makePkce: (oauthOptions: {
59
- azureCodeRedirect: string;
60
- clientId: string;
61
- authorizeUrl: string;
62
- tokenUrl: string;
63
- scopes: string | string[];
64
- }) => PKCE;
65
- export { makePkce as azure };
66
- export declare function useShv(options: VueShvOptions): {
67
- azureAuth: (redirectTo: string) => Promise<void>;
68
- azureHandlerError: Ref<string, string>;
69
- connected: Ref<"connected" | "connecting" | "disconnected", "connected" | "connecting" | "disconnected">;
70
- displayEmail: Ref<string, string>;
71
- displayFullName: Ref<string, string>;
72
- displayName: Ref<string, string>;
73
- displayPhoto: Ref<string | undefined, string | undefined>;
74
- displayShortName: Ref<string, string>;
75
- getConnection: () => Promise<WsClient>;
76
- handleAzureCode: () => Promise<string | void>;
77
- logContents: Ref<string, string>;
78
- loginFailure: Ref<LoginFailure | undefined, LoginFailure | undefined>;
79
- makeGlobalResource: {
80
- <ResourceType>(options: GlobalResourceOptions<ResourceType>): () => Ref<ResourceType | undefined>;
81
- <ResourceType>(options: GlobalResourceOptions<ResourceType> & {
82
- default: ResourceType;
83
- }): () => ComputedRef<ResourceType>;
84
- };
85
- makeRpcCall: <ResultType>(shvPath: StringGetter, method: string, validator: z.ZodType<ResultType>) => () => Promise<Error | ResultType>;
86
- makeRpcCallParam: <ResultType, ParamType extends RpcValue>(shvPath: StringGetter, method: string, _paramType: z.ZodType<ParamType>, validator: z.ZodType<ResultType>) => (param: ParamType) => Promise<Error | ResultType>;
87
- rpcCall: (shvPath: StringGetter, method: string, params?: RpcValue) => Promise<Error | RpcValue>;
88
- setShvCredentials: (userName: string, password: string) => void;
89
- shvLocalStorage: import("@vueuse/shared").RemovableRef<ShvLocalStorage>;
90
- shvLogout: () => void;
91
- shvSessionStorage: import("@vueuse/shared").RemovableRef<ShvSessionStorage>;
92
- };
93
- export declare const fullReloadHandler: (_param: RpcValue, _resource: unknown, reinit: () => void) => void;
package/dist/vue-shv.js DELETED
@@ -1,441 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.fullReloadHandler = exports.azure = exports.LoginFailureReason = void 0;
40
- exports.useShv = useShv;
41
- const vue_1 = require("vue");
42
- const ws_client_1 = require("./ws-client");
43
- const core_1 = require("@vueuse/core");
44
- const js_pkce_1 = __importDefault(require("js-pkce"));
45
- const z = __importStar(require("./zod"));
46
- const utils_1 = require("./utils");
47
- const OAuth2AzureWorkflowZod = z.map({
48
- type: z.literal('oauth2-azure'),
49
- authorizeUrl: z.string(),
50
- tokenUrl: z.string(),
51
- clientId: z.string(),
52
- scopes: z.string().or(z.array(z.string())),
53
- });
54
- var LoginFailureReason;
55
- (function (LoginFailureReason) {
56
- LoginFailureReason[LoginFailureReason["NoCredentials"] = 0] = "NoCredentials";
57
- LoginFailureReason[LoginFailureReason["AzureTimedOut"] = 1] = "AzureTimedOut";
58
- LoginFailureReason[LoginFailureReason["AzureUnsupported"] = 2] = "AzureUnsupported";
59
- LoginFailureReason[LoginFailureReason["CouldntLogin"] = 3] = "CouldntLogin";
60
- LoginFailureReason[LoginFailureReason["LoggedOut"] = 4] = "LoggedOut";
61
- })(LoginFailureReason || (exports.LoginFailureReason = LoginFailureReason = {}));
62
- const makePkce = (oauthOptions) => {
63
- const pkce = new js_pkce_1.default({
64
- client_id: oauthOptions.clientId,
65
- redirect_uri: (() => {
66
- const url = new URL(globalThis.location.href);
67
- url.pathname = oauthOptions.azureCodeRedirect;
68
- url.search = '';
69
- return url.toString();
70
- })(),
71
- authorization_endpoint: oauthOptions.authorizeUrl,
72
- token_endpoint: oauthOptions.tokenUrl,
73
- requested_scopes: Array.isArray(oauthOptions.scopes) ? oauthOptions.scopes.join(' ') : oauthOptions.scopes,
74
- });
75
- return pkce;
76
- };
77
- exports.azure = makePkce;
78
- function useShv(options) {
79
- const shvLocalStorage = (0, core_1.useLocalStorage)('vue-shv', {});
80
- const shvSessionStorage = (0, core_1.useSessionStorage)('vue-shv', {});
81
- const displayName = (0, vue_1.ref)('Loading...');
82
- const displayShortName = (0, vue_1.ref)('');
83
- const displayFullName = (0, vue_1.ref)('');
84
- const displayEmail = (0, vue_1.ref)('');
85
- const displayPhoto = (0, vue_1.ref)();
86
- const state = {
87
- ws: undefined,
88
- reconnectService: undefined,
89
- };
90
- const waitingForSocket = [];
91
- const resetAzureToken = () => {
92
- shvLocalStorage.value.azureAccessToken = undefined;
93
- };
94
- const azureAvailable = async () => {
95
- const accessToken = shvLocalStorage.value.azureAccessToken;
96
- if (accessToken === undefined) {
97
- return LoginFailureReason.NoCredentials;
98
- }
99
- const resp = await fetch('https://graph.microsoft.com/v1.0/me', {
100
- headers: {
101
- Authorization: `Bearer ${accessToken}`,
102
- },
103
- });
104
- const json = await resp.json();
105
- if (typeof json === 'object' && json !== null) {
106
- if ('displayName' in json && typeof json.displayName === 'string') {
107
- displayName.value = json.displayName;
108
- }
109
- if ('givenName' in json && typeof json.givenName === 'string'
110
- && 'surname' in json && typeof json.surname === 'string') {
111
- const firstName = json.givenName;
112
- const lastname = json.surname;
113
- displayShortName.value = firstName.charAt(0) + lastname.charAt(0);
114
- displayFullName.value = firstName + ' ' + lastname;
115
- }
116
- if ('mail' in json && typeof json.mail === 'string') {
117
- displayEmail.value = json.mail;
118
- }
119
- }
120
- const photo = await fetch('https://graph.microsoft.com/v1.0/me/photos/48x48/$value', {
121
- headers: {
122
- Authorization: `Bearer ${accessToken}`,
123
- },
124
- });
125
- if (photo.ok) {
126
- displayPhoto.value = URL.createObjectURL(await photo.blob());
127
- }
128
- if (!resp.ok) {
129
- resetAzureToken();
130
- }
131
- return resp.ok ? 'azureAvailable' : LoginFailureReason.AzureTimedOut;
132
- };
133
- const debug = (...args) => {
134
- logContents.value = logContents.value + args.join(' ') + '\n';
135
- console.debug(...args);
136
- };
137
- const azureAuth = async (redirectTo) => {
138
- if (options.azureCodeRedirect === undefined) {
139
- throw new Error('Azure redirect URL not set');
140
- }
141
- const { azureCodeRedirect } = options;
142
- shvLocalStorage.value.azureRedirectTo = redirectTo;
143
- const noBrokerSupport = () => {
144
- loginFailure.value = {
145
- reason: LoginFailureReason.AzureUnsupported,
146
- message: 'Broker does not support Azure',
147
- };
148
- };
149
- state.ws = new ws_client_1.WsClient({
150
- logDebug: debug,
151
- wsUri: await (0, utils_1.resolveString)(options.wsUri),
152
- onWorkflows(workflows) {
153
- if (!Array.isArray(workflows)) {
154
- noBrokerSupport();
155
- return;
156
- }
157
- for (const workflow of workflows) {
158
- const parsedWorkflow = OAuth2AzureWorkflowZod.safeParse(workflow);
159
- if (!parsedWorkflow.success) {
160
- continue;
161
- }
162
- shvSessionStorage.value.azureWorkflow = parsedWorkflow.data;
163
- globalThis.location.replace(makePkce({ ...parsedWorkflow.data, azureCodeRedirect }).authorizeUrl());
164
- }
165
- noBrokerSupport();
166
- },
167
- onWorkflowsFailed() {
168
- noBrokerSupport();
169
- },
170
- });
171
- };
172
- const setShvCredentials = (userName, password) => {
173
- shvLogout();
174
- shvSessionStorage.value.shvLoginUser = userName;
175
- shvSessionStorage.value.shvLoginPassword = password;
176
- };
177
- const rpcCall = async (shvPath, method, params) => {
178
- const shv = await getConnection();
179
- return shv.callRpcMethod(await (0, utils_1.resolveString)(shvPath), method, params);
180
- };
181
- const makeRpcCall = (shvPath, method, validator) => async () => {
182
- const resultOrError = await rpcCall(await (0, utils_1.resolveString)(shvPath), method);
183
- if (resultOrError instanceof Error) {
184
- return resultOrError;
185
- }
186
- const parsed = validator.safeParse(resultOrError);
187
- if (!parsed.success) {
188
- return new Error(parsed.error.message);
189
- }
190
- return parsed.data;
191
- };
192
- const makeRpcCallParam = (shvPath, method, _paramType, validator) => async (param) => {
193
- const resultOrError = await rpcCall(await (0, utils_1.resolveString)(shvPath), method, param);
194
- if (resultOrError instanceof Error) {
195
- return resultOrError;
196
- }
197
- const parsed = validator.safeParse(resultOrError);
198
- if (!parsed.success) {
199
- return new Error(parsed.error.message);
200
- }
201
- return parsed.data;
202
- };
203
- const connected = (0, vue_1.ref)('disconnected');
204
- const logContents = (0, vue_1.ref)('');
205
- const shvLogout = () => {
206
- resetAzureToken();
207
- shvSessionStorage.value.shvLoginUser = undefined;
208
- shvSessionStorage.value.shvLoginPassword = undefined;
209
- for (const waiter of waitingForSocket) {
210
- waiter.reject();
211
- }
212
- connected.value = 'disconnected';
213
- waitingForSocket.length = 0;
214
- state.ws?.close();
215
- displayName.value = 'Logged out';
216
- displayPhoto.value = undefined;
217
- state.ws = undefined;
218
- };
219
- const loginFailure = (0, vue_1.ref)();
220
- const getConnection = async () => {
221
- if (connected.value === 'connected') {
222
- return state.ws;
223
- }
224
- return new Promise((resolve, reject) => {
225
- waitingForSocket.push({ resolve, reject });
226
- if (connected.value === 'connecting') {
227
- // We should try to connect only once at the same time.
228
- return;
229
- }
230
- connected.value = 'connecting';
231
- const doConnect = async (user, password, loginType) => {
232
- const wsUri = await (0, utils_1.resolveString)(options.wsUri);
233
- console.log('Connecting to', wsUri);
234
- const makeLoginOptions = () => {
235
- switch (loginType) {
236
- case 'PLAIN':
237
- return {
238
- type: loginType,
239
- user,
240
- password,
241
- };
242
- case 'TOKEN':
243
- return {
244
- type: loginType,
245
- token: `oauth2-azure:${password}`,
246
- };
247
- }
248
- };
249
- state.ws = new ws_client_1.WsClient({
250
- login: makeLoginOptions(),
251
- wsUri,
252
- timeout: 120_000,
253
- mountPoint: options.mountPoint,
254
- logDebug: debug,
255
- onConnected() {
256
- for (const waiter of waitingForSocket) {
257
- waiter.resolve(state.ws);
258
- }
259
- waitingForSocket.length = 0;
260
- console.log('Connected to', wsUri);
261
- connected.value = 'connected';
262
- },
263
- onConnectionFailure(error) {
264
- console.error(`Failed to connect to: ${wsUri}`, error);
265
- shvLogout();
266
- loginFailure.value = {
267
- reason: LoginFailureReason.CouldntLogin,
268
- message: error.message,
269
- };
270
- },
271
- onDisconnected() {
272
- connected.value = 'disconnected';
273
- const RECONNECT_INTERVAL = 3000;
274
- if (shvLocalStorage.value.azureAccessToken !== undefined) {
275
- console.log('Disconnected from', wsUri, 'reconnecting in', RECONNECT_INTERVAL, 'ms');
276
- state.reconnectService = globalThis.setTimeout(async () => {
277
- await getConnection();
278
- }, RECONNECT_INTERVAL);
279
- }
280
- },
281
- onRequest: options.onRequest,
282
- });
283
- };
284
- const shvUser = shvSessionStorage.value.shvLoginUser;
285
- const shvPassword = shvSessionStorage.value.shvLoginPassword;
286
- if (shvUser !== undefined && shvPassword !== undefined) {
287
- displayName.value = shvUser;
288
- displayShortName.value = shvUser[0];
289
- displayFullName.value = shvUser;
290
- doConnect(shvUser, shvPassword, 'PLAIN')
291
- .catch((error) => {
292
- console.error('Unexpected failure in doConnect:', error);
293
- });
294
- return;
295
- }
296
- azureAvailable().then(isAzureAvailable => {
297
- switch (isAzureAvailable) {
298
- case LoginFailureReason.NoCredentials:
299
- case LoginFailureReason.AzureTimedOut:
300
- shvLogout();
301
- loginFailure.value = {
302
- reason: isAzureAvailable,
303
- };
304
- return;
305
- case 'azureAvailable':
306
- break;
307
- }
308
- const accessToken = shvLocalStorage.value.azureAccessToken;
309
- if (accessToken !== undefined) {
310
- doConnect('', accessToken, 'TOKEN')
311
- .catch((error) => {
312
- console.error('Unexpected failure in doConnect:', error);
313
- });
314
- }
315
- }).catch((error) => {
316
- console.error('Failed to fetch verify azure info, redirecting to the login page in 3 seconds', error);
317
- setTimeout(() => {
318
- loginFailure.value = {
319
- reason: LoginFailureReason.CouldntLogin,
320
- message: 'Failed to fetch verify azure info',
321
- };
322
- }, 3000);
323
- });
324
- });
325
- };
326
- function makeGlobalResource(options) {
327
- const resource = (0, vue_1.ref)();
328
- const resourceCall = makeRpcCall(options.shvPath, options.method, options.validator);
329
- const refreshValue = async () => {
330
- const newResource = await resourceCall();
331
- if (newResource instanceof Error) {
332
- return;
333
- }
334
- resource.value = newResource;
335
- };
336
- const initialize = async () => {
337
- const shvPath = await (0, utils_1.resolveString)(options.shvPath);
338
- const resIdentifier = `${shvPath}:${options.method}`;
339
- try {
340
- await refreshValue();
341
- const connection = await getConnection();
342
- await connection.subscribe(`Global-${resIdentifier}:`, shvPath, options.signalName, (_path, _method, param) => {
343
- options.signalHandler(param, resource, async () => refreshValue().catch((error) => {
344
- console.error(`Failed to initialize ${resIdentifier}`, error);
345
- }));
346
- });
347
- }
348
- catch (error) {
349
- console.error(`Failed to initialize ${resIdentifier}`, error);
350
- }
351
- };
352
- let initialized = false;
353
- return () => {
354
- if (!initialized) {
355
- initialized = true;
356
- (0, vue_1.watchEffect)(async () => {
357
- (0, vue_1.onWatcherCleanup)(() => {
358
- initialized = false;
359
- resource.value = undefined;
360
- });
361
- if (connected.value !== 'connected') {
362
- return;
363
- }
364
- const shvPath = await (0, utils_1.resolveString)(options.shvPath);
365
- const resIdentifier = `${shvPath}:${options.method}`;
366
- initialize().catch((error) => {
367
- console.error(`Failed to initialize ${resIdentifier}`, error);
368
- });
369
- });
370
- }
371
- if ('default' in options) {
372
- const defaultValue = options.default;
373
- const withDefault = (0, vue_1.computed)(() => {
374
- if (resource.value === undefined) {
375
- return defaultValue;
376
- }
377
- return resource.value;
378
- });
379
- return withDefault;
380
- }
381
- return resource;
382
- };
383
- }
384
- const azureHandlerError = (0, vue_1.ref)('');
385
- const handleAzureCode = async () => {
386
- if (shvSessionStorage.value.azureWorkflow === undefined) {
387
- azureHandlerError.value = 'Azure error: no active login procedure';
388
- return;
389
- }
390
- if (options.azureCodeRedirect === undefined) {
391
- throw new Error('Azure redirect URL not set');
392
- }
393
- const { azureCodeRedirect } = options;
394
- return makePkce({ ...shvSessionStorage.value.azureWorkflow, azureCodeRedirect }).exchangeForAccessToken(globalThis.location.href).then(resp => {
395
- shvSessionStorage.value.azureWorkflow = undefined;
396
- const token = resp.access_token;
397
- if (token === undefined) {
398
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: unable to exchange access token';
399
- return;
400
- }
401
- // Store the token and remove the code from the query params.
402
- shvLogout();
403
- shvLocalStorage.value.azureAccessToken = token;
404
- const redirectTo = shvLocalStorage.value.azureRedirectTo;
405
- if (redirectTo === undefined) {
406
- azureHandlerError.value = 'Couldn\'t authenticate to Azure: no redirect URL';
407
- return;
408
- }
409
- shvLocalStorage.value.azureRedirectTo = undefined;
410
- return redirectTo;
411
- }).catch((error) => {
412
- azureHandlerError.value = `Couldn't authenticate to Azure: ${JSON.stringify(error)}`;
413
- });
414
- };
415
- return {
416
- azureAuth,
417
- azureHandlerError,
418
- connected,
419
- displayEmail,
420
- displayFullName,
421
- displayName,
422
- displayPhoto,
423
- displayShortName,
424
- getConnection,
425
- handleAzureCode,
426
- logContents,
427
- loginFailure,
428
- makeGlobalResource,
429
- makeRpcCall,
430
- makeRpcCallParam,
431
- rpcCall,
432
- setShvCredentials,
433
- shvLocalStorage,
434
- shvLogout,
435
- shvSessionStorage,
436
- };
437
- }
438
- const fullReloadHandler = (_param, _resource, reinit) => {
439
- reinit();
440
- };
441
- exports.fullReloadHandler = fullReloadHandler;