dispose(): void {
				if (that._insets.has(handle)) {
					that._insets.delete(handle);
					that._proxy.$disposeEditorInset(handle);
					onDidDispose.fire();

					// final cleanup
					onDidDispose.dispose();
					onDidReceiveMessage.dispose();
				}
			}


$onDidDispose(handle: number): void {
		const value = this._insets.get(handle);
		if (value) {
			value.inset.dispose();
		}
	}


$onDidReceiveMessage(handle: number, message: any): void {
		const value = this._insets.get(handle);
		if (value) {
			value.onDidReceiveMessage.fire(message);
		}
	}


(resolve) => {
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer/number',
                method: 'get',
                dataType: 'json',
                success: (result) => {
                    resolve(result);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            })
        }


(result) => {
                    resolve(result);
                }


(xhr, error) => {
                    resolve(false);
                }


(resolve) => {
            const headers: any = {
                'X-Auth-Token': user.getToken()
            };
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer',
                method: 'get',
                dataType: 'json',
                success: (result: Array<any>) => {
                    const orders: Array<OrderModel> = result.map((order: any) => {
                        return (new OrderModel()).deserialize(order);
                    })
                    resolve(orders);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            });
        }


(result: Array<any>) => {
                    const orders: Array<OrderModel> = result.map((order: any) => {
                        return (new OrderModel()).deserialize(order);
                    })
                    resolve(orders);
                }


(order: any) => {
                        return (new OrderModel()).deserialize(order);
                    }


export class OrderService {
    public constructor() {}

    public getOrdersNumber(user: UserModel): Promise<any> {
        const headers: any = {
            'X-Auth-Token': user.getToken()
        };
        return new Promise((resolve) => {
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer/number',
                method: 'get',
                dataType: 'json',
                success: (result) => {
                    resolve(result);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            })
        });
    }

    public getCustomerOrders(user: UserModel): Promise<any> {
        return new Promise((resolve) => {
            const headers: any = {
                'X-Auth-Token': user.getToken()
            };
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer',
                method: 'get',
                dataType: 'json',
                success: (result: Array<any>) => {
                    const orders: Array<OrderModel> = result.map((order: any) => {
                        return (new OrderModel()).deserialize(order);
                    })
                    resolve(orders);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            });
        });
    }
}


public getOrdersNumber(user: UserModel): Promise<any> {
        const headers: any = {
            'X-Auth-Token': user.getToken()
        };
        return new Promise((resolve) => {
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer/number',
                method: 'get',
                dataType: 'json',
                success: (result) => {
                    resolve(result);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            })
        });
    }


public getCustomerOrders(user: UserModel): Promise<any> {
        return new Promise((resolve) => {
            const headers: any = {
                'X-Auth-Token': user.getToken()
            };
            $.ajax({
                headers: headers,
                url: Constants.apiRoot + 'order/customer',
                method: 'get',
                dataType: 'json',
                success: (result: Array<any>) => {
                    const orders: Array<OrderModel> = result.map((order: any) => {
                        return (new OrderModel()).deserialize(order);
                    })
                    resolve(orders);
                },
                error: (xhr, error) => {
                    resolve(false);
                }
            });
        });
    }


/**
 * Creates a polyhedron mesh
 * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
 * * The parameter `size` (positive float, default 1) sets the polygon size
 * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
 * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overrides the parameter `type`
 * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
 * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
 * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
 * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
 * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
 * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
 * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
 * @param name defines the name of the mesh
 * @param options defines the options used to create the mesh
 * @param options.type
 * @param scene defines the hosting scene
 * @param options.size
 * @param options.sizeX
 * @param options.sizeY
 * @param options.sizeZ
 * @param options.custom
 * @param options.faceUV
 * @param options.faceColors
 * @param options.flat
 * @param options.updatable
 * @param options.sideOrientation
 * @param options.frontUVs
 * @param options.backUVs
 * @returns the polyhedron mesh
 * @see https://doc.babylonjs.com/how_to/polyhedra_shapes
 */
export function CreatePolyhedron(
    name: string,
    options: {
        type?: number;
        size?: number;
        sizeX?: number;
        sizeY?: number;
        sizeZ?: number;
        custom?: any;
        faceUV?: Vector4[];
        faceColors?: Color4[];
        flat?: boolean;
        updatable?: boolean;
        sideOrientation?: number;
        frontUVs?: Vector4;
        backUVs?: Vector4;
    } = {},
    scene: Nullable<Scene> = null
): Mesh {
    const polyhedron = new Mesh(name, scene);

    options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);
    polyhedron._originalBuilderSideOrientation = options.sideOrientation;

    const vertexData = CreatePolyhedronVertexData(options);

    vertexData.applyToMesh(polyhedron, options.updatable);

    return polyhedron;
}


(
    name: string,
    options: {
        type?: number;
        size?: number;
        sizeX?: number;
        sizeY?: number;
        sizeZ?: number;
        custom?: any;
        faceUV?: Vector4[];
        faceColors?: Color4[];
        updatable?: boolean;
        sideOrientation?: number;
    },
    scene: Scene
): Mesh => {
    return CreatePolyhedron(name, options, scene);
}


export default class LoaderIndicator extends React.Component<Props, State> {
    constructor(props: Props);
    render(): JSX.Element | null;
    renderWaiting(): JSX.Element | null;
    renderPending(): JSX.Element | null;
    renderError(): JSX.Element | null;
    renderCanceled(): JSX.Element | null;
    renderDone(): JSX.Element | null;
}


interface Props {
    loadingInformation: LoaderRequest.Informations;
    waiting?: string | false;
    pending?: string | false;
    error?: string | false;
    canceled?: string | false;
    done?: string | false;
    contentStrategy?: ContentStrategy;
}


interface State {
}


render(): JSX.Element | null;


renderWaiting(): JSX.Element | null;


renderPending(): JSX.Element | null;


renderError(): JSX.Element | null;


renderCanceled(): JSX.Element | null;


renderDone(): JSX.Element | null;


@Injectable()
export class RethinkService {
  constructor(private rethinkRepository: RethinkRepository) {}

  async createTable(nameTable: string) {
    const result = await this.rethinkRepository.createTable(nameTable);
    return result;
  }
}


async createTable(nameTable: string) {
    const result = await this.rethinkRepository.createTable(nameTable);
    return result;
  }


/**
   * 创建托管域名
   */
async CreateHostingDomain(
    req: CreateHostingDomainRequest,
    cb?: (error: string, rep: CreateHostingDomainResponse) => void
  ): Promise<CreateHostingDomainResponse> {
    return this.request("CreateHostingDomain", req, cb)
  }


/**
   * 获取终端用户列表
   */
async DescribeEndUsers(
    req: DescribeEndUsersRequest,
    cb?: (error: string, rep: DescribeEndUsersResponse) => void
  ): Promise<DescribeEndUsersResponse> {
    return this.request("DescribeEndUsers", req, cb)
  }


/**
     * 查询后付费短信资源量
1 有免费包的返回SmsFreeQuota结构所有字段
2 没有免费包，有付费包，付费返回复用SmsFreeQuota结构，其中只有 TodayUsedQuota 字段有效
3 都没有返回为空数组
     */
async DescribeSmsQuotas(
    req: DescribeSmsQuotasRequest,
    cb?: (error: string, rep: DescribeSmsQuotasResponse) => void
  ): Promise<DescribeSmsQuotasResponse> {
    return this.request("DescribeSmsQuotas", req, cb)
  }


/**
   * 获取环境列表，含环境下的各个资源信息。尤其是各资源的唯一标识，是请求各资源的关键参数
   */
async DescribeEnvs(
    req: DescribeEnvsRequest,
    cb?: (error: string, rep: DescribeEnvsResponse) => void
  ): Promise<DescribeEnvsResponse> {
    return this.request("DescribeEnvs", req, cb)
  }


/**
   * 增加安全域名
   */
async CreateAuthDomain(
    req: CreateAuthDomainRequest,
    cb?: (error: string, rep: CreateAuthDomainResponse) => void
  ): Promise<CreateAuthDomainResponse> {
    return this.request("CreateAuthDomain", req, cb)
  }


/**
   * 创建服务版本
   */
async CreateCloudBaseRunServerVersion(
    req: CreateCloudBaseRunServerVersionRequest,
    cb?: (error: string, rep: CreateCloudBaseRunServerVersionResponse) => void
  ): Promise<CreateCloudBaseRunServerVersionResponse> {
    return this.request("CreateCloudBaseRunServerVersion", req, cb)
  }


/**
   * 查询服务版本的详情，CPU和MEM  请使用CPUSize和MemSize
   */
async DescribeCloudBaseRunServerVersion(
    req: DescribeCloudBaseRunServerVersionRequest,
    cb?: (error: string, rep: DescribeCloudBaseRunServerVersionResponse) => void
  ): Promise<DescribeCloudBaseRunServerVersionResponse> {
    return this.request("DescribeCloudBaseRunServerVersion", req, cb)
  }


/**
   * 获取安全域名列表
   */
async DescribeAuthDomains(
    req: DescribeAuthDomainsRequest,
    cb?: (error: string, rep: DescribeAuthDomainsResponse) => void
  ): Promise<DescribeAuthDomainsResponse> {
    return this.request("DescribeAuthDomains", req, cb)
  }


/**
   * 开通后付费资源
   */
async CreatePostpayPackage(
    req: CreatePostpayPackageRequest,
    cb?: (error: string, rep: CreatePostpayPackageResponse) => void
  ): Promise<CreatePostpayPackageResponse> {
    return this.request("CreatePostpayPackage", req, cb)
  }


/**
   * 查看容器托管的集群状态
   */
async DescribeCloudBaseRunResource(
    req: DescribeCloudBaseRunResourceRequest,
    cb?: (error: string, rep: DescribeCloudBaseRunResourceResponse) => void
  ): Promise<DescribeCloudBaseRunResourceResponse> {
    return this.request("DescribeCloudBaseRunResource", req, cb)
  }


/**
   * 获取云开发项目列表
   */
async DescribeCloudBaseProjectLatestVersionList(
    req: DescribeCloudBaseProjectLatestVersionListRequest,
    cb?: (error: string, rep: DescribeCloudBaseProjectLatestVersionListResponse) => void
  ): Promise<DescribeCloudBaseProjectLatestVersionListResponse> {
    return this.request("DescribeCloudBaseProjectLatestVersionList", req, cb)
  }


/**
   * 针对已隔离的免费环境，可以通过本接口将其恢复访问。
   */
async ReinstateEnv(
    req: ReinstateEnvRequest,
    cb?: (error: string, rep: ReinstateEnvResponse) => void
  ): Promise<ReinstateEnvResponse> {
    return this.request("ReinstateEnv", req, cb)
  }


/**
   * 获取终端用户总量与平台分布情况
   */
async DescribeEndUserStatistic(
    req: DescribeEndUserStatisticRequest,
    cb?: (error: string, rep: DescribeEndUserStatisticResponse) => void
  ): Promise<DescribeEndUserStatisticResponse> {
    return this.request("DescribeEndUserStatistic", req, cb)
  }


/**
   * 查看容器托管的集群状态扩展使用
   */
async DescribeCloudBaseRunResourceForExtend(
    req: DescribeCloudBaseRunResourceForExtendRequest,
    cb?: (error: string, rep: DescribeCloudBaseRunResourceForExtendResponse) => void
  ): Promise<DescribeCloudBaseRunResourceForExtendResponse> {
    return this.request("DescribeCloudBaseRunResourceForExtend", req, cb)
  }


/**
   * 管理终端用户
   */
