'use strict';

var vcStatusList = require('@digitalcredentials/vc-status-list');
var pako = require('pako');
var utils_types_bytes = require('../utils/types/bytes.cjs');
var vc_verifiableCredential = require('./verifiable-credential.cjs');
require('../utils/types/array.cjs');
require('bs58');
require('multiformats/bases/base58');
require('varint');
require('../utils/encoding/ss-58.cjs');
var utils_ident_ensureIdent = require('../utils/ident/ensure-ident.cjs');
require('jsonld');
require('@transmute/json-web-signature');
require('./crypto/Bls12381BBDT16KeyPairDock2024.cjs');
require('./crypto/Bls12381BBDT16MACDock2024.cjs');
require('./crypto/Bls12381BBDT16MACProofDock2024.cjs');
require('./crypto/Bls12381BBSKeyPairDock2023.cjs');
require('./crypto/Bls12381BBSSignatureDock2022.cjs');
require('./crypto/Bls12381BBSSignatureDock2023.cjs');
require('./crypto/Bls12381BBSSignatureProofDock2022.cjs');
require('./crypto/Bls12381BBSSignatureProofDock2023.cjs');
require('./crypto/Bls12381BDDT16KeyPairDock2024.cjs');
require('./crypto/Bls12381BDDT16MACDock2024.cjs');
require('./crypto/Bls12381BDDT16MACProofDock2024.cjs');
require('./crypto/Bls12381G2KeyPairDock2022.cjs');
require('./crypto/Bls12381PSKeyPairDock2023.cjs');
require('./crypto/Bls12381PSSignatureDock2023.cjs');
require('./crypto/Bls12381PSSignatureProofDock2023.cjs');
require('@juanelas/base64');
require('../keypairs/keypair-secp256k1.cjs');
require('./crypto/common/CustomLinkedDataSignature.cjs');
require('@stablelib/ed25519');
require('../types/public-keys/public-key.cjs');
require('../types/public-keys/public-key-sr25519-value.cjs');
require('../types/public-keys/public-key-ed25519-value.cjs');
require('../types/public-keys/public-key-secp256k1-value.cjs');
require('../types/public-keys/public-key-x25519-value.cjs');
require('../types/signatures/signature-value.cjs');
require('../types/signatures/signature.cjs');
require('../keypairs/dock-keypair.cjs');
require('../types/did/onchain/did-key.cjs');
require('../types/did/document/verification-method-ref-or-ident-ref.cjs');
require('../types/did/onchain/typed-did/index.cjs');
require('../types/did/document/verification-method-ref.cjs');
require('crypto');
require('../utils/interfaces.cjs');
require('../utils/assert.cjs');
require('../utils/error.cjs');
require('../utils/types/string.cjs');
require('../utils/types/iterable.cjs');
require('../utils/types/object.cjs');
require('../utils/inheritance.cjs');
require('../utils/types/set.cjs');
require('./helpers.cjs');
require('./document-loader.cjs');
require('./contexts.cjs');
require('./contexts/vc-examples-v1.cjs');
require('./contexts/security_context.cjs');
require('./contexts/status-list-21.cjs');
require('./contexts/private-status-list-21.cjs');
require('../utils/json-fetch.cjs');
require('./crypto/EcdsaSecp256k1Signature2019.cjs');
require('./crypto/constants.cjs');
require('./crypto/EcdsaSecp256k1VerificationKey2019.cjs');
require('../utils/encoding/multibase.cjs');
require('./crypto/Ed25519Signature2018.cjs');
require('./crypto/Ed25519VerificationKey2018.cjs');
require('../keypairs/keypair-ed25519.cjs');
require('../types/generic/typed-enum.cjs');
require('../types/generic/with-base.cjs');
require('../types/generic/with-catch-null.cjs');
require('../types/generic/with-eq.cjs');
require('../types/generic/any-of.cjs');
require('../types/generic/with-from.cjs');
require('blake2b');
require('../types/generic/with-from-json-bytes.cjs');
require('../types/generic/typed-null.cjs');
require('../types/generic/create-placeholder.cjs');
require('../types/generic/typed-bytes.cjs');
require('../types/generic/typed-string.cjs');
require('../types/generic/typed-array.cjs');
require('../types/generic/typed-tuple.cjs');
require('../types/generic/typed-number.cjs');
require('../types/generic/typed-set.cjs');
require('../types/generic/typed-map.cjs');
require('../types/generic/typed-struct.cjs');
require('uuid');
require('js-sha256');
require('../types/generic/sized.cjs');
require('../utils/types/number.cjs');
require('../types/signatures/signature-ed25519-value.cjs');
require('../types/signatures/signature-secp256k1-value.cjs');
require('../types/signatures/signature-sr25519-value.cjs');
require('./crypto/Ed25519Signature2020.cjs');
require('./crypto/Ed25519VerificationKey2020.cjs');
require('./crypto/JsonWebSignature2020.cjs');
require('../keypairs/did-keypair.cjs');
require('../types/offchain-signatures/params/index.cjs');
require('../types/offchain-signatures/params/value.cjs');
require('../types/generic/option.cjs');
require('../types/offchain-signatures/curve-type.cjs');
require('../types/offchain-signatures/params/id.cjs');
require('../types/generic/typed-uuid.cjs');
require('../types/generic/with-from-dock-id.cjs');
require('../types/did/onchain/typed-did/did-method-key/did-method-key-public-key.cjs');
require('../utils/encoding/base-58-btc.cjs');
require('../types/generic/with-qualifier.cjs');
require('../types/did/onchain/constants.cjs');
require('../types/did/onchain/typed-did/signature.cjs');
require('../types/did/onchain/typed-did/did-method-key/did-method-key-signature.cjs');
require('../types/did/onchain/typed-did/dock-did-value.cjs');
require('../types/generic/utils.cjs');
require('../types/generic/typed-bytes-array.cjs');
require('../types/did/onchain/typed-did/cheqd-did.cjs');
require('../types/offchain-signatures/public-keys/index.cjs');
require('../types/generic/with-prop.cjs');
require('../types/generic/with-props.cjs');
require('../types/offchain-signatures/public-keys/value.cjs');
require('../types/offchain-signatures/public-keys/ref.cjs');
require('../types/offchain-signatures/public-keys/id.cjs');
require('@docknetwork/crypto-wasm-ts');
require('./crypto/common/DockCryptoKeyPair.cjs');
require('@docknetwork/crypto-wasm-ts/lib/index.js');
require('./crypto/common/DockCryptoSignature.cjs');
require('jsonld-signatures');
require('json-stringify-deterministic');
require('semver/preload.js');
require('base64url');
require('./jws.cjs');
require('./crypto/common/DockCryptoSignatureProof.cjs');
require('elliptic');
require('../types/did/onchain/verification-relationship.cjs');
require('../types/did/document/ident-ref.cjs');
require('./credentials.cjs');
require('./CredentialIssuancePurpose.cjs');
require('./schema.cjs');
require('jsonschema');
require('./constants.cjs');
require('./revocation.cjs');
require('blakejs');
require('../utils/ident/matchers.cjs');

