PHP WebShell

Текущая директория: /usr/lib/node_modules/bitgo/node_modules/@polkadot-api/substrate-client/dist

Просмотр файла: index.js

"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// src/index.ts
var src_exports = {};
__export(src_exports, {
  AbortError: () => import_utils3.AbortError,
  DestroyedError: () => DestroyedError,
  DisjointError: () => DisjointError,
  OperationError: () => OperationError,
  OperationInaccessibleError: () => OperationInaccessibleError,
  OperationLimitError: () => OperationLimitError,
  RpcError: () => RpcError,
  StopError: () => StopError,
  createClient: () => createClient2
});
module.exports = __toCommonJS(src_exports);

// src/internal-utils/abortablePromiseFn.ts
var import_utils = require("@polkadot-api/utils");
var abortablePromiseFn = (fn) => (...args) => new Promise((res, rej) => {
  let cancel = import_utils.noop;
  const [actualArgs, abortSignal] = args[args.length - 1] instanceof AbortSignal ? [args.slice(0, args.length - 1), args[args.length - 1]] : [args];
  const onAbort = () => {
    cancel();
    rej(new import_utils.AbortError());
  };
  abortSignal?.addEventListener("abort", onAbort, { once: true });
  const withCleanup = (fn2) => (x) => {
    cancel = import_utils.noop;
    abortSignal?.removeEventListener("abort", onAbort);
    fn2(x);
  };
  cancel = fn(...[withCleanup(res), withCleanup(rej), ...actualArgs]);
});

// src/internal-utils/deferred-promise.ts
function deferred() {
  let res = () => {
  };
  let rej = () => {
  };
  const promise = new Promise((_res, _rej) => {
    res = _res;
    rej = _rej;
  });
  return { promise, res, rej };
}

// src/internal-utils/noop.ts
var noop2 = () => {
};

// src/internal-utils/subscriptions-manager.ts
var getSubscriptionsManager = () => {
  const subscriptions = /* @__PURE__ */ new Map();
  return {
    has: subscriptions.has.bind(subscriptions),
    subscribe(id, subscriber) {
      subscriptions.set(id, subscriber);
    },
    unsubscribe(id) {
      subscriptions.delete(id);
    },
    next(id, data) {
      subscriptions.get(id)?.next(data);
    },
    error(id, e) {
      const subscriber = subscriptions.get(id);
      if (subscriber) {
        subscriptions.delete(id);
        subscriber.error(e);
      }
    },
    errorAll(e) {
      const subscribers = [...subscriptions.values()];
      subscriptions.clear();
      subscribers.forEach((s) => {
        s.error(e);
      });
    }
  };
};

// src/methods.ts
var chainHead = {
  body: "",
  call: "",
  continue: "",
  follow: "",
  header: "",
  stopOperation: "",
  storage: "",
  unfollow: "",
  unpin: "",
  followEvent: ""
};
var chainSpec = {
  chainName: "",
  genesisHash: "",
  properties: ""
};
var transaction = {
  broadcast: "",
  stop: ""
};
var transactionWatch = {
  submitAndWatch: "",
  unwatch: ""
};
Object.entries({ chainHead, chainSpec, transaction, transactionWatch }).forEach(
  ([fnGroupName, methods]) => {
    Object.keys(methods).forEach((methodName) => {
      ;
      methods[methodName] = `${fnGroupName}_v1_${methodName}`;
    });
  }
);

// src/transaction/transaction.ts
var getTransaction = (request) => (tx, error) => {
  let cancel = request(transaction.broadcast, [tx], {
    onSuccess: (subscriptionId) => {
      cancel = subscriptionId === null ? noop2 : () => {
        request(transaction.stop, [subscriptionId]);
      };
      if (subscriptionId === null) {
        error(new Error("Max # of broadcasted transactions has been reached"));
      }
    },
    onError: error
  });
  return () => {
    cancel();
  };
};

// src/chainhead/errors.ts
var StopError = class extends Error {
  constructor() {
    super("ChainHead stopped");
    this.name = "StopError";
  }
};
var DisjointError = class extends Error {
  constructor() {
    super("ChainHead disjointed");
    this.name = "DisjointError";
  }
};
var OperationLimitError = class extends Error {
  constructor() {
    super("ChainHead operations limit reached");
    this.name = "OperationLimitError";
  }
};
var OperationError = class extends Error {
  constructor(error) {
    super(error);
    this.name = "OperationError";
  }
};
var OperationInaccessibleError = class extends Error {
  constructor() {
    super("ChainHead operation inaccessible");
    this.name = "OperationInaccessibleError";
  }
};

