/**
     * Specifies the audit configuration for a service. The configuration determines which permission types are logged, and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs.  If there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each AuditLogConfig are exempted.  Example Policy with multiple AuditConfigs:      {       "audit_configs": [         {           "service": "allServices"           "audit_log_configs": [             {               "log_type": "DATA_READ",               "exempted_members": [                 "user:foo@gmail.com"               ]             },             {               "log_type": "DATA_WRITE",             },             {               "log_type": "ADMIN_READ",             }           ]         },         {           "service": "fooservice.googleapis.com"           "audit_log_configs": [             {               "log_type": "DATA_READ",             },             {               "log_type": "DATA_WRITE",               "exempted_members": [                 "user:bar@gmail.com"               ]             }           ]         }       ]     }  For fooservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also exempts foo@gmail.com from DATA_READ logging, and bar@gmail.com from DATA_WRITE logging.
     */
interface Schema$AuditConfig {
        /**
         * The configuration for logging of each type of permission.
         */
        auditLogConfigs?: Schema$AuditLogConfig[];
        /**
         * Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
         */
        service?: string;
    }


/**
     * Provides the configuration for logging a type of permissions. Example:      {       "audit_log_configs": [         {           "log_type": "DATA_READ",           "exempted_members": [             "user:foo@gmail.com"           ]         },         {           "log_type": "DATA_WRITE",         }       ]     }  This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting foo@gmail.com from DATA_READ logging.
     */
interface Schema$AuditLogConfig {
        /**
         * Specifies the identities that do not cause logging for this type of permission. Follows the same format of Binding.members.
         */
        exemptedMembers?: string[];
        /**
         * The log type that this config enables.
         */
        logType?: string;
    }


/**
     * Batch get assets history response.
     */
interface Schema$BatchGetAssetsHistoryResponse {
        /**
         * A list of assets with valid time windows.
         */
        assets?: Schema$TemporalAsset[];
    }


/**
     * Associates `members` with a `role`.
     */
interface Schema$Binding {
        /**
         * The condition that is associated with this binding. NOTE: An unsatisfied condition will not allow user access via current binding. Different bindings, including their conditions, are examined independently.
         */
        condition?: Schema$Expr;
        /**
         * Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following values:  * `allUsers`: A special identifier that represents anyone who is    on the internet; with or without a Google account.  * `allAuthenticatedUsers`: A special identifier that represents anyone    who is authenticated with a Google account or a service account.  * `user:{emailid}`: An email address that represents a specific Google    account. For example, `alice@gmail.com` .   * `serviceAccount:{emailid}`: An email address that represents a service    account. For example, `my-other-app@appspot.gserviceaccount.com`.  * `group:{emailid}`: An email address that represents a Google group.    For example, `admins@example.com`.   * `domain:{domain}`: The G Suite domain (primary) that represents all the    users of that domain. For example, `google.com` or `example.com`.
         */
        members?: string[];
        /**
         * Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
         */
        role?: string;
    }


/**
     * Export asset request.
     */
interface Schema$ExportAssetsRequest {
        /**
         * A list of asset types of which to take a snapshot for. For example: "compute.googleapis.com/Disk". If specified, only matching assets will be returned. See [Introduction to Cloud Asset Inventory](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/overview) for all supported asset types.
         */
        assetTypes?: string[];
        /**
         * Asset content type. If not specified, no content but the asset name will be returned.
         */
        contentType?: string;
        /**
         * Required. Output configuration indicating where the results will be output to. All results will be in newline delimited JSON format.
         */
        outputConfig?: Schema$OutputConfig;
        /**
         * Timestamp to take an asset snapshot. This can only be set to a timestamp between 2018-10-02 UTC (inclusive) and the current time. If not specified, the current time will be used. Due to delays in resource data collection and indexing, there is a volatile window during which running the same query may get different results.
         */
        readTime?: string;
    }


/**
     * Represents an expression text. Example:      title: "User account presence"     description: "Determines whether the request has a user account"     expression: "size(request.user) > 0"
     */
interface Schema$Expr {
        /**
         * An optional description of the expression. This is a longer text which describes the expression, e.g. when hovered over it in a UI.
         */
        description?: string;
        /**
         * Textual representation of an expression in Common Expression Language syntax.  The application context of the containing message determines which well-known feature set of CEL is supported.
         */
        expression?: string;
        /**
         * An optional string indicating the location of the expression for error reporting, e.g. a file name and a position in the file.
         */
        location?: string;
        /**
         * An optional title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs which allow to enter the expression.
         */
        title?: string;
    }


/**
     * A Cloud Storage location.
     */
interface Schema$GcsDestination {
        /**
         * The uri of the Cloud Storage object. It's the same uri that is used by gsutil. For example: "gs://bucket_name/object_name". See [Viewing and Editing Object Metadata](https://cloud.google.com/storage/docs/viewing-editing-metadata) for more information.
         */
        uri?: string;
        /**
         * The uri prefix of all generated Cloud Storage objects. For example: "gs://bucket_name/object_name_prefix". Each object uri is in format: "gs://bucket_name/object_name_prefix/<asset type>/<shard number> and only contains assets for that type. <shard number> starts from 0. For example: "gs://bucket_name/object_name_prefix/compute.googleapis.com/Disk/0" is the first shard of output objects containing all compute.googleapis.com/Disk assets. An INVALID_ARGUMENT error will be returned if file with the same name "gs://bucket_name/object_name_prefix" already exists.
         */
        uriPrefix?: string;
    }


/**
     * Used in `policy_type` to specify how `boolean_policy` will behave at this resource.
     */
interface Schema$GoogleCloudOrgpolicyV1BooleanPolicy {
        /**
         * If `true`, then the `Policy` is enforced. If `false`, then any configuration is acceptable.  Suppose you have a `Constraint` `constraints/compute.disableSerialPortAccess` with `constraint_default` set to `ALLOW`. A `Policy` for that `Constraint` exhibits the following behavior:   - If the `Policy` at this resource has enforced set to `false`, serial     port connection attempts will be allowed.   - If the `Policy` at this resource has enforced set to `true`, serial     port connection attempts will be refused.   - If the `Policy` at this resource is `RestoreDefault`, serial port     connection attempts will be allowed.   - If no `Policy` is set at this resource or anywhere higher in the     resource hierarchy, serial port connection attempts will be allowed.   - If no `Policy` is set at this resource, but one exists higher in the     resource hierarchy, the behavior is as if the`Policy` were set at     this resource.  The following examples demonstrate the different possible layerings:  Example 1 (nearest `Constraint` wins):   `organizations/foo` has a `Policy` with:     {enforced: false}   `projects/bar` has no `Policy` set. The constraint at `projects/bar` and `organizations/foo` will not be enforced.  Example 2 (enforcement gets replaced):   `organizations/foo` has a `Policy` with:     {enforced: false}   `projects/bar` has a `Policy` with:     {enforced: true} The constraint at `organizations/foo` is not enforced. The constraint at `projects/bar` is enforced.  Example 3 (RestoreDefault):   `organizations/foo` has a `Policy` with:     {enforced: true}   `projects/bar` has a `Policy` with:     {RestoreDefault: {}} The constraint at `organizations/foo` is enforced. The constraint at `projects/bar` is not enforced, because `constraint_default` for the `Constraint` is `ALLOW`.
         */
        enforced?: boolean;
    }


/**
     * Used in `policy_type` to specify how `list_policy` behaves at this resource.  `ListPolicy` can define specific values and subtrees of Cloud Resource Manager resource hierarchy (`Organizations`, `Folders`, `Projects`) that are allowed or denied by setting the `allowed_values` and `denied_values` fields. This is achieved by using the `under:` and optional `is:` prefixes. The `under:` prefix is used to denote resource subtree values. The `is:` prefix is used to denote specific values, and is required only if the value contains a ":". Values prefixed with "is:" are treated the same as values with no prefix. Ancestry subtrees must be in one of the following formats:     - “projects/<project-id>”, e.g. “projects/tokyo-rain-123”     - “folders/<folder-id>”, e.g. “folders/1234”     - “organizations/<organization-id>”, e.g. “organizations/1234” The `supports_under` field of the associated `Constraint`  defines whether ancestry prefixes can be used. You can set `allowed_values` and `denied_values` in the same `Policy` if `all_values` is `ALL_VALUES_UNSPECIFIED`. `ALLOW` or `DENY` are used to allow or deny all values. If `all_values` is set to either `ALLOW` or `DENY`, `allowed_values` and `denied_values` must be unset.
     */