/**
 * Status list 2021 verifiable credential as per https://www.w3.org/TR/vc-status-list/#statuslist2021credential.
 */
class StatusList2021Credential extends vc_verifiableCredential {
  static Type = 'statusList2021';

  /**
   * Create a new Status List 2021 Verifiable Credential instance.
   * @param {string} id - id of the credential
   */
  constructor(id) {
    super(id);

    // Caches decoded status list.
    Object.defineProperty(this, 'internalCachedStatusList', {
      value: { encoded: void 0, decoded: void 0 },
      writable: true,
    });
  }

  /**
   * Fail if the given verifiable credential id isn't a valid `StatusList2021Credential` id.
   * @param {*} id
   */
  static verifyID(id) {
    utils_ident_ensureIdent.ensureStatusListId(id);
  }

  /**
   * Creates new `StatusList2021Credential` with supplied `id` and option `statusPurpose` = `revocation` by default,
   * `length` and `revokeIndices`. Note that credential with `statusPurpose` = `revocation` can't unsuspend its indices.
   * To allow unrevoking indices in the future, use `statusPurpose` = `suspension`.
   * The proof will be generated immediately using supplied `keyDoc`.
   *
   * @param {KeyDoc} keyDoc
   * @param {string} id - on-chain hex identifier for the `StatusList2021Credential`.
   * @param {object} [params={}]
   * @param {'revocation'|'suspension'} [params.statusPurpose=revocation] - `statusPurpose` of the `StatusList2021Credential`.
   * Can be either `revocation` or `suspension`.
   * @param {number} [params.length=1e4] - length of the underlying `StatusList`.
   * @param {Iterable<number>} [params.revokeIndices=[]] - iterable producing indices to be revoked or suspended initially
   * @returns {Promise<StatusList2021Credential>}
   */
  static async create(
    keyDoc,
    id,
    { statusPurpose = 'revocation', length = 1e4, revokeIndices = [] } = {},
  ) {
    const statusList = await vcStatusList.createList({ length });
    this.updateStatusList(statusPurpose, statusList, revokeIndices);

    const jsonCred = await vcStatusList.createCredential({
      id: String(id),
      list: statusList,
      statusPurpose,
    });

    const cred = this.fromJSON(jsonCred);

    return await cred.sign(keyDoc);
  }