// src/chainhead/operation-promise.ts
var createOperationPromise = (operationName, factory) => (request) => abortablePromiseFn((res, rej, ...args) => {
  let isRunning = true;
  let cancel = () => {
    isRunning = false;
  };
  const [requestArgs, logicCb] = factory(...args);
  request(operationName, requestArgs, {
    onSuccess: (response, followSubscription) => {
      if (response.result === "limitReached")
        return rej(new OperationLimitError());
      const { operationId } = response;
      const stopOperation = () => {
        request(chainHead.stopOperation, [operationId]);
      };
      if (!isRunning) return stopOperation();
      let done = noop2;
      const _res = (x) => {
        isRunning = false;
        done();
        res(x);
      };
      const _rej = (x) => {
        isRunning = false;
        done();
        rej(x);
      };
      done = followSubscription(operationId, {
        next: (e) => {
          const _e = e;
          if (_e.event === "operationError")
            rej(new OperationError(_e.error));
          else if (_e.event === "operationInaccessible")
            rej(new OperationInaccessibleError());
          else logicCb(e, _res, _rej);
        },
        error: _rej
      });
      cancel = () => {
        if (isRunning) {
          done();
          stopOperation();
        }
      };
    },
    onError: rej
  });
  return () => {
    cancel();
  };
});

// src/chainhead/body.ts
var createBodyFn = createOperationPromise(
  chainHead.body,
  (hash) => [
    [hash],
    (e, res) => {
      res(e.value);
    }
  ]
);

// src/chainhead/call.ts
var createCallFn = createOperationPromise(
  chainHead.call,
  (hash, fnName, callParameters) => [
    [hash, fnName, callParameters],
    (e, res) => {
      res(e.output);
    }
  ]
);

// src/chainhead/header.ts
var createHeaderFn = (request) => (hash) => new Promise((res, rej) => {
  request(chainHead.header, [hash], {
    onSuccess: res,
    onError: rej
  });
});

// src/chainhead/storage-subscription.ts
var import_utils2 = require("@polkadot-api/utils");
var createStorageCb = (request) => (hash, inputs, childTrie, onItems, onError, onDone, onDiscardedItems) => {
  if (inputs.length === 0) {
    onDone();
    return import_utils2.noop;
  }
  let isRunning = true;
  let cancel = () => {
    isRunning = false;
  };
  request(chainHead.storage, [hash, inputs, childTrie], {
    onSuccess: (response, followSubscription) => {
      if (response.result === "limitReached" || response.discardedItems === inputs.length)
        return onError(new OperationLimitError());
      const { operationId } = response;
      const stopOperation = () => {
        request(chainHead.stopOperation, [operationId]);
      };
      if (!isRunning) return stopOperation();
      const doneListening = followSubscription(response.operationId, {
        next: (event) => {
          switch (event.event) {
            case "operationStorageItems": {
              onItems(event.items);
              break;
            }
            case "operationStorageDone": {
              _onDone();
              break;
            }
            case "operationError": {
              _onError(new OperationError(event.error));
              break;
            }
            case "operationInaccessible": {
              _onError(new OperationInaccessibleError());
              break;
            }
            default:
              request(chainHead.continue, [event.operationId]);
          }
        },
        error: onError
      });
      cancel = () => {
        doneListening();
        request(chainHead.stopOperation, [response.operationId]);
      };
      const _onError = (e) => {
        cancel = import_utils2.noop;
        doneListening();
        onError(e);
      };
      const _onDone = () => {
        cancel = import_utils2.noop;
        doneListening();
        onDone();
      };
      onDiscardedItems(response.discardedItems);
    },
    onError
  });
  return () => {
    cancel();
  };
};

// src/chainhead/storage.ts
var createStorageFn = (request) => {
  const cbStore = createStorageCb(request);
  return abortablePromiseFn((resolve, reject, hash, type, key, childTrie) => {
    const isDescendants = type.startsWith("descendants");
    let result = isDescendants ? [] : null;
    const onItems = isDescendants ? (items) => {
      result.push(items);
    } : (items) => {
      result = items[0]?.[type];
    };
    const cancel = cbStore(
      hash,
      [{ key, type }],
      childTrie ?? null,
      onItems,
      reject,
      () => {
        try {
          resolve(isDescendants ? result.flat() : result);
        } catch (e) {
          reject(e);
        }
      },
      (nDiscarded) => {
        if (nDiscarded > 0) {
          cancel();
          reject(new OperationLimitError());
        }
      }
    );
    return cancel;
  });
};

// src/chainhead/unpin.ts
var createUnpinFn = (request) => (hashes) => hashes.length > 0 ? new Promise((res, rej) => {
  request(chainHead.unpin, [hashes], {
    onSuccess() {
      res();
    },
    onError: rej
  });
}) : Promise.resolve();

// src/client/DestroyedError.ts
var DestroyedError = class extends Error {
  constructor() {
    super("Client destroyed");
    this.name = "DestroyedError";
  }
};