interface Schema$GoogleCloudOrgpolicyV1ListPolicy {
        /**
         * List of values allowed  at this resource. Can only be set if `all_values` is set to `ALL_VALUES_UNSPECIFIED`.
         */
        allowedValues?: string[];
        /**
         * The policy all_values state.
         */
        allValues?: string;
        /**
         * List of values denied at this resource. Can only be set if `all_values` is set to `ALL_VALUES_UNSPECIFIED`.
         */
        deniedValues?: string[];
        /**
         * Determines the inheritance behavior for this `Policy`.  By default, a `ListPolicy` set at a resource supercedes any `Policy` set anywhere up the resource hierarchy. However, if `inherit_from_parent` is set to `true`, then the values from the effective `Policy` of the parent resource are inherited, meaning the values set in this `Policy` are added to the values inherited up the hierarchy.  Setting `Policy` hierarchies that inherit both allowed values and denied values isn't recommended in most circumstances to keep the configuration simple and understandable. However, it is possible to set a `Policy` with `allowed_values` set that inherits a `Policy` with `denied_values` set. In this case, the values that are allowed must be in `allowed_values` and not present in `denied_values`.  For example, suppose you have a `Constraint` `constraints/serviceuser.services`, which has a `constraint_type` of `list_constraint`, and with `constraint_default` set to `ALLOW`. Suppose that at the Organization level, a `Policy` is applied that restricts the allowed API activations to {`E1`, `E2`}. Then, if a `Policy` is applied to a project below the Organization that has `inherit_from_parent` set to `false` and field all_values set to DENY, then an attempt to activate any API will be denied.  The following examples demonstrate different possible layerings for `projects/bar` parented by `organizations/foo`:  Example 1 (no inherited values):   `organizations/foo` has a `Policy` with values:     {allowed_values: “E1” allowed_values:”E2”}   `projects/bar` has `inherit_from_parent` `false` and values:     {allowed_values: "E3" allowed_values: "E4"} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are `E3`, and `E4`.  Example 2 (inherited values):   `organizations/foo` has a `Policy` with values:     {allowed_values: “E1” allowed_values:”E2”}   `projects/bar` has a `Policy` with values:     {value: “E3” value: ”E4” inherit_from_parent: true} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are `E1`, `E2`, `E3`, and `E4`.  Example 3 (inheriting both allowed and denied values):   `organizations/foo` has a `Policy` with values:     {allowed_values: "E1" allowed_values: "E2"}   `projects/bar` has a `Policy` with:     {denied_values: "E1"} The accepted values at `organizations/foo` are `E1`, `E2`. The value accepted at `projects/bar` is `E2`.  Example 4 (RestoreDefault):   `organizations/foo` has a `Policy` with values:     {allowed_values: “E1” allowed_values:”E2”}   `projects/bar` has a `Policy` with values:     {RestoreDefault: {}} The accepted values at `organizations/foo` are `E1`, `E2`. The accepted values at `projects/bar` are either all or none depending on the value of `constraint_default` (if `ALLOW`, all; if `DENY`, none).  Example 5 (no policy inherits parent policy):   `organizations/foo` has no `Policy` set.   `projects/bar` has no `Policy` set. The accepted values at both levels are either all or none depending on the value of `constraint_default` (if `ALLOW`, all; if `DENY`, none).  Example 6 (ListConstraint allowing all):   `organizations/foo` has a `Policy` with values:     {allowed_values: “E1” allowed_values: ”E2”}   `projects/bar` has a `Policy` with:     {all: ALLOW} The accepted values at `organizations/foo` are `E1`, E2`. Any value is accepted at `projects/bar`.  Example 7 (ListConstraint allowing none):   `organizations/foo` has a `Policy` with values:     {allowed_values: “E1” allowed_values: ”E2”}   `projects/bar` has a `Policy` with:     {all: DENY} The accepted values at `organizations/foo` are `E1`, E2`. No value is accepted at `projects/bar`.  Example 10 (allowed and denied subtrees of Resource Manager hierarchy): Given the following resource hierarchy   O1->{F1, F2}; F1->{P1}; F2->{P2, P3},   `organizations/foo` has a `Policy` with values:     {allowed_values: "under:organizations/O1"}   `projects/bar` has a `Policy` with:     {allowed_values: "under:projects/P3"}     {denied_values: "under:folders/F2"} The accepted values at `organizations/foo` are `organizations/O1`,   `folders/F1`, `folders/F2`, `projects/P1`, `projects/P2`,   `projects/P3`. The accepted values at `projects/bar` are `organizations/O1`,   `folders/F1`, `projects/P1`.
         */
        inheritFromParent?: boolean;
        /**
         * Optional. The Google Cloud Console will try to default to a configuration that matches the value specified in this `Policy`. If `suggested_value` is not set, it will inherit the value specified higher in the hierarchy, unless `inherit_from_parent` is `false`.
         */
        suggestedValue?: string;
    }


/**
     * Defines a Cloud Organization `Policy` which is used to specify `Constraints` for configurations of Cloud Platform resources.
     */
interface Schema$GoogleCloudOrgpolicyV1Policy {
        /**
         * For boolean `Constraints`, whether to enforce the `Constraint` or not.
         */
        booleanPolicy?: Schema$GoogleCloudOrgpolicyV1BooleanPolicy;
        /**
         * The name of the `Constraint` the `Policy` is configuring, for example, `constraints/serviceuser.services`.  Immutable after creation.
         */
        constraint?: string;
        /**
         * An opaque tag indicating the current version of the `Policy`, used for concurrency control.  When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this `etag` indicates the version of the current `Policy` to use when executing a read-modify-write loop.  When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be unset.  When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional write of the `Policy`.
         */
        etag?: string;
        /**
         * List of values either allowed or disallowed.
         */
        listPolicy?: Schema$GoogleCloudOrgpolicyV1ListPolicy;
        /**
         * Restores the default behavior of the constraint; independent of `Constraint` type.
         */
        restoreDefault?: Schema$GoogleCloudOrgpolicyV1RestoreDefault;
        /**
         * The time stamp the `Policy` was previously updated. This is set by the server, not specified by the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`. Any value set by the client will be ignored.
         */
        updateTime?: string;
        /**
         * Version of the `Policy`. Default version is 0;
         */
        version?: number;
    }


/**
     * Ignores policies set above this resource and restores the `constraint_default` enforcement behavior of the specific `Constraint` at this resource.  Suppose that `constraint_default` is set to `ALLOW` for the `Constraint` `constraints/serviceuser.services`. Suppose that organization foo.com sets a `Policy` at their Organization resource node that restricts the allowed service activations to deny all service activations. They could then set a `Policy` with the `policy_type` `restore_default` on several experimental projects, restoring the `constraint_default` enforcement of the `Constraint` for only those projects, allowing those projects to have all services activated.
     */
interface Schema$GoogleCloudOrgpolicyV1RestoreDefault {
    }


/**
     * This resource represents a long-running operation that is the result of a network API call.
     */
interface Schema$Operation {
        /**
         * If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.
         */
        done?: boolean;
        /**
         * The error result of the operation in case of failure or cancellation.
         */
        error?: Schema$Status;
        /**
         * Service-specific metadata associated with the operation.  It typically contains progress information and common metadata such as create time. Some services might not provide such metadata.  Any method that returns a long-running operation should document the metadata type, if any.
         */
        metadata?: {
            [key: string]: any;
        };
        /**
         * The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
         */
        name?: string;
        /**
         * The normal response of the operation in case of success.  If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`.  If the original method is standard `Get`/`Create`/`Update`, the response should be the resource.  For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name.  For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
         */
        response?: {
            [key: string]: any;
        };
    }


/**
     * Output configuration for export assets destination.
     */
interface Schema$OutputConfig {
        /**
         * Destination on Cloud Storage.
         */
        gcsDestination?: Schema$GcsDestination;
    }


/**
     * Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources.   A `Policy` consists of a list of `bindings`. A `binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM.  **JSON Example**      {       "bindings": [         {           "role": "roles/owner",           "members": [             "user:mike@example.com",             "group:admins@example.com",             "domain:google.com",             "serviceAccount:my-other-app@appspot.gserviceaccount.com"           ]         },         {           "role": "roles/viewer",           "members": ["user:sean@example.com"]         }       ]     }  **YAML Example**      bindings:     - members:       - user:mike@example.com       - group:admins@example.com       - domain:google.com       - serviceAccount:my-other-app@appspot.gserviceaccount.com       role: roles/owner     - members:       - user:sean@example.com       role: roles/viewer   For a description of IAM and its features, see the [IAM developer's guide](https://cloud.google.com/iam/docs).
     */
interface Schema$Policy {
        /**
         * Specifies cloud audit logging configuration for this policy.
         */
        auditConfigs?: Schema$AuditConfig[];
        /**
         * Associates a list of `members` to a `role`. `bindings` with no members will result in an error.
         */
        bindings?: Schema$Binding[];
        /**
         * `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy from overwriting each other. It is strongly suggested that systems make use of the `etag` in the read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned in the response to `getIamPolicy`, and systems are expected to put that etag in the request to `setIamPolicy` to ensure that their change will be applied to the same version of the policy.  If no `etag` is provided in the call to `setIamPolicy`, then the existing policy is overwritten blindly.
         */
        etag?: string;
        /**
         * Deprecated.
         */
        version?: number;
    }


/**
     * Representation of a cloud resource.
     */
interface Schema$Resource {
        /**
         * The content of the resource, in which some sensitive fields are scrubbed away and may not be present.
         */
        data?: {
            [key: string]: any;
        };
        /**
         * The URL of the discovery document containing the resource's JSON schema. For example: `"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"`. It will be left unspecified for resources without a discovery-based API, such as Cloud Bigtable.
         */
        discoveryDocumentUri?: string;
        /**
         * The JSON schema name listed in the discovery document. Example: "Project". It will be left unspecified for resources (such as Cloud Bigtable) without a discovery-based API.
         */
        discoveryName?: string;
        /**
         * The full name of the immediate parent of this resource. See [Resource Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) for more information.  For GCP assets, it is the parent resource defined in the [Cloud IAM policy hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). For example: `"//cloudresourcemanager.googleapis.com/projects/my_project_123"`.  For third-party assets, it is up to the users to define.
         */
        parent?: string;
        /**
         * The REST URL for accessing the resource. An HTTP GET operation using this URL returns the resource itself. Example: `https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123`. It will be left unspecified for resources without a REST API.
         */
        resourceUrl?: string;
        /**
         * The API version. Example: "v1".
         */
        version?: string;
    }