  /**
   * Revokes indices and unsuspends other indices in the underlying status list, regenerating the proof.
   * If `statusPurpose` = `revocation`, indices can't be unsuspended.
   * The status list revoked (suspended)/unsuspended indices will be set atomically and in case of an error,
   * the underlying value won't be modified.
   * Throws an error if the underlying status list can't be decoded or any of the supplied indices is out of range.
   *
   * @param {KeyDoc} keyDoc
   * @param {object} [update={}]
   * @param {Iterable<number>} update.revokeIndices - indices to be revoked or suspended
   * @param {Iterable<number>} update.unsuspendIndices - indices to be unsuspended
   * @returns {Promise<this>}
   */
  async update(keyDoc, { revokeIndices = [], unsuspendIndices = [] }) {
    const currentStatusList = await this.decodedStatusList();
    const statusList = new vcStatusList.StatusList({
      buffer: new Uint8Array(currentStatusList.bitstring.bits),
    });

    this.constructor.updateStatusList(
      this.credentialSubject.statusPurpose,
      statusList,
      revokeIndices,
      unsuspendIndices,
    );

    this.credentialSubject.encodedList = await statusList.encode();
    // Remove `proof` so that an array of `proof`s is not created by the following `sign` call.
    delete this.proof;
    this.setIssuanceDate(new Date().toISOString());

    await this.sign(keyDoc);

    return this;
  }

  /**
   * Returns a `Promise` resolving to the decoded `StatusList`.
   *
   * @returns {Promise<StatusList>}
   */
  async decodedStatusList() {
    const { encoded, decoded } = this.internalCachedStatusList;

    if (encoded === this.credentialSubject.encodedList && decoded !== void 0) {
      return decoded;
    } else {
      this.internalCachedStatusList = {
        encoded: this.credentialSubject.encodedList,
        decoded: vcStatusList.decodeList(this.credentialSubject),
      };

      return this.internalCachedStatusList.decoded;
    }
  }

  /**
   * Returns `true` if given index is revoked or suspended, `false` otherwise.
   * Throws an error if the underlying status list can't be decoded or supplied index is out of range.
   *
   * @param {number} index
   * @returns {Promise<boolean>}
   */
  async revoked(index) {
    const decodedStatusList = await this.decodedStatusList();

    return decodedStatusList.getStatus(index);
  }

  /**
   * Accepts an iterable of indices to be checked and returns an array containing `true` in the positions
   * of revoked (suspended) indices and `false` for non-revoked (non-suspended) indices.
   * Throws an error if the underlying status list can't be decoded or any of supplied indices is out of range.
   *
   * @param {Iterable<number>} indices
   * @returns {Promise<Array<boolean>>}
   */
  async revokedBatch(indices) {
    const decodedStatusList = await this.decodedStatusList();

    return [...indices].map((index) => decodedStatusList.getStatus(index));
  }