// src/chainhead/chainhead.ts
function isOperationEvent(event) {
  return event.operationId !== void 0;
}
function getChainHead(request) {
  return (withRuntime, onFollowEvent, onFollowError) => {
    const subscriptions = getSubscriptionsManager();
    const ongoingRequests = /* @__PURE__ */ new Set();
    const deferredFollow = deferred();
    let followSubscription = deferredFollow.promise;
    const onAllFollowEventsNext = (event) => {
      if (isOperationEvent(event)) {
        if (!subscriptions.has(event.operationId))
          console.warn("Uknown operationId on", event);
        return subscriptions.next(event.operationId, event);
      }
      if (event.event !== "stop") {
        if (event.event === "initialized") {
          return onFollowEvent({
            type: event.event,
            finalizedBlockHashes: "finalizedBlockHash" in event ? [event.finalizedBlockHash] : event.finalizedBlockHashes,
            finalizedBlockRuntime: event.finalizedBlockRuntime
          });
        }
        const { event: type, ...rest } = event;
        return onFollowEvent({ type, ...rest });
      }
      onFollowError(new StopError());
      unfollow(false);
    };
    const onAllFollowEventsError = (error) => {
      onFollowError(error);
      unfollow(!(error instanceof DestroyedError));
    };
    const onFollowRequestSuccess = (subscriptionId, follow) => {
      const done = follow(subscriptionId, {
        next: onAllFollowEventsNext,
        error: onAllFollowEventsError
      });
      unfollow = (sendUnfollow = true) => {
        followSubscription = null;
        unfollow = noop2;
        done();
        sendUnfollow && request(chainHead.unfollow, [subscriptionId]);
        subscriptions.errorAll(new DisjointError());
        ongoingRequests.forEach((cb) => {
          cb();
        });
        ongoingRequests.clear();
      };
      followSubscription = subscriptionId;
      deferredFollow.res(subscriptionId);
    };
    const onFollowRequestError = (e) => {
      if (e instanceof DestroyedError) {
        unfollow(false);
      } else {
        onFollowError(e);
      }
      followSubscription = null;
      deferredFollow.res(e);
    };
    let unfollow = request(
      chainHead.follow,
      [withRuntime],
      { onSuccess: onFollowRequestSuccess, onError: onFollowRequestError }
    );
    const fRequest = (method, params, cb) => {
      const disjoint = () => {
        cb?.onError(new DisjointError());
      };
      if (followSubscription === null) {
        disjoint();
        return noop2;
      }
      const onSubscription = (subscription) => {
        if (!cb) return request(method, [subscription, ...params]);
        ongoingRequests.add(disjoint);
        const onSubscribeOperation = (operationId, subscriber) => {
          if (followSubscription === null) {
            subscriber.error(new DisjointError());
            return noop2;
          }
          subscriptions.subscribe(operationId, subscriber);
          return () => {
            subscriptions.unsubscribe(operationId);
          };
        };
        const cleanup = request(method, [subscription, ...params], {
          onSuccess: (response) => {
            ongoingRequests.delete(disjoint);
            cb.onSuccess(response, onSubscribeOperation);
          },
          onError: (e) => {
            ongoingRequests.delete(disjoint);
            cb.onError(e);
          }
        });
        return () => {
          ongoingRequests.delete(disjoint);
          cleanup();
        };
      };
      if (typeof followSubscription === "string")
        return onSubscription(followSubscription);
      let onCancel = noop2;
      followSubscription.then((x) => {
        if (x instanceof Error) return disjoint();
        if (followSubscription) onCancel = onSubscription(x);
      });
      return () => {
        onCancel();
      };
    };
    return {
      unfollow() {
        unfollow();
        followSubscription = null;
      },
      body: createBodyFn(fRequest),
      call: createCallFn(fRequest),
      header: createHeaderFn(fRequest),
      storage: createStorageFn(fRequest),
      storageSubscription: createStorageCb(fRequest),
      unpin: createUnpinFn(fRequest),
      _request: fRequest
    };
  };
}

// src/client/RpcError.ts
var RpcError = class extends Error {
  constructor(e) {
    super(e.message);
    __publicField(this, "code");
    __publicField(this, "data");
    this.code = e.code;
    this.data = e.data;
    this.name = "RpcError";
  }
};