/**
     * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details.  You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
     */
interface Schema$Status {
        /**
         * The status code, which should be an enum value of google.rpc.Code.
         */
        code?: number;
        /**
         * A list of messages that carry the error details.  There is a common set of message types for APIs to use.
         */
        details?: Array<{
            [key: string]: any;
        }>;
        /**
         * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
         */
        message?: string;
    }


/**
     * Temporal asset. In addition to the asset, the temporal asset includes the status of the asset and valid from and to time of it.
     */
interface Schema$TemporalAsset {
        /**
         * Asset.
         */
        asset?: Schema$Asset;
        /**
         * If the asset is deleted or not.
         */
        deleted?: boolean;
        /**
         * The time window when the asset data and state was observed.
         */
        window?: Schema$TimeWindow;
    }


/**
     * A time window of (start_time, end_time].
     */
interface Schema$TimeWindow {
        /**
         * End time of the time window (inclusive). Current timestamp if not specified.
         */
        endTime?: string;
        /**
         * Start time of the time window (exclusive).
         */
        startTime?: string;
    }


interface Params$Resource$Operations$Get extends StandardParameters {
        /**
         * Auth client or API Key for the request
         */
        auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
        /**
         * The name of the operation resource.
         */
        name?: string;
    }


interface Params$Resource$V1$Batchgetassetshistory extends StandardParameters {
        /**
         * Auth client or API Key for the request
         */
        auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
        /**
         * A list of the full names of the assets. For example: `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. See [Resource Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) and [Resource Name Format](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format) for more info.  The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request.
         */
        assetNames?: string[];
        /**
         * Required. The content type.
         */
        contentType?: string;
        /**
         * Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345").
         */
        parent?: string;
        /**
         * End time of the time window (inclusive). Current timestamp if not specified.
         */
        'readTimeWindow.endTime'?: string;
        /**
         * Start time of the time window (exclusive).
         */
        'readTimeWindow.startTime'?: string;
    }


interface Params$Resource$V1$Exportassets extends StandardParameters {
        /**
         * Auth client or API Key for the request
         */
        auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
        /**
         * Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123").
         */
        parent?: string;
        /**
         * Request body metadata
         */
        requestBody?: Schema$ExportAssetsRequest;
    }


/**
         * cloudasset.operations.get
         * @desc Gets the latest state of a long-running operation.  Clients can use this method to poll the operation result at intervals as recommended by the API service.
         * @alias cloudasset.operations.get
         * @memberOf! ()
         *
         * @param {object} params Parameters for request
         * @param {string} params.name The name of the operation resource.
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
get(params?: Params$Resource$Operations$Get, options?: MethodOptions): GaxiosPromise<Schema$Operation>;


get(params: Params$Resource$Operations$Get, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation>): void;


get(params: Params$Resource$Operations$Get, callback: BodyResponseCallback<Schema$Operation>): void;


/**
         * cloudasset.batchGetAssetsHistory
         * @desc Batch gets the update history of assets that overlap a time window. For RESOURCE content, this API outputs history with asset in both non-delete or deleted status. For IAM_POLICY content, this API outputs history when the asset and its attached IAM POLICY both exist. This can create gaps in the output history. If a specified asset does not exist, this API returns an INVALID_ARGUMENT error.
         * @alias cloudasset.batchGetAssetsHistory
         * @memberOf! ()
         *
         * @param {object} params Parameters for request
         * @param {string=} params.assetNames A list of the full names of the assets. For example: `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`. See [Resource Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) and [Resource Name Format](https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/resource-name-format) for more info.  The request becomes a no-op if the asset name list is empty, and the max size of the asset name list is 100 in one request.
         * @param {string=} params.contentType Required. The content type.
         * @param {string} params.parent Required. The relative name of the root asset. It can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id")", or a project number (such as "projects/12345").
         * @param {string=} params.readTimeWindow.endTime End time of the time window (inclusive). Current timestamp if not specified.
         * @param {string=} params.readTimeWindow.startTime Start time of the time window (exclusive).
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
batchGetAssetsHistory(params?: Params$Resource$V1$Batchgetassetshistory, options?: MethodOptions): GaxiosPromise<Schema$BatchGetAssetsHistoryResponse>;


batchGetAssetsHistory(params: Params$Resource$V1$Batchgetassetshistory, options: MethodOptions | BodyResponseCallback<Schema$BatchGetAssetsHistoryResponse>, callback: BodyResponseCallback<Schema$BatchGetAssetsHistoryResponse>): void;


batchGetAssetsHistory(params: Params$Resource$V1$Batchgetassetshistory, callback: BodyResponseCallback<Schema$BatchGetAssetsHistoryResponse>): void;


batchGetAssetsHistory(callback: BodyResponseCallback<Schema$BatchGetAssetsHistoryResponse>): void;


/**
         * cloudasset.exportAssets
         * @desc Exports assets with time and resource types to a given Cloud Storage location. The output format is newline-delimited JSON. This API implements the google.longrunning.Operation API allowing you to keep track of the export.
         * @alias cloudasset.exportAssets
         * @memberOf! ()
         *
         * @param {object} params Parameters for request
         * @param {string} params.parent Required. The relative name of the root asset. This can only be an organization number (such as "organizations/123"), a project ID (such as "projects/my-project-id"), or a project number (such as "projects/12345"), or a folder number (such as "folders/123").
         * @param {().ExportAssetsRequest} params.resource Request body data
         * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
         * @param {callback} callback The callback that handles the response.
         * @return {object} Request object
         */
exportAssets(params?: Params$Resource$V1$Exportassets, options?: MethodOptions): GaxiosPromise<Schema$Operation>;


exportAssets(params: Params$Resource$V1$Exportassets, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation>): void;


exportAssets(params: Params$Resource$V1$Exportassets, callback: BodyResponseCallback<Schema$Operation>): void;


exportAssets(callback: BodyResponseCallback<Schema$Operation>): void;