  /**
   * Decodes `StatusList2021Credential` from provided bytes.
   * @param {Uint8Array} bytes
   */
  static fromBytes(bytes) {
    const gzipBufferCred = Buffer.from(utils_types_bytes.u8aToU8a(bytes));
    const stringifiedCred = pako.ungzip(gzipBufferCred, { to: 'string' });
    const parsedCred = JSON.parse(stringifiedCred);

    return this.fromJSON(parsedCred);
  }

  /**
   * Instantiates `StatusList2021Credential` from the provided `JSON`.
   *
   * @param {object} json
   * @returns {StatusList2021Credential}
   */
  static fromJSON(json) {
    const cred = super.fromJSON(json);
    cred.validate();

    return cred;
  }

  /**
   * Converts `StatusList2021Credential` to its JSON representation.
   * @returns {object}
   */
  toJSON() {
    this.validate();

    return super.toJSON();
  }

  /**
   * Encodes `StatusList2021Credential` as bytes.
   * @returns {Uint8Array}
   */
  toBytes() {
    const jsonCred = this.toJSON();
    const stringifiedCred = JSON.stringify(jsonCred);
    const bufferCred = Buffer.from(stringifiedCred);

    return pako.gzip(bufferCred);
  }

  /**
   * Validates underlying `StatusList2021Credential`.
   */
  validate() {
    const { credentialSubject } = this;

    if (!credentialSubject) throw new Error('Missing `credentialSubject`');
    if (!this.constructor.statusPurposes.has(credentialSubject.statusPurpose)) {
      throw new Error(
        `Invalid \`statusPurpose\`, expected one of \`${[
          ...this.constructor.statusPurposes,
        ].join(', ')}\``,
      );
    }
    if (typeof credentialSubject.id !== 'string' || !credentialSubject.id) {
      throw new Error('Missing `credentialSubject.id`');
    }
    if (credentialSubject.type !== 'StatusList2021') {
      throw new Error(
        '`credentialSubject.type` must be set to `StatusList2021`',
      );
    }
    if (!credentialSubject.encodedList) {
      throw new Error('`credentialSubject.encodedList` must be present');
    }
  }

  /**
   * Revokes (suspends) `revokeIndices` and unsuspends `unsuspendIndices` from the supplied `StatusList`.
   *
   * Throws an error if
   * - non-empty `unsuspendIndices` passed along with `statusPurpose != suspension`
   * - any index is present in both iterables
   * - some index is out of bounds.
   *
   * @param {'revocation'|'suspension'} statusPurpose
   * @param {StatusList} statusList
   * @param {Iterable<number>} revokeIndices
   * @param {Iterable<number>} unsuspendIndices
   */
  static updateStatusList(
    statusPurpose,
    statusList,
    revokeIndices = [],
    unsuspendIndices = [],
  ) {
    const unsuspendIndiceSet = new Set(unsuspendIndices);
    if (statusPurpose !== 'suspension' && unsuspendIndiceSet.size > 0) {
      throw new Error(
        `Can't unsuspend indices for credential with \`statusPurpose\` = \`${statusPurpose}\`, it's only possible with \`statusPurpose\` = \`suspension\``,
      );
    }

    for (const idx of revokeIndices) {
      if (unsuspendIndiceSet.has(idx)) {
        throw new Error(
          `Index \`${idx}\` appears in both revoke and unsuspend sets`,
        );
      }

      statusList.setStatus(idx, true);
    }
    for (const idx of unsuspendIndiceSet) {
      statusList.setStatus(idx, false);
    }
  }
}

/**
 * Allowed status purposes for this credential type.
 */
StatusList2021Credential.statusPurposes = new Set(['revocation', 'suspension']);

module.exports = StatusList2021Credential;
//# sourceMappingURL=status-list2021-credential.cjs.map