async ModifyEndUser(
    req: ModifyEndUserRequest,
    cb?: (error: string, rep: ModifyEndUserResponse) => void
  ): Promise<ModifyEndUserResponse> {
    return this.request("ModifyEndUser", req, cb)
  }


/**
   * 获取增值包计费相关信息
   */
async DescribeExtraPkgBillingInfo(
    req: DescribeExtraPkgBillingInfoRequest,
    cb?: (error: string, rep: DescribeExtraPkgBillingInfoResponse) => void
  ): Promise<DescribeExtraPkgBillingInfoResponse> {
    return this.request("DescribeExtraPkgBillingInfo", req, cb)
  }


/**
   * 获取后付费免费额度
   */
async DescribePostpayPackageFreeQuotas(
    req: DescribePostpayPackageFreeQuotasRequest,
    cb?: (error: string, rep: DescribePostpayPackageFreeQuotasResponse) => void
  ): Promise<DescribePostpayPackageFreeQuotasResponse> {
    return this.request("DescribePostpayPackageFreeQuotas", req, cb)
  }


/**
   * 创建云应用服务
   */
async EstablishCloudBaseRunServer(
    req: EstablishCloudBaseRunServerRequest,
    cb?: (error: string, rep: EstablishCloudBaseRunServerResponse) => void
  ): Promise<EstablishCloudBaseRunServerResponse> {
    return this.request("EstablishCloudBaseRunServer", req, cb)
  }


/**
   * TCB云API统一入口
   */
async CommonServiceAPI(
    req: CommonServiceAPIRequest,
    cb?: (error: string, rep: CommonServiceAPIResponse) => void
  ): Promise<CommonServiceAPIResponse> {
    return this.request("CommonServiceAPI", req, cb)
  }


/**
   * 创建云开发项目
   */
async CreateAndDeployCloudBaseProject(
    req: CreateAndDeployCloudBaseProjectRequest,
    cb?: (error: string, rep: CreateAndDeployCloudBaseProjectResponse) => void
  ): Promise<CreateAndDeployCloudBaseProjectResponse> {
    return this.request("CreateAndDeployCloudBaseProject", req, cb)
  }


/**
   * 检查是否开通Tcb服务
   */
async CheckTcbService(
    req?: CheckTcbServiceRequest,
    cb?: (error: string, rep: CheckTcbServiceResponse) => void
  ): Promise<CheckTcbServiceResponse> {
    return this.request("CheckTcbService", req, cb)
  }


/**
   * 删除终端用户
   */
async DeleteEndUser(
    req: DeleteEndUserRequest,
    cb?: (error: string, rep: DeleteEndUserResponse) => void
  ): Promise<DeleteEndUserResponse> {
    return this.request("DeleteEndUser", req, cb)
  }


/**
   * 获取环境终端用户新增与登录信息
   */
async DescribeEndUserLoginStatistic(
    req: DescribeEndUserLoginStatisticRequest,
    cb?: (error: string, rep: DescribeEndUserLoginStatisticResponse) => void
  ): Promise<DescribeEndUserLoginStatisticResponse> {
    return this.request("DescribeEndUserLoginStatistic", req, cb)
  }


/**
   * 查询指定指标的配额使用量
   */
async DescribeQuotaData(
    req: DescribeQuotaDataRequest,
    cb?: (error: string, rep: DescribeQuotaDataResponse) => void
  ): Promise<DescribeQuotaDataResponse> {
    return this.request("DescribeQuotaData", req, cb)
  }


/**
   * 开通容器托管的资源，包括集群创建，VPC配置，异步任务创建，镜像托管，Coding等，查看创建结果需要根据DescribeCloudBaseRunResource接口来查看
   */
async CreateCloudBaseRunResource(
    req: CreateCloudBaseRunResourceRequest,
    cb?: (error: string, rep: CreateCloudBaseRunResourceResponse) => void
  ): Promise<CreateCloudBaseRunResourceResponse> {
    return this.request("CreateCloudBaseRunResource", req, cb)
  }


/**
   * 删除云项目
   */
async DeleteCloudBaseProjectLatestVersion(
    req: DeleteCloudBaseProjectLatestVersionRequest,
    cb?: (error: string, rep: DeleteCloudBaseProjectLatestVersionResponse) => void
  ): Promise<DeleteCloudBaseProjectLatestVersionResponse> {
    return this.request("DeleteCloudBaseProjectLatestVersion", req, cb)
  }


/**
   * 获取下载文件信息
   */
async DescribeDownloadFile(
    req: DescribeDownloadFileRequest,
    cb?: (error: string, rep: DescribeDownloadFileResponse) => void
  ): Promise<DescribeDownloadFileResponse> {
    return this.request("DescribeDownloadFile", req, cb)
  }


/**
   * 更新环境信息
   */
async ModifyEnv(
    req: ModifyEnvRequest,
    cb?: (error: string, rep: ModifyEnvResponse) => void
  ): Promise<ModifyEnvResponse> {
    return this.request("ModifyEnv", req, cb)
  }


/**
   * 获取数据库权限
   */
async DescribeDatabaseACL(
    req: DescribeDatabaseACLRequest,
    cb?: (error: string, rep: DescribeDatabaseACLResponse) => void
  ): Promise<DescribeDatabaseACLResponse> {
    return this.request("DescribeDatabaseACL", req, cb)
  }


/**
   * 销毁环境
   */
async DestroyEnv(
    req: DestroyEnvRequest,
    cb?: (error: string, rep: DestroyEnvResponse) => void
  ): Promise<DestroyEnvResponse> {
    return this.request("DestroyEnv", req, cb)
  }


/**
   * 获取云托管代码上传url
   */
async DescribeCloudBaseBuildService(
    req: DescribeCloudBaseBuildServiceRequest,
    cb?: (error: string, rep: DescribeCloudBaseBuildServiceResponse) => void
  ): Promise<DescribeCloudBaseBuildServiceResponse> {
    return this.request("DescribeCloudBaseBuildService", req, cb)
  }


/**
   * 查询版本历史
   */
async DescribeCloudBaseRunVersionSnapshot(
    req: DescribeCloudBaseRunVersionSnapshotRequest,
    cb?: (error: string, rep: DescribeCloudBaseRunVersionSnapshotResponse) => void
  ): Promise<DescribeCloudBaseRunVersionSnapshotResponse> {
    return this.request("DescribeCloudBaseRunVersionSnapshot", req, cb)
  }


/**
   * 销毁静态托管资源，该接口创建异步销毁任务，资源最终状态可从DestroyStaticStore接口查看
   */
async DestroyStaticStore(
    req: DestroyStaticStoreRequest,
    cb?: (error: string, rep: DestroyStaticStoreResponse) => void
  ): Promise<DestroyStaticStoreResponse> {
    return this.request("DestroyStaticStore", req, cb)
  }


/**
   * 修改数据库权限
   */
async ModifyDatabaseACL(
    req: ModifyDatabaseACLRequest,
    cb?: (error: string, rep: ModifyDatabaseACLResponse) => void
  ): Promise<ModifyDatabaseACLResponse> {
    return this.request("ModifyDatabaseACL", req, cb)
  }


/**
   * 创建静态托管资源，包括COS和CDN，异步任务创建，查看创建结果需要根据DescribeStaticStore接口来查看
   */
async CreateStaticStore(
    req: CreateStaticStoreRequest,
    cb?: (error: string, rep: CreateStaticStoreResponse) => void
  ): Promise<CreateStaticStoreResponse> {
    return this.request("CreateStaticStore", req, cb)
  }


/**
   * 查询环境个数上限
   */
async DescribeEnvLimit(
    req?: DescribeEnvLimitRequest,
    cb?: (error: string, rep: DescribeEnvLimitResponse) => void
  ): Promise<DescribeEnvLimitResponse> {
    return this.request("DescribeEnvLimit", req, cb)
  }


/**
   * 查询后付费资源免费量
   */
async DescribePostpayFreeQuotas(
    req: DescribePostpayFreeQuotasRequest,
    cb?: (error: string, rep: DescribePostpayFreeQuotasResponse) => void
  ): Promise<DescribePostpayFreeQuotasResponse> {
    return this.request("DescribePostpayFreeQuotas", req, cb)
  }


/**
   * 查询后付费免费配额信息
   */
async DescribeEnvFreeQuota(
    req: DescribeEnvFreeQuotaRequest,
    cb?: (error: string, rep: DescribeEnvFreeQuotaResponse) => void
  ): Promise<DescribeEnvFreeQuotaResponse> {
    return this.request("DescribeEnvFreeQuota", req, cb)
  }