({ classes }) => (
    <svg xmlns="http://www.w3.org/2000/svg"


(path) => {
  try {
    const requireFunc =
      // @ts-ignore
      typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;

    return requireFunc(path);
  } catch (e) {
    return {};
  }
}


(token) => {
      if (token.value !== undefined) {
        appValue[token.key] = token.value;
      }
    }


({ key, validator = noop, optional, dehydrate }) => {
      const value = envParameters[key];

      if (typeof value === 'undefined' && !optional) {
        throw new Error(
          `Env parameter ${key} not found. You need add a this env parameter. If you have questions read the docs`
        );
      }

      // Not calling validation on empty values.
      const validation = typeof value !== 'undefined' && validator(value);
      if (typeof validation === 'string') {
        throw new Error(
          `Env parameter ${key} with value ${value} not valid, message: ${validation}`
        );
      }

      result[key] = value;

      if (dehydrate !== false) {
        this.clientUsedList[key] = value;
      }
    }


export class EnvironmentManagerServer extends EnvironmentManager {
  private clientUsedList: Record<string, string> = {};

  constructor(private tokens: EnvParameter[]) {
    super();
    this.processing();
  }

  clientUsed() {
    return this.clientUsedList;
  }

  updateClientUsed(result) {
    this.clientUsedList = Object.assign(this.clientUsedList, result);
  }

  // eslint-disable-next-line class-methods-use-this
  private getEnvInFiles() {
    if (
      process.env.NODE_ENV === 'production' &&
      process.env.DANGEROUS_UNSAFE_ENV_FILES !== 'true'
    ) {
      return {};
    }

    const path = require('path');
    return {
      ...readFileWithEnv(path.resolve(process.cwd(), 'server', `env.js`)), // env.js убрать в будующем, как переедет платформа
      ...readFileWithEnv(path.resolve(process.cwd(), `env.development.js`)),
      ...readFileWithEnv(path.resolve(process.cwd(), `env.js`)),
    };
  }

  private getEnvInApp() {
    const appValue = {};
    this.tokens.forEach((token) => {
      if (token.value !== undefined) {
        appValue[token.key] = token.value;
      }
    });
    return appValue;
  }

  private collectionEnv() {
    return { ...this.getEnvInApp(), ...this.getEnvInFiles(), ...process.env };
  }

  private processing() {
    const result = {};
    const envParameters = this.collectionEnv();

    this.tokens.forEach(({ key, validator = noop, optional, dehydrate }) => {
      const value = envParameters[key];

      if (typeof value === 'undefined' && !optional) {
        throw new Error(
          `Env parameter ${key} not found. You need add a this env parameter. If you have questions read the docs`
        );
      }

      // Not calling validation on empty values.
      const validation = typeof value !== 'undefined' && validator(value);
      if (typeof validation === 'string') {
        throw new Error(
          `Env parameter ${key} with value ${value} not valid, message: ${validation}`
        );
      }

      result[key] = value;

      if (dehydrate !== false) {
        this.clientUsedList[key] = value;
      }
    });

    process.env = envParameters; // Записываем в process.env итоговый результат. TODO убрать позже

    this.update(result);
  }
}


clientUsed() {
    return this.clientUsedList;
  }


updateClientUsed(result) {
    this.clientUsedList = Object.assign(this.clientUsedList, result);
  }


// eslint-disable-next-line class-methods-use-this
private getEnvInFiles() {
    if (
      process.env.NODE_ENV === 'production' &&
      process.env.DANGEROUS_UNSAFE_ENV_FILES !== 'true'
    ) {
      return {};
    }

    const path = require('path');
    return {
      ...readFileWithEnv(path.resolve(process.cwd(), 'server', `env.js`)), // env.js убрать в будующем, как переедет платформа
      ...readFileWithEnv(path.resolve(process.cwd(), `env.development.js`)),
      ...readFileWithEnv(path.resolve(process.cwd(), `env.js`)),
    };
  }


private getEnvInApp() {
    const appValue = {};
    this.tokens.forEach((token) => {
      if (token.value !== undefined) {
        appValue[token.key] = token.value;
      }
    });
    return appValue;
  }


private collectionEnv() {
    return { ...this.getEnvInApp(), ...this.getEnvInFiles(), ...process.env };
  }


private processing() {
    const result = {};
    const envParameters = this.collectionEnv();

    this.tokens.forEach(({ key, validator = noop, optional, dehydrate }) => {
      const value = envParameters[key];

      if (typeof value === 'undefined' && !optional) {
        throw new Error(
          `Env parameter ${key} not found. You need add a this env parameter. If you have questions read the docs`
        );
      }

      // Not calling validation on empty values.
      const validation = typeof value !== 'undefined' && validator(value);
      if (typeof validation === 'string') {
        throw new Error(
          `Env parameter ${key} with value ${value} not valid, message: ${validation}`
        );
      }

      result[key] = value;

      if (dehydrate !== false) {
        this.clientUsedList[key] = value;
      }
    });

    process.env = envParameters; // Записываем в process.env итоговый результат. TODO убрать позже

    this.update(result);
  }


(props, ref) => {
    const { children, As = 'div', ...rest } = props;

    return (
        <As {...rest} ref={ref} {


export interface Props extends React.HTMLAttributes<HTMLElement> {
    /** Node(s) to be rendered inside the container */
    children: NotEmptyReactNode;
    /** HTML tag to be used to render the container */
    As?: string;
    /** Ref to access the main wrapper element */
    ref?: React.RefObject<HTMLElement>;
}


(resolve, reject) => {
                this.Model.find((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    const result = res.map((r) => this._readMapper(r));
                    resolve(result);
                });
            }


(err, res) => {
                    if (err) {
                        reject(err);
                    }
                    const result = res.map((r) => this._readMapper(r));
                    resolve(result);
                }


(r) => this._readMapper(r)


(resolve, reject) => {
                this.Model.findById(id, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    if (res === null) {
                        reject();
                    } else {
                        const result = this._readMapper(res);
                        resolve(result);
                    }
                });
            }


(err, res) => {
                    if (err) {
                        reject(err);
                    }
                    if (res === null) {
                        reject();
                    } else {
                        const result = this._readMapper(res);
                        resolve(result);
                    }
                }


(resolve, reject) => {
                const instance = new this.Model(doc);
                instance.save((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(this._readMapper(res));
                });
            }


(err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(this._readMapper(res));
                }


(resolve, reject) => {
                const query = { _id: { $in : ids } };
                this.Model.find(query, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            }


(err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                }


(resolve, reject) => {
                this.Model.find(query as any, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            }


@injectable()
export class GenericMongoDBRepository<TEntity, TModel extends Document>
    implements IRepository<TEntity> {

        private _name: string;
        protected Model: Model<TModel>;

        public constructor (
            @dbClient dbClient: DbClient,
            @unmanaged() name: string,
            @unmanaged() schemaDefinition: SchemaDefinition
        ) {
            this._name = name;
            const schema = new Schema(schemaDefinition, { collection: this._name });
            this.Model = dbClient.model<TModel>(this._name, schema);
        }

        // We wrap the mongoose API here so we can use async / await

        public async findAll() {
            return new Promise<TEntity[]>((resolve, reject) => {
                this.Model.find((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    const result = res.map((r) => this._readMapper(r));
                    resolve(result);
                });
            });
        }

        public async findById(id: string) {
            return new Promise<TEntity>((resolve, reject) => {
                this.Model.findById(id, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    if (res === null) {
                        reject();
                    } else {
                        const result = this._readMapper(res);
                        resolve(result);
                    }
                });
            });
        }

        public async save(doc: TEntity) {
            return new Promise<TEntity>((resolve, reject) => {
                const instance = new this.Model(doc);
                instance.save((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(this._readMapper(res));
                });
            });
        }

        public findManyById(ids: string[]) {
            return new Promise<TEntity[]>((resolve, reject) => {
                const query = { _id: { $in : ids } };
                this.Model.find(query, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            });
        }

        public findManyByQuery(
            query: Query<TEntity>,
        ) {
            return new Promise<TEntity[]>((resolve, reject) => {
                this.Model.find(query as any, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            });
        }

        private _readMapper(model: TModel) {
            const obj: any = model.toJSON();
            //Object.defineProperty(obj, "id", Object.getOwnPropertyDescriptor(obj, "_id"));
            delete obj["_id"];
            return obj as TEntity;
        }

}


// We wrap the mongoose API here so we can use async / await
public async findAll() {
            return new Promise<TEntity[]>((resolve, reject) => {
                this.Model.find((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    const result = res.map((r) => this._readMapper(r));
                    resolve(result);
                });
            });
        }


public async findById(id: string) {
            return new Promise<TEntity>((resolve, reject) => {
                this.Model.findById(id, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    if (res === null) {
                        reject();
                    } else {
                        const result = this._readMapper(res);
                        resolve(result);
                    }
                });
            });
        }


public async save(doc: TEntity) {
            return new Promise<TEntity>((resolve, reject) => {
                const instance = new this.Model(doc);
                instance.save((err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(this._readMapper(res));
                });
            });
        }


public findManyById(ids: string[]) {
            return new Promise<TEntity[]>((resolve, reject) => {
                const query = { _id: { $in : ids } };
                this.Model.find(query, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            });
        }


public findManyByQuery(
            query: Query<TEntity>,
        ) {
            return new Promise<TEntity[]>((resolve, reject) => {
                this.Model.find(query as any, (err, res) => {
                    if (err) {
                        reject(err);
                    }
                    resolve(res.map((r) => this._readMapper(r)));
                });
            });
        }


private _readMapper(model: TModel) {
            const obj: any = model.toJSON();
            //Object.defineProperty(obj, "id", Object.getOwnPropertyDescriptor(obj, "_id"));
            delete obj["_id"];
            return obj as TEntity;
        }


@Component({
  selector: 'app-dynamic-modules',
  templateUrl: './dynamic-modules.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DynamicModulesComponent extends BasePageComponent {}


/**
 * Returns rounded number to fix floating point bug http://floating-point-gui.de
 * @param {number} number The unrounded number
 * @returns {number} Rounded number
 */
export default function _default(number: number): number;


/**
 * @internal
 */
export class SVGRoot extends React.Component<SVGRootProperties, {}> {
    render() {
        const { children, frame } = this.props
        const { width, height } = frame

        const fx = Math.floor(frame.x)
        const fy = Math.floor(frame.y)

        const svgStyle: React.CSSProperties = {
            position: "absolute",
            width,
            height,
            overflow: "visible",
            display: "block",
            transform: `translate(${fx}px, ${fy}px)`,
        }

        Layer.applyWillChange(this, svgStyle)

        return (
            <svg
                width="100%"
                height="100%"
                xmlns="http://www.w3.org/2000/svg"
                xmlnsXlink="http://www.w3.org/1999/xlink"
                style={svgStyle}
            >
                {children}
            </svg>
        )
    }
}


/**
 * @internal
 */
export interface SVGRootProperties {
    frame: Rect
    width: number
    height: number
    willChangeTransform?: boolean
}


render() {
        const { children, frame } = this.props
        const { width, height } = frame

        const fx = Math.floor(frame.x)
        const fy = Math.floor(frame.y)

        const svgStyle: React.CSSProperties = {
            position: "absolute",
            width,
            height,
            overflow: "visible",
            display: "block",
            transform: `translate(${fx}px, ${fy}px)`,
        }

        Layer.applyWillChange(this, svgStyle)

        return (
            <svg
                width="100%"
                height="100%"
                xmlns="http://www.w3.org/2000/svg"
                xmlnsXlink="http://www.w3.org/1999/xlink"
                style={svgStyle}
            >
                {children}
            </svg>
        )
    }


@NgModule({
  declarations: [UrlDatasetModalComponent],
  imports: [CommonModule, CdCommonModule],
})
export class UrlDatasetModalModule {}


interface IvalidatorTypes {
  REQUIRED: 'required';
  MIN_LENGTH: 'min-length';
  MAX_LENGTH: 'max-length';
  EXACT_LENGTH: 'exact-length';
  MIN_ITEMS: 'min-items';
  MIN_NUMBER_VALUE: 'min-number-value';
  MAX_NUMBER_VALUE: 'max-number-value';
  PATTERN: 'pattern';
  URL: 'url';
}


(err: Error) => {
      if (err) {
        return cb(err, 'Bad file system permissions');
      }

      this.run(`git ls-remote ${this.settings.location}`, (err) => {
        if (err) {
          console.log(err);
          return cb(err, 'Repository not found');
        }

        return cb();
      });
    }


(err) => {
        if (err) {
          console.log(err);
          return cb(err, 'Repository not found');
        }

        return cb();
      }


(err?: Error) => {
      rimraf(this.dataFolder, (_) => {
        return cb(err, 'Unable to fetch git repository');
      });
    }


(_) => {
        return cb(err, 'Unable to fetch git repository');
      }


(err) => {
      if (err) {
        err.message = `Unable to init local git repository: ${err.message}`;
        return callback(err);
      }

      this.run(`git remote add dotsync ${this.settings.location}`, (err) => {
        if (err) {
          err.message = `Unable to add git remote: ${err.message}`;
          return callback(err);
        }

        this.run('git fetch dotsync', (err) => {
          if (err) {
            err.message = `Unable to fetch git repository: ${err.message}`;
            return callback(err);
          }

          return cb();
        });
      });
    }


(err) => {
        if (err) {
          err.message = `Unable to add git remote: ${err.message}`;
          return callback(err);
        }

        this.run('git fetch dotsync', (err) => {
          if (err) {
            err.message = `Unable to fetch git repository: ${err.message}`;
            return callback(err);
          }

          return cb();
        });
      }


(err) => {
          if (err) {
            err.message = `Unable to fetch git repository: ${err.message}`;
            return callback(err);
          }

          return cb();
        }


(err) => {
      if (err) {
        err.message = `Unable to fetch git repository: ${err.message}`;
        return cb(err);
      }

      this.run(`git log --format='%H' -n 1 dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git log': ${err.message}`;
          return cb(err);
        }

        cb(null, stdout.trim());
      });
    }


(err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git log': ${err.message}`;
          return cb(err);
        }

        cb(null, stdout.trim());
      }


(err, stdout) => {
      if (err) {
        err.message = `Unable to run 'git status': ${err.message}`;
        return cb(err);
      }

      if (stdout !== '') {
        return cb(new Error('Your local copy is dirty. Please save those changes somewhere else first.'));
      }

      this.run(`git reset --hard dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git reset': ${err.message}`;
          return cb(err);
        }

        if (stdout.match(/^HEAD is now at /) === null) {
          return cb(new Error(`Unable to download the data. Failed 'git reset --hard'.`));
        }

        this.run(`git submodule update --init --recursive`, (err) => {
          if (err) {
            err.message = `Unable to update git submodules: ${err.message}`;
            return cb(err);
          }

          return cb();
        });
      });
    }


(err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git reset': ${err.message}`;
          return cb(err);
        }

        if (stdout.match(/^HEAD is now at /) === null) {
          return cb(new Error(`Unable to download the data. Failed 'git reset --hard'.`));
        }

        this.run(`git submodule update --init --recursive`, (err) => {
          if (err) {
            err.message = `Unable to update git submodules: ${err.message}`;
            return cb(err);
          }

          return cb();
        });
      }


(err) => {
          if (err) {
            err.message = `Unable to update git submodules: ${err.message}`;
            return cb(err);
          }

          return cb();
        }


(err) => {
      if (err) {
        err.message = `Unable to push to git remote: ${err.message}`;
        return cb(err);
      }

      return cb();
    }


export default class Git extends utils.Storage {
  dataFolder: string

  constructor(opts: utils.StorageOptions) {
    super('Git', 'Use git repository to store your dotfiles', 'URL to git repository', opts);

    this.dataFolder = path.join(this.configdir, 'data');
  }

  run(cmd: string, cb: (err: Error, stdout?: string, stderr?: string) => void) {
    return exec(cmd, { cwd: this.dataFolder, encoding: 'utf8' }, cb);
  }

  datadir() {
    return this.dataFolder;
  }

  validate(cb: (err?: Error, m?: string) => void) {

    mkdirp(this.dataFolder, (err: Error) => {
      if (err) {
        return cb(err, 'Bad file system permissions');
      }

      this.run(`git ls-remote ${this.settings.location}`, (err) => {
        if (err) {
          console.log(err);
          return cb(err, 'Repository not found');
        }

        return cb();
      });
    });
  }

  init(cb: (err?: Error, m?: string) => void) {
    const callback = (err?: Error) => {
      rimraf(this.dataFolder, (_) => {
        return cb(err, 'Unable to fetch git repository');
      });
    };

    this.run('git init', (err) => {
      if (err) {
        err.message = `Unable to init local git repository: ${err.message}`;
        return callback(err);
      }

      this.run(`git remote add dotsync ${this.settings.location}`, (err) => {
        if (err) {
          err.message = `Unable to add git remote: ${err.message}`;
          return callback(err);
        }

        this.run('git fetch dotsync', (err) => {
          if (err) {
            err.message = `Unable to fetch git repository: ${err.message}`;
            return callback(err);
          }

          return cb();
        });
      });
    });
  }

  latestVersion(cb: (err: Error | null, version?: string) => void) {
    this.run(`git fetch dotsync`, (err) => {
      if (err) {
        err.message = `Unable to fetch git repository: ${err.message}`;
        return cb(err);
      }

      this.run(`git log --format='%H' -n 1 dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git log': ${err.message}`;
          return cb(err);
        }

        cb(null, stdout.trim());
      });
    });
  }

  beforeRestore(cb: utils.Callback) {
    this.run(`git status --porcelain`, (err, stdout) => {
      if (err) {
        err.message = `Unable to run 'git status': ${err.message}`;
        return cb(err);
      }

      if (stdout !== '') {
        return cb(new Error('Your local copy is dirty. Please save those changes somewhere else first.'));
      }

      this.run(`git reset --hard dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git reset': ${err.message}`;
          return cb(err);
        }

        if (stdout.match(/^HEAD is now at /) === null) {
          return cb(new Error(`Unable to download the data. Failed 'git reset --hard'.`));
        }

        this.run(`git submodule update --init --recursive`, (err) => {
          if (err) {
            err.message = `Unable to update git submodules: ${err.message}`;
            return cb(err);
          }

          return cb();
        });
      });
    });
  }

  // TODO: What if a previous `afterBackup` failed from device "A", and a
  // backup from another device "B" succeeded, then restoring the succeeded
  // backup on "A" would erase the stuff that was added there.
  afterBackup(cb: utils.Callback) {
    this.run(`git push dotsync master`, (err) => {
      if (err) {
        err.message = `Unable to push to git remote: ${err.message}`;
        return cb(err);
      }

      return cb();
    });
  }
}