// src/client/createClient.ts
var nextClientId = 1;
var createClient = (gProvider) => {
  let clientId = nextClientId++;
  const responses = /* @__PURE__ */ new Map();
  const subscriptions = getSubscriptionsManager();
  let connection = null;
  const send = (id, method, params) => {
    connection.send(
      JSON.stringify({
        jsonrpc: "2.0",
        id,
        method,
        params
      })
    );
  };
  function onMessage(message) {
    try {
      let id, result, error, params, subscription;
      const parsed = JSON.parse(message);
      ({ id, result, error, params } = parsed);
      if (id) {
        const cb = responses.get(id);
        if (!cb) return;
        responses.delete(id);
        return error ? cb.onError(new RpcError(error)) : cb.onSuccess(result, (opaqueId, subscriber) => {
          const subscriptionId2 = opaqueId;
          subscriptions.subscribe(subscriptionId2, subscriber);
          return () => {
            subscriptions.unsubscribe(subscriptionId2);
          };
        });
      }
      ;
      ({ subscription, result, error } = params);
      if (!subscription || !error && !Object.hasOwn(params, "result")) throw 0;
      const subscriptionId = subscription;
      if (error) {
        subscriptions.error(subscriptionId, new RpcError(error));
      } else {
        subscriptions.next(subscriptionId, result);
      }
    } catch (e) {
      console.warn("Error parsing incomming message: " + message);
      console.error(e);
    }
  }
  connection = gProvider(onMessage);
  const disconnect = () => {
    connection?.disconnect();
    connection = null;
    subscriptions.errorAll(new DestroyedError());
    responses.forEach((r) => r.onError(new DestroyedError()));
    responses.clear();
  };
  let nextId = 1;
  const request = (method, params, cb) => {
    if (!connection) throw new Error("Not connected");
    const id = `${clientId}-${nextId++}`;
    if (cb) responses.set(id, cb);
    send(id, method, params);
    return () => {
      responses.delete(id);
    };
  };
  return {
    request,
    disconnect
  };
};

// src/chainspec.ts
var createGetChainSpec = (clientRequest) => {
  const request = abortablePromiseFn(
    (onSuccess, onError, method, params) => clientRequest(method, params, { onSuccess, onError })
  );
  let cachedPromise = null;
  return async () => {
    if (cachedPromise) return cachedPromise;
    return cachedPromise = Promise.all([
      request(chainSpec.chainName, []),
      request(chainSpec.genesisHash, []),
      request(chainSpec.properties, [])
    ]).then(([name, genesisHash, properties]) => ({
      name,
      genesisHash,
      properties
    }));
  };
};

// src/request-compatibility-enhancer.ts
var getCompatibilityEnhancer = (rpcMethodsP, request) => (methods) => {
  let translations = {};
  let enhancedRequest = null;
  return (method, ...rest) => {
    if (enhancedRequest) return enhancedRequest(method, ...rest);
    let isRunning = true;
    let cleanup = () => {
      isRunning = false;
    };
    rpcMethodsP.then((rpcMethods) => {
      enhancedRequest = (method_, ...iRest) => {
        const method2 = translations[method_] ?? method_;
        if (rpcMethods.has(method2)) return request(method2, ...iRest);
        iRest[1]?.onError(new Error(`Unsupported method ${method2}`));
        return noop2;
      };
      if (rpcMethods.has(method)) return;
      const parts = method.split("_");
      if (parts[1] !== "v1") return;
      parts[1] = "unstable";
      if (rpcMethods.has(parts.join("_")))
        Object.values(methods).forEach((value) => {
          translations[value] = value.replace("_v1_", "_unstable_");
        });
      else if (parts[0] === "transaction") {
        let unwatch;
        let version;
        const txGroup = ["transactionWatch", "transaction"].find(
          (group) => {
            version = ["v1", "unstable"].find(
              (v) => rpcMethods.has(unwatch = `${group}_${v}_unwatch`)
            );
            return !!version;
          }
        );
        if (txGroup) {
          translations[methods.broadcast] = `${txGroup}_${version}_submitAndWatch`;
          translations[methods.stop] = unwatch;
        }
      }
    }).then(() => {
      if (isRunning) cleanup = enhancedRequest(method, ...rest);
    });
    return () => {
      cleanup();
    };
  };
};

// src/index.ts
var import_utils3 = require("@polkadot-api/utils");
var createClient2 = (provider) => {
  const client = createClient(provider);
  const request = abortablePromiseFn(
    (onSuccess, onError, method, params) => client.request(method, params, { onSuccess, onError })
  );
  const rpcMethods = request("rpc_methods", []).then(
    (x) => new Set(Array.isArray(x) ? x : x.methods),
    () => /* @__PURE__ */ new Set()
  );
  const compatibilityEnhancer = getCompatibilityEnhancer(
    rpcMethods,
    client.request
  );
  return {
    chainHead: getChainHead(
      compatibilityEnhancer(chainHead)
    ),
    transaction: getTransaction(
      compatibilityEnhancer(transaction)
    ),
    getChainSpecData: createGetChainSpec(
      compatibilityEnhancer(chainSpec)
    ),
    destroy: () => {
      client.disconnect();
    },
    request,
    _request: client.request
  };
};
//# sourceMappingURL=index.js.map

Выполнить команду


Для локальной разработки. Не используйте в интернете!