() => {
    let wrapper: ShallowWrapper<any, Readonly<{}>, React.Component<{}, {}, any>>;

    afterEach(() => {
        wrapper && wrapper.unmount();
    });

    it('should change input value after change props', () => {
        wrapper = shallow(<RangeDatePicker
            value={ null }
            onValueChange={ () => { } }
        />, {});

        wrapper.setProps({ value: { from: '2017-01-22', to: '2017-01-28' } });
        expect(wrapper.state('inputValue')).toEqual({ from: 'Jan 22, 2017', to: 'Jan 28, 2017' });
        expect(wrapper.state('selectedDate')).toEqual({ from: '2017-01-22', to: '2017-01-28' });
    }


() => {
        wrapper && wrapper.unmount();
    }


() => {
        wrapper = shallow(<RangeDatePicker
            value={ null }
            onValueChange={ () => { } }


() => {

        wrapper = shallow(<RangeDatePicker
            value={ null }
            onValueChange={ () => { } }


() => {
        let newState: any = {};
        wrapper = shallow(<RangeDatePicker
            value={ null }
            onValueChange={ (nV: any) => newState = nV }


() => {
        let baseValue = { from: '2019-10-47', to: '2019-10-07' };
        const onValueChangeSpy = jest.fn((nV: any) => null);
        wrapper = shallow(<RangeDatePicker
            value={ baseValue }
            onValueChange={ onValueChangeSpy }
        />, {});

        (wrapper.instance() as any).handleBlur('from');
        expect(onValueChangeSpy).toHaveBeenLastCalledWith({
            from: null,
            to: baseValue.to,
        });
    }


(nV: any) => null


() => {
        let baseValue = { from: '2019-09-10', to: '2019-09-12' };

        const onValueChangeSpy = jest.fn((nV: any) => null);
        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = RangeDatePicker.prototype.setState;
        RangeDatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<RangeDatePicker
            value={ { from: null, to: null } }


(nextState) => null


() => {
        let inputValue = { from: 'Sep 11, 2019', to: 'Sep 20, 2019' };
        let value = { from: '2019-09-14', to: '2019-09-15' };

        const setValueSpy = jest.fn((nV: any) => null);

        const pickerSetValue = RangeDatePicker.prototype.setValue;

        wrapper = shallow(<RangeDatePicker
            value={ value }
            onValueChange={ () => { } }


() => {
        let baseValue = { from: '2019-09-10', to: '2019-10-10' };

        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = RangeDatePicker.prototype.setState;
        RangeDatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<RangeDatePicker
            value={ baseValue }
            onValueChange={ () => { } }


() => {
        let baseValue = { from: '2019-09-10', to: '2019-09-12' };

        const onValueChangeSpy = jest.fn((nV: any) => null);
        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = RangeDatePicker.prototype.setState;
        RangeDatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<RangeDatePicker
            value={ baseValue }
            onValueChange={ onValueChangeSpy }
        />, {});
        const instance: any = wrapper.instance();

        instance.handleCancel();

        expect(onValueChangeSpy).toHaveBeenLastCalledWith({ from: null, to: null });
        expect(setStateSpy).toHaveBeenLastCalledWith({ inputValue: { from: null, to: null } });

        RangeDatePicker.prototype.setState = pickerSetState;
    }


() => {
        let baseValue = { from: '2019-09-10', to: '2019-09-12' };

        wrapper = shallow(<RangeDatePicker
            value={ baseValue }
            onValueChange={ () => { } }


() => {
        let baseValue = { from: '2019-09-10', to: '2019-09-12' };
        let inputValue = { from: 'Sep 10, 2019', to: 'Sep 12, 2019' };

        const setValueSpy = jest.fn((nV: any) => null);
        const focusSpy = jest.fn((nV: any) => null);
        const pickerSetValue = RangeDatePicker.prototype.setValue;

        wrapper = shallow(<RangeDatePicker
            value={ { from: null, to: null } }


() => {
        wrapper = shallow(<RangeDatePicker
            value={ { from: null, to: null } }


() => {
        let baseValue = { from: '2019-09-10', to: '2019-09-10' };

        const onValueChangeSpy = jest.fn((nV: any) => null);
        const setStateSpy = jest.fn((nextState) => null);

        const pickerSetState = RangeDatePicker.prototype.setState;
        RangeDatePicker.prototype.setState = setStateSpy;

        wrapper = shallow(<RangeDatePicker
            value={ { from: null, to: null } }


export async function* listDistributionConfigurationsPaginate(
  config: ImagebuilderPaginationConfiguration,
  input: ListDistributionConfigurationsCommandInput,
  ...additionalArguments: any
): Paginator<ListDistributionConfigurationsCommandOutput> {
  let token: string | undefined = config.startingToken || undefined;
  let hasNext = true;
  let page: ListDistributionConfigurationsCommandOutput;
  while (hasNext) {
    input.nextToken = token;
    input["maxResults"] = config.pageSize;
    if (config.client instanceof Imagebuilder) {
      page = await makePagedRequest(config.client, input, ...additionalArguments);
    } else if (config.client instanceof ImagebuilderClient) {
      page = await makePagedClientRequest(config.client, input, ...additionalArguments);
    } else {
      throw new Error("Invalid client, expected Imagebuilder | ImagebuilderClient");
    }
    yield page;
    token = page.nextToken;
    hasNext = !!token;
  }
  // @ts-ignore
  return undefined;
}


async (
  client: ImagebuilderClient,
  input: ListDistributionConfigurationsCommandInput,
  ...args: any
): Promise<ListDistributionConfigurationsCommandOutput> => {
  // @ts-ignore
  return await client.send(new ListDistributionConfigurationsCommand(input, ...args));
}


async (
  client: Imagebuilder,
  input: ListDistributionConfigurationsCommandInput,
  ...args: any
): Promise<ListDistributionConfigurationsCommandOutput> => {
  // @ts-ignore
  return await client.listDistributionConfigurations(input, ...args);
}


({ element, children, scale }) => (
  <g>
    <path style={


interface Props {
  element: UMLClassPackage;
  scale: number;
}


export class TeamMembershipTeam extends pulumi.CustomResource {
    /**
     * Get an existing TeamMembershipTeam resource's state with the given name, ID, and optional extra
     * properties used to qualify the lookup.
     *
     * @param name The _unique_ name of the resulting resource.
     * @param id The _unique_ provider ID of the resource to lookup.
     * @param state Any extra arguments used during the lookup.
     */
    public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TeamMembershipTeamState, opts?: pulumi.CustomResourceOptions): TeamMembershipTeam {
        return new TeamMembershipTeam(name, <any>state, { ...opts, id: id });
    }

    public /*out*/ readonly etag: pulumi.Output<string>;
    public readonly role: pulumi.Output<string | undefined>;
    public readonly teamId: pulumi.Output<string>;
    public readonly username: pulumi.Output<string>;

    /**
     * Create a TeamMembershipTeam resource with the given unique name, arguments, and options.
     *
     * @param name The _unique_ name of the resource.
     * @param args The arguments to use to populate this resource's properties.
     * @param opts A bag of options that control this resource's behavior.
     */
    constructor(name: string, args: TeamMembershipTeamArgs, opts?: pulumi.CustomResourceOptions)
    constructor(name: string, argsOrState?: TeamMembershipTeamArgs | TeamMembershipTeamState, opts?: pulumi.CustomResourceOptions) {
        let inputs: pulumi.Inputs = {};
        if (opts && opts.id) {
            const state: TeamMembershipTeamState = argsOrState as TeamMembershipTeamState | undefined;
            inputs["etag"] = state ? state.etag : undefined;
            inputs["role"] = state ? state.role : undefined;
            inputs["teamId"] = state ? state.teamId : undefined;
            inputs["username"] = state ? state.username : undefined;
        } else {
            const args = argsOrState as TeamMembershipTeamArgs | undefined;
            if (!args || args.teamId === undefined) {
                throw new Error("Missing required property 'teamId'");
            }
            if (!args || args.username === undefined) {
                throw new Error("Missing required property 'username'");
            }
            inputs["role"] = args ? args.role : undefined;
            inputs["teamId"] = args ? args.teamId : undefined;
            inputs["username"] = args ? args.username : undefined;
            inputs["etag"] = undefined /*out*/;
        }
        super("github:index/teamMembershipTeam:TeamMembershipTeam", name, inputs, opts);
    }
}


/**
 * Input properties used for looking up and filtering TeamMembershipTeam resources.
 */
export interface TeamMembershipTeamState {
    readonly etag?: pulumi.Input<string>;
    readonly role?: pulumi.Input<string>;
    readonly teamId?: pulumi.Input<string>;
    readonly username?: pulumi.Input<string>;
}


/**
 * The set of arguments for constructing a TeamMembershipTeam resource.
 */
export interface TeamMembershipTeamArgs {
    readonly role?: pulumi.Input<string>;
    readonly teamId: pulumi.Input<string>;
    readonly username: pulumi.Input<string>;
}


/**
     * Get an existing TeamMembershipTeam resource's state with the given name, ID, and optional extra
     * properties used to qualify the lookup.
     *
     * @param name The _unique_ name of the resulting resource.
     * @param id The _unique_ provider ID of the resource to lookup.
     * @param state Any extra arguments used during the lookup.
     */
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TeamMembershipTeamState, opts?: pulumi.CustomResourceOptions): TeamMembershipTeam {
        return new TeamMembershipTeam(name, <any>state, { ...opts, id: id });
    }


function AppRouter() {
  return (
    <Router>
      <Route path="/" exact component={Inference} />
      <Route path="/home" component={Home} />
    </Router>
  );
}


(callback) => {
            storedCallback = callback
        }


(err, mimeType, stream) => {
            presets.convertersFor(mimeType.type).forEach((converter) => {
                stream.converter = converter;
                stream.pipe(converter.toStream(size));
                storedCallback.call(stream, stream);
            })
        }


(converter) => {
                stream.converter = converter;
                stream.pipe(converter.toStream(size));
                storedCallback.call(stream, stream);
            }


export default class MediaConverter {
    private videoConverter = new VideoConverter()
    constructor(options = _options) {
        this.videoConverter.setFfmpegPath(options.programs.ffmpeg)
    }

    public thumbs(size) {
        let input = new Stream.PassThrough(),
            storedCallback
        input.forEach = (callback) => {
            storedCallback = callback
        }
        magic(input, (err, mimeType, stream) => {
            presets.convertersFor(mimeType.type).forEach((converter) => {
                stream.converter = converter;
                stream.pipe(converter.toStream(size));
                storedCallback.call(stream, stream);
            })
        })
        return input
    }
    public mp4Copy(){
        return presets.converters.mp4_copy.toStream()
    }
}


public thumbs(size) {
        let input = new Stream.PassThrough(),
            storedCallback
        input.forEach = (callback) => {
            storedCallback = callback
        }
        magic(input, (err, mimeType, stream) => {
            presets.convertersFor(mimeType.type).forEach((converter) => {
                stream.converter = converter;
                stream.pipe(converter.toStream(size));
                storedCallback.call(stream, stream);
            })
        })
        return input
    }


public mp4Copy(){
        return presets.converters.mp4_copy.toStream()
    }


function d(name: string, use: string, doc: string): vscode.CompletionItem {
    const i = new vscode.CompletionItem(name, vscode.CompletionItemKind.Variable);
    i.detail = use;
    i.documentation = doc;
    return i;
}


function val(name: string, use: string, doc: string): vscode.CompletionItem {
    const i = new vscode.CompletionItem(name, vscode.CompletionItemKind.Value);
    i.detail = use;
    i.documentation = doc;
    return i;
}


(item) => {
            const itemPath = filepath.join(path, item);
            const stat = fs.statSync(itemPath);
            if (stat.isDirectory()) {
                return;
            }
            const schema = JSON.parse(shell.cat(itemPath));
            if (!schema.models) {
                return;
            }
            console.log("Adding schema " + itemPath);
            res = res.concat(this.fromSchema(schema.models));
        }


(v, k) => {
            const i = k.lastIndexOf(".");
            const kind = k.substr(i+1);
            res.push(val(kind, `kind: ${ kind }`, v.description));
            _.each(v.properties, (spec, label) => {
                let type = "undefined";
                switch (spec.type) {
                    case undefined:
                        // This usually means there's a $ref instead of a type
                        if (spec["$ref"]) {
                            type = spec["$ref"];
                        }
                        break;
                    case "array":
                        // Try to give a pretty type.
                        if (spec.items.type) {
                            type = spec.items.type + "[]";
                            break;
                        } else if (spec.items["$ref"]) {
                            type = spec.items["$ref"] + "[]";
                            break;
                        }
                        type = "[]";
                        break;
                    default:
                        if (spec.type) {
                            type = spec.type;
                        }
                        break;
                }
                res.push(d(label, `${ label }: ${ type }`, spec.description));
            });
        }


(spec, label) => {
                let type = "undefined";
                switch (spec.type) {
                    case undefined:
                        // This usually means there's a $ref instead of a type
                        if (spec["$ref"]) {
                            type = spec["$ref"];
                        }
                        break;
                    case "array":
                        // Try to give a pretty type.
                        if (spec.items.type) {
                            type = spec.items.type + "[]";
                            break;
                        } else if (spec.items["$ref"]) {
                            type = spec.items["$ref"] + "[]";
                            break;
                        }
                        type = "[]";
                        break;
                    default:
                        if (spec.type) {
                            type = spec.type;
                        }
                        break;
                }
                res.push(d(label, `${ label }: ${ type }`, spec.description));
            }


// Resources describes Kubernetes resource keywords.
export class Resources {
    public all(): vscode.CompletionItem[] {
        const home = shell.home();
        const schemaDir = filepath.join(home, ".kube/schema");
        if (!fs.existsSync(schemaDir)) {
            // Return the default set.
            return this.v1();
        }
        const stat = fs.statSync(schemaDir);
        if (!stat.isDirectory()) {
            // Return the default set.
            return this.v1();
        }
        // Otherwise, try to dynamically build completion items from the
        // entire schema.
        const schemaDirContents = shell.ls(schemaDir);
        if (schemaDirContents.length === 0) {
            // Return the default set.
            return this.v1();
        }
        const kversion = _.last(schemaDirContents)!;
        console.log("Loading schema for version " + kversion);

        // Inside of the schemaDir, there are some top-level copies of the schemata.
        // Instead of walking the tree, we just parse those.  Note that kubectl loads
        // schemata on demand, which means we won't have an exhaustive list, but we are
        // more likely to get the ones that this user is actually using, including
        // TPRs.
        let res = Array.of<vscode.CompletionItem>();
        const path = filepath.join(schemaDir, kversion);
        shell.ls(path).forEach((item) => {
            const itemPath = filepath.join(path, item);
            const stat = fs.statSync(itemPath);
            if (stat.isDirectory()) {
                return;
            }
            const schema = JSON.parse(shell.cat(itemPath));
            if (!schema.models) {
                return;
            }
            console.log("Adding schema " + itemPath);
            res = res.concat(this.fromSchema(schema.models));
        });
        console.log(`Attached ${res.length} resource kinds`);
        return res;
    }

    v1(): vscode.CompletionItem[] {
        return this.fromSchema(v1.default.models);
    }

    // Extract hover documentation from a Swagger model.
    fromSchema(schema: any): vscode.CompletionItem[] {
        const res = Array.of<vscode.CompletionItem>();
        _.each(schema, (v, k) => {
            const i = k.lastIndexOf(".");
            const kind = k.substr(i+1);
            res.push(val(kind, `kind: ${ kind }`, v.description));
            _.each(v.properties, (spec, label) => {
                let type = "undefined";
                switch (spec.type) {
                    case undefined:
                        // This usually means there's a $ref instead of a type
                        if (spec["$ref"]) {
                            type = spec["$ref"];
                        }
                        break;
                    case "array":
                        // Try to give a pretty type.
                        if (spec.items.type) {
                            type = spec.items.type + "[]";
                            break;
                        } else if (spec.items["$ref"]) {
                            type = spec.items["$ref"] + "[]";
                            break;
                        }
                        type = "[]";
                        break;
                    default:
                        if (spec.type) {
                            type = spec.type;
                        }
                        break;
                }
                res.push(d(label, `${ label }: ${ type }`, spec.description));
            });
        });
        return res;
    }
}


public all(): vscode.CompletionItem[] {
        const home = shell.home();
        const schemaDir = filepath.join(home, ".kube/schema");
        if (!fs.existsSync(schemaDir)) {
            // Return the default set.
            return this.v1();
        }
        const stat = fs.statSync(schemaDir);
        if (!stat.isDirectory()) {
            // Return the default set.
            return this.v1();
        }
        // Otherwise, try to dynamically build completion items from the
        // entire schema.
        const schemaDirContents = shell.ls(schemaDir);
        if (schemaDirContents.length === 0) {
            // Return the default set.
            return this.v1();
        }
        const kversion = _.last(schemaDirContents)!;
        console.log("Loading schema for version " + kversion);

        // Inside of the schemaDir, there are some top-level copies of the schemata.
        // Instead of walking the tree, we just parse those.  Note that kubectl loads
        // schemata on demand, which means we won't have an exhaustive list, but we are
        // more likely to get the ones that this user is actually using, including
        // TPRs.
        let res = Array.of<vscode.CompletionItem>();
        const path = filepath.join(schemaDir, kversion);
        shell.ls(path).forEach((item) => {
            const itemPath = filepath.join(path, item);
            const stat = fs.statSync(itemPath);
            if (stat.isDirectory()) {
                return;
            }
            const schema = JSON.parse(shell.cat(itemPath));
            if (!schema.models) {
                return;
            }
            console.log("Adding schema " + itemPath);
            res = res.concat(this.fromSchema(schema.models));
        });
        console.log(`Attached ${res.length} resource kinds`);
        return res;
    }


v1(): vscode.CompletionItem[] {
        return this.fromSchema(v1.default.models);
    }


// Extract hover documentation from a Swagger model.
fromSchema(schema: any): vscode.CompletionItem[] {
        const res = Array.of<vscode.CompletionItem>();
        _.each(schema, (v, k) => {
            const i = k.lastIndexOf(".");
            const kind = k.substr(i+1);
            res.push(val(kind, `kind: ${ kind }`, v.description));
            _.each(v.properties, (spec, label) => {
                let type = "undefined";
                switch (spec.type) {
                    case undefined:
                        // This usually means there's a $ref instead of a type
                        if (spec["$ref"]) {
                            type = spec["$ref"];
                        }
                        break;
                    case "array":
                        // Try to give a pretty type.
                        if (spec.items.type) {
                            type = spec.items.type + "[]";
                            break;
                        } else if (spec.items["$ref"]) {
                            type = spec.items["$ref"] + "[]";
                            break;
                        }
                        type = "[]";
                        break;
                    default:
                        if (spec.type) {
                            type = spec.type;
                        }
                        break;
                }
                res.push(d(label, `${ label }: ${ type }`, spec.description));
            });
        });
        return res;
    }


() => {
  const mockClient = {
    clearStaleState: jest.fn(),
  };
  return {
    OidcClient: jest.fn().mockImplementation(() => {
      return mockClient;
    }),
    WebStorageStateStore: jest.fn(),
  };
}


() => {
      return mockClient;
    }


() => {
  it("removes the 'code' query string if present", () => {
    expect(removeOidcQueryParam("https://some.url/?code=aCode")).toEqual(
      "https://some.url/"
    );
  });

  it("removes the 'state' query string if present", () => {
    expect(removeOidcQueryParam("https://some.url/?state=arkansas")).toEqual(
      "https://some.url/"
    );
  });

  it("removes the hash part of the IRI", () => {
    expect(removeOidcQueryParam("https://some.url/#some-anchor")).toEqual(
      "https://some.url/"
    );
  });

  it("returns an URL without query strings as is", () => {
    expect(removeOidcQueryParam("https://some.url/")).toEqual(
      "https://some.url/"
    );
  });

  it("preserves other query strings", () => {
    expect(
      removeOidcQueryParam(
        "https://some.url/?code=someCode&state=someState&otherQuery=aValue"
      )
    ).toEqual("https://some.url/?otherQuery=aValue");
  });
}


() => {
    expect(removeOidcQueryParam("https://some.url/?code=aCode")).toEqual(
      "https://some.url/"
    );
  }


() => {
    expect(removeOidcQueryParam("https://some.url/?state=arkansas")).toEqual(
      "https://some.url/"
    );
  }


() => {
    expect(removeOidcQueryParam("https://some.url/#some-anchor")).toEqual(
      "https://some.url/"
    );
  }


() => {
    expect(removeOidcQueryParam("https://some.url/")).toEqual(
      "https://some.url/"
    );
  }


() => {
    expect(
      removeOidcQueryParam(
        "https://some.url/?code=someCode&state=someState&otherQuery=aValue"
      )
    ).toEqual("https://some.url/?otherQuery=aValue");
  }


() => {
  it("clears oidc-client storage", async () => {
    // This is a bad test, but we can only test for internal behaviour of oidc-client,
    // or test that the 'clearStaleState' function is called, which is done here.
    const clearSpy = jest.spyOn(new OidcClient({}), "clearStaleState");
    await clearOidcPersistentStorage();
    expect(clearSpy).toHaveBeenCalled();
  });

  it("removes keys matching expected patterns as a stopgap solution", async () => {
    window.localStorage.setItem("oidc.someOidcState", "a value");
    window.localStorage.setItem(
      "solidClientAuthenticationUser:someSessionId",
      "a value"
    );
    window.localStorage.setItem("anArbitraryKey", "a value");
    await clearOidcPersistentStorage();
    expect(window.localStorage).toHaveLength(1);
  });

  it("doesn't fail if localstorage is empty", async () => {
    window.localStorage.clear();
    await clearOidcPersistentStorage();
    expect(window.localStorage).toHaveLength(0);
  });
}


async () => {
    // This is a bad test, but we can only test for internal behaviour of oidc-client,
    // or test that the 'clearStaleState' function is called, which is done here.
    const clearSpy = jest.spyOn(new OidcClient({}), "clearStaleState");
    await clearOidcPersistentStorage();
    expect(clearSpy).toHaveBeenCalled();
  }


async () => {
    window.localStorage.setItem("oidc.someOidcState", "a value");
    window.localStorage.setItem(
      "solidClientAuthenticationUser:someSessionId",
      "a value"
    );
    window.localStorage.setItem("anArbitraryKey", "a value");
    await clearOidcPersistentStorage();
    expect(window.localStorage).toHaveLength(1);
  }


async () => {
    window.localStorage.clear();
    await clearOidcPersistentStorage();
    expect(window.localStorage).toHaveLength(0);
  }


@Component({
  selector: 'ab-checkbox',
  host: { class: 'ab-checkbox' },
  templateUrl: './checkbox.component.html'
})
export class CheckboxComponent {

  @Input() public checked: boolean = false;

}


/**
 * Test the generic Filter using collection.find<T>() method
 */
// a collection model for all possible MongoDB BSON types and TypeScript types
interface PetModel {
  _id: ObjectId; // ObjectId field
  name?: string; // optional field
  family: string; // string field
  age: number; // number field
  type: 'dog' | 'cat' | 'fish'; // union field
  isCute: boolean; // boolean field
  bestFriend?: PetModel; // object field (Embedded/Nested Documents)
  createdAt: Date; // date field
  treats: string[]; // array of string
  playTimePercent: Decimal128; // bson Decimal128 type
  readonly friends?: ReadonlyArray<PetModel>; // readonly array of objects
  playmates?: PetModel[]; // writable array of objects
}


() => {

    /* Check day popup disclaimer */

    let showPopupDisclaimer = false;
    if (localStorage.getItem('lastShownPopupDisclaimer')) {
        if (moment().format('YYYY-MM-DD') !== moment(localStorage.getItem('lastShownPopupDisclaimer'), 'YYYY-MM-DD hh:mm:ss').format('YYYY-MM-DD')) {
            showPopupDisclaimer = true;
            localStorage.setItem('lastShownPopupDisclaimer', moment().format('YYYY-MM-DD hh:mm:ss'));
        }
    } else {
        showPopupDisclaimer = true;
        localStorage.setItem('lastShownPopupDisclaimer', moment().format('YYYY-MM-DD hh:mm:ss'));
    }

    // Get locale
    const location = useLocation();
    const match: any = matchPath(location.pathname, {
        path: '/:locale',
        strict: false
    });

    const locale = match ? match.params.locale : 'en';

    return (
        <>
            <MobileLandscapeRequired locale={locale} />
            <div className="body-container">
                <Menu locale={locale}/>
                <Body />
                <Footer/>
                <Popup
                    show={showPopupDisclaimer}
                    head={_i18n(locale, 'disclaimer_popup_title')}
                    body={_i18n(locale, 'disclaimer_popup_msg', true)}
                />
            </div>
        </>


({ store, history }: Props) => {

    return (
        <Provider store={store}>
            <ConnectedRouter history={history}>
                <App/>
            </ConnectedRouter>
        </Provider>


type Props = {
    store: Store;
    history: History;
};


_i18n(locale, 'disclaimer_popup_title')


_i18n(locale, 'disclaimer_popup_msg', true)


function getHostLabel(labelService: ILabelService, item: ITrustedUriItem): string {
	return item.uri.authority ? labelService.getHostLabel(item.uri.scheme, item.uri.authority) : localize('localAuthority', "Local");
}


(item: ITrustedUriItem) => {
						const hostLabel = getHostLabel(this.labelService, item);
						if (hostLabel === undefined || hostLabel.length === 0) {
							return localize('trustedFolderAriaLabel', "{0}, trusted", this.labelService.getUriLabel(item.uri));
						}

						return localize('trustedFolderWithHostAriaLabel', "{0} on {1}, trusted", this.labelService.getUriLabel(item.uri), hostLabel);
					}


() => localize('trustedFoldersAndWorkspaces', "Trusted Folders & Workspaces")


item => {
			// default prevented when input box is double clicked #125052
			if (item && item.element && !item.browserEvent?.defaultPrevented) {
				this.edit(item.element, true);
			}
		}


async () => {
			const uri = await this.fileDialogService.showOpenDialog({
				canSelectFiles: false,
				canSelectFolders: true,
				canSelectMany: false,
				defaultUri: this.currentWorkspaceUri,
				openLabel: localize('trustUri', "Trust Folder"),
				title: localize('selectTrustedUri', "Select Folder To Trust")
			});

			if (uri) {
				this.workspaceTrustManagementService.setUrisTrust(uri, true);
			}
		}


() => {
			this.updateTable();
		}


folder => folder.uri


uri => {

			let relatedToCurrentWorkspace = false;
			for (const workspaceUri of currentWorkspaceUris) {
				relatedToCurrentWorkspace = relatedToCurrentWorkspace || this.uriService.extUri.isEqualOrParent(workspaceUri, uri);
			}

			return {
				uri,
				parentOfWorkspaceItem: relatedToCurrentWorkspace
			};
		}


(a, b) => {
			if (a.uri.scheme !== b.uri.scheme) {
				if (a.uri.scheme === Schemas.file) {
					return -1;
				}

				if (b.uri.scheme === Schemas.file) {
					return 1;
				}
			}

			const aIsWorkspace = a.uri.path.endsWith('.code-workspace');
			const bIsWorkspace = b.uri.path.endsWith('.code-workspace');

			if (aIsWorkspace !== bIsWorkspace) {
				if (aIsWorkspace) {
					return 1;
				}

				if (bIsWorkspace) {
					return -1;
				}
			}

			return a.uri.fsPath.localeCompare(b.uri.fsPath);
		}


s => s.length


u => this.uriService.extUri.isEqual(u, item.uri)


() => {
				this.table.edit(item, false);
			}


() => {
				this.table.edit(item, true);
			}


async () => {
				await this.table.delete(item);
			}


value => this.table.validateUri(value, this.currentItem)


async (e) => {
			if (item === e) {
				templateData.element.classList.add('input-mode');
				templateData.pathInput.focus();
				templateData.pathInput.select();
				templateData.element.parentElement!.style.paddingLeft = '0px';
			}
		}


e => {
			EventHelper.stop(e);
		}


() => {
			templateData.element.classList.remove('input-mode');
			templateData.element.parentElement!.style.paddingLeft = '5px';
		}


() => {
			hideInputBox();
			const uri = item.uri.with({ path: templateData.pathInput.value });
			templateData.pathLabel.innerText = templateData.pathInput.value;

			if (uri) {
				this.table.acceptEdit(item, uri);
			}
		}


() => {
			hideInputBox();
			templateData.pathInput.value = stringValue;
			this.table.rejectEdit(item);
		}


e => {
			let handled = false;
			if (e.equals(KeyCode.Enter)) {
				accept();
				handled = true;
			} else if (e.equals(KeyCode.Escape)) {
				reject();
				handled = true;
			}

			if (handled) {
				e.preventDefault();
				e.stopPropagation();
			}
		}


() => {
			reject();
		}


() => { clearNode(templateData.buttonBarContainer); }


colors => {
			this.rootElement.style.setProperty('--workspace-trust-selected-color', colors.buttonBackground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-unselected-color', colors.buttonSecondaryBackground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-check-color', colors.debugIconStartForeground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-x-color', colors.editorErrorForeground?.toString() || '');
		}


e => {
			const event = new StandardKeyboardEvent(e);

			if (event.equals(KeyCode.UpArrow) || event.equals(KeyCode.DownArrow)) {
				const navOrder = [this.headerContainer, this.trustedContainer, this.untrustedContainer, this.configurationContainer];
				const currentIndex = navOrder.findIndex(element => {
					return isAncestor(document.activeElement, element);
				});

				let newIndex = currentIndex;
				if (event.equals(KeyCode.DownArrow)) {
					newIndex++;
				} else if (event.equals(KeyCode.UpArrow)) {
					newIndex = Math.max(0, newIndex);
					newIndex--;
				}

				newIndex += navOrder.length;
				newIndex %= navOrder.length;

				navOrder[newIndex].focus();
			} else if (event.equals(KeyCode.Escape)) {
				this.rootElement.focus();
			}
		}


element => {
					return isAncestor(document.activeElement, element);
				}


() => this.render()


key => {
			const property = configurationRegistry.getConfigurationProperties()[key];

			// cannot be configured in workspace
			if (property.scope === ConfigurationScope.APPLICATION || property.scope === ConfigurationScope.MACHINE) {
				return false;
			}

			// If deprecated include only those configured in the workspace
			if (property.deprecationMessage || property.markdownDeprecationMessage) {
				if (restrictedSettings.workspace?.includes(key)) {
					return true;
				}
				if (restrictedSettings.workspaceFolder) {
					for (const workspaceFolderSettings of restrictedSettings.workspaceFolder.values()) {
						if (workspaceFolderSettings.includes(key)) {
							return true;
						}
					}
				}
				return false;
			}

			return true;
		}


ext => ext.local


ext => ext.local!


ext => this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === false


e => {
				if (e) {
					EventHelper.stop(e, true);
				}

				action.run();
			}


async () => {
				await this.workspaceTrustManagementService.setWorkspaceTrust(true);
			}


async () => {
				await this.workspaceTrustManagementService.setParentFolderTrust(true);
			}


async () => {
			await this.workspaceTrustManagementService.setWorkspaceTrust(false);
		}


participant => {
			participant.layout();
		}


class TrustedUriTableVirtualDelegate implements ITableVirtualDelegate<ITrustedUriItem> {
	static readonly HEADER_ROW_HEIGHT = 30;
	static readonly ROW_HEIGHT = 24;
	readonly headerRowHeight = TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT;
	getHeight(item: ITrustedUriItem) {
		return TrustedUriTableVirtualDelegate.ROW_HEIGHT;
	}
}


class TrustedUriActionsColumnRenderer implements ITableRenderer<ITrustedUriItem, IActionsColumnTemplateData> {

	static readonly TEMPLATE_ID = 'actions';

	readonly templateId: string = TrustedUriActionsColumnRenderer.TEMPLATE_ID;

	constructor(
		private readonly table: WorkspaceTrustedUrisTable,
		private readonly currentWorkspaceUri: URI,
		@IUriIdentityService private readonly uriService: IUriIdentityService) { }

	renderTemplate(container: HTMLElement): IActionsColumnTemplateData {
		const element = container.appendChild($('.actions'));
		const actionBar = new ActionBar(element, { animated: false });
		return { actionBar };
	}

	renderElement(item: ITrustedUriItem, index: number, templateData: IActionsColumnTemplateData, height: number | undefined): void {
		templateData.actionBar.clear();

		const canUseOpenDialog = item.uri.scheme === Schemas.file ||
			(
				item.uri.scheme === this.currentWorkspaceUri.scheme &&
				this.uriService.extUri.isEqualAuthority(this.currentWorkspaceUri.authority, item.uri.authority) &&
				!isVirtualResource(item.uri)
			);

		const actions: IAction[] = [];
		if (canUseOpenDialog) {
			actions.push(this.createPickerAction(item));
		}
		actions.push(this.createEditAction(item));
		actions.push(this.createDeleteAction(item));
		templateData.actionBar.push(actions, { icon: true });
	}

	private createEditAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(settingsEditIcon),
			enabled: true,
			id: 'editTrustedUri',
			tooltip: localize('editTrustedUri', "Edit Path"),
			run: () => {
				this.table.edit(item, false);
			}
		};
	}

	private createPickerAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(folderPickerIcon),
			enabled: true,
			id: 'pickerTrustedUri',
			tooltip: localize('pickerTrustedUri', "Open File Picker"),
			run: () => {
				this.table.edit(item, true);
			}
		};
	}

	private createDeleteAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(settingsRemoveIcon),
			enabled: true,
			id: 'deleteTrustedUri',
			tooltip: localize('deleteTrustedUri', "Delete Path"),
			run: async () => {
				await this.table.delete(item);
			}
		};
	}

	disposeTemplate(templateData: IActionsColumnTemplateData): void {
		templateData.actionBar.dispose();
	}

}


class TrustedUriPathColumnRenderer implements ITableRenderer<ITrustedUriItem, ITrustedUriPathColumnTemplateData> {
	static readonly TEMPLATE_ID = 'path';

	readonly templateId: string = TrustedUriPathColumnRenderer.TEMPLATE_ID;
	private currentItem?: ITrustedUriItem;

	constructor(
		private readonly table: WorkspaceTrustedUrisTable,
		@IContextViewService private readonly contextViewService: IContextViewService,
		@IThemeService private readonly themeService: IThemeService,
	) {
	}

	renderTemplate(container: HTMLElement): ITrustedUriPathColumnTemplateData {
		const element = container.appendChild($('.path'));
		const pathLabel = element.appendChild($('div.path-label'));

		const pathInput = new InputBox(element, this.contextViewService, {
			validationOptions: {
				validation: value => this.table.validateUri(value, this.currentItem)
			}
		});

		const disposables = new DisposableStore();
		disposables.add(attachInputBoxStyler(pathInput, this.themeService));

		const renderDisposables = disposables.add(new DisposableStore());

		return {
			element,
			pathLabel,
			pathInput,
			disposables,
			renderDisposables
		};
	}

	renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriPathColumnTemplateData, height: number | undefined): void {
		templateData.renderDisposables.clear();

		this.currentItem = item;
		templateData.renderDisposables.add(this.table.onEdit(async (e) => {
			if (item === e) {
				templateData.element.classList.add('input-mode');
				templateData.pathInput.focus();
				templateData.pathInput.select();
				templateData.element.parentElement!.style.paddingLeft = '0px';
			}
		}));

		// stop double click action from re-rendering the element on the table #125052
		templateData.renderDisposables.add(addDisposableListener(templateData.pathInput.element, EventType.DBLCLICK, e => {
			EventHelper.stop(e);
		}));

		const hideInputBox = () => {
			templateData.element.classList.remove('input-mode');
			templateData.element.parentElement!.style.paddingLeft = '5px';
		};

		const accept = () => {
			hideInputBox();
			const uri = item.uri.with({ path: templateData.pathInput.value });
			templateData.pathLabel.innerText = templateData.pathInput.value;

			if (uri) {
				this.table.acceptEdit(item, uri);
			}
		};

		const reject = () => {
			hideInputBox();
			templateData.pathInput.value = stringValue;
			this.table.rejectEdit(item);
		};

		templateData.renderDisposables.add(addStandardDisposableListener(templateData.pathInput.inputElement, EventType.KEY_DOWN, e => {
			let handled = false;
			if (e.equals(KeyCode.Enter)) {
				accept();
				handled = true;
			} else if (e.equals(KeyCode.Escape)) {
				reject();
				handled = true;
			}

			if (handled) {
				e.preventDefault();
				e.stopPropagation();
			}
		}));
		templateData.renderDisposables.add((addDisposableListener(templateData.pathInput.inputElement, EventType.BLUR, () => {
			reject();
		})));

		const stringValue = item.uri.scheme === Schemas.file ? URI.revive(item.uri).fsPath : item.uri.path;
		templateData.pathInput.value = stringValue;
		templateData.pathLabel.innerText = stringValue;
		templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem);

		// templateData.pathLabel.style.display = '';
	}

	disposeTemplate(templateData: ITrustedUriPathColumnTemplateData): void {
		templateData.disposables.dispose();
		templateData.renderDisposables.dispose();
	}

}


class TrustedUriHostColumnRenderer implements ITableRenderer<ITrustedUriItem, ITrustedUriHostColumnTemplateData> {
	static readonly TEMPLATE_ID = 'host';

	readonly templateId: string = TrustedUriHostColumnRenderer.TEMPLATE_ID;

	constructor(
		@ILabelService private readonly labelService: ILabelService,
	) { }

	renderTemplate(container: HTMLElement): ITrustedUriHostColumnTemplateData {
		const disposables = new DisposableStore();
		const renderDisposables = disposables.add(new DisposableStore());

		const element = container.appendChild($('.host'));
		const hostContainer = element.appendChild($('div.host-label'));
		const buttonBarContainer = element.appendChild($('div.button-bar'));

		return {
			element,
			hostContainer,
			buttonBarContainer,
			disposables,
			renderDisposables
		};
	}

	renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriHostColumnTemplateData, height: number | undefined): void {
		templateData.renderDisposables.clear();
		templateData.renderDisposables.add({ dispose: () => { clearNode(templateData.buttonBarContainer); } });

		templateData.hostContainer.innerText = getHostLabel(this.labelService, item);
		templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem);

		templateData.hostContainer.style.display = '';
		templateData.buttonBarContainer.style.display = 'none';
	}

	disposeTemplate(templateData: ITrustedUriHostColumnTemplateData): void {
		templateData.disposables.dispose();
	}

}


interface ITrustedUriItem {
	parentOfWorkspaceItem: boolean;
	uri: URI;
}


interface IActionsColumnTemplateData {
	readonly actionBar: ActionBar;
}


interface ITrustedUriPathColumnTemplateData {
	element: HTMLElement;
	pathLabel: HTMLElement;
	pathInput: InputBox;
	renderDisposables: DisposableStore;
	disposables: DisposableStore;
}


interface ITrustedUriHostColumnTemplateData {
	element: HTMLElement;
	hostContainer: HTMLElement;
	buttonBarContainer: HTMLElement;
	disposables: DisposableStore;
	renderDisposables: DisposableStore;
}


project(row: ITrustedUriItem): ITrustedUriItem { return row; }


private getIndexOfTrustedUriEntry(item: ITrustedUriItem): number {
		const index = this.trustedUriEntries.indexOf(item);
		if (index === -1) {
			for (let i = 0; i < this.trustedUriEntries.length; i++) {
				if (this.trustedUriEntries[i].uri === item.uri) {
					return i;
				}
			}
		}

		return index;
	}


private selectTrustedUriEntry(item: ITrustedUriItem, focus: boolean = true): void {
		const index = this.getIndexOfTrustedUriEntry(item);
		if (index !== -1) {
			if (focus) {
				this.table.domFocus();
				this.table.setFocus([index]);
			}
			this.table.setSelection([index]);
		}
	}


layout(): void {
		this.table.layout((this.trustedUriEntries.length * TrustedUriTableVirtualDelegate.ROW_HEIGHT) + TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT, undefined);
	}


updateTable(): void {
		const entries = this.trustedUriEntries;
		this.container.classList.toggle('empty', entries.length === 0);

		this.descriptionElement.innerText = entries.length ?
			localize('trustedFoldersDescription', "You trust the following folders, their subfolders, and workspace files.") :
			localize('noTrustedFoldersDescriptions', "You haven't trusted any folders or workspace files yet.");

		this.table.splice(0, Number.POSITIVE_INFINITY, this.trustedUriEntries);
		this.layout();
	}


validateUri(path: string, item?: ITrustedUriItem): IMessage | null {
		if (!item) {
			return null;
		}

		if (item.uri.scheme === 'vscode-vfs') {
			const segments = path.split(posix.sep).filter(s => s.length);
			if (segments.length === 0 && path.startsWith(posix.sep)) {
				return {
					type: MessageType.WARNING,
					content: localize('trustAll', "You will trust all repositories on {0}.", getHostLabel(this.labelService, item))
				};
			}

			if (segments.length === 1) {
				return {
					type: MessageType.WARNING,
					content: localize('trustOrg', "You will trust all repositories and forks under '{0}' on {1}.", segments[0], getHostLabel(this.labelService, item))
				};
			}

			if (segments.length > 2) {
				return {
					type: MessageType.ERROR,
					content: localize('invalidTrust', "You cannot trust individual folders within a repository.", path)
				};
			}
		}

		return null;
	}


acceptEdit(item: ITrustedUriItem, uri: URI) {
		const trustedFolders = this.workspaceTrustManagementService.getTrustedUris();
		const index = trustedFolders.findIndex(u => this.uriService.extUri.isEqual(u, item.uri));

		if (index >= trustedFolders.length || index === -1) {
			trustedFolders.push(uri);
		} else {
			trustedFolders[index] = uri;
		}

		this.workspaceTrustManagementService.setTrustedUris(trustedFolders);
		this._onDidAcceptEdit.fire(item);
	}


rejectEdit(item: ITrustedUriItem) {
		this._onDidRejectEdit.fire(item);
	}


async delete(item: ITrustedUriItem) {
		await this.workspaceTrustManagementService.setUrisTrust([item.uri], false);
		this._onDelete.fire(item);
	}


async edit(item: ITrustedUriItem, usePickerIfPossible?: boolean) {
		const canUseOpenDialog = item.uri.scheme === Schemas.file ||
			(
				item.uri.scheme === this.currentWorkspaceUri.scheme &&
				this.uriService.extUri.isEqualAuthority(this.currentWorkspaceUri.authority, item.uri.authority) &&
				!isVirtualResource(item.uri)
			);
		if (canUseOpenDialog && usePickerIfPossible) {
			const uri = await this.fileDialogService.showOpenDialog({
				canSelectFiles: false,
				canSelectFolders: true,
				canSelectMany: false,
				defaultUri: item.uri,
				openLabel: localize('trustUri', "Trust Folder"),

				title: localize('selectTrustedUri', "Select Folder To Trust")
			});

			if (uri) {
				this.acceptEdit(item, uri[0]);
			} else {
				this.rejectEdit(item);
			}
		} else {
			this.selectTrustedUriEntry(item);
			this._onEdit.fire(item);
		}
	}


getHeight(item: ITrustedUriItem) {
		return TrustedUriTableVirtualDelegate.ROW_HEIGHT;
	}


renderTemplate(container: HTMLElement): IActionsColumnTemplateData {
		const element = container.appendChild($('.actions'));
		const actionBar = new ActionBar(element, { animated: false });
		return { actionBar };
	}


renderElement(item: ITrustedUriItem, index: number, templateData: IActionsColumnTemplateData, height: number | undefined): void {
		templateData.actionBar.clear();

		const canUseOpenDialog = item.uri.scheme === Schemas.file ||
			(
				item.uri.scheme === this.currentWorkspaceUri.scheme &&
				this.uriService.extUri.isEqualAuthority(this.currentWorkspaceUri.authority, item.uri.authority) &&
				!isVirtualResource(item.uri)
			);

		const actions: IAction[] = [];
		if (canUseOpenDialog) {
			actions.push(this.createPickerAction(item));
		}
		actions.push(this.createEditAction(item));
		actions.push(this.createDeleteAction(item));
		templateData.actionBar.push(actions, { icon: true });
	}


private createEditAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(settingsEditIcon),
			enabled: true,
			id: 'editTrustedUri',
			tooltip: localize('editTrustedUri', "Edit Path"),
			run: () => {
				this.table.edit(item, false);
			}
		};
	}


private createPickerAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(folderPickerIcon),
			enabled: true,
			id: 'pickerTrustedUri',
			tooltip: localize('pickerTrustedUri', "Open File Picker"),
			run: () => {
				this.table.edit(item, true);
			}
		};
	}


private createDeleteAction(item: ITrustedUriItem): IAction {
		return <IAction>{
			class: ThemeIcon.asClassName(settingsRemoveIcon),
			enabled: true,
			id: 'deleteTrustedUri',
			tooltip: localize('deleteTrustedUri', "Delete Path"),
			run: async () => {
				await this.table.delete(item);
			}
		};
	}


disposeTemplate(templateData: IActionsColumnTemplateData): void {
		templateData.actionBar.dispose();
	}


renderTemplate(container: HTMLElement): ITrustedUriPathColumnTemplateData {
		const element = container.appendChild($('.path'));
		const pathLabel = element.appendChild($('div.path-label'));

		const pathInput = new InputBox(element, this.contextViewService, {
			validationOptions: {
				validation: value => this.table.validateUri(value, this.currentItem)
			}
		});

		const disposables = new DisposableStore();
		disposables.add(attachInputBoxStyler(pathInput, this.themeService));

		const renderDisposables = disposables.add(new DisposableStore());

		return {
			element,
			pathLabel,
			pathInput,
			disposables,
			renderDisposables
		};
	}


renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriPathColumnTemplateData, height: number | undefined): void {
		templateData.renderDisposables.clear();

		this.currentItem = item;
		templateData.renderDisposables.add(this.table.onEdit(async (e) => {
			if (item === e) {
				templateData.element.classList.add('input-mode');
				templateData.pathInput.focus();
				templateData.pathInput.select();
				templateData.element.parentElement!.style.paddingLeft = '0px';
			}
		}));

		// stop double click action from re-rendering the element on the table #125052
		templateData.renderDisposables.add(addDisposableListener(templateData.pathInput.element, EventType.DBLCLICK, e => {
			EventHelper.stop(e);
		}));

		const hideInputBox = () => {
			templateData.element.classList.remove('input-mode');
			templateData.element.parentElement!.style.paddingLeft = '5px';
		};

		const accept = () => {
			hideInputBox();
			const uri = item.uri.with({ path: templateData.pathInput.value });
			templateData.pathLabel.innerText = templateData.pathInput.value;

			if (uri) {
				this.table.acceptEdit(item, uri);
			}
		};

		const reject = () => {
			hideInputBox();
			templateData.pathInput.value = stringValue;
			this.table.rejectEdit(item);
		};

		templateData.renderDisposables.add(addStandardDisposableListener(templateData.pathInput.inputElement, EventType.KEY_DOWN, e => {
			let handled = false;
			if (e.equals(KeyCode.Enter)) {
				accept();
				handled = true;
			} else if (e.equals(KeyCode.Escape)) {
				reject();
				handled = true;
			}

			if (handled) {
				e.preventDefault();
				e.stopPropagation();
			}
		}));
		templateData.renderDisposables.add((addDisposableListener(templateData.pathInput.inputElement, EventType.BLUR, () => {
			reject();
		})));

		const stringValue = item.uri.scheme === Schemas.file ? URI.revive(item.uri).fsPath : item.uri.path;
		templateData.pathInput.value = stringValue;
		templateData.pathLabel.innerText = stringValue;
		templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem);

		// templateData.pathLabel.style.display = '';
	}


disposeTemplate(templateData: ITrustedUriPathColumnTemplateData): void {
		templateData.disposables.dispose();
		templateData.renderDisposables.dispose();
	}


renderTemplate(container: HTMLElement): ITrustedUriHostColumnTemplateData {
		const disposables = new DisposableStore();
		const renderDisposables = disposables.add(new DisposableStore());

		const element = container.appendChild($('.host'));
		const hostContainer = element.appendChild($('div.host-label'));
		const buttonBarContainer = element.appendChild($('div.button-bar'));

		return {
			element,
			hostContainer,
			buttonBarContainer,
			disposables,
			renderDisposables
		};
	}


renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriHostColumnTemplateData, height: number | undefined): void {
		templateData.renderDisposables.clear();
		templateData.renderDisposables.add({ dispose: () => { clearNode(templateData.buttonBarContainer); } });

		templateData.hostContainer.innerText = getHostLabel(this.labelService, item);
		templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem);

		templateData.hostContainer.style.display = '';
		templateData.buttonBarContainer.style.display = 'none';
	}


disposeTemplate(templateData: ITrustedUriHostColumnTemplateData): void {
		templateData.disposables.dispose();
	}


protected createEditor(parent: HTMLElement): void {
		this.rootElement = append(parent, $('.workspace-trust-editor', { tabindex: '0' }));
		this.rootElement.style.visibility = 'hidden';

		this.createHeaderElement(this.rootElement);

		const scrollableContent = $('.workspace-trust-editor-body');
		this.bodyScrollBar = this._register(new DomScrollableElement(scrollableContent, {
			horizontal: ScrollbarVisibility.Hidden,
			vertical: ScrollbarVisibility.Auto,
		}));

		append(this.rootElement, this.bodyScrollBar.getDomNode());

		this.createAffectedFeaturesElement(scrollableContent);
		this.createConfigurationElement(scrollableContent);

		this._register(attachStylerCallback(this.themeService, { debugIconStartForeground, editorErrorForeground, buttonBackground, buttonSecondaryBackground }, colors => {
			this.rootElement.style.setProperty('--workspace-trust-selected-color', colors.buttonBackground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-unselected-color', colors.buttonSecondaryBackground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-check-color', colors.debugIconStartForeground?.toString() || '');
			this.rootElement.style.setProperty('--workspace-trust-x-color', colors.editorErrorForeground?.toString() || '');
		}));

		// Navigate page with keyboard
		this._register(addDisposableListener(this.rootElement, EventType.KEY_DOWN, e => {
			const event = new StandardKeyboardEvent(e);

			if (event.equals(KeyCode.UpArrow) || event.equals(KeyCode.DownArrow)) {
				const navOrder = [this.headerContainer, this.trustedContainer, this.untrustedContainer, this.configurationContainer];
				const currentIndex = navOrder.findIndex(element => {
					return isAncestor(document.activeElement, element);
				});

				let newIndex = currentIndex;
				if (event.equals(KeyCode.DownArrow)) {
					newIndex++;
				} else if (event.equals(KeyCode.UpArrow)) {
					newIndex = Math.max(0, newIndex);
					newIndex--;
				}

				newIndex += navOrder.length;
				newIndex %= navOrder.length;

				navOrder[newIndex].focus();
			} else if (event.equals(KeyCode.Escape)) {
				this.rootElement.focus();
			}
		}));
	}


override focus() {
		this.rootElement.focus();
	}


override async setInput(input: WorkspaceTrustEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> {

		await super.setInput(input, options, context, token);
		if (token.isCancellationRequested) { return; }

		await this.workspaceTrustManagementService.workspaceTrustInitialized;
		this.registerListeners();
		this.render();
	}


private registerListeners(): void {
		this._register(this.extensionWorkbenchService.onChange(() => this.render()));
		this._register(this.configurationService.onDidChangeRestrictedSettings(() => this.render()));
		this._register(this.workspaceTrustManagementService.onDidChangeTrust(() => this.render()));
		this._register(this.workspaceTrustManagementService.onDidChangeTrustedFolders(() => this.render()));
	}


private getHeaderContainerClass(trusted: boolean): string {
		if (trusted) {
			return 'workspace-trust-header workspace-trust-trusted';
		}

		return 'workspace-trust-header workspace-trust-untrusted';
	}


private getHeaderTitleText(trusted: boolean): string {
		if (trusted) {
			if (this.workspaceTrustManagementService.isWorkspaceTrustForced()) {
				return localize('trustedUnsettableWindow', "This window is trusted");
			}

			switch (this.workspaceService.getWorkbenchState()) {
				case WorkbenchState.EMPTY:
					return localize('trustedHeaderWindow', "You trust this window");
				case WorkbenchState.FOLDER:
					return localize('trustedHeaderFolder', "You trust this folder");
				case WorkbenchState.WORKSPACE:
					return localize('trustedHeaderWorkspace', "You trust this workspace");
			}
		}

		return localize('untrustedHeader', "You are in Restricted Mode");
	}


private getHeaderTitleIconClassNames(trusted: boolean): string[] {
		return shieldIcon.classNamesArray;
	}


private getFeaturesHeaderText(trusted: boolean): [string, string] {
		let title: string = '';
		let subTitle: string = '';

		switch (this.workspaceService.getWorkbenchState()) {
			case WorkbenchState.EMPTY: {
				title = trusted ? localize('trustedWindow', "In a Trusted Window") : localize('untrustedWorkspace', "In Restricted Mode");
				subTitle = trusted ? localize('trustedWindowSubtitle', "You trust the authors of the files in the current window. All features are enabled:") :
					localize('untrustedWindowSubtitle', "You do not trust the authors of the files in the current window. The following features are disabled:");
				break;
			}
			case WorkbenchState.FOLDER: {
				title = trusted ? localize('trustedFolder', "In a Trusted Folder") : localize('untrustedWorkspace', "In Restricted Mode");
				subTitle = trusted ? localize('trustedFolderSubtitle', "You trust the authors of the files in the current folder. All features are enabled:") :
					localize('untrustedFolderSubtitle', "You do not trust the authors of the files in the current folder. The following features are disabled:");
				break;
			}
			case WorkbenchState.WORKSPACE: {
				title = trusted ? localize('trustedWorkspace', "In a Trusted Workspace") : localize('untrustedWorkspace', "In Restricted Mode");
				subTitle = trusted ? localize('trustedWorkspaceSubtitle', "You trust the authors of the files in the current workspace. All features are enabled:") :
					localize('untrustedWorkspaceSubtitle', "You do not trust the authors of the files in the current workspace. The following features are disabled:");
				break;
			}
		}

		return [title, subTitle];
	}


@debounce(100)
	private async render() {
		if (this.rendering) {
			return;
		}

		this.rendering = true;
		this.rerenderDisposables.clear();

		const isWorkspaceTrusted = this.workspaceTrustManagementService.isWorkspaceTrusted();
		this.rootElement.classList.toggle('trusted', isWorkspaceTrusted);
		this.rootElement.classList.toggle('untrusted', !isWorkspaceTrusted);

		// Header Section
		this.headerTitleText.innerText = this.getHeaderTitleText(isWorkspaceTrusted);
		this.headerTitleIcon.className = 'workspace-trust-title-icon';
		this.headerTitleIcon.classList.add(...this.getHeaderTitleIconClassNames(isWorkspaceTrusted));
		this.headerDescription.innerText = '';

		const headerDescriptionText = append(this.headerDescription, $('div'));
		headerDescriptionText.innerText = isWorkspaceTrusted ?
			localize('trustedDescription', "All features are enabled because trust has been granted to the workspace.") :
			localize('untrustedDescription', "{0} is in a restricted mode intended for safe code browsing.", product.nameShort);

		const headerDescriptionActions = append(this.headerDescription, $('div'));
		const headerDescriptionActionsText = localize({ key: 'workspaceTrustEditorHeaderActions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[Configure your settings]({0}) or [learn more](https://aka.ms/vscode-workspace-trust).", `command:workbench.trust.configure`);
		for (const node of parseLinkedText(headerDescriptionActionsText).nodes) {
			if (typeof node === 'string') {
				append(headerDescriptionActions, document.createTextNode(node));
			} else {
				this.rerenderDisposables.add(this.instantiationService.createInstance(Link, headerDescriptionActions, { ...node, tabIndex: -1 }, {}));
			}
		}

		this.headerContainer.className = this.getHeaderContainerClass(isWorkspaceTrusted);
		this.rootElement.setAttribute('aria-label', `${localize('root element label', "Manage Workspace Trust")}:  ${this.headerContainer.innerText}`);

		// Settings
		const restrictedSettings = this.configurationService.restrictedSettings;
		const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
		const settingsRequiringTrustedWorkspaceCount = restrictedSettings.default.filter(key => {
			const property = configurationRegistry.getConfigurationProperties()[key];

			// cannot be configured in workspace
			if (property.scope === ConfigurationScope.APPLICATION || property.scope === ConfigurationScope.MACHINE) {
				return false;
			}

			// If deprecated include only those configured in the workspace
			if (property.deprecationMessage || property.markdownDeprecationMessage) {
				if (restrictedSettings.workspace?.includes(key)) {
					return true;
				}
				if (restrictedSettings.workspaceFolder) {
					for (const workspaceFolderSettings of restrictedSettings.workspaceFolder.values()) {
						if (workspaceFolderSettings.includes(key)) {
							return true;
						}
					}
				}
				return false;
			}

			return true;
		}).length;

		// Features List
		this.renderAffectedFeatures(settingsRequiringTrustedWorkspaceCount, this.getExtensionCount());

		// Configuration Tree
		this.workspaceTrustedUrisTable.updateTable();

		this.bodyScrollBar.getDomNode().style.height = `calc(100% - ${this.headerContainer.clientHeight}px)`;
		this.bodyScrollBar.scanDomNode();
		this.rootElement.style.visibility = '';
		this.rendering = false;
	}


private getExtensionCount(): number {
		const set = new Set<string>();

		const inVirtualWorkspace = isVirtualWorkspace(this.workspaceService.getWorkspace());
		const localExtensions = this.extensionWorkbenchService.local.filter(ext => ext.local).map(ext => ext.local!);

		for (const extension of localExtensions) {
			const enablementState = this.extensionEnablementService.getEnablementState(extension);
			if (enablementState !== EnablementState.EnabledGlobally && enablementState !== EnablementState.EnabledWorkspace &&
				enablementState !== EnablementState.DisabledByTrustRequirement && enablementState !== EnablementState.DisabledByExtensionDependency) {
				continue;
			}

			if (inVirtualWorkspace && this.extensionManifestPropertiesService.getExtensionVirtualWorkspaceSupportType(extension.manifest) === false) {
				continue;
			}

			if (this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(extension.manifest) !== true) {
				set.add(extension.identifier.id);
				continue;
			}

			const dependencies = getExtensionDependencies(localExtensions, extension);
			if (dependencies.some(ext => this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === false)) {
				set.add(extension.identifier.id);
			}
		}

		return set.size;
	}


private createHeaderElement(parent: HTMLElement): void {
		this.headerContainer = append(parent, $('.workspace-trust-header', { tabIndex: '0' }));
		this.headerTitleContainer = append(this.headerContainer, $('.workspace-trust-title'));
		this.headerTitleIcon = append(this.headerTitleContainer, $('.workspace-trust-title-icon'));
		this.headerTitleText = append(this.headerTitleContainer, $('.workspace-trust-title-text'));
		this.headerDescription = append(this.headerContainer, $('.workspace-trust-description'));
	}


private createConfigurationElement(parent: HTMLElement): void {
		this.configurationContainer = append(parent, $('.workspace-trust-settings', { tabIndex: '0' }));
		const configurationTitle = append(this.configurationContainer, $('.workspace-trusted-folders-title'));
		configurationTitle.innerText = localize('trustedFoldersAndWorkspaces', "Trusted Folders & Workspaces");

		this.workspaceTrustedUrisTable = this._register(this.instantiationService.createInstance(WorkspaceTrustedUrisTable, this.configurationContainer));
	}


private createAffectedFeaturesElement(parent: HTMLElement): void {
		this.affectedFeaturesContainer = append(parent, $('.workspace-trust-features'));
		this.trustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.trusted', { tabIndex: '0' }));
		this.untrustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.untrusted', { tabIndex: '0' }));
	}


private async renderAffectedFeatures(numSettings: number, numExtensions: number): Promise<void> {
		clearNode(this.trustedContainer);
		clearNode(this.untrustedContainer);

		// Trusted features
		const [trustedTitle, trustedSubTitle] = this.getFeaturesHeaderText(true);

		this.renderLimitationsHeaderElement(this.trustedContainer, trustedTitle, trustedSubTitle);
		const trustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ?
			[
				localize('trustedTasks', "Tasks are allowed to run"),
				localize('trustedDebugging', "Debugging is enabled"),
				localize('trustedExtensions', "All extensions are enabled")
			] :
			[
				localize('trustedTasks', "Tasks are allowed to run"),
				localize('trustedDebugging', "Debugging is enabled"),
				localize('trustedSettings', "All workspace settings are applied"),
				localize('trustedExtensions', "All extensions are enabled")
			];
		this.renderLimitationsListElement(this.trustedContainer, trustedContainerItems, checkListIcon.classNamesArray);

		// Restricted Mode features
		const [untrustedTitle, untrustedSubTitle] = this.getFeaturesHeaderText(false);

		this.renderLimitationsHeaderElement(this.untrustedContainer, untrustedTitle, untrustedSubTitle);
		const untrustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ?
			[
				localize('untrustedTasks', "Tasks are not allowed to run"),
				localize('untrustedDebugging', "Debugging is disabled"),
				localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`)
			] :
			[
				localize('untrustedTasks', "Tasks are not allowed to run"),
				localize('untrustedDebugging', "Debugging is disabled"),
				numSettings ? localize({ key: 'untrustedSettings', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} workspace settings]({1}) are not applied", numSettings, 'command:settings.filterUntrusted') : localize('no untrustedSettings', "Workspace settings requiring trust are not applied"),
				localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`)
			];
		this.renderLimitationsListElement(this.untrustedContainer, untrustedContainerItems, xListIcon.classNamesArray);

		if (this.workspaceTrustManagementService.isWorkspaceTrusted()) {
			if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) {
				this.addDontTrustButtonToElement(this.untrustedContainer);
			} else {
				this.addTrustedTextToElement(this.untrustedContainer);
			}
		} else {
			if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) {
				this.addTrustButtonToElement(this.trustedContainer);
			}
		}
	}


private createButtonRow(parent: HTMLElement, actions: Action | Action[], enabled?: boolean): void {
		const buttonRow = append(parent, $('.workspace-trust-buttons-row'));
		const buttonContainer = append(buttonRow, $('.workspace-trust-buttons'));
		const buttonBar = this.rerenderDisposables.add(new ButtonBar(buttonContainer));

		if (actions instanceof Action) {
			actions = [actions];
		}

		for (const action of actions) {
			const button =
				action instanceof ChoiceAction && action.menu?.length ?
					buttonBar.addButtonWithDropdown({
						title: true,
						actions: action.menu ?? [],
						contextMenuProvider: this.contextMenuService
					}) :
					buttonBar.addButton();

			button.label = action.label;
			button.enabled = enabled !== undefined ? enabled : action.enabled;

			this.rerenderDisposables.add(button.onDidClick(e => {
				if (e) {
					EventHelper.stop(e, true);
				}

				action.run();
			}));

			this.rerenderDisposables.add(attachButtonStyler(button, this.themeService));
		}
	}


private addTrustButtonToElement(parent: HTMLElement): void {
		const trustActions = [
			new Action('workspace.trust.button.action.grant', localize('trustButton', "Trust"), undefined, true, async () => {
				await this.workspaceTrustManagementService.setWorkspaceTrust(true);
			})
		];

		if (this.workspaceTrustManagementService.canSetParentFolderTrust()) {
			const workspaceIdentifier = toWorkspaceIdentifier(this.workspaceService.getWorkspace()) as ISingleFolderWorkspaceIdentifier;
			const { name } = splitName(splitName(workspaceIdentifier.uri.fsPath).parentPath);

			const trustMessageElement = append(parent, $('.trust-message-box'));
			trustMessageElement.innerText = localize('trustMessage', "Trust the authors of all files in the current folder or its parent '{0}'.", name);

			trustActions.push(new Action('workspace.trust.button.action.grantParent', localize('trustParentButton', "Trust Parent"), undefined, true, async () => {
				await this.workspaceTrustManagementService.setParentFolderTrust(true);
			}));
		}

		this.createButtonRow(parent, trustActions);
	}


private addDontTrustButtonToElement(parent: HTMLElement): void {
		this.createButtonRow(parent, new Action('workspace.trust.button.action.deny', localize('dontTrustButton', "Don't Trust"), undefined, true, async () => {
			await this.workspaceTrustManagementService.setWorkspaceTrust(false);
		}));
	}


private addTrustedTextToElement(parent: HTMLElement): void {
		if (this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY) {
			return;
		}

		const textElement = append(parent, $('.workspace-trust-untrusted-description'));
		if (!this.workspaceTrustManagementService.isWorkspaceTrustForced()) {
			textElement.innerText = this.workspaceService.getWorkbenchState() === WorkbenchState.WORKSPACE ? localize('untrustedWorkspaceReason', "This workspace is trusted via the bolded entries in the trusted folders below.") : localize('untrustedFolderReason', "This folder is trusted via the bolded entries in the the trusted folders below.");
		} else {
			textElement.innerText = localize('trustedForcedReason', "This window is trusted by nature of the workspace that is opened.");
		}
	}


private renderLimitationsHeaderElement(parent: HTMLElement, headerText: string, subtitleText: string): void {
		const limitationsHeaderContainer = append(parent, $('.workspace-trust-limitations-header'));
		const titleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-title'));
		const textElement = append(titleElement, $('.workspace-trust-limitations-title-text'));
		const subtitleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-subtitle'));

		textElement.innerText = headerText;
		subtitleElement.innerText = subtitleText;
	}


private renderLimitationsListElement(parent: HTMLElement, limitations: string[], iconClassNames: string[]): void {
		const listContainer = append(parent, $('.workspace-trust-limitations-list-container'));
		const limitationsList = append(listContainer, $('ul'));
		for (const limitation of limitations) {
			const limitationListItem = append(limitationsList, $('li'));
			const icon = append(limitationListItem, $('.list-item-icon'));
			const text = append(limitationListItem, $('.list-item-text'));

			icon.classList.add(...iconClassNames);

			const linkedText = parseLinkedText(limitation);
			for (const node of linkedText.nodes) {
				if (typeof node === 'string') {
					append(text, document.createTextNode(node));
				} else {
					this.rerenderDisposables.add(this.instantiationService.createInstance(Link, text, { ...node, tabIndex: -1 }, {}));
				}
			}
		}
	}


layout(dimension: Dimension): void {
		if (!this.isVisible()) {
			return;
		}

		this.workspaceTrustedUrisTable.layout();

		this.layoutParticipants.forEach(participant => {
			participant.layout();
		});

		this.bodyScrollBar.scanDomNode();
	}


export function Root() {
  const store = createStore(reducers);

  return (
    <BrowserRouter>
      <Provider store={store}>
        <Application />
      </Provider>
    </BrowserRouter>
  );
}


async (req: Request, res: Response) => {
  const { user, error, errorCode } = await UserServiceInstance.findById(
    req.userId
  );

  if (error && errorCode) return res.status(errorCode).json({ error });

  return res.status(200).json(user);
}


async (req: Request, res: Response) => {
  const data: Partial<IUser> = req.body;

  // Don't allow updating other fields
  const allowedData = userSchema.update.noUnknown().cast(data);

  const { user, error, errorCode } = await UserServiceInstance.update(
    req.userId,
    allowedData
  );

  if (error && errorCode) return res.status(errorCode).json({ error });

  return res.status(200).json({ user, message: "Successfully updated user" });
}


async (req: Request, res: Response) => {
  const { error, errorCode } = await UserServiceInstance.delete(req.userId);

  if (error && errorCode) return res.status(errorCode).json({ error });

  return res.status(200).json({ message: "Successfully deleted user" });
}


() => {
  test.each([null, 'string', {}])(
    'Throws when middleware is not an array (%j)',
    (value) => {
      // Act
      const act = () => new HttpClient(value as [HippityMiddleware])

      // Assert
      expect(act).toThrow(new TypeError('Middleware stack must be an array'))
    }
  )
}


(value) => {
      // Act
      const act = () => new HttpClient(value as [HippityMiddleware])

      // Assert
      expect(act).toThrow(new TypeError('Middleware stack must be an array'))
    }


() => new HttpClient(value as [HippityMiddleware])


() => {
  it('Throws exception when send is called with no middleware registered', async () => {
    // Arrange
    const sut = new HttpClient()

    // Act
    const act = sut.send({})

    // Assert
    await expect(act).rejects.toThrow(
      new Error(
        'Reached end of pipeline. Use a middleware which terminates the pipeline.'
      )
    )
  })

  it('Throws if no middleware terminates', async () => {
    // Arrange
    const sut = new HttpClient().use((r, n) => n(r))

    // Act
    const act = sut.send({})

    // Assert
    await expect(act).rejects.toThrow(
      new Error(
        'Reached end of pipeline. Use a middleware which terminates the pipeline.'
      )
    )
  })

  it('Calls middleware in reverse order', async () => {
    // Arrange
    let order = ''
    const sut = new HttpClient()
      .use(() => {
        order += '1'
        return Promise.resolve({ status: 200, success: true })
      })
      .use((r, n) => {
        order += '2'
        return n(r)
      })
      .use((r, n) => {
        order += '3'
        return n(r)
      })

    // Act
    await sut.send({})

    // Assert
    expect(order).toEqual('321')
  })

  it('Calls terminator last', async () => {
    // Arrange
    let order = ''
    const sut = new HttpClient()
      .use(() => {
        order += '0'
        return Promise.resolve({ status: 200, success: true })
      })
      .use((r, n) => {
        order += '1'
        return n(r)
      })

    // Act
    await sut.send({})

    // Assert
    expect(order).toEqual('10')
  })

  it('Lets middleware switch request', async () => {
    // Arrange
    const middleware = jest.fn(() =>
      Promise.resolve({ status: 200, success: true })
    )
    const sut = new HttpClient()
      .use(middleware)
      .use((_, n) => n({ changed: true }))

    // Act
    await sut.send({})

    // Assert
    expect(middleware).toHaveBeenCalledWith(
      { changed: true },
      expect.any(Function)
    )
  })

  it('Does not call middleware if one terminates earlier in the pipeline', async () => {
    // Arrange
    const middleware = jest.fn()
    const sut = new HttpClient()
      .use(middleware)
      .use(() => Promise.resolve({ status: 200, success: true }))

    // Act
    await sut.send({})

    // Assert
    expect(middleware).not.toHaveBeenCalled()
  })

  it('Uses current request if middleware calls next without a request', async () => {
    // Arrange
    const middleware = jest.fn(() =>
      Promise.resolve({ status: 200, success: true })
    )

    const sut = new HttpClient().use((_, n) => n()).use(middleware)

    // Act
    await sut.send({ changed: false })

    // Assert
    expect(middleware).toHaveBeenCalledWith(
      { changed: false },
      expect.any(Function)
    )
  })
}


async () => {
    // Arrange
    const sut = new HttpClient()

    // Act
    const act = sut.send({})

    // Assert
    await expect(act).rejects.toThrow(
      new Error(
        'Reached end of pipeline. Use a middleware which terminates the pipeline.'
      )
    )
  }


async () => {
    // Arrange
    const sut = new HttpClient().use((r, n) => n(r))

    // Act
    const act = sut.send({})

    // Assert
    await expect(act).rejects.toThrow(
      new Error(
        'Reached end of pipeline. Use a middleware which terminates the pipeline.'
      )
    )
  }


(r, n) => n(r)


async () => {
    // Arrange
    let order = ''
    const sut = new HttpClient()
      .use(() => {
        order += '1'
        return Promise.resolve({ status: 200, success: true })
      })
      .use((r, n) => {
        order += '2'
        return n(r)
      })
      .use((r, n) => {
        order += '3'
        return n(r)
      })

    // Act
    await sut.send({})

    // Assert
    expect(order).toEqual('321')
  }


() => {
        order += '1'
        return Promise.resolve({ status: 200, success: true })
      }


(r, n) => {
        order += '2'
        return n(r)
      }