run(cmd: string, cb: (err: Error, stdout?: string, stderr?: string) => void) {
    return exec(cmd, { cwd: this.dataFolder, encoding: 'utf8' }, cb);
  }


datadir() {
    return this.dataFolder;
  }


validate(cb: (err?: Error, m?: string) => void) {

    mkdirp(this.dataFolder, (err: Error) => {
      if (err) {
        return cb(err, 'Bad file system permissions');
      }

      this.run(`git ls-remote ${this.settings.location}`, (err) => {
        if (err) {
          console.log(err);
          return cb(err, 'Repository not found');
        }

        return cb();
      });
    });
  }


init(cb: (err?: Error, m?: string) => void) {
    const callback = (err?: Error) => {
      rimraf(this.dataFolder, (_) => {
        return cb(err, 'Unable to fetch git repository');
      });
    };

    this.run('git init', (err) => {
      if (err) {
        err.message = `Unable to init local git repository: ${err.message}`;
        return callback(err);
      }

      this.run(`git remote add dotsync ${this.settings.location}`, (err) => {
        if (err) {
          err.message = `Unable to add git remote: ${err.message}`;
          return callback(err);
        }

        this.run('git fetch dotsync', (err) => {
          if (err) {
            err.message = `Unable to fetch git repository: ${err.message}`;
            return callback(err);
          }

          return cb();
        });
      });
    });
  }


latestVersion(cb: (err: Error | null, version?: string) => void) {
    this.run(`git fetch dotsync`, (err) => {
      if (err) {
        err.message = `Unable to fetch git repository: ${err.message}`;
        return cb(err);
      }

      this.run(`git log --format='%H' -n 1 dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git log': ${err.message}`;
          return cb(err);
        }

        cb(null, stdout.trim());
      });
    });
  }


beforeRestore(cb: utils.Callback) {
    this.run(`git status --porcelain`, (err, stdout) => {
      if (err) {
        err.message = `Unable to run 'git status': ${err.message}`;
        return cb(err);
      }

      if (stdout !== '') {
        return cb(new Error('Your local copy is dirty. Please save those changes somewhere else first.'));
      }

      this.run(`git reset --hard dotsync/master`, (err, stdout) => {
        if (err) {
          err.message = `Unable to run 'git reset': ${err.message}`;
          return cb(err);
        }

        if (stdout.match(/^HEAD is now at /) === null) {
          return cb(new Error(`Unable to download the data. Failed 'git reset --hard'.`));
        }

        this.run(`git submodule update --init --recursive`, (err) => {
          if (err) {
            err.message = `Unable to update git submodules: ${err.message}`;
            return cb(err);
          }

          return cb();
        });
      });
    });
  }


// TODO: What if a previous `afterBackup` failed from device "A", and a
// backup from another device "B" succeeded, then restoring the succeeded
// backup on "A" would erase the stuff that was added there.
afterBackup(cb: utils.Callback) {
    this.run(`git push dotsync master`, (err) => {
      if (err) {
        err.message = `Unable to push to git remote: ${err.message}`;
        return cb(err);
      }

      return cb();
    });
  }


/* tslint:disable */
/* eslint-disable */
/**
 * Midgard API Docs
 * This is the docs for midgard api for argonaut
 *
 * The version of the OpenAPI document: 0.4.0
 * Contact: support@swagger.io
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */
/**
 *
 * @export
 * @interface V1HostPathVolumeSource
 */
export interface V1HostPathVolumeSource {
    /**
     * Path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath
     * @type {string}
     * @memberof V1HostPathVolumeSource
     */
    path?: string;
    /**
     * Type for HostPath Volume Defaults to \"\" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath +optional
     * @type {string}
     * @memberof V1HostPathVolumeSource
     */
    type?: string;
}


@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  /**
   * Http exception filters
   * @param exception
   * @param host
   */
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        message: exception.message,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}


/**
   * Http exception filters
   * @param exception
   * @param host
   */
catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        message: exception.message,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }


export function toast(message : string, duration = 2000) {
  const toast = document.createElement('ion-toast');
  toast.message = message;
  toast.duration = 2000;

  document.body.appendChild(toast);
  return toast.present();
}


({ name }) => name === "Contract-Src"


({ name }) => name.toLowerCase() === "init-state-tx"


({ name }) => name.toLowerCase() === "init-state"


(tag) => {
      transaction.addTag(
        tag.get("name", { decode: true, string: true }),
        tag.get("value", { decode: true, string: true })
      );
    }


(tag) => ({
      name: tag.get("name", { decode: true, string: true }),
      value: tag.get("value", { decode: true, string: true })
    })


type PSTContractsType = [string, string, string, string];


/**
   * Copy a contract from Arweave to the ArLocal server
   *
   * @param contractID Arweave contract ID
   * @param useLatestState Wether to use the default state of the contract or start with the current state
   * @param stateModifier A callback to use to modify the contract's state before initializing it
   *
   * @returns New contract ID
   */
async copyContract(
    contractID: string,
    useLatestState: boolean = false,
    stateModifier?: (state: any) => Promise<any> | any
  ): Promise<string> {
    this.validateHash(contractID);

    // get contract init transaction data
    const contractTx = await this.arweave.transactions.get(contractID);
    const contractTxTags = this.mapTags(contractTx);
    const { data: contractTxData } = await axios.get(
      `${this.gatewayURL}/${contractID}`
    );

    // get contract source data
    const contractSourceID = contractTxTags.find(
      ({ name }) => name === "Contract-Src"
    ).value;
    const contractSourceTx = await this.arweave.transactions.get(
      contractSourceID
    );
    const contractSourceTags = this.mapTags(contractSourceTx);
    const { data: contractSourceData } = await axios.get(
      `${this.gatewayURL}/${contractSourceID}`
    );

    // latest state
    let state: any = contractTxData;
    const initStateTxID = contractTxTags.find(
      ({ name }) => name.toLowerCase() === "init-state-tx"
    )?.value;

    if (useLatestState) {
      // calculate latest state
      const smartweave = SmartWeaveNodeFactory.memCached(this.arweave);
      const contract = smartweave.contract(contractID);

      state = (await contract.readState()).state;
    } else if (!useLatestState && !!initStateTxID) {
      // handle if the initial state is stored in a different tx
      state = (await axios.get(`${this.gatewayURL}/${initStateTxID}`)).data;
    }

    // run state modifier
    if (!!stateModifier) state = await stateModifier(state);

    // copy the transactions
    const newContractTx = await this.arlocal.createTransaction(
      {
        data:
          (typeof contractTxData === "string" && contractTxData) ||
          JSON.stringify(contractTxData)
      },
      this.wallet
    );
    const newContractSourceTx = await this.arlocal.createTransaction(
      {
        data: contractSourceData
      },
      this.wallet
    );

    for (const tag of contractSourceTags) {
      newContractSourceTx.addTag(tag.name, tag.value);
    }

    await this.arlocal.transactions.sign(newContractSourceTx, this.wallet);

    const uploader2 = await this.arlocal.transactions.getUploader(
      newContractSourceTx
    );

    while (!uploader2.isComplete) {
      await uploader2.uploadChunk();
    }

    const stateInTags = !!contractTxTags.find(
      ({ name }) => name.toLowerCase() === "init-state"
    );
    let setSrc = false;

    for (const tag of contractTxTags) {
      // overwrite init-state with the latest state, if the tag exits
      if (tag.name.toLowerCase() === "init-state" && state && useLatestState) {
        newContractTx.addTag(tag.name, JSON.stringify(state));
        continue;
      }

      // if the contract uses a tx to initialize it's state, overwrite that
      if (tag.name.toLowerCase() === "init-state-tx") {
        if (!stateInTags)
          newContractTx.addTag("Init-State", JSON.stringify(state));

        continue;
      }

      if (tag.name.toLowerCase() === "contract-src") {
        newContractTx.addTag(tag.name, newContractSourceTx.id);
        setSrc = true;
        continue;
      }

      newContractTx.addTag(tag.name, tag.value);
    }

    if (!setSrc) newContractTx.addTag("Contract-Src", newContractSourceTx.id);

    await this.arlocal.transactions.sign(newContractTx, this.wallet);

    const uploader1 = await this.arlocal.transactions.getUploader(
      newContractTx
    );

    while (!uploader1.isComplete) {
      await uploader1.uploadChunk();
    }

    // mine txs
    await this.mine();

    return newContractTx.id;
  }


/**
   * Copy a transaction from Arweave (with tags and data) to the ArLocal server
   *
   * @param txID ID of the transaction to copy
   * @returns New transaction ID
   */
async copyTransaction(txID: string): Promise<string> {
    this.validateHash(txID);

    let data = "SAMPLE_DATA";
    const oldTx = await this.arweave.transactions.get(txID);

    try {
      data = (await axios.get(`${this.gatewayURL}/${txID}`, { timeout: 10000 }))
        .data;
    } catch {}

    const transaction = await this.arlocal.createTransaction(
      {
        data
      },
      this.wallet
    );

    // @ts-ignore
    oldTx.get("tags").forEach((tag) => {
      transaction.addTag(
        tag.get("name", { decode: true, string: true }),
        tag.get("value", { decode: true, string: true })
      );
    });

    await this.arlocal.transactions.sign(transaction, this.wallet);

    const uploader = await this.arlocal.transactions.getUploader(transaction);

    while (!uploader.isComplete) {
      await uploader.uploadChunk();
    }

    // mine tx
    await this.mine();

    return transaction.id;
  }


/**
   * Get example PST contracts
   *
   * @returns 4 PST contract IDs
   */
async examplePSTs(): Promise<PSTContractsType> {
    if (this.psts) return this.psts;

    return [
      await this.copyContract("usjm4PCxUd5mtaon7zc97-dt-3qf67yPyqgzLnLqk5A"),
      await this.copyContract("-8A6RexFkpfWwuyVO98wzSFZh0d6VJuI-buTJvlwOJQ"),
      await this.copyContract("f6lW-sKxsc340p8eBBL2i_fnmSI_fRSFmkqvzqyUsRs"),
      await this.copyContract("mzvUgNc8YFk0w5K5H7c8pyT-FC5Y_ba0r7_8766Kx74")
    ];
  }


private validateHash(hash: string) {
    if (!/[a-z0-9_-]{43}/i.test(hash))
      throw new Error("Invalid hash: not an Arweave format");
  }


private mapTags(tx: Transaction): { name: string; value: string }[] {
    // @ts-ignore
    return tx.get("tags").map((tag) => ({
      name: tag.get("name", { decode: true, string: true }),
      value: tag.get("value", { decode: true, string: true })
    }));
  }


private async mine() {
    await this.arlocal.api.get("mine");
  }


@NgModule({
  declarations: [
    AppComponent,
    InfoComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


(): React.ReactElement => {
    // The questions array set for a meeting.
    const [questionDetails, setQuestionDetails] = React.useState<any[]>([]);
    const [ratingsArray, setRatingsArray] = React.useState<any[]>([]);
    const [showLoader, setShowLoader] = React.useState<boolean>(false);

    // Method to start task module to add questions.
    const addQuestionsTaskModule = () => {
        let taskInfo = {
            title: "Questions",
            height: 300,
            width: 400,
            url: `${window.location.origin}/questions`,
        };

        microsoftTeams.tasks.startTask(taskInfo, (err, questionsJson) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }
            const questionsObject = JSON.parse(questionsJson);
            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet[] = questionsObject.map((question: any) => {
                    if (question.checked) {
                        // The question details to save.
                        return {
                            meetingId: context.meetingId!,
                            question: question.value,
                            setBy: context.userPrincipalName!,
                            isDelete: 0
                        };
                    }
                })

                // API call to save the question to storage.
                saveQuestions(questDetails)
                    .then((res) => {
                        loadQuestions()
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details" + ex)
                    });
            })
        });
    };

    // Method to start task module to edit a question.
    const editQuestionsTaskModule = (editText: string, rowKey: any) => {
        let taskInfo = {
            title: "Questions",
            height: 300,
            width: 400,
            url: `${window.location.origin}/edit?editText=` + editText,
        };

        microsoftTeams.tasks.startTask(taskInfo, (err, question: string) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }

            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet = {
                    MeetingId: context.meetingId!,
                    Question: question,
                    SetBy: context.userPrincipalName!,
                    IsDelete: 0,
                    QuestionId: rowKey
                };
                setShowLoader(true);
                // API call to save the question to storage.
                editQuestion(questDetails)
                    .then((res) => {
                        loadQuestions();
                        setShowLoader(false);
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details in edit" + ex);
                        setShowLoader(false);
                    });
            })
        });
    };

    // Method to load the questions in the question container.
    const loadQuestions = () => {
        microsoftTeams.getContext((context) => {
            getQuestions(context.meetingId!)
                .then((res) => {
                    console.log(res)
                    const questions = res.data as any[];
                    setQuestionDetails(questions)
                })
                .catch((ex) => {
                    console.log("Error while getting the question details" + ex)
                });
        });
    }

    const deleteQuestion = (questionDetail: any) => {
        const questionDetails: IQuestionSet = {
            MeetingId: questionDetail.MeetingId,
            Question: questionDetail.Question,
            QuestionId: questionDetail.RowKey,
            SetBy: questionDetail.SetBy,
            IsDelete: 1
        }
        setShowLoader(true);
        // API call to save the question to storage.
        deleteQuestionDetails(questionDetails)
            .then((res) => {
                loadQuestions();
                setShowLoader(false);
            })
            .catch((ex) => {
                console.log("Error while deleting question details" + ex);
                setShowLoader(false);
            });
    }

    React.useEffect((): any => {
        const prevItems = [];
        for (var i = 1; i <= 5; i++) {
            prevItems.push(
                <Button size="small" circular content={i} />
            )
        }

        // Setting ratings to show in the UI.
        setRatingsArray(prevItems);

        microsoftTeams.initialize();
        loadQuestions();
    }, [])

    return (
        <>
            <Loader hidden={!showLoader}


() => {
        let taskInfo = {
            title: "Questions",
            height: 300,
            width: 400,
            url: `${window.location.origin}/questions`,
        };

        microsoftTeams.tasks.startTask(taskInfo, (err, questionsJson) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }
            const questionsObject = JSON.parse(questionsJson);
            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet[] = questionsObject.map((question: any) => {
                    if (question.checked) {
                        // The question details to save.
                        return {
                            meetingId: context.meetingId!,
                            question: question.value,
                            setBy: context.userPrincipalName!,
                            isDelete: 0
                        };
                    }
                })

                // API call to save the question to storage.
                saveQuestions(questDetails)
                    .then((res) => {
                        loadQuestions()
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details" + ex)
                    });
            })
        });
    }


(err, questionsJson) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }
            const questionsObject = JSON.parse(questionsJson);
            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet[] = questionsObject.map((question: any) => {
                    if (question.checked) {
                        // The question details to save.
                        return {
                            meetingId: context.meetingId!,
                            question: question.value,
                            setBy: context.userPrincipalName!,
                            isDelete: 0
                        };
                    }
                })

                // API call to save the question to storage.
                saveQuestions(questDetails)
                    .then((res) => {
                        loadQuestions()
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details" + ex)
                    });
            })
        }


(context) => {
                const questDetails: IQuestionSet[] = questionsObject.map((question: any) => {
                    if (question.checked) {
                        // The question details to save.
                        return {
                            meetingId: context.meetingId!,
                            question: question.value,
                            setBy: context.userPrincipalName!,
                            isDelete: 0
                        };
                    }
                })

                // API call to save the question to storage.
                saveQuestions(questDetails)
                    .then((res) => {
                        loadQuestions()
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details" + ex)
                    });
            }


(question: any) => {
                    if (question.checked) {
                        // The question details to save.
                        return {
                            meetingId: context.meetingId!,
                            question: question.value,
                            setBy: context.userPrincipalName!,
                            isDelete: 0
                        };
                    }
                }


(res) => {
                        loadQuestions()
                    }


(ex) => {
                        console.log("Error while saving question details" + ex)
                    }


(editText: string, rowKey: any) => {
        let taskInfo = {
            title: "Questions",
            height: 300,
            width: 400,
            url: `${window.location.origin}/edit?editText=` + editText,
        };

        microsoftTeams.tasks.startTask(taskInfo, (err, question: string) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }

            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet = {
                    MeetingId: context.meetingId!,
                    Question: question,
                    SetBy: context.userPrincipalName!,
                    IsDelete: 0,
                    QuestionId: rowKey
                };
                setShowLoader(true);
                // API call to save the question to storage.
                editQuestion(questDetails)
                    .then((res) => {
                        loadQuestions();
                        setShowLoader(false);
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details in edit" + ex);
                        setShowLoader(false);
                    });
            })
        });
    }


(err, question: string) => {
            if (err) {
                console.log("Some error occurred in the task module")
                return
            }

            microsoftTeams.getContext((context) => {
                const questDetails: IQuestionSet = {
                    MeetingId: context.meetingId!,
                    Question: question,
                    SetBy: context.userPrincipalName!,
                    IsDelete: 0,
                    QuestionId: rowKey
                };
                setShowLoader(true);
                // API call to save the question to storage.
                editQuestion(questDetails)
                    .then((res) => {
                        loadQuestions();
                        setShowLoader(false);
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details in edit" + ex);
                        setShowLoader(false);
                    });
            })
        }


(context) => {
                const questDetails: IQuestionSet = {
                    MeetingId: context.meetingId!,
                    Question: question,
                    SetBy: context.userPrincipalName!,
                    IsDelete: 0,
                    QuestionId: rowKey
                };
                setShowLoader(true);
                // API call to save the question to storage.
                editQuestion(questDetails)
                    .then((res) => {
                        loadQuestions();
                        setShowLoader(false);
                    })
                    .catch((ex) => {
                        console.log("Error while saving question details in edit" + ex);
                        setShowLoader(false);
                    });
            }


(res) => {
                        loadQuestions();
                        setShowLoader(false);
                    }


(ex) => {
                        console.log("Error while saving question details in edit" + ex);
                        setShowLoader(false);
                    }


() => {
        microsoftTeams.getContext((context) => {
            getQuestions(context.meetingId!)
                .then((res) => {
                    console.log(res)
                    const questions = res.data as any[];
                    setQuestionDetails(questions)
                })
                .catch((ex) => {
                    console.log("Error while getting the question details" + ex)
                });
        });
    }


(context) => {
            getQuestions(context.meetingId!)
                .then((res) => {
                    console.log(res)
                    const questions = res.data as any[];
                    setQuestionDetails(questions)
                })
                .catch((ex) => {
                    console.log("Error while getting the question details" + ex)
                });
        }


(res) => {
                    console.log(res)
                    const questions = res.data as any[];
                    setQuestionDetails(questions)
                }


(ex) => {
                    console.log("Error while getting the question details" + ex)
                }


(questionDetail: any) => {
        const questionDetails: IQuestionSet = {
            MeetingId: questionDetail.MeetingId,
            Question: questionDetail.Question,
            QuestionId: questionDetail.RowKey,
            SetBy: questionDetail.SetBy,
            IsDelete: 1
        }
        setShowLoader(true);
        // API call to save the question to storage.
        deleteQuestionDetails(questionDetails)
            .then((res) => {
                loadQuestions();
                setShowLoader(false);
            })
            .catch((ex) => {
                console.log("Error while deleting question details" + ex);
                setShowLoader(false);
            });
    }


(res) => {
                loadQuestions();
                setShowLoader(false);
            }


(ex) => {
                console.log("Error while deleting question details" + ex);
                setShowLoader(false);
            }


(): any => {
        const prevItems = [];
        for (var i = 1; i <= 5; i++) {
            prevItems.push(
                <Button size="small" circular content={i} />
            )
        }

        // Setting ratings to show in the UI.
        setRatingsArray(prevItems);

        microsoftTeams.initialize();
        loadQuestions();
    }


() => addQuestionsTaskModule()


(questionDetail, index) => {
                        return (
                            <>
                                <Card key={index} fluid aria-roledescription="card with question details" className="questionsCard">
                                    <Card.Body>
                                        <Flex gap="gap.smaller" column>
                                            <Flex gap="gap.smaller" space="between">
                                                <Text content={questionDetail.Question} />
                                                <Tooltip
                                                    trigger={<MoreIcon />}


// Function implementations ================================
function isNative(func: string): boolean {
    return /.*\[native code\].*/g.test( Array.prototype[func].toString() );
}


function flatMap<T, U>(propertyFn: (item: T, index: number, array: T[]) => U[], thisArg?: any): U[] {
    return this.reduce(
        (flatten, item, index, array) =>
            [ ...flatten, propertyFn(item, index, array) ]
        , []
    );
}


function groupBy<T>(propertyFn: (item: T, index: number, array: T[]) => number | string): { [id: string]: T[] } {
    return this.reduce(
        (group, item, index, array) => {
            const id = '' + propertyFn(item, index, array);
            return {
                ...group,
                [id]: [ ...( group[id] || [] ), item ]
            };
        },
        {}
    );
}


function min(): number {
    if (this.length) {
        return Math.min(...this);
    }
}


function max(): number {
    if (this.length) {
        return Math.max(...this);
    }
}


function reverse<T>(): T[] {
    return nativeReverse.call(this.slice());
}


function sort<T>(compareFn?: (a: T, b: T) => number): T[] {
    return nativeSort.call(this.slice(), compareFn);
}


function sortBy<T>(propertyFn: (item: T) => any): T[] {
    return this.sort((a, b) => {
        const aProp = propertyFn(a);
        const bProp = propertyFn(b);

        if (!aProp && !bProp) {
            return 0;
        }
        if (!aProp || aProp > bProp) {
            return 1;
        }
        if (!bProp || aProp < bProp) {
            return -1;
        }

        return 0;
    });
}


function toHashMap<T>(propertyFn: (item: T, index: number) => string | number): { [id: string]: T } {
    return this.reduce(
        (hashMap, item, index) => (
            { ...hashMap, ['' + propertyFn(item, index)]: item }
        ),
        {}
    );
}


(flatten, item, index, array) =>
            [ ...flatten, propertyFn(item, index, array) ]


(group, item, index, array) => {
            const id = '' + propertyFn(item, index, array);
            return {
                ...group,
                [id]: [ ...( group[id] || [] ), item ]
            };
        }


(a, b) => {
        const aProp = propertyFn(a);
        const bProp = propertyFn(b);

        if (!aProp && !bProp) {
            return 0;
        }
        if (!aProp || aProp > bProp) {
            return 1;
        }
        if (!bProp || aProp < bProp) {
            return -1;
        }

        return 0;
    }


(hashMap, item, index) => (
            { ...hashMap, ['' + propertyFn(item, index)]: item }
        )


// https://aws.amazon.com/blogs/compute/support-for-multi-value-parameters-in-amazon-api-gateway/
// [ [ 'petType', 'dog' ], [ 'petType', 'fish' ] ]
// => { petType: [ 'dog', 'fish' ] },
export default function parseMultiValueQueryStringParameters(url: string) {
  // dummy placeholder url for the WHATWG URL constructor
  // https://github.com/nodejs/node/issues/12682
  const { searchParams } = new URL(url, BASE_URL_PLACEHOLDER)

  if (Array.from(searchParams).length === 0) {
    return null
  }

  const map = new Map()

  // eslint-disable-next-line no-restricted-syntax
  for (const [key, value] of searchParams) {
    const item = map.get(key)

    if (item) {
      item.push(value)
    } else {
      map.set(key, [value])
    }
  }

  return fromEntries(map)
}


/**
 * Protection container mapping object.
 */
export function getReplicationProtectionContainerMapping(args: GetReplicationProtectionContainerMappingArgs, opts?: pulumi.InvokeOptions): Promise<GetReplicationProtectionContainerMappingResult> {
    if (!opts) {
        opts = {}
    }

    if (!opts.version) {
        opts.version = utilities.getVersion();
    }
    return pulumi.runtime.invoke("azure-native:recoveryservices/v20210301:getReplicationProtectionContainerMapping", {
        "fabricName": args.fabricName,
        "mappingName": args.mappingName,
        "protectionContainerName": args.protectionContainerName,
        "resourceGroupName": args.resourceGroupName,
        "resourceName": args.resourceName,
    }, opts);
}


export interface GetReplicationProtectionContainerMappingArgs {
    /**
     * Fabric name.
     */
    fabricName: string;
    /**
     * Protection Container mapping name.
     */
    mappingName: string;
    /**
     * Protection container name.
     */
    protectionContainerName: string;
    /**
     * The name of the resource group where the recovery services vault is present.
     */
    resourceGroupName: string;
    /**
     * The name of the recovery services vault.
     */
    resourceName: string;
}


/**
 * Protection container mapping object.
 */
export interface GetReplicationProtectionContainerMappingResult {
    /**
     * Resource Id
     */
    readonly id: string;
    /**
     * Resource Location
     */
    readonly location?: string;
    /**
     * Resource Name
     */
    readonly name: string;
    /**
     * The custom data.
     */
    readonly properties: outputs.recoveryservices.v20210301.ProtectionContainerMappingPropertiesResponse;
    /**
     * Resource Type
     */
    readonly type: string;
}


({ color, height, width }: IconProps) => (
  <Svg width={width}


type IconProps = {
  color: string,
  height: number,
  width: number,
}


(element) => {
      return element.id === id;
    }


(company) => {
          return company["id"] ? true : false;
        }


(success) => {
          if (success) {
            this.deleteCompany(id);
          }
        }


(err) => {
          return of(false);
        }


(company) => {
        return company["id"] ? company : false;
      }


(err) => {
        return of(false);
      }


(company) => {
          return company["id"] ? company : false;
        }


(company: ModelCompany) => {
          if (company) {
            this.updateCompany(id, company);
          }
        }


(company: ModelCompany) => {
        if (company) {
          this.addCompany(company);
        }
      }


(element) => {
        return element.id === id;
      }


(data) => {
        return data ? data : [];
      }


(companies: ModelCompany[]) => {
        if (companies.length > 0) {
          this.companies$.next(companies);
        }
      }


@Injectable({
  providedIn: "root",
})
export class CompaniesService {
  // Create a BehaviourSubject Observable with type HobbyModel[] and default value []
  companies$ = new BehaviorSubject<ModelCompany[]>([]);

  constructor(private http: HttpClient, private router: Router) {}

  clear(): void {
    this.companies$.next([]);
  }

  getAll(): ModelCompany[] {
    return this.companies$.getValue();
  }

  getToken(): string {
    return localStorage.getItem("token");
  }

  get(id: number): ModelCompany {
    const currentItems: ModelCompany[] = this.getAll();
    if (currentItems.length === 0) {
      return null;
    }

    const firstIndex = currentItems.findIndex((element) => {
      return element.id === id;
    });
    return firstIndex >= 0 && currentItems[firstIndex]
      ? currentItems[firstIndex]
      : null;
  }

  delete(id: number): Observable<any> {
    return this.http
      .delete(environment["apiBaseUrl"] + "/company/" + id, {
        headers: new HttpHeaders().set(
          "Authorization",
          `Bearer ${this.getToken()}`
        ),
      })
      .pipe(
        map((company) => {
          return company["id"] ? true : false;
        }),
        tap((success) => {
          if (success) {
            this.deleteCompany(id);
          }
        }), // when success, delete the item from the local service
        catchError((err) => {
          return of(false);
        })
      );
  }

  fetchCompany(id: number): Observable<any> {
    return this.http.get(environment["apiBaseUrl"] + "/company/" + id).pipe(
      map((company) => {
        return company["id"] ? company : false;
      }),
      catchError((err) => {
        return of(false);
      })
    );
  }

  update(id: number, payload: ModelCompany): Observable<any> {
    return this.http
      .put(environment["apiBaseUrl"] + "/company/" + id, payload, {
        headers: new HttpHeaders().set(
          "Authorization",
          `Bearer ${this.getToken()}`
        ),
      })
      .pipe(
        map((company) => {
          return company["id"] ? company : false;
        }),
        tap((company: ModelCompany) => {
          if (company) {
            this.updateCompany(id, company);
          }
        }), // when success result, update the item in the local service
        catchError((err) => {
          return of(false);
        })
      );
  }

  add(payload: ModelCompany): Observable<any> {
    return this.http.post(environment["apiBaseUrl"] + "/company", payload).pipe(
      map((company) => {
        return company["id"] ? company : false;
      }),
      tap((company: ModelCompany) => {
        if (company) {
          this.addCompany(company);
        }
      }), // when success, add the item to the local service
      catchError((err) => {
        return of(false);
      })
    );
  }

  deleteCompany(id: number): boolean {
    const currentItems: ModelCompany[] = this.getAll();
    if (currentItems.length > 0) {
      const indexOne = currentItems.findIndex((element) => {
        return element.id === id;
      });
      if (indexOne >= 0) {
        currentItems.splice(indexOne, 1);
        this.companies$.next(currentItems);
        return true;
      }
    }

    return false;
  }

  addCompany(company: ModelCompany): void {
    const currentItems: ModelCompany[] = this.getAll();
    currentItems.push(company);
    this.companies$.next(currentItems);
  }

  updateCompany(id: number, company: ModelCompany): boolean {
    const currentItems: ModelCompany[] = this.getAll();
    if (currentItems.length > 0) {
      const indexOne = currentItems.findIndex((element) => {
        return element.id === id;
      });
      if (indexOne >= 0) {
        currentItems[indexOne] = company;
        this.companies$.next(currentItems);
        this.router.navigate(["/company"]);
        return true;
      }
    }

    return false;
  }

  fetch(): Observable<any> {
    this.clear();

    return this.http.get(environment["apiBaseUrl"] + "/company").pipe(
      map((data) => {
        return data ? data : [];
      }),
      tap((companies: ModelCompany[]) => {
        if (companies.length > 0) {
          this.companies$.next(companies);
        }
      }),
      catchError((err) => {
        return of(false);
      })
    );
  }
}


clear(): void {
    this.companies$.next([]);
  }


getAll(): ModelCompany[] {
    return this.companies$.getValue();
  }


getToken(): string {
    return localStorage.getItem("token");
  }


get(id: number): ModelCompany {
    const currentItems: ModelCompany[] = this.getAll();
    if (currentItems.length === 0) {
      return null;
    }

    const firstIndex = currentItems.findIndex((element) => {
      return element.id === id;
    });
    return firstIndex >= 0 && currentItems[firstIndex]
      ? currentItems[firstIndex]
      : null;
  }


delete(id: number): Observable<any> {
    return this.http
      .delete(environment["apiBaseUrl"] + "/company/" + id, {
        headers: new HttpHeaders().set(
          "Authorization",
          `Bearer ${this.getToken()}`
        ),
      })
      .pipe(
        map((company) => {
          return company["id"] ? true : false;
        }),
        tap((success) => {
          if (success) {
            this.deleteCompany(id);
          }
        }), // when success, delete the item from the local service
        catchError((err) => {
          return of(false);
        })
      );
  }


fetchCompany(id: number): Observable<any> {
    return this.http.get(environment["apiBaseUrl"] + "/company/" + id).pipe(
      map((company) => {
        return company["id"] ? company : false;
      }),
      catchError((err) => {
        return of(false);
      })
    );
  }


update(id: number, payload: ModelCompany): Observable<any> {
    return this.http
      .put(environment["apiBaseUrl"] + "/company/" + id, payload, {
        headers: new HttpHeaders().set(
          "Authorization",
          `Bearer ${this.getToken()}`
        ),
      })
      .pipe(
        map((company) => {
          return company["id"] ? company : false;
        }),
        tap((company: ModelCompany) => {
          if (company) {
            this.updateCompany(id, company);
          }
        }), // when success result, update the item in the local service
        catchError((err) => {
          return of(false);
        })
      );
  }