text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* 输出数据配置 */ export interface OutputDataConfig { /** * cos输出桶 注意:此字段可能返回 null,表示取不到有效值。 */ CosOutputBucket?: string /** * cos输出key前缀 注意:此字段可能返回 null,表示取不到有效值。 */ CosOutputKeyPrefix?: string /** * 文件系统输出,如果指定了文件系统,那么Cos输出会被忽略 注意:此字段可能返回 null,表示取不到有效值。 */ FileSystemDataSource?: FileSystemDataSource } /** * StopTrainingJob返回参数结构体 */ export interface StopTrainingJobResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 计费标签 */ export interface BillingLabel { /** * 计费项标识 注意:此字段可能返回 null,表示取不到有效值。 */ Label: string /** * 存储大小 */ VolumeSize: number /** * 计费状态 None: 不计费 StorageOnly: 仅存储计费 Computing: 计算和存储都计费 */ Status: string } /** * 环境变量 */ export interface EnvConfig { /** * 名称 */ Name: string /** * 值 */ Value: string } /** * CreateNotebookInstance请求参数结构体 */ export interface CreateNotebookInstanceRequest { /** * Notebook实例名称,不能超过63个字符 规则:“^\[a-zA-Z0-9\](-\*\[a-zA-Z0-9\])\*$” */ NotebookInstanceName: string /** * Notebook算力类型 参考https://cloud.tencent.com/document/product/851/41239 */ InstanceType: string /** * 数据卷大小(GB) 用户持久化Notebook实例的数据 */ VolumeSizeInGB: number /** * 外网访问权限,可取值Enabled/Disabled 开启后,Notebook实例可以具有访问外网80,443端口的权限 */ DirectInternetAccess?: string /** * Root用户权限,可取值Enabled/Disabled 开启后,Notebook实例可以切换至root用户执行命令 */ RootAccess?: string /** * 子网ID 如果需要Notebook实例访问VPC内的资源,则需要选择对应的子网 */ SubnetId?: string /** * 生命周期脚本名称 必须是已存在的生命周期脚本,具体参考https://cloud.tencent.com/document/product/851/43140 */ LifecycleScriptsName?: string /** * 默认存储库名称 可以是已创建的存储库名称或者已https://开头的公共git库 参考https://cloud.tencent.com/document/product/851/43139 */ DefaultCodeRepository?: string /** * 其他存储库列表 每个元素可以是已创建的存储库名称或者已https://开头的公共git库 参考https://cloud.tencent.com/document/product/851/43139 */ AdditionalCodeRepositories?: Array<string> /** * 已弃用,请使用ClsConfig配置。 是否开启CLS日志服务,可取值Enabled/Disabled,默认为Disabled 开启后,Notebook运行的日志会收集到CLS中,CLS会产生费用,请根据需要选择 */ ClsAccess?: string /** * 自动停止配置 选择定时停止Notebook实例 */ StoppingCondition?: StoppingCondition /** * 自动停止,可取值Enabled/Disabled 取值为Disabled的时候StoppingCondition将被忽略 取值为Enabled的时候读取StoppingCondition作为自动停止的配置 */ AutoStopping?: string /** * 接入日志的配置,默认接入免费日志 */ ClsConfig?: ClsConfig } /** * DescribeNotebookSummary请求参数结构体 */ export type DescribeNotebookSummaryRequest = null /** * 二级状态流水 */ export interface SecondaryStatusTransition { /** * 状态开始时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartTime: string /** * 状态结束时间 注意:此字段可能返回 null,表示取不到有效值。 */ EndTime: string /** * 状态名 注意:此字段可能返回 null,表示取不到有效值。 */ Status: string /** * 状态详情 注意:此字段可能返回 null,表示取不到有效值。 */ StatusMessage: string } /** * DescribeNotebookInstance请求参数结构体 */ export interface DescribeNotebookInstanceRequest { /** * Notebook实例名称 规则:“^\[a-zA-Z0-9\](-\*\[a-zA-Z0-9\])\*$” */ NotebookInstanceName: string } /** * DeleteNotebookInstance返回参数结构体 */ export interface DeleteNotebookInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * notebook实例概览 */ export interface NotebookInstanceSummary { /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreationTime: string /** * 最近修改时间 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifiedTime: string /** * notebook实例名字 注意:此字段可能返回 null,表示取不到有效值。 */ NotebookInstanceName: string /** * notebook实例状态,取值范围: Pending: 创建中 Inservice: 运行中 Stopping: 停止中 Stopped: 已停止 Failed: 失败 注意:此字段可能返回 null,表示取不到有效值。 */ NotebookInstanceStatus: string /** * 算力类型 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceType: string /** * 实例ID 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceId: string /** * 启动时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartupTime: string /** * 运行截止时间 注意:此字段可能返回 null,表示取不到有效值。 */ Deadline: string /** * 自动停止配置 注意:此字段可能返回 null,表示取不到有效值。 */ StoppingCondition: StoppingCondition /** * 是否是预付费实例 注意:此字段可能返回 null,表示取不到有效值。 */ Prepay: boolean /** * 计费标识 注意:此字段可能返回 null,表示取不到有效值。 */ BillingLabel: BillingLabel /** * 运行时长,秒 注意:此字段可能返回 null,表示取不到有效值。 */ RuntimeInSeconds: number /** * 剩余时长,秒 注意:此字段可能返回 null,表示取不到有效值。 */ RemainTimeInSeconds: number } /** * 存储库Git相关配置 */ export interface GitConfig { /** * git地址 */ RepositoryUrl: string /** * 代码分支 注意:此字段可能返回 null,表示取不到有效值。 */ Branch?: string } /** * 存储库列表 */ export interface CodeRepoSummary { /** * 创建时间 */ CreationTime: string /** * 更新时间 */ LastModifiedTime: string /** * 存储库名称 */ CodeRepositoryName: string /** * Git配置 */ GitConfig: GitConfig /** * 是否有Git凭证 */ NoSecret: boolean } /** * 计算资源配置 */ export interface ResourceConfig { /** * 计算实例数量 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceCount: number /** * 计算实例类型 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceType: string /** * 挂载CBS大小(GB) 注意:此字段可能返回 null,表示取不到有效值。 */ VolumeSizeInGB?: number } /** * DeleteNotebookLifecycleScript返回参数结构体 */ export interface DeleteNotebookLifecycleScriptResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeNotebookLifecycleScripts请求参数结构体 */ export interface DescribeNotebookLifecycleScriptsRequest { /** * 偏移量,默认为0 */ Offset?: number /** * 返回数量,默认为20 */ Limit?: number /** * 过滤条件。 instance-name - String - 是否必填:否 -(过滤条件)按照名称过滤。 search-by-name - String - 是否必填:否 -(过滤条件)按照名称检索,模糊匹配。 */ Filters?: Array<Filter> /** * 排序规则。默认取Descending Descending 按更新时间降序 Ascending 按更新时间升序 */ SortOrder?: string } /** * Git凭证 */ export interface GitSecret { /** * 无秘钥,默认选项 */ NoSecret?: boolean /** * Git用户名密码base64编码后的字符串 编码前的内容应为Json字符串,如 {"UserName": "用户名", "Password":"密码"} */ Secret?: string } /** * DeleteCodeRepository请求参数结构体 */ export interface DeleteCodeRepositoryRequest { /** * 存储库名称 */ CodeRepositoryName: string } /** * DescribeCodeRepository返回参数结构体 */ export interface DescribeCodeRepositoryResponse { /** * 创建时间 */ CreationTime?: string /** * 更新时间 */ LastModifiedTime?: string /** * 存储库名称 */ CodeRepositoryName?: string /** * Git存储配置 */ GitConfig?: GitConfig /** * 是否有Git凭证 */ NoSecret?: boolean /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 输入数据配置 */ export interface InputDataConfig { /** * 通道名 注意:此字段可能返回 null,表示取不到有效值。 */ ChannelName?: string /** * 数据源配置 注意:此字段可能返回 null,表示取不到有效值。 */ DataSource?: DataSource /** * 输入类型 注意:此字段可能返回 null,表示取不到有效值。 */ InputMode?: string /** * 文件类型 注意:此字段可能返回 null,表示取不到有效值。 */ ContentType?: string } /** * StartNotebookInstance返回参数结构体 */ export interface StartNotebookInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * UpdateCodeRepository返回参数结构体 */ export interface UpdateCodeRepositoryResponse { /** * 存储库名称 */ CodeRepositoryName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateNotebookInstance返回参数结构体 */ export interface CreateNotebookInstanceResponse { /** * Notebook实例名字 */ NotebookInstanceName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 文件系统输入数据源 */ export interface FileSystemDataSource { /** * 文件系统目录 注意:此字段可能返回 null,表示取不到有效值。 */ DirectoryPath?: string /** * 文件系统类型 注意:此字段可能返回 null,表示取不到有效值。 */ FileSystemType?: string /** * 文件系统访问模式 注意:此字段可能返回 null,表示取不到有效值。 */ FileSystemAccessMode?: string /** * 文件系统ID 注意:此字段可能返回 null,表示取不到有效值。 */ FileSystemId?: string } /** * notebook生命周期脚本实例概览 */ export interface NotebookLifecycleScriptsSummary { /** * notebook生命周期脚本名称 */ NotebookLifecycleScriptsName: string /** * 创建时间 */ CreationTime: string /** * 修改时间 */ LastModifiedTime: string } /** * StopTrainingJob请求参数结构体 */ export interface StopTrainingJobRequest { /** * 训练任务名称 */ TrainingJobName: string } /** * UpdateNotebookInstance返回参数结构体 */ export interface UpdateNotebookInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 接入CLS服务的配置 */ export interface ClsConfig { /** * 接入类型,可选项为free、customer */ Type: string /** * 自定义CLS的日志集ID,只有当Type为customer时生效 */ LogSetId?: string /** * 自定义CLS的日志主题ID,只有当Type为customer时生效 */ TopicId?: string } /** * UpdateNotebookLifecycleScript请求参数结构体 */ export interface UpdateNotebookLifecycleScriptRequest { /** * notebook生命周期脚本名称 */ NotebookLifecycleScriptsName: string /** * 创建脚本,base64编码 base64后的脚本长度不能超过16384个字符 */ CreateScript?: string /** * 启动脚本,base64编码 base64后的脚本长度不能超过16384个字符 */ StartScript?: string } /** * UpdateNotebookInstance请求参数结构体 */ export interface UpdateNotebookInstanceRequest { /** * Notebook实例名称 规则:“^\[a-zA-Z0-9\](-\*\[a-zA-Z0-9\])\*$” */ NotebookInstanceName: string /** * 角色的资源描述 */ RoleArn?: string /** * Root访问权限 */ RootAccess?: string /** * 数据卷大小(GB) */ VolumeSizeInGB?: number /** * 算力资源类型 */ InstanceType?: string /** * notebook生命周期脚本名称 */ LifecycleScriptsName?: string /** * 是否解绑生命周期脚本,默认 false。 该值为true时,LifecycleScriptsName将被忽略 */ DisassociateLifecycleScript?: boolean /** * 默认存储库名称 可以是已创建的存储库名称或者已https://开头的公共git库 */ DefaultCodeRepository?: string /** * 其他存储库列表 每个元素可以是已创建的存储库名称或者已https://开头的公共git库 */ AdditionalCodeRepositories?: Array<string> /** * 是否取消关联默认存储库,默认false 该值为true时,DefaultCodeRepository将被忽略 */ DisassociateDefaultCodeRepository?: boolean /** * 是否取消关联其他存储库,默认false 该值为true时,AdditionalCodeRepositories将被忽略 */ DisassociateAdditionalCodeRepositories?: boolean /** * 已弃用,请使用ClsConfig配置。是否开启CLS日志服务,可取值Enabled/Disabled */ ClsAccess?: string /** * 自动停止,可取值Enabled/Disabled 取值为Disabled的时候StoppingCondition将被忽略 取值为Enabled的时候读取StoppingCondition作为自动停止的配置 */ AutoStopping?: string /** * 自动停止配置,只在AutoStopping为Enabled的时候生效 */ StoppingCondition?: StoppingCondition /** * 接入日志的配置,默认使用免费日志服务。 */ ClsConfig?: ClsConfig } /** * CreatePresignedNotebookInstanceUrl请求参数结构体 */ export interface CreatePresignedNotebookInstanceUrlRequest { /** * Notebook实例名称 规则:“^\[a-zA-Z0-9\](-\*\[a-zA-Z0-9\])\*$” */ NotebookInstanceName: string /** * session有效时间,秒,取值范围[1800, 43200] */ SessionExpirationDurationInSeconds?: number } /** * CreateNotebookLifecycleScript请求参数结构体 */ export interface CreateNotebookLifecycleScriptRequest { /** * Notebook生命周期脚本名称 */ NotebookLifecycleScriptsName: string /** * 创建脚本,base64编码 base64后的脚本长度不能超过16384个字符 */ CreateScript?: string /** * 启动脚本,base64编码 base64后的脚本长度不能超过16384个字符 */ StartScript?: string } /** * CreateCodeRepository请求参数结构体 */ export interface CreateCodeRepositoryRequest { /** * 存储库名称 */ CodeRepositoryName: string /** * Git相关配置 */ GitConfig: GitConfig /** * Git凭证 */ GitSecret: GitSecret } /** * DescribeNotebookInstances请求参数结构体 */ export interface DescribeNotebookInstancesRequest { /** * 偏移量 */ Offset?: number /** * 限制数目 */ Limit?: number /** * 排序规则。默认取Descending Descending 按更新时间降序 Ascending 按更新时间升序 */ SortOrder?: string /** * 过滤条件。 instance-name - String - 是否必填:否 -(过滤条件)按照名称过滤。 search-by-name - String - 是否必填:否 -(过滤条件)按照名称检索,模糊匹配。 lifecycle-name - String - 是否必填:否 -(过滤条件)按照生命周期脚本名称过滤。 default-code-repo-name - String - 是否必填:否 -(过滤条件)按照默认存储库名称过滤。 additional-code-repo-name - String - 是否必填:否 -(过滤条件)按照其他存储库名称过滤。 billing-status - String - 是否必填:否 - (过滤条件)按照计费状态过滤,可取以下值 StorageOnly:仅存储计费的实例 Computing:计算和存储都计费的实例 */ Filters?: Array<Filter> /** * 【废弃字段】排序字段 */ SortBy?: string } /** * DescribeTrainingJobs返回参数结构体 */ export interface DescribeTrainingJobsResponse { /** * 训练任务列表 */ TrainingJobSet?: Array<TrainingJobSummary> /** * 训练任务总数目 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 终止条件 */ export interface StoppingCondition { /** * 最长运行运行时间(秒) 注意:此字段可能返回 null,表示取不到有效值。 */ MaxRuntimeInSeconds?: number /** * 最长等待运行时间(秒) 注意:此字段可能返回 null,表示取不到有效值。 */ MaxWaitTimeInSeconds?: number } /** * DescribeCodeRepositories返回参数结构体 */ export interface DescribeCodeRepositoriesResponse { /** * 存储库总数目 */ TotalCount?: number /** * 存储库列表 注意:此字段可能返回 null,表示取不到有效值。 */ CodeRepoSet?: Array<CodeRepoSummary> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeNotebookInstances返回参数结构体 */ export interface DescribeNotebookInstancesResponse { /** * Notebook实例列表 */ NotebookInstanceSet?: Array<NotebookInstanceSummary> /** * Notebook实例总数目 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeCodeRepository请求参数结构体 */ export interface DescribeCodeRepositoryRequest { /** * 存储库名称 */ CodeRepositoryName: string } /** * CreateTrainingJob返回参数结构体 */ export interface CreateTrainingJobResponse { /** * 训练任务名称 */ TrainingJobName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeNotebookInstance返回参数结构体 */ export interface DescribeNotebookInstanceResponse { /** * Notebook实例名称 */ NotebookInstanceName?: string /** * Notebook算力资源类型 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceType?: string /** * 角色的资源描述 注意:此字段可能返回 null,表示取不到有效值。 */ RoleArn?: string /** * 外网访问权限 注意:此字段可能返回 null,表示取不到有效值。 */ DirectInternetAccess?: string /** * Root用户权限 注意:此字段可能返回 null,表示取不到有效值。 */ RootAccess?: string /** * 子网ID 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetId?: string /** * 数据卷大小(GB) 注意:此字段可能返回 null,表示取不到有效值。 */ VolumeSizeInGB?: number /** * 创建失败原因 注意:此字段可能返回 null,表示取不到有效值。 */ FailureReason?: string /** * Notebook实例创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreationTime?: string /** * Notebook实例最近修改时间 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifiedTime?: string /** * Notebook实例日志链接 注意:此字段可能返回 null,表示取不到有效值。 */ LogUrl?: string /** * Notebook实例状态 Pending: 创建中 Inservice: 运行中 Stopping: 停止中 Stopped: 已停止 Failed: 失败 注意:此字段可能返回 null,表示取不到有效值。 */ NotebookInstanceStatus?: string /** * Notebook实例ID 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceId?: string /** * notebook生命周期脚本名称 注意:此字段可能返回 null,表示取不到有效值。 */ LifecycleScriptsName?: string /** * 默认存储库名称 可以是已创建的存储库名称或者已https://开头的公共git库 注意:此字段可能返回 null,表示取不到有效值。 */ DefaultCodeRepository?: string /** * 其他存储库列表 每个元素可以是已创建的存储库名称或者已https://开头的公共git库 注意:此字段可能返回 null,表示取不到有效值。 */ AdditionalCodeRepositories?: Array<string> /** * 是否开启CLS日志服务 注意:此字段可能返回 null,表示取不到有效值。 */ ClsAccess?: string /** * 是否预付费实例 注意:此字段可能返回 null,表示取不到有效值。 */ Prepay?: boolean /** * 实例运行截止时间 注意:此字段可能返回 null,表示取不到有效值。 */ Deadline?: string /** * 自动停止配置 注意:此字段可能返回 null,表示取不到有效值。 */ StoppingCondition?: StoppingCondition /** * Cls配置 注意:此字段可能返回 null,表示取不到有效值。 */ ClsConfig?: ClsConfig /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrainingJob请求参数结构体 */ export interface DescribeTrainingJobRequest { /** * 训练任务名称 */ TrainingJobName: string } /** * 训练任务概要 */ export interface TrainingJobSummary { /** * 任务创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreationTime: string /** * 最近修改时间 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifiedTime: string /** * 训练任务名 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingJobName: string /** * 训练任务状态,取值范围 InProgress:运行中 Completed: 已完成 Failed: 失败 Stopping: 停止中 Stopped:已停止 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingJobStatus: string /** * 完成时间 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingEndTime: string /** * 算了实例Id 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceId: string /** * 资源配置 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceConfig: ResourceConfig } /** * 算法配置 */ export interface AlgorithmSpecification { /** * 镜像名字 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingImageName?: string /** * 输入模式File|Pipe 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingInputMode?: string /** * 算法名字 注意:此字段可能返回 null,表示取不到有效值。 */ AlgorithmName?: string } /** * cos路径 */ export interface CosDataSource { /** * cos桶 注意:此字段可能返回 null,表示取不到有效值。 */ Bucket: string /** * cos文件key 注意:此字段可能返回 null,表示取不到有效值。 */ KeyPrefix: string /** * 分布式数据下载方式 注意:此字段可能返回 null,表示取不到有效值。 */ DataDistributionType: string /** * 数据类型 注意:此字段可能返回 null,表示取不到有效值。 */ DataType: string } /** * DescribeNotebookLifecycleScripts返回参数结构体 */ export interface DescribeNotebookLifecycleScriptsResponse { /** * Notebook生命周期脚本列表 */ NotebookLifecycleScriptsSet?: Array<NotebookLifecycleScriptsSummary> /** * Notebook生命周期脚本总数量 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeNotebookSummary返回参数结构体 */ export interface DescribeNotebookSummaryResponse { /** * 实例总数 */ AllInstanceCnt?: number /** * 计费实例总数 */ BillingInstanceCnt?: number /** * 仅存储计费的实例总数 */ StorageOnlyBillingInstanceCnt?: number /** * 计算和存储都计费的实例总数 */ ComputingBillingInstanceCnt?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 过滤器 */ export interface Filter { /** * 过滤字段名称 */ Name?: string /** * 过滤字段取值 */ Values?: Array<string> } /** * StopNotebookInstance请求参数结构体 */ export interface StopNotebookInstanceRequest { /** * Notebook实例名称 */ NotebookInstanceName: string } /** * DeleteNotebookLifecycleScript请求参数结构体 */ export interface DeleteNotebookLifecycleScriptRequest { /** * 生命周期脚本名称 */ NotebookLifecycleScriptsName: string /** * 是否忽略已关联的 notebook 实例强行删除生命周期脚本,默认 false */ Forcible?: boolean } /** * DescribeNotebookLifecycleScript返回参数结构体 */ export interface DescribeNotebookLifecycleScriptResponse { /** * 生命周期脚本名称 */ NotebookLifecycleScriptsName?: string /** * 创建脚本 注意:此字段可能返回 null,表示取不到有效值。 */ CreateScript?: string /** * 启动脚本 注意:此字段可能返回 null,表示取不到有效值。 */ StartScript?: string /** * 创建时间 */ CreationTime?: string /** * 最后修改时间 */ LastModifiedTime?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrainingJob返回参数结构体 */ export interface DescribeTrainingJobResponse { /** * 算法镜像配置 */ AlgorithmSpecification?: AlgorithmSpecification /** * 任务名称 */ TrainingJobName?: string /** * 算法超级参数 注意:此字段可能返回 null,表示取不到有效值。 */ HyperParameters?: string /** * 输入数据配置 */ InputDataConfig?: Array<InputDataConfig> /** * 输出数据配置 */ OutputDataConfig?: OutputDataConfig /** * 中止条件 注意:此字段可能返回 null,表示取不到有效值。 */ StoppingCondition?: StoppingCondition /** * 计算实例配置 */ ResourceConfig?: ResourceConfig /** * 私有网络配置 注意:此字段可能返回 null,表示取不到有效值。 */ VpcConfig?: VpcConfig /** * 失败原因 注意:此字段可能返回 null,表示取不到有效值。 */ FailureReason?: string /** * 最近修改时间 */ LastModifiedTime?: string /** * 任务开始时间 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingStartTime?: string /** * 任务完成时间 注意:此字段可能返回 null,表示取不到有效值。 */ TrainingEndTime?: string /** * 模型输出配置 注意:此字段可能返回 null,表示取不到有效值。 */ ModelArtifacts?: ModelArtifacts /** * 详细状态,取值范围 Starting:启动中 Downloading: 准备训练数据 Training: 正在训练 Uploading: 上传训练结果 Completed:已完成 Failed: 失败 MaxRuntimeExceeded: 任务超过最大运行时间 Stopping: 停止中 Stopped:已停止 */ SecondaryStatus?: string /** * 详细状态事件记录 注意:此字段可能返回 null,表示取不到有效值。 */ SecondaryStatusTransitions?: Array<SecondaryStatusTransition> /** * 角色名称 注意:此字段可能返回 null,表示取不到有效值。 */ RoleName?: string /** * 训练任务状态,取值范围 InProgress:运行中 Completed: 已完成 Failed: 失败 Stopping: 停止中 Stopped:已停止 */ TrainingJobStatus?: string /** * 训练任务日志链接 注意:此字段可能返回 null,表示取不到有效值。 */ LogUrl?: string /** * 训练任务实例ID */ InstanceId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * StopNotebookInstance返回参数结构体 */ export interface StopNotebookInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * UpdateCodeRepository请求参数结构体 */ export interface UpdateCodeRepositoryRequest { /** * 查询存储库名称 */ CodeRepositoryName: string /** * Git凭证 */ GitSecret?: GitSecret } /** * CreateTrainingJob请求参数结构体 */ export interface CreateTrainingJobRequest { /** * 算法镜像配置 */ AlgorithmSpecification: AlgorithmSpecification /** * 输出数据配置 */ OutputDataConfig: OutputDataConfig /** * 资源实例配置 */ ResourceConfig: ResourceConfig /** * 训练任务名称 */ TrainingJobName: string /** * 输入数据配置 */ InputDataConfig?: Array<InputDataConfig> /** * 中止条件 */ StoppingCondition?: StoppingCondition /** * 私有网络配置 */ VpcConfig?: VpcConfig /** * 算法超级参数 */ HyperParameters?: string /** * 环境变量配置 */ EnvConfig?: Array<EnvConfig> /** * 角色名称 */ RoleName?: string /** * 在资源不足(ResourceInsufficient)时后台不定时尝试重新创建训练任务。可取值Enabled/Disabled 默认值为Disabled即不重新尝试。设为Enabled时重新尝试有一定的时间期限,定义在 StoppingCondition 中 MaxWaitTimeInSecond中 ,默认值为1天,超过该期限创建失败。 */ RetryWhenResourceInsufficient?: string } /** * DeleteNotebookInstance请求参数结构体 */ export interface DeleteNotebookInstanceRequest { /** * Notebook实例名称 */ NotebookInstanceName: string } /** * DescribeNotebookLifecycleScript请求参数结构体 */ export interface DescribeNotebookLifecycleScriptRequest { /** * 生命周期脚本名称 */ NotebookLifecycleScriptsName: string } /** * VPC配置 */ export interface VpcConfig { /** * 安全组id 注意:此字段可能返回 null,表示取不到有效值。 */ SecurityGroupIds: Array<string> /** * 子网id 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetId: string } /** * CreateNotebookLifecycleScript返回参数结构体 */ export interface CreateNotebookLifecycleScriptResponse { /** * 生命周期脚本名称 */ NotebookLifecycleScriptsName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreatePresignedNotebookInstanceUrl返回参数结构体 */ export interface CreatePresignedNotebookInstanceUrlResponse { /** * 授权url */ AuthorizedUrl?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * UpdateNotebookLifecycleScript返回参数结构体 */ export interface UpdateNotebookLifecycleScriptResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTrainingJobs请求参数结构体 */ export interface DescribeTrainingJobsRequest { /** * 偏移量 */ Offset?: number /** * 限制数目 */ Limit?: number /** * 创建时间晚于 */ CreationTimeAfter?: string /** * 创建时间早于 */ CreationTimeBefore?: string /** * 根据名称过滤 */ NameContains?: string /** * 根据状态过滤 */ StatusEquals?: string /** * 过滤条件。 instance-name - String - 是否必填:否 -(过滤条件)按照名称过滤。 search-by-name - String - 是否必填:否 -(过滤条件)按照名称检索,模糊匹配。 */ Filters?: Array<Filter> } /** * StartNotebookInstance请求参数结构体 */ export interface StartNotebookInstanceRequest { /** * Notebook实例名称 */ NotebookInstanceName: string /** * 自动停止,可取值Enabled/Disabled 取值为Disabled的时候StoppingCondition将被忽略 取值为Enabled的时候读取StoppingCondition作为自动停止的配置 */ AutoStopping?: string /** * 自动停止配置,只在AutoStopping为Enabled的时候生效 */ StoppingCondition?: StoppingCondition } /** * CreateCodeRepository返回参数结构体 */ export interface CreateCodeRepositoryResponse { /** * 存储库名称 */ CodeRepositoryName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeCodeRepositories请求参数结构体 */ export interface DescribeCodeRepositoriesRequest { /** * 偏移量,默认为0 */ Offset?: number /** * 返回数量,默认为20 */ Limit?: number /** * 过滤条件。 instance-name - String - 是否必填:否 -(过滤条件)按照名称过滤。 search-by-name - String - 是否必填:否 -(过滤条件)按照名称检索,模糊匹配。 */ Filters?: Array<Filter> /** * 排序规则。默认取Descending Descending 按更新时间降序 Ascending 按更新时间升序 */ SortOrder?: string } /** * 数据源 */ export interface DataSource { /** * cos数据源 注意:此字段可能返回 null,表示取不到有效值。 */ CosDataSource?: CosDataSource /** * 文件系统输入源 注意:此字段可能返回 null,表示取不到有效值。 */ FileSystemDataSource?: FileSystemDataSource } /** * 模型输出 */ export interface ModelArtifacts { /** * cos输出路径 注意:此字段可能返回 null,表示取不到有效值。 */ CosModelArtifacts: string } /** * DeleteCodeRepository返回参数结构体 */ export interface DeleteCodeRepositoryResponse { /** * 存储库名称 */ CodeRepositoryName?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string }
the_stack
import stream from "stream"; import { TsUtil, TsChar, TsStream, TsDate } from "@chinachu/aribts"; import zlib from "zlib"; import { EntityParser, MediaType, parseMediaType, entityHeaderToString, parseMediaTypeFromString } from './entity_parser'; import * as wsApi from "./ws_api"; import { ComponentPMT, AdditionalAribBXMLInfo } from './ws_api'; type DownloadComponentInfo = { componentId: number, transactionId: number, downloadedModuleCount: number, modules: Map<number, DownloadModuleInfo>, dataEventId: number, }; enum CompressionType { None = -1, Zlib = 0, } type DownloadModuleInfo = { compressionType: CompressionType, originalSize?: number, moduleId: number, moduleVersion: number, moduleSize: number, contentType?: string, blocks: (Buffer | undefined)[], downloadedBlockCount: number, dataEventId: number, }; type CachedModuleFile = { contentType: MediaType, contentLocation: string | null, data: Buffer, }; type CachedModule = { downloadModuleInfo: DownloadModuleInfo, files?: Map<string | null, CachedModuleFile>, dataEventId: number, }; export type DecodeTSOptions = { sendCallback: (msg: wsApi.ResponseMessage) => void; serviceId?: number; parsePES?: boolean; dumpError?: boolean; }; type CachedComponent = { modules: Map<number, CachedModule>, }; export function decodeTS(options: DecodeTSOptions): TsStream { const { sendCallback: send, serviceId, parsePES, dumpError } = options; const tsStream = new TsStream(); const tsUtil = new TsUtil(); let pmtRetrieved = false; let pidToComponent = new Map<number, ComponentPMT>(); let componentToPid = new Map<number, ComponentPMT>(); let currentTime: number | null = null; const downloadComponents = new Map<number, DownloadComponentInfo>(); const cachedComponents = new Map<number, CachedComponent>(); let currentProgramInfo: wsApi.ProgramInfoMessage | null = null; // SDTのEIT_present_following_flag // key: service_id const eitPresentFollowingFlag = new Map<number, boolean>(); // program_number = service_id let pidToProgramNumber = new Map<number, number>(); let programNumber: number | null = null; let pcr_pid: number | null = null; // 字幕/文字スーパーのPESのPID let privatePes = new Set<number>(); if (dumpError) { tsStream.on("drop", (pid: any, counter: any, expected: any) => { let time = "unknown"; if (tsUtil.hasTime()) { let date = tsUtil.getTime(); if (date) { time = `${("0" + date.getHours()).slice(-2)}:${("0" + date.getMinutes()).slice(-2)}:${("0" + date.getSeconds()).slice(-2)}`; } } console.error(`pid: 0x${("000" + pid.toString(16)).slice(-4)}, counter: ${counter}, expected: ${expected}, time: ${time}`); }); } tsStream.on("info", (data: any) => { console.error(""); console.error("info:"); Object.keys(data).forEach(key => { console.error(`0x${("000" + parseInt(key, 10).toString(16)).slice(-4)}: packet: ${data[key].packet}, drop: ${data[key].drop}, scrambling: ${data[key].scrambling}`); }); }); tsStream.on("tdt", (pid: any, data: any) => { tsUtil.addTdt(pid, data); const time = tsUtil.getTime()?.getTime(); if (time != null && currentTime !== time) { currentTime = time; send({ type: "currentTime", timeUnixMillis: currentTime, }); } }); tsStream.on("tot", (pid: any, data: any) => { tsUtil.addTot(pid, data); const time = tsUtil.getTime()?.getTime(); if (time != null && currentTime !== time) { currentTime = time; send({ type: "currentTime", timeUnixMillis: currentTime, }); } }); tsStream.on("pat", (pid: any, data: any) => { tsUtil.addPat(pid, data); const programs: { program_number: number, network_PID?: number, program_map_PID?: number }[] = data.programs; const pat = new Map<number, number>(); programNumber = null; for (const program of programs) { if (program.program_map_PID != null) { // 多重化されていればとりあえず一番最初のprogram_number使っておく programNumber ??= program.program_number; pat.set(program.program_map_PID, program.program_number); } } if (pat.size !== pidToProgramNumber.size || [...pidToProgramNumber.keys()].some((x) => !pat.has(x))) { console.log("PAT changed", pat); if (serviceId != null && pat.size !== 1) { console.warn("multiplexed!"); } pmtRetrieved = false; } pidToProgramNumber = pat; }); tsStream.on("pmt", (pid: any, data: any) => { // 多重化されている if (pidToProgramNumber.size >= 2) { if (pidToProgramNumber.get(pid) !== (serviceId ?? programNumber)) { return; } } const ptc = new Map<number, ComponentPMT>(); const ctp = new Map<number, ComponentPMT>(); privatePes.clear(); for (const stream of data.streams) { if (parsePES && stream.stream_type === 0x06) { privatePes.add(stream.elementary_PID); } const pid = stream.elementary_PID; let bxmlInfo: AdditionalAribBXMLInfo | undefined; let componentId: number | undefined; for (const esInfo of stream.ES_info) { if (esInfo.descriptor_tag == 0x52) { // Stream identifier descriptor ストリーム識別記述子 // PID => component_tagの対応 const component_tag = esInfo.component_tag; componentId = component_tag; } else if (esInfo.descriptor_tag == 0xfd) { // Data component descriptor データ符号化方式記述子 let additional_data_component_info: Buffer = esInfo.additional_data_component_info; let data_component_id: number = esInfo.data_component_id; // FIXME!!!!!!!! // aribtsの実装がおかしくてdata_component_idを8ビットとして読んでる if (esInfo.additional_data_component_info.length + 1 === esInfo.descriptor_length) { data_component_id <<= 8; data_component_id |= additional_data_component_info[0]; additional_data_component_info = additional_data_component_info.subarray(1); } // STD-B10 第2部 付録J 表J-1参照 if (data_component_id == 0x0C || // 地上波 data_component_id == 0x0D || // 地上波 data_component_id == 0x07 || // BS data_component_id == 0x0B // CS ) { bxmlInfo = decodeAdditionalAribBXMLInfo(additional_data_component_info); } } } if (componentId == null) { continue; } const componentPMT: ComponentPMT = { componentId, pid, bxmlInfo, streamType: stream.stream_type, }; ptc.set(pid, componentPMT); ctp.set(componentPMT.componentId, componentPMT); } pcr_pid = data.PCR_PID; pidToComponent = ptc; if (!pmtRetrieved || componentToPid.size !== ctp.size || [...componentToPid.keys()].some((x) => !ctp.has(x))) { // PMTが変更された // console.log("PMT changed"); componentToPid = ctp; pmtRetrieved = true; const msg: wsApi.PMTMessage = { type: "pmt", components: [...componentToPid.values()] }; send(msg); } }); tsStream.on("packet", (pid, data) => { if (privatePes.has(pid) && data.data_byte != null) { const info = (tsStream.info as any)[pid]; if (data.payload_unit_start_indicator) { info.buffer.reset(); info.buffer.add(data.data_byte); if (data.data_byte.length >= 6) { info.buffer.entireLength = data.data_byte.readUInt16BE(4) + 6; } else { info.buffer.entireLength = 0x7fffffff; } } else { info.buffer.add(data.data_byte); } if (info.buffer.entireLength === info.buffer.length) { const pes: Buffer = info.buffer.concat(); info.buffer.reset(); const msg = decodePES(pes); if (msg != null) { send(msg); } } } if (pid !== pcr_pid) { return; } const program_clock_reference_base = data.adaptation_field?.program_clock_reference_base; const program_clock_reference_extension = data.adaptation_field?.program_clock_reference_extension; // console.log(program_clock_reference_base); if (program_clock_reference_base != null && program_clock_reference_extension != null) { send({ type: "pcr", pcrBase: program_clock_reference_base, pcrExtension: program_clock_reference_extension, }); } }); tsStream.on("bit", (_pid, data) => { // FIXME: node-aribts側の問題でCRCが不一致だと変なobjBitが送られてきてしまう if (data.broadcaster_descriptors == null) { return; } // data.first_descriptorsはSI伝送記述子のみ // 地上波だとbroadcaster_idは255 const original_network_id: number = data.original_network_id; const broadcasters: wsApi.BITBroadcaster[] = []; for (const broadcaster_descriptor of data.broadcaster_descriptors) { let broadcaster_id: number = broadcaster_descriptor.broadcaster_id; const broadcasterNameDescriptor = broadcaster_descriptor.descriptors.find((x: any) => x.descriptor_tag === 0xD8); const broadcasterName = broadcasterNameDescriptor?.char == null ? null : new TsChar(broadcasterNameDescriptor.char).decode(); const serviceListDescriptor = broadcaster_descriptor.descriptors.find((x: any) => x.descriptor_tag === 0x41); const extendedBroadcasterDescriptor = broadcaster_descriptor.descriptors.find((x: any) => x.descriptor_tag === 0xCE); const affiliations = extendedBroadcasterDescriptor?.affiliations?.map((x: { affiliation_id: number }) => x.affiliation_id) ?? []; const affiliationBroadcasters = extendedBroadcasterDescriptor?.broadcasters?.map((x: { original_network_id: number, broadcaster_id: number }) => ({ originalNetworkId: x.original_network_id, broadcasterId: x.broadcaster_id })) ?? []; const services = (serviceListDescriptor?.services as ({ service_id: number, service_type: number }[] | null | undefined))?.map(x => ({ serviceId: x.service_id, serviceType: x.service_type })) ?? []; if (broadcaster_id === 255) { // broadcaster_id = extendedBroadcasterDescriptor?.terrestrial_broadcaster_id ?? broadcaster_id; } const broadcaster: wsApi.BITBroadcaster = { affiliations, broadcasterId: broadcaster_id, broadcasterName, affiliationBroadcasters: affiliationBroadcasters, services, terrestrialBroadcasterId: extendedBroadcasterDescriptor?.terrestrial_broadcaster_id, }; broadcasters.push(broadcaster); } const msg: wsApi.BITMessage = { type: "bit", broadcasters, originalNetworkId: original_network_id, }; send(msg); }); function getStreamInfo() { if (!tsUtil.hasOriginalNetworkId() || !tsUtil.hasTransportStreamId() || !tsUtil.hasServiceIds() || !tsUtil.hasTransportStreams(tsUtil.getOriginalNetworkId())) { return; } return { onid: (tsUtil.getTransportStreams(tsUtil.getOriginalNetworkId()) as { [key: number]: any })[tsUtil.getTransportStreamId()].original_network_id, tsid: tsUtil.getTransportStreamId(), sid: serviceId ?? tsUtil.getServiceIds()[0] }; } function sendStreamInfo() { if (currentProgramInfo == null) { const ids = getStreamInfo(); if (ids != null) { currentProgramInfo = { type: "programInfo", eventId: null, transportStreamId: ids.tsid, originalNetworkId: ids.onid, serviceId: ids.sid, eventName: null, startTimeUnixMillis: null, durationSeconds: null, }; send(currentProgramInfo); } } } tsStream.on("eit", (pid, data) => { // FIXME: node-aribts側の問題でCRCが不一致だと変なobjEitが送られてきてしまう if (data.events == null) { return; } tsUtil.addEit(pid, data); const ids = getStreamInfo(); if (ids == null) { return; } if (!tsUtil.hasPresent(ids.onid, ids.tsid, ids.sid)) { return; } const p = tsUtil.getPresent(ids.onid, ids.tsid, ids.sid); const prevProgramInfo = currentProgramInfo; currentProgramInfo = { type: "programInfo", eventId: p.event_id, transportStreamId: ids.tsid, originalNetworkId: ids.onid, serviceId: ids.sid, eventName: p.short_event?.event_name, startTimeUnixMillis: p.start_time?.getTime(), durationSeconds: p.durationSeconds, }; if (prevProgramInfo?.eventId !== currentProgramInfo.eventId || prevProgramInfo?.transportStreamId !== currentProgramInfo.transportStreamId || prevProgramInfo?.originalNetworkId !== currentProgramInfo.originalNetworkId || prevProgramInfo?.serviceId !== currentProgramInfo.serviceId || prevProgramInfo?.startTimeUnixMillis !== currentProgramInfo.startTimeUnixMillis || prevProgramInfo?.eventName !== currentProgramInfo.eventName || prevProgramInfo?.durationSeconds !== currentProgramInfo.durationSeconds) { send(currentProgramInfo); } }); tsStream.on("nit", (pid, data) => { tsUtil.addNit(pid, data); sendStreamInfo(); }); tsStream.on("sdt", (pid, data) => { tsUtil.addSdt(pid, data); eitPresentFollowingFlag.clear(); if (data.table_id === 0x42) { // 自ストリームのSDT for (const service of data.services) { eitPresentFollowingFlag.set(service.service_id, service.EIT_present_following_flag !== 0); for (const descriptor of service.descriptors) { if (descriptor.descriptor_tag == 0x48) {// 0x48 サービス記述子 // console.log(service.service_id, new TsChar(descriptor.service_name_char).decode(), new TsChar(descriptor.service_provider_name_char).decode()); } } } } sendStreamInfo(); }); tsStream.on("sit", (pid: any, data: any) => { const services = data.services[0].service; const short_event_descriptor = services.filter((data: any) => data.descriptor_tag === 0x4D); const event_name_char = new TsChar(short_event_descriptor[0].event_name_char).decode(); const serviceId = data.services[0].service_id; let tot_descriptor; const transmission_tot = data.transmission_info.filter((data: any) => data.descriptor_tag === 0xC3); const service_tot = services.filter((data: any) => data.descriptor_tag === 0xC3); let jst_time = 0; let event_start_time = 0; if (transmission_tot.length > 0) { tot_descriptor = transmission_tot; } else if (service_tot.length > 0) { tot_descriptor = service_tot; } if (tot_descriptor) { jst_time = new TsDate(tot_descriptor[0].jst_time).decode().getTime(); event_start_time = new TsDate(service_tot[0].event_start_time).decode().getTime(); } const event_group_descriptor = services.filter((data: any) => data.descriptor_tag === 0xD6); let event_Id = null; if (event_group_descriptor.length > 0) { if (event_group_descriptor[0].events.filter((data: any) => data.service_id === serviceId).length > 0) { event_Id = event_group_descriptor[0].events.filter((data: any) => data.service_id === serviceId)[0].event_id; } } currentProgramInfo = { type: "programInfo", eventId: event_Id, transportStreamId: null, originalNetworkId: data.transmission_info[1].network_id, serviceId: serviceId, eventName: event_name_char, startTimeUnixMillis: event_start_time, durationSeconds: null, }; send(currentProgramInfo); if (currentTime !== jst_time) { currentTime = jst_time; send({ type: "currentTime", timeUnixMillis: currentTime, }); } }); tsStream.on("dsmcc", (pid: any, data: any) => { const c = pidToComponent.get(pid); if (c == null) { return; } const { componentId, bxmlInfo } = c; if (data.table_id === 0x3b) { // DII // console.log(pid, data); const transationIdLow2byte: number = data.table_id_extension; const sectionNumber: number = data.section_number; const lastSectionNumber: number = data.last_section_number; // dsmccMessageHeader // protocolDiscriminatorは常に0x11 // dsmccTypeは常に0x03 // messageIdは常に0x1002 const message = data.message; const downloadId: number = message.downloadId; // downloadIdの下位28ビットは常に1で運用される const data_event_id = (downloadId >> 28) & 15; const modules = new Map<number, DownloadModuleInfo>(); const transactionId: number = message.transaction_id; if (downloadComponents.get(componentId)?.transactionId === data.message.transaction_id) { return; } const componentInfo: DownloadComponentInfo = { componentId, modules, transactionId, downloadedModuleCount: 0, dataEventId: data_event_id, }; // console.log(`componentId: ${componentId.toString(16).padStart(2, "0")} downloadId: ${downloadId}`) // blockSizeは常に4066 const blockSize: number = message.blockSize; // windowSize, ackPeriod, tCDownloadWindowは常に0 // privateDataは運用しない // 0<=numberOfModules<=64で運用 // moduleSize<=256KB // compatibilityDescriptorは運用しない for (const module of data.message.modules) { const moduleId: number = module.moduleId; const moduleVersion: number = module.moduleVersion; const moduleSize: number = module.moduleSize; const moduleInfo: DownloadModuleInfo = { compressionType: CompressionType.None, moduleId, moduleVersion, moduleSize, blocks: new Array(Math.ceil(moduleSize / blockSize)), downloadedBlockCount: 0, dataEventId: data_event_id, }; modules.set(moduleId, moduleInfo); // console.log(` moduleId: ${moduleId.toString(16).padStart(4, "0")} moduleVersion: ${moduleVersion}`) for (const info of module.moduleInfo) { // Type記述子, ダウンロード推定時間記述子, Compression Type記述子のみ運用される(TR-B14 第三分冊 4.2.4 表4-4参照) if (info.descriptor_tag === 0x01) { // Type記述子 STD-B24 第三分冊 第三編 6.2.3.1 const contentType = info.text_char.toString("ascii"); moduleInfo.contentType = contentType; } else if (info.descriptor_tag === 0x07) { // ダウンロード推定時間記述子 STD-B24 第三分冊 第三編 6.2.3.6 const descriptor: Buffer = info.descriptor; const est_download_time = descriptor.readUInt32BE(0); } else if (info.descriptor_tag === 0xC2) { // Compression Type記述子 STD-B24 第三分冊 第三編 6.2.3.9 const descriptor: Buffer = info.descriptor; const compression_type = descriptor.readInt8(0); // 0: zlib const original_size = descriptor.readUInt32BE(1); moduleInfo.originalSize = original_size; moduleInfo.compressionType = compression_type as CompressionType; } } } let returnToEntryFlag: boolean | undefined; for (const privateData of data.message.privateData) { const descriptor_tag: number = privateData.descriptor_tag; // arib_bxml_privatedata_descriptor // STD-B24 第二分冊 (1/2) 第二編 9.3.4参照 if (descriptor_tag === 0xF0) { returnToEntryFlag = !!(privateData.descriptor[0] & 0x80); } } const cachedComponent = cachedComponents.get(componentId); if (downloadComponents.get(componentId)?.dataEventId !== componentInfo.dataEventId && cachedComponent != null) { cachedComponent.modules.clear(); } send({ type: "moduleListUpdated", componentId, modules: data.message.modules.map((x: any) => ({ id: x.moduleId, version: x.moduleVersion, size: x.moduleSize })), dataEventId: data_event_id, returnToEntryFlag, }); downloadComponents.set(componentId, componentInfo); } else if (data.table_id === 0x3c) { if (bxmlInfo == null) { return; } const componentInfo = downloadComponents.get(componentId); if (componentInfo == null) { return; } // DDB const headerModuleId: number = data.table_id_extension; const headerModuleVersionLow5bit: number = data.version_number; const headerBlockNumberLow8bit: number = data.section_number; // dsmccMessageHeader // protocolDiscriminatorは常に0x11 // dsmccTypeは常に0x03 // messageIdは常に0x1002 const message = data.message; const downloadId: number = message.downloadId; // downloadIdの下位28ビットは常に1で運用される const data_event_id = (downloadId >> 28) & 15; const moduleId = message.moduleId; const moduleVersion = message.moduleVersion; const blockNumber = message.blockNumber; const moduleInfo = componentInfo.modules.get(moduleId); // console.log(`download ${componentId.toString(16).padStart(2, "0")}/${moduleId.toString(16).padStart(4, "0")}`) if (moduleInfo == null) { return; } if (moduleInfo.moduleVersion !== moduleVersion) { return; } if (moduleInfo.dataEventId !== data_event_id) { return; } if (moduleInfo.blocks.length <= blockNumber) { return; } if (moduleInfo.blocks[blockNumber] != null) { return; } moduleInfo.blocks[blockNumber] = data.message.blockDataByte as Buffer; moduleInfo.downloadedBlockCount++; if (moduleInfo.downloadedBlockCount >= moduleInfo.blocks.length) { componentInfo.downloadedModuleCount++; const cachedComponent = cachedComponents.get(componentId) ?? { modules: new Map<number, CachedModule>(), }; const cachedModule: CachedModule = { downloadModuleInfo: moduleInfo, dataEventId: data_event_id, }; let moduleData = Buffer.concat(moduleInfo.blocks as Buffer[]); const previousCachedModule = cachedComponent.modules.get(moduleInfo.moduleId); if (previousCachedModule != null && previousCachedModule.downloadModuleInfo.moduleVersion === moduleInfo.moduleVersion && previousCachedModule.dataEventId === moduleInfo.dataEventId) { // 更新されていない return; } if (moduleInfo.compressionType === CompressionType.Zlib) { moduleData = zlib.inflateSync(moduleData); } const mediaType = moduleInfo.contentType == null ? null : parseMediaTypeFromString(moduleInfo.contentType).mediaType; // console.info(`component ${componentId.toString(16).padStart(2, "0")} module ${moduleId.toString(16).padStart(4, "0")}updated`); if (mediaType == null || (mediaType.type === "multipart" && mediaType.subtype === "mixed")) { const parser = new EntityParser(moduleData); const mod = parser.readEntity(); if (mod?.multipartBody == null) { console.error("failed to parse module"); } else { const files = new Map<string | null, CachedModuleFile>(); for (const entity of mod.multipartBody) { const location = entity.headers.find(x => x.name === "content-location"); if (location == null) { // 必ず含む console.error("failed to find Content-Location"); continue; } const contentType = entity.headers.find(x => x.name === "content-type"); if (contentType == null) { // 必ず含む console.error("failed to find Content-Type"); continue; } const mediaType = parseMediaType(contentType.value); if (mediaType.mediaType == null) { console.error("failed to parse Content-Type", entityHeaderToString(contentType)); continue; } if (mediaType.error) { console.log("failed to parse Content-Type", entityHeaderToString(contentType)); } const locationString = entityHeaderToString(location); // console.log(" ", locationString, entityHeaderToString(contentType)); files.set(locationString, { contentLocation: locationString, contentType: mediaType.mediaType, data: entity.body, }); } cachedModule.files = files; send({ type: "moduleDownloaded", componentId, moduleId, files: [...files.values()].map(x => ({ contentType: x.contentType, contentLocation: x.contentLocation, dataBase64: x.data.toString("base64"), })), version: moduleVersion, dataEventId: data_event_id, }); } } else { const files = new Map<string | null, CachedModuleFile>(); files.set(null, { contentLocation: null, contentType: mediaType, data: moduleData, }); cachedModule.files = files; send({ type: "moduleDownloaded", componentId, moduleId, files: [...files.values()].map(x => ({ contentType: x.contentType, contentLocation: x.contentLocation, dataBase64: x.data.toString("base64"), })), version: moduleVersion, dataEventId: data_event_id, }); } cachedComponent.modules.set(moduleInfo.moduleId, cachedModule); cachedComponents.set(componentId, cachedComponent); } } else if (data.table_id === 0x3d) { // ストリーム記述子 const data_event_id = data.table_id_extension >> 12; const event_msg_group_id = data.table_id_extension & 0b1111_1111_1111; const stream_descriptor: Buffer = data.stream_descriptor; const events: wsApi.ESEvent[] = []; for (let i = 0; i + 1 < stream_descriptor.length;) { const descriptor_tag = stream_descriptor.readUInt8(i); i++; const descriptor_length = stream_descriptor.readUInt8(i); i++; const descriptor = stream_descriptor.subarray(i, i + descriptor_length); i += descriptor_length; if (descriptor.length !== descriptor_length) { break; } if (descriptor_tag === 0x17) { // NPT参照記述子 NPTReferenceDescriptor if (descriptor_length < 18) { continue; } // 0のみ運用 const postDiscontinuityIndicator = descriptor[0] >> 7; // 運用しない (常に0) const dsm_contentId = descriptor[0] & 127; // 7bit reserved const STC_Reference = descriptor.readUInt32BE(2) + ((descriptor[1] & 1) * 0x100000000); // 31bit reserved const NPT_Reference = descriptor.readUInt32BE(10) + ((descriptor[9] & 1) * 0x100000000); // 0/1か1/1のみ運用 const scaleNumerator = descriptor.readUInt16BE(14); const scaleDenominator = descriptor.readUInt16BE(16); events.push({ type: "nptReference", postDiscontinuityIndicator: !!postDiscontinuityIndicator, dsmContentId: dsm_contentId, STCReference: STC_Reference, NPTReference: NPT_Reference, scaleNumerator, scaleDenominator, }); } else if (descriptor_tag === 0x40) { // 汎用イベントメッセージ記述子 General_event_descriptor if (descriptor_length < 11) { continue; } const event_msg_group_id = (descriptor.readUInt16BE(0) >> 4) & 0b1111_1111_1111; // 4bit reserved_future_use const time_mode = descriptor.readUInt8(2); const event_msg_type = descriptor.readUInt8(8); const event_msg_id = descriptor.readUInt16BE(9); const private_data_byte = descriptor.subarray(11); // 0x00と0x02のみが運用される(TR-B14, TR-B15) if (time_mode === 0) { // 40bit reserved_future_use events.push({ type: "immediateEvent", eventMessageType: event_msg_type, eventMessageGroupId: event_msg_group_id, eventMessageId: event_msg_id, privateDataByte: Array.from(private_data_byte), timeMode: time_mode }); } else if (time_mode === 0x01 || time_mode === 0x05) { // event_msg_MJD_JST_time } else if (time_mode === 0x02) { // 7bit reserved_future_use // event_msg_NPT const NPT = descriptor.readUInt32BE(4) + ((descriptor[3] & 1) * 0x100000000); events.push({ type: "nptEvent", eventMessageType: event_msg_type, eventMessageNPT: NPT, eventMessageGroupId: event_msg_group_id, eventMessageId: event_msg_id, privateDataByte: Array.from(private_data_byte), timeMode: time_mode }); } else if (time_mode === 0x03) { // 4bit reserved_future_use // 36bit event_msg_relativeTime } } } send({ type: "esEventUpdated", events, componentId, dataEventId: data_event_id, }); } }); return tsStream; } function decodeAdditionalAribBXMLInfo(additional_data_component_info: Buffer): AdditionalAribBXMLInfo { let off = 0; // 地上波についてはTR-B14 第二分冊 2.1.4 表2-3を参照 // BSについてはTR-B15 第一分冊 5.1.5 表5-4を参照 // BS, CSについてはTR-B15 第四分冊 5.1.5 表5-4を参照 // 00: データカルーセル伝送方式およびイベントメッセージ伝送方式 これのみが運用される // 01: データカルーセル伝送方式(蓄積専用データサービス) const transmission_format = ((additional_data_component_info[off] & 0b11000000) >> 6) & 0b11; // component_tag=0x40のとき必ず1となる // startup.xmlが最初に起動される (STD-B24 第二分冊 (1/2) 第二編 9.2.2参照) const entry_point_flag = ((additional_data_component_info[off] & 0b00100000) >> 5) & 0b1; const bxmlInfo: AdditionalAribBXMLInfo = { transmissionFormat: transmission_format, entryPointFlag: !!entry_point_flag, }; // STD-B24 第二分冊 (1/2) 第二編 9.3参照 if (entry_point_flag) { // 運用 const auto_start_flag = ((additional_data_component_info[off] & 0b00010000) >> 4) & 0b1; // 以下が運用される // 0011: 960x540 (16:9) // 0100: 640x480 (16:9) // 0101: 640x480 (4:3) // 以下は仕様のみ // 0000: 混在 // 0001: 1920x1080 (16:9) // 0010: 1280x720 (16:9) // 0110: 320x240 (4:3) // 1111: 指定しない (Cプロファイルでのみ運用) const document_resolution = ((additional_data_component_info[off] & 0b00001111) >> 0) & 0b1111; off++; // 0のみが運用される const use_xml = ((additional_data_component_info[off] & 0b10000000) >> 7) & 0b1; // 地上波, CSでは0のみが運用される // BSでは1(bml_major_version=1, bml_minor_version=0)が指定されることもある const default_version_flag = ((additional_data_component_info[off] & 0b01000000) >> 6) & 0b1; // 地上波では1のみ運用, BS/CSの場合1の場合単独視聴可能, 0の場合単独視聴不可 const independent_flag = ((additional_data_component_info[off] & 0b00100000) >> 5) & 0b1; // 運用される const style_for_tv_flag = ((additional_data_component_info[off] & 0b00010000) >> 4) & 0b1; // reserved off++; bxmlInfo.entryPointInfo = { autoStartFlag: !!auto_start_flag, documentResolution: document_resolution, useXML: !!use_xml, defaultVersionFlag: !!default_version_flag, independentFlag: !!independent_flag, styleForTVFlag: !!style_for_tv_flag, bmlMajorVersion: 1, bmlMinorVersion: 0, }; // BSではbml_major_versionは1 // CSではbml_major_versionは2 // 地上波ではbml_major_versionは3 if (default_version_flag === 0) { let bml_major_version = additional_data_component_info[off] << 16; off++; bml_major_version |= additional_data_component_info[off]; bxmlInfo.entryPointInfo.bmlMajorVersion = bml_major_version; off++; let bml_minor_version = additional_data_component_info[off] << 16; off++; bml_minor_version |= additional_data_component_info[off]; bxmlInfo.entryPointInfo.bmlMinorVersion = bml_minor_version; off++; // 運用されない if (use_xml == 1) { let bxml_major_version = additional_data_component_info[off] << 16; off++; bxml_major_version |= additional_data_component_info[off]; bxmlInfo.entryPointInfo.bxmlMajorVersion = bxml_major_version; off++; let bxml_minor_version = additional_data_component_info[off] << 16; off++; bxml_minor_version |= additional_data_component_info[off]; bxmlInfo.entryPointInfo.bxmlMinorVersion = bxml_minor_version; off++; } } } else { // reserved off++; } if (transmission_format === 0) { // additional_arib_carousel_info (STD-B24 第三分冊 第三編 C.1) // 常に0xF const data_event_id = ((additional_data_component_info[off] & 0b11110000) >> 4) & 0b1111; // 常に1 const event_section_flag = ((additional_data_component_info[off] & 0b00001000) >> 3) & 0b1; //reserved off++; // 地上波ならば常に1, BS/CSなら1/0 const ondemand_retrieval_flag = ((additional_data_component_info[off] & 0b10000000) >> 7) & 0b1; // 地上波ならば常に0, BS/CSなら/- const file_storable_flag = ((additional_data_component_info[off] & 0b01000000) >> 6) & 0b1; // 運用 const start_priority = ((additional_data_component_info[off] & 0b00100000) >> 5) & 0b1; bxmlInfo.additionalAribCarouselInfo = { dataEventId: data_event_id, eventSectionFlag: !!event_section_flag, ondemandRetrievalFlag: !!ondemand_retrieval_flag, fileStorableFlag: !!file_storable_flag, startPriority: start_priority, }; // reserved off++; } else if (transmission_format == 1) { // reserved off++; } return bxmlInfo; } function decodePES(pes: Buffer): wsApi.PESMessage | null { let pos = 0; if (pes.length < 5) { return null; } if (pes[0] !== 0 || pes[1] !== 0 || pes[2] !== 1) { return null; } pos += 3; const streamId = pes.readUInt8(pos); pos++; const pesPacketLength = pes.readUInt16BE(pos); pos += 2; if (streamId === 0xBF) { return { type: "pes", data: Array.from(pes.subarray(pos, pos + pesPacketLength)), streamId }; } if (streamId === 0xBE) { return null; } if ((pes[pos] >> 6) !== 0b10) { return null; } const scramblingControl = (pes[pos] >> 4) & 0b11; const priority = (pes[pos] >> 3) & 0b1; const dataAlignmentIndicator = (pes[pos] >> 2) & 0b1; const copyright = (pes[pos] >> 1) & 0b1; const original = (pes[pos] >> 0) & 0b1; pos++; const ptsDTSIndicator = (pes[pos] >> 6) & 0b11; const escrFlag = (pes[pos] >> 5) & 0b1; const esRateFlag = (pes[pos] >> 4) & 0b1; const dsmTrickModeFlag = (pes[pos] >> 3) & 0b1; const additionalCopyInfoFlag = (pes[pos] >> 2) & 0b1; const crcFlag = (pes[pos] >> 1) & 0b1; const extensionFlag = (pes[pos] >> 0) & 0b1; pos++; const pesHeaderLength = pes[pos]; pos++; const dataPos = pos + pesHeaderLength; let pts: number | undefined; if (ptsDTSIndicator === 0b10 || ptsDTSIndicator === 0b11) { const pts3230 = (pes[pos] >> 1) & 0b111; pos++; const pts2915 = pes.readUInt16BE(pos) >> 1; pos += 2; const pts1400 = pes.readUInt16BE(pos) >> 1; pos += 2; pts = pts1400 + (pts2915 << 15) + (pts3230 * 0x40000000); } return { type: "pes", data: Array.from(pes.subarray(dataPos)), pts, streamId }; }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const MetadataDTO: msRest.CompositeMapper = { serializedName: "MetadataDTO", type: { name: "Composite", className: "MetadataDTO", modelProperties: { name: { required: true, serializedName: "name", constraints: { MaxLength: 100, MinLength: 1 }, type: { name: "String" } }, value: { required: true, serializedName: "value", constraints: { MaxLength: 500, MinLength: 1 }, type: { name: "String" } } } } }; export const ContextDTO: msRest.CompositeMapper = { serializedName: "ContextDTO", type: { name: "Composite", className: "ContextDTO", modelProperties: { isContextOnly: { serializedName: "isContextOnly", type: { name: "Boolean" } }, prompts: { serializedName: "prompts", constraints: { MaxItems: 20 }, type: { name: "Sequence", element: { type: { name: "Composite", className: "PromptDTO" } } } } } } }; export const QnADTOContext: msRest.CompositeMapper = { serializedName: "QnADTO_context", type: { name: "Composite", className: "QnADTOContext", modelProperties: { ...ContextDTO.type.modelProperties } } }; export const QnADTO: msRest.CompositeMapper = { serializedName: "QnADTO", type: { name: "Composite", className: "QnADTO", modelProperties: { id: { serializedName: "id", type: { name: "Number" } }, answer: { required: true, serializedName: "answer", constraints: { MaxLength: 25000, MinLength: 1 }, type: { name: "String" } }, source: { serializedName: "source", constraints: { MaxLength: 300 }, type: { name: "String" } }, questions: { required: true, serializedName: "questions", type: { name: "Sequence", element: { type: { name: "String" } } } }, metadata: { serializedName: "metadata", type: { name: "Sequence", element: { type: { name: "Composite", className: "MetadataDTO" } } } }, context: { serializedName: "context", type: { name: "Composite", className: "QnADTOContext" } } } } }; export const PromptDTOQna: msRest.CompositeMapper = { serializedName: "PromptDTO_qna", type: { name: "Composite", className: "PromptDTOQna", modelProperties: { ...QnADTO.type.modelProperties } } }; export const PromptDTO: msRest.CompositeMapper = { serializedName: "PromptDTO", type: { name: "Composite", className: "PromptDTO", modelProperties: { displayOrder: { serializedName: "displayOrder", type: { name: "Number" } }, qnaId: { serializedName: "qnaId", type: { name: "Number" } }, qna: { serializedName: "qna", type: { name: "Composite", className: "PromptDTOQna" } }, displayText: { serializedName: "displayText", constraints: { MaxLength: 200 }, type: { name: "String" } } } } }; export const ErrorModel: msRest.CompositeMapper = { serializedName: "Error", type: { name: "Composite", className: "ErrorModel", modelProperties: { code: { required: true, serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } }, target: { serializedName: "target", type: { name: "String" } }, details: { serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorModel" } } } }, innerError: { serializedName: "innerError", type: { name: "Composite", className: "InnerErrorModel" } } } } }; export const ErrorResponseError: msRest.CompositeMapper = { serializedName: "ErrorResponse_error", type: { name: "Composite", className: "ErrorResponseError", modelProperties: { ...ErrorModel.type.modelProperties } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorResponseError" } } } } }; export const InnerErrorModel: msRest.CompositeMapper = { serializedName: "InnerErrorModel", type: { name: "Composite", className: "InnerErrorModel", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, innerError: { serializedName: "innerError", type: { name: "Composite", className: "InnerErrorModel" } } } } }; export const QueryContextDTO: msRest.CompositeMapper = { serializedName: "QueryContextDTO", type: { name: "Composite", className: "QueryContextDTO", modelProperties: { previousQnaId: { serializedName: "previousQnaId", type: { name: "String" } }, previousUserQuery: { serializedName: "previousUserQuery", type: { name: "String" } } } } }; export const QueryDTOContext: msRest.CompositeMapper = { serializedName: "QueryDTO_context", type: { name: "Composite", className: "QueryDTOContext", modelProperties: { ...QueryContextDTO.type.modelProperties } } }; export const QueryDTO: msRest.CompositeMapper = { serializedName: "QueryDTO", type: { name: "Composite", className: "QueryDTO", modelProperties: { qnaId: { serializedName: "qnaId", type: { name: "String" } }, question: { serializedName: "question", type: { name: "String" } }, top: { serializedName: "top", type: { name: "Number" } }, userId: { serializedName: "userId", type: { name: "String" } }, isTest: { serializedName: "isTest", type: { name: "Boolean" } }, scoreThreshold: { serializedName: "scoreThreshold", type: { name: "Number" } }, context: { serializedName: "context", type: { name: "Composite", className: "QueryDTOContext" } }, rankerType: { serializedName: "rankerType", type: { name: "String" } }, strictFilters: { serializedName: "strictFilters", type: { name: "Sequence", element: { type: { name: "Composite", className: "MetadataDTO" } } } } } } }; export const QnASearchResultContext: msRest.CompositeMapper = { serializedName: "QnASearchResult_context", type: { name: "Composite", className: "QnASearchResultContext", modelProperties: { ...ContextDTO.type.modelProperties } } }; export const QnASearchResult: msRest.CompositeMapper = { serializedName: "QnASearchResult", type: { name: "Composite", className: "QnASearchResult", modelProperties: { questions: { serializedName: "questions", type: { name: "Sequence", element: { type: { name: "String" } } } }, answer: { serializedName: "answer", type: { name: "String" } }, score: { serializedName: "score", type: { name: "Number" } }, id: { serializedName: "id", type: { name: "Number" } }, source: { serializedName: "source", type: { name: "String" } }, metadata: { serializedName: "metadata", type: { name: "Sequence", element: { type: { name: "Composite", className: "MetadataDTO" } } } }, context: { serializedName: "context", type: { name: "Composite", className: "QnASearchResultContext" } } } } }; export const QnASearchResultList: msRest.CompositeMapper = { serializedName: "QnASearchResultList", type: { name: "Composite", className: "QnASearchResultList", modelProperties: { answers: { serializedName: "answers", type: { name: "Sequence", element: { type: { name: "Composite", className: "QnASearchResult" } } } } } } }; export const FeedbackRecordDTO: msRest.CompositeMapper = { serializedName: "FeedbackRecordDTO", type: { name: "Composite", className: "FeedbackRecordDTO", modelProperties: { userId: { serializedName: "userId", type: { name: "String" } }, userQuestion: { serializedName: "userQuestion", constraints: { MaxLength: 1000 }, type: { name: "String" } }, qnaId: { serializedName: "qnaId", type: { name: "Number" } } } } }; export const FeedbackRecordsDTO: msRest.CompositeMapper = { serializedName: "FeedbackRecordsDTO", type: { name: "Composite", className: "FeedbackRecordsDTO", modelProperties: { feedbackRecords: { serializedName: "feedbackRecords", type: { name: "Sequence", element: { type: { name: "Composite", className: "FeedbackRecordDTO" } } } } } } };
the_stack
import { isSinglePageApp } from './spa-component'; import { resolveAssetsPath } from '../libs/iso-libs'; import * as deepmerge from 'deepmerge'; import { IConfigParseResult } from '../libs/config-parse-result'; import { IPlugin } from '../libs/plugin'; import { PARSER_MODES } from '../libs/parser'; import extractDomain from 'extract-domain'; /** * Parameters that apply to the whole Plugin, passed by other plugins */ export interface ISpaPlugin { /** * the stage is the environment to apply */ stage: string, /** * one of the [[PARSER_MODES]] */ parserMode: string, /** * path to a directory where we put the final bundles */ buildPath: string, /** * path to the main config file */ configFilePath: string } /** * A Plugin to detect SinglePage-App-Components * @param props */ export const SpaPlugin = (props: ISpaPlugin): IPlugin => { //console.log("configFilePath: " , props.configFilePath); const result: IPlugin = { // identify Isomorphic-App-Components applies: (component): boolean => { return isSinglePageApp(component); }, // convert the component into configuration parts process: ( component: any, childConfigs: Array<IConfigParseResult>, infrastructureMode: string | undefined ): IConfigParseResult => { const path = require('path'); const webappBuildPath = path.join(require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), props.buildPath); const spaWebPack = require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs") .complementWebpackConfig(require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs") .createClientWebpackConfig( "./"+path.join("node_modules", "infrastructure-components", "dist" , "assets", "spa.js"), //entryPath: string, path.join(require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), props.buildPath), //use the buildpath from the parent plugin component.id, //appName undefined, //assetsPath undefined, // stagePath: TODO take from Environment! { __CONFIG_FILE_PATH__: require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").pathToConfigFile(props.configFilePath), // replace the IsoConfig-Placeholder with the real path to the main-config-bundle // required of the routed-app "react-router-dom": path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), "node_modules", "react-router-dom"), // required of the data-layer / apollo "react-apollo": path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), "node_modules", "react-apollo"), }, { } ), props.parserMode === PARSER_MODES.MODE_DEPLOY //isProd ); // provide all client configs in a flat list const webpackConfigs: any = childConfigs.reduce((result, config) => result.concat(config.webpackConfigs), []); const createHtml = () => { //console.log("check for >>copyAssetsPostBuild<<"); //if (props.parserMode == PARSER_MODES.MODE_BUILD) { console.log("write the index.html!"); require('fs').writeFileSync(path.join(webappBuildPath, component.stackName, "index.html"), `<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>${component.stackName}</title> <style> body { display: block; margin: 0px; } </style> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="${component.stackName}.bundle.js"></script> </body> </html>`); }; // check whether we already created the domain of this environment const deployedDomain = process.env[`DOMAIN_${props.stage}`] !== undefined; const domain = childConfigs.map(config => config.domain).reduce((result, domain) => result !== undefined ? result : domain, undefined); const certArn = childConfigs.map(config => config.certArn).reduce((result, certArn) => result !== undefined ? result : certArn, undefined); const invalidateCloudFrontCache = () => { if (deployedDomain && props.parserMode === PARSER_MODES.MODE_DEPLOY) { require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").invalidateCloudFrontCache(domain); } } const hostedZoneName = domain !== undefined ? extractDomain(domain.toString()) : {}; /** post build function to write to the .env file that the domain has been deployed */ const writeDomainEnv = () => { //console.log("check for >>writeDomainEnv<<"); // we only write to the .env file when we are in domain mode, i.e. this script creates the domain // and we did not yet deployed the domain previously if (!deployedDomain && props.parserMode === PARSER_MODES.MODE_DOMAIN) { require('fs').appendFileSync( path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), ".env"), `\nDOMAIN_${props.stage}=TRUE` ); } }; /* const postDeploy = async () => { //console.log("check for >>showStaticPageName<<"); if (props.parserMode === PARSER_MODES.MODE_DEPLOY) { await require('../libs/scripts-libs').fetchData("deploy", { proj: component.stackName, envi: props.stage, domain: domain, endp: `http://${component.stackName}-${props.stage}.s3-website-${component.region}.amazonaws.com` }); console.log(`Your SinglePageApp is now available at: http://${component.stackName}-${props.stage}.s3-website-${component.region}.amazonaws.com`); } };*/ async function deployWithDomain() { // start the sls-config if (props.parserMode === PARSER_MODES.MODE_DOMAIN) { await require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").deploySls(component.stackName); } } /** * ONLY add the domain config if we are in domain mode! * TODO once the domain has been added, we need to add this with every deployment */ const domainConfig = (props.parserMode === PARSER_MODES.MODE_DOMAIN || deployedDomain) && domain !== undefined && certArn !== undefined ? { // required of the SPA-domain-alias provider: { customDomainName: domain, hostedZoneName: hostedZoneName, certArn: certArn }, resources: { Resources: { WebAppCloudFrontDistribution: { Type: "AWS::CloudFront::Distribution", Properties: { DistributionConfig: { Origins: [ { DomainName: "${self:provider.staticBucket}.s3.amazonaws.com", Id: component.stackName, CustomOriginConfig: { HTTPPort: 80, HTTPSPort: 443, OriginProtocolPolicy: "https-only", } } ], Enabled: "'true'", DefaultRootObject: "index.html", CustomErrorResponses: [{ ErrorCode: 404, ResponseCode: 200, ResponsePagePath: "/index.html" }], DefaultCacheBehavior: { AllowedMethods: [ "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT" ], TargetOriginId: component.stackName, ForwardedValues: { QueryString: "'false'", Cookies: { Forward: "none" } }, ViewerProtocolPolicy: "redirect-to-https" }, ViewerCertificate: { AcmCertificateArn: "${self:provider.certArn}", SslSupportMethod: "sni-only", }, Aliases: ["${self:provider.customDomainName}"] } } }, DnsRecord: { Type: "AWS::Route53::RecordSet", Properties: { AliasTarget: { DNSName: "!GetAtt WebAppCloudFrontDistribution.DomainName", HostedZoneId: "Z2FDTNDATAQYW2" }, HostedZoneName: "${self:provider.hostedZoneName}.", Name: "${self:provider.customDomainName}.", Type: "'A'" } } }, Outputs: { WebAppCloudFrontDistributionOutput: { Value: { "Fn::GetAtt": "[ WebAppCloudFrontDistribution, DomainName ]" } } } } } : {}; return { stackType: "SPA", slsConfigs: deepmerge.all([ require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").toSpaSlsConfig( component.stackName, component.buildPath, component.region, domain ), domainConfig, { plugins: ["serverless-pseudo-parameters"], /** we need to add a dummy value-anything-to custom. Otherwise, the pseudo-parameters plugin doesn't work*/ custom: { dummy: "none" } }, ...childConfigs.map(config => config.slsConfigs) ] ), // add the server config webpackConfigs: webpackConfigs.concat([spaWebPack]), postBuilds: childConfigs.reduce((result, config) => result.concat(config.postBuilds), [createHtml, writeDomainEnv, deployWithDomain, invalidateCloudFrontCache /*, postDeploy*/]), iamRoleStatements: [], environments: childConfigs.reduce((result, config) => (result !== undefined ? result : []).concat(config.environments !== undefined ? config.environments : []), []), stackName: component.stackName, assetsPath: undefined, buildPath: component.buildPath, region: component.region, domain: domain, certArn: certArn, // start the sls-stack offline does not work and does make sense either, we can use the hot-dev-mode supportOfflineStart: false, supportCreateDomain: true } } } return result; };
the_stack
import { css } from '@emotion/react'; import { border, neutral, text, textSans, from, until, space, } from '@guardian/source-foundations'; import { ArticleDisplay } from '@guardian/libs'; import { adSizes } from '@guardian/commercial-core'; type Props = { display: ArticleDisplay; position: AdSlotType; }; export const labelHeight = 24; const adSlotLabelStyles = css` ${textSans.xxsmall()}; position: relative; height: ${labelHeight}px; background-color: ${neutral[97]}; padding: 0 8px; border-top: 1px solid ${border.secondary}; color: ${text.supporting}; text-align: left; box-sizing: border-box; &.visible { visibility: initial; } &.hidden { visibility: hidden; } &.ad-slot__label--toggle { margin: 0 auto; ${until.tablet} { display: none; } } `; const outOfPageStyles = css` height: 0; `; export const labelStyles = css` .ad-slot__label, .ad-slot__scroll { ${adSlotLabelStyles} } .ad-slot__close-button { display: none; } .ad-slot__scroll { position: fixed; bottom: 0; width: 100%; } `; export const adCollapseStyles = css` & .ad-slot.ad-slot--collapse { display: none; } `; /** * For implementation in Frontend, see mark: dca5c7dd-dda4-4922-9317-a55a3789fe4c * These styles come mostly from RichLink in DCR. */ export const carrotAdStyles = css` .ad-slot--carrot { float: left; clear: both; width: 140px; margin-right: 20px; margin-bottom: ${space[1]}px; ${from.leftCol} { position: relative; margin-left: -160px; width: 140px; } ${from.wide} { margin-left: -240px; width: 220px; } } `; /** * For CSS in Frontend, see mark: 9473ae05-a901-4a8d-a51d-1b9c894d6e1f */ const fluidAdStyles = css` &.ad-slot--fluid { min-height: 250px; line-height: 10px; padding: 0; margin: 0; } `; /** * Usage according to DAP (Digital Ad Production) * * #### Desktop * - `fabric` &rarr; `top-above-nav`,`merchandising-high`,`merchandising` * - `fabric-custom` &rarr; `top-above-nav`,`merchandising-high`,`merchandising` * - `fabric-expandable` &rarr; `merchandising-high` * - `fabric-third-party` &rarr; `top-above-nav`,`merchandising-high`,`merchandising` * - `fabric-video` &rarr; `top-above-nav`,`merchandising-high` * - `fabric-video-expandable` &rarr; `merchandising-high` * * #### Mobile * - `interscroller` &rarr; `top-above-nav` * - `mobile-revealer` &rarr; `top-above-nav` */ const fluidFullWidthAdStyles = css` &.ad-slot--fluid { width: 100%; } `; const mobileStickyAdStyles = css` position: fixed; bottom: 0; width: 320px; margin: 0 auto; right: 0; left: 0; z-index: 1010; ${from.phablet} { display: none; } .ad-slot__close-button { display: none; position: absolute; right: 3px; top: 3px; padding: 0; border: 0; height: 21px; width: 21px; background-color: transparent; } .ad-slot__close-button svg { height: 0.75rem; width: 0.75rem; stroke: ${neutral[7]}; fill: ${neutral[7]}; stroke-linecap: round; stroke-width: 0; text-align: center; } .ad-slot--mobile-sticky .ad-slot__label .ad-slot__close-button { display: block; } .ad-slot__close-button__x { stroke: ${neutral[7]}; fill: transparent; stroke-linecap: round; stroke-width: 2; text-align: center; } .ad-slot__label { font-size: 0.75rem; line-height: 1.25rem; position: relative; height: 1.5rem; background-color: ${neutral[97]}; padding: 0 0.5rem; border-top: 0.0625rem solid ${border.secondary}; color: ${neutral[60]}; text-align: left; box-sizing: border-box; ${textSans.xxsmall()}; } `; const adStyles = [labelStyles, fluidAdStyles]; const AdSlotLabelToggled: React.FC = () => ( <div className={['ad-slot__label', 'ad-slot__label--toggle', 'hidden'].join( ' ', )} css={adSlotLabelStyles} > Advertisement </div> ); export const AdSlot: React.FC<Props> = ({ position, display }) => { switch (position) { case 'right': switch (display) { case ArticleDisplay.Immersive: case ArticleDisplay.Showcase: case ArticleDisplay.NumberedList: { return ( <div id="dfp-ad--right" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--right', 'ad-slot--mpu-banner-ad', 'ad-slot--rendered', 'js-sticky-mpu', ].join(' ')} css={adStyles} data-link-name="ad slot right" data-name="right" // mark: 01303e88-ef1f-462d-9b6e-242419435cec data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.halfPage, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> ); } case ArticleDisplay.Standard: { const MOSTVIEWED_STICKY_HEIGHT = 1059; return ( <div id="top-right-ad-slot" css={css` position: static; height: ${MOSTVIEWED_STICKY_HEIGHT}px; `} > <div id="dfp-ad--right" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--right', 'ad-slot--mpu-banner-ad', 'ad-slot--rendered', 'js-sticky-mpu', ].join(' ')} css={[ css` position: sticky; top: 0; `, adStyles, ]} data-link-name="ad slot right" data-name="right" // mark: 01303e88-ef1f-462d-9b6e-242419435cec data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.halfPage, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> </div> ); } default: return null; } case 'comments': { return ( <div css={css` position: static; height: 100%; `} > <div id="dfp-ad--comments" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--comments', 'ad-slot--mpu-banner-ad', 'ad-slot--rendered', 'js-sticky-mpu', ].join(' ')} css={[ css` position: sticky; top: 0; width: 300px; `, adStyles, ]} data-link-name="ad slot comments" data-name="comments" data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.halfPage, adSizes.outstreamMobile, adSizes.mpu, adSizes.googleCard, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} data-desktop={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.video, adSizes.outstreamDesktop, adSizes.outstreamGoogleDesktop, adSizes.fluid, adSizes.halfPage, adSizes.skyscraper, ] .map((size) => size.toString()) .join('|')} data-phablet={[ adSizes.outOfPage, adSizes.empty, adSizes.outstreamMobile, adSizes.mpu, adSizes.googleCard, adSizes.outstreamDesktop, adSizes.outstreamGoogleDesktop, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> </div> ); } case 'top-above-nav': { const adSlotAboveNav = css` position: relative; margin: 0 auto; min-height: ${adSizes.leaderboard.height}px; text-align: left; display: block; min-width: 728px; `; return ( <> <AdSlotLabelToggled /> <div id="dfp-ad--top-above-nav" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--top-above-nav', 'ad-slot--mpu-banner-ad', 'ad-slot--rendered', ].join(' ')} css={[adStyles, fluidFullWidthAdStyles, adSlotAboveNav]} data-link-name="ad slot top-above-nav" data-name="top-above-nav" // The sizes here come from two places in the frontend code // 1. file mark: 432b3a46-90c1-4573-90d3-2400b51af8d0 // 2. file mark: c66fae4e-1d29-467a-a081-caad7a90cacd data-tablet={[ adSizes.outOfPage, adSizes.empty, adSizes.fabric, adSizes.fluid, adSizes.leaderboard, ] .map((size) => size.toString()) .join('|')} data-desktop={[ adSizes.outOfPage, adSizes.empty, adSizes.leaderboard, `940,230`, `900,250`, adSizes.billboard, adSizes.fabric, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} // Values from file mark: c66fae4e-1d29-467a-a081-caad7a90cacd aria-hidden="true" /> </> ); } case 'mostpop': { return ( <div id="dfp-ad--mostpop" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--mostpop', 'ad-slot--mpu-banner-ad', 'ad-slot--rendered', ].join(' ')} css={[ css` position: relative; `, adStyles, ]} data-link-name="ad slot mostpop" data-name="mostpop" // mirror frontend file mark: 432b3a46-90c1-4573-90d3-2400b51af8d0 data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} data-tablet={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.halfPage, adSizes.leaderboard, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} data-phablet={[ adSizes.outOfPage, adSizes.empty, adSizes.outstreamMobile, adSizes.mpu, adSizes.googleCard, adSizes.halfPage, adSizes.outstreamGoogleDesktop, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} data-desktop={[ adSizes.outOfPage, adSizes.empty, adSizes.mpu, adSizes.googleCard, adSizes.halfPage, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> ); } case 'merchandising-high': { return ( <div id="dfp-ad--merchandising-high" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--merchandising-high', ].join(' ')} css={[ css` position: relative; `, adStyles, fluidFullWidthAdStyles, ]} data-link-name="ad slot merchandising-high" data-name="merchandising-high" // mirror frontend file mark: 432b3a46-90c1-4573-90d3-2400b51af8d0 data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.merchandisingHigh, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> ); } case 'merchandising': { return ( <div id="dfp-ad--merchandising" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--merchandising', ].join(' ')} css={[ css` position: relative; `, adStyles, fluidFullWidthAdStyles, ]} data-link-name="ad slot merchandising" data-name="merchandising" // mirror frontend file mark: 432b3a46-90c1-4573-90d3-2400b51af8d0 data-mobile={[ adSizes.outOfPage, adSizes.empty, adSizes.merchandising, adSizes.fluid, ] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> ); } case 'survey': { return ( <div id="dfp-ad--survey" className={[ 'js-ad-slot', 'ad-slot', 'ad-slot--survey', ].join(' ')} css={outOfPageStyles} data-link-name="ad slot survey" data-name="survey" data-label="false" data-refresh="false" data-out-of-page="true" data-desktop={[adSizes.outOfPage] .map((size) => size.toString()) .join('|')} aria-hidden="true" /> ); } default: return null; } }; export const MobileStickyContainer: React.FC = () => { return ( <div className="mobilesticky-container" css={mobileStickyAdStyles} /> ); };
the_stack
import {assert} from '../../platform/chai-web.js'; import {RenderPacket} from '../slot-observer.js'; import {AbstractSlotObserver} from '../slot-observer.js'; const logging = false; const log = !logging ? (...args) => {} : console.log.bind(console, 'SlotTestObserver::'); type SlotTestObserverOptions = { strict?: boolean; logging?: boolean; }; /** * A helper SlotObserver allowing expressing and asserting expectations on slot rendering. * Usage example: * observer * .newExpectations() * .expectRenderSlot('MyParticle1', 'mySlot1'); * .expectRenderSlot('MyParticle1', 'mySlot1', {times: 2}) * .expectRenderSlot('MyParticle2', 'mySlot2', {verify: (content) => !!content.myParam}) * .expectRenderSlot('MyOptionalParticle', 'myOptionalSlot', {isOptional: true}) * await observer.expectationsCompleted(); */ export class SlotTestObserver extends AbstractSlotObserver { private expectQueue; onExpectationsComplete; strict: boolean; logging: boolean; debugMessages; pec; /** * |options| may contain: * - strict: whether unexpected render slot requests cause an assert or a warning log (default: true) */ constructor(options: SlotTestObserverOptions = {}) { super(); this.expectQueue = []; this.onExpectationsComplete = () => undefined; this.strict = options.strict != undefined ? options.strict : true; this.logging = Boolean(options.logging); this.debugMessages = []; } /** * Reinitializes expectations queue. */ newExpectations(name?: string) { this.expectQueue = []; if (!this.strict) { this.ignoreUnexpectedRender(); } this.debugMessages.push({name: name || `debug${Object.keys(this.debugMessages).length}`, messages: []}); return this; } /** * Allows ignoring unexpected render slot requests. */ ignoreUnexpectedRender() { this.expectQueue.push({type: 'render', ignoreUnexpected: true, isOptional: true, toString: () => `render: ignoreUnexpected optional`}); return this; } /** * Returns true, if the number of items in content's model is equal to the given number. */ expectContentItemsNumber(num: number, content) { assert(content.model, `Content doesn't have model`); assert(content.model.items, `Content model doesn't have items (${num} expected}`); assert(content.model.items.length <= num, `Too many items (${content.model.items.length}), while only ${num} were expected.`); return content.model.items.length === num; } /** * Adds a rendering expectation for the given particle and slot names, where options may contain: * times: number of time the rendering request will occur * contentTypes: the types appearing in the rendering content * isOptional: whether this expectation is optional (default: false) * hostedParticle: for transformation particles, the name of the hosted particle * verify: an additional optional handler that determines whether the incoming render request satisfies the expectation */ expectRenderSlot(particleName, slotName, options?) { options = options || {}; const times = options.times || 1; for (let i = 0; i < times; ++i) { this.addRenderExpectation({ particleName, slotName, isOptional: options.isOptional, hostedParticle: options.hostedParticle, verifyComplete: options.verify, ignoreUnexpected: options.ignoreUnexpected }); } return this; } addRenderExpectation(expectation) { //let current = this.expectQueue.find(e => // e.particleName === expectation.particleName // && e.slotName === expectation.slotName // && e.hostedParticle === expectation.hostedParticle // && e.isOptional === expectation.isOptional // ); // if (!current) { const {particleName, slotName, hostedParticle, isOptional, ignoreUnexpected, verifyComplete} = expectation; const toString = () => `render:${isOptional ? ' optional' : ' '} ${particleName}:${slotName} ${hostedParticle}`; // ${contentTypes}` const current = { type: 'render', particleName, slotName, hostedParticle, isOptional, ignoreUnexpected, toString, verifyComplete }; this.expectQueue.push(current); // } // if (expectation.verifyComplete) { // assert(!current.verifyComplete); // current.verifyComplete = expectation.verifyComplete; // } //current.contentTypes = (current.contentTypes || []).concat(expectation.contentTypes); return this; } /** * Returns promise to completion of all expectations. */ async expectationsCompleted(): Promise<void> { if (this.onlyOptionalExpectations()) { return Promise.resolve(); } return new Promise((resolve, reject) => { this.onExpectationsComplete = resolve; }); } assertExpectationsCompleted() { if (this.onlyOptionalExpectations()) { return true; } assert(false, `${this.debugMessagesToString()}\nremaining expectations:\n ${this.expectQueue.map(expect => ` ${expect.toString()}`).join('\n')}`); return undefined; } onlyOptionalExpectations() { return (this.expectQueue.length === 0 || this.expectQueue.every(e => e.isOptional)); } //TODO: reaching directly into data objects like this is super dodgy and we should // fix. It's particularly bad here as there's no guarantee that the backingStore // exists - should await ensureBackingStore() before accessing it. // _getHostedParticleNames(particle: Particle) { // return Object.values(particle.connections) // .filter(conn => conn.type instanceof InterfaceType) // .map(conn => { // const allArcs = this.consumers.reduce((arcs, consumer) => arcs.add(consumer.arc), new Set<Arc>()); // const store = [...allArcs].map(arc => arc.findStoreById(conn.handle.id)).find(store => !!store) as StorageProviderBase; // if (store.referenceMode) { // // TODO(cypher1): Unsafe. _stored does not exist on StorageProviderBase. // // tslint:disable-next-line: no-any // return store.backingStore._model.getValue((store as any)._stored.id).name; // } // // TODO(cypher1): Unsafe. _stored does not exist on StorageProviderBase. // // tslint:disable-next-line: no-any // return (store as any)._stored.name; // }); // } observe(packet: RenderPacket) { const {particle, containerSlotName: slotName, content} = packet; log(`observe: ${particle.name}:${slotName}`); log('queue:', this.expectQueue.map(e => `${e.particleName}:${e.slotName}`).join(',')); //const names = this._getHostedParticleNames(particle); //const nameJoin = names.length > 0 ? `(${names.join(',')}) ` : '(no-names)'; const nameJoin = '(names not available)'; this.addDebugMessages(` renderSlot ${particle.name} ${nameJoin}: ${slotName} - ${Object.keys(content).join(', ')}`); assert.isAbove(this.expectQueue.length, 0, `observed a render packet for ${particle.name}:${slotName}}), but not expecting anything further. Enable {strict: false, logging: true} to diagnose`); const found = this.verifyRenderContent(particle, slotName, content); if (!found) { const canIgnore = this.canIgnore(particle.name, slotName, content); const info = `${particle.name}:${slotName}`; // (content types: ${Object.keys(content).join(', ')})`; if (canIgnore && !SlotTestObserver['warnedIgnore']) { SlotTestObserver['warnedIgnore'] = true; console.log(`Skipping unexpected render slot request: ${info}`); console.log('expected? add this line:'); console.log(` .expectRenderSlot('${particle.name}', '${slotName}', {'contentTypes': ['${Object.keys(content).join('\', \'')}']})`); console.log(`(additional warnings are suppressed)`); } //console.log('slot-test-observer: queue:', this.expectQueue); assert(canIgnore, `Unexpected render slot ${info}`); } this.expectationsMet(); this.detailedLogDebug(); } verifyRenderContent(particle, slotName, content) { const index = this.expectQueue.findIndex(e => e.type === 'render' && e.particleName === particle.name && e.slotName === slotName // && (!e.hostedParticle || ((names) => names.length === 1 && names[0] === e.hostedParticle)(this._getHostedParticleNames(particle))); ); if (index < 0) { return false; } const expectation = this.expectQueue[index]; let found = true; let complete = true; if (expectation.verifyComplete) { found = true; complete = expectation.verifyComplete(content); } if (complete) { this.expectQueue.splice(index, 1); } return found; } canIgnore(particleName: string, slotName: string, content): boolean { // TODO: add support for ignoring specific particles and/or slots. return this.expectQueue.find(e => e.type === 'render' && e.ignoreUnexpected); } expectationsMet(): void { if (this.expectQueue.length === 0 || this.onlyOptionalExpectations()) { this.onExpectationsComplete(); } } detailedLogDebug() { const expect = {}; this.expectQueue.forEach(e => { if (!expect[e.particleName]) { expect[e.particleName] = {}; } }); this.addDebugMessages(`${this.expectQueue.length} expectations : {${Object.keys(expect).map(p => { return `${p}: (${Object.keys(expect[p]).map(key => `${key}=${expect[p][key]}`).join('; ')})`; }).join(', ')}}`); return this; } addDebugMessages(message) { assert(this.debugMessages.length > 0, 'debugMessages length is 0'); this.debugMessages[this.debugMessages.length - 1].messages.push(message); if (this.logging) { console.log(message); } } debugMessagesToString(): string { const result: string[] = []; result.push('--------------------------------------------'); this.debugMessages.forEach(debug => { result.push(`${debug.name} : `); debug.messages.forEach(message => result.push(message)); result.push('----------------------'); }); return result.join('\n'); } }
the_stack
import { tree } from 'antlr4'; // This class defines a complete listener for a parse tree produced by SqlBaseParser. export const SqlBaseListener = function() { tree.ParseTreeListener.call(this); return this; } as any; SqlBaseListener.prototype = Object.create(tree.ParseTreeListener.prototype); SqlBaseListener.prototype.constructor = SqlBaseListener; // Enter a parse tree produced by SqlBaseParser#multiStatement. SqlBaseListener.prototype.enterMultiStatement = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#multiStatement. SqlBaseListener.prototype.exitMultiStatement = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#singleStatement. SqlBaseListener.prototype.enterSingleStatement = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#singleStatement. SqlBaseListener.prototype.exitSingleStatement = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#singleExpression. SqlBaseListener.prototype.enterSingleExpression = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#singleExpression. SqlBaseListener.prototype.exitSingleExpression = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#statementDefault. SqlBaseListener.prototype.enterStatementDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#statementDefault. SqlBaseListener.prototype.exitStatementDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#use. SqlBaseListener.prototype.enterUse = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#use. SqlBaseListener.prototype.exitUse = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#createSchema. SqlBaseListener.prototype.enterCreateSchema = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#createSchema. SqlBaseListener.prototype.exitCreateSchema = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#dropSchema. SqlBaseListener.prototype.enterDropSchema = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#dropSchema. SqlBaseListener.prototype.exitDropSchema = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#renameSchema. SqlBaseListener.prototype.enterRenameSchema = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#renameSchema. SqlBaseListener.prototype.exitRenameSchema = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#createTableAsSelect. SqlBaseListener.prototype.enterCreateTableAsSelect = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#createTableAsSelect. SqlBaseListener.prototype.exitCreateTableAsSelect = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#createTable. SqlBaseListener.prototype.enterCreateTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#createTable. SqlBaseListener.prototype.exitCreateTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#dropTable. SqlBaseListener.prototype.enterDropTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#dropTable. SqlBaseListener.prototype.exitDropTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#insertInto. SqlBaseListener.prototype.enterInsertInto = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#insertInto. SqlBaseListener.prototype.exitInsertInto = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#delete. SqlBaseListener.prototype.enterDelete = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#delete. SqlBaseListener.prototype.exitDelete = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#renameTable. SqlBaseListener.prototype.enterRenameTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#renameTable. SqlBaseListener.prototype.exitRenameTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#renameColumn. SqlBaseListener.prototype.enterRenameColumn = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#renameColumn. SqlBaseListener.prototype.exitRenameColumn = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#addColumn. SqlBaseListener.prototype.enterAddColumn = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#addColumn. SqlBaseListener.prototype.exitAddColumn = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#createView. SqlBaseListener.prototype.enterCreateView = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#createView. SqlBaseListener.prototype.exitCreateView = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#dropView. SqlBaseListener.prototype.enterDropView = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#dropView. SqlBaseListener.prototype.exitDropView = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#call. SqlBaseListener.prototype.enterCall = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#call. SqlBaseListener.prototype.exitCall = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#grant. SqlBaseListener.prototype.enterGrant = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#grant. SqlBaseListener.prototype.exitGrant = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#revoke. SqlBaseListener.prototype.enterRevoke = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#revoke. SqlBaseListener.prototype.exitRevoke = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#explain. SqlBaseListener.prototype.enterExplain = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#explain. SqlBaseListener.prototype.exitExplain = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showCreateTable. SqlBaseListener.prototype.enterShowCreateTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showCreateTable. SqlBaseListener.prototype.exitShowCreateTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showCreateView. SqlBaseListener.prototype.enterShowCreateView = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showCreateView. SqlBaseListener.prototype.exitShowCreateView = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showTables. SqlBaseListener.prototype.enterShowTables = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showTables. SqlBaseListener.prototype.exitShowTables = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showSchemas. SqlBaseListener.prototype.enterShowSchemas = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showSchemas. SqlBaseListener.prototype.exitShowSchemas = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showCatalogs. SqlBaseListener.prototype.enterShowCatalogs = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showCatalogs. SqlBaseListener.prototype.exitShowCatalogs = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showColumns. SqlBaseListener.prototype.enterShowColumns = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showColumns. SqlBaseListener.prototype.exitShowColumns = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showFunctions. SqlBaseListener.prototype.enterShowFunctions = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showFunctions. SqlBaseListener.prototype.exitShowFunctions = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showSession. SqlBaseListener.prototype.enterShowSession = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showSession. SqlBaseListener.prototype.exitShowSession = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#setSession. SqlBaseListener.prototype.enterSetSession = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#setSession. SqlBaseListener.prototype.exitSetSession = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#resetSession. SqlBaseListener.prototype.enterResetSession = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#resetSession. SqlBaseListener.prototype.exitResetSession = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#startTransaction. SqlBaseListener.prototype.enterStartTransaction = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#startTransaction. SqlBaseListener.prototype.exitStartTransaction = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#commit. SqlBaseListener.prototype.enterCommit = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#commit. SqlBaseListener.prototype.exitCommit = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#rollback. SqlBaseListener.prototype.enterRollback = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#rollback. SqlBaseListener.prototype.exitRollback = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#showPartitions. SqlBaseListener.prototype.enterShowPartitions = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#showPartitions. SqlBaseListener.prototype.exitShowPartitions = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#prepare. SqlBaseListener.prototype.enterPrepare = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#prepare. SqlBaseListener.prototype.exitPrepare = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#deallocate. SqlBaseListener.prototype.enterDeallocate = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#deallocate. SqlBaseListener.prototype.exitDeallocate = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#execute. SqlBaseListener.prototype.enterExecute = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#execute. SqlBaseListener.prototype.exitExecute = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#describeInput. SqlBaseListener.prototype.enterDescribeInput = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#describeInput. SqlBaseListener.prototype.exitDescribeInput = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#describeOutput. SqlBaseListener.prototype.enterDescribeOutput = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#describeOutput. SqlBaseListener.prototype.exitDescribeOutput = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#query. SqlBaseListener.prototype.enterQuery = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#query. SqlBaseListener.prototype.exitQuery = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#presto_with. SqlBaseListener.prototype.enterPresto_with = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#presto_with. SqlBaseListener.prototype.exitPresto_with = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#tableElement. SqlBaseListener.prototype.enterTableElement = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#tableElement. SqlBaseListener.prototype.exitTableElement = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#columnDefinition. SqlBaseListener.prototype.enterColumnDefinition = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#columnDefinition. SqlBaseListener.prototype.exitColumnDefinition = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#likeClause. SqlBaseListener.prototype.enterLikeClause = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#likeClause. SqlBaseListener.prototype.exitLikeClause = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#tableProperties. SqlBaseListener.prototype.enterTableProperties = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#tableProperties. SqlBaseListener.prototype.exitTableProperties = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#tableProperty. SqlBaseListener.prototype.enterTableProperty = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#tableProperty. SqlBaseListener.prototype.exitTableProperty = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#queryNoWith. SqlBaseListener.prototype.enterQueryNoWith = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#queryNoWith. SqlBaseListener.prototype.exitQueryNoWith = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#queryTermDefault. SqlBaseListener.prototype.enterQueryTermDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#queryTermDefault. SqlBaseListener.prototype.exitQueryTermDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#setOperation. SqlBaseListener.prototype.enterSetOperation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#setOperation. SqlBaseListener.prototype.exitSetOperation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#queryPrimaryDefault. SqlBaseListener.prototype.enterQueryPrimaryDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#queryPrimaryDefault. SqlBaseListener.prototype.exitQueryPrimaryDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#table. SqlBaseListener.prototype.enterTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#table. SqlBaseListener.prototype.exitTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#inlineTable. SqlBaseListener.prototype.enterInlineTable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#inlineTable. SqlBaseListener.prototype.exitInlineTable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#subquery. SqlBaseListener.prototype.enterSubquery = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#subquery. SqlBaseListener.prototype.exitSubquery = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#sortItem. SqlBaseListener.prototype.enterSortItem = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#sortItem. SqlBaseListener.prototype.exitSortItem = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#querySpecification. SqlBaseListener.prototype.enterQuerySpecification = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#querySpecification. SqlBaseListener.prototype.exitQuerySpecification = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#groupBy. SqlBaseListener.prototype.enterGroupBy = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#groupBy. SqlBaseListener.prototype.exitGroupBy = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#singleGroupingSet. SqlBaseListener.prototype.enterSingleGroupingSet = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#singleGroupingSet. SqlBaseListener.prototype.exitSingleGroupingSet = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#rollup. SqlBaseListener.prototype.enterRollup = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#rollup. SqlBaseListener.prototype.exitRollup = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#cube. SqlBaseListener.prototype.enterCube = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#cube. SqlBaseListener.prototype.exitCube = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#multipleGroupingSets. SqlBaseListener.prototype.enterMultipleGroupingSets = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#multipleGroupingSets. SqlBaseListener.prototype.exitMultipleGroupingSets = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#groupingExpressions. SqlBaseListener.prototype.enterGroupingExpressions = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#groupingExpressions. SqlBaseListener.prototype.exitGroupingExpressions = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#groupingSet. SqlBaseListener.prototype.enterGroupingSet = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#groupingSet. SqlBaseListener.prototype.exitGroupingSet = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#namedQuery. SqlBaseListener.prototype.enterNamedQuery = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#namedQuery. SqlBaseListener.prototype.exitNamedQuery = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#setQuantifier. SqlBaseListener.prototype.enterSetQuantifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#setQuantifier. SqlBaseListener.prototype.exitSetQuantifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#selectSingle. SqlBaseListener.prototype.enterSelectSingle = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#selectSingle. SqlBaseListener.prototype.exitSelectSingle = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#selectAll. SqlBaseListener.prototype.enterSelectAll = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#selectAll. SqlBaseListener.prototype.exitSelectAll = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#relationDefault. SqlBaseListener.prototype.enterRelationDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#relationDefault. SqlBaseListener.prototype.exitRelationDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#joinRelation. SqlBaseListener.prototype.enterJoinRelation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#joinRelation. SqlBaseListener.prototype.exitJoinRelation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#joinType. SqlBaseListener.prototype.enterJoinType = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#joinType. SqlBaseListener.prototype.exitJoinType = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#joinCriteria. SqlBaseListener.prototype.enterJoinCriteria = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#joinCriteria. SqlBaseListener.prototype.exitJoinCriteria = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#sampledRelation. SqlBaseListener.prototype.enterSampledRelation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#sampledRelation. SqlBaseListener.prototype.exitSampledRelation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#sampleType. SqlBaseListener.prototype.enterSampleType = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#sampleType. SqlBaseListener.prototype.exitSampleType = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#aliasedRelation. SqlBaseListener.prototype.enterAliasedRelation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#aliasedRelation. SqlBaseListener.prototype.exitAliasedRelation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#columnAliases. SqlBaseListener.prototype.enterColumnAliases = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#columnAliases. SqlBaseListener.prototype.exitColumnAliases = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#tableName. SqlBaseListener.prototype.enterTableName = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#tableName. SqlBaseListener.prototype.exitTableName = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#subqueryRelation. SqlBaseListener.prototype.enterSubqueryRelation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#subqueryRelation. SqlBaseListener.prototype.exitSubqueryRelation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#unnest. SqlBaseListener.prototype.enterUnnest = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#unnest. SqlBaseListener.prototype.exitUnnest = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#parenthesizedRelation. SqlBaseListener.prototype.enterParenthesizedRelation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#parenthesizedRelation. SqlBaseListener.prototype.exitParenthesizedRelation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#expression. SqlBaseListener.prototype.enterExpression = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#expression. SqlBaseListener.prototype.exitExpression = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#logicalNot. SqlBaseListener.prototype.enterLogicalNot = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#logicalNot. SqlBaseListener.prototype.exitLogicalNot = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#booleanDefault. SqlBaseListener.prototype.enterBooleanDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#booleanDefault. SqlBaseListener.prototype.exitBooleanDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#logicalBinary. SqlBaseListener.prototype.enterLogicalBinary = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#logicalBinary. SqlBaseListener.prototype.exitLogicalBinary = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#predicated. SqlBaseListener.prototype.enterPredicated = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#predicated. SqlBaseListener.prototype.exitPredicated = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#comparison. SqlBaseListener.prototype.enterComparison = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#comparison. SqlBaseListener.prototype.exitComparison = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#quantifiedComparison. SqlBaseListener.prototype.enterQuantifiedComparison = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#quantifiedComparison. SqlBaseListener.prototype.exitQuantifiedComparison = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#between. SqlBaseListener.prototype.enterBetween = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#between. SqlBaseListener.prototype.exitBetween = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#inList. SqlBaseListener.prototype.enterInList = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#inList. SqlBaseListener.prototype.exitInList = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#inSubquery. SqlBaseListener.prototype.enterInSubquery = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#inSubquery. SqlBaseListener.prototype.exitInSubquery = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#like. SqlBaseListener.prototype.enterLike = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#like. SqlBaseListener.prototype.exitLike = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#nullPredicate. SqlBaseListener.prototype.enterNullPredicate = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#nullPredicate. SqlBaseListener.prototype.exitNullPredicate = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#distinctFrom. SqlBaseListener.prototype.enterDistinctFrom = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#distinctFrom. SqlBaseListener.prototype.exitDistinctFrom = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#valueExpressionDefault. SqlBaseListener.prototype.enterValueExpressionDefault = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#valueExpressionDefault. SqlBaseListener.prototype.exitValueExpressionDefault = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#concatenation. SqlBaseListener.prototype.enterConcatenation = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#concatenation. SqlBaseListener.prototype.exitConcatenation = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#arithmeticBinary. SqlBaseListener.prototype.enterArithmeticBinary = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#arithmeticBinary. SqlBaseListener.prototype.exitArithmeticBinary = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#arithmeticUnary. SqlBaseListener.prototype.enterArithmeticUnary = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#arithmeticUnary. SqlBaseListener.prototype.exitArithmeticUnary = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#atTimeZone. SqlBaseListener.prototype.enterAtTimeZone = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#atTimeZone. SqlBaseListener.prototype.exitAtTimeZone = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#dereference. SqlBaseListener.prototype.enterDereference = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#dereference. SqlBaseListener.prototype.exitDereference = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#typeConstructor. SqlBaseListener.prototype.enterTypeConstructor = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#typeConstructor. SqlBaseListener.prototype.exitTypeConstructor = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#specialDateTimeFunction. SqlBaseListener.prototype.enterSpecialDateTimeFunction = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#specialDateTimeFunction. SqlBaseListener.prototype.exitSpecialDateTimeFunction = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#substring. SqlBaseListener.prototype.enterSubstring = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#substring. SqlBaseListener.prototype.exitSubstring = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#cast. SqlBaseListener.prototype.enterCast = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#cast. SqlBaseListener.prototype.exitCast = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#lambda. SqlBaseListener.prototype.enterLambda = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#lambda. SqlBaseListener.prototype.exitLambda = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#parameter. SqlBaseListener.prototype.enterParameter = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#parameter. SqlBaseListener.prototype.exitParameter = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#normalize. SqlBaseListener.prototype.enterNormalize = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#normalize. SqlBaseListener.prototype.exitNormalize = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#intervalLiteral. SqlBaseListener.prototype.enterIntervalLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#intervalLiteral. SqlBaseListener.prototype.exitIntervalLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#numericLiteral. SqlBaseListener.prototype.enterNumericLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#numericLiteral. SqlBaseListener.prototype.exitNumericLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#booleanLiteral. SqlBaseListener.prototype.enterBooleanLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#booleanLiteral. SqlBaseListener.prototype.exitBooleanLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#implicitRowConstructor. SqlBaseListener.prototype.enterImplicitRowConstructor = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#implicitRowConstructor. SqlBaseListener.prototype.exitImplicitRowConstructor = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#simpleCase. SqlBaseListener.prototype.enterSimpleCase = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#simpleCase. SqlBaseListener.prototype.exitSimpleCase = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#columnReference. SqlBaseListener.prototype.enterColumnReference = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#columnReference. SqlBaseListener.prototype.exitColumnReference = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#nullLiteral. SqlBaseListener.prototype.enterNullLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#nullLiteral. SqlBaseListener.prototype.exitNullLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#rowConstructor. SqlBaseListener.prototype.enterRowConstructor = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#rowConstructor. SqlBaseListener.prototype.exitRowConstructor = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#subscript. SqlBaseListener.prototype.enterSubscript = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#subscript. SqlBaseListener.prototype.exitSubscript = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#subqueryExpression. SqlBaseListener.prototype.enterSubqueryExpression = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#subqueryExpression. SqlBaseListener.prototype.exitSubqueryExpression = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#binaryLiteral. SqlBaseListener.prototype.enterBinaryLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#binaryLiteral. SqlBaseListener.prototype.exitBinaryLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#extract. SqlBaseListener.prototype.enterExtract = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#extract. SqlBaseListener.prototype.exitExtract = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#stringLiteral. SqlBaseListener.prototype.enterStringLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#stringLiteral. SqlBaseListener.prototype.exitStringLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#arrayConstructor. SqlBaseListener.prototype.enterArrayConstructor = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#arrayConstructor. SqlBaseListener.prototype.exitArrayConstructor = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#functionCall. SqlBaseListener.prototype.enterFunctionCall = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#functionCall. SqlBaseListener.prototype.exitFunctionCall = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#exists. SqlBaseListener.prototype.enterExists = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#exists. SqlBaseListener.prototype.exitExists = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#position. SqlBaseListener.prototype.enterPosition = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#position. SqlBaseListener.prototype.exitPosition = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#searchedCase. SqlBaseListener.prototype.enterSearchedCase = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#searchedCase. SqlBaseListener.prototype.exitSearchedCase = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#timeZoneInterval. SqlBaseListener.prototype.enterTimeZoneInterval = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#timeZoneInterval. SqlBaseListener.prototype.exitTimeZoneInterval = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#timeZoneString. SqlBaseListener.prototype.enterTimeZoneString = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#timeZoneString. SqlBaseListener.prototype.exitTimeZoneString = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#comparisonOperator. SqlBaseListener.prototype.enterComparisonOperator = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#comparisonOperator. SqlBaseListener.prototype.exitComparisonOperator = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#comparisonQuantifier. SqlBaseListener.prototype.enterComparisonQuantifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#comparisonQuantifier. SqlBaseListener.prototype.exitComparisonQuantifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#booleanValue. SqlBaseListener.prototype.enterBooleanValue = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#booleanValue. SqlBaseListener.prototype.exitBooleanValue = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#interval. SqlBaseListener.prototype.enterInterval = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#interval. SqlBaseListener.prototype.exitInterval = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#intervalField. SqlBaseListener.prototype.enterIntervalField = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#intervalField. SqlBaseListener.prototype.exitIntervalField = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#type. SqlBaseListener.prototype.enterType = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#type. SqlBaseListener.prototype.exitType = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#typeParameter. SqlBaseListener.prototype.enterTypeParameter = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#typeParameter. SqlBaseListener.prototype.exitTypeParameter = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#baseType. SqlBaseListener.prototype.enterBaseType = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#baseType. SqlBaseListener.prototype.exitBaseType = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#whenClause. SqlBaseListener.prototype.enterWhenClause = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#whenClause. SqlBaseListener.prototype.exitWhenClause = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#filter. SqlBaseListener.prototype.enterFilter = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#filter. SqlBaseListener.prototype.exitFilter = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#over. SqlBaseListener.prototype.enterOver = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#over. SqlBaseListener.prototype.exitOver = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#windowFrame. SqlBaseListener.prototype.enterWindowFrame = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#windowFrame. SqlBaseListener.prototype.exitWindowFrame = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#unboundedFrame. SqlBaseListener.prototype.enterUnboundedFrame = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#unboundedFrame. SqlBaseListener.prototype.exitUnboundedFrame = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#currentRowBound. SqlBaseListener.prototype.enterCurrentRowBound = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#currentRowBound. SqlBaseListener.prototype.exitCurrentRowBound = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#boundedFrame. SqlBaseListener.prototype.enterBoundedFrame = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#boundedFrame. SqlBaseListener.prototype.exitBoundedFrame = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#explainFormat. SqlBaseListener.prototype.enterExplainFormat = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#explainFormat. SqlBaseListener.prototype.exitExplainFormat = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#explainType. SqlBaseListener.prototype.enterExplainType = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#explainType. SqlBaseListener.prototype.exitExplainType = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#isolationLevel. SqlBaseListener.prototype.enterIsolationLevel = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#isolationLevel. SqlBaseListener.prototype.exitIsolationLevel = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#transactionAccessMode. SqlBaseListener.prototype.enterTransactionAccessMode = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#transactionAccessMode. SqlBaseListener.prototype.exitTransactionAccessMode = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#readUncommitted. SqlBaseListener.prototype.enterReadUncommitted = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#readUncommitted. SqlBaseListener.prototype.exitReadUncommitted = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#readCommitted. SqlBaseListener.prototype.enterReadCommitted = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#readCommitted. SqlBaseListener.prototype.exitReadCommitted = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#repeatableRead. SqlBaseListener.prototype.enterRepeatableRead = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#repeatableRead. SqlBaseListener.prototype.exitRepeatableRead = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#serializable. SqlBaseListener.prototype.enterSerializable = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#serializable. SqlBaseListener.prototype.exitSerializable = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#positionalArgument. SqlBaseListener.prototype.enterPositionalArgument = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#positionalArgument. SqlBaseListener.prototype.exitPositionalArgument = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#namedArgument. SqlBaseListener.prototype.enterNamedArgument = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#namedArgument. SqlBaseListener.prototype.exitNamedArgument = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#privilege. SqlBaseListener.prototype.enterPrivilege = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#privilege. SqlBaseListener.prototype.exitPrivilege = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#qualifiedName. SqlBaseListener.prototype.enterQualifiedName = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#qualifiedName. SqlBaseListener.prototype.exitQualifiedName = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#unquotedIdentifier. SqlBaseListener.prototype.enterUnquotedIdentifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#unquotedIdentifier. SqlBaseListener.prototype.exitUnquotedIdentifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#quotedIdentifierAlternative. SqlBaseListener.prototype.enterQuotedIdentifierAlternative = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#quotedIdentifierAlternative. SqlBaseListener.prototype.exitQuotedIdentifierAlternative = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#backQuotedIdentifier. SqlBaseListener.prototype.enterBackQuotedIdentifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#backQuotedIdentifier. SqlBaseListener.prototype.exitBackQuotedIdentifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#digitIdentifier. SqlBaseListener.prototype.enterDigitIdentifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#digitIdentifier. SqlBaseListener.prototype.exitDigitIdentifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#quotedIdentifier. SqlBaseListener.prototype.enterQuotedIdentifier = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#quotedIdentifier. SqlBaseListener.prototype.exitQuotedIdentifier = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#decimalLiteral. SqlBaseListener.prototype.enterDecimalLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#decimalLiteral. SqlBaseListener.prototype.exitDecimalLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#integerLiteral. SqlBaseListener.prototype.enterIntegerLiteral = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#integerLiteral. SqlBaseListener.prototype.exitIntegerLiteral = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#nonReserved. SqlBaseListener.prototype.enterNonReserved = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#nonReserved. SqlBaseListener.prototype.exitNonReserved = function(ctx) {}; // Enter a parse tree produced by SqlBaseParser#normalForm. SqlBaseListener.prototype.enterNormalForm = function(ctx) {}; // Exit a parse tree produced by SqlBaseParser#normalForm. SqlBaseListener.prototype.exitNormalForm = function(ctx) {};
the_stack
import { DataTypeFieldConfig, FieldType, DataTypeFields, ReadonlyDataTypeFields, GeoPoint, GeoBoundary } from '@terascope/types'; import { createHash } from 'crypto'; import { primitiveToString, toString } from './strings'; import { isIPRangeOrThrow, isIPOrThrow } from './ip'; import { toEpochMSOrThrow } from './dates'; import { toBooleanOrThrow } from './booleans'; import { isValidateNumberType, toBigIntOrThrow, toNumberOrThrow, toIntegerOrThrow, toFloatOrThrow, } from './numbers'; import { toGeoJSONOrThrow, parseGeoPoint } from './geo'; import { hasOwn } from './objects'; import { isArrayLike, castArray } from './arrays'; import { getTypeOf, isPlainObject } from './deps'; import { noop } from './functions'; import { isNotNil } from './empty'; import { isIterator } from './iterators'; type CoerceFN<T = unknown> = (input: unknown) => T /** Will return a function that will coerce the input values to the DataTypeFieldConfig provided. * The parameter childConfig is only necessary with Tuple or Object field types */ export function coerceToType<T = unknown>( fieldConfig: DataTypeFieldConfig, childConfig?: DataTypeFields ): CoerceFN<T> { if (fieldConfig.array) { const fn = getTransformerForFieldType<T>(fieldConfig, childConfig); return callIfNotNil(coerceToArrayType<T>(fn)); } return getTransformerForFieldType<T>(fieldConfig, childConfig) as CoerceFN<T>; } function coerceToArrayType<T = unknown>( fn: CoerceFN<T>, ): CoerceFN<T> { return function _coerceToArrayType(inputs: unknown): T { return castArray(inputs).map(fn) as unknown as T; }; } function _shouldCheckIntSize(type: FieldType) { if (type === FieldType.Integer) return true; if (type === FieldType.Short) return true; if (type === FieldType.Byte) return true; return false; } const NumberTypeFNDict = { [FieldType.Float]: toFloatOrThrow, [FieldType.Number]: toNumberOrThrow, [FieldType.Double]: toNumberOrThrow, [FieldType.Integer]: toIntegerOrThrow, [FieldType.Byte]: toIntegerOrThrow, [FieldType.Short]: toIntegerOrThrow, [FieldType.Long]: toBigIntOrThrow, }; export function coerceToNumberType(type: FieldType): (input: unknown) => number { const numberValidator = isValidateNumberType(type); const coerceFn = NumberTypeFNDict[type]; const smallSize = _shouldCheckIntSize(type); if (coerceFn == null) { throw new Error(`Unsupported type ${type}, please provide a valid numerical field type`); } return function _coerceToNumberType(input: unknown): number { /** * We should keep these irrational numbers since they * useful for certain operations, however they will * be converted to null when converted to JavaScript */ if (Number.isNaN(input) || input === Number.POSITIVE_INFINITY || input === Number.NEGATIVE_INFINITY) { return input as number; } const num = coerceFn(input); if (smallSize) { if (numberValidator(input)) return num; throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be a a valid ${type}`); } return num; }; } /** * Convert value to a GeoPoint data type */ export function coerceToGeoPoint(input: unknown): GeoPoint { return parseGeoPoint(input, true); } /** * Convert value to a GeoBoundary data type, a GeoBoundary * is two GeoPoints, one representing the top left, the other representing * the bottom right */ export function coerceToGeoBoundary(input: unknown): GeoBoundary { if (!Array.isArray(input)) { throw new TypeError(`Geo Boundary requires an array, got ${input} (${getTypeOf(input)})`); } if (input.length !== 2) { throw new TypeError(`Geo Boundary requires two Geo Points, got ${input.length}`); } return [coerceToGeoPoint(input[0]), coerceToGeoPoint(input[1])]; } function _mapToString(input: any): string { let hash = ''; if (isIterator(input)) { for (const value of input) { hash += `,${_getHashCodeFrom(value)}`; } } else { for (const prop in input) { if (hasOwn(input, prop)) { hash += `,${prop}:${_getHashCodeFrom(input[prop])}`; } } } return hash; } function _getHashCodeFrom(value: unknown): string { if (value == null) return ''; const typeOf = typeof value; return typeOf + ( typeOf === 'object' ? _mapToString(value) : value ); } /** * If we have a hash that is a long value we want to ensure that * the value doesn't explode the memory since we may be using * that value as a key. So when a string exceeds this specified * length we can reduce its length to 35 characters by using md5 */ export const MAX_STRING_LENGTH_BEFORE_MD5 = 1024; /** * Generate a unique hash code from a value, this is * not a guarantee but it is close enough for doing * groupBys and caching */ export function getHashCodeFrom(value: unknown): string { const hash = _getHashCodeFrom(value); if (hash.length > MAX_STRING_LENGTH_BEFORE_MD5) return `;${md5(hash)}`; return `:${hash}`; } export function md5(value: string|Buffer): string { return createHash('md5').update(value).digest('hex'); } function getChildDataTypeConfig( config: DataTypeFields|ReadonlyDataTypeFields, baseField: string, fieldType: FieldType ): DataTypeFields|undefined { // Tuples are configured like objects except the nested field names // are the positional indexes in the tuple if (fieldType !== FieldType.Object && fieldType !== FieldType.Tuple) return; const childConfig: DataTypeFields = {}; for (const [field, fieldConfig] of Object.entries(config)) { const withoutBase = field.replace(`${baseField}.`, ''); if (withoutBase !== field) { childConfig[withoutBase] = fieldConfig; } } return childConfig; } type ChildFields = readonly ( [field: string, transformer: CoerceFN] )[]; function formatObjectChildFields(childConfigs?: DataTypeFields) { if (!childConfigs) { return []; } const childFields: ChildFields = Object.entries(childConfigs) .map(([field, config]): [field: string, transformer: CoerceFN]|undefined => { const [base] = field.split('.', 1); if (base !== field && childConfigs![base]) return; const childConfig = getChildDataTypeConfig( childConfigs!, field, config.type as FieldType ); return [field, coerceToType(config, childConfig)]; }) .filter(isNotNil) as ChildFields; return childFields; } function coerceToObject(fieldConfig: DataTypeFieldConfig, childConfig?: DataTypeFields) { const childFields = formatObjectChildFields(childConfig); return function _coerceToObject(input: unknown) { if (!isPlainObject(input)) { throw new TypeError(`Expected ${toString(input)} (${getTypeOf(input)}) to be an object`); } if (!childFields.length && !fieldConfig._allow_empty) { return { ...input as Record<string, unknown> }; } const value = input as Readonly<Record<string, unknown>>; function _valueMap([field, transformer]: [field: string, transformer: CoerceFN]) { return [field, transformer(value[field])]; } return Object.fromEntries(childFields.map(_valueMap)); }; } function formatTupleChildFields(childConfigs?: DataTypeFields): readonly CoerceFN[] { if (!childConfigs) { return []; } return Object.entries(childConfigs) .map(([field, config]) => { const childConfig = getChildDataTypeConfig( childConfigs!, field, config.type as FieldType ); return coerceToType(config, childConfig); }); } function coerceToTuple(_fieldConfig: DataTypeFieldConfig, childConfig?: DataTypeFields) { const childFields = formatTupleChildFields(childConfig); return function _coerceToTuple(input: unknown) { if (!isArrayLike(input)) { throw new TypeError(`Expected ${toString(input)} (${getTypeOf(input)}) to be an array`); } const len = childFields.length; if (input.length > len) { throw new TypeError(`Expected ${toString(input)} (${getTypeOf(input)}) to have a length of ${len}`); } return childFields.map((transformer, index) => transformer(input[index])); }; } /** * This is a low level api, only coerceToType should reference this, * all other transforms should reference coerceToType as it handles arrays */ function getTransformerForFieldType<T = unknown>( argFieldType: DataTypeFieldConfig, childConfig?: DataTypeFields ): CoerceFN<T> { switch (argFieldType.type) { case FieldType.String: case FieldType.Text: case FieldType.Keyword: case FieldType.KeywordCaseInsensitive: case FieldType.KeywordTokens: case FieldType.KeywordTokensCaseInsensitive: case FieldType.KeywordPathAnalyzer: case FieldType.Domain: case FieldType.Hostname: case FieldType.NgramTokens: return callIfNotNil(primitiveToString) as CoerceFN<any>; case FieldType.IP: return callIfNotNil(isIPOrThrow) as CoerceFN<any>; case FieldType.IPRange: return callIfNotNil(isIPRangeOrThrow) as CoerceFN<any>; case FieldType.Date: return callIfNotNil(toEpochMSOrThrow) as CoerceFN<any>; case FieldType.Boolean: return callIfNotNil(toBooleanOrThrow) as CoerceFN<any>; case FieldType.Float: case FieldType.Number: case FieldType.Double: case FieldType.Byte: case FieldType.Short: case FieldType.Integer: case FieldType.Long: return callIfNotNil( coerceToNumberType(argFieldType.type as FieldType) ) as CoerceFN<any>; case FieldType.Geo: case FieldType.GeoPoint: return callIfNotNil(coerceToGeoPoint) as CoerceFN<any>; case FieldType.Boundary: return callIfNotNil(coerceToGeoBoundary) as CoerceFN<any>; case FieldType.GeoJSON: return callIfNotNil(toGeoJSONOrThrow) as CoerceFN<any>; case FieldType.Object: return callIfNotNil(coerceToObject(argFieldType, childConfig)) as CoerceFN<any>; case FieldType.Tuple: return callIfNotNil(coerceToTuple(argFieldType, childConfig)) as CoerceFN<any>; case FieldType.Any: return callIfNotNil(noop); default: throw new Error(`Invalid FieldType ${argFieldType.type}, was pulled from the type field of input ${JSON.stringify(argFieldType, null, 2)}`); } } function callIfNotNil<T extends(value: any) => any>(fn: T): T { return function _callIfNotNil(value) { return value != null ? fn(value) : undefined; } as T; }
the_stack
import { parseColorHexRGB } from "@microsoft/fast-colors"; import { blackOrWhiteByContrast } from "../color/index.js"; import { ColorRecipe, InteractiveColorRecipe, InteractiveSwatchSet, } from "../color/recipe.js"; import { blackOrWhiteByContrastSet } from "../color/recipes/black-or-white-by-contrast-set.js"; import { contrastAndDeltaSwatchSet } from "../color/recipes/contrast-and-delta-swatch-set.js"; import { contrastSwatch } from "../color/recipes/contrast-swatch.js"; import { deltaSwatchSet } from "../color/recipes/delta-swatch-set.js"; import { deltaSwatch } from "../color/recipes/delta-swatch.js"; import { Swatch, SwatchRGB } from "../color/swatch.js"; import { create, createNonCss } from "./create.js"; import { accentPalette, neutralPalette } from "./palette.js"; enum ContrastTarget { NormalText = 4.5, LargeText = 3, } /** @public */ export const fillColor = create<Swatch>("fill-color").withDefault( SwatchRGB.from(parseColorHexRGB("#FFFFFF")!) ); // Accent Fill /** @public */ export const accentFillMinContrast = createNonCss<number>( "accent-fill-min-contrast" ).withDefault(5.5); /** @public */ export const accentFillRestDelta = createNonCss<number>( "accent-fill-rest-delta" ).withDefault(0); /** @public */ export const accentFillHoverDelta = createNonCss<number>( "accent-fill-hover-delta" ).withDefault(-2); /** @public */ export const accentFillActiveDelta = createNonCss<number>( "accent-fill-active-delta" ).withDefault(-5); /** @public */ export const accentFillFocusDelta = createNonCss<number>( "accent-fill-focus-delta" ).withDefault(0); /** @public */ export const accentFillRecipe = createNonCss<InteractiveColorRecipe>( "accent-fill-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => contrastAndDeltaSwatchSet( accentPalette.getValueFor(element), reference || fillColor.getValueFor(element), accentFillMinContrast.getValueFor(element), accentFillRestDelta.getValueFor(element), accentFillHoverDelta.getValueFor(element), accentFillActiveDelta.getValueFor(element), accentFillFocusDelta.getValueFor(element) ), }); /** @public */ export const accentFillRest = create<Swatch>("accent-fill-rest").withDefault( (element: HTMLElement) => { return accentFillRecipe.getValueFor(element).evaluate(element).rest; } ); /** @public */ export const accentFillHover = create<Swatch>("accent-fill-hover").withDefault( (element: HTMLElement) => { return accentFillRecipe.getValueFor(element).evaluate(element).hover; } ); /** @public */ export const accentFillActive = create<Swatch>("accent-fill-active").withDefault( (element: HTMLElement) => { return accentFillRecipe.getValueFor(element).evaluate(element).active; } ); /** @public */ export const accentFillFocus = create<Swatch>("accent-fill-focus").withDefault( (element: HTMLElement) => { return accentFillRecipe.getValueFor(element).evaluate(element).focus; } ); // Foreground On Accent /** @public */ export const foregroundOnAccentRecipe = createNonCss<InteractiveColorRecipe>( "foreground-on-accent-recipe" ).withDefault({ evaluate: (element: HTMLElement): InteractiveSwatchSet => blackOrWhiteByContrastSet( accentFillRest.getValueFor(element), accentFillHover.getValueFor(element), accentFillActive.getValueFor(element), accentFillFocus.getValueFor(element), ContrastTarget.NormalText, false ), }); /** @public */ export const foregroundOnAccentRest = create<Swatch>( "foreground-on-accent-rest" ).withDefault( (element: HTMLElement) => foregroundOnAccentRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const foregroundOnAccentHover = create<Swatch>( "foreground-on-accent-hover" ).withDefault( (element: HTMLElement) => foregroundOnAccentRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const foregroundOnAccentActive = create<Swatch>( "foreground-on-accent-active" ).withDefault( (element: HTMLElement) => foregroundOnAccentRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const foregroundOnAccentFocus = create<Swatch>( "foreground-on-accent-focus" ).withDefault( (element: HTMLElement) => foregroundOnAccentRecipe.getValueFor(element).evaluate(element).focus ); // Accent Foreground /** @public */ export const accentForegroundMinContrast = createNonCss<number>( "accent-foreground-min-contrast" ).withDefault(0); /** @public */ export const accentForegroundRestDelta = createNonCss<number>( "accent-foreground-rest-delta" ).withDefault(0); /** @public */ export const accentForegroundHoverDelta = createNonCss<number>( "accent-foreground-hover-delta" ).withDefault(3); /** @public */ export const accentForegroundActiveDelta = createNonCss<number>( "accent-foreground-active-delta" ).withDefault(-8); /** @public */ export const accentForegroundFocusDelta = createNonCss<number>( "accent-foreground-focus-delta" ).withDefault(0); /** @public */ export const accentForegroundRecipe = createNonCss<InteractiveColorRecipe>( "accent-foreground-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => contrastAndDeltaSwatchSet( accentPalette.getValueFor(element), reference || fillColor.getValueFor(element), accentForegroundMinContrast.getValueFor(element), accentForegroundRestDelta.getValueFor(element), accentForegroundHoverDelta.getValueFor(element), accentForegroundActiveDelta.getValueFor(element), accentForegroundFocusDelta.getValueFor(element) ), }); /** @public */ export const accentForegroundRest = create<Swatch>("accent-foreground-rest").withDefault( (element: HTMLElement) => accentForegroundRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const accentForegroundHover = create<Swatch>( "accent-foreground-hover" ).withDefault( (element: HTMLElement) => accentForegroundRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const accentForegroundActive = create<Swatch>( "accent-foreground-active" ).withDefault( (element: HTMLElement) => accentForegroundRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const accentForegroundFocus = create<Swatch>( "accent-foreground-focus" ).withDefault( (element: HTMLElement) => accentForegroundRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Foreground /** @public */ export const neutralForegroundMinContrast = createNonCss<number>( "neutral-foreground-min-contrast" ).withDefault(16); /** @public */ export const neutralForegroundRestDelta = createNonCss<number>( "neutral-foreground-rest-delta" ).withDefault(0); /** @public */ export const neutralForegroundHoverDelta = createNonCss<number>( "neutral-foreground-hover-delta" ).withDefault(-19); /** @public */ export const neutralForegroundActiveDelta = createNonCss<number>( "neutral-foreground-active-delta" ).withDefault(-30); /** @public */ export const neutralForegroundFocusDelta = createNonCss<number>( "neutral-foreground-focus-delta" ).withDefault(0); /** @public */ export const neutralForegroundRecipe = createNonCss<InteractiveColorRecipe>( "neutral-foreground-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => contrastAndDeltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralForegroundMinContrast.getValueFor(element), neutralForegroundRestDelta.getValueFor(element), neutralForegroundHoverDelta.getValueFor(element), neutralForegroundActiveDelta.getValueFor(element), neutralForegroundFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralForegroundRest = create<Swatch>( "neutral-foreground-rest" ).withDefault( (element: HTMLElement) => neutralForegroundRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralForegroundHover = create<Swatch>( "neutral-foreground-hover" ).withDefault( (element: HTMLElement) => neutralForegroundRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralForegroundActive = create<Swatch>( "neutral-foreground-active" ).withDefault( (element: HTMLElement) => neutralForegroundRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralForegroundFocus = create<Swatch>( "neutral-foreground-focus" ).withDefault( (element: HTMLElement) => neutralForegroundRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Foreground Hint /** @public */ export const neutralForegroundHintRecipe = createNonCss<ColorRecipe>( "neutral-foreground-hint-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): Swatch => contrastSwatch( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), ContrastTarget.NormalText ), }); /** @public */ export const neutralForegroundHint = create<Swatch>( "neutral-foreground-hint" ).withDefault((element: HTMLElement) => neutralForegroundHintRecipe.getValueFor(element).evaluate(element) ); // Neutral Fill /** @public */ export const neutralFillRestDelta = createNonCss<number>( "neutral-fill-rest-delta" ).withDefault(-1); /** @public */ export const neutralFillHoverDelta = createNonCss<number>( "neutral-fill-hover-delta" ).withDefault(1); /** @public */ export const neutralFillActiveDelta = createNonCss<number>( "neutral-fill-active-delta" ).withDefault(0); /** @public */ export const neutralFillFocusDelta = createNonCss<number>( "neutral-fill-focus-delta" ).withDefault(0); /** @public */ export const neutralFillRecipe = createNonCss<InteractiveColorRecipe>( "neutral-fill-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element), neutralFillFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralFillRest = create<Swatch>("neutral-fill-rest").withDefault( (element: HTMLElement) => neutralFillRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralFillHover = create<Swatch>("neutral-fill-hover").withDefault( (element: HTMLElement) => neutralFillRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralFillActive = create<Swatch>("neutral-fill-active").withDefault( (element: HTMLElement) => neutralFillRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralFillFocus = create<Swatch>("neutral-fill-focus").withDefault( (element: HTMLElement) => neutralFillRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Fill Input /** @public */ export const neutralFillInputRestDelta = createNonCss<number>( "neutral-fill-input-rest-delta" ).withDefault(-1); /** @public */ export const neutralFillInputHoverDelta = createNonCss<number>( "neutral-fill-input-hover-delta" ).withDefault(1); /** @public */ export const neutralFillInputActiveDelta = createNonCss<number>( "neutral-fill-input-active-delta" ).withDefault(0); /** @public */ export const neutralFillInputFocusDelta = createNonCss<number>( "neutral-fill-input-focus-delta" ).withDefault(-2); /** @public */ export const neutralFillInputRecipe = createNonCss<InteractiveColorRecipe>( "neutral-fill-input-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillInputRestDelta.getValueFor(element), neutralFillInputHoverDelta.getValueFor(element), neutralFillInputActiveDelta.getValueFor(element), neutralFillInputFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralFillInputRest = create<Swatch>("neutral-fill-input-rest").withDefault( (element: HTMLElement) => neutralFillInputRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralFillInputHover = create<Swatch>( "neutral-fill-input-hover" ).withDefault( (element: HTMLElement) => neutralFillInputRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralFillInputActive = create<Swatch>( "neutral-fill-input-active" ).withDefault( (element: HTMLElement) => neutralFillInputRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralFillInputFocus = create<Swatch>( "neutral-fill-input-focus" ).withDefault( (element: HTMLElement) => neutralFillInputRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Fill Secondary /** @public */ export const neutralFillSecondaryRestDelta = createNonCss<number>( "neutral-fill-secondary-rest-delta" ).withDefault(3); /** @public */ export const neutralFillSecondaryHoverDelta = createNonCss<number>( "neutral-fill-secondary-hover-delta" ).withDefault(2); /** @public */ export const neutralFillSecondaryActiveDelta = createNonCss<number>( "neutral-fill-secondary-active-delta" ).withDefault(1); /** @public */ export const neutralFillSecondaryFocusDelta = createNonCss<number>( "neutral-fill-secondary-focus-delta" ).withDefault(3); /** @public */ export const neutralFillSecondaryRecipe = createNonCss<InteractiveColorRecipe>( "neutral-fill-secondary-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillSecondaryRestDelta.getValueFor(element), neutralFillSecondaryHoverDelta.getValueFor(element), neutralFillSecondaryActiveDelta.getValueFor(element), neutralFillSecondaryFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralFillSecondaryRest = create<Swatch>( "neutral-fill-secondary-rest" ).withDefault( (element: HTMLElement) => neutralFillSecondaryRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralFillSecondaryHover = create<Swatch>( "neutral-fill-secondary-hover" ).withDefault( (element: HTMLElement) => neutralFillSecondaryRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralFillSecondaryActive = create<Swatch>( "neutral-fill-secondary-active" ).withDefault( (element: HTMLElement) => neutralFillSecondaryRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralFillSecondaryFocus = create<Swatch>( "neutral-fill-secondary-focus" ).withDefault( (element: HTMLElement) => neutralFillSecondaryRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Fill Stealth /** @public */ export const neutralFillStealthRestDelta = createNonCss<number>( "neutral-fill-stealth-rest-delta" ).withDefault(0); /** @public */ export const neutralFillStealthHoverDelta = createNonCss<number>( "neutral-fill-stealth-hover-delta" ).withDefault(3); /** @public */ export const neutralFillStealthActiveDelta = createNonCss<number>( "neutral-fill-stealth-active-delta" ).withDefault(2); /** @public */ export const neutralFillStealthFocusDelta = createNonCss<number>( "neutral-fill-stealth-focus-delta" ).withDefault(0); /** @public */ export const neutralFillStealthRecipe = createNonCss<InteractiveColorRecipe>( "neutral-fill-stealth-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillStealthRestDelta.getValueFor(element), neutralFillStealthHoverDelta.getValueFor(element), neutralFillStealthActiveDelta.getValueFor(element), neutralFillStealthFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralFillStealthRest = create<Swatch>( "neutral-fill-stealth-rest" ).withDefault( (element: HTMLElement) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralFillStealthHover = create<Swatch>( "neutral-fill-stealth-hover" ).withDefault( (element: HTMLElement) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralFillStealthActive = create<Swatch>( "neutral-fill-stealth-active" ).withDefault( (element: HTMLElement) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralFillStealthFocus = create<Swatch>( "neutral-fill-stealth-focus" ).withDefault( (element: HTMLElement) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Fill Strong /** @public */ export const neutralFillStrongMinContrast = createNonCss<number>( "neutral-fill-strong-min-contrast" ).withDefault(0); /** @public */ export const neutralFillStrongRestDelta = createNonCss<number>( "neutral-fill-strong-rest-delta" ).withDefault(0); /** @public */ export const neutralFillStrongHoverDelta = createNonCss<number>( "neutral-fill-strong-hover-delta" ).withDefault(8); /** @public */ export const neutralFillStrongActiveDelta = createNonCss<number>( "neutral-fill-strong-active-delta" ).withDefault(-5); /** @public */ export const neutralFillStrongFocusDelta = createNonCss<number>( "neutral-fill-strong-focus-delta" ).withDefault(0); /** @public */ export const neutralFillStrongRecipe = createNonCss<InteractiveColorRecipe>( "neutral-fill-strong-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => contrastAndDeltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillStrongMinContrast.getValueFor(element), neutralFillStrongRestDelta.getValueFor(element), neutralFillStrongHoverDelta.getValueFor(element), neutralFillStrongActiveDelta.getValueFor(element), neutralFillStrongFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralFillStrongRest = create<Swatch>( "neutral-fill-strong-rest" ).withDefault( (element: HTMLElement) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralFillStrongHover = create<Swatch>( "neutral-fill-strong-hover" ).withDefault( (element: HTMLElement) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralFillStrongActive = create<Swatch>( "neutral-fill-strong-active" ).withDefault( (element: HTMLElement) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralFillStrongFocus = create<Swatch>( "neutral-fill-strong-focus" ).withDefault( (element: HTMLElement) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Stroke /** @public */ export const neutralStrokeRestDelta = createNonCss<number>( "neutral-stroke-rest-delta" ).withDefault(8); /** @public */ export const neutralStrokeHoverDelta = createNonCss<number>( "neutral-stroke-hover-delta" ).withDefault(12); /** @public */ export const neutralStrokeActiveDelta = createNonCss<number>( "neutral-stroke-active-delta" ).withDefault(6); /** @public */ export const neutralStrokeFocusDelta = createNonCss<number>( "neutral-stroke-focus-delta" ).withDefault(8); /** @public */ export const neutralStrokeRecipe = createNonCss<InteractiveColorRecipe>( "neutral-stroke-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => { return deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralStrokeRestDelta.getValueFor(element), neutralStrokeHoverDelta.getValueFor(element), neutralStrokeActiveDelta.getValueFor(element), neutralStrokeFocusDelta.getValueFor(element) ); }, }); /** @public */ export const neutralStrokeRest = create<Swatch>("neutral-stroke-rest").withDefault( (element: HTMLElement) => neutralStrokeRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralStrokeHover = create<Swatch>("neutral-stroke-hover").withDefault( (element: HTMLElement) => neutralStrokeRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralStrokeActive = create<Swatch>("neutral-stroke-active").withDefault( (element: HTMLElement) => neutralStrokeRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralStrokeFocus = create<Swatch>("neutral-stroke-focus").withDefault( (element: HTMLElement) => neutralStrokeRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Stroke Divider /** @public */ export const neutralStrokeDividerRestDelta = createNonCss<number>( "neutral-stroke-divider-rest-delta" ).withDefault(4); /** @public */ export const neutralStrokeDividerRecipe = createNonCss<ColorRecipe>( "neutral-stroke-divider-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): Swatch => deltaSwatch( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralStrokeDividerRestDelta.getValueFor(element) ), }); /** @public */ export const neutralStrokeDividerRest = create<Swatch>( "neutral-stroke-divider-rest" ).withDefault(element => neutralStrokeDividerRecipe.getValueFor(element).evaluate(element) ); // Neutral Stroke Input /** @public */ export const neutralStrokeInputRestDelta = createNonCss<number>( "neutral-stroke-input-rest-delta" ).withDefault(3); /** @public */ export const neutralStrokeInputHoverDelta = createNonCss<number>( "neutral-stroke-input-hover-delta" ).withDefault(5); /** @public */ export const neutralStrokeInputActiveDelta = createNonCss<number>( "neutral-stroke-input-active-delta" ).withDefault(5); /** @public */ export const neutralStrokeInputFocusDelta = createNonCss<number>( "neutral-stroke-input-focus-delta" ).withDefault(5); /** @public */ export const neutralStrokeInputRecipe = createNonCss<InteractiveColorRecipe>( "neutral-stroke-input-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => { return deltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralStrokeInputRestDelta.getValueFor(element), neutralStrokeInputHoverDelta.getValueFor(element), neutralStrokeInputActiveDelta.getValueFor(element), neutralStrokeInputFocusDelta.getValueFor(element) ); }, }); /** @public */ export const neutralStrokeInputRest = create<Swatch>( "neutral-stroke-input-rest" ).withDefault( (element: HTMLElement) => neutralStrokeInputRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralStrokeInputHover = create<Swatch>( "neutral-stroke-input-hover" ).withDefault( (element: HTMLElement) => neutralStrokeInputRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralStrokeInputActive = create<Swatch>( "neutral-stroke-input-active" ).withDefault( (element: HTMLElement) => neutralStrokeInputRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralStrokeInputFocus = create<Swatch>( "neutral-stroke-input-focus" ).withDefault( (element: HTMLElement) => neutralStrokeInputRecipe.getValueFor(element).evaluate(element).focus ); // Neutral Stroke Strong /** @public */ export const neutralStrokeStrongMinContrast = createNonCss<number>( "neutral-stroke-strong-min-contrast" ).withDefault(5.5); /** @public */ export const neutralStrokeStrongRestDelta = createNonCss<number>( "neutral-stroke-strong-rest-delta" ).withDefault(0); /** @public */ export const neutralStrokeStrongHoverDelta = createNonCss<number>( "neutral-stroke-strong-hover-delta" ).withDefault(0); /** @public */ export const neutralStrokeStrongActiveDelta = createNonCss<number>( "neutral-stroke-strong-active-delta" ).withDefault(0); /** @public */ export const neutralStrokeStrongFocusDelta = createNonCss<number>( "neutral-stroke-strong-focus-delta" ).withDefault(0); /** @public */ export const neutralStrokeStrongRecipe = createNonCss<InteractiveColorRecipe>( "neutral-stroke-strong-recipe" ).withDefault({ evaluate: (element: HTMLElement, reference?: Swatch): InteractiveSwatchSet => contrastAndDeltaSwatchSet( neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralStrokeStrongMinContrast.getValueFor(element), neutralStrokeStrongRestDelta.getValueFor(element), neutralStrokeStrongHoverDelta.getValueFor(element), neutralStrokeStrongActiveDelta.getValueFor(element), neutralStrokeStrongFocusDelta.getValueFor(element) ), }); /** @public */ export const neutralStrokeStrongRest = create<Swatch>( "neutral-stroke-strong-rest" ).withDefault( (element: HTMLElement) => neutralStrokeStrongRecipe.getValueFor(element).evaluate(element).rest ); /** @public */ export const neutralStrokeStrongHover = create<Swatch>( "neutral-stroke-strong-hover" ).withDefault( (element: HTMLElement) => neutralStrokeStrongRecipe.getValueFor(element).evaluate(element).hover ); /** @public */ export const neutralStrokeStrongActive = create<Swatch>( "neutral-stroke-strong-active" ).withDefault( (element: HTMLElement) => neutralStrokeStrongRecipe.getValueFor(element).evaluate(element).active ); /** @public */ export const neutralStrokeStrongFocus = create<Swatch>( "neutral-stroke-strong-focus" ).withDefault( (element: HTMLElement) => neutralStrokeStrongRecipe.getValueFor(element).evaluate(element).focus ); // Focus Stroke Outer /** @public */ export const focusStrokeOuterRecipe = createNonCss<ColorRecipe>( "focus-stroke-outer-recipe" ).withDefault({ evaluate: (element: HTMLElement): Swatch => blackOrWhiteByContrast( fillColor.getValueFor(element), ContrastTarget.NormalText, true ), }); /** @public */ export const focusStrokeOuter = create<Swatch>( "focus-stroke-outer" ).withDefault((element: HTMLElement) => focusStrokeOuterRecipe.getValueFor(element).evaluate(element) ); // Focus Stroke Inner /** @public */ export const focusStrokeInnerRecipe = createNonCss<ColorRecipe>( "focus-stroke-inner-recipe" ).withDefault({ evaluate: (element: HTMLElement): Swatch => blackOrWhiteByContrast( focusStrokeOuter.getValueFor(element), ContrastTarget.NormalText, false ), }); /** @public */ export const focusStrokeInner = create<Swatch>( "focus-stroke-inner" ).withDefault((element: HTMLElement) => focusStrokeInnerRecipe.getValueFor(element).evaluate(element) );
the_stack
import { IVec2Like, Vec2 } from '../../../core'; // http://answers.unity3d.com/questions/977416/2d-polygon-convex-decomposition-code.html /// <summary> /// This class is took from the "FarseerUnity" physics engine, which uses Mark Bayazit's decomposition algorithm. /// I also have to make it work with self-intersecting polygons, so I'll use another different algorithm to decompose a self-intersecting polygon into several simple polygons, /// and then I would decompose each of them into convex polygons. /// </summary> // From phed rev 36 /// <summary> /// Convex decomposition algorithm created by Mark Bayazit (http://mnbayazit.com/) /// For more information about this algorithm, see http://mnbayazit.com/406/bayazit /// </summary> function At (i: number, vertices: IVec2Like[]) { const s = vertices.length; return vertices[i < 0 ? s - (-i % s) : i % s]; } function Copy (i: number, j: number, vertices: IVec2Like[]) { const p: IVec2Like[] = []; while (j < i) j += vertices.length; // p.reserve(j - i + 1); for (; i <= j; ++i) { p.push(At(i, vertices)); } return p; } /// <summary> /// Decompose the polygon into several smaller non-concave polygon. /// If the polygon is already convex, it will return the original polygon, unless it is over Settings.MaxPolygonVertices. /// Precondition: Counter Clockwise polygon /// </summary> /// <param name="vertices"></param> /// <returns></returns> export function ConvexPartition (vertices: IVec2Like[]) { // We force it to CCW as it is a precondition in this algorithm. ForceCounterClockWise(vertices); let list: IVec2Like[][] = []; let d; let lowerDist; let upperDist; let p; let lowerInt = new Vec2(); let upperInt = new Vec2(); // intersection points let lowerIndex = 0; let upperIndex = 0; let lowerPoly; let upperPoly; for (let i = 0; i < vertices.length; ++i) { if (Reflex(i, vertices)) { lowerDist = upperDist = 10e7; // std::numeric_limits<qreal>::max(); for (let j = 0; j < vertices.length; ++j) { // if line intersects with an edge if (Left(At(i - 1, vertices), At(i, vertices), At(j, vertices)) && RightOn(At(i - 1, vertices), At(i, vertices), At(j - 1, vertices))) { // find the povar of intersection p = LineIntersect(At(i - 1, vertices), At(i, vertices), At(j, vertices), At(j - 1, vertices)); if (Right(At(i + 1, vertices), At(i, vertices), p)) { // make sure it's inside the poly d = SquareDist(At(i, vertices), p); if (d < lowerDist) { // keep only the closest intersection lowerDist = d; lowerInt = p; lowerIndex = j; } } } if (Left(At(i + 1, vertices), At(i, vertices), At(j + 1, vertices)) && RightOn(At(i + 1, vertices), At(i, vertices), At(j, vertices))) { p = LineIntersect(At(i + 1, vertices), At(i, vertices), At(j, vertices), At(j + 1, vertices)); if (Left(At(i - 1, vertices), At(i, vertices), p)) { d = SquareDist(At(i, vertices), p); if (d < upperDist) { upperDist = d; upperIndex = j; upperInt = p; } } } } // if there are no vertices to connect to, choose a povar in the middle if (lowerIndex == (upperIndex + 1) % vertices.length) { const sp = lowerInt.add(upperInt).multiplyScalar(1 / 2); lowerPoly = Copy(i, upperIndex, vertices); lowerPoly.push(sp); upperPoly = Copy(lowerIndex, i, vertices); upperPoly.push(sp); } else { let highestScore = 0; let bestIndex = lowerIndex; while (upperIndex < lowerIndex) { upperIndex += vertices.length; } for (let j = lowerIndex; j <= upperIndex; ++j) { if (CanSee(i, j, vertices)) { let score = 1 / (SquareDist(At(i, vertices), At(j, vertices)) + 1); if (Reflex(j, vertices)) { if (RightOn(At(j - 1, vertices), At(j, vertices), At(i, vertices)) && LeftOn(At(j + 1, vertices), At(j, vertices), At(i, vertices))) { score += 3; } else { score += 2; } } else { score += 1; } if (score > highestScore) { bestIndex = j; highestScore = score; } } } lowerPoly = Copy(i, bestIndex, vertices); upperPoly = Copy(bestIndex, i, vertices); } list = list.concat(ConvexPartition(lowerPoly)); list = list.concat(ConvexPartition(upperPoly)); return list; } } // polygon is already convex list.push(vertices); // Remove empty vertice collections for (let i = list.length - 1; i >= 0; i--) { if (list[i].length == 0) list.splice(i, 0); } return list; } function CanSee (i, j, vertices) { if (Reflex(i, vertices)) { if (LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices)) && RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices))) return false; } else if (RightOn(At(i, vertices), At(i + 1, vertices), At(j, vertices)) || LeftOn(At(i, vertices), At(i - 1, vertices), At(j, vertices))) return false; if (Reflex(j, vertices)) { if (LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices)) && RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices))) return false; } else if (RightOn(At(j, vertices), At(j + 1, vertices), At(i, vertices)) || LeftOn(At(j, vertices), At(j - 1, vertices), At(i, vertices))) return false; for (let k = 0; k < vertices.length; ++k) { if ((k + 1) % vertices.length == i || k == i || (k + 1) % vertices.length == j || k == j) { continue; // ignore incident edges } const intersectionPoint = new Vec2(); if (LineIntersect2(At(i, vertices), At(j, vertices), At(k, vertices), At(k + 1, vertices), intersectionPoint)) { return false; } } return true; } // precondition: ccw function Reflex (i: number, vertices: IVec2Like[]) { return Right(i, vertices); } function Right (a: number | IVec2Like, b: IVec2Like | IVec2Like[], c?: IVec2Like) { if (typeof c === 'undefined') { const i = a as number; const vertices = b as IVec2Like[]; a = At(i - 1, vertices); b = At(i, vertices); c = At(i + 1, vertices); } return Area(a as IVec2Like, b as IVec2Like, c) < 0; } function Left (a: IVec2Like, b: IVec2Like, c: IVec2Like) { return Area(a, b, c) > 0; } function LeftOn (a: IVec2Like, b: IVec2Like, c: IVec2Like) { return Area(a, b, c) >= 0; } function RightOn (a: IVec2Like, b: IVec2Like, c: IVec2Like) { return Area(a, b, c) <= 0; } function SquareDist (a: IVec2Like, b: IVec2Like) { const dx = b.x - a.x; const dy = b.y - a.y; return dx * dx + dy * dy; } // forces counter clock wise order. export function ForceCounterClockWise (vertices) { if (!IsCounterClockWise(vertices)) { vertices.reverse(); } } export function IsCounterClockWise (vertices) { // We just return true for lines if (vertices.length < 3) return true; return (GetSignedArea(vertices) > 0); } // gets the signed area. function GetSignedArea (vertices) { let i; let area = 0; for (i = 0; i < vertices.length; i++) { const j = (i + 1) % vertices.length; area += vertices[i].x * vertices[j].y; area -= vertices[i].y * vertices[j].x; } area /= 2; return area; } // From Mark Bayazit's convex decomposition algorithm function LineIntersect (p1, p2, q1, q2) { const i = new Vec2(); const a1 = p2.y - p1.y; const b1 = p1.x - p2.x; const c1 = a1 * p1.x + b1 * p1.y; const a2 = q2.y - q1.y; const b2 = q1.x - q2.x; const c2 = a2 * q1.x + b2 * q1.y; const det = a1 * b2 - a2 * b1; if (!FloatEquals(det, 0)) { // lines are not parallel i.x = (b2 * c1 - b1 * c2) / det; i.y = (a1 * c2 - a2 * c1) / det; } return i; } // from Eric Jordan's convex decomposition library, it checks if the lines a0->a1 and b0->b1 cross. // if they do, intersectionPovar will be filled with the povar of crossing. Grazing lines should not return true. function LineIntersect2 (a0, a1, b0, b1, intersectionPoint) { if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1) return false; const x1 = a0.x; const y1 = a0.y; const x2 = a1.x; const y2 = a1.y; const x3 = b0.x; const y3 = b0.y; const x4 = b1.x; const y4 = b1.y; // AABB early exit if (Math.max(x1, x2) < Math.min(x3, x4) || Math.max(x3, x4) < Math.min(x1, x2)) return false; if (Math.max(y1, y2) < Math.min(y3, y4) || Math.max(y3, y4) < Math.min(y1, y2)) return false; let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)); let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)); const denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); if (Math.abs(denom) < 10e-7) { // Lines are too close to parallel to call return false; } ua /= denom; ub /= denom; if ((ua > 0) && (ua < 1) && (ub > 0) && (ub < 1)) { intersectionPoint.x = (x1 + ua * (x2 - x1)); intersectionPoint.y = (y1 + ua * (y2 - y1)); return true; } return false; } function FloatEquals (value1, value2) { return Math.abs(value1 - value2) <= 10e-7; } // returns a positive number if c is to the left of the line going from a to b. Positive number if povar is left, negative if povar is right, and 0 if points are collinear.</returns> function Area (a: IVec2Like, b: IVec2Like, c: IVec2Like) { return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y); }
the_stack
import * as Random from '../random'; import * as RoseTree from '../rosetree'; import * as Fuzz from '../fuzz'; import * as Iter from '../iterable'; import * as Shrink from '../shrink'; import { Awaitable } from '../types'; import { sample } from './helpers'; const sampleFuzzer = <A>(fuzz: Fuzz.Fuzzer<A>, count?: number, seed?: Random.Seed) => sample(fuzz.generator, count, seed); const staticSeed = Random.initialSeed(1514568898760); const serialize = async <A>(depth: number, trees: AsyncIterable<RoseTree.Rose<A>>): Promise<any> => { if (depth <= 0) { return []; } const result = []; for await (let tree of trees) { let root = await RoseTree.root(tree); let children = await serialize(depth - 1, RoseTree.children(tree)); const next = { root, children }; result.push(next); } return result; }; const serializedSample = <A>(fuzzer: Fuzz.Fuzzer<A>, count = 10) => { const result = sampleFuzzer(fuzzer, count, staticSeed); return serialize(2, result); }; const testValues = async <A>(fuzzer: Fuzz.Fuzzer<A>, callback: (a: A) => void) => { for await (let tree of sampleFuzzer(fuzzer)) { callback(await RoseTree.root(tree)); for await (let kid of RoseTree.children(tree)) { callback(await RoseTree.root(kid)); } } }; const some = async <A>(children: A[], fn: (a: A) => Awaitable<boolean>) => { for await (let c of children) { if ((await fn(c)) === true) { return true; } } return false; }; test('custom with constant generator', async () => { const value = 1000; const fuzz = Fuzz.custom(Random.constant(value), Shrink.atLeastInteger(0)); const result = await serializedSample(fuzz); for await (let tree of result) { const children = await Iter.toArray(RoseTree.children(tree)); // all children should be less than the constant value children.forEach(child => { const root = RoseTree.root(child as any); expect(root).toBeLessThan(value); }); } }); test('boolean', async () => { expect(await serializedSample(Fuzz.boolean())).toMatchSnapshot(); }); test('boolean 2', async () => { // validate that when a boolean fuzzer is zipped with something else, there // will still be children with `true` const result = sampleFuzzer( Fuzz.zip(Fuzz.boolean(), Fuzz.string({ maxSize: 4 })), 1, Random.initialSeed(1514568898760 + 2), ); for await (let tree of result) { // the pre-condition if ((await RoseTree.root(tree))[0] !== true) { continue; } const children = await Iter.toArray(RoseTree.children(tree)); expect(await some(children, async kid => (await RoseTree.root(kid))[0] === true)).toEqual(true); } }); test('boolean structure', async () => { const result = sampleFuzzer(Fuzz.boolean(), 10); for await (let tree of result) { const children = await Iter.toArray<RoseTree.Rose<boolean>>(RoseTree.children(tree)); if ((await RoseTree.root(tree)) === true) { for await (let c of children) { expect(await RoseTree.root(c)).toEqual(false); } } else { expect(children).toHaveLength(0); } } }); test('integer', async () => { const result = await serializedSample(Fuzz.integer({ minSize: 10, maxSize: 20 })); expect(result).toMatchSnapshot(); }); test('integer structure', async () => { const result = sampleFuzzer(Fuzz.integer({ minSize: -1e5, maxSize: 1e5 }), 10); for await (let tree of result) { const root: number = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<number>>(RoseTree.children(tree)); for await (let c of RoseTree.children(tree)) { if (root < 0) { expect(await RoseTree.root(c)).toBeGreaterThan(root); } else { expect(await RoseTree.root(c)).toBeLessThan(root); } } } }); test('integer structure 2', async () => { const result = sampleFuzzer(Fuzz.integer({ minSize: 0, maxSize: 1e5 }), 10); for await (let tree of result) { const root: number = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<number>>(RoseTree.children(tree)); for await (let c of children) { const value = await RoseTree.root(c); expect(value).toBeGreaterThanOrEqual(0); expect(value).toBeLessThanOrEqual(1e5); expect(value).toBeLessThanOrEqual(root); } } }); test('float', async () => { expect(await serializedSample(Fuzz.float({ minSize: -10.1, maxSize: 10.1 }))).toMatchSnapshot(); }); test('float structure', async () => { const result = sampleFuzzer(Fuzz.float({ minSize: -1e5, maxSize: 1e5 }), 10); for await (let tree of result) { const root: number = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<number>>(RoseTree.children(tree)); for await (let c of children) { const value = await RoseTree.root(c); if (root === 0) { expect(value).toEqual(0); } else if (root < 0) { expect(value).toBeGreaterThanOrEqual(root); } else { expect(value).toBeLessThanOrEqual(root); } } } }); test('number', async () => { const result = sampleFuzzer(Fuzz.number({ minSize: -1e5, maxSize: 1e5 }), 10); for await (let tree of result) { const root: number = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<number>>(RoseTree.children(tree)); for await (let c of children) { const value = await RoseTree.root(c); if (root === 0) { expect(value).toEqual(0); } else if (root < 0) { expect(value).toBeGreaterThanOrEqual(root); } else { expect(value).toBeLessThanOrEqual(root); } } } }); test('posInteger', async () => { const fuzzer = Fuzz.posInteger(); await testValues(fuzzer, num => expect(num).toBeGreaterThanOrEqual(0)); }); test('negInteger', async () => { const fuzzer = Fuzz.negInteger(); await testValues(fuzzer, num => expect(num).toBeLessThanOrEqual(0)); }); test('posFloat', async () => { const fuzzer = Fuzz.posFloat(); await testValues(fuzzer, num => expect(num).toBeGreaterThanOrEqual(0)); }); test('negFloat', async () => { const fuzzer = Fuzz.negFloat(); await testValues(fuzzer, num => expect(num).toBeLessThanOrEqual(0)); }); test('posNumber', async () => { const fuzzer = Fuzz.posNumber(); await testValues(fuzzer, num => expect(num).toBeGreaterThanOrEqual(0)); }); test('negNumber', async () => { const fuzzer = Fuzz.negNumber(); await testValues(fuzzer, num => expect(num).toBeLessThanOrEqual(0)); }); test('string', async () => { expect(await serializedSample(Fuzz.string({ maxSize: 10 }))).toMatchSnapshot(); }); test('string structure', async () => { const result = sampleFuzzer(Fuzz.string({ maxSize: 50 }), 10); for await (let tree of result) { const root: string = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<string>>(RoseTree.children(tree)); for await (let c of RoseTree.children(tree)) { const value = await RoseTree.root(c); expect(value.length).toBeLessThanOrEqual(root.length); } if (root === '') { expect(children).toHaveLength(0); } else { expect(await some(children, async c => (await RoseTree.root(c)).length < root.length)).toEqual(true); } } }); test('asciiString', async () => { expect(await serializedSample(Fuzz.asciiString({ maxSize: 10 }))).toMatchSnapshot(); }); test('string structure', async () => { const result = sampleFuzzer(Fuzz.asciiString({ maxSize: 50 }), 10); for await (let tree of result) { const root: string = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<string>>(RoseTree.children(tree)); for (let c of children) { const value = await RoseTree.root(c); expect(value.length).toBeLessThanOrEqual(root.length); } if (root === '') { expect(children).toHaveLength(0); } else { expect(await some(children, async c => (await RoseTree.root(c)).length < root.length)).toEqual(true); } } }); test('array', async () => { expect( await serializedSample(Fuzz.array(Fuzz.integer({ minSize: 10, maxSize: 20 }), { maxSize: 10 })), ).toMatchSnapshot(); }); test('array structure', async () => { const result = sampleFuzzer(Fuzz.array(Fuzz.integer({ minSize: 10, maxSize: 20 }), { maxSize: 40 }), 10); for await (let tree of result) { const root: number[] = await RoseTree.root(tree); const children = await Iter.toArray<RoseTree.Rose<number[]>>(RoseTree.children(tree)); for await (let c of RoseTree.children(tree)) { const value = await RoseTree.root(c); expect(value.length).toBeLessThanOrEqual(root.length); } } }); test('object structure', async () => { const result = await Iter.toArray( sampleFuzzer( Fuzz.object<{ a: number; b: string }>({ a: Fuzz.integer({ minSize: -1e5, maxSize: 1e5 }), b: Fuzz.string({ maxSize: 12 }), }), ), ); const tree = result[0]; const root = await RoseTree.root(tree as any); const children = RoseTree.children(tree as any); for await (let kid of children) { const next = await RoseTree.root(kid); expect(next).not.toEqual(root); } }); test('zip', async () => { const fuzzer = Fuzz.zip(Fuzz.string({ maxSize: 10 }), Fuzz.integer({ minSize: -1e5, maxSize: 1e5 })); testValues(fuzzer, ([a, b]) => { expect(typeof a).toEqual('string'); expect(typeof b).toEqual('number'); }); }); test('zip3', async () => { const fuzzer = Fuzz.zip3( Fuzz.string({ maxSize: 40 }), Fuzz.integer({ minSize: -1e5, maxSize: 1e5 }), Fuzz.object({ a: Fuzz.string({ maxSize: 10 }) }), ); testValues(fuzzer, ([a, b, c]) => { expect(typeof a).toEqual('string'); expect(typeof b).toEqual('number'); expect(typeof c.a).toEqual('string'); expect(Object.keys(c)).toEqual(['a']); }); }); test('zip4', async () => { const fuzzer = Fuzz.zip4( Fuzz.string({ maxSize: 40 }), Fuzz.integer({ minSize: -1e5, maxSize: 1e5 }), Fuzz.object({ a: Fuzz.string({ maxSize: 10 }) }), Fuzz.array(Fuzz.integer({ minSize: 0, maxSize: 10 }), { maxSize: 5 }), ); testValues(fuzzer, ([a, b, c, d]) => { expect(typeof a).toEqual('string'); expect(typeof b).toEqual('number'); expect(typeof c.a).toEqual('string'); expect(Object.keys(c)).toEqual(['a']); expect(Array.isArray(d)).toEqual(true); d.forEach(val => { expect(typeof val).toEqual('number'); expect(val).toBeGreaterThanOrEqual(0); expect(val).toBeLessThanOrEqual(10); }); }); }); test('zip5', async () => { const fuzzer = Fuzz.zip5( Fuzz.string({ maxSize: 40 }), Fuzz.integer({ minSize: -1e5, maxSize: 1e5 }), Fuzz.object({ a: Fuzz.string({ maxSize: 10 }) }), Fuzz.array(Fuzz.integer({ minSize: 0, maxSize: 10 }), { maxSize: 5 }), Fuzz.constant('!!!!'), ); testValues(fuzzer, ([a, b, c, d, e]) => { expect(typeof a).toEqual('string'); expect(typeof b).toEqual('number'); expect(typeof c.a).toEqual('string'); expect(Object.keys(c)).toEqual(['a']); expect(Array.isArray(d)).toEqual(true); d.forEach(val => { expect(typeof val).toEqual('number'); expect(val).toBeGreaterThanOrEqual(0); expect(val).toBeLessThanOrEqual(10); }); expect(e).toEqual('!!!!'); }); }); test('map', async () => { const fuzzA = Fuzz.string({ maxSize: 40 }); const fuzzB = fuzzA.map(str => str.length); const resultA: string[] = (await serializedSample(fuzzA)).map(RoseTree.root); const resultB: number[] = (await serializedSample(fuzzB)).map(RoseTree.root); expect(resultA.every(o => typeof o === 'string')).toEqual(true); expect(resultB.every(o => typeof o === 'number')).toEqual(true); }); test('map2', async () => { const fuzzA = Fuzz.string({ maxSize: 40 }); const fuzzB = Fuzz.constant('!'); const fuzzC = Fuzz.map2((a, b) => '!' + b + a, fuzzA, fuzzB); const result = await serializedSample(fuzzC); result.map(RoseTree.root).forEach((root: string) => { expect(root.length).toBeGreaterThanOrEqual(2); expect(root.slice(0, 2)).toEqual('!!'); }); expect(result).toMatchSnapshot(); }); test('filter', async () => { const fuzz = Fuzz.integer().filter(num => num > 5); await testValues(fuzz, num => { expect(num).toBeGreaterThan(5); }); }); test('maybe', async () => { const fuzz = Fuzz.string({ maxSize: 40 }).maybe(); const result = await serializedSample(fuzz); // from static seed, this is the one with an undefined root. const str = result[0]; const undef = result[6]; // validate assumption expect(typeof RoseTree.root(str)).toEqual('string'); expect(RoseTree.root(undef)).toEqual(undefined); const strChildren = await Iter.toArray(RoseTree.children(str)); const undefChildren = await Iter.toArray(RoseTree.children(undef)); expect(strChildren.every((c: RoseTree.Rose<any>) => typeof RoseTree.root(c) === 'string')).toEqual(true); expect(undefChildren.every((c: RoseTree.Rose<any>) => RoseTree.root(c) === undefined)).toEqual(true); }); test('noShrink', async () => { const fuzzA = Fuzz.string({ maxSize: 20 }).noShrink(); const fuzzB = Fuzz.integer({ minSize: 10, maxSize: 50 }); const fuzz = Fuzz.zip(fuzzA, fuzzB); const trees = sampleFuzzer(fuzz); const someHaveChildren = await Iter.some(async tree => { const arr = await Iter.toArray(RoseTree.children(tree as any)); return arr.length > 0; }, trees); const everyHasChildrenOrStartsWithMinInteger = await Iter.every(async tree => { const arr = await Iter.toArray(RoseTree.children(tree as any)); return arr.length > 0 || (await RoseTree.root(tree))[1] === 10; }, trees); expect(someHaveChildren && everyHasChildrenOrStartsWithMinInteger).toEqual(true); for await (let tree of trees) { const [stringA, numberA] = await RoseTree.root(tree); for await (let child of RoseTree.children(tree)) { const [stringB, numberB] = await RoseTree.root(child); expect(stringA).toEqual(stringB); expect(numberA).toBeGreaterThan(numberB); } } }); test('oneOf', async () => { const oneOrTwo = Fuzz.oneOf([Fuzz.constant(1), Fuzz.constant(2)]); const trees = sampleFuzzer(oneOrTwo); let found1 = false; let found2 = false; for await (let tree of trees) { const root = await RoseTree.root(tree); found1 = root === 1 ? true : found1; found2 = root === 2 ? true : found2; expect([1, 2]).toContain(root); } expect(found1).toEqual(true); expect(found2).toEqual(true); }); test('flatMap', async () => { const fuzz = Fuzz.posInteger({ maxSize: 5 }).flatMap(maxSize => Fuzz.string({ maxSize })); await testValues(fuzz, str => expect(typeof str).toEqual('string')); });
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQueryUI plugin that can display a list of flight/aircraft data for a report. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.reportListClass = VRS.globalOptions.reportListClass || 'vrsAircraftList flights'; // The CSS class to attach to the report list. VRS.globalOptions.reportListSingleAircraftColumns = VRS.globalOptions.reportListSingleAircraftColumns || [ // The default columns to show in the list for reports where there is only a single aircraft specified by the criteria and only one aircraft in the results. VRS.ReportFlightProperty.RowNumber, VRS.ReportFlightProperty.StartTime, VRS.ReportFlightProperty.Duration, VRS.ReportFlightProperty.Callsign, VRS.ReportFlightProperty.RouteShort, VRS.ReportFlightProperty.Altitude, VRS.ReportFlightProperty.Speed, VRS.ReportFlightProperty.Squawk ]; VRS.globalOptions.reportListManyAircraftColumns = VRS.globalOptions.reportListManyAircraftColumns || [ // The default columns to show in the list for reports where the criteria could match more than one aircraft. VRS.ReportFlightProperty.RowNumber, VRS.ReportFlightProperty.StartTime, VRS.ReportFlightProperty.Duration, VRS.ReportAircraftProperty.Silhouette, VRS.ReportAircraftProperty.OperatorFlag, VRS.ReportAircraftProperty.Registration, VRS.ReportAircraftProperty.Icao, VRS.ReportFlightProperty.Callsign, VRS.ReportFlightProperty.RouteShort, VRS.ReportAircraftProperty.Operator, VRS.ReportAircraftProperty.ModelIcao, VRS.ReportAircraftProperty.Model, VRS.ReportAircraftProperty.Species, VRS.ReportAircraftProperty.ModeSCountry, VRS.ReportAircraftProperty.Military ]; VRS.globalOptions.reportListDefaultShowUnits = VRS.globalOptions.reportListDefaultShowUnits !== undefined ? VRS.globalOptions.reportListDefaultShowUnits : true; // True if the default should be to show units. VRS.globalOptions.reportListDistinguishOnGround = VRS.globalOptions.reportListDistinguishOnGround !== undefined ? VRS.globalOptions.reportListDistinguishOnGround : true; // True if aircraft on ground should be shown as an altitude of GND. VRS.globalOptions.reportListShowPagerTop = VRS.globalOptions.reportListShowPagerTop !== undefined ? VRS.globalOptions.reportListShowPagerTop : true; // True if the report list is to show a pager above the list. VRS.globalOptions.reportListShowPagerBottom = VRS.globalOptions.reportListShowPagerBottom !== undefined ? VRS.globalOptions.reportListShowPagerBottom : true; // True if the report list is to show a pager below the list. VRS.globalOptions.reportListUserCanConfigureColumns = VRS.globalOptions.reportListUserCanConfigureColumns !== undefined ? VRS.globalOptions.reportListUserCanConfigureColumns : true; // True if the user is allowed to configure the columns in the report list. VRS.globalOptions.reportListGroupBySortColumn = VRS.globalOptions.reportListGroupBySortColumn !== undefined ? VRS.globalOptions.reportListGroupBySortColumn : true; // True if the report list should show group rows when the value of the first sort column changes. VRS.globalOptions.reportListGroupResetAlternateRows = VRS.globalOptions.reportListGroupResetAlternateRows !== undefined ? VRS.globalOptions.reportListGroupResetAlternateRows : false; // True if the report list should reset the alternate row shading at the start of each group. /** * The options for the ReportListPlugin */ export interface ReportListPlugin_Options extends ReportRender_Options { /** * The name to use when saving and loading state. */ name?: string; /** * The report whose content is going to be displayed by the list. */ report: Report; /** * The VRS.UnitDisplayPreferences that dictate how values are to be displayed. */ unitDisplayPreferences: UnitDisplayPreferences /** * The columns to display when the report criteria only allows for a single aircraft and only 0 or 1 aircraft were returned. */ singleAircraftColumns?: ReportAircraftPropertyEnum[]; /** * The columns to display when the report criteria allows for more than one aircraft to be returned. */ manyAircraftColumns?: ReportAircraftOrFlightPropertyEnum[]; /** * True if the state last saved by the user against name should be loaded and applied immediately when creating the control. */ useSavedState?: boolean; /** * True if heights, distances and speeds should indicate their units. */ showUnits?: boolean; /** * True if altitudes should distinguish between altitudes of zero and aircraft on the ground. */ distinguishOnGround?: boolean; /** * True if the pager is to be shown above the list, false if it is not. */ showPagerTop?: boolean; /** * True if the pager is to be shown below the list, false if it is not. */ showPagerBottom?: boolean; /** * True if the report should break the report into groups on the first sort column. */ groupBySortColumn?: boolean; /** * True if the report should reset the alternate row shading at the start of each group. */ groupResetAlternateRows?: boolean; /** * FOR INTERNAL USE ONLY. True if only the start time is to be shown on start dates. */ justShowStartTime?: boolean; /** * FOR INTERNAL USE ONLY. True if the end date should always show the date portion, even if it is the same as the start date. */ alwaysShowEndDate?: boolean; } /** * The state for ReportListPlugin. */ class ReportListPlugin_State { /** * The element holding the table. */ tableElement: JQuery = null; /** * The element that is shown when a message is to be displayed instead of the table - e.g. when the report is empty. */ messageElement: JQuery = null; /** * An associative array of flight row numbers and the table row element for that flight's row. */ flightRows: { [index: number]: JQuery } = {}; /** * The element for the row that is currently marked as selected. */ selectedRowElement: JQuery = null; /** * The element for the pager placed before the list. */ pagerTopElement: JQuery = null; /** * The direct reference to the pager placed after the list, if any. */ pagerTopPlugin: ReportPagerPlugin = null; /** * The element for the pager placed after the list. */ pagerBottomElement: JQuery = null; /** * The direct reference to the pager placed after the list, if any. */ pagerBottomPlugin: ReportPagerPlugin = null; /** * The hook result for the rows fetched event. */ rowsFetchedHookResult: IEventHandle = null; /** * The hook result for the selected flight changed event. */ selectedFlightChangedHookResult: IEventHandle = null; /** * The hook result for the locale changed event. */ localeChangedHookResult: IEventHandle = null; } /** * The settings saved by the ReportListPlugin between sessions. */ export interface ReportListPlugin_SaveState { singleAircraftColumns: ReportAircraftPropertyEnum[]; manyAircraftColumns: ReportAircraftOrFlightPropertyEnum[]; showUnits: boolean; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getReportListPlugin = function(jQueryElement: JQuery) : ReportListPlugin { return jQueryElement.data('vrsVrsReportList'); } VRS.jQueryUIHelper.getReportListOptions = function(overrides?: ReportListPlugin_Options) : ReportListPlugin_Options { return $.extend({ name: 'default', singleAircraftColumns: VRS.globalOptions.reportListSingleAircraftColumns.slice(), manyAircraftColumns: VRS.globalOptions.reportListManyAircraftColumns.slice(), useSavedState: true, showUnits: VRS.globalOptions.reportListDefaultShowUnits, distinguishOnGround: VRS.globalOptions.reportListDistinguishOnGround, showPagerTop: VRS.globalOptions.reportListShowPagerTop, showPagerBottom: VRS.globalOptions.reportListShowPagerBottom, groupBySortColumn: VRS.globalOptions.reportListGroupBySortColumn, groupResetAlternateRows: VRS.globalOptions.reportListGroupResetAlternateRows, // These are intended for internal use only. justShowStartTime: false, alwaysShowEndDate: false }, overrides); } /** * A jQuery UI widget that can display the rows in a report. */ export class ReportListPlugin extends JQueryUICustomWidget implements ISelfPersist<ReportListPlugin_SaveState> { options: ReportListPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getReportListOptions(); } private _getState() : ReportListPlugin_State { var result = this.element.data('reportListPluginState'); if(result === undefined) { result = new ReportListPlugin_State(); this.element.data('reportListPluginState', result); } return result; } _create() { var state = this._getState(); var options = this.options; this.element.addClass(VRS.globalOptions.reportListClass); if(options.useSavedState) { this.loadAndApplyState(); } VRS.globalisation.hookLocaleChanged(this._localeChanged, this); state.rowsFetchedHookResult = options.report.hookRowsFetched(this._rowsFetched, this); state.selectedFlightChangedHookResult = options.report.hookSelectedFlightCHanged(this._selectedFlightChanged, this); } private _destroy() { var state = this._getState(); var options = this.options; if(state.rowsFetchedHookResult && options.report) { options.report.unhook(state.rowsFetchedHookResult); } state.rowsFetchedHookResult = null; if(state.selectedFlightChangedHookResult && options.report) { options.report.unhook(state.selectedFlightChangedHookResult); } state.selectedFlightChangedHookResult = null; if(state.localeChangedHookResult && VRS.globalisation) { VRS.globalisation.unhook(state.localeChangedHookResult); } state.localeChangedHookResult = null; this._destroyTable(state); this.element.removeClass(VRS.globalOptions.reportListClass); } /** * Saves the current state of the object. */ saveState() { VRS.configStorage.save(this._persistenceKey(), this._createSettings()); } /** * Loads the previously saved state of the object or the current state if it's never been saved. */ loadState() : ReportListPlugin_SaveState { var savedSettings = VRS.configStorage.load(this._persistenceKey(), {}); var result = $.extend(this._createSettings(), savedSettings); result.singleAircraftColumns = VRS.reportPropertyHandlerHelper.buildValidReportPropertiesList(result.singleAircraftColumns, [ VRS.ReportSurface.List ]); result.manyAircraftColumns = VRS.reportPropertyHandlerHelper.buildValidReportPropertiesList(result.manyAircraftColumns, [ VRS.ReportSurface.List ]); return result; } /** * Applies a previously saved state to the object. */ applyState(settings: ReportListPlugin_SaveState) { this.options.singleAircraftColumns = settings.singleAircraftColumns; this.options.manyAircraftColumns = settings.manyAircraftColumns; this.options.showUnits = settings.showUnits; } /** * Loads and then applies a previousy saved state to the object. */ loadAndApplyState() { this.applyState(this.loadState()); } /** * Returns the key under which the state will be saved. */ private _persistenceKey() : string { return 'vrsReportList-' + this.options.report.getName() + '-' + this.options.name; } /** * Creates the saved state object. */ private _createSettings() : ReportListPlugin_SaveState { return { singleAircraftColumns: this.options.singleAircraftColumns, manyAircraftColumns: this.options.manyAircraftColumns, showUnits: this.options.showUnits }; } /** * Returns the option pane that can be used to configure the widget via the UI. */ createOptionPane(displayOrder: number) : OptionPane[] { var result: OptionPane[] = []; result.push(new VRS.OptionPane({ name: 'commonListSettingsPane', titleKey: 'PaneListSettings', displayOrder: displayOrder, fields: [ new VRS.OptionFieldCheckBox({ name: 'showUnits', labelKey: 'ShowUnits', getValue: () => this.options.showUnits, setValue: (value) => { this.options.showUnits = value; this.refreshDisplay(); }, saveState: () => this.saveState() }) ] })); if(VRS.globalOptions.reportListUserCanConfigureColumns) { var singleAircraftPane = new VRS.OptionPane({ name: 'singleAircraftPane', titleKey: 'PaneSingleAircraft', displayOrder: displayOrder + 10 }); result.push(singleAircraftPane); VRS.reportPropertyHandlerHelper.addReportPropertyListOptionsToPane({ pane: singleAircraftPane, fieldLabel: 'Columns', surface: VRS.ReportSurface.List, getList: () => this.options.singleAircraftColumns, setList: (cols) => { this.options.singleAircraftColumns = cols; this.refreshDisplay(); }, saveState: () => this.saveState() }); var manyAircraftPane = new VRS.OptionPane({ name: 'manyAircraftPane', titleKey: 'PaneManyAircraft', displayOrder: displayOrder + 20 }); result.push(manyAircraftPane); VRS.reportPropertyHandlerHelper.addReportPropertyListOptionsToPane({ pane: manyAircraftPane, fieldLabel: 'Columns', surface: VRS.ReportSurface.List, getList: () => this.options.manyAircraftColumns, setList: (cols) => { this.options.manyAircraftColumns = cols; this.refreshDisplay(); }, saveState: () => this.saveState() }); } return result; } /** * Rebuilds the display. */ refreshDisplay() { this._buildTable(this._getState()); } /** * Erases the table if it currently exists and then rebuilds it in its entirety. Unlike the aircraft list speed * is not an issue here - the table is not being continuously updated. However, be aware that if the user asks * for all rows then it could be an extremely large table, so we don't want to be too tardy about it. */ private _buildTable(state: ReportListPlugin_State) { var options = this.options; this._destroyTable(state); if(options.report.getFlights().length === 0) { state.messageElement = $('<div/>') .addClass('emptyReport') .text(VRS.$$.ReportEmpty) .appendTo(this.element); } else { var self = this; var createPager = function(enabled, isTop) { var element = null, plugin = null; if(enabled && VRS.jQueryUIHelper.getReportPagerPlugin) { element = $('<div/>') .addClass(isTop ? 'top' : 'bottom') .vrsReportPager(VRS.jQueryUIHelper.getReportPagerOptions({ report: options.report })); plugin = VRS.jQueryUIHelper.getReportPagerPlugin(element); } if(isTop) { state.pagerTopElement = element; state.pagerTopPlugin = plugin; } else { state.pagerBottomElement = element; state.pagerBottomPlugin = plugin; } return element; }; var topPager = createPager(options.showPagerTop, true); var bottomPager = createPager(options.showPagerBottom, false); state.tableElement = $('<table/>') .addClass('aircraftList report') .appendTo(this.element); var columns = options.report.getCriteria().isForSingleAircraft() ? options.singleAircraftColumns : options.manyAircraftColumns; columns = VRS.arrayHelper.filter(columns, function(item) { return VRS.reportPropertyHandlers[item] instanceof VRS.ReportPropertyHandler; }); this._buildHeader(state, columns, topPager); this._buildBody(state, columns, options.report.getFlights(), bottomPager); } } /** * Adds the pager passed across to a table. */ private _addPagerToTable(pager: JQuery, section: JQuery, cellType: string, colspan: number) { if(pager) { var pagerRow = $('<tr/>') .addClass('pagerRow') .appendTo(section); $(cellType) .attr('colspan', colspan) .appendTo(pagerRow) .append(pager); } } /** * Builds the table header. */ private _buildHeader(state: ReportListPlugin_State, columns: ReportAircraftOrFlightPropertyEnum[], pager: JQuery) { var thead = $('<thead/>') .appendTo(state.tableElement); this._addPagerToTable(pager, thead, '<th/>', columns.length); var tr = $('<tr/>') .appendTo(thead); var length = columns.length; var lastCell; for(var i = 0;i < length;++i) { var property = columns[i]; var handler = VRS.reportPropertyHandlers[property]; var cell = lastCell = $('<th/>') .text(VRS.globalisation.getText(handler.headingKey)) .appendTo(tr); this._setCellAlignment(cell, handler.headingAlignment); if(handler.fixedWidth) this._setFixedWidth(cell, handler.fixedWidth()); } if(lastCell) { lastCell.addClass('lastColumn'); } } /** * Builds the table body. */ private _buildBody(state: ReportListPlugin_State, columns: ReportAircraftOrFlightPropertyEnum[], flights: IReportFlight[], pager: JQuery) { var options = this.options; var self = this; var tbody = $('<tbody/>') .appendTo(state.tableElement); var groupColumnHandler = VRS.reportPropertyHandlerHelper.findPropertyHandlerForSortColumn(options.report.getGroupSortColumn()); var previousGroupValue = null; var justShowStartTime = options.justShowStartTime; if(groupColumnHandler && groupColumnHandler.property === VRS.ReportFlightProperty.StartTime) { options.justShowStartTime = true; } var countColumns = columns.length; var countRows = flights.length; var isOdd = true; for(var rowNum = 0;rowNum < countRows;++rowNum) { var flight = flights[rowNum]; var aircraft = flight.aircraft; var firstRow = rowNum === 0; if(options.groupBySortColumn && groupColumnHandler) { var groupValue = groupColumnHandler.groupValue(groupColumnHandler.isAircraftProperty ? aircraft : flight); if(!groupValue) { groupValue = VRS.$$.None; } if(rowNum === 0 || groupValue !== previousGroupValue) { if(options.groupResetAlternateRows) { isOdd = true; } var groupRow = $('<tr/>') .addClass('group') .appendTo(tbody); if(firstRow) { groupRow.addClass('firstRow'); firstRow = false; } var groupCell = $('<td/>') .appendTo(groupRow) .attr('colspan', countColumns) .text(groupValue); } previousGroupValue = groupValue; } var tr = $('<tr/>') .addClass(isOdd ? 'vrsOdd' : 'vrsEven') .appendTo(tbody) .on('click', function(e) { self._rowClicked(e, this); }); if(firstRow) { tr.addClass('firstRow'); } state.flightRows[flight.row] = tr; var lastCell; for(var colNum = 0;colNum < countColumns;++colNum) { var property = columns[colNum]; var handler = VRS.reportPropertyHandlers[property]; var cell = lastCell = $('<td/>') .appendTo(tr); this._setCellAlignment(cell, handler.headingAlignment); if(handler.fixedWidth) { this._setFixedWidth(cell, handler.fixedWidth(VRS.ReportSurface.List)); } handler.renderIntoJQueryElement(cell, handler.isAircraftProperty ? aircraft : flight, options, VRS.ReportSurface.List); } if(lastCell) { lastCell.addClass('lastColumn'); } isOdd = !isOdd; } this._addPagerToTable(pager, tbody, '<td/>', columns.length); options.justShowStartTime = justShowStartTime; this._markSelectedRow(); } /** * Erases the table if it currently exists, releasing all resources allocated to it. */ private _destroyTable(state: ReportListPlugin_State) { if(state.messageElement) { state.messageElement.remove(); } state.messageElement = null; for(var rowId in state.flightRows) { var row = state.flightRows[rowId]; if(row instanceof jQuery) { row.off(); } } state.flightRows = {}; if(state.tableElement) { state.tableElement.remove(); state.tableElement = null; } state.selectedRowElement = null; if(state.pagerTopPlugin) { state.pagerTopPlugin.destroy(); } if(state.pagerTopElement) { state.pagerTopElement.remove(); } state.pagerTopElement = state.pagerTopPlugin = null; if(state.pagerBottomPlugin) { state.pagerBottomPlugin.destroy(); } if(state.pagerBottomElement) { state.pagerBottomElement.remove(); } state.pagerBottomElement = state.pagerBottomPlugin = null; } /** * Sets the alignment on a cell. */ private _setCellAlignment(cell: JQuery, alignment: AlignmentEnum) { if(cell && alignment) { switch(alignment) { case VRS.Alignment.Left: break; case VRS.Alignment.Centre: cell.addClass('vrsCentre'); break; case VRS.Alignment.Right: cell.addClass('vrsRight'); break; } } } /** * Sets the fixed width on a cell. */ private _setFixedWidth(cell: JQuery, fixedWidth: string) { if(fixedWidth) { cell.attr('width', fixedWidth); cell.addClass('fixedWidth'); } } /** * Returns the flight corresponding to the row clicked. */ private _getFlightForTableRow(row: JQuery | HTMLTableRowElement) : IReportFlight { var result: IReportFlight = null; var state = this._getState(); var options = this.options; var flights = options.report.getFlights(); if(flights.length) { if(!(row instanceof jQuery)) { row = $(row); } for(var rowId in state.flightRows) { var numericRowId = Number(rowId); var flightRow = state.flightRows[rowId]; if(flightRow instanceof jQuery && flightRow.is(row)) { var length = flights.length; for(var i = 0;i < length;++i) { var flight = flights[i]; if(flight.row == numericRowId) { result = flight; break; } } break; } } } return result; } /** * Ensures that the selected row, and only the selected row, has a class on it to indicate that it is selected. */ private _markSelectedRow() { var state = this._getState(); if(state.selectedRowElement) { state.selectedRowElement.removeClass('vrsSelected'); } var selectedFlight = this.options.report.getSelectedFlight(); if(!selectedFlight) { state.selectedRowElement = null; } else { var selectedFlightRowId = selectedFlight ? selectedFlight.row : null; var selectedRow = state.flightRows[selectedFlightRowId]; if(selectedRow) selectedRow.addClass('vrsSelected'); state.selectedRowElement = selectedRow; } } /** * Called when the user chooses another language. */ private _localeChanged() { this.refreshDisplay(); } /** * Called when the user clicks a row in the body of the list. */ private _rowClicked(event: Event, target: HTMLTableRowElement) { var flight = this._getFlightForTableRow(target); this.options.report.setSelectedFlight(flight); } /** * Called when the report has successfully fetched some data to display. */ private _rowsFetched() { var state = this._getState(); this._buildTable(state); } /** * Called when something changes the selected flight on the report. */ private _selectedFlightChanged() { this._markSelectedRow(); } } $.widget('vrs.vrsReportList', new ReportListPlugin()); } declare interface JQuery { vrsReportList(); vrsReportList(options: VRS.ReportListPlugin_Options); vrsReportList(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
"use strict"; import * as path from "path"; import * as vscode from "vscode"; import { FileHelper, IFileResolver } from "./FileHelper"; import { Helper, IFormat } from "./helper"; import { fdir, OnlyCountsOutput, PathsOutput } from "fdir"; import { SassHelper } from "./SassCompileHelper"; import { StatusBarUi } from "./StatusbarUi"; import { ErrorLogger, OutputLevel, OutputWindow } from "./VscodeExtensions"; import autoprefixer from "autoprefixer"; import BrowserslistError from "browserslist/error"; import fs from "fs"; import picomatch from "picomatch"; import postcss from "postcss"; import { Options } from "sass"; export class AppModel { private isWatching: boolean; private _logger: ErrorLogger; constructor(workplaceState: vscode.Memento) { OutputWindow.Show(OutputLevel.Trace, "Constructing app model"); this.isWatching = Helper.getConfigSettings<boolean>("watchOnLaunch"); this._logger = new ErrorLogger(workplaceState); if (this.isWatching) { OutputWindow.Show(OutputLevel.Information, "Watching..."); } StatusBarUi.init(this.isWatching); OutputWindow.Show(OutputLevel.Trace, "App model constructed"); } async StartWatching(): Promise<void> { const compileOnWatch = Helper.getConfigSettings<boolean>("compileOnWatch"); if (!this.isWatching) { this.isWatching = !this.isWatching; if (compileOnWatch) { await this.compileAllFiles(); return; } } this.revertUIToWatchingStatusNow(); } StopWatching(): void { if (this.isWatching) { this.isWatching = !this.isWatching; } this.revertUIToWatchingStatusNow(); } openOutputWindow(): void { OutputWindow.Show(OutputLevel.Critical, null, null, false); } async createIssue(): Promise<void> { await this._logger.InitiateIssueCreator(); } /** * Waiting to see if Autoprefixer will add my changes async browserslistChecks(): Promise<void> { try { const autoprefixerTarget = Helper.getConfigSettings<Array<string> | boolean>( "autoprefix" ), filePath = vscode.window.activeTextEditor.document.fileName; if ( autoprefixerTarget === true && ( filePath.endsWith(`${path.sep}package.json`) || filePath.endsWith(`${path.sep}.browserslistrc`) ) ) autoprefixer.clearBrowserslistCaches(); } catch (err) { await this._logger.LogIssueWithAlert( `Unhandled error while clearing browserslist cache. Error message: ${err.message}`, { triggeringFile: vscode.window.activeTextEditor.document.fileName, error: ErrorLogger.PrepErrorForLogging(err), } ); } } */ //#region Compilation functions //#region Public /** * Compile all files. */ async compileAllFiles(): Promise<void> { OutputWindow.Show(OutputLevel.Trace, "Starting to compile all files"); try { StatusBarUi.working(); await this.GenerateAllCssAndMap(); } catch (err) { let files: string[] | string; try { files = await this.getSassFiles(); } catch (_) { files = "Error lies in getSassFiles()"; } if (err instanceof Error) { await this._logger.LogIssueWithAlert( `Unhandled error while compiling all files. Error message: ${err.message}`, { files: files, error: ErrorLogger.PrepErrorForLogging(err), } ); } else { await this._logger.LogIssueWithAlert( "Unhandled error while compiling all files. Error message: UNKNOWN (not Error type)", { files: files, error: JSON.stringify(err), } ); } } this.revertUIToWatchingStatusNow(); } /** * Compiles the currently active file */ async compileCurrentFile(): Promise<void> { OutputWindow.Show(OutputLevel.Trace, "Starting to compile current file"); try { if (!vscode.window.activeTextEditor) { StatusBarUi.customMessage( "No file open", "No file is open, ensure a file is open in the editor window", "warning" ); OutputWindow.Show(OutputLevel.Debug, "No active file", [ "There isn't an active editor window to process", ]); this.revertUIToWatchingStatus(); return; } const sassPath = vscode.window.activeTextEditor.document.fileName; if (!this.isSassFile(sassPath)) { if (this.isSassFile(sassPath, true)) { OutputWindow.Show(OutputLevel.Debug, "Can't process partial Sass", [ "The file currently open in the editor window is a partial sass file, these aren't processed singly", ]); StatusBarUi.customMessage( "Can't process partial Sass", "The file currently open in the editor window is a partial sass file, these aren't processed singly", "warning" ); } else { OutputWindow.Show(OutputLevel.Debug, "Not a Sass file", [ "The file currently open in the editor window isn't a sass file", ]); StatusBarUi.customMessage( "Not a Sass file", "The file currently open in the editor window isn't a sass file", "warning" ); } this.revertUIToWatchingStatus(); return; } StatusBarUi.working("Processing single file..."); OutputWindow.Show(OutputLevel.Debug, "Processing the current file", [ `Path: ${sassPath}`, ]); const workspaceFolder = AppModel.getWorkspaceFolder(sassPath); const formats = Helper.getConfigSettings<IFormat[]>("formats", workspaceFolder); const result = await Promise.all( formats.map(async (format, index) => { OutputWindow.Show( OutputLevel.Trace, `Starting format ${index + 1} of ${formats.length}`, [`Settings: ${JSON.stringify(format)}`] ); // Each format const options = this.getSassOptions(format), pathData = await this.generateCssAndMapUri( sassPath, format, workspaceFolder ); return await this.GenerateCssAndMap( workspaceFolder, sassPath, pathData.css, pathData.map, options ); }) ); if (result.indexOf(false) < 0) { StatusBarUi.compilationSuccess(this.isWatching); } } catch (err) { const sassPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.fileName : "/* NO ACTIVE FILE, PROCESSING SHOULD NOT HAVE OCCURRED */"; if (err instanceof Error) { await this._logger.LogIssueWithAlert( `Unhandled error while compiling the active file. Error message: ${err.message}`, { files: sassPath, error: ErrorLogger.PrepErrorForLogging(err), } ); } else { await this._logger.LogIssueWithAlert( "Unhandled error while compiling the active file. Error message: UNKNOWN (not Error type)", { files: sassPath, error: JSON.stringify(err), } ); } } } /** * Compiles the file that has just been saved */ async compileOnSave(): Promise<void> { try { const currentFile = vscode.window.activeTextEditor?.document.fileName; if (!currentFile || !this.isSassFile(currentFile, true)) { return; } OutputWindow.Show(OutputLevel.Trace, "SASS file saved", [ "A SASS file has been saved, starting checks", ]); if (!this.isWatching) { OutputWindow.Show(OutputLevel.Trace, "Not watching", [ "The file has not been compiled as Live SASS is not watching", ]); return; } const workspaceFolder = AppModel.getWorkspaceFolder(currentFile); if (await this.isSassFileExcluded(currentFile, workspaceFolder)) { OutputWindow.Show(OutputLevel.Trace, "File excluded", [ "The file has not been compiled as it's excluded by user settings", `Path: ${currentFile}`, ]); return; } OutputWindow.Show( OutputLevel.Information, "Change detected - " + new Date().toLocaleString(), [path.basename(currentFile)] ); if (this.isSassFile(currentFile)) { OutputWindow.Show(OutputLevel.Trace, "File is not a partial", [ "The file is not a partial so we will compile only this one", `Path: ${currentFile}`, ]); const formats = Helper.getConfigSettings<IFormat[]>("formats", workspaceFolder); await Promise.all( formats.map(async (format, index) => { OutputWindow.Show( OutputLevel.Trace, `Starting format ${index + 1} of ${formats.length}`, [`Settings: ${JSON.stringify(format)}`] ); // Each format const options = this.getSassOptions(format), cssMapUri = await this.generateCssAndMapUri( currentFile, format, workspaceFolder ); await this.GenerateCssAndMap( workspaceFolder, currentFile, cssMapUri.css, cssMapUri.map, options ); }) ); } else { // Partial await this.GenerateAllCssAndMap(); } } catch (err) { let files: string[] | string; try { files = await this.getSassFiles(); } catch (_) { files = "Error lies in getSassFiles()"; } if (err instanceof Error) { await this._logger.LogIssueWithAlert( `Unhandled error while compiling the saved changes. Error message: ${err.message}`, { triggeringFile: vscode.window.activeTextEditor?.document.fileName ?? "NO SASS FILE - Should not have been called", allFiles: files, error: ErrorLogger.PrepErrorForLogging(err), } ); } else { await this._logger.LogIssueWithAlert( "Unhandled error while compiling the saved changes. Error message: UNKNOWN (not Error type)", { triggeringFile: vscode.window.activeTextEditor?.document.fileName ?? "NO SASS FILE - Should not have been called", allFiles: files, error: JSON.stringify(err), } ); } } this.revertUIToWatchingStatus(); } //#endregion Public //#region Private private getSassOptions(format: IFormat) { return SassHelper.toSassOptions(format); } /** * To Generate one One Css & Map file from Sass/Scss * @param sassPath Sass/Scss file URI (string) * @param targetCssUri Target CSS file URI (string) * @param mapFileUri Target MAP file URI (string) * @param options - Object - It includes target CSS style and some more. */ private async GenerateCssAndMap( folder: vscode.WorkspaceFolder | undefined, sassPath: string, targetCssUri: string, mapFileUri: string, options: Options ) { OutputWindow.Show(OutputLevel.Trace, "Starting compilation", [ "Starting compilation of file", `Path: ${sassPath}`, ]); const generateMap = Helper.getConfigSettings<boolean>("generateMap", folder), autoprefixerTarget = Helper.getConfigSettings<Array<string> | boolean>( "autoprefix", folder ), compileResult = SassHelper.compileOne(sassPath, mapFileUri, options), promises: Promise<IFileResolver>[] = []; if (compileResult.errorString !== null) { OutputWindow.Show(OutputLevel.Error, "Compilation Error", [compileResult.errorString]); StatusBarUi.compilationError(this.isWatching); return false; } let css: string | undefined = compileResult.result?.css.toString(), map: string | undefined | null = compileResult.result?.map?.toString(); if (!css) { OutputWindow.Show(OutputLevel.Error, "Compilation Error", [ "There was no CSS output from sass/sass", ]); StatusBarUi.compilationError(this.isWatching); return false; } if (autoprefixerTarget != false) { OutputWindow.Show(OutputLevel.Trace, "Autoprefixer isn't false, applying to file", [ `Path: ${sassPath}`, ]); try { const autoprefixerResult = await this.autoprefix( folder, css, map, sassPath, targetCssUri, autoprefixerTarget ); css = autoprefixerResult.css; map = autoprefixerResult.map; } catch (err) { if (err instanceof BrowserslistError) { OutputWindow.Show( OutputLevel.Error, "Autoprefix error. Your changes have not been saved", [`Message: ${err.message}`, `Path: ${sassPath}`] ); return false; } else { throw err; } } } else if (map && generateMap) { const pMap: { file: string } = JSON.parse(map); pMap.file = `${path.basename(targetCssUri)}.map`; map = JSON.stringify(pMap); } if (map && generateMap) { css += `/*# sourceMappingURL=${path.basename(targetCssUri)}.map */`; promises.push(FileHelper.writeToOneFile(mapFileUri, map)); } promises.push(FileHelper.writeToOneFile(targetCssUri, css)); const fileResolvers = await Promise.all(promises); StatusBarUi.compilationSuccess(this.isWatching); OutputWindow.Show(OutputLevel.Information, "Generated:", null, false); fileResolvers.forEach((fileResolver) => { if (fileResolver.Exception) { OutputWindow.Show(OutputLevel.Error, "Error:", [ fileResolver.Exception.errno?.toString() ?? "UNKNOWN ERR NUMBER", fileResolver.Exception.path ?? "UNKNOWN PATH", fileResolver.Exception.message, ]); console.error("error :", fileResolver); } else { OutputWindow.Show(OutputLevel.Information, null, [fileResolver.FileUri], false); } }); OutputWindow.Show(OutputLevel.Information, null, null, true); return true; } /** * To compile all Sass/scss files */ private async GenerateAllCssAndMap() { const sassPaths = await this.getSassFiles(); OutputWindow.Show(OutputLevel.Debug, "Compiling Sass/Scss Files: ", sassPaths); await Promise.all( sassPaths.map(async (sassPath, pathIndex) => { OutputWindow.Show( OutputLevel.Trace, `Starting file ${pathIndex + 1} of ${sassPaths.length}`, [`Path: ${sassPath}`] ); const workspaceFolder = AppModel.getWorkspaceFolder(sassPath), formats = Helper.getConfigSettings<IFormat[]>("formats", workspaceFolder); await Promise.all( formats.map(async (format, formatIndex) => { OutputWindow.Show( OutputLevel.Trace, `Starting format ${formatIndex + 1} of ${formats.length}`, [`Settings: ${JSON.stringify(format)}`] ); // Each format const options = this.getSassOptions(format), cssMapUri = await this.generateCssAndMapUri( sassPath, format, workspaceFolder ); await this.GenerateCssAndMap( workspaceFolder, sassPath, cssMapUri.css, cssMapUri.map, options ); }) ); }) ); } /** * Generate a full save path for the final css & map files * @param filePath The path to the current SASS file */ private async generateCssAndMapUri( filePath: string, format: IFormat, workspaceRoot?: vscode.WorkspaceFolder ) { OutputWindow.Show(OutputLevel.Trace, "Calculating file paths", [ "Calculating the save paths for the css and map output files", `Originating path: ${filePath}`, ]); const extensionName = format.extensionName || ".css"; if (workspaceRoot) { OutputWindow.Show(OutputLevel.Trace, "No workspace provided", [ `Using originating path: ${filePath}`, ]); const workspacePath = workspaceRoot.uri.fsPath; let generatedUri = null; // NOTE: If all SavePath settings are `NULL`, CSS Uri will be same location as SASS if (format.savePath) { OutputWindow.Show(OutputLevel.Trace, "Using `savePath` setting", [ "This format has a `savePath`, using this (takes precedence if others are present)", `savePath: ${format.savePath}`, ]); if (format.savePath.startsWith("~")) { OutputWindow.Show( OutputLevel.Trace, "Path is relative to current file", [ "Path starts with a tilde, so the path is relative to the current path", `Original path: ${filePath}`, ], false ); generatedUri = path.join(path.dirname(filePath), format.savePath.substring(1)); } else { OutputWindow.Show( OutputLevel.Trace, "Path is relative to workspace folder", [ "No tilde so the path is relative to the workspace folder being used", `Original path: ${filePath}`, ], false ); generatedUri = path.join(workspacePath, format.savePath); } OutputWindow.Show(OutputLevel.Trace, `New path: ${generatedUri}`); FileHelper.MakeDirIfNotAvailable(generatedUri); filePath = path.join(generatedUri, path.basename(filePath)); } else if ( format.savePathSegmentKeys && format.savePathSegmentKeys.length && format.savePathReplaceSegmentsWith ) { OutputWindow.Show( OutputLevel.Trace, "Using segment replacement", [ `Keys: [${format.savePathSegmentKeys.join(", ")}] - Replacement: ${ format.savePathReplaceSegmentsWith }`, `Original path: ${filePath}`, ], false ); generatedUri = path.join( workspacePath, path .dirname(filePath) .substring(workspacePath.length + 1) .split(path.sep) .map((folder) => { return format.savePathSegmentKeys!.indexOf(folder) >= 0 ? format.savePathReplaceSegmentsWith : folder; }) .join(path.sep) ); OutputWindow.Show(OutputLevel.Trace, `New path: ${generatedUri}`); FileHelper.MakeDirIfNotAvailable(generatedUri); filePath = path.join(generatedUri, path.basename(filePath)); } } const cssUri = filePath.substring(0, filePath.lastIndexOf(".")) + extensionName; return { css: cssUri, map: cssUri + ".map", }; } /** * Autoprefix CSS properties */ private async autoprefix( folder: vscode.WorkspaceFolder | undefined, css: string, map: string | undefined, filePath: string, savePath: string, browsers: Array<string> | true ): Promise<{ css: string; map: string | null }> { OutputWindow.Show(OutputLevel.Trace, "Preparing autoprefixer"); const generateMap = Helper.getConfigSettings<boolean>("generateMap", folder), prefixer = postcss( autoprefixer({ overrideBrowserslist: browsers === true ? undefined : browsers, }) ); // TODO: REMOVE - when autoprefixer can stop caching the browsers const oldBrowserlistCache = process.env.BROWSERSLIST_DISABLE_CACHE; process.env.BROWSERSLIST_DISABLE_CACHE = "1"; OutputWindow.Show(OutputLevel.Trace, "Changing BROWSERSLIST_DISABLE_CACHE setting", [ `Was: ${oldBrowserlistCache ?? "UNDEFINED"}`, "Now: 1", ]); try { OutputWindow.Show(OutputLevel.Trace, "Starting autoprefixer"); const result = await prefixer.process(css, { from: filePath, to: savePath, map: { inline: false, prev: map, }, }); result.warnings().forEach((warn) => { const body: string[] = []; if (warn.node.source?.input.file) { body.push(warn.node.source.input.file + `:${warn.line}:${warn.column}`); } body.push(warn.text); OutputWindow.Show( warn.type === "warning" ? OutputLevel.Warning : OutputLevel.Error, `Autoprefix ${warn.type || "error"}`, body ); }); OutputWindow.Show(OutputLevel.Trace, "Completed autoprefixer"); return { css: result.css, map: generateMap ? result.map.toString() : null, }; } finally { process.env.BROWSERSLIST_DISABLE_CACHE = oldBrowserlistCache; OutputWindow.Show( OutputLevel.Trace, `Restored BROWSERSLIST_DISABLE_CACHE to: ${oldBrowserlistCache ?? "UNDEFINED"}` ); } } //#endregion Private //#endregion Compilation functions //#region UI manipulation functions private revertUIToWatchingStatus() { OutputWindow.Show( OutputLevel.Trace, "Registered timeout to revert UI to correct watching status" ); setTimeout(() => { this.revertUIToWatchingStatusNow(); }, 3000); } private revertUIToWatchingStatusNow() { OutputWindow.Show(OutputLevel.Trace, "Switching UI state"); if (this.isWatching) { StatusBarUi.watching(); OutputWindow.Show(OutputLevel.Information, "Watching..."); } else { StatusBarUi.notWatching(); OutputWindow.Show(OutputLevel.Information, "Not Watching..."); } } //#endregion UI manipulation functions //#region Fetch & check SASS functions //#region Private private isSassFile(pathUrl: string, partialSass = false): boolean { const filename = path.basename(pathUrl); return ( (partialSass || !filename.startsWith("_")) && (filename.endsWith("sass") || filename.endsWith("scss")) ); } private async isSassFileExcluded( sassPath: string, workspaceFolder?: vscode.WorkspaceFolder ): Promise<boolean> { OutputWindow.Show(OutputLevel.Trace, "Checking SASS path isn't excluded", [ `Path: ${sassPath}`, ]); if (workspaceFolder) { const includeItems = Helper.getConfigSettings<string[] | null>( "includeItems", workspaceFolder ), excludeItems = AppModel.stripAnyLeadingSlashes( Helper.getConfigSettings<string[]>("excludeList", workspaceFolder) ), forceBaseDirectory = Helper.getConfigSettings<string | null>( "forceBaseDirectory", workspaceFolder ); let fileList = ["**/*.s[a|c]ss"]; if (includeItems && includeItems.length) { fileList = AppModel.stripAnyLeadingSlashes(includeItems.concat("**/_*.s[a|c]ss")); } let basePath = workspaceFolder.uri.fsPath; if (forceBaseDirectory && forceBaseDirectory.length > 1) { OutputWindow.Show( OutputLevel.Trace, "`forceBaseDirectory` setting found, checking validity" ); basePath = path.resolve(basePath, AppModel.stripLeadingSlash(forceBaseDirectory)); try { if (!(await fs.promises.stat(basePath)).isDirectory()) { OutputWindow.Show( OutputLevel.Critical, "Error with your `forceBaseDirectory` setting", [ `Path is not a folder: ${basePath}`, `Setting: "${forceBaseDirectory}"`, `Workspace folder: ${workspaceFolder.name}`, ] ); return false; } } catch { OutputWindow.Show( OutputLevel.Critical, "Error with your `forceBaseDirectory` setting", [ `Can not find path: ${basePath}`, `Setting: "${forceBaseDirectory}"`, `Workspace folder: ${workspaceFolder.name}`, ] ); return false; } OutputWindow.Show( OutputLevel.Trace, "No problem with path, changing from workspace folder", [`New folder: ${basePath}`] ); } else { OutputWindow.Show( OutputLevel.Trace, "No base folder override found. Keeping workspace folder" ); } // @ts-ignore ts2322 => string[] doesn't match string (False negative as string[] is allowed) const isMatch = picomatch(fileList, { ignore: excludeItems, dot: true }); OutputWindow.Show(OutputLevel.Trace, "Searching folder", null, false); const searchFileCount = ( (await new fdir() .crawlWithOptions(basePath, { filters: [ (filePath) => filePath.endsWith(".scss") || filePath.endsWith(".sass"), (filePath) => isMatch(path.relative(basePath, filePath)), (filePath) => filePath.localeCompare(sassPath, undefined, { sensitivity: "accent", }) === 0, ], includeBasePath: true, onlyCounts: true, resolvePaths: true, suppressErrors: true, }) .withPromise()) as OnlyCountsOutput ).files; // If doesn't include true then it's not been found if (searchFileCount > 0) { OutputWindow.Show(OutputLevel.Trace, "File found, not excluded"); return false; } else { OutputWindow.Show(OutputLevel.Trace, "File not found, must be excluded"); return true; } } else { OutputWindow.Show(OutputLevel.Trace, "No workspace folder, checking the current file"); return ( path.basename(sassPath).startsWith("_") || !(sassPath.endsWith(".scss") || sassPath.endsWith(".sass")) ); } } private async getSassFiles( queryPattern: string | string[] = "**/[^_]*.s[a|c]ss", isQueryPatternFixed = false, isDebugging = false ): Promise<string[]> { OutputWindow.Show(OutputLevel.Trace, "Getting SASS files", [ `Query pattern: ${queryPattern}`, `Can be overwritten: ${!isQueryPatternFixed}`, ]); const fileList: string[] = []; if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 0) { ( await Promise.all( vscode.workspace.workspaceFolders.map( async (folder, index): Promise<PathsOutput | null> => { OutputWindow.Show( OutputLevel.Trace, `Checking folder ${index + 1} of ${ vscode.workspace.workspaceFolders!.length }`, [`Folder: ${folder.name}`] ); const includeItems = Helper.getConfigSettings<string[] | null>( "includeItems", folder ), forceBaseDirectory = Helper.getConfigSettings<string | null>( "forceBaseDirectory", folder ); let basePath = folder.uri.fsPath, excludedItems = isDebugging ? ["**/node_modules/**", ".vscode/**"] : Helper.getConfigSettings<string[]>("excludeList", folder); if (!isQueryPatternFixed && includeItems && includeItems.length) { queryPattern = AppModel.stripAnyLeadingSlashes(includeItems); OutputWindow.Show(OutputLevel.Trace, "Query pattern overwritten", [ `New pattern(s): "${includeItems.join('" , "')}"`, ]); } excludedItems = AppModel.stripAnyLeadingSlashes(excludedItems); if (forceBaseDirectory && forceBaseDirectory.length > 1) { OutputWindow.Show( OutputLevel.Trace, "`forceBaseDirectory` setting found, checking validity" ); basePath = path.resolve( basePath, AppModel.stripLeadingSlash(forceBaseDirectory) ); try { if (!(await fs.promises.stat(basePath)).isDirectory()) { OutputWindow.Show( OutputLevel.Critical, "Error with your `forceBaseDirectory` setting", [ `Path is not a folder: ${basePath}`, `Setting: "${forceBaseDirectory}"`, `Workspace folder: ${folder.name}`, ] ); return null; } } catch { OutputWindow.Show( OutputLevel.Critical, "Error with your `forceBaseDirectory` setting", [ `Can not find path: ${basePath}`, `Setting: "${forceBaseDirectory}"`, `Workspace folder: ${folder.name}`, ] ); return null; } OutputWindow.Show( OutputLevel.Trace, "No problem with path, changing from workspace folder", [`New folder: ${basePath}`] ); } else { OutputWindow.Show( OutputLevel.Trace, "No base folder override found. Keeping workspace folder" ); } const isMatch = picomatch(queryPattern, { // @ts-ignore ts2322 => string[] doesn't match string (False negative as string[] is allowed) ignore: excludedItems, dot: true, }); return (await new fdir() .crawlWithOptions(basePath, { filters: [ (filePath) => filePath.endsWith(".scss") || filePath.endsWith(".sass"), (filePath) => isMatch(path.relative(basePath, filePath)), (filePath) => isQueryPatternFixed || this.isSassFile(filePath, false), ], includeBasePath: true, resolvePaths: true, suppressErrors: true, }) .withPromise()) as PathsOutput; } ) ) ).forEach((files) => { files?.forEach((file) => { fileList.push(file); }); }); } else { OutputWindow.Show(OutputLevel.Trace, "No workspace, must be a single file solution"); if (vscode.window.activeTextEditor) { fileList.push(vscode.window.activeTextEditor.document.fileName); } else { fileList.push("No files found - not even an active file"); } } OutputWindow.Show(OutputLevel.Trace, `Found ${fileList.length} SASS files`); return fileList; } //#endregion Private //#endregion Fetch & check SASS functions //#region Debugging async debugInclusion(): Promise<void> { OutputWindow.Show(OutputLevel.Critical, "Checking current file", null, false); try { if (!vscode.window.activeTextEditor) { OutputWindow.Show(OutputLevel.Critical, "No active file", [ "There isn't an active editor window to process", "Click an open file so it can be checked", ]); return; } const sassPath = vscode.window.activeTextEditor.document.fileName; OutputWindow.Show(OutputLevel.Critical, sassPath, null, true); const workspaceFolder = AppModel.getWorkspaceFolder(sassPath); if (!this.isSassFile(sassPath, true)) { OutputWindow.Show(OutputLevel.Critical, "Not a Sass file", [ "The file currently open in the editor window isn't a sass file", ]); } else if (await this.isSassFileExcluded(sassPath, workspaceFolder)) { OutputWindow.Show(OutputLevel.Critical, "File excluded", [ "The file is excluded based on your settings, please check your configuration", ]); } else { OutputWindow.Show(OutputLevel.Critical, "File should get processed", [ "If the file isn't being processed, run `liveSass.command.debugFileList`", ]); } } catch (err) { const sassPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.fileName : "/* NO ACTIVE FILE, MESSAGE SHOULD HAVE BEEN THROWN */"; if (err instanceof Error) { await this._logger.LogIssueWithAlert( `Unhandled error while checking the active file. Error message: ${err.message}`, { file: sassPath, error: ErrorLogger.PrepErrorForLogging(err), } ); } else { await this._logger.LogIssueWithAlert( "Unhandled error while compiling the active file. Error message: UNKNOWN (not Error type)", { files: sassPath, error: JSON.stringify(err), } ); } } } async debugFileList(): Promise<void> { try { const outputInfo: string[] = [], workspaceCount = vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders.length : null; if (vscode.window.activeTextEditor) { outputInfo.push( "--------------------", "Current File", "--------------------", vscode.window.activeTextEditor.document.fileName ); } outputInfo.push("--------------------", "Workspace Folders", "--------------------"); if (workspaceCount === null) { outputInfo.push("No workspaces, must be a single file"); } else { vscode.workspace.workspaceFolders!.map((folder) => { outputInfo.push(`[${folder.index}] ${folder.name}\n${folder.uri.fsPath}`); }); await Promise.all( vscode.workspace.workspaceFolders!.map(async (folder, index) => { outputInfo.push( "--------------------", `Checking workspace folder ${index} of ${workspaceCount}`, `Path: ${folder.uri.fsPath}`, "--------------------" ); const exclusionList = Helper.getConfigSettings<string[]>( "excludeList", folder ); outputInfo.push( "--------------------", "Current Include/Exclude Settings", "--------------------", `Include: [ ${ Helper.getConfigSettings<string[] | null>( "includeItems", folder )?.join(", ") ?? "NULL" } ]`, `Exclude: [ ${exclusionList.join(", ")} ]` ); outputInfo.push( "--------------------", "Included SASS Files", "--------------------" ); (await this.getSassFiles()).map((file) => { outputInfo.push(file); }); outputInfo.push( "--------------------", "Included Partial SASS Files", "--------------------" ); (await this.getSassFiles("**/_*.s[a|c]ss", true)).map((file) => { outputInfo.push(file); }); outputInfo.push( "--------------------", "Excluded SASS Files", "--------------------" ); if (exclusionList.length > 0) { (await this.getSassFiles(exclusionList, true, true)).map((file) => { outputInfo.push(file); }); } else { outputInfo.push("NONE"); } }) ); } OutputWindow.Show(OutputLevel.Critical, "Extension Info", outputInfo); } catch (err) { const sassPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.fileName : "/* NO ACTIVE FILE, DETAILS BELOW */"; if (err instanceof Error) { await this._logger.LogIssueWithAlert( `Unhandled error while checking the active file. Error message: ${err.message}`, { file: sassPath, error: ErrorLogger.PrepErrorForLogging(err), } ); } else { await this._logger.LogIssueWithAlert( "Unhandled error while compiling the active file. Error message: UNKNOWN (not Error type)", { files: sassPath, error: JSON.stringify(err), } ); } } } //#endregion Debugging private static stripLeadingSlash(partialPath: string): string { return ["\\", "/"].indexOf(partialPath.substr(0, 1)) >= 0 ? partialPath.substr(1) : partialPath; } private static stripAnyLeadingSlashes(stringArray: string[] | null): string[] { if (!stringArray) { return []; } return stringArray.map((file) => { return AppModel.stripLeadingSlash(file); }); } private static getWorkspaceFolder(filePath: string) { const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(filePath)); if (workspaceFolder) { OutputWindow.Show(OutputLevel.Trace, "Found the workspace folder", [ `Workspace Name: ${workspaceFolder.name}`, ]); } else { OutputWindow.Show(OutputLevel.Warning, "Warning: File is not in a workspace", [ `Path: ${filePath}`, ]); } return workspaceFolder; } dispose(): void { OutputWindow.Show(OutputLevel.Trace, "Disposing app model"); StatusBarUi.dispose(); OutputWindow.dispose(); OutputWindow.Show(OutputLevel.Trace, "App model disposed"); } }
the_stack
import type { MessageValue, PromiseWorkerResponseWrapper } from '../utility-types' import { EMPTY_FUNCTION } from '../utils' import { isKillBehavior, KillBehaviors } from '../worker/worker-options' import type { IPoolInternal } from './pool-internal' import { PoolEmitter, PoolType } from './pool-internal' import type { WorkerChoiceStrategy } from './selection-strategies' import { WorkerChoiceStrategies, WorkerChoiceStrategyContext } from './selection-strategies' /** * Callback invoked if the worker has received a message. */ export type MessageHandler<Worker> = (this: Worker, m: unknown) => void /** * Callback invoked if the worker raised an error. */ export type ErrorHandler<Worker> = (this: Worker, e: Error) => void /** * Callback invoked when the worker has started successfully. */ export type OnlineHandler<Worker> = (this: Worker) => void /** * Callback invoked when the worker exits successfully. */ export type ExitHandler<Worker> = (this: Worker, code: number) => void /** * Basic interface that describes the minimum required implementation of listener events for a pool-worker. */ export interface IWorker { /** * Register a listener to the message event. * * @param event `'message'`. * @param handler The message handler. */ on(event: 'message', handler: MessageHandler<this>): void /** * Register a listener to the error event. * * @param event `'error'`. * @param handler The error handler. */ on(event: 'error', handler: ErrorHandler<this>): void /** * Register a listener to the online event. * * @param event `'online'`. * @param handler The online handler. */ on(event: 'online', handler: OnlineHandler<this>): void /** * Register a listener to the exit event. * * @param event `'exit'`. * @param handler The exit handler. */ on(event: 'exit', handler: ExitHandler<this>): void /** * Register a listener to the exit event that will only performed once. * * @param event `'exit'`. * @param handler The exit handler. */ once(event: 'exit', handler: ExitHandler<this>): void } /** * Options for a poolifier pool. */ export interface PoolOptions<Worker> { /** * A function that will listen for message event on each worker. */ messageHandler?: MessageHandler<Worker> /** * A function that will listen for error event on each worker. */ errorHandler?: ErrorHandler<Worker> /** * A function that will listen for online event on each worker. */ onlineHandler?: OnlineHandler<Worker> /** * A function that will listen for exit event on each worker. */ exitHandler?: ExitHandler<Worker> /** * The work choice strategy to use in this pool. */ workerChoiceStrategy?: WorkerChoiceStrategy /** * Pool events emission. * * @default true */ enableEvents?: boolean } /** * Base class containing some shared logic for all poolifier pools. * * @template Worker Type of worker which manages this pool. * @template Data Type of data sent to the worker. This can only be serializable data. * @template Response Type of response of execution. This can only be serializable data. */ export abstract class AbstractPool< Worker extends IWorker, Data = unknown, Response = unknown > implements IPoolInternal<Worker, Data, Response> { /** @inheritdoc */ public readonly workers: Worker[] = [] /** @inheritdoc */ public readonly tasks: Map<Worker, number> = new Map<Worker, number>() /** @inheritdoc */ public readonly emitter?: PoolEmitter /** @inheritdoc */ public readonly max?: number /** * The promise map. * * - `key`: This is the message Id of each submitted task. * - `value`: An object that contains the worker, the resolve function and the reject function. * * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message. */ protected promiseMap: Map< number, PromiseWorkerResponseWrapper<Worker, Response> > = new Map<number, PromiseWorkerResponseWrapper<Worker, Response>>() /** * Id of the next message. */ protected nextMessageId: number = 0 /** * Worker choice strategy instance implementing the worker choice algorithm. * * Default to a strategy implementing a round robin algorithm. */ protected workerChoiceStrategyContext: WorkerChoiceStrategyContext< Worker, Data, Response > /** * Constructs a new poolifier pool. * * @param numberOfWorkers Number of workers that this pool should manage. * @param filePath Path to the worker-file. * @param opts Options for the pool. */ public constructor ( public readonly numberOfWorkers: number, public readonly filePath: string, public readonly opts: PoolOptions<Worker> ) { if (!this.isMain()) { throw new Error('Cannot start a pool from a worker!') } this.checkNumberOfWorkers(this.numberOfWorkers) this.checkFilePath(this.filePath) this.checkPoolOptions(this.opts) this.setupHook() for (let i = 1; i <= this.numberOfWorkers; i++) { this.createAndSetupWorker() } if (this.opts.enableEvents) { this.emitter = new PoolEmitter() } this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext( this, () => { const workerCreated = this.createAndSetupWorker() this.registerWorkerMessageListener(workerCreated, async message => { const tasksInProgress = this.tasks.get(workerCreated) if ( isKillBehavior(KillBehaviors.HARD, message.kill) || tasksInProgress === 0 ) { // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime) await this.destroyWorker(workerCreated) } }) return workerCreated }, this.opts.workerChoiceStrategy ) } private checkFilePath (filePath: string): void { if (!filePath) { throw new Error('Please specify a file with a worker implementation') } } private checkNumberOfWorkers (numberOfWorkers: number): void { if (numberOfWorkers == null) { throw new Error( 'Cannot instantiate a pool without specifying the number of workers' ) } else if (!Number.isSafeInteger(numberOfWorkers)) { throw new Error( 'Cannot instantiate a pool with a non integer number of workers' ) } else if (numberOfWorkers < 0) { throw new Error( 'Cannot instantiate a pool with a negative number of workers' ) } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) { throw new Error('Cannot instantiate a fixed pool with no worker') } } private checkPoolOptions (opts: PoolOptions<Worker>): void { this.opts.workerChoiceStrategy = opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN this.opts.enableEvents = opts.enableEvents ?? true } /** @inheritdoc */ public abstract get type (): PoolType /** @inheritdoc */ public get numberOfRunningTasks (): number { return this.promiseMap.size } /** @inheritdoc */ public setWorkerChoiceStrategy ( workerChoiceStrategy: WorkerChoiceStrategy ): void { this.opts.workerChoiceStrategy = workerChoiceStrategy this.workerChoiceStrategyContext.setWorkerChoiceStrategy( workerChoiceStrategy ) } /** @inheritdoc */ public abstract get busy (): boolean protected internalGetBusyStatus (): boolean { return ( this.numberOfRunningTasks >= this.numberOfWorkers && this.findFreeTasksMapEntry() === false ) } /** @inheritdoc */ public findFreeTasksMapEntry (): [Worker, number] | false { for (const [worker, numberOfTasks] of this.tasks) { if (numberOfTasks === 0) { // A worker is free, return the matching tasks map entry return [worker, numberOfTasks] } } return false } /** @inheritdoc */ public execute (data: Data): Promise<Response> { // Configure worker to handle message with the specified task const worker = this.chooseWorker() const messageId = ++this.nextMessageId const res = this.internalExecute(worker, messageId) this.checkAndEmitBusy() this.sendToWorker(worker, { data: data || ({} as Data), id: messageId }) return res } /** @inheritdoc */ public async destroy (): Promise<void> { await Promise.all(this.workers.map(worker => this.destroyWorker(worker))) } /** * Shut down given worker. * * @param worker A worker within `workers`. */ protected abstract destroyWorker (worker: Worker): void | Promise<void> /** * Setup hook that can be overridden by a Poolifier pool implementation * to run code before workers are created in the abstract constructor. */ protected setupHook (): void { // Can be overridden } /** * Should return whether the worker is the main worker or not. */ protected abstract isMain (): boolean /** * Increase the number of tasks that the given worker has applied. * * @param worker Worker whose tasks are increased. */ protected increaseWorkersTask (worker: Worker): void { this.stepWorkerNumberOfTasks(worker, 1) } /** * Decrease the number of tasks that the given worker has applied. * * @param worker Worker whose tasks are decreased. */ protected decreaseWorkersTasks (worker: Worker): void { this.stepWorkerNumberOfTasks(worker, -1) } /** * Step the number of tasks that the given worker has applied. * * @param worker Worker whose tasks are set. * @param step Worker number of tasks step. */ private stepWorkerNumberOfTasks (worker: Worker, step: number): void { const numberOfTasksInProgress = this.tasks.get(worker) if (numberOfTasksInProgress !== undefined) { this.tasks.set(worker, numberOfTasksInProgress + step) } else { throw Error('Worker could not be found in tasks map') } } /** * Removes the given worker from the pool. * * @param worker Worker that will be removed. */ protected removeWorker (worker: Worker): void { // Clean worker from data structure const workerIndex = this.workers.indexOf(worker) this.workers.splice(workerIndex, 1) this.tasks.delete(worker) } /** * Choose a worker for the next task. * * The default implementation uses a round robin algorithm to distribute the load. * * @returns Worker. */ protected chooseWorker (): Worker { return this.workerChoiceStrategyContext.execute() } /** * Send a message to the given worker. * * @param worker The worker which should receive the message. * @param message The message. */ protected abstract sendToWorker ( worker: Worker, message: MessageValue<Data> ): void /** * Register a listener callback on a given worker. * * @param worker A worker. * @param listener A message listener callback. */ protected abstract registerWorkerMessageListener< Message extends Data | Response > (worker: Worker, listener: (message: MessageValue<Message>) => void): void protected internalExecute ( worker: Worker, messageId: number ): Promise<Response> { this.increaseWorkersTask(worker) return new Promise<Response>((resolve, reject) => { this.promiseMap.set(messageId, { resolve, reject, worker }) }) } /** * Returns a newly created worker. */ protected abstract createWorker (): Worker /** * Function that can be hooked up when a worker has been newly created and moved to the workers registry. * * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default. * * @param worker The newly created worker. */ protected abstract afterWorkerSetup (worker: Worker): void /** * Creates a new worker for this pool and sets it up completely. * * @returns New, completely set up worker. */ protected createAndSetupWorker (): Worker { const worker: Worker = this.createWorker() worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION) worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION) worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION) worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION) worker.once('exit', () => this.removeWorker(worker)) this.workers.push(worker) // Init tasks map this.tasks.set(worker, 0) this.afterWorkerSetup(worker) return worker } /** * This function is the listener registered for each worker. * * @returns The listener function to execute when a message is sent from a worker. */ protected workerListener (): (message: MessageValue<Response>) => void { return message => { if (message.id) { const value = this.promiseMap.get(message.id) if (value) { this.decreaseWorkersTasks(value.worker) if (message.error) value.reject(message.error) else value.resolve(message.data as Response) this.promiseMap.delete(message.id) } } } } private checkAndEmitBusy (): void { if (this.opts.enableEvents && this.busy) { this.emitter?.emit('busy') } } }
the_stack
import React, {useEffect, useState, useRef, useReducer} from 'react'; import ReactDOM from 'react-dom'; import * as monaco from 'monaco-editor'; import puppeteerTypes from './typedefs/puppeteer.d.ts'; import {EditorTabs} from './components/EditorTabs'; import {IDEContext} from './components/IDEContext'; import {ActionBar} from './components/ActionBar'; import './idePanel.scss'; import {Editor} from './components/Editor'; import {ExecuteScriptCommand} from '../sandbox/sandbox'; import {Message} from '../../background'; import { ExtensionState, extensionStateReducer, Script, } from './extensionReducer'; import {getElementSelector} from './utils/getElementSelector'; export const initialScript = ` await page.goto('https://wikipedia.org') const englishButton = await page.waitForSelector('#js-link-box-en > strong') await englishButton.click() const searchBox = await page.waitForSelector('#searchInput') await searchBox.type('telephone') await page.keyboard.press('Enter') await page.close() `; function App() { const theme = chrome.devtools?.panels?.themeName === 'default' ? 'light' : 'dark'; const initialExtensionState: ExtensionState = { tabs: [], scripts: [], activeTab: 0, theme: theme, }; const [extensionState, dispatch] = useReducer( extensionStateReducer, initialExtensionState ); const [port, setPort] = useState<chrome.runtime.Port | null>(null); const [isLoading, setIsLoading] = useState(true); const [isExecuting, setIsExecuting] = useState(false); const sandboxRef = useRef<HTMLIFrameElement>(null); /** * Read and delete script from older version if available * @returns script from older version of extension */ const portOldScript = async () => { const scriptStore = await chrome.storage.local.get('script'); if (scriptStore.script) { await chrome.storage.local.remove('script'); return { id: Date.now(), name: 'anonymous', value: scriptStore.script, }; } else { return null; } }; const getScriptById = (scriptId: number) => { return extensionState.scripts.find(script => script.id === scriptId); }; /** * Creates react state from state serialized in `chrome.storage` * If not available, creates initial state and ports script from older version if available */ const getExtensionState = async () => { const extensionStore = await chrome.storage.local.get('state'); if (extensionStore.state) { const state: ExtensionState = extensionStore.state; state.tabs = state.tabs.map(tab => { const script = state.scripts.find(script => script.id === tab.scriptId); return { scriptId: script?.id || 0, model: monaco.editor.createModel(script?.value || '', 'javascript'), }; }); dispatch({ type: 'initialize', state: state, }); } else { const sampleScript: Script = { id: Date.now(), name: 'sample', value: initialScript, }; const state: ExtensionState = { scripts: [sampleScript], tabs: [ { scriptId: sampleScript.id, model: monaco.editor.createModel(sampleScript.value, 'javascript'), }, ], activeTab: 0, theme: initialExtensionState.theme, }; const oldScript = await portOldScript(); if (oldScript) { state.scripts.push(oldScript); state.tabs.push({ scriptId: oldScript.id, model: monaco.editor.createModel(oldScript.value, 'javascript'), }); state.activeTab = 1; } dispatch({ type: 'initialize', state: state, }); } }; /** * Get selected element's selector * @returns selector for current selected element or null */ const elementSelectorSuggestor = (): Promise<string> => { return new Promise(resolve => { // replacing `exports.` with '' as tsc adds it while compiling chrome.devtools.inspectedWindow.eval( ` var getElementSelector = ${getElementSelector .toString() .replace(/(\w+\.)(?=getElementSelector)/, '')} $0 ? getElementSelector($0) : '' `, (result, error) => { error?.value ? resolve('') : resolve(result as string); } ); }); }; /** * Registers suggestions provider for editor */ const registerSuggestionsProvider = () => { monaco.languages.registerCompletionItemProvider('javascript', { provideCompletionItems: async function (model, position) { const word = model.getWordUntilPosition(position); const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn, }; return { suggestions: [ { label: '"$0"', kind: monaco.languages.CompletionItemKind.Value, documentation: 'Get selector of currently selected element', insertText: `"${await elementSelectorSuggestor()}"`, range: range, }, ], }; }, }); }; /** * Registers type definitions for editor */ const registerTypeDefs = () => { monaco.languages.typescript.javascriptDefaults.addExtraLib(puppeteerTypes); }; /** * Custom actions provider for editor * @returns Action dispatcher */ const editorActionProvider = () => { return []; }; /** * Save state changes to `chrome.storage` */ const saveExtensionState = async () => { await chrome.storage.local.set({ state: { ...extensionState, tabs: extensionState.tabs.map(tab => { return { scriptId: tab.scriptId, }; }), }, }); }; /** Script execution triggerer */ const execute = () => { port?.postMessage({ type: 'startExecution', tabId: chrome.devtools.inspectedWindow.tabId, }); }; /** Script execution stop triggerer */ const stop = () => { port?.postMessage({ type: 'stopExecution', tabId: chrome.devtools.inspectedWindow.tabId, }); }; /** Evals puppeteer script in sandbox frame */ const evalInSandbox = (script: string) => { const sandboxFrame = sandboxRef.current; if (sandboxFrame) { const executeCommand: ExecuteScriptCommand = { type: 'executeScript', script: script, }; sandboxFrame.contentWindow?.postMessage(executeCommand, '*'); } }; /** Connect to background service worker. */ const connectPort = () => { const port = chrome.runtime.connect({ name: `${chrome.devtools.inspectedWindow.tabId}`, }); setPort(port); port.onDisconnect.addListener(() => { setTimeout(() => connectPort(), 1 * 1000); }); }; useEffect(() => { connectPort(); getExtensionState(); registerTypeDefs(); registerSuggestionsProvider(); }, []); useEffect(() => { if (isLoading) setIsLoading(false); saveExtensionState(); }, [extensionState]); useEffect(() => { /** * Handles messages from background service worker and passes cdp responses/events * to sandbox frame * @param message - incoming message from background service worker */ const portMessageHandler = (message: Message) => { if (message.type === 'executionStarted') { const activeTab = extensionState.tabs[extensionState.activeTab]; const script = getScriptById(activeTab.scriptId); if (script) { evalInSandbox(script.value); setIsExecuting(true); } } else if (message.type === 'executionStopped') { setIsExecuting(false); sandboxRef.current?.contentWindow?.postMessage(message, '*'); } else if (message.type === 'cdpEvent') { // forward cdp response/event from service worker to sandbox frame sandboxRef.current?.contentWindow?.postMessage(message, '*'); } }; port?.onMessage.addListener(portMessageHandler); /** * Handles messages from sandbox frame and passes cdp commands * to background service worker * @param message incoming message from sandbox frame */ const windowMessageHandler = (message: MessageEvent<Message>) => { if (message.data.type === 'cdpCommand') { // forward cdp command coming from sandbox to service worker port?.postMessage(message.data); } else if (message.data.type === 'console') { const consoleCommand = message.data; chrome.devtools.inspectedWindow.eval( `console.${consoleCommand.level}(...${consoleCommand.args})` ); } }; window.addEventListener('message', windowMessageHandler); return () => { port?.onMessage.removeListener(portMessageHandler); window.removeEventListener('message', windowMessageHandler); }; }, [extensionState, port]); if (!isLoading) { const activeTab = extensionState.tabs[extensionState.activeTab]; return ( <IDEContext.Provider value={{ port: port, setPort: setPort, dispatch: dispatch, theme: extensionState.theme, }} > <ActionBar execute={execute} stop={stop} activeTab={activeTab} isExecuting={isExecuting} scripts={extensionState.scripts} ></ActionBar> <EditorTabs activeTab={extensionState.activeTab} getScriptById={getScriptById} tabs={extensionState.tabs} ></EditorTabs> {activeTab?.model ? ( <Editor onChange={value => dispatch({ type: 'editScript', value: value, }) } actions={editorActionProvider()} model={activeTab.model} /> ) : null} <iframe ref={sandboxRef} src="../sandbox/sandbox.html"></iframe> </IDEContext.Provider> ); } else { return null; } } ReactDOM.render(<App></App>, document.querySelector('#ide'));
the_stack
import { ThemeObject } from "./themeTypes"; const defaultTheme: Partial<ThemeObject> = { colorPrimary100: "#f2f6ff", colorPrimary200: "#d9e4ff", colorPrimary300: "#a6c1ff", colorPrimary400: "#598bff", colorPrimary500: "#3366ff", colorPrimary600: "#274bdb", colorPrimary700: "#1a34b8", colorPrimary800: "#102694", colorPrimary900: "#091c7a", colorPrimaryTransparent100: "rgba(51, 102, 255, 0.08)", colorPrimaryTransparent200: "rgba(51, 102, 255, 0.16)", colorPrimaryTransparent300: "rgba(51, 102, 255, 0.24)", colorPrimaryTransparent400: "rgba(51, 102, 255, 0.32)", colorPrimaryTransparent500: "rgba(51, 102, 255, 0.4)", colorPrimaryTransparent600: "rgba(51, 102, 255, 0.48)", colorSuccess100: "#f0fff5", colorSuccess200: "#ccfce3", colorSuccess300: "#8cfac7", colorSuccess400: "#2ce69b", colorSuccess500: "#00d68f", colorSuccess600: "#00b887", colorSuccess700: "#00997a", colorSuccess800: "#007d6c", colorSuccess900: "#004a45", colorSuccessTransparent100: "rgba(0, 214, 143, 0.08)", colorSuccessTransparent200: "rgba(0, 214, 143, 0.16)", colorSuccessTransparent300: "rgba(0, 214, 143, 0.24)", colorSuccessTransparent400: "rgba(0, 214, 143, 0.32)", colorSuccessTransparent500: "rgba(0, 214, 143, 0.4)", colorSuccessTransparent600: "rgba(0, 214, 143, 0.48)", colorInfo100: "#f2f8ff", colorInfo200: "#c7e2ff", colorInfo300: "#94cbff", colorInfo400: "#42aaff", colorInfo500: "#0095ff", colorInfo600: "#006fd6", colorInfo700: "#0057c2", colorInfo800: "#0041a8", colorInfo900: "#002885", colorInfoTransparent100: "rgba(0, 149, 255, 0.08)", colorInfoTransparent200: "rgba(0, 149, 255, 0.16)", colorInfoTransparent300: "rgba(0, 149, 255, 0.24)", colorInfoTransparent400: "rgba(0, 149, 255, 0.32)", colorInfoTransparent500: "rgba(0, 149, 255, 0.4)", colorInfoTransparent600: "rgba(0, 149, 255, 0.48)", colorWarning100: "#fffdf2", colorWarning200: "#fff1c2", colorWarning300: "#ffe59e", colorWarning400: "#ffc94d", colorWarning500: "#ffaa00", colorWarning600: "#db8b00", colorWarning700: "#b86e00", colorWarning800: "#945400", colorWarning900: "#703c00", colorWarningTransparent100: "rgba(255, 170, 0, 0.08)", colorWarningTransparent200: "rgba(255, 170, 0, 0.16)", colorWarningTransparent300: "rgba(255, 170, 0, 0.24)", colorWarningTransparent400: "rgba(255, 170, 0, 0.32)", colorWarningTransparent500: "rgba(255, 170, 0, 0.4)", colorWarningTransparent600: "rgba(255, 170, 0, 0.48)", colorDanger100: "#fff2f2", colorDanger200: "#ffd6d9", colorDanger300: "#ffa8b4", colorDanger400: "#ff708d", colorDanger500: "#ff3d71", colorDanger600: "#db2c66", colorDanger700: "#b81d5b", colorDanger800: "#94124e", colorDanger900: "#700940", colorDangerTransparent100: "rgba(255, 61, 113, 0.08)", colorDangerTransparent200: "rgba(255, 61, 113, 0.16)", colorDangerTransparent300: "rgba(255, 61, 113, 0.24)", colorDangerTransparent400: "rgba(255, 61, 113, 0.32)", colorDangerTransparent500: "rgba(255, 61, 113, 0.4)", colorDangerTransparent600: "rgba(255, 61, 113, 0.48)", /* Basic colors - for backgrounds and borders and texts */ colorBasic100: "#ffffff", colorBasic200: "#f7f9fc", colorBasic300: "#edf1f7", colorBasic400: "#e4e9f2", colorBasic500: "#c5cee0", colorBasic600: "#8f9bb3", colorBasic700: "#2e3a59", colorBasic800: "#222b45", colorBasic900: "#192038", colorBasic1000: "#151a30", colorBasic1100: "#101426", colorBasicTransparent100: "rgba(143, 155, 179, 0.08)", colorBasicTransparent200: "rgba(143, 155, 179, 0.16)", colorBasicTransparent300: "rgba(143, 155, 179, 0.24)", colorBasicTransparent400: "rgba(143, 155, 179, 0.32)", colorBasicTransparent500: "rgba(143, 155, 179, 0.4)", colorBasicTransparent600: "rgba(143, 155, 179, 0.48)", colorBasicControlTransparent100: "rgba(255, 255, 255, 0.08)", colorBasicControlTransparent200: "rgba(255, 255, 255, 0.16)", colorBasicControlTransparent300: "rgba(255, 255, 255, 0.24)", colorBasicControlTransparent400: "rgba(255, 255, 255, 0.32)", colorBasicControlTransparent500: "rgba(255, 255, 255, 0.4)", colorBasicControlTransparent600: "rgba(255, 255, 255, 0.48)", /* Status colors states - focus, hover, default, active, disabled */ colorBasicFocus: "colorBasic400", colorBasicHover: "colorBasic200", colorBasicDefault: "colorBasic300", colorBasicActive: "colorBasic400", colorBasicDisabled: "colorBasicTransparent300", colorBasicFocusBorder: "colorBasic500", colorBasicHoverBorder: "colorBasicHover", colorBasicDefaultBorder: "colorBasicDefault", colorBasicActiveBorder: "colorBasicActive", colorBasicDisabledBorder: "colorBasicDisabled", colorBasicTransparentFocus: "colorBasicTransparent300", colorBasicTransparentHover: "colorBasicTransparent200", colorBasicTransparentDefault: "colorBasicTransparent100", colorBasicTransparentActive: "colorBasicTransparent300", colorBasicTransparentDisabled: "colorBasicTransparent200", colorBasicTransparentFocusBorder: "colorBasic600", colorBasicTransparentHoverBorder: "colorBasic600", colorBasicTransparentDefaultBorder: "colorBasic600", colorBasicTransparentActiveBorder: "colorBasic600", colorBasicTransparentDisabledBorder: "colorBasicTransparent300", colorPrimaryFocus: "colorPrimary600", colorPrimaryHover: "colorPrimary400", colorPrimaryDefault: "colorPrimary500", colorPrimaryActive: "colorPrimary600", colorPrimaryDisabled: "colorBasicTransparent300", colorPrimaryFocusBorder: "colorPrimary700", colorPrimaryHoverBorder: "colorPrimaryHover", colorPrimaryDefaultBorder: "colorPrimaryDefault", colorPrimaryActiveBorder: "colorPrimaryActive", colorPrimaryDisabledBorder: "colorPrimaryDisabled", colorPrimaryTransparentFocus: "colorPrimaryTransparent300", colorPrimaryTransparentHover: "colorPrimaryTransparent200", colorPrimaryTransparentDefault: "colorPrimaryTransparent100", colorPrimaryTransparentActive: "colorPrimaryTransparent300", colorPrimaryTransparentDisabled: "colorBasicTransparent200", colorPrimaryTransparentFocusBorder: "colorPrimary500", colorPrimaryTransparentHoverBorder: "colorPrimary500", colorPrimaryTransparentDefaultBorder: "colorPrimary500", colorPrimaryTransparentActiveBorder: "colorPrimary500", colorPrimaryTransparentDisabledBorder: "colorBasicTransparent300", colorSuccessFocus: "colorSuccess600", colorSuccessHover: "colorSuccess400", colorSuccessDefault: "colorSuccess500", colorSuccessActive: "colorSuccess600", colorSuccessDisabled: "colorBasicTransparent300", colorSuccessFocusBorder: "colorSuccess700", colorSuccessHoverBorder: "colorSuccessHover", colorSuccessDefaultBorder: "colorSuccessDefault", colorSuccessActiveBorder: "colorSuccessActive", colorSuccessDisabledBorder: "colorSuccessDisabled", colorSuccessTransparentFocus: "colorSuccessTransparent300", colorSuccessTransparentFocusBorder: "colorSuccess500", colorSuccessTransparentHover: "colorSuccessTransparent200", colorSuccessTransparentHoverBorder: "colorSuccess500", colorSuccessTransparentDefault: "colorSuccessTransparent100", colorSuccessTransparentDefaultBorder: "colorSuccess500", colorSuccessTransparentActive: "colorSuccessTransparent300", colorSuccessTransparentActiveBorder: "colorSuccess500", colorSuccessTransparentDisabled: "colorBasicTransparent200", colorSuccessTransparentDisabledBorder: "colorBasicTransparent300", colorInfoFocus: "colorInfo600", colorInfoHover: "colorInfo400", colorInfoDefault: "colorInfo500", colorInfoActive: "colorInfo600", colorInfoDisabled: "colorBasicTransparent300", colorInfoFocusBorder: "colorInfo700", colorInfoHoverBorder: "colorInfoHover", colorInfoDefaultBorder: "colorInfoDefault", colorInfoActiveBorder: "colorInfoActive", colorInfoDisabledBorder: "colorInfoDisabled", colorInfoTransparentFocus: "colorInfoTransparent300", colorInfoTransparentHover: "colorInfoTransparent200", colorInfoTransparentDefault: "colorInfoTransparent100", colorInfoTransparentActive: "colorInfoTransparent300", colorInfoTransparentDisabled: "colorBasicTransparent200", colorInfoTransparentFocusBorder: "colorInfo500", colorInfoTransparentHoverBorder: "colorInfo500", colorInfoTransparentDefaultBorder: "colorInfo500", colorInfoTransparentActiveBorder: "colorInfo500", colorInfoTransparentDisabledBorder: "colorBasicTransparent300", colorWarningFocus: "colorWarning600", colorWarningHover: "colorWarning400", colorWarningDefault: "colorWarning500", colorWarningActive: "colorWarning600", colorWarningDisabled: "colorBasicTransparent300", colorWarningFocusBorder: "colorWarning700", colorWarningHoverBorder: "colorWarningHover", colorWarningDefaultBorder: "colorWarningDefault", colorWarningActiveBorder: "colorWarningActive", colorWarningDisabledBorder: "colorWarningDisabled", colorWarningTransparentFocus: "colorWarningTransparent300", colorWarningTransparentHover: "colorWarningTransparent200", colorWarningTransparentDefault: "colorWarningTransparent100", colorWarningTransparentActive: "colorWarningTransparent300", colorWarningTransparentDisabled: "colorBasicTransparent200", colorWarningTransparentFocusBorder: "colorWarning500", colorWarningTransparentHoverBorder: "colorWarning500", colorWarningTransparentDefaultBorder: "colorWarning500", colorWarningTransparentActiveBorder: "colorWarning500", colorWarningTransparentDisabledBorder: "colorBasicTransparent300", colorDangerFocus: "colorDanger600", colorDangerHover: "colorDanger400", colorDangerDefault: "colorDanger500", colorDangerActive: "colorDanger600", colorDangerDisabled: "colorBasicTransparent300", colorDangerFocusBorder: "colorDanger700", colorDangerHoverBorder: "colorDangerHover", colorDangerDefaultBorder: "colorDangerDefault", colorDangerActiveBorder: "colorDangerActive", colorDangerDisabledBorder: "colorDangerDisabled", colorDangerTransparentFocus: "colorDangerTransparent300", colorDangerTransparentHover: "colorDangerTransparent200", colorDangerTransparentDefault: "colorDangerTransparent100", colorDangerTransparentActive: "colorDangerTransparent300", colorDangerTransparentDisabled: "colorBasicTransparent200", colorDangerTransparentFocusBorder: "colorDanger500", colorDangerTransparentHoverBorder: "colorDanger500", colorDangerTransparentDefaultBorder: "colorDanger500", colorDangerTransparentActiveBorder: "colorDanger500", colorDangerTransparentDisabledBorder: "colorBasicTransparent300", colorControlFocus: "colorBasic300", colorControlHover: "colorBasic200", colorControlDefault: "colorBasic100", colorControlActive: "colorBasic300", colorControlDisabled: "colorBasicTransparent300", colorControlFocusBorder: "colorBasic500", colorControlHoverBorder: "colorControlHover", colorControlDefaultBorder: "colorControlDefault", colorControlActiveBorder: "colorControlActive", colorControlDisabledBorder: "colorControlDisabled", colorControlTransparentFocus: "colorBasicControlTransparent300", colorControlTransparentHover: "colorBasicControlTransparent200", colorControlTransparentDefault: "colorBasicControlTransparent100", colorControlTransparentActive: "colorBasicControlTransparent300", colorControlTransparentDisabled: "colorBasicTransparent200", colorControlTransparentFocusBorder: "colorBasic100", colorControlTransparentHoverBorder: "colorBasic100", colorControlTransparentDefaultBorder: "colorBasic100", colorControlTransparentActiveBorder: "colorBasic100", colorControlTransparentDisabledBorder: "colorBasicTransparent300", /* Backgrounds and borders - basic, alternative and primary */ backgroundBasicColor1: "colorBasic100", backgroundBasicColor2: "colorBasic200", backgroundBasicColor3: "colorBasic300", backgroundBasicColor4: "colorBasic400", borderBasicColor1: "colorBasic100", borderBasicColor2: "colorBasic200", borderBasicColor3: "colorBasic300", borderBasicColor4: "colorBasic400", borderBasicColor5: "colorBasic500", backgroundAlternativeColor1: "colorBasic800", backgroundAlternativeColor2: "colorBasic900", backgroundAlternativeColor3: "colorBasic1000", backgroundAlternativeColor4: "colorBasic1100", borderAlternativeColor1: "colorBasic800", borderAlternativeColor2: "colorBasic900", borderAlternativeColor3: "colorBasic1000", borderAlternativeColor4: "colorBasic1100", borderAlternativeColor5: "colorBasic1100", backgroundPrimaryColor1: "colorPrimary500", backgroundPrimaryColor2: "colorPrimary600", backgroundPrimaryColor3: "colorPrimary700", backgroundPrimaryColor4: "colorPrimary800", borderPrimaryColor1: "colorBasic500", borderPrimaryColor2: "colorBasic600", borderPrimaryColor3: "colorBasic700", borderPrimaryColor4: "colorBasic800", borderPrimaryColor5: "colorBasic900", /* Text colors - general and status */ textBasicColor: "colorBasic800", textAlternateColor: "colorBasic100", textControlColor: "colorBasic100", textDisabledColor: "colorBasicTransparent600", textHintColor: "colorBasic600", textPrimaryColor: "colorPrimaryDefault", textPrimaryFocusColor: "colorPrimaryFocus", textPrimaryHoverColor: "colorPrimaryHover", textPrimaryActiveColor: "colorPrimaryActive", textPrimaryDisabledColor: "colorPrimary400", textSuccessColor: "colorSuccessDefault", textSuccessFocusColor: "colorSuccessFocus", textSuccessHoverColor: "colorSuccessHover", textSuccessActiveColor: "colorSuccessActive", textSuccessDisabledColor: "colorSuccess400", textInfoColor: "colorInfoDefault", textInfoFocusColor: "colorInfoFocus", textInfoHoverColor: "colorInfoHover", textInfoActiveColor: "colorInfoActive", textInfoDisabledColor: "colorInfo400", textWarningColor: "colorWarningDefault", textWarningFocusColor: "colorWarningFocus", textWarningHoverColor: "colorWarningHover", textWarningActiveColor: "colorWarningActive", textWarningDisabledColor: "colorWarning400", textDangerColor: "colorDangerDefault", textDangerFocusColor: "colorDangerFocus", textDangerHoverColor: "colorDangerHover", textDangerActiveColor: "colorDangerActive", textDangerDisabledColor: "colorDanger400", /* Fonts and text styles - headings, subtitles, paragraphs, captions, button */ fontFamilyPrimary: "unquote('Open Sans, sans-serif')", fontFamilySecondary: "fontFamilyPrimary", textHeading1FontFamily: "fontFamilySecondary", textHeading1FontSize: "2.25rem", textHeading1FontWeight: 700, textHeading1LineHeight: "3rem", textHeading2FontFamily: "fontFamilySecondary", textHeading2FontSize: "2rem", textHeading2FontWeight: 700, textHeading2LineHeight: "2.5rem", textHeading3FontFamily: "fontFamilySecondary", textHeading3FontSize: "1.875rem", textHeading3FontWeight: 700, textHeading3LineHeight: "2.5rem", textHeading4FontFamily: "fontFamilySecondary", textHeading4FontSize: "1.625rem", textHeading4FontWeight: 700, textHeading4LineHeight: "2rem", textHeading5FontFamily: "fontFamilySecondary", textHeading5FontSize: "1.375rem", textHeading5FontWeight: 700, textHeading5LineHeight: "2rem", textHeading6FontFamily: "fontFamilySecondary", textHeading6FontSize: "1.125rem", textHeading6FontWeight: 700, textHeading6LineHeight: "1.5rem", textSubtitleFontFamily: "fontFamilyPrimary", textSubtitleFontSize: "0.9375rem", textSubtitleFontWeight: 600, textSubtitleLineHeight: "1.5rem", textSubtitle2FontFamily: "fontFamilyPrimary", textSubtitle2FontSize: "0.8125rem", textSubtitle2FontWeight: 600, textSubtitle2LineHeight: "1.5rem", textParagraphFontFamily: "fontFamilyPrimary", textParagraphFontSize: "0.9375rem", textParagraphFontWeight: 400, textParagraphLineHeight: "1.25rem", textParagraph2FontFamily: "fontFamilyPrimary", textParagraph2FontSize: "0.8125rem", textParagraph2FontWeight: 400, textParagraph2LineHeight: "1.125rem", textLabelFontFamily: "fontFamilyPrimary", textLabelFontSize: "0.75rem", textLabelFontWeight: 700, textLabelLineHeight: "1rem", textCaptionFontFamily: "fontFamilyPrimary", textCaptionFontSize: "0.75rem", textCaptionFontWeight: 400, textCaptionLineHeight: "1rem", textCaption2FontFamily: "fontFamilyPrimary", textCaption2FontSize: "0.75rem", textCaption2FontWeight: 600, textCaption2LineHeight: "1rem", textButtonFontFamily: "fontFamilyPrimary", textButtonFontWeight: 700, textButtonTinyFontSize: "0.625rem", textButtonTinyLineHeight: "0.75rem", textButtonSmallFontSize: "0.75rem", textButtonSmallLineHeight: "1rem", textButtonMediumFontSize: "0.875rem", textButtonMediumLineHeight: "1rem", textButtonLargeFontSize: "1rem", textButtonLargeLineHeight: "1.25rem", textButtonGiantFontSize: "1.125rem", textButtonGiantLineHeight: "1.5rem", /* Supporting variables - border radius, outline, shadow, divider */ borderRadius: "0.25rem", outlineWidth: "0.375rem", outlineColor: "colorBasicTransparent200", scrollbarColor: "backgroundBasicColor4", scrollbarBackgroundColor: "backgroundBasicColor2", scrollbarWidth: "0.3125rem", shadow: "0 0.5rem 1rem 0 rgba(44, 51, 73, 0.1)", dividerColor: "borderBasicColor3", dividerStyle: "solid", dividerWidth: "1px", }; export default defaultTheme;
the_stack
import { configure } from "mobx"; import { types } from "mobx-state-tree"; import { Field, Form, Group, SubForm, RepeatingForm, RepeatingFormAccessor, RepeatingFormIndexedAccessor, SubFormAccessor, converters, } from "../src"; // "always" leads to trouble during initialization. configure({ enforceActions: "observed" }); test("groups basic", () => { const M = types.model("M", { a: types.number, b: types.number, c: types.number, d: types.number, }); const form = new Form( M, { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ include: ["a", "b"] }), two: new Group({ include: ["c", "d"] }), } ); const o = M.create({ a: 1, b: 2, c: 3, d: 4 }); const state = form.state(o); const a = state.field("a"); const b = state.field("b"); const c = state.field("c"); const d = state.field("d"); const one = state.group("one"); const two = state.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeTruthy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); }); test("groups exclude", () => { const M = types.model("M", { a: types.number, b: types.number, c: types.number, d: types.number, }); const form = new Form( M, { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ exclude: ["a", "b"] }), two: new Group({ exclude: ["c", "d"] }), } ); const o = M.create({ a: 1, b: 2, c: 3, d: 4 }); const state = form.state(o); const a = state.field("a"); const b = state.field("b"); const c = state.field("c"); const d = state.field("d"); const one = state.group("one"); const two = state.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeFalsy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); }); test("groups sub form", () => { const N = types.model("N", { a: types.number, b: types.number, c: types.number, d: types.number, }); const M = types.model("M", { field: types.number, item: N, }); const form = new Form( M, { field: new Field(converters.number), item: new SubForm( { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ include: ["a", "b"] }), two: new Group({ include: ["c", "d"] }), } ), }, { whole: new Group({ include: ["item"] }) } ); const o = M.create({ field: 0, item: { a: 1, b: 2, c: 3, d: 4 } }); const state = form.state(o); const field = state.field("field"); const item = state.subForm("item"); const whole = state.group("whole"); const a = item.field("a"); const b = item.field("b"); const c = item.field("c"); const d = item.field("d"); const one = item.group("one"); const two = item.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeTruthy(); expect(whole.isValid).toBeFalsy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); expect(whole.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); expect(whole.isValid).toBeTruthy(); field.setRaw("wrong"); // whole is not affected as it only is affected by the sub form expect(whole.isValid).toBeTruthy(); }); test("groups sub form exclude", () => { const N = types.model("N", { a: types.number, b: types.number, c: types.number, d: types.number, }); const M = types.model("M", { field: types.number, item: N, }); const form = new Form( M, { field: new Field(converters.number), item: new SubForm( { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ exclude: ["a", "b"] }), two: new Group({ exclude: ["c", "d"] }), } ), }, { whole: new Group({ include: ["item"] }) } ); const o = M.create({ field: 0, item: { a: 1, b: 2, c: 3, d: 4 } }); const state = form.state(o); const field = state.field("field"); const item = state.subForm("item"); const whole = state.group("whole"); const a = item.field("a"); const b = item.field("b"); const c = item.field("c"); const d = item.field("d"); const one = item.group("one"); const two = item.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeFalsy(); expect(whole.isValid).toBeFalsy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); expect(whole.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); expect(whole.isValid).toBeTruthy(); field.setRaw("wrong"); // whole is not affected as it only is affected by the sub form expect(whole.isValid).toBeTruthy(); }); test("groups repeating form", () => { const N = types.model("N", { a: types.number, b: types.number, c: types.number, d: types.number, }); const M = types.model("M", { items: types.array(N), }); const form = new Form(M, { items: new RepeatingForm( { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ include: ["a", "b"] }), two: new Group({ include: ["c", "d"] }), } ), }); const o = M.create({ items: [{ a: 1, b: 2, c: 3, d: 4 }] }); const state = form.state(o); const item0 = state.repeatingForm("items").index(0); const a = item0.field("a"); const b = item0.field("b"); const c = item0.field("c"); const d = item0.field("d"); const one = item0.group("one"); const two = item0.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeTruthy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); }); test("groups repeating form exclude", () => { const N = types.model("N", { a: types.number, b: types.number, c: types.number, d: types.number, }); const M = types.model("M", { items: types.array(N), }); const form = new Form(M, { items: new RepeatingForm( { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ exclude: ["a", "b"] }), two: new Group({ exclude: ["c", "d"] }), } ), }); const o = M.create({ items: [{ a: 1, b: 2, c: 3, d: 4 }] }); const state = form.state(o); const item0 = state.repeatingForm("items").index(0); const a = item0.field("a"); const b = item0.field("b"); const c = item0.field("c"); const d = item0.field("d"); const one = item0.group("one"); const two = item0.group("two"); a.setRaw("wrong"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeFalsy(); c.setRaw("wrong too"); expect(one.isValid).toBeFalsy(); expect(two.isValid).toBeFalsy(); a.setRaw("10"); c.setRaw("30"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); }); test("groups with warnings", () => { const M = types.model("M", { a: types.number, b: types.number, c: types.number, d: types.number, }); const form = new Form( M, { a: new Field(converters.number), b: new Field(converters.number), c: new Field(converters.number), d: new Field(converters.number), }, { one: new Group({ include: ["a", "b"] }), two: new Group({ include: ["c", "d"] }), } ); const o = M.create({ a: 1, b: 2, c: 3, d: 4 }); const state = form.state(o, { getWarning: (accessor: any) => accessor.path === "/a" ? "Please reconsider" : undefined, }); const a = state.field("a"); const b = state.field("b"); const c = state.field("c"); const d = state.field("d"); const one = state.group("one"); const two = state.group("two"); expect(one.isValid).toBeTruthy(); expect(two.isValid).toBeTruthy(); expect(a.isWarningFree).toBeFalsy(); expect(b.isWarningFree).toBeTruthy(); expect(one.isWarningFree).toBeFalsy(); expect(two.isWarningFree).toBeTruthy(); expect(state.isWarningFree).toBeFalsy(); }); test("groups with warnings in subform", () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: types.string, sub: N, }); const form = new Form( M, { foo: new Field(converters.string), sub: new SubForm({ bar: new Field(converters.string), }), }, { one: new Group({ include: ["sub"] }), } ); const o = M.create({ foo: "FOO", sub: { bar: "BAR" } }); const state = form.state(o, { getWarning: (accessor: any) => accessor.path === "/sub" ? "SubWarning" : undefined, }); const subForm = state.subForm("sub"); const group = state.group("one"); expect(subForm.isWarningFree).toBeFalsy(); expect(subForm.warning).toEqual("SubWarning"); expect(state.isWarningFree).toBeFalsy(); expect(group.isWarningFree).toBeFalsy(); }); test("groups with warnings in repeatingform", () => { const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: types.array(N), }); const form = new Form( M, { foo: new RepeatingForm({ bar: new Field(converters.string), }), }, { one: new Group({ include: ["foo"] }), } ); const o = M.create({ foo: [{ bar: "correct" }, { bar: "incorrect" }] }); const state = form.state(o, { getWarning: (accessor: any) => accessor.path === "/foo/1/bar" ? "Warning" : undefined, }); const repeatingForm = state.repeatingForm("foo"); const repeatingFormEntry1 = repeatingForm.accessors[0]; const repeatingFormEntry2 = repeatingForm.accessors[1]; const group = state.group("one"); expect(repeatingForm.isWarningFree).toBeFalsy(); expect(repeatingFormEntry1.isWarningFree).toBeTruthy(); expect(repeatingFormEntry2.isWarningFree).toBeFalsy(); expect(group.isWarningFree).toBeFalsy(); }); test("groups with repeatingform and subform error on top-level", async () => { const L = types.model("L", { baz: types.string, }); const N = types.model("N", { bar: types.string, }); const M = types.model("M", { foo: types.array(N), sub: L, }); const form = new Form( M, { foo: new RepeatingForm({ bar: new Field(converters.string), }), sub: new SubForm({ baz: new Field(converters.string), }), }, { one: new Group({ include: ["foo"] }), two: new Group({ include: ["sub"] }), } ); const o = M.create({ foo: [], sub: { baz: "BAZ" } }); const state = form.state(o, { getError: (accessor: any) => { if (accessor instanceof RepeatingFormAccessor) { return "Cannot be empty"; } if (accessor instanceof SubFormAccessor) { return "Is wrong for some reason"; } return undefined; }, }); const repeatingForm = state.repeatingForm("foo"); const subForm = state.subForm("sub"); const group = state.group("one"); const groupTwo = state.group("two"); expect(repeatingForm.isValid).toBeFalsy(); expect(subForm.isValid).toBeFalsy(); expect(group.isValid).toBeFalsy(); expect(groupTwo.isValid).toBeFalsy(); const p = M.create({ foo: [{ bar: "BAR" }], sub: { baz: "BAZ" } }); const stateWithWarning = form.state(p, { getError: (accessor: any) => { if (accessor instanceof RepeatingFormIndexedAccessor) { return "Cannot be empty"; } return undefined; }, }); const repeatingFormWithWarning = stateWithWarning.repeatingForm("foo"); const indexedRepeatingForm = repeatingFormWithWarning.index(0); const groupWithWarning = stateWithWarning.group("one"); expect(indexedRepeatingForm.isValid).toBeFalsy(); expect(groupWithWarning.isValid).toBeFalsy(); });
the_stack
import { createTestkit } from '@envelop/testing'; import { makeExecutableSchema } from '@graphql-tools/schema'; import Redis from 'ioredis'; import { createRedisCache, defaultBuildRedisEntityId, defaultBuildRedisOperationResultCacheKey } from '../src'; import { useResponseCache } from '@envelop/response-cache'; jest.mock('ioredis', () => require('ioredis-mock/jest')); describe('useResponseCache with Redis cache', () => { const redis = new Redis(); const cache = createRedisCache({ redis }); beforeEach(async () => { jest.useRealTimers(); await redis.flushall(); }); test('should create a default entity id with a number id', () => { const entityId = defaultBuildRedisEntityId('User', 1); expect(entityId).toEqual('User:1'); }); test('should create a default entity id with a string id', () => { const entityId = defaultBuildRedisEntityId('User', 'aaa-bbb-ccc-111-222'); expect(entityId).toEqual('User:aaa-bbb-ccc-111-222'); }); test('should create a default key used to cache associated response operations', () => { const entityId = defaultBuildRedisOperationResultCacheKey('abcde123456XYZ='); expect(entityId).toEqual('operations:abcde123456XYZ='); }); test('should reuse cache', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit([useResponseCache({ cache })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; await testInstance.execute(query); await testInstance.execute(query); expect(spy).toHaveBeenCalledTimes(1); }); test('should purge cache on mutation', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, Mutation: { updateUser(_, { id }) { return { id, }; }, }, }, }); const testInstance = createTestkit([useResponseCache({ cache })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; await testInstance.execute(query); await testInstance.execute(query); expect(spy).toHaveBeenCalledTimes(1); await testInstance.execute( /* GraphQL */ ` mutation test($id: ID!) { updateUser(id: $id) { id } } `, { id: 1, } ); await testInstance.execute(query); expect(spy).toHaveBeenCalledTimes(2); }); test('should purge cache on demand (typename+id)', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, Mutation: { updateUser(_, { id }) { return { id, }; }, }, }, }); const testInstance = createTestkit([useResponseCache({ cache })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache await testInstance.execute(query); // get from cache await testInstance.execute(query); // so queried just once expect(spy).toHaveBeenCalledTimes(1); // we have our two Users expect(await redis.exists('User:1')).toBeTruthy(); expect(await redis.exists('User:2')).toBeTruthy(); // but not this one expect(await redis.exists('User:3')).toBeFalsy(); // we have our two Comments expect(await redis.exists('Comment:1')).toBeTruthy(); expect(await redis.exists('Comment:2')).toBeTruthy(); // but not this one expect(await redis.exists('Comment:3')).toBeFalsy(); const commentResultCacheKeys = await redis.smembers('Comment'); // Comments are found in 1 ResultCacheKey expect(commentResultCacheKeys).toHaveLength(1); const comment1ResultCacheKeys = await redis.smembers('Comment:1'); // Comment:1 is found in 1 ResultCacheKey expect(comment1ResultCacheKeys).toHaveLength(1); const comment2ResultCacheKeys = await redis.smembers('Comment:2'); // Comment:2 is found in 1 ResultCacheKey expect(comment2ResultCacheKeys).toHaveLength(1); // then when we invalidate Comment:2 await cache.invalidate([{ typename: 'Comment', id: 2 }]); // and get the all Comment(s) key const commentResultCacheKeysAfterInvalidation = await redis.smembers('Comment'); // and the Comment:1 key const comment1ResultCacheKeysAfterInvalidation = await redis.smembers('Comment:1'); // Comment:1 is found in 1 ResultCacheKey ... expect(comment1ResultCacheKeysAfterInvalidation).toHaveLength(1); // ... and Comment also is found in 1 key (the same result key) expect(commentResultCacheKeysAfterInvalidation).toHaveLength(1); expect(await redis.exists('Comment:1')).toBeTruthy(); // but Comment:2 is no longer there since if was been invalidated expect(await redis.exists('Comment:2')).toBeFalsy(); // query and cache since ws invalidated await testInstance.execute(query); // from cache await testInstance.execute(query); // from cache await testInstance.execute(query); // but since we've queried once before when we started above, we've now actually queried twice expect(spy).toHaveBeenCalledTimes(2); }); test('should purge cache on demand (typename)', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, Mutation: { updateUser(_, { id }) { return { id, }; }, }, }, }); const testInstance = createTestkit([useResponseCache({ cache })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache await testInstance.execute(query); // from cache await testInstance.execute(query); // queried once expect(spy).toHaveBeenCalledTimes(1); expect(await redis.exists('User:1')).toBeTruthy(); expect(await redis.exists('User:2')).toBeTruthy(); expect(await redis.exists('User:3')).toBeFalsy(); expect(await redis.exists('Comment:1')).toBeTruthy(); expect(await redis.exists('Comment:2')).toBeTruthy(); expect(await redis.exists('User:3')).toBeFalsy(); await cache.invalidate([{ typename: 'Comment' }]); expect(await redis.exists('Comment')).toBeFalsy(); expect(await redis.exists('Comment:1')).toBeFalsy(); expect(await redis.exists('Comment:2')).toBeFalsy(); expect(await redis.smembers('Comment')).toHaveLength(0); // we've invalidated so, now query and cache await testInstance.execute(query); // so have queried twice expect(spy).toHaveBeenCalledTimes(2); // from cache await testInstance.execute(query); // from cache await testInstance.execute(query); // from cache await testInstance.execute(query); // still just queried twice expect(spy).toHaveBeenCalledTimes(2); }); test('should indicate if the cache was hit or missed', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, Mutation: { updateUser(_, { id }) { return { id, }; }, }, }, }); const testInstance = createTestkit([useResponseCache({ cache, includeExtensionMetadata: true })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache const queryResult = await testInstance.execute(query); let cacheHitMaybe = queryResult['extensions']['responseCache']['hit']; expect(cacheHitMaybe).toBeFalsy(); // get from cache const cachedResult = await testInstance.execute(query); cacheHitMaybe = cachedResult['extensions']['responseCache']['hit']; expect(cacheHitMaybe).toBeTruthy(); const mutationResult = await testInstance.execute( /* GraphQL */ ` mutation test($id: ID!) { updateUser(id: $id) { id } } `, { id: 1, } ); cacheHitMaybe = mutationResult['extensions']['responseCache']['hit']; expect(cacheHitMaybe).toBeFalsy(); }); test('should purge cache on mutation and include invalidated entities', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type Mutation { updateUser(id: ID!): User! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, Mutation: { updateUser(_, { id }) { return { id, }; }, }, }, }); const testInstance = createTestkit([useResponseCache({ cache, includeExtensionMetadata: true })], schema); const result = await testInstance.execute( /* GraphQL */ ` mutation test($id: ID!) { updateUser(id: $id) { id } } `, { id: 1, } ); const responseCache = result['extensions']['responseCache']; const invalidatedEntities = responseCache['invalidatedEntities']; expect(invalidatedEntities).toHaveLength(1); const invalidatedUser = invalidatedEntities[0]; expect(invalidatedUser).toEqual({ typename: 'User', id: '1', }); }); test('should consider variables when saving response', async () => { const spy = jest.fn((_, { limit }: { limit: number }) => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ].slice(0, limit) ); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users(limit: Int!): [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit([useResponseCache({ cache })], schema); const query = /* GraphQL */ ` query test($limit: Int!) { users(limit: $limit) { id name comments { id text } } } `; // query and cache 2 users await testInstance.execute(query, { limit: 2 }); // fetch 2 users from cache await testInstance.execute(query, { limit: 2 }); // so just one query expect(spy).toHaveBeenCalledTimes(1); // we should have one response with operations expect(await redis.keys('operations:*')).toHaveLength(1); // query just one user await testInstance.execute(query, { limit: 1 }); // since 2 users are in cache, we query again for the 1 as a response expect(spy).toHaveBeenCalledTimes(2); }); test('should purge response after it expired', async () => { jest.useFakeTimers(); const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit([useResponseCache({ cache, ttl: 100 })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache await testInstance.execute(query); // from cache await testInstance.execute(query); // so queried just once expect(spy).toHaveBeenCalledTimes(1); // let's travel in time beyond the ttl of 100 jest.advanceTimersByTime(150); // since the cache has expired, now when we query await testInstance.execute(query); // we query again so now twice expect(spy).toHaveBeenCalledTimes(2); }); test('should cache responses based on session', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit( [ useResponseCache({ cache, session(ctx: { sessionId: number }) { return ctx.sessionId + ''; }, }), ], schema ); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; await testInstance.execute( query, {}, { sessionId: 1, } ); await testInstance.execute( query, {}, { sessionId: 1, } ); expect(spy).toHaveBeenCalledTimes(1); // we should have one response for that sessionId of 1 expect(await redis.keys('operations:*')).toHaveLength(1); await testInstance.execute( query, {}, { sessionId: 2, } ); expect(spy).toHaveBeenCalledTimes(2); // we should have one response for both sessions expect(await redis.keys('operations:*')).toHaveLength(2); }); test('should skip cache of ignored types', async () => { const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit([useResponseCache({ cache, ignoredTypes: ['Comment'] })], schema); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query but don't cache await testInstance.execute(query); // none of the queries entities are cached because contains Comment expect(await redis.exists('User')).toBeFalsy(); expect(await redis.exists('User:1')).toBeFalsy(); expect(await redis.exists('Comment')).toBeFalsy(); expect(await redis.exists('Comment:2')).toBeFalsy(); // since not cached await testInstance.execute(query); // still none of the queries entities are cached because contains Comment expect(await redis.exists('User')).toBeFalsy(); expect(await redis.exists('User:1')).toBeFalsy(); expect(await redis.exists('Comment')).toBeFalsy(); expect(await redis.exists('Comment:2')).toBeFalsy(); // we've queried twice expect(spy).toHaveBeenCalledTimes(2); }); test('custom ttl per type', async () => { jest.useFakeTimers(); const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit( [ useResponseCache({ cache, ttl: 500, ttlPerType: { User: 200, }, }), ], schema ); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache await testInstance.execute(query); // from cache await testInstance.execute(query); expect(spy).toHaveBeenCalledTimes(1); // wait so User expires jest.advanceTimersByTime(201); await testInstance.execute(query); // now we've queried twice expect(spy).toHaveBeenCalledTimes(2); }); test('custom ttl per schema coordinate', async () => { jest.useFakeTimers(); const spy = jest.fn(() => [ { id: 1, name: 'User 1', comments: [ { id: 1, text: 'Comment 1 of User 1', }, ], }, { id: 2, name: 'User 2', comments: [ { id: 2, text: 'Comment 2 of User 2', }, ], }, ]); const schema = makeExecutableSchema({ typeDefs: /* GraphQL */ ` type Query { users: [User!]! } type User { id: ID! name: String! comments: [Comment!]! recentComment: Comment } type Comment { id: ID! text: String! } `, resolvers: { Query: { users: spy, }, }, }); const testInstance = createTestkit( [ useResponseCache({ cache, ttl: 500, ttlPerSchemaCoordinate: { 'Query.users': 200, }, }), ], schema ); const query = /* GraphQL */ ` query test { users { id name comments { id text } } } `; // query and cache await testInstance.execute(query); // from cache await testInstance.execute(query); expect(spy).toHaveBeenCalledTimes(1); // wait so User expires jest.advanceTimersByTime(201); await testInstance.execute(query); // now we've queried twice expect(spy).toHaveBeenCalledTimes(2); }); });
the_stack
import DatabaseIO from "./DatabaseIO.js"; import * as Utils from "../utils.js"; import { getDisplayNoteTitle, normalizeNoteTitle, removeDefaultTextParagraphs, removeEmptyLinkBlocks, noteWithSameTitleExists, findNote, getNewNoteId, updateNotePosition, getLinkedNotes, removeLinksOfNote, incorporateUserChangesIntoNote, createNoteToTransmit, getSortFunction, getNumberOfLinkedNotes, createNoteListItems, getNumberOfComponents, getNumberOfUnlinkedNotes, getNotesWithDuplicateUrls, getNotesThatContainTokens, getNotesByTitle, getNotesWithUrl, getNotesWithFile, getNotesWithTitleContainingTokens, getNotesWithBlocksOfTypes, getNotesWithDuplicateTitles, } from "./noteUtils.js"; import Graph from "./interfaces/Graph.js"; import NoteListItem from "./interfaces/NoteListItem.js"; import GraphVisualization from "./interfaces/GraphVisualization.js"; import { GraphId } from "./interfaces/GraphId.js"; import { NoteId } from "./interfaces/NoteId.js"; import NoteToTransmit from "./interfaces/NoteToTransmit.js"; import GraphNode from "./interfaces/GraphVisualizationNode.js"; import SavedNote from "./interfaces/SavedNote.js"; import NoteFromUser from "./interfaces/NoteFromUser.js"; import GraphStats from "./interfaces/GraphStats.js"; import GraphVisualizationFromUser from "./interfaces/GraphVisualizationFromUser.js"; import GraphNodePositionUpdate from "./interfaces/NodePositionUpdate.js"; import { FileId } from "./interfaces/FileId.js"; import UrlMetadataResponse from "./interfaces/UrlMetadataResponse.js"; import ImportLinkAsNoteFailure from "./interfaces/ImportLinkAsNoteFailure.js"; import * as config from "./config.js"; import { Readable } from "stream"; import NoteListPage from "./interfaces/NoteListPage.js"; import { NoteListSortMode } from "./interfaces/NoteListSortMode.js"; import ReadableWithType from "./interfaces/ReadableWithMimeType.js"; import GraphObject from "./interfaces/Graph.js"; import { NoteContentBlockType } from "./interfaces/NoteContentBlock.js"; import { ErrorMessage } from "./interfaces/ErrorMessage.js"; import DatabaseQuery from "./interfaces/DatabaseQuery.js"; let io; let randomUUID; /* this is the fallback getUrlMetadata function that is used if the initializer does not provide a better one */ let getUrlMetadata = (url) => { return Promise.resolve({ "url": url, "title": url, "description": "", "image": "", }); }; /** EXPORTS **/ const init = async ( storageProvider, _getUrlMetadata, _randomUUID, ):Promise<void> => { if (typeof _getUrlMetadata === "function") { getUrlMetadata = _getUrlMetadata; } randomUUID = _randomUUID; io = new DatabaseIO({storageProvider}); }; const get = async ( noteId: NoteId, graphId: GraphId, ):Promise<NoteToTransmit> => { const graph = await io.getGraph(graphId); const noteFromDB:SavedNote | null = findNote(graph, noteId); if (!noteFromDB) { throw new Error(ErrorMessage.NOTE_NOT_FOUND); } const noteToTransmit:NoteToTransmit = createNoteToTransmit(noteFromDB, graph); return noteToTransmit; }; const getNotesList = async ( graphId: GraphId, query: DatabaseQuery, ): Promise<NoteListPage> => { const searchString = query.searchString || ""; const caseSensitive = query.caseSensitive || false; const page = query.page ? Math.max(query.page, 1) : 1; const sortMode = query.sortMode || NoteListSortMode.CREATION_DATE_DESCENDING; const limit = query.limit || 0; const graph: Graph = await io.getGraph(graphId); let matchingNotes; // search for note pairs containing identical urls if (searchString.includes("duplicates:")){ const startOfDuplicateType = searchString.indexOf("duplicates:") + "duplicates:".length; const duplicateType = searchString.substring(startOfDuplicateType); if (duplicateType === "url") { matchingNotes = getNotesWithDuplicateUrls(graph.notes); } else if (duplicateType === "title"){ matchingNotes = getNotesWithDuplicateTitles(graph.notes); } else { matchingNotes = []; } // search for exact title } else if (searchString.includes("exact:")) { const startOfExactQuery = searchString.indexOf("exact:") + "exact:".length; const exactQuery = searchString.substring(startOfExactQuery); matchingNotes = getNotesByTitle(graph.notes, exactQuery, false); // search for notes with specific urls } else if (searchString.includes("has-url:")) { const startOfExactQuery = searchString.indexOf("has-url:") + "has-url:".length; const url = searchString.substring(startOfExactQuery); matchingNotes = getNotesWithUrl(graph.notes, url); // search for notes with specific fileIds } else if (searchString.includes("has-file:")) { const startOfExactQuery = searchString.indexOf("has-file:") + "has-file:".length; const fileId = searchString.substring(startOfExactQuery); matchingNotes = getNotesWithFile(graph.notes, fileId); // search for notes with specific block types } else if (searchString.includes("has:")) { const startOfExactQuery = searchString.indexOf("has:") + "has:".length; const typesString = searchString.substring(startOfExactQuery); /* has:audio+video - show all notes that contain audio as well as video has:audio|video - show all notes that contain audio or video */ if (typesString.includes("+")) { const types = typesString.split("+") as NoteContentBlockType[]; matchingNotes = getNotesWithBlocksOfTypes(graph.notes, types, true); } else { const types = typesString.split("|") as NoteContentBlockType[]; matchingNotes = getNotesWithBlocksOfTypes(graph.notes, types, false); } // full-text search } else if (searchString.includes("ft:")) { const startOfFtQuery = searchString.indexOf("ft:") + "ft:".length; const ftQuery = searchString.substring(startOfFtQuery); matchingNotes = getNotesThatContainTokens( graph.notes, ftQuery, caseSensitive, ); // default mode: check if all query tokens are included in note title } else { matchingNotes = getNotesWithTitleContainingTokens( graph.notes, searchString, caseSensitive, ); } // now we need to transform all notes into NoteListItems before we can // sort those let noteListItems:NoteListItem[] = createNoteListItems(matchingNotes, graph) .sort(getSortFunction(sortMode)); // let's only slice the array if it makes sense to do so if (limit > 0 && limit < noteListItems.length) { noteListItems = noteListItems.slice(0, limit); } // let's extract the list items for the requested page const noteListItemsOfPage:NoteListItem[] = Utils.getPagedMatches( noteListItems, page, config.NUMBER_OF_RESULTS_PER_NOTE_LIST_PAGE, ); const noteListPage:NoteListPage = { results: noteListItemsOfPage, numberOfResults: noteListItems.length, } return noteListPage; }; const getGraphVisualization = async (graphId: GraphId):Promise<GraphVisualization> => { const graph = await io.getGraph(graphId); const graphNodes:GraphNode[] = graph.notes.map((note) => { const graphNode:GraphNode = { id: note.id, title: getDisplayNoteTitle(note), position: note.position, linkedNotes: getLinkedNotes(graph, note.id), creationTime: note.creationTime, }; return graphNode; }); const graphVisualization:GraphVisualization = { nodes: graphNodes, links: graph.links, screenPosition: graph.screenPosition, initialNodePosition: graph.initialNodePosition, } return graphVisualization; }; const getStats = async ( graphId:GraphId, /* including a graph analysis is quite CPU-heavy, that's why we include it only if explicitly asked for */ options:{ includeMetadata: boolean, includeAnalysis: boolean, }, ):Promise<GraphStats> => { const graph:GraphObject = await io.getGraph(graphId); const numberOfUnlinkedNotes = getNumberOfUnlinkedNotes(graph); let stats:GraphStats = { numberOfAllNotes: graph.notes.length, numberOfLinks: graph.links.length, numberOfFiles: await io.getNumberOfFiles(graphId), numberOfPins: graph.pinnedNotes.length, numberOfUnlinkedNotes, }; if (options.includeMetadata) { stats = { ...stats, creationTime: graph.creationTime, updateTime: graph.updateTime, id: graphId, size: { graph: await io.getSizeOfGraph(graphId), files: await io.getSizeOfGraphFiles(graphId), }, }; } if (options.includeAnalysis) { const numberOfComponents = getNumberOfComponents(graph.notes, graph.links); stats = { ...stats, numberOfComponents, numberOfComponentsWithMoreThanOneNode: numberOfComponents - numberOfUnlinkedNotes, numberOfHubs: graph.notes .filter((note) => { const numberOfLinkedNotes = getNumberOfLinkedNotes(graph, note.id); return numberOfLinkedNotes >= config.MIN_NUMBER_OF_LINKS_FOR_HUB; }) .length, nodesWithHighestNumberOfLinks: createNoteListItems(graph.notes, graph) .sort(getSortFunction(NoteListSortMode.NUMBER_OF_LINKS_DESCENDING)) .slice(0, 3), } } return stats; }; const setGraphVisualization = async ( graphVisualizationFromUser:GraphVisualizationFromUser, graphId:GraphId, ):Promise<void> => { const graph:Graph = await io.getGraph(graphId); graphVisualizationFromUser.nodePositionUpdates.forEach( (nodePositionUpdate:GraphNodePositionUpdate):void => { updateNotePosition(graph, nodePositionUpdate); }, ); graph.links = graphVisualizationFromUser.links; graph.screenPosition = graphVisualizationFromUser.screenPosition; graph.initialNodePosition = graphVisualizationFromUser.initialNodePosition; await io.flushChanges(graphId, graph); }; const put = async ( noteFromUser:NoteFromUser, graphId:GraphId, options ):Promise<NoteToTransmit> => { if ( (!noteFromUser) || (!Array.isArray(noteFromUser.blocks)) || (typeof noteFromUser.title !== "string") ) { throw new Error(ErrorMessage.INVALID_NOTE_STRUCTURE); } let ignoreDuplicateTitles = true; if ( (typeof options === "object") && (options.ignoreDuplicateTitles === false) ) { ignoreDuplicateTitles = false; } const graph:Graph = await io.getGraph(graphId); if (!ignoreDuplicateTitles && noteWithSameTitleExists(noteFromUser, graph)) { throw new Error(ErrorMessage.NOTE_WITH_SAME_TITLE_EXISTS); } let savedNote:SavedNote | null = null; if ( typeof noteFromUser.id === "number" ) { savedNote = await findNote(graph, noteFromUser.id); } if (savedNote === null) { const noteId:NoteId = getNewNoteId(graph); savedNote = { id: noteId, position: graph.initialNodePosition, title: normalizeNoteTitle(noteFromUser.title), blocks: noteFromUser.blocks, creationTime: Date.now(), updateTime: Date.now(), }; graph.notes.push(savedNote); } else { savedNote.blocks = noteFromUser.blocks; savedNote.title = normalizeNoteTitle(noteFromUser.title); savedNote.updateTime = Date.now(); } removeDefaultTextParagraphs(savedNote); removeEmptyLinkBlocks(savedNote); incorporateUserChangesIntoNote(noteFromUser.changes, savedNote, graph); await io.flushChanges(graphId, graph); const noteToTransmit:NoteToTransmit = createNoteToTransmit(savedNote, graph); return noteToTransmit; }; const remove = async ( noteId:NoteId, graphId:GraphId, ):Promise<void> => { const graph = await io.getGraph(graphId); const noteIndex = Utils.binaryArrayFindIndex(graph.notes, "id", noteId); if ((noteIndex === -1) || (noteIndex === null)) { throw new Error(ErrorMessage.NOTE_NOT_FOUND); } graph.notes.splice(noteIndex, 1); removeLinksOfNote(graph, noteId); graph.pinnedNotes = graph.pinnedNotes.filter((nId) => nId !== noteId); /* we do not remove files used in this note, because they could be used in other notes. this module considers files to exist independently of notes. unused files should be deleted in the clean up process, if at all. */ await io.flushChanges(graphId, graph); }; const importDB = ( graph:GraphObject, graphId:GraphId, ):Promise<boolean> => { return io.flushChanges(graphId, graph); }; const addFile = async ( graphId:GraphId, readable:Readable, mimeType: string, ):Promise<{ fileId: FileId, size: number, }> => { const fileType = config.ALLOWED_FILE_TYPES .find((filetype) => { return filetype.mimeType === mimeType; }); if (!fileType) { throw new Error(ErrorMessage.INVALID_MIME_TYPE); } const fileId:FileId = randomUUID() + "." + fileType.extension; const size = await io.addFile(graphId, fileId, readable); return { fileId, size, }; }; const deleteFile = async ( graphId: GraphId, fileId: FileId, ):Promise<void> => { return io.deleteFile(graphId, fileId); }; const getFiles = async ( graphId, ):Promise<FileId[]> => { return io.getFiles(graphId); }; const getReadableFileStream = ( graphId: GraphId, fileId:FileId, range?, ):Promise<ReadableWithType> => { return io.getReadableFileStream(graphId, fileId, range); }; const getFileSize = ( graphId: GraphId, fileId:FileId, ):Promise<number> => { return io.getFileSize(graphId, fileId); }; const getReadableGraphStream = async (graphId, withFiles) => { return await io.getReadableGraphStream(graphId, withFiles); }; const importLinksAsNotes = async (graphId, links) => { const promises:Promise<UrlMetadataResponse>[] = links.map((url:string):Promise<UrlMetadataResponse> => { return getUrlMetadata(url); }); const promiseSettledResults = await Promise.allSettled(promises); const fulfilledPromises:PromiseSettledResult<UrlMetadataResponse>[] = promiseSettledResults.filter((response) => { return response.status === "fulfilled"; }); const urlMetadataResults:UrlMetadataResponse[] = fulfilledPromises.map((response) => { return (response.status === "fulfilled") && response.value; }) .filter(Utils.isNotFalse); const notesFromUser:NoteFromUser[] = urlMetadataResults.map((urlMetadataObject) => { const noteFromUser:NoteFromUser = { title: urlMetadataObject.title, blocks: [ { "type": NoteContentBlockType.LINK, "data": { "link": urlMetadataObject.url, "meta": { "title": urlMetadataObject.title, "description": urlMetadataObject.description, "image": { "url": urlMetadataObject.image, }, } }, }, ], }; return noteFromUser; }); const notesToTransmit:NoteToTransmit[] = []; const failures:ImportLinkAsNoteFailure[] = []; for (let i = 0; i < notesFromUser.length; i++) { const noteFromUser:NoteFromUser = notesFromUser[i]; try { const noteToTransmit:NoteToTransmit = await put( noteFromUser, graphId, { ignoreDuplicateTitles: true, }, ); notesToTransmit.push(noteToTransmit); } catch (e) { const errorMessage:string = e.toString(); const failure:ImportLinkAsNoteFailure = { note: noteFromUser, error: errorMessage, }; failures.push(failure); } } return { notesToTransmit, failures, }; }; const pin = async ( graphId:GraphId, noteId:NoteId, ):Promise<NoteToTransmit[]> => { const graph = await io.getGraph(graphId); const noteIndex = Utils.binaryArrayFindIndex(graph.notes, "id", noteId); if (noteIndex === -1) { throw new Error(ErrorMessage.NOTE_NOT_FOUND); } graph.pinnedNotes = Array.from( new Set([...graph.pinnedNotes, noteId]), ); await io.flushChanges(graphId, graph); const pinnedNotes:NoteToTransmit[] = await Promise.all( graph.pinnedNotes .map((noteId) => { return get(noteId, graphId); }) ); return pinnedNotes; }; const unpin = async ( graphId:GraphId, noteId:NoteId, ):Promise<NoteToTransmit[]> => { const graph = await io.getGraph(graphId); graph.pinnedNotes = graph.pinnedNotes.filter((nId) => nId !== noteId); await io.flushChanges(graphId, graph); const pinnedNotes:NoteToTransmit[] = await Promise.all( graph.pinnedNotes .map((noteId) => { return get(noteId, graphId); }) ); return pinnedNotes; }; const getPins = async (graphId:GraphId):Promise<NoteToTransmit[]> => { const graph = await io.getGraph(graphId); const pinnedNotes:NoteToTransmit[] = await Promise.all( graph.pinnedNotes .map((noteId) => { return get(noteId, graphId); }) ); return pinnedNotes; }; export { init, get, getNotesList, getGraphVisualization, setGraphVisualization, getStats, put, remove, importDB, addFile, deleteFile, getFiles, getReadableFileStream, getFileSize, getReadableGraphStream, importLinksAsNotes, getUrlMetadata, pin, unpin, getPins, };
the_stack
import * as React from "react" /** * A close enough check to test if a value is a Synthetic Event or not. * See: https://github.com/reactjs/rfcs/pull/112 * @private */ function isReactSyntheticEvent(value: any) { if (typeof value !== "object" || value === null) return false if (typeof value.bubbles !== "boolean") return false if (typeof value.cancellable !== "boolean") return false if (typeof value.defaultPrevented !== "boolean") return false if (typeof value.eventPhase !== "number") return false if (typeof value.isTrusted !== "boolean") return false if (typeof value.timestamp !== "number") return false if (typeof value.type !== "string") return false return true } function isEmptyValue(value: any) { if (value === "") return true if (value === null) return true if (typeof value === "undefined") return true return false } /** * A function that accepts a value and returns an array of errors. If the array * is empty, the value is assumed to be valid. The validation can also return * asynchronously using a promise. * * Validation errors default to being strings, but can have any shape. */ export interface Validation<Val, Err = string> { (value: Val): Err[] | Promise<Err[]> } /** * Options to pass into `useField(opts)` */ export interface FieldOptions<Val, Err = string> { /** * The default value of the field. */ defaultValue: Val /** * Validations to run when the field is `validate()`'d. */ validations?: Array<Validation<Val, Err>> /** * Should the field be required? */ required?: boolean /** * Should the field be disabled? */ disabled?: boolean /** * Should the field be readOnly? */ readOnly?: boolean } /** * Options to pass into `useForm(opts)` */ export interface FormOptions<Err = string> { /** * All of the fields created via `useField()` that are part of the form. */ fields: Array<Field<any, Err>> /** * A submit handler for the form that receives the form submit event and can * return additional validation errors. May also return asynchronously using * a promise. */ onSubmit: () => void | Err[] | Promise<void> | Promise<Err[]> } /** * The object returned by `useField()` */ export interface Field<Val, Err = string> { /** * The current value of the field. */ value: Val /** * The `defaultValue` passed into `useField({ defaultValue })`. */ defaultValue: Val /** * Has the field been changed from its defaultValue? */ dirty: boolean /** * Has the element this field is attached to been focused previously? */ touched: boolean /** * Is the element this field is attached to currently focused? */ focused: boolean /** * Has the element this field is attached to been focused and then blurred? */ blurred: boolean /** * Is the field validating itself? */ validating: boolean /** * Is the field currently valid? * * Must have no errors, and if the field is required, must not be empty. */ valid: boolean /** * The collected errors returned by `opts.validations` */ errors: Err[] /** * Is the field required? */ required: boolean /** * Is the field disabled? */ disabled: boolean /** * Is the field readOnly? */ readOnly: boolean /** * Call with a value to manually update the value of the field. */ setValue: (value: Val) => any /** * Call with true/false to manually set the `required` state of the field. */ setRequired: (required: boolean) => void /** * Call with true/false to manually set the `disabled` state of the field. */ setDisabled: (disabled: boolean) => void /** * Call with true/false to manually set the `readOnly` state of the field. */ setReadOnly: (readonly: boolean) => void /** * Reset the field to its default state. */ reset: () => void /** * Manually tell the field to validate itself (updating other fields). */ validate: () => Promise<void> /** * Props to pass into an component to attach the `field` to it */ props: { /** * The current value (matches `field.value`). */ value: Val /** * An `onChange` handler to update the value of the field. */ onChange: (value: Val) => void /** * An `onFocus` handler to update the focused/touched/blurred states of the field. */ onFocus: () => void /** * An `onFocus` handler to update the focused/blurred states of the field. */ onBlur: () => void /** * Should the element be `required`? */ required: boolean /** * Should the element be `disabled`? */ disabled: boolean /** * Should the element be `readOnly`? */ readOnly: boolean } } /** * The object returned by `useForm()` */ export interface Form<Err = string> { /** * The collected errors from all of the fields in the form. */ fieldErrors: Array<Err> /** * The errors returned by `opts.onSubmit`. */ submitErrors: Array<Err> /** * Has the form been submitted at any point? */ submitted: boolean /** * Is the form currently submitting? */ submitting: boolean /** * Are *any* of the fields in the form currently `focused`? */ focused: boolean /** * Are *any* of the fields in the form currently `touched`? */ touched: boolean /** * Are *any* of the fields in the form currently `dirty`? */ dirty: boolean /** * Are *all* of the fields in the form currently `valid`? */ valid: boolean /** * Are *any* of the fields in the form currently `validating`? */ validating: boolean /** * Reset all of the fields in the form. */ reset: () => void /** * Validate all of the fields in the form. */ validate: () => Promise<void> /** * Submit the form manually. */ submit: () => Promise<void> /** * Props to pass into a form component to attach the `form` to it: */ props: { /** * An `onSubmit` handler to pass to an element that submits the form. */ onSubmit: () => Promise<void> } } /** * Call `useField()` to create a single field in a form. */ export function useField<Val, Err = string>( options: FieldOptions<Val, Err>, ): Field<Val, Err> { let defaultValue = options.defaultValue let validations = options.validations || [] let [value, setValue] = React.useState(defaultValue) let [errors, setErrors] = React.useState<Err[]>([]) let [validating, setValidating] = React.useState(false) let [focused, setFocused] = React.useState(false) let [blurred, setBlurred] = React.useState(false) let [touched, setTouched] = React.useState(false) let [dirty, setDirty] = React.useState(false) let [required, setRequired] = React.useState(options.required || false) let [disabled, setDisabled] = React.useState(options.disabled || false) let [readOnly, setReadOnly] = React.useState(options.readOnly || false) let onFocus = React.useCallback(() => { setFocused(true) setTouched(true) }, []) let onBlur = React.useCallback(() => { setFocused(false) setBlurred(true) }, []) let valueRef = React.useRef<Val>(value) function reset() { valueRef.current = defaultValue; setValue(defaultValue) setErrors([]) setValidating(false) setBlurred(false) if (!focused) setTouched(false) setDirty(false) } function validate() { let initValue = valueRef.current let errorsMap: Err[][] = [] setValidating(true) let promises = validations.map((validation, index) => { return Promise.resolve() .then(() => validation(initValue)) .then(errors => { errorsMap[index] = errors if (Object.is(initValue, valueRef.current)) { setErrors(errorsMap.flat(1)) } }) }) return Promise.all(promises) .then(() => { if (Object.is(initValue, valueRef.current)) { setValidating(false) } }) .catch(err => { if (Object.is(initValue, valueRef.current)) { setValidating(false) } throw err }) } let setValueHandler = (value: Val) => { valueRef.current = value setDirty(true) setValue(value) setErrors([]) validate() } let onChange = (value: Val) => { if (isReactSyntheticEvent(value)) { throw new TypeError( "Expected `field.onChange` to be called with a value, not an event", ) } setValueHandler(value) } let valid = !errors.length && (required ? !isEmptyValue(value) : true) return { value, errors, defaultValue, setValue: setValueHandler, focused, blurred, touched, dirty, valid, validating, required, disabled, readOnly, setRequired, setDisabled, setReadOnly, reset, validate, props: { value, required, disabled, readOnly, onFocus, onBlur, onChange, }, } } /** * Call `useForm()` with to create a single form. */ export function useForm<Err = string>(options: FormOptions<Err>): Form<Err> { let fields = options.fields let onSubmit = options.onSubmit let [submitted, setSubmitted] = React.useState(false) let [submitting, setSubmitting] = React.useState(false) let [submitErrors, setSubmitErrors] = React.useState<Err[]>([]) let focused = fields.some(field => field.focused) let touched = fields.some(field => field.touched) let dirty = fields.some(field => field.dirty) let valid = fields.every(field => field.valid) let validating = fields.some(field => field.validating) let fieldErrors = fields.reduce( (errors, field) => errors.concat(field.errors), [] as Err[], ) function reset() { setSubmitted(false) setSubmitting(false) setSubmitErrors([]) fields.forEach(field => field.reset()) } function validate() { return Promise.all(fields.map(field => field.validate())).then(() => {}) } function onSubmitHandler() { setSubmitted(true) setSubmitting(true) return Promise.resolve() .then(() => onSubmit() as any) // Dunno why TS is mad .then((errs: void | Err[]) => { setSubmitting(false) setSubmitErrors(errs || []) }) .catch((err: Error) => { setSubmitting(false) throw err }) } return { fieldErrors, submitErrors, submitted, submitting, focused, touched, dirty, valid, validating, validate, reset, submit: onSubmitHandler, props: { onSubmit: onSubmitHandler, }, } }
the_stack
import throttle from 'lodash/throttle'; import {CHUNK_LAYER_STATISTICS_RPC_ID, CHUNK_MANAGER_RPC_ID, CHUNK_QUEUE_MANAGER_RPC_ID, CHUNK_SOURCE_INVALIDATE_RPC_ID, ChunkDownloadStatistics, ChunkMemoryStatistics, ChunkPriorityTier, LayerChunkProgressInfo, ChunkSourceParametersConstructor, ChunkState, getChunkDownloadStatisticIndex, getChunkStateStatisticIndex, numChunkMemoryStatistics, numChunkStatistics, REQUEST_CHUNK_STATISTICS_RPC_ID} from 'neuroglancer/chunk_manager/base'; import {SharedWatchableValue} from 'neuroglancer/shared_watchable_value'; import {TypedArray} from 'neuroglancer/util/array'; import {CancellationToken, CancellationTokenSource} from 'neuroglancer/util/cancellation'; import {Disposable, RefCounted} from 'neuroglancer/util/disposable'; import {Borrowed} from 'neuroglancer/util/disposable'; import {LinkedListOperations} from 'neuroglancer/util/linked_list'; import LinkedList0 from 'neuroglancer/util/linked_list.0'; import LinkedList1 from 'neuroglancer/util/linked_list.1'; import {StringMemoize} from 'neuroglancer/util/memoize'; import {ComparisonFunction, PairingHeapOperations} from 'neuroglancer/util/pairing_heap'; import PairingHeap0 from 'neuroglancer/util/pairing_heap.0'; import PairingHeap1 from 'neuroglancer/util/pairing_heap.1'; import {NullarySignal} from 'neuroglancer/util/signal'; import {initializeSharedObjectCounterpart, registerPromiseRPC, registerRPC, registerSharedObject, registerSharedObjectOwner, RPC, SharedObject, SharedObjectCounterpart} from 'neuroglancer/worker_rpc'; const DEBUG_CHUNK_UPDATES = false; export interface ChunkStateListener { stateChanged(chunk: Chunk, oldState: ChunkState): void; } let nextMarkGeneration = 0; export function getNextMarkGeneration() { return ++nextMarkGeneration; } export class Chunk implements Disposable { // Node properties used for eviction/promotion heaps and LRU linked lists. child0: Chunk|null = null; next0: Chunk|null = null; prev0: Chunk|null = null; child1: Chunk|null = null; next1: Chunk|null = null; prev1: Chunk|null = null; source: ChunkSource|null = null; key: string|null = null; private state_ = ChunkState.NEW; error: any = null; // Used by layers for marking chunks for various purposes. markGeneration = -1; /** * Specifies existing priority within priority tier. Only meaningful if priorityTier in * CHUNK_ORDERED_PRIORITY_TIERS. Higher numbers mean higher priority. */ priority = 0; /** * Specifies updated priority within priority tier, not yet reflected in priority queue state. * Only meaningful if newPriorityTier in CHUNK_ORDERED_PRIORITY_TIERS. */ newPriority = 0; priorityTier = ChunkPriorityTier.RECENT; /** * Specifies updated priority tier, not yet reflected in priority queue state. */ newPriorityTier = ChunkPriorityTier.RECENT; private systemMemoryBytes_: number = 0; private gpuMemoryBytes_: number = 0; private downloadSlots_: number = 1; backendOnly = false; isComputational = false; newlyRequestedToFrontend = false; requestedToFrontend = false; /** * Cancellation token used to cancel the pending download. Set to undefined except when state !== * DOWNLOADING. This should not be accessed by code outside this module. */ downloadCancellationToken: CancellationTokenSource|undefined = undefined; initialize(key: string) { this.key = key; this.priority = Number.NEGATIVE_INFINITY; this.priorityTier = ChunkPriorityTier.RECENT; this.newPriority = Number.NEGATIVE_INFINITY; this.newPriorityTier = ChunkPriorityTier.RECENT; this.error = null; this.state = ChunkState.NEW; this.requestedToFrontend = false; this.newlyRequestedToFrontend = false; } /** * Sets this.priority{Tier,} to this.newPriority{Tier,}, and resets this.newPriorityTier to * ChunkPriorityTier.RECENT. * * This does not actually update any queues to reflect this change. */ updatePriorityProperties() { this.priorityTier = this.newPriorityTier; this.priority = this.newPriority; this.newPriorityTier = ChunkPriorityTier.RECENT; this.newPriority = Number.NEGATIVE_INFINITY; this.requestedToFrontend = this.newlyRequestedToFrontend; } dispose() { this.source = null; this.error = null; } get chunkManager() { return (<ChunkSource>this.source).chunkManager; } get queueManager() { return (<ChunkSource>this.source).chunkManager.queueManager; } downloadFailed(error: any) { this.error = error; this.queueManager.updateChunkState(this, ChunkState.FAILED); } downloadSucceeded() { this.queueManager.updateChunkState(this, ChunkState.SYSTEM_MEMORY_WORKER); } freeSystemMemory() {} serialize(msg: any, _transfers: any[]) { msg['id'] = this.key; msg['source'] = (<ChunkSource>this.source).rpcId; msg['new'] = true; } toString() { return this.key; } set state(newState: ChunkState) { if (newState === this.state_) { return; } const oldState = this.state_; this.state_ = newState; this.source!.chunkStateChanged(this, oldState); } get state() { return this.state_; } set systemMemoryBytes(bytes: number) { updateChunkStatistics(this, -1); this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false); this.systemMemoryBytes_ = bytes; this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true); updateChunkStatistics(this, 1); this.chunkManager.queueManager.scheduleUpdate(); } get systemMemoryBytes() { return this.systemMemoryBytes_; } set gpuMemoryBytes(bytes: number) { updateChunkStatistics(this, -1); this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false); this.gpuMemoryBytes_ = bytes; this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true); updateChunkStatistics(this, 1); this.chunkManager.queueManager.scheduleUpdate(); } get gpuMemoryBytes() { return this.gpuMemoryBytes_; } get downloadSlots() { return this.downloadSlots_; } set downloadSlots(count: number) { if (count === this.downloadSlots_) return; updateChunkStatistics(this, -1); this.chunkManager.queueManager.adjustCapacitiesForChunk(this, false); this.downloadSlots_ = count; this.chunkManager.queueManager.adjustCapacitiesForChunk(this, true); updateChunkStatistics(this, 1); this.chunkManager.queueManager.scheduleUpdate(); } registerListener(listener: ChunkStateListener) { if (!this.source) { return false; } return this.source.registerChunkListener(this.key!, listener); } unregisterListener(listener: ChunkStateListener) { if (!this.source) { return false; } return this.source.unregisterChunkListener(this.key!, listener); } static priorityLess(a: Chunk, b: Chunk) { return a.priority < b.priority; } static priorityGreater(a: Chunk, b: Chunk) { return a.priority > b.priority; } } export interface ChunkConstructor<T extends Chunk> { new(): T; } const numSourceQueueLevels = 2; /** * Base class inherited by both ChunkSource, for implementing the backend part of chunk sources that * also have a frontend-part, as well as other chunk sources, such as the GenericFileSource, that * has only a backend part. */ export class ChunkSourceBase extends SharedObject { private listeners_ = new Map<string, ChunkStateListener[]>(); chunks: Map<string, Chunk> = new Map<string, Chunk>(); freeChunks: Chunk[] = new Array<Chunk>(); statistics = new Float64Array(numChunkStatistics); /** * sourceQueueLevel must be greater than the sourceQueueLevel of any ChunkSource whose download * method depends on chunks from this source. A normal ChunkSource with no other dependencies * should have a level of 0. */ sourceQueueLevel = 0; constructor(public chunkManager: Borrowed<ChunkManager>) { super(); chunkManager.queueManager.sources.add(this); } disposed() { this.chunkManager.queueManager.sources.delete(this); super.disposed(); } getNewChunk_<T extends Chunk>(chunkType: ChunkConstructor<T>): T { let freeChunks = this.freeChunks; let freeChunksLength = freeChunks.length; if (freeChunksLength > 0) { let chunk = <T>freeChunks[freeChunksLength - 1]; freeChunks.length = freeChunksLength - 1; chunk.source = this; return chunk; } let chunk = new chunkType(); chunk.source = this; return chunk; } /** * Adds the specified chunk to the chunk cache. * * If the chunk cache was previously empty, also call this.addRef() to increment the reference * count. */ addChunk(chunk: Chunk) { let {chunks} = this; if (chunks.size === 0) { this.addRef(); } chunks.set(chunk.key!, chunk); updateChunkStatistics(chunk, 1); } /** * Remove the specified chunk from the chunk cache. * * If the chunk cache becomes empty, also call this.dispose() to decrement the reference count. */ removeChunk(chunk: Chunk) { let {chunks, freeChunks} = this; chunks.delete(chunk.key!); chunk.dispose(); freeChunks[freeChunks.length] = chunk; if (chunks.size === 0) { this.dispose(); } } registerChunkListener(key: string, listener: ChunkStateListener) { if (!this.listeners_.has(key)) { this.listeners_.set(key, [listener]); } else { this.listeners_.get(key)!.push(listener); } return true; } unregisterChunkListener(key: string, listener: ChunkStateListener) { if (!this.listeners_.has(key)) { return false; } const keyListeners = this.listeners_.get(key)!; const idx = keyListeners.indexOf(listener); if (idx < 0) { return false; } keyListeners.splice(idx, 1); if (keyListeners.length === 0) { this.listeners_.delete(key); } return true; } chunkStateChanged(chunk: Chunk, oldState: ChunkState) { if (!chunk.key) { return; } if (!this.listeners_.has(chunk.key)) { return; } for (const listener of [...this.listeners_.get(chunk.key)!]) { listener.stateChanged(chunk, oldState); } } } function updateChunkStatistics(chunk: Chunk, sign: number) { const {statistics} = chunk.source!; const {systemMemoryBytes, gpuMemoryBytes} = chunk; const index = getChunkStateStatisticIndex(chunk.state, chunk.priorityTier); statistics[index * numChunkMemoryStatistics + ChunkMemoryStatistics.numChunks] += sign; statistics[index * numChunkMemoryStatistics + ChunkMemoryStatistics.systemMemoryBytes] += sign * systemMemoryBytes; statistics[index * numChunkMemoryStatistics + ChunkMemoryStatistics.gpuMemoryBytes] += sign * gpuMemoryBytes; } export interface ChunkSourceBase { /** * Begin downloading the specified the chunk. The returned promise should resolve when the * downloaded data has been successfully decoded and stored in the chunk, or rejected if the * download or decoding fails. * * Note: This method must be defined by subclasses. * * @param chunk Chunk to download. * @param cancellationToken If this token is canceled, the download/decoding should be aborted if * possible. * * TODO(jbms): Move this back to the class definition above and declare this abstract once mixins * are compatible with abstract classes. */ download(chunk: Chunk, cancellationToken: CancellationToken): Promise<void>; } export class ChunkSource extends ChunkSourceBase { constructor(rpc: RPC, options: any) { // No need to add a reference, since the owner counterpart will hold a reference to the owner // counterpart of chunkManager. const chunkManager = <ChunkManager>rpc.get(options['chunkManager']); super(chunkManager); initializeSharedObjectCounterpart(this, rpc, options); } } function startChunkDownload(chunk: Chunk) { const downloadCancellationToken = chunk.downloadCancellationToken = new CancellationTokenSource(); const startTime = Date.now(); chunk.source!.download(chunk, downloadCancellationToken) .then( () => { if (chunk.downloadCancellationToken === downloadCancellationToken) { chunk.downloadCancellationToken = undefined; const endTime = Date.now(); const {statistics} = chunk.source!; statistics[getChunkDownloadStatisticIndex(ChunkDownloadStatistics.totalTime)] += (endTime - startTime); ++statistics[getChunkDownloadStatisticIndex(ChunkDownloadStatistics.totalChunks)]; chunk.downloadSucceeded(); } }, (error: any) => { if (chunk.downloadCancellationToken === downloadCancellationToken) { chunk.downloadCancellationToken = undefined; chunk.downloadFailed(error); console.log(`Error retrieving chunk ${chunk}: ${error}`); } }); } function cancelChunkDownload(chunk: Chunk) { const token = chunk.downloadCancellationToken!; chunk.downloadCancellationToken = undefined; token.cancel(); } class ChunkPriorityQueue { /** * Heap roots for VISIBLE and PREFETCH priority tiers. */ private heapRoots: (Chunk|null)[] = [null, null]; /** * Head node for RECENT linked list. */ private recentHead = new Chunk(); constructor( private heapOperations: PairingHeapOperations<Chunk>, private linkedListOperations: LinkedListOperations<Chunk>) { linkedListOperations.initializeHead(this.recentHead); } add(chunk: Chunk) { let priorityTier = chunk.priorityTier; if (priorityTier === ChunkPriorityTier.RECENT) { this.linkedListOperations.insertAfter(this.recentHead, chunk); } else { let {heapRoots} = this; heapRoots[priorityTier] = this.heapOperations.meld(heapRoots[priorityTier], chunk); } } * candidates(): Iterator<Chunk> { if (this.heapOperations.compare === Chunk.priorityLess) { // Start with least-recently used RECENT chunk. let {linkedListOperations, recentHead} = this; while (true) { let chunk = linkedListOperations.back(recentHead); if (chunk == null) { break; } else { yield chunk; } } let {heapRoots} = this; for (let tier = ChunkPriorityTier.LAST_ORDERED_TIER; tier >= ChunkPriorityTier.FIRST_ORDERED_TIER; --tier) { while (true) { let root = heapRoots[tier]; if (root == null) { break; } else { yield root; } } } } else { let heapRoots = this.heapRoots; for (let tier = ChunkPriorityTier.FIRST_ORDERED_TIER; tier <= ChunkPriorityTier.LAST_ORDERED_TIER; ++tier) { while (true) { let root = heapRoots[tier]; if (root == null) { break; } else { yield root; } } } let {linkedListOperations, recentHead} = this; while (true) { let chunk = linkedListOperations.front(recentHead); if (chunk == null) { break; } else { yield chunk; } } } } /** * Deletes a chunk from this priority queue. * @param chunk The chunk to delete from the priority queue. */ delete(chunk: Chunk) { let priorityTier = chunk.priorityTier; if (priorityTier === ChunkPriorityTier.RECENT) { this.linkedListOperations.pop(chunk); } else { let heapRoots = this.heapRoots; heapRoots[priorityTier] = this.heapOperations.remove(<Chunk>heapRoots[priorityTier], chunk); } } } function makeChunkPriorityQueue0(compare: ComparisonFunction<Chunk>) { return new ChunkPriorityQueue(new PairingHeap0(compare), LinkedList0); } function makeChunkPriorityQueue1(compare: ComparisonFunction<Chunk>) { return new ChunkPriorityQueue(new PairingHeap1(compare), LinkedList1); } function tryToFreeCapacity( size: number, capacity: AvailableCapacity, priorityTier: ChunkPriorityTier, priority: number, evictionCandidates: Iterator<Chunk>, evict: (chunk: Chunk) => void) { while (capacity.availableItems < 1 || capacity.availableSize < size) { let evictionCandidate = evictionCandidates.next().value; if (evictionCandidate === undefined) { // No eviction candidates available, promotions are done. return false; } else { let evictionTier = evictionCandidate.priorityTier; if (evictionTier < priorityTier || (evictionTier === priorityTier && evictionCandidate.priority >= priority)) { // Lowest priority eviction candidate has priority >= highest // priority promotion candidate. No more promotions are // possible. return false; } evict(evictionCandidate); } } return true; } class AvailableCapacity extends RefCounted { currentSize: number = 0; currentItems: number = 0; capacityChanged = new NullarySignal(); constructor( public itemLimit: Borrowed<SharedWatchableValue<number>>, public sizeLimit: Borrowed<SharedWatchableValue<number>>) { super(); this.registerDisposer(itemLimit.changed.add(this.capacityChanged.dispatch)); this.registerDisposer(sizeLimit.changed.add(this.capacityChanged.dispatch)); } /** * Adjust available capacity by the specified amounts. */ adjust(items: number, size: number) { this.currentItems -= items; this.currentSize -= size; } get availableSize() { return this.sizeLimit.value - this.currentSize; } get availableItems() { return this.itemLimit.value - this.currentItems; } toString() { return `bytes=${this.currentSize}/${this.sizeLimit.value},` + `items=${this.currentItems}/${this.itemLimit.value}`; } } @registerSharedObject(CHUNK_QUEUE_MANAGER_RPC_ID) export class ChunkQueueManager extends SharedObjectCounterpart { gpuMemoryCapacity: AvailableCapacity; systemMemoryCapacity: AvailableCapacity; /** * Download capacity for each sourceQueueLevel. */ downloadCapacity: AvailableCapacity[]; computeCapacity: AvailableCapacity; enablePrefetch: SharedWatchableValue<boolean>; /** * Set of chunk sources associated with this queue manager. */ sources = new Set<Borrowed<ChunkSource>>(); /** * Contains all chunks in QUEUED state pending download, for each sourceQueueLevel. */ private queuedDownloadPromotionQueue = [ makeChunkPriorityQueue1(Chunk.priorityGreater), makeChunkPriorityQueue1(Chunk.priorityGreater), ]; /** * Contains all chunks in QUEUED state pending compute. */ private queuedComputePromotionQueue = makeChunkPriorityQueue1(Chunk.priorityGreater); /** * Contains all chunks in DOWNLOADING state, for each sourceQueueLevel. */ private downloadEvictionQueue = [ makeChunkPriorityQueue1(Chunk.priorityLess), makeChunkPriorityQueue1(Chunk.priorityLess), ]; /** * Contains all chunks in COMPUTING state. */ private computeEvictionQueue = makeChunkPriorityQueue1(Chunk.priorityLess); /** * Contains all chunks that take up memory (DOWNLOADING, SYSTEM_MEMORY, * GPU_MEMORY). */ private systemMemoryEvictionQueue = makeChunkPriorityQueue0(Chunk.priorityLess); /** * Contains all chunks in SYSTEM_MEMORY state not in RECENT priority tier. */ private gpuMemoryPromotionQueue = makeChunkPriorityQueue1(Chunk.priorityGreater); /** * Contains all chunks in GPU_MEMORY state. */ private gpuMemoryEvictionQueue = makeChunkPriorityQueue1(Chunk.priorityLess); // Should be `number|null`, but marked `any` to work around @types/node being pulled in. private updatePending: any = null; gpuMemoryChanged = new NullarySignal(); private numQueued = 0; private numFailed = 0; private gpuMemoryGeneration = 0; constructor(rpc: RPC, options: any) { super(rpc, options); const getCapacity = (capacity: any) => { const result = this.registerDisposer( new AvailableCapacity(rpc.get(capacity['itemLimit']), rpc.get(capacity['sizeLimit']))); result.capacityChanged.add(() => this.scheduleUpdate()); return result; }; this.gpuMemoryCapacity = getCapacity(options['gpuMemoryCapacity']); this.systemMemoryCapacity = getCapacity(options['systemMemoryCapacity']); this.enablePrefetch = rpc.get(options['enablePrefetch']); this.downloadCapacity = [ getCapacity(options['downloadCapacity']), getCapacity(options['downloadCapacity']), ]; this.computeCapacity = getCapacity(options['computeCapacity']); } scheduleUpdate() { if (this.updatePending === null) { this.updatePending = setTimeout(this.process.bind(this), 0); } } * chunkQueuesForChunk(chunk: Chunk) { switch (chunk.state) { case ChunkState.QUEUED: if (chunk.isComputational) { yield this.queuedComputePromotionQueue; } else { yield this.queuedDownloadPromotionQueue[chunk.source!.sourceQueueLevel]; } break; case ChunkState.DOWNLOADING: if (chunk.isComputational) { yield this.computeEvictionQueue; } else { yield this.downloadEvictionQueue[chunk.source!.sourceQueueLevel]; yield this.systemMemoryEvictionQueue; } break; case ChunkState.SYSTEM_MEMORY_WORKER: case ChunkState.SYSTEM_MEMORY: yield this.systemMemoryEvictionQueue; if (chunk.priorityTier !== ChunkPriorityTier.RECENT && !chunk.backendOnly && chunk.requestedToFrontend) { yield this.gpuMemoryPromotionQueue; } break; case ChunkState.GPU_MEMORY: yield this.systemMemoryEvictionQueue; yield this.gpuMemoryEvictionQueue; break; } } adjustCapacitiesForChunk(chunk: Chunk, add: boolean) { let factor = add ? -1 : 1; switch (chunk.state) { case ChunkState.FAILED: this.numFailed -= factor; break; case ChunkState.QUEUED: this.numQueued -= factor; break; case ChunkState.DOWNLOADING: (chunk.isComputational ? this.computeCapacity : this.downloadCapacity[chunk.source!.sourceQueueLevel]) .adjust(factor * chunk.downloadSlots, factor * chunk.systemMemoryBytes); this.systemMemoryCapacity.adjust(factor, factor * chunk.systemMemoryBytes); break; case ChunkState.SYSTEM_MEMORY: case ChunkState.SYSTEM_MEMORY_WORKER: this.systemMemoryCapacity.adjust(factor, factor * chunk.systemMemoryBytes); break; case ChunkState.GPU_MEMORY: this.systemMemoryCapacity.adjust(factor, factor * chunk.systemMemoryBytes); this.gpuMemoryCapacity.adjust(factor, factor * chunk.gpuMemoryBytes); break; } } private removeChunkFromQueues_(chunk: Chunk) { updateChunkStatistics(chunk, -1); for (let queue of this.chunkQueuesForChunk(chunk)) { queue.delete(chunk); } } // var freedChunks = 0; private addChunkToQueues_(chunk: Chunk) { if (chunk.state === ChunkState.QUEUED && chunk.priorityTier === ChunkPriorityTier.RECENT) { // Delete this chunk. let {source} = chunk; source!.removeChunk(chunk); this.adjustCapacitiesForChunk(chunk, false); return false; } else { updateChunkStatistics(chunk, 1); for (let queue of this.chunkQueuesForChunk(chunk)) { queue.add(chunk); } return true; } } performChunkPriorityUpdate(chunk: Chunk) { if (chunk.priorityTier === chunk.newPriorityTier && chunk.priority === chunk.newPriority) { chunk.newPriorityTier = ChunkPriorityTier.RECENT; chunk.newPriority = Number.NEGATIVE_INFINITY; return; } if (DEBUG_CHUNK_UPDATES) { console.log( `${chunk}: changed priority ${chunk.priorityTier}:` + `${chunk.priority} -> ${chunk.newPriorityTier}:${chunk.newPriority}`); } this.removeChunkFromQueues_(chunk); chunk.updatePriorityProperties(); if (chunk.state === ChunkState.NEW) { chunk.state = ChunkState.QUEUED; this.adjustCapacitiesForChunk(chunk, true); } this.addChunkToQueues_(chunk); } updateChunkState(chunk: Chunk, newState: ChunkState) { if (newState === chunk.state) { return; } if (DEBUG_CHUNK_UPDATES) { console.log(`${chunk}: changed state ${ChunkState[chunk.state]} -> ${ChunkState[newState]}`); } this.adjustCapacitiesForChunk(chunk, false); this.removeChunkFromQueues_(chunk); chunk.state = newState; this.adjustCapacitiesForChunk(chunk, true); this.addChunkToQueues_(chunk); this.scheduleUpdate(); } private processGPUPromotions_() { let queueManager = this; function evictFromGPUMemory(chunk: Chunk) { queueManager.freeChunkGPUMemory(chunk); chunk.source!.chunkManager.queueManager.updateChunkState(chunk, ChunkState.SYSTEM_MEMORY); } let promotionCandidates = this.gpuMemoryPromotionQueue.candidates(); let evictionCandidates = this.gpuMemoryEvictionQueue.candidates(); let capacity = this.gpuMemoryCapacity; while (true) { let promotionCandidate = promotionCandidates.next().value; if (promotionCandidate === undefined) { break; } else { let priorityTier = promotionCandidate.priorityTier; let priority = promotionCandidate.priority; if (!tryToFreeCapacity( promotionCandidate.gpuMemoryBytes, capacity, priorityTier, priority, evictionCandidates, evictFromGPUMemory)) { break; } this.copyChunkToGPU(promotionCandidate); this.updateChunkState(promotionCandidate, ChunkState.GPU_MEMORY); } } } freeChunkGPUMemory(chunk: Chunk) { ++this.gpuMemoryGeneration; this.rpc!.invoke( 'Chunk.update', {'id': chunk.key, 'state': ChunkState.SYSTEM_MEMORY, 'source': chunk.source!.rpcId}); } freeChunkSystemMemory(chunk: Chunk) { if (chunk.state === ChunkState.SYSTEM_MEMORY_WORKER) { chunk.freeSystemMemory(); } else { this.rpc!.invoke( 'Chunk.update', {'id': chunk.key, 'state': ChunkState.EXPIRED, 'source': chunk.source!.rpcId}); } } retrieveChunkData(chunk: Chunk) { return this.rpc!.promiseInvoke<TypedArray>( 'Chunk.retrieve', {key: chunk.key!, source: chunk.source!.rpcId}); } copyChunkToGPU(chunk: Chunk) { ++this.gpuMemoryGeneration; let rpc = this.rpc!; if (chunk.state === ChunkState.SYSTEM_MEMORY) { rpc.invoke( 'Chunk.update', {'id': chunk.key, 'source': chunk.source!.rpcId, 'state': ChunkState.GPU_MEMORY}); } else { let msg: any = {}; let transfers: any[] = []; chunk.serialize(msg, transfers); msg['state'] = ChunkState.GPU_MEMORY; rpc.invoke('Chunk.update', msg, transfers); } } private processQueuePromotions_() { let queueManager = this; const evict = (chunk: Chunk) => { switch (chunk.state) { case ChunkState.DOWNLOADING: cancelChunkDownload(chunk); break; case ChunkState.GPU_MEMORY: queueManager.freeChunkGPUMemory(chunk); case ChunkState.SYSTEM_MEMORY_WORKER: case ChunkState.SYSTEM_MEMORY: queueManager.freeChunkSystemMemory(chunk); break; } // Note: After calling this, chunk may no longer be valid. this.updateChunkState(chunk, ChunkState.QUEUED); }; const promotionLambda = (promotionCandidates: Iterator<Chunk>, evictionCandidates: Iterator<Chunk>, capacity: AvailableCapacity) => { let systemMemoryEvictionCandidates = this.systemMemoryEvictionQueue.candidates(); let systemMemoryCapacity = this.systemMemoryCapacity; while (true) { let promotionCandidateResult = promotionCandidates.next(); if (promotionCandidateResult.done) { return; } let promotionCandidate = promotionCandidateResult.value; const size = 0; /* unknown size, since it hasn't been downloaded yet. */ let priorityTier = promotionCandidate.priorityTier; let priority = promotionCandidate.priority; // console.log("Download capacity: " + downloadCapacity); if (!tryToFreeCapacity( size, capacity, priorityTier, priority, evictionCandidates, evict)) { return; } if (!tryToFreeCapacity( size, systemMemoryCapacity, priorityTier, priority, systemMemoryEvictionCandidates, evict)) { return; } this.updateChunkState(promotionCandidate, ChunkState.DOWNLOADING); startChunkDownload(promotionCandidate); } }; for (let sourceQueueLevel = 0; sourceQueueLevel < numSourceQueueLevels; ++sourceQueueLevel) { promotionLambda( this.queuedDownloadPromotionQueue[sourceQueueLevel].candidates(), this.downloadEvictionQueue[sourceQueueLevel].candidates(), this.downloadCapacity[sourceQueueLevel]); } promotionLambda( this.queuedComputePromotionQueue.candidates(), this.computeEvictionQueue.candidates(), this.computeCapacity); } process() { if (!this.updatePending) { return; } this.updatePending = null; const gpuMemoryGeneration = this.gpuMemoryGeneration; this.processGPUPromotions_(); this.processQueuePromotions_(); this.logStatistics(); if (this.gpuMemoryGeneration !== gpuMemoryGeneration) { this.gpuMemoryChanged.dispatch(); } } logStatistics() { if (DEBUG_CHUNK_UPDATES) { console.log( `[Chunk status] QUEUED: ${this.numQueued}, FAILED: ` + `${this.numFailed}, DOWNLOAD: ${this.downloadCapacity}, ` + `MEM: ${this.systemMemoryCapacity}, GPU: ${this.gpuMemoryCapacity}`); } } invalidateSourceCache(source: ChunkSource) { for (const chunk of source.chunks.values()) { switch (chunk.state) { case ChunkState.DOWNLOADING: cancelChunkDownload(chunk); break; case ChunkState.SYSTEM_MEMORY_WORKER: chunk.freeSystemMemory(); break; } // Note: After calling this, chunk may no longer be valid. this.updateChunkState(chunk, ChunkState.QUEUED); } this.rpc!.invoke('Chunk.update', {'source': source.rpcId}); this.scheduleUpdate(); } } export class ChunkRenderLayerBackend extends SharedObjectCounterpart implements LayerChunkProgressInfo { chunkManagerGeneration: number = -1; numVisibleChunksNeeded: number = 0; numVisibleChunksAvailable: number = 0; numPrefetchChunksNeeded: number = 0; numPrefetchChunksAvailable: number = 0; } const LAYER_CHUNK_STATISTICS_INTERVAL = 200; @registerSharedObject(CHUNK_MANAGER_RPC_ID) export class ChunkManager extends SharedObjectCounterpart { queueManager: ChunkQueueManager; /** * Array of chunks within each existing priority tier. */ private existingTierChunks: Chunk[][] = []; /** * Array of chunks whose new priorities have not yet been reflected in the * queue states. */ private newTierChunks: Chunk[] = []; // Should be `number|null`, but marked `any` to workaround `@types/node` being pulled in. private updatePending: any = null; recomputeChunkPriorities = new NullarySignal(); /** * Dispatched immediately after recomputeChunkPriorities is dispatched. * This signal should be used for handlers that depend on the result of another handler. */ recomputeChunkPrioritiesLate = new NullarySignal(); memoize = new StringMemoize(); layers: ChunkRenderLayerBackend[] = []; private sendLayerChunkStatistics = this.registerCancellable(throttle(() => { this.rpc!.invoke(CHUNK_LAYER_STATISTICS_RPC_ID, { id: this.rpcId, layers: this.layers.map(layer => ({ id: layer.rpcId, numVisibleChunksAvailable: layer.numVisibleChunksAvailable, numVisibleChunksNeeded: layer.numVisibleChunksNeeded, numPrefetchChunksAvailable: layer.numPrefetchChunksAvailable, numPrefetchChunksNeeded: layer.numPrefetchChunksNeeded })) }); }, LAYER_CHUNK_STATISTICS_INTERVAL)); constructor(rpc: RPC, options: any) { super(rpc, options); this.queueManager = (<ChunkQueueManager>rpc.get(options['chunkQueueManager'])).addRef(); // Update chunk priorities periodically after GPU memory changes to ensure layer chunk // statistics are updated. this.registerDisposer(this.queueManager.gpuMemoryChanged.add(this.registerCancellable(throttle( () => this.scheduleUpdateChunkPriorities(), LAYER_CHUNK_STATISTICS_INTERVAL, {leading: false, trailing: true})))); for (let tier = ChunkPriorityTier.FIRST_TIER; tier <= ChunkPriorityTier.LAST_TIER; ++tier) { if (tier === ChunkPriorityTier.RECENT) { continue; } this.existingTierChunks[tier] = []; } } scheduleUpdateChunkPriorities() { if (this.updatePending === null) { this.updatePending = setTimeout(this.recomputeChunkPriorities_.bind(this), 0); } } registerLayer(layer: ChunkRenderLayerBackend) { const generation = this.recomputeChunkPriorities.count; if (layer.chunkManagerGeneration !== generation) { layer.chunkManagerGeneration = generation; this.layers.push(layer); layer.numVisibleChunksAvailable = 0; layer.numVisibleChunksNeeded = 0; layer.numPrefetchChunksAvailable = 0; layer.numPrefetchChunksNeeded = 0; } } private recomputeChunkPriorities_() { this.updatePending = null; this.layers.length = 0; this.recomputeChunkPriorities.dispatch(); this.recomputeChunkPrioritiesLate.dispatch(); this.updateQueueState([ChunkPriorityTier.VISIBLE, ChunkPriorityTier.PREFETCH]); this.sendLayerChunkStatistics(); } /** * @param chunk * @param tier New priority tier. Must not equal ChunkPriorityTier.RECENT. * @param priority Priority within tier. * @param toFrontend true if the chunk should be moved to the frontend when ready. */ requestChunk(chunk: Chunk, tier: ChunkPriorityTier, priority: number, toFrontend = true) { if (!Number.isFinite(priority)) { // Non-finite priority indicates a bug. debugger; return; } if (tier === ChunkPriorityTier.RECENT) { throw new Error('Not going to request a chunk with the RECENT tier'); } chunk.newlyRequestedToFrontend = chunk.newlyRequestedToFrontend || toFrontend; if (chunk.newPriorityTier === ChunkPriorityTier.RECENT) { this.newTierChunks.push(chunk); } const newPriorityTier = chunk.newPriorityTier; if (tier < newPriorityTier || (tier === newPriorityTier && priority > chunk.newPriority)) { chunk.newPriorityTier = tier; chunk.newPriority = priority; } } /** * Update queue state to reflect updated contents of the specified priority tiers. Existing * chunks within those tiers not present in this.newTierChunks will be moved to the RECENT tier * (and removed if in the QUEUED state). */ updateQueueState(tiers: ChunkPriorityTier[]) { let existingTierChunks = this.existingTierChunks; let queueManager = this.queueManager; for (let tier of tiers) { let chunks = existingTierChunks[tier]; if (DEBUG_CHUNK_UPDATES) { console.log(`existingTierChunks[${ChunkPriorityTier[tier]}].length=${chunks.length}`); } for (let chunk of chunks) { if (chunk.newPriorityTier === ChunkPriorityTier.RECENT) { // Downgrade the priority of this chunk. queueManager.performChunkPriorityUpdate(chunk); } } chunks.length = 0; } let newTierChunks = this.newTierChunks; for (let chunk of newTierChunks) { queueManager.performChunkPriorityUpdate(chunk); existingTierChunks[chunk.priorityTier].push(chunk); } if (DEBUG_CHUNK_UPDATES) { console.log(`updateQueueState: newTierChunks.length = ${newTierChunks.length}`); } newTierChunks.length = 0; this.queueManager.scheduleUpdate(); } } /** * Mixin for adding a `parameters` member to a ChunkSource, and for registering the shared object * type based on the `RPC_ID` member of the Parameters class. */ export function WithParameters<Parameters, TBase extends {new (...args: any[]): SharedObject}>( Base: TBase, parametersConstructor: ChunkSourceParametersConstructor<Parameters>) { @registerSharedObjectOwner(parametersConstructor.RPC_ID) class C extends Base { parameters: Parameters; constructor(...args: any[]) { super(...args); const options = args[1]; this.parameters = options['parameters']; } } return C; } /** * Interface that represents shared objects that request chunks from a ChunkManager. */ export interface ChunkRequester extends SharedObject { chunkManager: ChunkManager; } /** * Mixin that adds a chunkManager property initialized from the RPC-supplied options. * * The resultant class implements `ChunkRequester`. */ export function withChunkManager<T extends {new (...args: any[]): SharedObject}>(Base: T) { return class extends Base implements ChunkRequester { chunkManager: ChunkManager; constructor(...args: any[]) { super(...args); const rpc: RPC = args[0]; const options = args[1]; // We don't increment the reference count, because our owner owns a reference to the // ChunkManager. this.chunkManager = <ChunkManager>rpc.get(options['chunkManager']); } }; } registerRPC(CHUNK_SOURCE_INVALIDATE_RPC_ID, function(x) { const source = <ChunkSource>this.get(x['id']); source.chunkManager.queueManager.invalidateSourceCache(source); }); registerPromiseRPC(REQUEST_CHUNK_STATISTICS_RPC_ID, function(x: {queue: number}) { const queue = this.get(x.queue) as ChunkQueueManager; const results = new Map<number, Float64Array>(); for (const source of queue.sources) { results.set(source.rpcId!, source.statistics); } return Promise.resolve({value: results}); });
the_stack
import { downgradeInjectable } from '@angular/upgrade/static'; import { EventEmitter, Injectable } from '@angular/core'; import cloneDeep from 'lodash/cloneDeep'; import isObject from 'lodash/isObject'; import { BaseTranslatableObject, InteractionRuleInputs } from 'interactions/rule-input-defs'; import { PlayerTranscriptService } from 'pages/exploration-player-page/services/player-transcript.service'; import { StateCard } from 'domain/state_card/state-card.model'; import { WrittenTranslation } from 'domain/exploration/WrittenTranslationObjectFactory'; import { SubtitledHtml } from 'domain/exploration/subtitled-html.model'; import { Schema } from 'services/schema-default-value.service'; import { SchemaConstants } from 'components/forms/schema-based-editors/schema.constants'; import { InteractionSpecsConstants, InteractionSpecsKey } from 'pages/interaction-specs.constants'; import { WrittenTranslations } from 'domain/exploration/WrittenTranslationsObjectFactory'; import { SubtitledUnicode } from 'domain/exploration/SubtitledUnicodeObjectFactory'; import { ExtensionTagAssemblerService } from 'services/extension-tag-assembler.service'; import { InteractionCustomizationArgs } from 'interactions/customization-args-defs'; @Injectable({ providedIn: 'root' }) export class ContentTranslationManagerService { // This is initialized using the class initialization method. // and we need to do non-null assertion, for more information see // https://github.com/oppia/oppia/wiki/Guide-on-defining-types#ts-7-1 private explorationLanguageCode!: string; private onStateCardContentUpdateEmitter: EventEmitter<void> = ( new EventEmitter()); // The 'originalTranscript' is a copy of the transcript in the exploration // language in it's initial state. private originalTranscript: StateCard[] = []; constructor( private playerTranscriptService: PlayerTranscriptService, private extensionTagAssemblerService: ExtensionTagAssemblerService ) {} setOriginalTranscript(explorationLanguageCode: string): void { this.explorationLanguageCode = explorationLanguageCode; this.originalTranscript = cloneDeep( this.playerTranscriptService.transcript); } get onStateCardContentUpdate(): EventEmitter<void> { return this.onStateCardContentUpdateEmitter; } /** * This method replaces the translatable content inside the player transcript * service's StateCards. If the language code is set back to the original * exploration language, the original transcript in the exploration language * is restored, since it was previously modified from switching to another * language previously. Note that learners can only freely switch content * languages when they are on the first state and have not entered an answer * yet (so, there are no response pairs), otherwise they will have to refresh * the page and restart the exploration. * @param {string} languageCode The language code to display translations for. */ displayTranslations(languageCode: string): void { const cards = this.playerTranscriptService.transcript; if (languageCode === this.explorationLanguageCode) { this.playerTranscriptService.restoreImmutably(this.originalTranscript); } else { cards.forEach( card => this._displayTranslationsForCard(card, languageCode)); } this.onStateCardContentUpdateEmitter.emit(); } getTranslatedHtml( writtenTranslations: WrittenTranslations, languageCode: string, content: SubtitledHtml ): string { if (!content.contentId) { throw new Error('Content ID does not exist'); } const writtenTranslation = writtenTranslations.translationsMapping[ content.contentId][languageCode]; if (!writtenTranslation) { return content.html; } const translationText = writtenTranslation.getTranslation(); // The isString() check is needed for the TypeScript compiler to narrow the // type down from string|string[] to string. See "Using type predicates" at // https://www.typescriptlang.org/docs/handbook/2/narrowing.html // for more information. if (this._isString(translationText) && this._isValidStringTranslation(writtenTranslation)) { return translationText; } return content.html; } _swapContent( writtenTranslations: WrittenTranslations, languageCode: string, content: SubtitledHtml|SubtitledUnicode ): void { if (!content.contentId) { throw new Error('Content ID does not exist'); } const writtenTranslation: WrittenTranslation | null = ( writtenTranslations.translationsMapping[content.contentId][languageCode]); if ( !writtenTranslation || !this._isValidStringTranslation(writtenTranslation) ) { return; } let valueName = ''; // Note: The content can only be of type SubtitledHtml|SubtitledUnicode. if (content instanceof SubtitledHtml) { valueName = '_html'; } else if (content instanceof SubtitledUnicode) { valueName = '_unicode'; } Object.defineProperty(content, valueName, { value: writtenTranslation.translation }); } _displayTranslationsForCard(card: StateCard, languageCode: string): void { const writtenTranslations = card.writtenTranslations; const contentTranslation = writtenTranslations.translationsMapping[ card.contentId][languageCode]; const contentTranslationText = ( contentTranslation && contentTranslation.getTranslation()); // The isString() check is needed for the TypeScript compiler to narrow the // type down from string|string[] to string. See "Using type predicates" at // https://www.typescriptlang.org/docs/handbook/2/narrowing.html // for more information. if (this._isString(contentTranslationText) && this._isValidStringTranslation(contentTranslation)) { card.contentHtml = contentTranslationText; } card.getHints().forEach(hint => this._swapContent( writtenTranslations, languageCode, hint.hintContent)); const solution = card.getSolution(); if (solution !== null) { this._swapContent( writtenTranslations, languageCode, solution.explanation); } const defaultOutcome = card.getInteraction().defaultOutcome; if (defaultOutcome) { this._swapContent( writtenTranslations, languageCode, defaultOutcome.feedback); } const answerGroups = card.getInteraction().answerGroups; answerGroups.forEach(answerGroup => { this._swapContent( writtenTranslations, languageCode, answerGroup.outcome.feedback); }); if (card.getInteraction().id) { this._swapContentInCustomizationArgs(card, languageCode); this._swapContentInRules(card, languageCode); } } _swapContentInCustomizationArgs(card: StateCard, languageCode: string): void { const interactionId = card.getInteractionId(); const caValues = card.getInteraction().customizationArgs; const writtenTranslations = card.writtenTranslations; let traverseSchemaAndSwapTranslatableContent = ( value: Object | Object[], schema: Schema ): void => { const schemaIsSubtitledHtml = ( schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM && schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_HTML); const schemaIsSubtitledUnicode = ( schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM && schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_UNICODE ); if (schemaIsSubtitledHtml || schemaIsSubtitledUnicode) { this._swapContent( writtenTranslations, languageCode, value as SubtitledHtml|SubtitledUnicode); } else if (schema.type === SchemaConstants.SCHEMA_KEY_LIST) { (value as Object[]).forEach( item => traverseSchemaAndSwapTranslatableContent( item, schema.items as Schema)); } else if (schema.type === SchemaConstants.SCHEMA_TYPE_DICT) { schema.properties.forEach(property => { const name = property.name as keyof typeof value; traverseSchemaAndSwapTranslatableContent( value[name], property.schema); }); } }; const caSpecs = InteractionSpecsConstants.INTERACTION_SPECS[ interactionId as InteractionSpecsKey ].customization_arg_specs; for (const caSpec of caSpecs) { const name = caSpec.name as keyof InteractionCustomizationArgs; if (caValues.hasOwnProperty(name)) { const attr = caValues[name] as {value: Object}; traverseSchemaAndSwapTranslatableContent( attr.value, caSpec.schema as Schema); } } const element = new DOMParser().parseFromString( card.getInteractionHtml(), 'text/html' ).body; this.extensionTagAssemblerService.formatCustomizationArgAttrs( element, caValues); card.setInteractionHtml(element.outerHTML); } _swapContentInRules(card: StateCard, languageCode: string): void { const writtenTranslations = card.writtenTranslations; const CONTENT_ID_KEY = 'contentId'; const answerGroups = card.getInteraction().answerGroups; answerGroups.forEach(answerGroup => { answerGroup.rules.forEach(rule => { for (var key in rule.inputs) { let ruleInputValue = rule.inputs[key]; if (this._isTranslatableObject(ruleInputValue)) { const writtenTranslation = writtenTranslations.translationsMapping[ ruleInputValue.contentId as string ][languageCode]; // There must be at least one translation. if ( !writtenTranslation || writtenTranslation.translation.length === 0 ) { continue; } let ruleInputValueKeys = Object.keys(ruleInputValue); // Remove the 'contentId' key. let contentIdIndex = ruleInputValueKeys.indexOf(CONTENT_ID_KEY); ruleInputValueKeys.splice(contentIdIndex, 1); // Retrieve the value corresponding to the other key. let nonContentIdKey = ( ruleInputValueKeys[0] as keyof BaseTranslatableObject); ruleInputValue[nonContentIdKey] = ( writtenTranslation.translation as string); } } }); }); } _isTranslatableObject( ruleInputValue: InteractionRuleInputs): ruleInputValue is BaseTranslatableObject { return isObject(ruleInputValue) && 'contentId' in ruleInputValue; } _isString(translation: string|string[]): translation is string { return (typeof translation === 'string'); } _isValidStringTranslation(writtenTranslation: WrittenTranslation): boolean { return ( writtenTranslation !== undefined && this._isString(writtenTranslation.translation) && writtenTranslation.translation !== '' && writtenTranslation.needsUpdate === false); } } angular.module('oppia').factory( 'ContentTranslationManagerService', downgradeInjectable(ContentTranslationManagerService));
the_stack
* ## Controlled vs. uncontrolled * * This hook acts as a hybrid between a controlled and uncontrolled component; * it will copy through any configuration changes to the underlying CodeMirror * instance, but the it will still let the user make changes even if you don't * handle the events. This lets the editor immediately display changes, ensuring * there's minimal input delay. * * ## Docs * * CodeMirror stores undo history, current selection and cursor position in a * "Doc" object -- along with the actual text. If you're sharing the editor over * multiple different files, the hook needs to swap these doc objects objects * out as you change between files. * * To help keep track of this, the hook allows you to pass in a string to the * `doc` property with the current document's filename. The hook will create * store docs internally for each file. */ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react' // CAUTION: do not add imports, or you'll break SSR. This is used for types, // but real imports should be handled through the importCodeMirror() option. import {} from 'codemirror' // React currently throws a warning when using useLayoutEffect on the server. // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. We need useLayoutEffect because we want // `connect` to perform sync updates to a ref to save the latest props after // a render is actually committed to the DOM. // https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85#gistcomment-2911761 const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect export interface UseCodeMirrorOptions { autoCursor?: boolean // default: true autoScroll?: boolean // default: false cursor?: CodeMirror.Position doc?: CodeMirror.Doc docName?: string scroll?: SetScrollOptions selection?: { ranges: Array<SetSelectionOptions>; focus?: boolean } value: string config?: CodeMirror.EditorConfiguration onBlur?: () => void onChange?: ( value: string, docName: string | undefined, changes: CodeMirror.EditorChange[], doc: CodeMirror.Doc, ) => void onCursor?: (data: CodeMirror.Position) => void onFocus?: () => void onGutterClick?: (lineNumber: number, gutter: string, event: Event) => void onScroll?: (scrollInfo: CodeMirror.ScrollInfo) => void onSelection?: (data: any) => void onViewportChange?: (start: number, end: number) => void // Only used on initial run importCodeMirror?: () => Promise<any> importCodeMirrorAddons?: () => Promise<any> } export interface SetScrollOptions { x?: number | null y?: number | null } export interface SetSelectionOptions { anchor: CodeMirror.Position head: CodeMirror.Position } export type CodeMirrorRefFunction = { bivarianceHack(instance: HTMLElement | null): void }['bivarianceHack'] export interface ReactCodeMirror { config: CodeMirror.EditorConfiguration editor?: CodeMirror.Editor focus(): void ref: CodeMirrorRefFunction } export function useCodeMirror( unmemoizedOptions: UseCodeMirrorOptions, ): ReactCodeMirror { const config = useEditorConfiguration( unmemoizedOptions.config, unmemoizedOptions.docName, ) const options = useMemo( () => ({ ...unmemoizedOptions, config, }), [config, unmemoizedOptions], ) const initialOptionsRef = useRef(options) const instanceRef = useRef<CodeMirrorInstance | null>(null) const externalRef = useRef<CodeMirrorRefFunction>() const nodePromiseRef = useRef<Promise<HTMLElement>>() if (!externalRef.current) { nodePromiseRef.current = new Promise(resolve => { externalRef.current = element => { if (element) { resolve(element) } } }) } useIsomorphicLayoutEffect(() => { if (instanceRef.current) { instanceRef.current.update(options) } else { initialOptionsRef.current = options } }) useEffect(() => { const importCodeMirror = options.importCodeMirror || defaultImportCodeMirror const importCodeMirrorAddons = options.importCodeMirrorAddons || defaultImportCodeMirrorAddons let isMounted = true Promise.all([ nodePromiseRef.current!, importCodeMirror(), importCodeMirrorAddons(), ]).then(([node, CodeMirror]) => { if (isMounted) { instanceRef.current = new CodeMirrorInstance( CodeMirror, node, initialOptionsRef.current, ) } }) return () => { isMounted = false if (instanceRef.current) { instanceRef.current.dispose() } } // eslint-disable-next-line }, []) const editor = (instanceRef.current && instanceRef.current.editor) || undefined return { config, editor, focus: useCallback(() => editor && editor.focus(), [editor]), ref: externalRef.current!, } } // --- export interface CodeMirrorConstructor { new ( callback: (host: HTMLElement) => void, options?: CodeMirror.EditorConfiguration, ): CodeMirror.Editor Doc: any defaults: any } interface PreservedOptions { cursor: CodeMirror.Position | null } interface EditorConfigurationWithMode extends CodeMirror.EditorConfiguration { mode: string } interface CodeMirrorInstanceOptions extends UseCodeMirrorOptions { config: EditorConfigurationWithMode } class CodeMirrorInstance { CodeMirror: CodeMirrorConstructor docs: { [pathname: string]: CodeMirror.Doc } editor: CodeMirror.Editor options: CodeMirrorInstanceOptions constructor( CodeMirror: CodeMirrorConstructor, placeholderNode: HTMLElement, options: CodeMirrorInstanceOptions, ) { this.CodeMirror = CodeMirror this.docs = {} this.options = options const editor = (this.editor = new CodeMirror( (editorNode: Node) => placeholderNode.parentNode!.replaceChild(editorNode, placeholderNode), options.config, )) this.updateDocIfRequired() editor.on('blur', this.handleBlur) editor.on('changes', this.handleChanges) editor.on('scroll', this.handleScroll) editor.on('cursor', this.handleCursor) editor.on('focus', this.handleFocus) editor.on('gutterClick', this.handleGutterClick) editor.on('beforeSelectionChange', this.handleSelection) editor.on('viewportChange', this.handleViewportChange) } dispose() { // is there a lighter-weight way to remove the cm instance? if (this.editor) { // Need to swap out the old doc, otherwise it can't be used again on // future codemirror instances. this.editor.swapDoc(new this.CodeMirror.Doc('')) delete this.editor delete this.CodeMirror } } update(options: CodeMirrorInstanceOptions) { const oldOptions = options this.options = options // Switch out the doc if required const doc = this.updateDocIfRequired() const preserved: PreservedOptions = { cursor: null } if (!options.autoCursor && options.autoCursor !== undefined) { preserved.cursor = this.editor.getDoc().getCursor() } // If a new value has been set, and it differs from the editor's current // value, then set it in the editor. let didUpdateValue = false if ( options.value !== undefined && normalizeLineEndings(this.editor.getValue()) !== normalizeLineEndings(options.value) && (!oldOptions || oldOptions.value !== options.value) ) { this.editor.setValue(options.value) didUpdateValue = true } // Update any editor config options that have changed const configKeys = Object.keys( this.options.config, ) as (keyof EditorConfigurationWithMode)[] const configDelta = configKeys.filter( key => this.editor.getOption(key) !== this.options.config[key], ) configDelta.forEach(key => { this.editor.setOption(key, this.options.config[key]) }) // Update selection if required if (didUpdateValue && options.selection && options.selection.ranges) { doc.setSelections(options.selection.ranges) if (options.selection.focus) { this.editor.focus() } } // Update cursor position if required if (options.cursor) { if (this.editor.getOption('autofocus')) { this.editor.focus() } doc.setCursor( preserved.cursor || options.cursor, undefined, options.autoScroll ? undefined : { scroll: false }, ) } // Update scroll if required if (options.scroll) { this.editor.scrollTo(options.scroll.x, options.scroll.y) } } // Returns true if the doc was updated private updateDocIfRequired() { let { config: { mode }, doc, docName, value, } = this.options if (!docName) { docName = '' } if (!doc) { doc = this.docs[docName] if (!doc) { doc = this.docs[docName] = new this.CodeMirror.Doc(value, mode) } } this.docs[docName] = doc! if (doc !== this.editor.getDoc()) { this.editor.swapDoc(doc!) } return doc! } private handleBlur = () => { if (this.options.onBlur) { this.options.onBlur() } } private handleChanges = ( editor: CodeMirror.Editor, changes: CodeMirror.EditorChange[], ) => { // Ignore changes caused by this component if (changes.length === 1 && changes[0].origin === 'setValue') { return } if (!this.options.config.readOnly && this.options.onChange) { this.options.onChange( editor.getValue(), this.options.docName, changes, editor.getDoc(), ) } } private handleCursor = (editor: CodeMirror.Editor) => { if (this.options.onCursor) { this.options.onCursor(editor.getDoc().getCursor()) } } private handleFocus = () => { if (this.options.onFocus) { this.options.onFocus() } } private handleGutterClick = ( editor: CodeMirror.Editor, lineNumber: number, gutter: string, event: Event, ) => { if (this.options.onGutterClick) { this.options.onGutterClick(lineNumber, gutter, event) } } private handleScroll = (editor: CodeMirror.Editor) => { if (this.options.onScroll) { this.options.onScroll(editor.getScrollInfo()) } } private handleSelection = (editor: CodeMirror.Editor, data: any) => { if (this.options.onSelection) { this.options.onSelection(data) } } private handleViewportChange = ( editor: CodeMirror.Editor, from: number, to: number, ) => { if (this.options.onViewportChange) { this.options.onViewportChange(from, to) } } } const modeAliases: { [name: string]: string } = { js: 'jsx', html: 'htmlmixed', md: 'markdown', mdx: 'markdown', scss: 'text/x-scss', } function defaultImportCodeMirror() { // CodeMirror crashes when loaded without a DOM, so let's avoid loading // it on the server. let codeMirrorPromise = typeof navigator === 'undefined' ? Promise.resolve([]) : Promise.all([ import('codemirror'), ]) return codeMirrorPromise.then(([{ default: codeMirror }]) => codeMirror) } function defaultImportCodeMirrorAddons() { return Promise.all([ import('codemirror/mode/jsx/jsx'), import('codemirror/mode/css/css'), import('codemirror/mode/markdown/markdown'), import('codemirror/mode/htmlmixed/htmlmixed'), import('codemirror/keymap/sublime'), import('codemirror/addon/comment/comment'), import('codemirror/addon/edit/closebrackets'), import('codemirror/addon/edit/matchbrackets'), import('codemirror/addon/edit/matchtags'), import('codemirror/addon/fold/xml-fold'), import('codemirror/addon/scroll/simplescrollbars'), import('codemirror/addon/selection/active-line'), import('codemirror/addon/search/search'), import('codemirror/addon/search/searchcursor'), import('codemirror/addon/dialog/dialog'), ]) } function getDefaultMode(docName?: string) { return docName && docName.split('.').reverse()[0] } const defaultMatchTagsConfig = { bothTags: true } const defaultExtraKeysConfig = { Tab: (cm: CodeMirror.Editor) => { var spaces = Array(cm.getOption('indentUnit')! + 1).join(' ') cm.getDoc().replaceSelection(spaces) }, 'Cmd-/': (cm: CodeMirror.Editor) => { cm.getDoc() .listSelections() .forEach(() => { cm.toggleComment({ indent: true }) }) }, } function useEditorConfiguration( { extraKeys, mode, ...rest }: CodeMirror.EditorConfiguration = {}, docName?: string, ): EditorConfigurationWithMode { const extraKeysConfig = useMemo( () => typeof extraKeys === 'string' ? extraKeys : { ...defaultExtraKeysConfig, ...extraKeys, }, [extraKeys], ) if (!mode) { mode = getDefaultMode(docName) } return useMemo( () => ({ autoCloseBrackets: true, indentWithTabs: false, extraKeys: extraKeysConfig, keyMap: 'sublime', matchBrackets: true, matchTags: defaultMatchTagsConfig, mode: modeAliases[mode] || mode, scrollbarStyle: 'simple', smartIndent: false, styleActiveLine: true, tabSize: 2, ...rest, }), // eslint-disable-next-line react-hooks/exhaustive-deps [extraKeys, mode, ...Object.values(rest)], ) } function normalizeLineEndings(str: string) { if (!str) return str return str.replace(/\r\n|\r/g, '\n') }
the_stack
// Typescript defs adapted from draco3d emscripten IDL // https://raw.githubusercontent.com/google/draco/master/src/draco/javascript/emscripten/draco_web_decoder.idl // Interface exposed to emscripten's WebIDL Binder. // http://kripken.github.io/emscripten-site/docs/porting/connecting_cpp_and_javascript/WebIDL-Binder.html /* eslint-disable camelcase */ /** Draco3D untyped memory pointer */ type VoidPtr = any; // DRACO WEB DECODER IDL /** Draco3D geometry attribute type */ export enum draco_GeometryAttribute_Type { 'draco_GeometryAttribute::INVALID', 'draco_GeometryAttribute::POSITION', 'draco_GeometryAttribute::NORMAL', 'draco_GeometryAttribute::COLOR', 'draco_GeometryAttribute::TEX_COORD', 'draco_GeometryAttribute::GENERIC' } /** Draco3D encoded geometry type */ export enum draco_EncodedGeometryType { 'draco::INVALID_GEOMETRY_TYPE', 'draco::POINT_CLOUD', 'draco::TRIANGULAR_MESH' } /** Draco3D data type */ export enum draco_DataType { 'draco::DT_INVALID', 'draco::DT_INT8', 'draco::DT_UINT8', 'draco::DT_INT16', 'draco::DT_UINT16', 'draco::DT_INT32', 'draco::DT_UINT32', 'draco::DT_INT64', 'draco::DT_UINT64', 'draco::DT_FLOAT32', 'draco::DT_FLOAT64', 'draco::DT_BOOL', 'draco::DT_TYPES_COUNT' } /** Draco3D status code */ export enum draco_StatusCode { 'draco_Status::OK', 'draco_Status::DRACO_ERROR', 'draco_Status::IO_ERROR', 'draco_Status::INVALID_PARAMETER', 'draco_Status::UNSUPPORTED_VERSION', 'draco_Status::UNKNOWN_VERSION' } /** Draco3D decoder buffer allocated on emscripten heap */ export declare class DecoderBuffer { constructor(); Init(data: Int8Array, data_size: number): void; } /** Draco3D attribute transform data */ export declare class AttributeTransformData { constructor(); transform_type(): number; } /** Draco3D geometry attribute */ export declare class GeometryAttribute { constructor(); } /** Draco3D point attribute */ export declare class PointAttribute { ptr: VoidPtr; constructor(); size(): number; GetAttributeTransformData(): AttributeTransformData; // From GeometryAttribute attribute_type(): number; data_type(): number; num_components(): number; normalized(): boolean; byte_stride(): number; byte_offset(): number; unique_id(): number; } /** Draco3D attribute transform */ export declare class AttributeQuantizationTransform { constructor(); InitFromAttribute(att: PointAttribute): boolean; quantization_bits(): number; min_value(axis: number): number; range(): number; } /** Draco3D attribute transform */ export declare class AttributeOctahedronTransform { constructor(); InitFromAttribute(att: PointAttribute): boolean; quantization_bits(): number; } /** Draco3D point cloud */ export declare class PointCloud { ptr: VoidPtr; constructor(); num_attributes(): number; num_points(): number; } /** Draco3D mesh */ export declare class Mesh extends PointCloud { constructor(); num_faces(): number; } /** Draco3D metadata */ export declare class Metadata { ptr: VoidPtr; constructor(); } /** Draco3D status */ export declare class Status { constructor(); code(): draco_StatusCode; ok(): boolean; error_msg(): string; } /** Draco3D Float32Array allocated on the emscripten heap */ export declare class DracoFloat32Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D Int8Array allocated on the emscripten heap */ export declare class DracoInt8Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D Uint8Array allocated on the emscripten heap */ export declare class DracoUInt8Array { GetValue(index: number): number; size(): number; } /** Draco3D Int16Array allocated on the emscripten heap */ export declare class DracoInt16Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D Uint16Array allocated on the emscripten heap */ export declare class DracoUInt16Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D Int32Array allocated on the emscripten heap */ export declare class DracoInt32Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D Uint32Array allocated on the emscripten heap */ export declare class DracoUInt32Array { constructor(); GetValue(index: number): number; size(): number; } /** Draco3D metadata querier */ export declare class MetadataQuerier { constructor(); HasEntry(metadata: Metadata, entry_name: string): string; GetIntEntry(metadata: Metadata, entry_name: string); GetIntEntryArray(metadata: Metadata, entry_name: string, out_values: DracoInt32Array); GetDoubleEntry(metadata: Metadata, entry_name: string): number; GetStringEntry(metadata: Metadata, entry_name: string): string; NumEntries(metadata: Metadata): number; GetEntryName(metadata: Metadata, entry_id: number): string; } /** * Draco3D Decoder class */ export declare class Decoder { constructor(); GetEncodedGeometryType(in_buffer: DecoderBuffer): draco_EncodedGeometryType; DecodeBufferToPointCloud(in_buffer: DecoderBuffer, out_point_cloud: PointCloud): Status; DecodeBufferToMesh(in_buffer: DecoderBuffer, out_mesh: Mesh): Status; GetAttributeId(pc: PointCloud, type: draco_GeometryAttribute_Type): number; GetAttributeIdByName(pc: PointCloud, name: string): number; GetAttributeIdByMetadataEntry(pc: PointCloud, name: string, value: string): number; GetAttribute(pc: PointCloud, att_id: number): PointAttribute; GetAttributeByUniqueId(pc: PointCloud, unique_id: number): PointAttribute; GetMetadata(pc: PointCloud): Metadata; GetAttributeMetadata(pc: PointCloud, att_id: number): Metadata; GetFaceFromMesh(m: Mesh, face_id: number, out_values: DracoInt32Array): boolean; GetTriangleStripsFromMesh(m: Mesh, strip_values: DracoInt32Array); GetTrianglesUInt16Array(m: Mesh, out_size: number, out_values: VoidPtr): boolean; GetTrianglesUInt32Array(m: Mesh, out_size: number, out_values: VoidPtr): boolean; GetAttributeFloat(pa: PointAttribute, att_index: number, out_values: DracoFloat32Array): boolean; GetAttributeFloatForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoFloat32Array ): boolean; // Deprecated, use GetAttributeInt32ForAllPoints instead. GetAttributeIntForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoInt32Array ): boolean; GetAttributeInt8ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoInt8Array ): boolean; GetAttributeUInt8ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoUInt8Array ): boolean; GetAttributeInt16ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoInt16Array ): boolean; GetAttributeUInt16ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoUInt16Array ): boolean; GetAttributeInt32ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoInt32Array ): boolean; GetAttributeUInt32ForAllPoints( pc: PointCloud, pa: PointAttribute, out_values: DracoUInt32Array ): boolean; GetAttributeDataArrayForAllPoints( pc: PointCloud, pa: PointAttribute, data_type: draco_DataType, out_size: number, out_values: VoidPtr ): boolean; SkipAttributeTransform(att_type: draco_GeometryAttribute_Type): void; } // DRACO WEB ENCODER IDL /** Draco3D metadata builder */ export declare class MetadataBuilder { constructor(); AddStringEntry(metadata: Metadata, entry_name: string, entry_value: string); AddIntEntry(metadata: Metadata, entry_name: string, entry_value: number); AddDoubleEntry(metadata: Metadata, entry_name: string, entry_value: number); AddIntEntryArray( metadata: Metadata, entry_name: string, entry_value: Int32Array, num_values: number ); } /** Draco3D point cloud builder */ export declare class PointCloudBuilder { constructor(); PointCloudBuilder(): void; AddFloatAttribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Float32Array ); AddInt8Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Int8Array ); AddUInt8Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Uint8Array ); AddInt16Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Int16Array ); AddUInt16Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Uint16Array ); AddInt32Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Int32Array ); AddUInt32Attribute( pc: PointCloud, type: draco_GeometryAttribute_Type, num_vertices: number, num_components: number, att_values: Uint32Array ); AddMetadata(pc: PointCloud, metadata: Metadata): boolean; SetMetadataForAttribute(pc: PointCloud, attribute_id: number, metadata: Metadata); } /** Draco3D mesh builder */ export declare class MeshBuilder extends PointCloudBuilder { constructor(); AddFacesToMesh(mesh: Mesh, num_faces: number, faces: number[]): boolean; } /** Draco3D encoder */ export declare class Encoder { constructor(); Encoder(): void; SetEncodingMethod(method: number): void; SetAttributeQuantization(type: draco_GeometryAttribute_Type, quantization_bits: number); SetAttributeExplicitQuantization( type: draco_GeometryAttribute_Type, quantization_bits: number, num_components: number, origin: number[], range: number ); SetSpeedOptions(encoding_speed: number, decoding_speed: number): void; SetTrackEncodedProperties(flag: boolean): void; EncodeMeshToDracoBuffer(mesh: Mesh, encoded_data: DracoInt8Array); EncodePointCloudToDracoBuffer( pc: PointCloud, deduplicate_values: boolean, encoded_data: DracoInt8Array ); // Returns the number of encoded points or faces from the last Encode // operation. Returns 0 if SetTrackEncodedProperties was not set to true. GetNumberOfEncodedPoints(): number; GetNumberOfEncodedFaces(): number; } /** Draco3D expert encoder */ export declare class ExpertEncoder { constructor(); ExpertEncoder(pc: PointCloud): void; SetEncodingMethod(method: number): void; SetAttributeQuantization(att_id: number, quantization_bits: number); SetAttributeExplicitQuantization( att_id: number, quantization_bits: number, num_components: number, origin: number[], range: number ); SetSpeedOptions(encoding_speed: number, decoding_speed: number): void; SetTrackEncodedProperties(flag: boolean): void; EncodeToDracoBuffer(deduplicate_values: boolean, encoded_data: DracoInt8Array); // Returns the number of encoded points or faces from the last Encode // operation. Returns 0 if SetTrackEncodedProperties was not set to true. GetNumberOfEncodedPoints(): number; GetNumberOfEncodedFaces(): number; } /** Draco3D module interface */ export interface Draco3D { // ENUMS // draco_EncodedGeometryType readonly INVALID_GEOMETRY_TYPE: draco_EncodedGeometryType; readonly POINT_CLOUD: draco_EncodedGeometryType; readonly TRIANGULAR_MESH: draco_EncodedGeometryType; // enum draco_GeometryAttribute_Type readonly INVALID: draco_GeometryAttribute_Type; readonly POSITION: draco_GeometryAttribute_Type; readonly NORMAL: draco_GeometryAttribute_Type; readonly COLOR: draco_GeometryAttribute_Type; readonly TEX_COORD: draco_GeometryAttribute_Type; readonly GENERIC: draco_GeometryAttribute_Type; // enum draco_DataType readonly DT_INVALID: draco_DataType; readonly DT_INT8: draco_DataType; readonly DT_UINT8: draco_DataType; readonly DT_INT16: draco_DataType; readonly DT_UINT16: draco_DataType; readonly DT_INT32: draco_DataType; readonly DT_UINT32: draco_DataType; readonly DT_INT64: draco_DataType; readonly DT_UINT64: draco_DataType; readonly DT_FLOAT32: draco_DataType; readonly DT_FLOAT64: draco_DataType; readonly DT_BOOL: draco_DataType; readonly DT_TYPES_COUNT: draco_DataType; readonly Mesh: typeof Mesh; readonly PointCloud: typeof PointCloud; readonly Metadata: typeof Metadata; readonly Encoder: typeof Encoder; readonly MeshBuilder: typeof MeshBuilder; readonly MetadataBuilder: typeof MetadataBuilder; readonly MetadataQuerier: typeof MetadataQuerier; readonly Decoder: typeof Decoder; readonly DecoderBuffer: typeof DecoderBuffer; readonly DracoFloat32Array: typeof DracoFloat32Array; readonly DracoInt8Array: typeof DracoInt8Array; readonly DracoUInt8Array: typeof DracoUInt8Array; readonly DracoInt16Array: typeof DracoInt16Array; readonly DracoUInt16Array: typeof DracoUInt16Array; readonly DracoInt32Array: typeof DracoInt32Array; readonly DracoUInt32Array: typeof DracoUInt32Array; readonly AttributeQuantizationTransform: typeof AttributeQuantizationTransform; // createEncoderModule(): Encoder; // createDecoderModule(): Decoder; destroy(resource: any): void; _malloc(byteLength: number): number; _free(ptr: number): void; HEAPF32: { buffer: ArrayBuffer; }; }
the_stack
import { QueryRunner } from "../../query-runner/QueryRunner.ts"; import { ObjectLiteral } from "../../common/ObjectLiteral.ts"; import { TableColumn } from "../../schema-builder/table/TableColumn.ts"; import { Table } from "../../schema-builder/table/Table.ts"; import { TableForeignKey } from "../../schema-builder/table/TableForeignKey.ts"; import { TableIndex } from "../../schema-builder/table/TableIndex.ts"; import {View} from "../../schema-builder/view/View.ts"; import { AggregationCursor, BulkWriteOpResultObject, ChangeStream, ChangeStreamOptions, Code, Collection, CollectionAggregationOptions, CollectionBulkWriteOptions, CollectionInsertManyOptions, CollectionInsertOneOptions, CollectionOptions, CollStats, CommandCursor, Cursor, Db, DeleteWriteOpResultObject, FindAndModifyWriteOpResultObject, FindOneAndReplaceOption, GeoHaystackSearchOptions, GeoNearOptions, InsertOneWriteOpResult, InsertWriteOpResult, MapReduceOptions, MongoCountPreferences, MongodbIndexOptions, OrderedBulkOperation, ParallelCollectionScanOptions, ReadPreference, ReplaceOneOptions, UnorderedBulkOperation, UpdateWriteOpResult } from "./typings.ts"; import { Connection } from "../../connection/Connection.ts"; import { ReadStream } from "../../platform/PlatformTools.ts"; import { MongoEntityManager } from "../../entity-manager/MongoEntityManager.ts"; import { SqlInMemory } from "../SqlInMemory.ts"; import { TableUnique } from "../../schema-builder/table/TableUnique.ts"; import { Broadcaster } from "../../subscriber/Broadcaster.ts"; import { TableCheck } from "../../schema-builder/table/TableCheck.ts"; import { TableExclusion } from "../../schema-builder/table/TableExclusion.ts"; /** * Runs queries on a single MongoDB connection. */ export class MongoQueryRunner implements QueryRunner { // ------------------------------------------------------------------------- // Public Implemented Properties // ------------------------------------------------------------------------- /** * Connection used by this query runner. */ connection: Connection; /** * Broadcaster used on this query runner to broadcast entity events. */ broadcaster: Broadcaster; /** * Entity manager working only with current query runner. */ manager!: MongoEntityManager; /** * Indicates if connection for this query runner is released. * Once its released, query runner cannot run queries anymore. * Always false for mongodb since mongodb has a single query executor instance. */ isReleased = false; /** * Indicates if transaction is active in this query executor. * Always false for mongodb since mongodb does not support transactions. */ isTransactionActive = false; /** * Stores temporarily user data. * Useful for sharing data with subscribers. */ data = {}; /** * All synchronized tables in the database. */ loadedTables!: Table[]; /** * All synchronized views in the database. */ loadedViews!: View[]; /** * Real database connection from a connection pool used to perform queries. */ databaseConnection: Db; // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(connection: Connection, databaseConnection: Db) { this.connection = connection; this.databaseConnection = databaseConnection; this.broadcaster = new Broadcaster(this); } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Creates a cursor for a query that can be used to iterate over results from MongoDB. */ cursor(collectionName: string, query?: ObjectLiteral): Cursor<any> { return this.getCollection(collectionName).find(query || {}); } /** * Execute an aggregation framework pipeline against the collection. */ aggregate(collectionName: string, pipeline: ObjectLiteral[], options?: CollectionAggregationOptions): AggregationCursor<any> { return this.getCollection(collectionName).aggregate(pipeline, options); } /** * Perform a bulkWrite operation without a fluent API. */ async bulkWrite(collectionName: string, operations: ObjectLiteral[], options?: CollectionBulkWriteOptions): Promise<BulkWriteOpResultObject> { return await this.getCollection(collectionName).bulkWrite(operations, options); } /** * Count number of matching documents in the db to a query. */ async count(collectionName: string, query?: ObjectLiteral, options?: MongoCountPreferences): Promise<any> { return await this.getCollection(collectionName).countDocuments(query || {}, options); } /** * Creates an index on the db and collection. */ async createCollectionIndex(collectionName: string, fieldOrSpec: string | any, options?: MongodbIndexOptions): Promise<string> { return await this.getCollection(collectionName).createIndex(fieldOrSpec, options); } /** * Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. * Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. */ async createCollectionIndexes(collectionName: string, indexSpecs: ObjectLiteral[]): Promise<void> { return await this.getCollection(collectionName).createIndexes(indexSpecs); } /** * Delete multiple documents on MongoDB. */ async deleteMany(collectionName: string, query: ObjectLiteral, options?: CollectionOptions): Promise<DeleteWriteOpResultObject> { return await this.getCollection(collectionName).deleteMany(query, options); } /** * Delete a document on MongoDB. */ async deleteOne(collectionName: string, query: ObjectLiteral, options?: CollectionOptions): Promise<DeleteWriteOpResultObject> { return await this.getCollection(collectionName).deleteOne(query, options); } /** * The distinct command returns returns a list of distinct values for the given key across a collection. */ async distinct(collectionName: string, key: string, query: ObjectLiteral, options?: { readPreference?: ReadPreference | string }): Promise<any> { return await this.getCollection(collectionName).distinct(key, query, options); } /** * Drops an index from this collection. */ async dropCollectionIndex(collectionName: string, indexName: string, options?: CollectionOptions): Promise<any> { return await this.getCollection(collectionName).dropIndex(indexName, options); } /** * Drops all indexes from the collection. */ async dropCollectionIndexes(collectionName: string): Promise<any> { return await this.getCollection(collectionName).dropIndexes(); } /** * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. */ async findOneAndDelete(collectionName: string, query: ObjectLiteral, options?: { projection?: Object, sort?: Object, maxTimeMS?: number }): Promise<FindAndModifyWriteOpResultObject> { return await this.getCollection(collectionName).findOneAndDelete(query, options); } /** * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. */ async findOneAndReplace(collectionName: string, query: ObjectLiteral, replacement: Object, options?: FindOneAndReplaceOption): Promise<FindAndModifyWriteOpResultObject> { return await this.getCollection(collectionName).findOneAndReplace(query, replacement, options); } /** * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. */ async findOneAndUpdate(collectionName: string, query: ObjectLiteral, update: Object, options?: FindOneAndReplaceOption): Promise<FindAndModifyWriteOpResultObject> { return await this.getCollection(collectionName).findOneAndUpdate(query, update, options); } /** * Execute a geo search using a geo haystack index on a collection. */ async geoHaystackSearch(collectionName: string, x: number, y: number, options?: GeoHaystackSearchOptions): Promise<any> { return await this.getCollection(collectionName).geoHaystackSearch(x, y, options); } /** * Execute the geoNear command to search for items in the collection. */ async geoNear(collectionName: string, x: number, y: number, options?: GeoNearOptions): Promise<any> { return await this.getCollection(collectionName).geoNear(x, y, options); } /** * Run a group command across a collection. */ async group(collectionName: string, keys: Object | Array<any> | Function | Code, condition: Object, initial: Object, reduce: Function | Code, finalize: Function | Code, command: boolean, options?: { readPreference?: ReadPreference | string }): Promise<any> { return await this.getCollection(collectionName).group(keys, condition, initial, reduce, finalize, command, options); } /** * Retrieve all the indexes on the collection. */ async collectionIndexes(collectionName: string): Promise<any> { return await this.getCollection(collectionName).indexes(); } /** * Retrieve all the indexes on the collection. */ async collectionIndexExists(collectionName: string, indexes: string | string[]): Promise<boolean> { return await this.getCollection(collectionName).indexExists(indexes); } /** * Retrieves this collections index info. */ async collectionIndexInformation(collectionName: string, options?: { full: boolean }): Promise<any> { return await this.getCollection(collectionName).indexInformation(options); } /** * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. */ initializeOrderedBulkOp(collectionName: string, options?: CollectionOptions): OrderedBulkOperation { return this.getCollection(collectionName).initializeOrderedBulkOp(options); } /** * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. */ initializeUnorderedBulkOp(collectionName: string, options?: CollectionOptions): UnorderedBulkOperation { return this.getCollection(collectionName).initializeUnorderedBulkOp(options); } /** * Inserts an array of documents into MongoDB. */ async insertMany(collectionName: string, docs: ObjectLiteral[], options?: CollectionInsertManyOptions): Promise<InsertWriteOpResult> { return await this.getCollection(collectionName).insertMany(docs, options); } /** * Inserts a single document into MongoDB. */ async insertOne(collectionName: string, doc: ObjectLiteral, options?: CollectionInsertOneOptions): Promise<InsertOneWriteOpResult> { return await this.getCollection(collectionName).insertOne(doc, options); } /** * Returns if the collection is a capped collection. */ async isCapped(collectionName: string): Promise<any> { return await this.getCollection(collectionName).isCapped(); } /** * Get the list of all indexes information for the collection. */ listCollectionIndexes(collectionName: string, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor { return this.getCollection(collectionName).listIndexes(options); } /** * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. */ async mapReduce(collectionName: string, map: Function | string, reduce: Function | string, options?: MapReduceOptions): Promise<any> { return await this.getCollection(collectionName).mapReduce(map, reduce, options); } /** * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. * There are no ordering guarantees for returned results. */ async parallelCollectionScan(collectionName: string, options?: ParallelCollectionScanOptions): Promise<Cursor<any>[]> { return await this.getCollection(collectionName).parallelCollectionScan(options); } /** * Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. */ async reIndex(collectionName: string): Promise<any> { return await this.getCollection(collectionName).reIndex(); } /** * Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. */ async rename(collectionName: string, newName: string, options?: { dropTarget?: boolean }): Promise<Collection<any>> { return await this.getCollection(collectionName).rename(newName, options); } /** * Replace a document on MongoDB. */ async replaceOne(collectionName: string, query: ObjectLiteral, doc: ObjectLiteral, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult> { return await this.getCollection(collectionName).replaceOne(query, doc, options); } /** * Get all the collection statistics. */ async stats(collectionName: string, options?: { scale: number }): Promise<CollStats> { return await this.getCollection(collectionName).stats(options); } /** * Watching new changes as stream. */ watch(collectionName: string, pipeline?: Object[], options?: ChangeStreamOptions): ChangeStream { return this.getCollection(collectionName).watch(pipeline, options); } /** * Update multiple documents on MongoDB. */ async updateMany(collectionName: string, query: ObjectLiteral, update: ObjectLiteral, options?: { upsert?: boolean, w?: any, wtimeout?: number, j?: boolean }): Promise<UpdateWriteOpResult> { return await this.getCollection(collectionName).updateMany(query, update, options); } /** * Update a single document on MongoDB. */ async updateOne(collectionName: string, query: ObjectLiteral, update: ObjectLiteral, options?: ReplaceOneOptions): Promise<UpdateWriteOpResult> { return await this.getCollection(collectionName).updateOne(query, update, options); } // ------------------------------------------------------------------------- // Public Implemented Methods (from QueryRunner) // ------------------------------------------------------------------------- /** * Removes all collections from the currently connected database. * Be careful with using this method and avoid using it in production or migrations * (because it can clear all your database). */ async clearDatabase(): Promise<void> { await this.databaseConnection.db(this.connection.driver.database!).dropDatabase(); } /** * For MongoDB database we don't create connection, because its single connection already created by a driver. */ async connect(): Promise<any> { } /** * For MongoDB database we don't release connection, because its single connection. */ async release(): Promise<void> { // releasing connection are not supported by mongodb driver, so simply don't do anything here } /** * Starts transaction. */ async startTransaction(): Promise<void> { // transactions are not supported by mongodb driver, so simply don't do anything here } /** * Commits transaction. */ async commitTransaction(): Promise<void> { // transactions are not supported by mongodb driver, so simply don't do anything here } /** * Rollbacks transaction. */ async rollbackTransaction(): Promise<void> { // transactions are not supported by mongodb driver, so simply don't do anything here } /** * Executes a given SQL query. */ query(query: string, parameters?: any[]): Promise<any> { throw new Error(`Executing SQL query is not supported by MongoDB driver.`); } /** * Returns raw data stream. */ stream(query: string, parameters?: any[], onEnd?: Function, onError?: Function): Promise<ReadStream> { throw new Error(`Stream is not supported by MongoDB driver. Use watch instead.`); } /** * Insert a new row with given values into the given table. * Returns value of inserted object id. async insert(collectionName: string, keyValues: ObjectLiteral): Promise<any> { // todo: fix any const results = await this.databaseConnection .collection(collectionName) .insertOne(keyValues); const generatedMap = this.connection.getMetadata(collectionName).objectIdColumn!.createValueMap(results.insertedId); return { result: results, generatedMap: generatedMap }; }*/ /** * Updates rows that match given conditions in the given table. async update(collectionName: string, valuesMap: ObjectLiteral, conditions: ObjectLiteral): Promise<any> { // todo: fix any await this.databaseConnection .collection(collectionName) .updateOne(conditions, valuesMap); }*/ /** * Deletes from the given table by a given conditions. async delete(collectionName: string, conditions: ObjectLiteral|ObjectLiteral[]|string, maybeParameters?: any[]): Promise<any> { // todo: fix any if (typeof conditions === "string") throw new Error(`String condition is not supported by MongoDB driver.`); await this.databaseConnection .collection(collectionName) .deleteOne(conditions); }*/ /** * Returns all available database names including system databases. */ async getDatabases(): Promise<string[]> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Returns all available schema names including system schemas. * If database parameter specified, returns schemas of that database. */ async getSchemas(database?: string): Promise<string[]> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Loads given table's data from the database. */ async getTable(collectionName: string): Promise<Table | undefined> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Loads all tables (with given names) from the database and creates a Table from them. */ async getTables(collectionNames: string[]): Promise<Table[]> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Loads given views's data from the database. */ async getView(collectionName: string): Promise<View | undefined> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Loads all views (with given names) from the database and creates a Table from them. */ async getViews(collectionNames: string[]): Promise<View[]> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Checks if database with the given name exist. */ async hasDatabase(database: string): Promise<boolean> { throw new Error(`Check database queries are not supported by MongoDB driver.`); } /** * Checks if schema with the given name exist. */ async hasSchema(schema: string): Promise<boolean> { throw new Error(`Check schema queries are not supported by MongoDB driver.`); } /** * Checks if table with the given name exist in the database. */ async hasTable(collectionName: string): Promise<boolean> { throw new Error(`Check schema queries are not supported by MongoDB driver.`); } /** * Checks if column with the given name exist in the given table. */ async hasColumn(tableOrName: Table | string, columnName: string): Promise<boolean> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a database if it's not created. */ async createDatabase(database: string): Promise<void> { throw new Error(`Database create queries are not supported by MongoDB driver.`); } /** * Drops database. */ async dropDatabase(database: string, ifExist?: boolean): Promise<void> { throw new Error(`Database drop queries are not supported by MongoDB driver.`); } /** * Creates a new table schema. */ async createSchema(schema: string, ifNotExist?: boolean): Promise<void> { throw new Error(`Schema create queries are not supported by MongoDB driver.`); } /** * Drops table schema. */ async dropSchema(schemaPath: string, ifExist?: boolean): Promise<void> { throw new Error(`Schema drop queries are not supported by MongoDB driver.`); } /** * Creates a new table from the given table and columns inside it. */ async createTable(table: Table): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops the table. */ async dropTable(tableName: Table | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new view. */ async createView(view: View): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops the view. */ async dropView(target: View|string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Renames the given table. */ async renameTable(oldTableOrName: Table | string, newTableOrName: Table | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new column from the column in the table. */ async addColumn(tableOrName: Table | string, column: TableColumn): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new columns from the column in the table. */ async addColumns(tableOrName: Table | string, columns: TableColumn[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Renames column in the given table. */ async renameColumn(tableOrName: Table | string, oldTableColumnOrName: TableColumn | string, newTableColumnOrName: TableColumn | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Changes a column in the table. */ async changeColumn(tableOrName: Table | string, oldTableColumnOrName: TableColumn | string, newColumn: TableColumn): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Changes a column in the table. */ async changeColumns(tableOrName: Table | string, changedColumns: { newColumn: TableColumn, oldColumn: TableColumn }[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops column in the table. */ async dropColumn(tableOrName: Table | string, columnOrName: TableColumn | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops the columns in the table. */ async dropColumns(tableOrName: Table | string, columns: TableColumn[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new primary key. */ async createPrimaryKey(tableOrName: Table | string, columnNames: string[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Updates composite primary keys. */ async updatePrimaryKeys(tableOrName: Table | string, columns: TableColumn[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops a primary key. */ async dropPrimaryKey(tableOrName: Table | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new unique constraint. */ async createUniqueConstraint(tableOrName: Table | string, uniqueConstraint: TableUnique): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new unique constraints. */ async createUniqueConstraints(tableOrName: Table | string, uniqueConstraints: TableUnique[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops an unique constraint. */ async dropUniqueConstraint(tableOrName: Table | string, uniqueOrName: TableUnique | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops an unique constraints. */ async dropUniqueConstraints(tableOrName: Table | string, uniqueConstraints: TableUnique[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new check constraint. */ async createCheckConstraint(tableOrName: Table | string, checkConstraint: TableCheck): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new check constraints. */ async createCheckConstraints(tableOrName: Table | string, checkConstraints: TableCheck[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops check constraint. */ async dropCheckConstraint(tableOrName: Table | string, checkOrName: TableCheck | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops check constraints. */ async dropCheckConstraints(tableOrName: Table | string, checkConstraints: TableCheck[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new exclusion constraint. */ async createExclusionConstraint(tableOrName: Table | string, exclusionConstraint: TableExclusion): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new exclusion constraints. */ async createExclusionConstraints(tableOrName: Table | string, exclusionConstraints: TableExclusion[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops exclusion constraint. */ async dropExclusionConstraint(tableOrName: Table | string, exclusionOrName: TableExclusion | string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops exclusion constraints. */ async dropExclusionConstraints(tableOrName: Table | string, exclusionConstraints: TableExclusion[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new foreign key. */ async createForeignKey(tableOrName: Table | string, foreignKey: TableForeignKey): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new foreign keys. */ async createForeignKeys(tableOrName: Table | string, foreignKeys: TableForeignKey[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops a foreign key from the table. */ async dropForeignKey(tableOrName: Table | string, foreignKey: TableForeignKey): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops a foreign keys from the table. */ async dropForeignKeys(tableOrName: Table | string, foreignKeys: TableForeignKey[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new index. */ async createIndex(tableOrName: Table | string, index: TableIndex): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Creates a new indices */ async createIndices(tableOrName: Table | string, indices: TableIndex[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops an index from the table. */ async dropIndex(collectionName: string, indexName: string): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops an indices from the table. */ async dropIndices(tableOrName: Table | string, indices: TableIndex[]): Promise<void> { throw new Error(`Schema update queries are not supported by MongoDB driver.`); } /** * Drops collection. */ async clearTable(collectionName: string): Promise<void> { await this.databaseConnection .db(this.connection.driver.database!) .dropCollection(collectionName); } /** * Enables special query runner mode in which sql queries won't be executed, * instead they will be memorized into a special variable inside query runner. * You can get memorized sql using getMemorySql() method. */ enableSqlMemory(): void { throw new Error(`This operation is not supported by MongoDB driver.`); } /** * Disables special query runner mode in which sql queries won't be executed * started by calling enableSqlMemory() method. * * Previously memorized sql will be flushed. */ disableSqlMemory(): void { throw new Error(`This operation is not supported by MongoDB driver.`); } /** * Flushes all memorized sqls. */ clearSqlMemory(): void { throw new Error(`This operation is not supported by MongoDB driver.`); } /** * Gets sql stored in the memory. Parameters in the sql are already replaced. */ getMemorySql(): SqlInMemory { throw new Error(`This operation is not supported by MongoDB driver.`); } /** * Executes up sql queries. */ async executeMemoryUpSql(): Promise<void> { throw new Error(`This operation is not supported by MongoDB driver.`); } /** * Executes down sql queries. */ async executeMemoryDownSql(): Promise<void> { throw new Error(`This operation is not supported by MongoDB driver.`); } // ------------------------------------------------------------------------- // Protected Methods // ------------------------------------------------------------------------- /** * Gets collection from the database with a given name. */ protected getCollection(collectionName: string): Collection<any> { return this.databaseConnection.db(this.connection.driver.database!).collection(collectionName); } }
the_stack
import { Loader, LoadingManager, Scene, BufferGeometry, Material, Object3D, Mesh, BufferAttribute, } from '../../../src/Three'; declare class IFCLoader extends Loader { ifcManager: IFCManager; constructor(manager?: LoadingManager); load( url: any, onLoad: (ifc: IFCModel) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void, ): void; parse(buffer: ArrayBuffer): Promise<IFCModel>; } export interface LoaderSettings { COORDINATE_TO_ORIGIN: boolean; USE_FAST_BOOLS: boolean; CIRCLE_SEGMENTS_LOW?: number; CIRCLE_SEGMENTS_MEDIUM?: number; CIRCLE_SEGMENTS_HIGH?: number; } export class IFCManager { private state; private BVH; private parser; private subsets; private properties; private types; private hider; parse(buffer: ArrayBuffer): Promise<IFCModel>; /** * Sets the relative path of web-ifc.wasm file in the project. * Beware: you **must** serve this file in your page; this means * that you have to copy this files from *node_modules/web-ifc* * to your deployment directory. * * If you don't use this methods, * IFC.js assumes that you are serving it in the root directory. * * Example if web-ifc.wasm is in dist/wasmDir: * `ifcLoader.setWasmPath("dist/wasmDir/");` * * @path Relative path to web-ifc.wasm. */ setWasmPath(path: string): void; /** * Applies a configuration for [web-ifc](https://ifcjs.github.io/info/docs/Guide/web-ifc/Introduction). */ applyWebIfcConfig(settings: LoaderSettings): void; /** * Enables the JSON mode (which consumes way less memory) and eliminates the WASM data. * Only use this in the following scenarios: * - If you don't need to access the properties of the IFC * - If you will provide the properties as JSON. */ useJSONData(useJSON?: boolean): void; /** * Adds the properties of a model as JSON data. * @modelID ID of the IFC model. * @data: data as an object where the keys are the expressIDs and the values the properties. */ addModelJSONData( modelID: number, data: { [id: number]: JSONObject; }, ): void; /** * Completely releases the WASM memory, thus drastically decreasing the memory use of the app. * Only use this in the following scenarios: * - If you don't need to access the properties of the IFC * - If you will provide the properties as JSON. */ disposeMemory(): void; /** * Makes object picking a lot faster * Courtesy of gkjohnson's [work](https://github.com/gkjohnson/three-mesh-bvh). * Import these objects from his library and pass them as arguments. IFC.js takes care of the rest! */ setupThreeMeshBVH(computeBoundsTree: any, disposeBoundsTree: any, acceleratedRaycast: any): void; /** * Closes the specified model and deletes it from the [scene](https://threejs.org/docs/#api/en/scenes/Scene). * @modelID ID of the IFC model. * @scene Scene where the model is (if it's located in a scene). */ close(modelID: number, scene?: Scene): void; /** * Gets the **Express ID** to which the given face belongs. * This ID uniquely identifies this entity within this IFC file. * @geometry The geometry of the IFC model. * @faceIndex The index of the face of a geometry.You can easily get this index using the [Raycaster](https://threejs.org/docs/#api/en/core/Raycaster). */ getExpressId(geometry: BufferGeometry, faceIndex: number): number | undefined; /** * Returns all items of the specified type. You can import * the types from *web-ifc*. * * Example to get all the standard walls of a project: * ```js * import { IFCWALLSTANDARDCASE } from 'web-ifc'; * const walls = ifcLoader.getAllItemsOfType(IFCWALLSTANDARDCASE); * ``` * @modelID ID of the IFC model. * @ifcType type of IFC items to get. * @verbose If false (default), this only gets IDs. If true, this also gets the native properties of all the fetched items. */ getAllItemsOfType(modelID: number, type: number, verbose: boolean): any[]; /** * Gets the native properties of the given element. * @modelID ID of the IFC model. * @id Express ID of the element. * @recursive Wether you want to get the information of the referenced elements recursively. */ getItemProperties(modelID: number, id: number, recursive?: boolean): any; /** * Gets the [property sets](https://standards.buildingsmart.org/IFC/DEV/IFC4_2/FINAL/HTML/schema/ifckernel/lexical/ifcpropertyset.htm) * assigned to the given element. * @modelID ID of the IFC model. * @id Express ID of the element. * @recursive If true, this gets the native properties of the referenced elements recursively. */ getPropertySets(modelID: number, id: number, recursive?: boolean): any[]; /** * Gets the properties of the type assigned to the element. * For example, if applied to a wall (IfcWall), this would get back the information * contained in the IfcWallType assigned to it, if any. * @modelID ID of the IFC model. * @id Express ID of the element. * @recursive If true, this gets the native properties of the referenced elements recursively. */ getTypeProperties(modelID: number, id: number, recursive?: boolean): any[]; /** * Gets the materials assigned to the given element. * @modelID ID of the IFC model. * @id Express ID of the element. * @recursive If true, this gets the native properties of the referenced elements recursively. */ getMaterialsProperties(modelID: number, id: number, recursive?: boolean): any[]; /** * Gets the ifc type of the specified item. * @modelID ID of the IFC model. * @id Express ID of the element. */ getIfcType(modelID: number, id: number): string; /** * Gets the spatial structure of the project. The * [spatial structure](https://standards.buildingsmart.org/IFC/DEV/IFC4_2/FINAL/HTML/schema/ifcproductextension/lexical/ifcspatialstructureelement.htm) * is the hierarchical structure that organizes every IFC project (all physical items * are referenced to an element of the spatial structure). It is formed by * one IfcProject that contains one or more IfcSites, that contain one or more * IfcBuildings, that contain one or more IfcBuildingStoreys, that contain * one or more IfcSpaces. * @modelID ID of the IFC model. */ getSpatialStructure(modelID: number): { expressID: number; type: string; children: never[]; }; /** * Gets the mesh of the subset with the specified [material](https://threejs.org/docs/#api/en/materials/Material). * If no material is given, this returns the subset with the original materials. * @modelID ID of the IFC model. * @material Material assigned to the subset (if any). */ getSubset(modelID: number, material?: Material): Mesh | null; /** * Removes the specified subset. * @modelID ID of the IFC model. * @parent The parent where the subset is (can be any `THREE.Object3D`). * @material Material assigned to the subset, if any. */ removeSubset(modelID: number, parent?: Object3D, material?: Material): void; /** * Creates a new geometric subset. * @config A configuration object with the following options: * - **scene**: `THREE.Object3D` where the model is located. * - **modelID**: ID of the model. * - **ids**: Express IDs of the items of the model that will conform the subset. * - **removePrevious**: wether to remove the previous subset of this model with this material. * - **material**: (optional) wether to apply a material to the subset */ createSubset(config: HighlightConfigOfModel): void | Mesh; /** * Hides the selected items in the specified model * @modelID ID of the IFC model. * @ids Express ID of the elements. */ hideItems(modelID: number, ids: number[]): void; /** * Hides all the items of the specified model * @modelID ID of the IFC model. */ hideAllItems(modelID: number): void; /** * Shows all the items of the specified model * @modelID ID of the IFC model. * @ids Express ID of the elements. */ showItems(modelID: number, ids: number[]): void; /** * Shows all the items of the specified model * @modelID ID of the IFC model. */ showAllItems(modelID: number): void; } /** * Represents an IFC model. This object is returned by the `IFCLoader` after loading an IFC. * @geometry `THREE.Buffergeometry`, see Three.js documentation. * @materials `THREE.Material[]`, see Three.js documentation. * @manager contains all the logic to work with IFC. */ export class IFCModel extends Mesh { modelID: number; ifcManager: IFCManager | null; /** * @deprecated `IfcModel` is already a mesh; you can place it in the scene directly. */ mesh: this; setIFCManager(manager: IFCManager): void; /** * @deprecated Use `IfcModel.ifcManager.setWasmPath` instead. * * Sets the relative path of web-ifc.wasm file in the project. * Beware: you **must** serve this file in your page; this means * that you have to copy this files from *node_modules/web-ifc* * to your deployment directory. * * If you don't use this methods, * IFC.js assumes that you are serving it in the root directory. * * Example if web-ifc.wasm is in dist/wasmDir: * `ifcLoader.setWasmPath("dist/wasmDir/");` * * @path Relative path to web-ifc.wasm. */ setWasmPath(path: string): void; /** * @deprecated Use `IfcModel.ifcManager.close` instead. * * Closes the specified model and deletes it from the [scene](https://threejs.org/docs/#api/en/scenes/Scene). * @scene Scene where the model is (if it's located in a scene). */ close(scene?: Scene): void; /** * @deprecated Use `IfcModel.ifcManager.getExpressId` instead. * * Gets the **Express ID** to which the given face belongs. * This ID uniquely identifies this entity within this IFC file. * @geometry The geometry of the IFC model. * @faceIndex The index of the face of a geometry.You can easily get this index using the [Raycaster](https://threejs.org/docs/#api/en/core/Raycaster). */ getExpressId(geometry: BufferGeometry, faceIndex: number): number | undefined; /** * @deprecated Use `IfcModel.ifcManager.getAllItemsOfType` instead. * * Returns all items of the specified type. You can import * the types from *web-ifc*. * * Example to get all the standard walls of a project: * ```js * import { IFCWALLSTANDARDCASE } from 'web-ifc'; * const walls = ifcLoader.getAllItemsOfType(IFCWALLSTANDARDCASE); * ``` * @ifcType The type of IFC items to get. * @verbose If false (default), this only gets IDs. If true, this also gets the native properties of all the fetched items. */ getAllItemsOfType(type: number, verbose: boolean): any[]; /** * @deprecated Use `IfcModel.ifcManager.getItemProperties` instead. * * Gets the native properties of the given element. * @id Express ID of the element. * @recursive Wether you want to get the information of the referenced elements recursively. */ getItemProperties(id: number, recursive?: boolean): any; /** * @deprecated Use `IfcModel.ifcManager.getPropertySets` instead. * * Gets the [property sets](https://standards.buildingsmart.org/IFC/DEV/IFC4_2/FINAL/HTML/schema/ifckernel/lexical/ifcpropertyset.htm) * assigned to the given element. * @id Express ID of the element. * @recursive If true, this gets the native properties of the referenced elements recursively. */ getPropertySets(id: number, recursive?: boolean): any[]; /** * @deprecated Use `IfcModel.ifcManager.getTypeProperties` instead. * * Gets the properties of the type assigned to the element. * For example, if applied to a wall (IfcWall), this would get back the information * contained in the IfcWallType assigned to it, if any. * @id Express ID of the element. * @recursive If true, this gets the native properties of the referenced elements recursively. */ getTypeProperties(id: number, recursive?: boolean): any[]; /** * @deprecated Use `IfcModel.ifcManager.getIfcType` instead. * * Gets the ifc type of the specified item. * @id Express ID of the element. */ getIfcType(id: number): string; /** * @deprecated Use `IfcModel.ifcManager.getSpatialStructure` instead. * * Gets the spatial structure of the project. The * [spatial structure](https://standards.buildingsmart.org/IFC/DEV/IFC4_2/FINAL/HTML/schema/ifcproductextension/lexical/ifcspatialstructureelement.htm) * is the hierarchical structure that organizes every IFC project (all physical items * are referenced to an element of the spatial structure). It is formed by * one IfcProject that contains one or more IfcSites, that contain one or more * IfcBuildings, that contain one or more IfcBuildingStoreys, that contain * one or more IfcSpaces. */ getSpatialStructure(): { expressID: number; type: string; children: never[]; }; /** * @deprecated Use `IfcModel.ifcManager.getSubset` instead. * * Gets the mesh of the subset with the specified [material](https://threejs.org/docs/#api/en/materials/Material). * If no material is given, this returns the subset with the original materials. * @material Material assigned to the subset, if any. */ getSubset(material?: Material): Mesh | null; /** * @deprecated Use `IfcModel.ifcManager.removeSubset` instead. * * Removes the specified subset. * @parent The parent where the subset is (can be any `THREE.Object3D`). * @material Material assigned to the subset, if any. */ removeSubset(parent?: Object3D, material?: Material): void; /** * @deprecated Use `IfcModel.ifcManager.createSubset` instead. * * Creates a new geometric subset. * @config A configuration object with the following options: * - **scene**: `THREE.Object3D` where the model is located. * - **ids**: Express IDs of the items of the model that will conform the subset. * - **removePrevious**: Wether to remove the previous subset of this model with this material. * - **material**: (optional) Wether to apply a material to the subset */ createSubset(config: HighlightConfig): void | Mesh; /** * @deprecated Use `IfcModel.ifcManager.hideItems` instead. * * Hides the selected items in the specified model * @ids Express ID of the elements. */ hideItems(ids: number[]): void; /** * @deprecated Use `IfcModel.ifcManager.hideAllItems` instead. * * Hides all the items of the specified model */ hideAllItems(): void; /** * @deprecated Use `IfcModel.ifcManager.showItems` instead. * * Hides all the items of the specified model * @ids Express ID of the elements. */ showItems(ids: number[]): void; /** * @deprecated Use `IfcModel.ifcManager.showAllItems` instead. * * Shows all the items of the specified model */ showAllItems(): void; } export const IdAttrName = 'expressID'; export interface IdAttributeByMaterial { [id: number]: number; } export interface IdAttributesByMaterials { [materialID: string]: IdAttributeByMaterial; } export function merge(geoms: BufferGeometry[], createGroups?: boolean): BufferGeometry; export function newFloatAttr(data: any[], size: number): BufferAttribute; export function newIntAttr(data: any[], size: number): BufferAttribute; export interface HighlightConfig { scene: Object3D; ids: number[]; removePrevious: boolean; material?: Material; } export interface HighlightConfigOfModel extends HighlightConfig { modelID: number; } export const DEFAULT = 'default'; export interface SelectedItems { [matID: string]: { ids: Set<number>; mesh: Mesh; }; } export interface MapFaceindexID { [key: number]: number; } export interface IdGeometries { [expressID: number]: BufferGeometry; } export interface GeometriesByMaterial { material: Material; geometries: IdGeometries; } export interface GeometriesByMaterials { [materialID: string]: GeometriesByMaterial; } export interface TypesMap { [key: number]: number; } export interface IfcModel { modelID: number; mesh: IfcMesh; items: GeometriesByMaterials; types: TypesMap; jsonData: { [id: number]: JSONObject; }; } export interface JSONObject { expressID: number; type: string; [key: string]: any; } export interface IfcState { models: { [modelID: number]: IfcModel; }; api: IfcAPI; useJSON: boolean; webIfcSettings?: LoaderSettings; } export interface IfcMesh extends Mesh { modelID: number; } export interface Node { expressID: number; type: string; children: Node[]; } export interface pName { name: number; relating: string; related: string; key: string; } export const PropsNames: { aggregates: { name: number; relating: string; related: string; key: string; }; spatial: { name: number; relating: string; related: string; key: string; }; psets: { name: number; relating: string; related: string; key: string; }; materials: { name: number; relating: string; related: string; key: string; }; type: { name: number; relating: string; related: string; key: string; }; }; export interface IfcGeometry { GetVertexData(): number; GetVertexDataSize(): number; GetIndexData(): number; GetIndexDataSize(): number; } export interface RawLineData { ID: number; type: number; arguments: any[]; } export interface Vector<T> { get(index: number): T; size(): number; } export interface FlatMesh { geometries: Vector<PlacedGeometry>; expressID: number; } export interface PlacedGeometry { color: Color; geometryExpressID: number; flatTransformation: number[]; } export interface Color { x: number; y: number; z: number; w: number; } export class IfcAPI { wasmModule: any; fs: any; /** * Initializes the WASM module (WebIFCWasm), required before using any other functionality */ Init(): Promise<void>; /** * Opens a model and returns a modelID number * @data Buffer containing IFC data (bytes) * @data Settings settings for loading the model */ OpenModel(data: string | Uint8Array, settings?: LoaderSettings): number; /** * Creates a new model and returns a modelID number * @data Settings settings for generating data the model */ CreateModel(settings?: LoaderSettings): number; ExportFileAsIFC(modelID: number): Uint8Array; /** * Opens a model and returns a modelID number * @modelID Model handle retrieved by OpenModel, model must not be closed * @data Buffer containing IFC data (bytes) */ GetGeometry(modelID: number, geometryExpressID: number): IfcGeometry; GetLine(modelID: number, expressID: number, flatten?: boolean): any; WriteLine(modelID: number, lineObject: any): void; FlattenLine(modelID: number, line: any): void; GetRawLineData(modelID: number, expressID: number): RawLineData; WriteRawLineData(modelID: number, data: RawLineData): any; GetLineIDsWithType(modelID: number, type: number): Vector<number>; GetAllLines(modelID: number): Vector<number>; SetGeometryTransformation(modelID: number, transformationMatrix: number[]): void; GetVertexArray(ptr: number, size: number): Float32Array; GetIndexArray(ptr: number, size: number): Uint32Array; getSubArray(heap: any, startPtr: any, sizeBytes: any): any; /** * Closes a model and frees all related memory * @modelID Model handle retrieved by OpenModel, model must not be closed */ CloseModel(modelID: number): void; StreamAllMeshes(modelID: number, meshCallback: (mesh: FlatMesh) => void): void; /** * Checks if a specific model ID is open or closed * @modelID Model handle retrieved by OpenModel */ IsModelOpen(modelID: number): boolean; /** * Load all geometry in a model * @modelID Model handle retrieved by OpenModel */ LoadAllGeometry(modelID: number): Vector<FlatMesh>; /** * Load geometry for a single element * @modelID Model handle retrieved by OpenModel */ GetFlatMesh(modelID: number, expressID: number): FlatMesh; SetWasmPath(path: string): void; } export { IFCLoader };
the_stack
* @fileoverview Implements the CHTMLWrapper class * * @author dpvc@mathjax.org (Davide Cervone) */ import {OptionList} from '../../util/Options.js'; import * as LENGTHS from '../../util/lengths.js'; import {CommonWrapper, AnyWrapperClass, Constructor, StringMap} from '../common/Wrapper.js'; import {CHTML} from '../chtml.js'; import {CHTMLWrapperFactory} from './WrapperFactory.js'; import {BBox} from '../../util/BBox.js'; import {CHTMLFontData, CHTMLCharOptions, CHTMLDelimiterData} from './FontData.js'; export {Constructor, StringMap} from '../common/Wrapper.js'; /*****************************************************************/ /** * Some standard sizes to use in predefind CSS properties */ export const FONTSIZE: StringMap = { '70.7%': 's', '70%': 's', '50%': 'ss', '60%': 'Tn', '85%': 'sm', '120%': 'lg', '144%': 'Lg', '173%': 'LG', '207%': 'hg', '249%': 'HG' }; export const SPACE: StringMap = { /* tslint:disable:whitespace */ [LENGTHS.em(2/18)]: '1', [LENGTHS.em(3/18)]: '2', [LENGTHS.em(4/18)]: '3', [LENGTHS.em(5/18)]: '4', [LENGTHS.em(6/18)]: '5' /* tslint:enable */ }; /** * Shorthand for making a CHTMLWrapper constructor */ export type CHTMLConstructor<N, T, D> = Constructor<CHTMLWrapper<N, T, D>>; /*****************************************************************/ /** * The type of the CHTMLWrapper class (used when creating the wrapper factory for this class) */ export interface CHTMLWrapperClass extends AnyWrapperClass { kind: string; /** * If true, this causes a style for the node type to be generated automatically * that sets display:inline-block (as needed for the output for MmlNodes). */ autoStyle: boolean; } /*****************************************************************/ /** * The base CHTMLWrapper class * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class */ export class CHTMLWrapper<N, T, D> extends CommonWrapper< CHTML<N, T, D>, CHTMLWrapper<N, T, D>, CHTMLWrapperClass, CHTMLCharOptions, CHTMLDelimiterData, CHTMLFontData > { /** * The wrapper type */ public static kind: string = 'unknown'; /** * If true, this causes a style for the node type to be generated automatically * that sets display:inline-block (as needed for the output for MmlNodes). */ public static autoStyle = true; /** * @override */ protected factory: CHTMLWrapperFactory<N, T, D>; /** * @override */ public parent: CHTMLWrapper<N, T, D>; /** * @override */ public childNodes: CHTMLWrapper<N, T, D>[]; /** * The HTML element generated for this wrapped node */ public chtml: N = null; /*******************************************************************/ /** * Create the HTML for the wrapped node. * * @param {N} parent The HTML node where the output is added */ public toCHTML(parent: N) { const chtml = this.standardCHTMLnode(parent); for (const child of this.childNodes) { child.toCHTML(chtml); } } /*******************************************************************/ /** * Create the standard CHTML element for the given wrapped node. * * @param {N} parent The HTML element in which the node is to be created * @returns {N} The root of the HTML tree for the wrapped node's output */ protected standardCHTMLnode(parent: N): N { this.markUsed(); const chtml = this.createCHTMLnode(parent); this.handleStyles(); this.handleVariant(); this.handleScale(); this.handleColor(); this.handleSpace(); this.handleAttributes(); this.handlePWidth(); return chtml; } /** * Mark this class as having been typeset (so its styles will be output) */ public markUsed() { this.jax.wrapperUsage.add(this.kind); } /** * @param {N} parent The HTML element in which the node is to be created * @returns {N} The root of the HTML tree for the wrapped node's output */ protected createCHTMLnode(parent: N): N { const href = this.node.attributes.get('href'); if (href) { parent = this.adaptor.append(parent, this.html('a', {href: href})) as N; } this.chtml = this.adaptor.append(parent, this.html('mjx-' + this.node.kind)) as N; return this.chtml; } /** * Set the CSS styles for the chtml element */ protected handleStyles() { if (!this.styles) return; const styles = this.styles.cssText; if (styles) { this.adaptor.setAttribute(this.chtml, 'style', styles); const family = this.styles.get('font-family'); if (family) { this.adaptor.setStyle(this.chtml, 'font-family', 'MJXZERO, ' + family); } } } /** * Set the CSS for the math variant */ protected handleVariant() { if (this.node.isToken && this.variant !== '-explicitFont') { this.adaptor.setAttribute(this.chtml, 'class', (this.font.getVariant(this.variant) || this.font.getVariant('normal')).classes); } } /** * Set the (relative) scaling factor for the node */ protected handleScale() { this.setScale(this.chtml, this.bbox.rscale); } /** * @param {N} chtml The HTML node to scale * @param {number} rscale The relatie scale to apply * @return {N} The HTML node (for chaining) */ protected setScale(chtml: N, rscale: number): N { const scale = (Math.abs(rscale - 1) < .001 ? 1 : rscale); if (chtml && scale !== 1) { const size = this.percent(scale); if (FONTSIZE[size]) { this.adaptor.setAttribute(chtml, 'size', FONTSIZE[size]); } else { this.adaptor.setStyle(chtml, 'fontSize', size); } } return chtml; } /** * Add the proper spacing */ protected handleSpace() { for (const data of [[this.bbox.L, 'space', 'marginLeft'], [this.bbox.R, 'rspace', 'marginRight']]) { const [dimen, name, margin] = data as [number, string, string]; if (dimen) { const space = this.em(dimen); if (SPACE[space]) { this.adaptor.setAttribute(this.chtml, name, SPACE[space]); } else { this.adaptor.setStyle(this.chtml, margin, space); } } } } /** * Add the foreground and background colors * (Only look at explicit attributes, since inherited ones will * be applied to a parent element, and we will inherit from that) */ protected handleColor() { const attributes = this.node.attributes; const mathcolor = attributes.getExplicit('mathcolor') as string; const color = attributes.getExplicit('color') as string; const mathbackground = attributes.getExplicit('mathbackground') as string; const background = attributes.getExplicit('background') as string; if (mathcolor || color) { this.adaptor.setStyle(this.chtml, 'color', mathcolor || color); } if (mathbackground || background) { this.adaptor.setStyle(this.chtml, 'backgroundColor', mathbackground || background); } } /** * Copy RDFa, aria, and other tags from the MathML to the CHTML output nodes. * Don't copy those in the skipAttributes list, or anything that already exists * as a property of the node (e.g., no "onlick", etc.). If a name in the * skipAttributes object is set to false, then the attribute WILL be copied. * Add the class to any other classes already in use. */ protected handleAttributes() { const attributes = this.node.attributes; const defaults = attributes.getAllDefaults(); const skip = CHTMLWrapper.skipAttributes; for (const name of attributes.getExplicitNames()) { if (skip[name] === false || (!(name in defaults) && !skip[name] && !this.adaptor.hasAttribute(this.chtml, name))) { this.adaptor.setAttribute(this.chtml, name, attributes.getExplicit(name) as string); } } if (attributes.get('class')) { const names = (attributes.get('class') as string).trim().split(/ +/); for (const name of names) { this.adaptor.addClass(this.chtml, name); } } } /** * Handle the attributes needed for percentage widths */ protected handlePWidth() { if (this.bbox.pwidth) { if (this.bbox.pwidth === BBox.fullWidth) { this.adaptor.setAttribute(this.chtml, 'width', 'full'); } else { this.adaptor.setStyle(this.chtml, 'width', this.bbox.pwidth); } } } /*******************************************************************/ /** * @param {N} chtml The HTML node whose indentation is to be adjusted * @param {string} align The alignment for the node * @param {number} shift The indent (positive or negative) for the node */ protected setIndent(chtml: N, align: string, shift: number) { const adaptor = this.adaptor; if (align === 'center' || align === 'left') { const L = this.getBBox().L; adaptor.setStyle(chtml, 'margin-left', this.em(shift + L)); } if (align === 'center' || align === 'right') { const R = this.getBBox().R; adaptor.setStyle(chtml, 'margin-right', this.em(-shift + R)); } } /*******************************************************************/ /** * For debugging */ public drawBBox() { let {w, h, d, R} = this.getBBox(); const box = this.html('mjx-box', {style: { opacity: .25, 'margin-left': this.em(-w - R) }}, [ this.html('mjx-box', {style: { height: this.em(h), width: this.em(w), 'background-color': 'red' }}), this.html('mjx-box', {style: { height: this.em(d), width: this.em(w), 'margin-left': this.em(-w), 'vertical-align': this.em(-d), 'background-color': 'green' }}) ] as N[]); const node = this.chtml || this.parent.chtml; const size = this.adaptor.getAttribute(node, 'size'); if (size) { this.adaptor.setAttribute(box, 'size', size); } const fontsize = this.adaptor.getStyle(node, 'fontSize'); if (fontsize) { this.adaptor.setStyle(box, 'fontSize', fontsize); } this.adaptor.append(this.adaptor.parent(node), box); this.adaptor.setStyle(node, 'backgroundColor', '#FFEE00'); } /*******************************************************************/ /* * Easy access to some utility routines */ /** * @param {string} type The tag name of the HTML node to be created * @param {OptionList} def The properties to set for the created node * @param {(N|T)[]} content The child nodes for the created HTML node * @return {N} The generated HTML tree */ public html(type: string, def: OptionList = {}, content: (N | T)[] = []): N { return this.jax.html(type, def, content); } /** * @param {string} text The text from which to create an HTML text node * @return {T} The generated text node with the given text */ public text(text: string): T { return this.jax.text(text); } /** * @param {number} n A unicode code point to be converted to a character className reference. * @return {string} The className for the character */ protected char(n: number): string { return this.font.charSelector(n).substr(1); } }
the_stack
import * as zlib from 'zlib'; import { PassThrough } from 'stream'; import { getLocal } from "../../.."; import { expect, fetch, Headers, delay, nodeOnly } from "../../test-utils"; describe("Body matching", function () { let server = getLocal(); beforeEach(() => server.start()); afterEach(() => server.stop()); describe("for exact strings", () => { beforeEach(async () => { await server.forPost("/") .withBody('should-match') .thenReply(200, 'matched'); }); it("should match requests by body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'should-match' })).to.have.responseText('matched'); }); it("shouldn't match requests with the wrong body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'should-not-match' })).not.to.have.responseText('matched'); }); it("should match requests ignoring content types", async () => { return expect(fetch(server.url, { method: 'POST', body: 'should-match', headers: new Headers({ 'Content-Type': 'application/json' }), })).to.have.responseText('matched'); }); it("should not match requests with no body", async () => { return expect(fetch(server.url, { method: 'POST' })).not.to.have.responseText("matched"); }); it("should not match requests that only contain the given body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'this-should-match-nothing' })).not.to.have.responseText('matched'); }); }); describe("for regexes", () => { beforeEach(async () => { await server.forPost("/") .withBody(/"username": "test"/gi) .thenReply(200, 'matched'); }); it('should match requests by regular expressions', async () => { return expect(fetch(server.url, { method: 'POST', body: '{"username": "test", "passwd": "test"}' })).to.have.responseText('matched'); }); it('should not match requests with non-matching regular expressions', async () => { return expect(fetch(server.url, { method: 'POST', body: '{"user": "test", "passwd": "test"}' })).not.to.have.responseText('matched'); }); it("should not match requests with no body", async () => { return expect(fetch(server.url, { method: 'POST' })).not.to.have.responseText("matched"); }); }); describe("for included strings", () => { beforeEach(async () => { await server.forPost("/") .withBodyIncluding('should-match') .thenReply(200, 'matched'); }); it("should match requests with an exactly matching body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'should-match' })).to.have.responseText('matched'); }); it("should match requests that contain the given body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'this-should-match-as-included' })).to.have.responseText('matched'); }); it("shouldn't match requests with the wrong body", async () => { return expect(fetch(server.url, { method: 'POST', body: 'should-not-match' })).not.to.have.responseText('matched'); }); it("should match requests ignoring content types", async () => { return expect(fetch(server.url, { method: 'POST', body: 'this-should-match', headers: new Headers({ 'Content-Type': 'application/json' }), })).to.have.responseText('matched'); }); it("should not match requests with no body", async () => { return expect(fetch(server.url, { method: 'POST' })).not.to.have.responseText("matched"); }); it("should match gzip-encoded requests that contain the given body", async () => { return expect(fetch(server.url, { method: 'POST', headers: { 'content-encoding': 'gzip' }, body: zlib.gzipSync( 'this-should-match-as-included' ) })).to.have.responseText('matched'); }); }); describe("for exact JSON", () => { beforeEach(async () => { await server.forPost("/") .withJsonBody({ "username": "test" }) .thenReply(200, 'matched'); }); it("should match requests with the expected body", () => { return expect(fetch(server.url, { method: 'POST', body: '{"username": "test"}' })).to.have.responseText('matched'); }); it("should not match requests with no body", () => { return expect(fetch(server.url, { method: 'POST' })).not.to.have.responseText("matched"); }); it("should not match requests with non-parseable bodies", () => { return expect(fetch(server.url, { method: 'POST', body: '???{"username": "test"}', })).not.to.have.responseText("matched"); }); it("should not match requests with extra fields", () => { return expect(fetch(server.url, { method: 'POST', body: '{"username": "test", "passwd": "test"}' })).not.to.have.responseText('matched'); }); }); describe("for fuzzy JSON", () => { beforeEach(async () => { await server.forPost("/") .withJsonBodyIncluding({ "username": "test", "values": [1] }) .thenReply(200, 'matched'); }); it("should match requests with the exact expected body", () => { return expect(fetch(server.url, { method: 'POST', body: '{ "username": "test", "values": [1] }' })).to.have.responseText('matched'); }); it("should not match requests with no body", () => { return expect(fetch(server.url, { method: 'POST' })).not.to.have.responseText("matched"); }); it("should not match requests with non-parseable bodies", () => { return expect(fetch(server.url, { method: 'POST', body: '???{ "username": "test", "values": [1] }', })).not.to.have.responseText("matched"); }); it("should match requests with extra fields", () => { return expect(fetch(server.url, { method: 'POST', body: '{"username": "test", "values": [1], "passwd": "test"}' })).to.have.responseText('matched'); }); it("should match requests with extra array values", () => { return expect(fetch(server.url, { method: 'POST', body: '{"username": "test", "values": [1, 2, 3]}' })).to.have.responseText('matched'); }); }); nodeOnly(() => { // TODO: This could be tested in a browser, but it's just a bit fiddly describe("when waiting for a body", function () { this.timeout(500); it("should short-circuit, not waiting, if another matcher fails", async () => { await server.forPut().thenReply(201, "Created"); await server.forPost().withBody('should-match').thenReply(400, 'Body matched'); const neverEndingStream = new PassThrough(); neverEndingStream.write('some data\n'); const neverEndingFetch = fetch(server.url, { method: 'PUT', // Matches the PUT rule, not the POST body: neverEndingStream as any }); const fetchResult = await neverEndingFetch; // Should return immediately, regardless of the request body not completing: expect (fetchResult.status).to.equal(201); }); it("should short-circuit, not waiting, if an incomplete matcher matches first", async () => { await server.forPost().thenReply(201, "Created"); await server.forPost().withBody('should-match').thenReply(400, 'Body matched'); const neverEndingStream = new PassThrough(); neverEndingStream.write('some data\n'); const neverEndingFetch = fetch(server.urlFor('/specific-endpoint'), { method: 'POST', // Matches the PUT rule, not the POST body: neverEndingStream as any }); const fetchResult = await neverEndingFetch; // Should match immediately, regardless of the request body not completing: expect (fetchResult.status).to.equal(201); }); it("should wait, if it really might be the best match", async () => { await server.forPost().withBody('should-match').thenReply(400, 'Body matched'); await server.forPost().thenReply(201, "Created"); const neverEndingStream = new PassThrough(); neverEndingStream.write('some data\n'); const neverEndingFetch = fetch(server.url, { method: 'POST', body: neverEndingStream as any }); const result = await Promise.race([ neverEndingFetch, delay(200).then(() => 'timeout') ]); // Should time out, because we really need to know if this rule really matches expect (result).to.equal('timeout'); neverEndingStream.end(); // Clean up }); }); }); });
the_stack
import { Autowired, Component, ICellEditor, ICellRendererComp, ICellRendererParams, IRichCellEditorParams, PopupComponent, AgPromise, UserComponentFactory, RefSelector, VirtualList, KeyCode, KeyCreatorParams, _, } from "@ag-grid-community/core"; import { RichSelectRow } from "./richSelectRow"; export class RichSelectCellEditor extends PopupComponent implements ICellEditor { // tab index is needed so we can focus, which is needed for keyboard events private static TEMPLATE = /* html */ `<div class="ag-rich-select" tabindex="-1"> <div ref="eValue" class="ag-rich-select-value"></div> <div ref="eList" class="ag-rich-select-list"></div> </div>`; @Autowired('userComponentFactory') private userComponentFactory: UserComponentFactory; @RefSelector('eValue') private eValue: HTMLElement; @RefSelector('eList') private eList: HTMLElement; private params: IRichCellEditorParams; private virtualList: VirtualList; private focusAfterAttached: boolean; // as the user moves the mouse, the selectedValue changes private selectedValue: any; // the original selection, as if the edit is not confirmed, getValue() will // return back the selected value. 'not confirmed' can happen if the user // opens the dropdown, hovers the mouse over a new value (selectedValue will // change to the new value) but then click on another cell (which will stop // the editing). in this instance, selectedValue will be a new value, however // the editing was effectively cancelled. private originalSelectedValue: any; private selectionConfirmed = false; private searchString = ''; constructor() { super(RichSelectCellEditor.TEMPLATE); } public init(params: IRichCellEditorParams): void { this.params = params; this.selectedValue = params.value; this.originalSelectedValue = params.value; this.focusAfterAttached = params.cellStartedEdit; const icon = _.createIconNoSpan('smallDown', this.gridOptionsWrapper); _.addCssClass(icon!, 'ag-rich-select-value-icon'); this.eValue.appendChild(icon!); this.virtualList = this.getContext().createBean(new VirtualList('rich-select')); this.virtualList.setComponentCreator(this.createRowComponent.bind(this)); this.eList.appendChild(this.virtualList.getGui()); if (_.exists(this.params.cellHeight)) { this.virtualList.setRowHeight(this.params.cellHeight); } this.renderSelectedValue(); if (_.missing(params.values)) { console.warn('AG Grid: richSelectCellEditor requires values for it to work'); return; } const values = params.values; this.virtualList.setModel({ getRowCount: () => values.length, getRow: (index: number) => values[index] }); this.addGuiEventListener('keydown', this.onKeyDown.bind(this)); const virtualListGui = this.virtualList.getGui(); this.addManagedListener(virtualListGui, 'click', this.onClick.bind(this)); this.addManagedListener(virtualListGui, 'mousemove', this.onMouseMove.bind(this)); const debounceDelay = _.exists(params.searchDebounceDelay) ? params.searchDebounceDelay : 300; this.clearSearchString = _.debounce(this.clearSearchString, debounceDelay); if (_.exists(params.charPress)) { this.searchText(params.charPress); } } private onKeyDown(event: KeyboardEvent): void { const key = event.keyCode; event.preventDefault(); switch (key) { case KeyCode.ENTER: this.onEnterKeyDown(); break; case KeyCode.TAB: this.confirmSelection(); break; case KeyCode.DOWN: case KeyCode.UP: this.onNavigationKeyPressed(event, key); break; default: this.searchText(event); } } private confirmSelection(): void { this.selectionConfirmed = true; } private onEnterKeyDown(): void { this.confirmSelection(); this.params.stopEditing(); } private onNavigationKeyPressed(event: any, key: number): void { // if we don't preventDefault the page body and/or grid scroll will move. event.preventDefault(); const oldIndex = this.params.values.indexOf(this.selectedValue); const newIndex = key === KeyCode.UP ? oldIndex - 1 : oldIndex + 1; if (newIndex >= 0 && newIndex < this.params.values.length) { const valueToSelect = this.params.values[newIndex]; this.setSelectedValue(valueToSelect); } } private searchText(key: KeyboardEvent | string) { if (typeof key !== 'string') { const keyCode = key.keyCode; let keyString = key.key; if (keyCode === KeyCode.BACKSPACE) { this.searchString = this.searchString.slice(0, -1); keyString = ''; } else if (!_.isEventFromPrintableCharacter(key)) { return; } this.searchText(keyString); return; } this.searchString += key; this.runSearch(); this.clearSearchString(); } private runSearch() { const values = this.params.values; let searchStrings: string[] | undefined; if (typeof values[0] === 'number' || typeof values[0] === 'string') { searchStrings = values.map(String); } if (typeof values[0] === 'object' && this.params.colDef.keyCreator) { searchStrings = values.map(value => { const keyParams: KeyCreatorParams = { value: value, colDef: this.params.colDef, column: this.params.column, node: this.params.node, data: this.params.data, api: this.gridOptionsWrapper.getApi()!, columnApi: this.gridOptionsWrapper.getColumnApi()!, context: this.gridOptionsWrapper.getContext() }; return this.params.colDef.keyCreator!(keyParams); }) } if (!searchStrings) { return; } const topSuggestion = _.fuzzySuggestions(this.searchString, searchStrings, true, true)[0]; if (!topSuggestion) { return; } const topSuggestionIndex = searchStrings.indexOf(topSuggestion); const topValue = values[topSuggestionIndex]; this.setSelectedValue(topValue); } private clearSearchString(): void { this.searchString = ''; } private renderSelectedValue(): void { const valueFormatted = this.params.formatValue(this.selectedValue); const eValue = this.eValue; const params = { value: this.selectedValue, valueFormatted: valueFormatted, api: this.gridOptionsWrapper.getApi() } as ICellRendererParams; const promise: AgPromise<ICellRendererComp> | null = this.userComponentFactory.newCellRenderer(this.params, params); if (_.exists(promise)) { _.bindCellRendererToHtmlElement(promise, eValue); promise.then(renderer => { this.addDestroyFunc(() => this.getContext().destroyBean(renderer)); }); } else { if (_.exists(this.selectedValue)) { eValue.innerHTML = valueFormatted; } else { _.clearElement(eValue); } } } private setSelectedValue(value: any): void { if (this.selectedValue === value) { return; } const index = this.params.values.indexOf(value); if (index === -1) { return; } this.selectedValue = value; this.virtualList.ensureIndexVisible(index); this.virtualList.refresh(); } private createRowComponent(value: any): Component { const valueFormatted = this.params.formatValue(value); const row = new RichSelectRow(this.params); this.getContext().createBean(row); row.setState(value, valueFormatted, value === this.selectedValue); return row; } private onMouseMove(mouseEvent: MouseEvent): void { const rect = this.virtualList.getGui().getBoundingClientRect(); const scrollTop = this.virtualList.getScrollTop(); const mouseY = mouseEvent.clientY - rect.top + scrollTop; const row = Math.floor(mouseY / this.virtualList.getRowHeight()); const value = this.params.values[row]; // not using utils.exist() as want empty string test to pass if (value !== undefined) { this.setSelectedValue(value); } } private onClick(): void { this.confirmSelection(); this.params.stopEditing(); } // we need to have the gui attached before we can draw the virtual rows, as the // virtual row logic needs info about the gui state public afterGuiAttached(): void { const selectedIndex = this.params.values.indexOf(this.selectedValue); // we have to call this here to get the list to have the right height, ie // otherwise it would not have scrolls yet and ensureIndexVisible would do nothing this.virtualList.refresh(); if (selectedIndex >= 0) { this.virtualList.ensureIndexVisible(selectedIndex); } // we call refresh again, as the list could of moved, and we need to render the new rows this.virtualList.refresh(); if (this.focusAfterAttached) { this.getGui().focus(); } } public getValue(): any { // NOTE: we don't use valueParser for Set Filter. The user should provide values that are to be // set into the data. valueParser only really makese sense when the user is typing in text (not picking // form a set). return this.selectionConfirmed ? this.selectedValue : this.originalSelectedValue; } }
the_stack
export interface Unit { name: { singular: string; plural: string; }; to_anchor: number; anchor_shift?: number; } export interface Conversion< TMeasures extends string, TSystems extends string, TUnits extends string > { abbr: TUnits; measure: TMeasures; system: TSystems; unit: Unit; } export interface UnitDescription { abbr: string; measure: string; system: string; singular: string; plural: string; } type TransformFunc = (value: number) => number; export interface Anchor { ratio?: number; transform?: TransformFunc; } export interface Measure<TSystems extends string, TUnits extends string> { systems: Partial<Record<TSystems, Partial<Record<TUnits, Unit>>>>; anchors?: Partial<Record<TSystems, Partial<Record<TSystems, Anchor>>>>; } export interface BestResult { val: number; unit: string; singular: string; plural: string; } /** * Represents a conversion path */ export class Converter< TMeasures extends string, TSystems extends string, TUnits extends string > { private val = 0; private destination: Conversion<TMeasures, TSystems, TUnits> | null = null; private origin: Conversion<TMeasures, TSystems, TUnits> | null = null; private measureData: Record<TMeasures, Measure<TSystems, TUnits>>; constructor( measures: Record<TMeasures, Measure<TSystems, TUnits>>, value?: number ) { if (typeof value === 'number') { this.val = value; } if (typeof measures !== 'object') { throw new Error('Measures cannot be blank'); } this.measureData = measures; } /** * Lets the converter know the source unit abbreviation */ from(from: TUnits): this { if (this.destination != null) throw new Error('.from must be called before .to'); this.origin = this.getUnit(from); if (this.origin == null) { this.throwUnsupportedUnitError(from); } return this; } /** * Converts the unit and returns the value */ to(to: TUnits): number { if (this.origin == null) throw new Error('.to must be called after .from'); this.destination = this.getUnit(to); if (this.destination == null) { this.throwUnsupportedUnitError(to); } const destination = this.destination as Conversion< TMeasures, TSystems, TUnits >; const origin = this.origin as Conversion<TMeasures, TSystems, TUnits>; // Don't change the value if origin and destination are the same if (origin.abbr === destination.abbr) { return this.val; } // You can't go from liquid to mass, for example if (destination.measure != origin.measure) { throw new Error( `Cannot convert incompatible measures of ${destination.measure} and ${origin.measure}` ); } /** * Convert from the source value to its anchor inside the system */ let result: number = this.val * origin.unit.to_anchor; /** * For some changes it's a simple shift (C to K) * So we'll add it when convering into the unit (later) * and subtract it when converting from the unit */ if (origin.unit.anchor_shift) { result -= origin.unit.anchor_shift; } /** * Convert from one system to another through the anchor ratio. Some conversions * aren't ratio based or require more than a simple shift. We can provide a custom * transform here to provide the direct result */ if (origin.system != destination.system) { const measure = this.measureData[origin.measure]; const anchors = measure.anchors; if (anchors == null) { throw new Error( `Unable to convert units. Anchors are missing for "${origin.measure}" and "${destination.measure}" measures.` ); } const anchor: Partial<Record<TSystems, Anchor>> | undefined = anchors[origin.system]; if (anchor == null) { throw new Error( `Unable to find anchor for "${origin.measure}" to "${destination.measure}". Please make sure it is defined.` ); } const transform: unknown = anchor[destination.system]?.transform; const ratio: unknown = anchor[destination.system]?.ratio; if (typeof transform === 'function') { result = transform(result); } else if (typeof ratio === 'number') { result *= ratio; } else { throw new Error( 'A system anchor needs to either have a defined ratio number or a transform function.' ); } } /** * This shift has to be done after the system conversion business */ if (destination.unit.anchor_shift) { result += destination.unit.anchor_shift; } /** * Convert to another unit inside the destination system */ return result / destination.unit.to_anchor; } /** * Converts the unit to the best available unit. */ toBest(options?: { exclude?: TUnits[]; cutOffNumber?: number; system?: TSystems; }): BestResult | null { if (this.origin == null) throw new Error('.toBest must be called after .from'); let exclude: TUnits[] = []; let cutOffNumber = 1; let system = this.origin.system; if (typeof options === 'object') { exclude = options.exclude ?? []; cutOffNumber = options.cutOffNumber ?? 1; system = options.system ?? this.origin.system; } let best = null; /** Looks through every possibility for the 'best' available unit. i.e. Where the value has the fewest numbers before the decimal point, but is still higher than 1. */ for (const possibility of this.possibilities()) { const unit = this.describe(possibility); const isIncluded = exclude.indexOf(possibility) === -1; if (isIncluded && unit.system === system) { const result = this.to(possibility); if (result < cutOffNumber) { continue; } if (best == null || (result >= cutOffNumber && result < best.val)) { best = { val: result, unit: possibility, singular: unit.singular, plural: unit.plural, }; } } } return best; } /** * Finds the unit */ getUnit(abbr: TUnits): Conversion<TMeasures, TSystems, TUnits> | null { const found = null; for (const [measureName, measure] of Object.entries(this.measureData)) { for (const [systemName, system] of Object.entries( (measure as Measure<TSystems, TUnits>).systems )) { for (const [testAbbr, unit] of Object.entries( system as Partial<Record<TUnits, Unit>> )) { if (testAbbr == abbr) { return { abbr: abbr as TUnits, measure: measureName as TMeasures, system: systemName as TSystems, unit: unit as Unit, }; } } } } return found; } /** * An alias for getUnit */ describe(abbr: TUnits): UnitDescription | never { const result = this.getUnit(abbr); if (result != null) { return this.describeUnit(result); } this.throwUnsupportedUnitError(abbr); } private describeUnit( unit: Conversion<TMeasures, TSystems, TUnits> ): UnitDescription { return { abbr: unit.abbr, measure: unit.measure, system: unit.system, singular: unit.unit.name.singular, plural: unit.unit.name.plural, }; } /** * Detailed list of all supported units * * If a measure is supplied the list will only contain * details about that measure. Otherwise the list will contain * details abaout all measures. * * However, if the measure doesn't exist, an empty array will be * returned * */ list(measureName?: TMeasures): UnitDescription[] | never { const list = []; if (measureName == null) { for (const [name, measure] of Object.entries(this.measureData)) { for (const [systemName, units] of Object.entries( (measure as Measure<TSystems, TUnits>).systems )) { for (const [abbr, unit] of Object.entries( units as Partial<Record<TUnits, Unit>> )) { list.push( this.describeUnit({ abbr: abbr as TUnits, measure: name as TMeasures, system: systemName as TSystems, unit: unit as Unit, }) ); } } } } else if (!(measureName in this.measureData)) { throw new Error(`Meausre "${measureName}" not found.`); } else { const measure = this.measureData[measureName]; for (const [systemName, units] of Object.entries( (measure as Measure<TSystems, TUnits>).systems )) { for (const [abbr, unit] of Object.entries( units as Partial<Record<TUnits, Unit>> )) { list.push( this.describeUnit({ abbr: abbr as TUnits, measure: measureName as TMeasures, system: systemName as TSystems, unit: unit as Unit, }) ); } } } return list; } private throwUnsupportedUnitError(what: string): never { let validUnits: string[] = []; for (const measure of Object.values(this.measureData)) { for (const systems of Object.values( (measure as Measure<TSystems, TUnits>).systems )) { validUnits = validUnits.concat( Object.keys(systems as Record<TUnits, Unit>) ); } } throw new Error( `Unsupported unit ${what}, use one of: ${validUnits.join(', ')}` ); } /** * Returns the abbreviated measures that the value can be * converted to. */ possibilities(forMeasure?: TMeasures): TUnits[] { let possibilities: TUnits[] = []; let list_measures: TMeasures[] = []; if (typeof forMeasure == 'string') { list_measures.push(forMeasure); } else if (this.origin != null) { list_measures.push(this.origin.measure); } else { list_measures = Object.keys(this.measureData) as TMeasures[]; } for (const measure of list_measures) { const systems = this.measureData[measure].systems; for (const system of Object.values(systems)) { possibilities = [ ...possibilities, ...(Object.keys(system as Record<TUnits, Unit>) as TUnits[]), ]; } } return possibilities; } /** * Returns the abbreviated measures that the value can be * converted to. */ measures(): TMeasures[] { return Object.keys(this.measureData) as TMeasures[]; } } export default function < TMeasures extends string, TSystems extends string, TUnits extends string >( measures: Record<TMeasures, Measure<TSystems, TUnits>> ): (value?: number) => Converter<TMeasures, TSystems, TUnits> { return (value?: number) => new Converter<TMeasures, TSystems, TUnits>(measures, value); }
the_stack
import { useIsRTL, useSyncRef } from '@ui5/webcomponents-react-base/dist/hooks'; import { ThemingParameters } from '@ui5/webcomponents-react-base/dist/ThemingParameters'; import { enrichEventWithDetails } from '@ui5/webcomponents-react-base/dist/Utils'; import { ChartContainer } from '@ui5/webcomponents-react-charts/dist/components/ChartContainer'; import { ChartDataLabel } from '@ui5/webcomponents-react-charts/dist/components/ChartDataLabel'; import { XAxisTicks } from '@ui5/webcomponents-react-charts/dist/components/XAxisTicks'; import { YAxisTicks } from '@ui5/webcomponents-react-charts/dist/components/YAxisTicks'; import { LineChartPlaceholder } from '@ui5/webcomponents-react-charts/dist/LineChartPlaceholder'; import { useLegendItemClick } from '@ui5/webcomponents-react-charts/dist/useLegendItemClick'; import { resolvePrimaryAndSecondaryMeasures } from '@ui5/webcomponents-react-charts/dist/Utils'; import React, { FC, forwardRef, Ref, useCallback, useRef } from 'react'; import { Brush, CartesianGrid, Label, Legend, Line, LineChart as LineChartLib, ReferenceLine, Tooltip, XAxis, YAxis } from 'recharts'; import { useChartMargin } from '../../hooks/useChartMargin'; import { useLabelFormatter } from '../../hooks/useLabelFormatter'; import { useLongestYAxisLabel } from '../../hooks/useLongestYAxisLabel'; import { useObserveXAxisHeights } from '../../hooks/useObserveXAxisHeights'; import { usePrepareDimensionsAndMeasures } from '../../hooks/usePrepareDimensionsAndMeasures'; import { useTooltipFormatter } from '../../hooks/useTooltipFormatter'; import { IChartBaseProps } from '../../interfaces/IChartBaseProps'; import { IChartDimension } from '../../interfaces/IChartDimension'; import { IChartMeasure } from '../../interfaces/IChartMeasure'; import { defaultFormatter } from '../../internal/defaults'; import { tickLineConfig, tooltipContentStyle, tooltipFillOpacity, xAxisPadding } from '../../internal/staticProps'; interface MeasureConfig extends IChartMeasure { /** * Line Width * @default 1 */ width?: number; /** * Line Opacity * @default 1 */ opacity?: number; /** * Flag whether the line dot should be displayed or not. */ showDot?: boolean; } interface DimensionConfig extends IChartDimension { interval?: number; } export interface LineChartProps extends IChartBaseProps { /** * An array of config objects. Each object will define one dimension of the chart. * * #### Required Properties * - `accessor`: string containing the path to the dataset key the dimension should display. Supports object structures by using <code>'parent.child'</code>. * Can also be a getter. * * #### Optional Properties * - `formatter`: function will be called for each data label and allows you to format it according to your needs * - `interval`: number that controls how many ticks are rendered on the x axis * */ dimensions: DimensionConfig[]; /** * An array of config objects. Each object is defining one line in the chart. * * #### Required properties * - `accessor`: string containing the path to the dataset key this line should display. Supports object structures by using <code>'parent.child'</code>. * Can also be a getter. * * #### Optional properties * * - `label`: Label to display in legends or tooltips. Falls back to the <code>accessor</code> if not present. * - `color`: any valid CSS Color or CSS Variable. Defaults to the `sapChart_Ordinal` colors * - `formatter`: function will be called for each data label and allows you to format it according to your needs * - `hideDataLabel`: flag whether the data labels should be hidden in the chart for this line. * - `DataLabel`: a custom component to be used for the data label * - `width`: line width, defaults to `1` * - `opacity`: line opacity, defaults to `1` * - `showDot`: Flag whether the line dot should be displayed or not. * */ measures: MeasureConfig[]; } const dimensionDefaults = { formatter: defaultFormatter }; const measureDefaults = { formatter: defaultFormatter, width: 1, opacity: 1 }; /** * A `LineChart` is a type of chart used to show information that changes over time - it connects multiple dots. */ const LineChart: FC<LineChartProps> = forwardRef((props: LineChartProps, ref: Ref<HTMLDivElement>) => { const { dataset, loading, noLegend, noAnimation, tooltipConfig, onDataPointClick, onLegendClick, onClick, style, className, tooltip, slot, syncId, ChartPlaceholder, children, ...rest } = props; const chartConfig = { yAxisVisible: false, xAxisVisible: true, gridStroke: ThemingParameters.sapList_BorderColor, gridHorizontal: true, gridVertical: false, legendPosition: 'bottom', legendHorizontalAlign: 'left', zoomingTool: false, resizeDebounce: 250, yAxisTicksVisible: true, yAxisConfig: {}, xAxisConfig: {}, secondYAxisConfig: {}, ...props.chartConfig }; const { dimensions, measures } = usePrepareDimensionsAndMeasures( props.dimensions, props.measures, dimensionDefaults, measureDefaults ); const tooltipValueFormatter = useTooltipFormatter(measures); const primaryDimension = dimensions[0]; const { primaryMeasure, secondaryMeasure } = resolvePrimaryAndSecondaryMeasures( measures, chartConfig?.secondYAxis?.dataKey ); const labelFormatter = useLabelFormatter(primaryDimension); const [componentRef, chartRef] = useSyncRef<any>(ref); const dataKeys = measures.map(({ accessor }) => accessor); const colorSecondY = chartConfig.secondYAxis ? dataKeys.findIndex((key) => key === chartConfig.secondYAxis?.dataKey) : 0; const onItemLegendClick = useLegendItemClick(onLegendClick); const preventOnClickCall = useRef(0); const onDataPointClickInternal = useCallback( (payload, eventOrIndex) => { if (eventOrIndex.dataKey && typeof onDataPointClick === 'function') { preventOnClickCall.current = 2; onDataPointClick( enrichEventWithDetails({} as any, { value: eventOrIndex.value, dataKey: eventOrIndex.dataKey, dataIndex: eventOrIndex.index, payload: eventOrIndex.payload }) ); } else if (typeof onClick === 'function' && preventOnClickCall.current === 0) { onClick( enrichEventWithDetails(eventOrIndex, { payload: payload?.activePayload?.[0]?.payload, activePayloads: payload?.activePayload }) ); } if (preventOnClickCall.current > 0) { preventOnClickCall.current -= 1; } }, [onDataPointClick, preventOnClickCall.current] ); const isBigDataSet = dataset?.length > 30 ?? false; const primaryDimensionAccessor = primaryDimension?.accessor; const [yAxisWidth, legendPosition] = useLongestYAxisLabel(dataset, measures); const marginChart = useChartMargin(chartConfig.margin, chartConfig.zoomingTool); const xAxisHeights = useObserveXAxisHeights(chartRef, props.dimensions.length); const { chartConfig: _0, dimensions: _1, measures: _2, ...propsWithoutOmitted } = rest; const isRTL = useIsRTL(chartRef); return ( <ChartContainer dataset={dataset} loading={loading} Placeholder={ChartPlaceholder ?? LineChartPlaceholder} ref={componentRef} style={style} className={className} tooltip={tooltip} slot={slot} resizeDebounce={chartConfig.resizeDebounce} {...propsWithoutOmitted} > <LineChartLib syncId={syncId} margin={marginChart} data={dataset} onClick={onDataPointClickInternal} className={typeof onDataPointClick === 'function' ? 'has-click-handler' : undefined} > <CartesianGrid vertical={chartConfig.gridVertical} horizontal={chartConfig.gridHorizontal} stroke={chartConfig.gridStroke} /> {dimensions.map((dimension, index) => { return ( <XAxis key={dimension.accessor} dataKey={dimension.accessor} xAxisId={index} interval={dimension?.interval ?? (isBigDataSet ? 'preserveStart' : 0)} tick={<XAxisTicks config={dimension} />} tickLine={index < 1} axisLine={index < 1} height={chartConfig.xAxisVisible ? xAxisHeights[index] : 0} padding={xAxisPadding} allowDuplicatedCategory={index === 0} reversed={isRTL} {...chartConfig.xAxisConfig} /> ); })} <YAxis orientation={isRTL === true ? 'right' : 'left'} axisLine={chartConfig.yAxisVisible} tickLine={tickLineConfig} yAxisId="left" tickFormatter={primaryMeasure?.formatter} interval={0} tick={chartConfig.yAxisTicksVisible && <YAxisTicks config={primaryMeasure} />} width={yAxisWidth} {...chartConfig.yAxisConfig} /> {chartConfig.secondYAxis?.dataKey && ( <YAxis dataKey={chartConfig.secondYAxis.dataKey} axisLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} tick={ <YAxisTicks config={secondaryMeasure} secondYAxisConfig={{ color: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} /> } tickLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore label={{ value: chartConfig.secondYAxis.name, offset: 2, angle: +90, position: 'center' }} orientation={isRTL === true ? 'left' : 'right'} yAxisId="right" interval={0} {...chartConfig.secondYAxisConfig} /> )} {measures.map((element, index) => { return ( <Line dot={element.showDot ?? !isBigDataSet} yAxisId={chartConfig.secondYAxis?.dataKey === element.accessor ? 'right' : 'left'} key={element.accessor} name={element.label ?? element.accessor} strokeOpacity={element.opacity} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore label={isBigDataSet ? false : <ChartDataLabel config={element} chartType="line" position="top" />} type="monotone" dataKey={element.accessor} stroke={element.color ?? `var(--sapChart_OrderedColor_${(index % 11) + 1})`} strokeWidth={element.width} activeDot={{ onClick: onDataPointClickInternal } as any} isAnimationActive={noAnimation === false} /> ); })} {!noLegend && ( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore <Legend verticalAlign={chartConfig.legendPosition} align={chartConfig.legendHorizontalAlign} onClick={onItemLegendClick} wrapperStyle={legendPosition} /> )} {chartConfig.referenceLine && ( <ReferenceLine stroke={chartConfig.referenceLine.color} y={chartConfig.referenceLine.value} yAxisId={'left'}> <Label>{chartConfig.referenceLine.label}</Label> </ReferenceLine> )} <Tooltip cursor={tooltipFillOpacity} formatter={tooltipValueFormatter} contentStyle={tooltipContentStyle} labelFormatter={labelFormatter} {...tooltipConfig} /> {chartConfig.zoomingTool && ( <Brush y={10} dataKey={primaryDimensionAccessor} tickFormatter={primaryDimension.formatter} stroke={ThemingParameters.sapObjectHeader_BorderColor} travellerWidth={10} height={20} /> )} {children} </LineChartLib> </ChartContainer> ); }); LineChart.defaultProps = { noLegend: false, noAnimation: false }; LineChart.displayName = 'LineChart'; export { LineChart };
the_stack
import cloneDeep from "lodash/cloneDeep"; import { Logger, LogLevel } from "@pnp/logging"; import { Web, IWeb } from "@pnp/sp/webs"; import { IItemUpdateResult, IItemAddResult } from "@pnp/sp/items/types"; import "@pnp/sp/lists"; import "@pnp/sp/items"; import { params } from "../services/Parameters"; import { IPlaylist, IAsset, ICacheConfig, ICustomizations, ICustomCDN, IMetadata, CacheConfig, Customizations, CustomCDN, IMultilingualString } from '../models/Models'; import { CustomListNames } from "../models/Enums"; import { UpgradeService } from "./UpgradeService"; import { IDataService } from "./DataService"; export interface ICustomDataService { doDataUpgrade(dataService: IDataService, configManifest: string, config: ICacheConfig, metadata: IMetadata, callBack?: () => void): Promise<void>; getCacheConfig(language: string): Promise<ICacheConfig>; getCustomCDN(): Promise<ICustomCDN>; getCustomization(): Promise<ICustomizations>; getCustomPlaylists(): Promise<IPlaylist[]>; getCustomAssets(): Promise<IAsset[]>; createPlaylist(newPlaylist: IPlaylist): Promise<number>; modifyPlaylist(editPlaylist: IPlaylist, cdn?: string): Promise<string>; deletePlaylist(playlistId: string): Promise<boolean>; createAsset(newAsset: IAsset): Promise<number>; modifyAsset(editAsset: IAsset, cdn?: string): Promise<string>; createCache(newConfig: ICacheConfig, language: string): Promise<number>; modifyCache(editConfig: ICacheConfig, cdn?: string): Promise<string>; createCustomization(newCustomization: ICustomizations): Promise<number>; modifyCustomization(editCustomization: ICustomizations, cdn?: string): Promise<string>; upsertCdn(cdn: ICustomCDN): Promise<string>; } export interface IUpdateFunctions { _web: IWeb; modifyPlaylist(editPlaylist: IPlaylist, cdn?: string): Promise<string>; modifyAsset(editAsset: IAsset, cdn?: string): Promise<string>; modifyCache(editConfig: ICacheConfig, cdn?: string): Promise<string>; modifyCustomization(editCustomization: ICustomizations, cdn?: string): Promise<string>; } export class CustomDataService implements ICustomDataService { private LOG_SOURCE: string = "CustomDataService"; private _web: IWeb; private _cdn: string; constructor(currentCDN: string) { try { this._web = Web(params.learningSiteUrl); this._cdn = currentCDN; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (constructor) - ${err}`, LogLevel.Error); } } //Optional formatter for dates using JSON.parse private dateTimeReviver(key, value) { const dateFormat: RegExp = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/; if (typeof value === "string" && dateFormat.test(value)) { return new Date(value); } return value; } public async doDataUpgrade(dataService: IDataService, configManifest: string, config: any, metadata: IMetadata, callBack?: () => void): Promise<void> { try { let workingConfig = cloneDeep(config); let upgradeFunctions: IUpdateFunctions = { _web: this._web, modifyCache: this.modifyCache, modifyCustomization: this.modifyCustomization, modifyPlaylist: this.modifyPlaylist, modifyAsset: this.modifyAsset }; let startVersion = +configManifest.substr(1, 1); let endVersion = +params.manifestVersion.substr(1, 1); if (startVersion < endVersion) { let us = new UpgradeService(upgradeFunctions, startVersion, endVersion, metadata); Logger.write(`Upgrade Custom Config from ${configManifest} to ${params.manifestVersion} - ${this.LOG_SOURCE} (doDataUpgrade)`, LogLevel.Warning); let customization = await this.getCustomization(); customization = await us.doUpgradeCustomization(customization, config); dataService.customization = customization; Logger.write(`Upgrade Playlists and Assets from ${configManifest} to ${params.manifestVersion} - ${this.LOG_SOURCE} (doDataUpgrade)`, LogLevel.Info); let cp = await this.getCustomPlaylists(); cp = await us.doUpgradePlaylists(cp); let ca = await this.getCustomAssets(); ca = await us.doUpgradeAssets(ca); Logger.write(`Upgrade Cache Config from ${configManifest} to ${params.manifestVersion} - ${this.LOG_SOURCE} (doDataUpgrade)`, LogLevel.Warning); workingConfig = await us.doUpgradeCacheConfig(workingConfig); } if (callBack) callBack(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (doDataUpgrade) - ${err}`, LogLevel.Error); } } //Gets custom configuration stored in local SharePoint list public async getCacheConfig(language: string): Promise<ICacheConfig> { let config: ICacheConfig = new CacheConfig(); if (!language) language = params.defaultLanguage; try { let configResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items .select("Id", "Title", "JSONData") .orderBy("Id", false) .filter(`(Title eq 'CustomConfig') and (CDN eq '${this._cdn}') and (Language eq '${language}')`) .top(1) .get<{ Id: string, Title: string, JSONData: string }[]>(); if (configResponse.length === 1) { if (configResponse[0].JSONData.length > 0) { config.Id = +configResponse[0].Id; config.eTag = JSON.parse(configResponse[0]["odata.etag"]); try { config = JSON.parse(configResponse[0].JSONData, this.dateTimeReviver); } catch (errJSON) { //If JSON data can't be parsed, remove item as it will be regenerated. this._web.lists.getByTitle(CustomListNames.customConfigName).items.getById(config.Id).delete(); config = null; } } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomConfig) No configuration was found for CDN ${this._cdn} and Language ${language}`, LogLevel.Error); config = null; } } catch (err) { config = null; Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomConfig) - ${err}`, LogLevel.Error); } return config; } //Gets custom configuration stored in local SharePoint list public async getCustomization(): Promise<ICustomizations> { let config: ICustomizations = new Customizations(); try { let configResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items .select("Id", "Title", "JSONData") .filter(`(Title eq 'CustomSubCategories') and (CDN eq '${this._cdn}')`) .top(1) .get<{ Id: string, Title: string, JSONData: string }[]>(); if (configResponse.length == 1) { if (configResponse[0].JSONData.length > 0) { config = JSON.parse(configResponse[0].JSONData); config.Id = +configResponse[0].Id; config.eTag = JSON.parse(configResponse[0]["odata.etag"]); } } else { config = new Customizations(); } } catch (err) { config = null; Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomization) - ${err}`, LogLevel.Error); } return config; } //Gets custom configuration stored in local SharePoint list public async getCustomCDN(): Promise<ICustomCDN> { let cdn: ICustomCDN = new CustomCDN(); try { let cdnResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items .select("Id", "Title", "JSONData") .filter(`Title eq 'CustomCDN'`) .top(1) .get<{ Id: string, Title: string, JSONData: string }[]>(); if (cdnResponse.length == 1) { if (cdnResponse[0].JSONData.length > 0) { cdn = JSON.parse(cdnResponse[0].JSONData); cdn.Id = +cdnResponse[0].Id; cdn.eTag = JSON.parse(cdnResponse[0]["odata.etag"]); } } } catch (err) { cdn = null; Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomCDN) - ${err}`, LogLevel.Error); } return cdn; } //Gets custom playlists stored in local SharePoint list (this code assumes the same site collection) public async getCustomPlaylists(): Promise<IPlaylist[]> { let customPlaylists: IPlaylist[] = []; try { let playlists = await this._web.lists.getByTitle(CustomListNames.customPlaylistsName).items .top(5000) .select("Id", "Title", "JSONData") .filter(`CDN eq '${this._cdn}'`) .get<{ Id: string, Title: string, JSONData: string }[]>(); for (let i = 0; i < playlists.length; i++) { try { let playlist: IPlaylist = JSON.parse(playlists[i].JSONData); playlist["@odata.etag"] = playlists[i]["@odata.etag"]; playlist.Id = `${playlists[i].Id}`; customPlaylists.push(playlist); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomPlaylists) - ${err}`, LogLevel.Error); } } } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomPlaylists) - ${err}`, LogLevel.Error); } return customPlaylists; } //Gets custom playlist assets stored in local SharePoint list (this code assumes the same site collection) public async getCustomAssets(): Promise<IAsset[]> { let customAssets: IAsset[] = []; let assets = await this._web.lists.getByTitle(CustomListNames.customAssetsName).items .top(5000) .select("Id", "Title", "JSONData") .filter(`CDN eq '${this._cdn}'`) .get<{ Id: string, Title: string, JSONData: string }[]>(); for (let i = 0; i < assets.length; i++) { try { let asset: IAsset = JSON.parse(assets[i].JSONData); asset["@odata.etag"] = assets[i]["@odata.etag"]; asset.Id = `${assets[i].Id}`; customAssets.push(asset); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getCustomAssets) - ${err}`, LogLevel.Error); } } return customAssets; } //Creates a custom playlist stored in local SharePoint list (this code assumes the same site collection) public async createPlaylist(newPlaylist: IPlaylist): Promise<number> { try { delete newPlaylist['@odata.etag']; delete newPlaylist.LevelValue; delete newPlaylist.AudienceValue; let title = (newPlaylist.Title instanceof Array) ? (newPlaylist.Title as IMultilingualString[])[0].Text : newPlaylist.Title as string; let item = { Title: title, CDN: this._cdn, JSONData: JSON.stringify(newPlaylist) }; let newPlaylistResponse = await this._web.lists.getByTitle(CustomListNames.customPlaylistsName).items.add(item); newPlaylist.Id = newPlaylistResponse.data.Id; item.JSONData = JSON.stringify(newPlaylist); let updatedPlaylistResponse = await this._web.lists.getByTitle(CustomListNames.customPlaylistsName).items.getById(+newPlaylistResponse.data.Id).update(item); return newPlaylistResponse.data.Id; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (createPlaylist) - ${err}`, LogLevel.Error); return 0; } } //Updates a custom playlist stored in local SharePoint list (this code assumes the same site collection) public async modifyPlaylist(editPlaylist: IPlaylist, cdn?: string): Promise<string> { try { delete editPlaylist['@odata.etag']; delete editPlaylist.LevelValue; delete editPlaylist.AudienceValue; let title = (editPlaylist.Title instanceof Array) ? (editPlaylist.Title as IMultilingualString[])[0].Text : editPlaylist.Title as string; let item = { Title: title, JSONData: JSON.stringify(editPlaylist) }; if (cdn) item["CDN"] = cdn; let updatedPlaylistResponse = await this._web.lists.getByTitle(CustomListNames.customPlaylistsName).items.getById(+editPlaylist.Id).update(item); return updatedPlaylistResponse.data["odata.etag"].split('\"')[1].toString(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (modifyPlaylist) - ${err}`, LogLevel.Error); return "0"; } } //Deletes a custom playlist stored in local SharePoint list (this code assumes the same site collection) //Does not remove associated assets, could be updated to look for orphaned assets and act accordingly public async deletePlaylist(playlistId: string): Promise<boolean> { try { await this._web.lists.getByTitle(CustomListNames.customPlaylistsName).items.getById(+playlistId).recycle(); return true; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (deletePlaylist) - ${err}`, LogLevel.Error); return false; } } //Creates a custom playlist asset stored in local SharePoint list (this code assumes the same site collection) public async createAsset(newAsset: IAsset): Promise<number> { try { delete newAsset['@odata.etag']; let title = (newAsset.Title instanceof Array) ? (newAsset.Title as IMultilingualString[])[0].Text : newAsset.Title as string; let item = { Title: title, CDN: this._cdn, JSONData: JSON.stringify(newAsset) }; let newAssetResponse = await this._web.lists.getByTitle(CustomListNames.customAssetsName).items.add(item); newAsset.Id = newAssetResponse.data.Id; item.JSONData = JSON.stringify(newAsset); let updatedAssetResponse = await this._web.lists.getByTitle(CustomListNames.customAssetsName).items.getById(+newAssetResponse.data.Id).update(item); return newAssetResponse.data.Id; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (createAsset) - ${err}`, LogLevel.Error); return 0; } } //Updates a custom playlist asset stored in local SharePoint list (this code assumes the same site collection) public async modifyAsset(editAsset: IAsset, cdn?: string): Promise<string> { try { delete editAsset['@odata.etag']; let title = (editAsset.Title instanceof Array) ? (editAsset.Title as IMultilingualString[])[0].Text : editAsset.Title as string; let item = { Title: title, JSONData: JSON.stringify(editAsset) }; if (cdn) item["CDN"] = cdn; let updatedAssetResponse = await this._web.lists.getByTitle(CustomListNames.customAssetsName).items.getById(+editAsset.Id).update(item); return updatedAssetResponse.data["odata.etag"].split('\"')[1].toString(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (modifyAsset) - ${err}`, LogLevel.Error); return "0"; } } //Creates a custom config stored in local SharePoint list public async createCache(newConfig: ICacheConfig, language: string): Promise<number> { try { if (!language) language = params.defaultLanguage; delete newConfig['@odata.etag']; let newConfigResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items .add({ Title: "CustomConfig", CDN: this._cdn, Language: language, JSONData: JSON.stringify(newConfig) }); return newConfigResponse.data.Id; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (createConfig) - ${err}`, LogLevel.Error); return 0; } } //Updates a custom config stored in local SharePoint list public async modifyCache(editConfig: ICacheConfig, cdn?: string): Promise<string> { try { delete editConfig['@odata.etag']; let item = { JSONData: JSON.stringify(editConfig) }; if (cdn) item["CDN"] = cdn; let updatedConfigResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items .getById(editConfig.Id).update(item); return updatedConfigResponse.data["odata.etag"].split('\"')[1].toString(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (modifyConfig) - ${err}`, LogLevel.Error); return "0"; } } //Creates a custom sub category array stored in local SharePoint list; public async createCustomization(newCustomization: ICustomizations): Promise<number> { try { delete newCustomization['@odata.etag']; let newConfigResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items.add({ Title: "CustomSubCategories", CDN: this._cdn, JSONData: JSON.stringify(newCustomization) }); return newConfigResponse.data.Id; } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (createCustomization) - ${err}`, LogLevel.Error); return 0; } } //Updates a custom sub category array stored in local SharePoint list public async modifyCustomization(editCustomization: ICustomizations, cdn?: string): Promise<string> { try { delete editCustomization['@odata.etag']; let item = { JSONData: JSON.stringify(editCustomization) }; if (cdn) item["CDN"] = cdn; let updatedConfigResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items.getById(+editCustomization.Id).update(item); return updatedConfigResponse.data["odata.etag"].split('\"')[1].toString(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (modifyCustomization) - ${err}`, LogLevel.Error); return "0"; } } public async upsertCdn(cdn: ICustomCDN): Promise<string> { try { delete cdn['@odata.etag']; let cdnResponse: IItemAddResult | IItemUpdateResult; if (cdn.Id === 0) { cdnResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items.add({ Title: "CustomCDN", JSONData: JSON.stringify(cdn) }); } else { cdnResponse = await this._web.lists.getByTitle(CustomListNames.customConfigName).items.getById(cdn.Id).update({ JSONData: JSON.stringify(cdn) }); } return (cdn.Id === 0) ? cdnResponse.data.Id.toString() : cdnResponse.data["odata.etag"].split('\"')[1].toString(); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (createSubCategories) - ${err}`, LogLevel.Error); return null; } } }
the_stack
import { IterableIterator } from '@stdlib/types/iter'; import filledarrayBy = require( './index' ); /** * Returns an iterator protocol-compliant object. * * @returns iterator protocol-compliant object */ function iterator(): IterableIterator { const obj: IterableIterator = { [Symbol.iterator]: iterator, 'next': next }; return obj; } /** * Implements the iterator protocol `next` method. * * @returns iterator protocol-compliant object */ function next(): any { return { 'value': 1.0, 'done': false }; } /** * Callback function. * * @param i - current array index * @returns return value */ function clbk( i: number ): number { return i; } // TESTS // // The function returns an array or typed array... { filledarrayBy(); // $ExpectType ArrayOrTypedArray filledarrayBy( 'float32' ); // $ExpectType ArrayOrTypedArray filledarrayBy( 10, clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( 10, clbk, {} ); // $ExpectType ArrayOrTypedArray filledarrayBy( 10, 'int32', clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( 10, 'int32', clbk, {} ); // $ExpectType ArrayOrTypedArray const x = new Float64Array( 10 ); filledarrayBy( x, clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( x, clbk, {} ); // $ExpectType ArrayOrTypedArray filledarrayBy( x, 'uint8', clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( x, 'uint8', clbk, {} ); // $ExpectType ArrayOrTypedArray const y = [ 2.0, 2.0, 2.0 ]; filledarrayBy( y, clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( y, clbk, {} ); // $ExpectType ArrayOrTypedArray filledarrayBy( y, 'float64', clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( y, 'float64', clbk, {} ); // $ExpectType ArrayOrTypedArray const it = iterator(); filledarrayBy( it, clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( it, clbk, {} ); // $ExpectType ArrayOrTypedArray filledarrayBy( it, 'uint8c', clbk ); // $ExpectType ArrayOrTypedArray filledarrayBy( it, 'uint8c', clbk, {} ); // $ExpectType ArrayOrTypedArray const buf = new ArrayBuffer( 32 ); filledarrayBy( buf, clbk ); // $ExpectType TypedArray filledarrayBy( buf, clbk, {} ); // $ExpectType TypedArray filledarrayBy( buf, 'uint32', clbk ); // $ExpectType TypedArray filledarrayBy( buf, 'uint32', clbk, {} ); // $ExpectType TypedArray filledarrayBy( buf, 8, clbk ); // $ExpectType TypedArray filledarrayBy( buf, 8, clbk, {} ); // $ExpectType TypedArray filledarrayBy( buf, 8, 'uint16', clbk ); // $ExpectType TypedArray filledarrayBy( buf, 8, 'uint16', clbk, {} ); // $ExpectType TypedArray filledarrayBy( buf, 8, 2, clbk ); // $ExpectType TypedArray filledarrayBy( buf, 8, 2, clbk, {} ); // $ExpectType TypedArray filledarrayBy( buf, 8, 2, 'int16', clbk ); // $ExpectType TypedArray filledarrayBy( buf, 8, 2, 'int16', clbk, {} ); // $ExpectType TypedArray } // The compiler throws an error if a callback function argument is not a function... { filledarrayBy( 'float64', '5' ); // $ExpectError filledarrayBy( 'float64', 1.0 ); // $ExpectError filledarrayBy( 'float64', false ); // $ExpectError filledarrayBy( 'float64', true ); // $ExpectError filledarrayBy( 'float64', null ); // $ExpectError filledarrayBy( 'float64', undefined ); // $ExpectError filledarrayBy( 'float64', [] ); // $ExpectError filledarrayBy( 'float64', {} ); // $ExpectError filledarrayBy( 'float64', '5', {} ); // $ExpectError filledarrayBy( 'float64', 1.0, {} ); // $ExpectError filledarrayBy( 'float64', false, {} ); // $ExpectError filledarrayBy( 'float64', true, {} ); // $ExpectError filledarrayBy( 'float64', null, {} ); // $ExpectError filledarrayBy( 'float64', undefined, {} ); // $ExpectError filledarrayBy( 'float64', [], {} ); // $ExpectError filledarrayBy( 'float64', {}, {} ); // $ExpectError filledarrayBy( 10, '5' ); // $ExpectError filledarrayBy( 10, 1.0 ); // $ExpectError filledarrayBy( 10, false ); // $ExpectError filledarrayBy( 10, true ); // $ExpectError filledarrayBy( 10, null ); // $ExpectError filledarrayBy( 10, undefined ); // $ExpectError filledarrayBy( 10, [] ); // $ExpectError filledarrayBy( 10, {} ); // $ExpectError filledarrayBy( 10, '5', {} ); // $ExpectError filledarrayBy( 10, 1.0, {} ); // $ExpectError filledarrayBy( 10, false, {} ); // $ExpectError filledarrayBy( 10, true, {} ); // $ExpectError filledarrayBy( 10, null, {} ); // $ExpectError filledarrayBy( 10, undefined, {} ); // $ExpectError filledarrayBy( 10, [], {} ); // $ExpectError filledarrayBy( 10, {}, {} ); // $ExpectError filledarrayBy( 10, 'float64', '5' ); // $ExpectError filledarrayBy( 10, 'float64', 1.0 ); // $ExpectError filledarrayBy( 10, 'float64', false ); // $ExpectError filledarrayBy( 10, 'float64', true ); // $ExpectError filledarrayBy( 10, 'float64', null ); // $ExpectError filledarrayBy( 10, 'float64', undefined ); // $ExpectError filledarrayBy( 10, 'float64', [] ); // $ExpectError filledarrayBy( 10, 'float64', {} ); // $ExpectError filledarrayBy( 10, 'float64', '5', {} ); // $ExpectError filledarrayBy( 10, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( 10, 'float64', false, {} ); // $ExpectError filledarrayBy( 10, 'float64', true, {} ); // $ExpectError filledarrayBy( 10, 'float64', null, {} ); // $ExpectError filledarrayBy( 10, 'float64', undefined, {} ); // $ExpectError filledarrayBy( 10, 'float64', [], {} ); // $ExpectError filledarrayBy( 10, 'float64', {}, {} ); // $ExpectError const x = new Float64Array( 10 ); filledarrayBy( x, '5' ); // $ExpectError filledarrayBy( x, 1.0 ); // $ExpectError filledarrayBy( x, false ); // $ExpectError filledarrayBy( x, true ); // $ExpectError filledarrayBy( x, null ); // $ExpectError filledarrayBy( x, undefined ); // $ExpectError filledarrayBy( x, [] ); // $ExpectError filledarrayBy( x, {} ); // $ExpectError filledarrayBy( x, '5', {} ); // $ExpectError filledarrayBy( x, 1.0, {} ); // $ExpectError filledarrayBy( x, false, {} ); // $ExpectError filledarrayBy( x, true, {} ); // $ExpectError filledarrayBy( x, null, {} ); // $ExpectError filledarrayBy( x, undefined, {} ); // $ExpectError filledarrayBy( x, [], {} ); // $ExpectError filledarrayBy( x, {}, {} ); // $ExpectError filledarrayBy( x, 'float64', '5' ); // $ExpectError filledarrayBy( x, 'float64', 1.0 ); // $ExpectError filledarrayBy( x, 'float64', false ); // $ExpectError filledarrayBy( x, 'float64', true ); // $ExpectError filledarrayBy( x, 'float64', null ); // $ExpectError filledarrayBy( x, 'float64', undefined ); // $ExpectError filledarrayBy( x, 'float64', [] ); // $ExpectError filledarrayBy( x, 'float64', {} ); // $ExpectError filledarrayBy( x, 'float64', '5', {} ); // $ExpectError filledarrayBy( x, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( x, 'float64', false, {} ); // $ExpectError filledarrayBy( x, 'float64', true, {} ); // $ExpectError filledarrayBy( x, 'float64', null, {} ); // $ExpectError filledarrayBy( x, 'float64', undefined, {} ); // $ExpectError filledarrayBy( x, 'float64', [], {} ); // $ExpectError filledarrayBy( x, 'float64', {}, {} ); // $ExpectError const y = [ 2.0, 2.0, 2.0 ]; filledarrayBy( y, '5' ); // $ExpectError filledarrayBy( y, 1.0 ); // $ExpectError filledarrayBy( y, false ); // $ExpectError filledarrayBy( y, true ); // $ExpectError filledarrayBy( y, null ); // $ExpectError filledarrayBy( y, undefined ); // $ExpectError filledarrayBy( y, [] ); // $ExpectError filledarrayBy( y, {} ); // $ExpectError filledarrayBy( y, '5', {} ); // $ExpectError filledarrayBy( y, 1.0, {} ); // $ExpectError filledarrayBy( y, false, {} ); // $ExpectError filledarrayBy( y, true, {} ); // $ExpectError filledarrayBy( y, null, {} ); // $ExpectError filledarrayBy( y, undefined, {} ); // $ExpectError filledarrayBy( y, [], {} ); // $ExpectError filledarrayBy( y, {}, {} ); // $ExpectError filledarrayBy( y, 'float64', '5' ); // $ExpectError filledarrayBy( y, 'float64', 1.0 ); // $ExpectError filledarrayBy( y, 'float64', false ); // $ExpectError filledarrayBy( y, 'float64', true ); // $ExpectError filledarrayBy( y, 'float64', null ); // $ExpectError filledarrayBy( y, 'float64', undefined ); // $ExpectError filledarrayBy( y, 'float64', [] ); // $ExpectError filledarrayBy( y, 'float64', {} ); // $ExpectError filledarrayBy( y, 'float64', '5', {} ); // $ExpectError filledarrayBy( y, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( y, 'float64', false, {} ); // $ExpectError filledarrayBy( y, 'float64', true, {} ); // $ExpectError filledarrayBy( y, 'float64', null, {} ); // $ExpectError filledarrayBy( y, 'float64', undefined, {} ); // $ExpectError filledarrayBy( y, 'float64', [], {} ); // $ExpectError filledarrayBy( y, 'float64', {}, {} ); // $ExpectError const it = iterator(); filledarrayBy( it, '5' ); // $ExpectError filledarrayBy( it, 1.0 ); // $ExpectError filledarrayBy( it, false ); // $ExpectError filledarrayBy( it, true ); // $ExpectError filledarrayBy( it, null ); // $ExpectError filledarrayBy( it, undefined ); // $ExpectError filledarrayBy( it, [] ); // $ExpectError filledarrayBy( it, {} ); // $ExpectError filledarrayBy( it, '5', {} ); // $ExpectError filledarrayBy( it, 1.0, {} ); // $ExpectError filledarrayBy( it, false, {} ); // $ExpectError filledarrayBy( it, true, {} ); // $ExpectError filledarrayBy( it, null, {} ); // $ExpectError filledarrayBy( it, undefined, {} ); // $ExpectError filledarrayBy( it, [], {} ); // $ExpectError filledarrayBy( it, {}, {} ); // $ExpectError filledarrayBy( it, 'float64', '5' ); // $ExpectError filledarrayBy( it, 'float64', 1.0 ); // $ExpectError filledarrayBy( it, 'float64', false ); // $ExpectError filledarrayBy( it, 'float64', true ); // $ExpectError filledarrayBy( it, 'float64', null ); // $ExpectError filledarrayBy( it, 'float64', undefined ); // $ExpectError filledarrayBy( it, 'float64', [] ); // $ExpectError filledarrayBy( it, 'float64', {} ); // $ExpectError filledarrayBy( it, 'float64', '5', {} ); // $ExpectError filledarrayBy( it, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( it, 'float64', false, {} ); // $ExpectError filledarrayBy( it, 'float64', true, {} ); // $ExpectError filledarrayBy( it, 'float64', null, {} ); // $ExpectError filledarrayBy( it, 'float64', undefined, {} ); // $ExpectError filledarrayBy( it, 'float64', [], {} ); // $ExpectError filledarrayBy( it, 'float64', {}, {} ); // $ExpectError const buf = new ArrayBuffer( 32 ); filledarrayBy( buf, '5' ); // $ExpectError filledarrayBy( buf, 1.0 ); // $ExpectError filledarrayBy( buf, false ); // $ExpectError filledarrayBy( buf, true ); // $ExpectError filledarrayBy( buf, null ); // $ExpectError filledarrayBy( buf, undefined ); // $ExpectError filledarrayBy( buf, [] ); // $ExpectError filledarrayBy( buf, {} ); // $ExpectError filledarrayBy( buf, '5', {} ); // $ExpectError filledarrayBy( buf, 1.0, {} ); // $ExpectError filledarrayBy( buf, false, {} ); // $ExpectError filledarrayBy( buf, true, {} ); // $ExpectError filledarrayBy( buf, null, {} ); // $ExpectError filledarrayBy( buf, undefined, {} ); // $ExpectError filledarrayBy( buf, [], {} ); // $ExpectError filledarrayBy( buf, {}, {} ); // $ExpectError filledarrayBy( buf, 'float64', '5' ); // $ExpectError filledarrayBy( buf, 'float64', 1.0 ); // $ExpectError filledarrayBy( buf, 'float64', false ); // $ExpectError filledarrayBy( buf, 'float64', true ); // $ExpectError filledarrayBy( buf, 'float64', null ); // $ExpectError filledarrayBy( buf, 'float64', undefined ); // $ExpectError filledarrayBy( buf, 'float64', [] ); // $ExpectError filledarrayBy( buf, 'float64', {} ); // $ExpectError filledarrayBy( buf, 'float64', '5', {} ); // $ExpectError filledarrayBy( buf, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( buf, 'float64', false, {} ); // $ExpectError filledarrayBy( buf, 'float64', true, {} ); // $ExpectError filledarrayBy( buf, 'float64', null, {} ); // $ExpectError filledarrayBy( buf, 'float64', undefined, {} ); // $ExpectError filledarrayBy( buf, 'float64', [], {} ); // $ExpectError filledarrayBy( buf, 'float64', {}, {} ); // $ExpectError filledarrayBy( buf, 8, '5' ); // $ExpectError filledarrayBy( buf, 8, 1.0 ); // $ExpectError filledarrayBy( buf, 8, false ); // $ExpectError filledarrayBy( buf, 8, true ); // $ExpectError filledarrayBy( buf, 8, null ); // $ExpectError filledarrayBy( buf, 8, undefined ); // $ExpectError filledarrayBy( buf, 8, [] ); // $ExpectError filledarrayBy( buf, 8, {} ); // $ExpectError filledarrayBy( buf, 8, '5', {} ); // $ExpectError filledarrayBy( buf, 8, 1.0, {} ); // $ExpectError filledarrayBy( buf, 8, false, {} ); // $ExpectError filledarrayBy( buf, 8, true, {} ); // $ExpectError filledarrayBy( buf, 8, null, {} ); // $ExpectError filledarrayBy( buf, 8, undefined, {} ); // $ExpectError filledarrayBy( buf, 8, [], {} ); // $ExpectError filledarrayBy( buf, 8, {}, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', '5' ); // $ExpectError filledarrayBy( buf, 8, 'float64', 1.0 ); // $ExpectError filledarrayBy( buf, 8, 'float64', false ); // $ExpectError filledarrayBy( buf, 8, 'float64', true ); // $ExpectError filledarrayBy( buf, 8, 'float64', null ); // $ExpectError filledarrayBy( buf, 8, 'float64', undefined ); // $ExpectError filledarrayBy( buf, 8, 'float64', [] ); // $ExpectError filledarrayBy( buf, 8, 'float64', {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', '5', {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', false, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', true, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', null, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', undefined, {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', [], {} ); // $ExpectError filledarrayBy( buf, 8, 'float64', {}, {} ); // $ExpectError filledarrayBy( buf, 8, 2, '5' ); // $ExpectError filledarrayBy( buf, 8, 2, 1.0 ); // $ExpectError filledarrayBy( buf, 8, 2, false ); // $ExpectError filledarrayBy( buf, 8, 2, true ); // $ExpectError filledarrayBy( buf, 8, 2, null ); // $ExpectError filledarrayBy( buf, 8, 2, undefined ); // $ExpectError filledarrayBy( buf, 8, 2, [] ); // $ExpectError filledarrayBy( buf, 8, 2, {} ); // $ExpectError filledarrayBy( buf, 8, 2, '5', {} ); // $ExpectError filledarrayBy( buf, 8, 2, 1.0, {} ); // $ExpectError filledarrayBy( buf, 8, 2, false, {} ); // $ExpectError filledarrayBy( buf, 8, 2, true, {} ); // $ExpectError filledarrayBy( buf, 8, 2, null, {} ); // $ExpectError filledarrayBy( buf, 8, 2, undefined, {} ); // $ExpectError filledarrayBy( buf, 8, 2, [], {} ); // $ExpectError filledarrayBy( buf, 8, 2, {}, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', '5' ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', 1.0 ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', false ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', true ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', null ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', undefined ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', [] ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', '5', {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', 1.0, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', false, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', true, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', null, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', undefined, {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', [], {} ); // $ExpectError filledarrayBy( buf, 8, 2, 'float64', {}, {} ); // $ExpectError } // The compiler throws an error if the function is not provided a valid length, typed array, array-like object, `ArrayBuffer`, or iterable argument... { filledarrayBy( false, clbk ); // $ExpectError filledarrayBy( true, clbk ); // $ExpectError filledarrayBy( null, clbk ); // $ExpectError filledarrayBy( {}, clbk ); // $ExpectError filledarrayBy( false, clbk, {} ); // $ExpectError filledarrayBy( true, clbk, {} ); // $ExpectError filledarrayBy( null, clbk, {} ); // $ExpectError filledarrayBy( {}, clbk, {} ); // $ExpectError filledarrayBy( false, 'float64', clbk ); // $ExpectError filledarrayBy( true, 'float64', clbk ); // $ExpectError filledarrayBy( null, 'float64', clbk ); // $ExpectError filledarrayBy( undefined, 'float64', clbk ); // $ExpectError filledarrayBy( {}, 'float64', clbk ); // $ExpectError filledarrayBy( false, 'float64', clbk, {} ); // $ExpectError filledarrayBy( true, 'float64', clbk, {} ); // $ExpectError filledarrayBy( null, 'float64', clbk, {} ); // $ExpectError filledarrayBy( undefined, 'float64', clbk, {} ); // $ExpectError filledarrayBy( {}, 'float64', clbk, {} ); // $ExpectError filledarrayBy( '5', 8, clbk ); // $ExpectError filledarrayBy( 1.0, 8, clbk ); // $ExpectError filledarrayBy( false, 8, clbk ); // $ExpectError filledarrayBy( true, 8, clbk ); // $ExpectError filledarrayBy( null, 8, clbk ); // $ExpectError filledarrayBy( undefined, 8, clbk ); // $ExpectError filledarrayBy( [], 8, clbk ); // $ExpectError filledarrayBy( {}, 8, clbk ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, clbk ); // $ExpectError filledarrayBy( '5', 8, clbk, {} ); // $ExpectError filledarrayBy( 1.0, 8, clbk, {} ); // $ExpectError filledarrayBy( false, 8, clbk, {} ); // $ExpectError filledarrayBy( true, 8, clbk, {} ); // $ExpectError filledarrayBy( null, 8, clbk, {} ); // $ExpectError filledarrayBy( undefined, 8, clbk, {} ); // $ExpectError filledarrayBy( [], 8, clbk, {} ); // $ExpectError filledarrayBy( {}, 8, clbk, {} ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, clbk, {} ); // $ExpectError filledarrayBy( '5', 8, 'float64', clbk ); // $ExpectError filledarrayBy( 1.0, 8, 'float64', clbk ); // $ExpectError filledarrayBy( false, 8, 'float64', clbk ); // $ExpectError filledarrayBy( true, 8, 'float64', clbk ); // $ExpectError filledarrayBy( null, 8, 'float64', clbk ); // $ExpectError filledarrayBy( undefined, 8, 'float64', clbk ); // $ExpectError filledarrayBy( [], 8, 'float64', clbk ); // $ExpectError filledarrayBy( {}, 8, 'float64', clbk ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 'float64', clbk ); // $ExpectError filledarrayBy( '5', 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( 1.0, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( false, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( true, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( null, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( undefined, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( [], 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( {}, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 'float64', clbk, {} ); // $ExpectError filledarrayBy( '5', 8, 2, clbk ); // $ExpectError filledarrayBy( 1.0, 8, 2, clbk ); // $ExpectError filledarrayBy( false, 8, 2, clbk ); // $ExpectError filledarrayBy( true, 8, 2, clbk ); // $ExpectError filledarrayBy( null, 8, 2, clbk ); // $ExpectError filledarrayBy( undefined, 8, 2, clbk ); // $ExpectError filledarrayBy( [], 8, 2, clbk ); // $ExpectError filledarrayBy( {}, 8, 2, clbk ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 2, clbk ); // $ExpectError filledarrayBy( '5', 8, 2, clbk, {} ); // $ExpectError filledarrayBy( 1.0, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( false, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( true, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( null, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( undefined, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( [], 8, 2, clbk, {} ); // $ExpectError filledarrayBy( {}, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 2, clbk, {} ); // $ExpectError filledarrayBy( '5', 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( 1.0, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( false, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( true, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( null, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( undefined, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( [], 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( {}, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 2, 'float64', clbk ); // $ExpectError filledarrayBy( '5', 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( 1.0, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( false, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( true, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( null, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( undefined, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( [], 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( {}, 8, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( ( x: number ): number => x, 8, 2, 'float64', clbk, {} ); // $ExpectError } // The compiler throws an error if the function is provided a byte offset argument which is not a number... { const buf = new ArrayBuffer( 32 ); filledarrayBy( buf, false, clbk ); // $ExpectError filledarrayBy( buf, true, clbk ); // $ExpectError filledarrayBy( buf, null, clbk ); // $ExpectError filledarrayBy( buf, [], clbk ); // $ExpectError filledarrayBy( buf, {}, clbk ); // $ExpectError filledarrayBy( buf, false, clbk, {} ); // $ExpectError filledarrayBy( buf, true, clbk, {} ); // $ExpectError filledarrayBy( buf, null, clbk, {} ); // $ExpectError filledarrayBy( buf, [], clbk, {} ); // $ExpectError filledarrayBy( buf, {}, clbk, {} ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, clbk, {} ); // $ExpectError filledarrayBy( buf, '5', 'float64', clbk ); // $ExpectError filledarrayBy( buf, false, 'float64', clbk ); // $ExpectError filledarrayBy( buf, true, 'float64', clbk ); // $ExpectError filledarrayBy( buf, null, 'float64', clbk ); // $ExpectError filledarrayBy( buf, undefined, 'float64', clbk ); // $ExpectError filledarrayBy( buf, [], 'float64', clbk ); // $ExpectError filledarrayBy( buf, {}, 'float64', clbk ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 'float64', clbk ); // $ExpectError filledarrayBy( buf, '5', 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, false, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, true, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, null, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, undefined, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, [], 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, {}, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, false, 2, clbk ); // $ExpectError filledarrayBy( buf, true, 2, clbk ); // $ExpectError filledarrayBy( buf, null, 2, clbk ); // $ExpectError filledarrayBy( buf, [], 2, clbk ); // $ExpectError filledarrayBy( buf, {}, 2, clbk ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 2, clbk ); // $ExpectError filledarrayBy( buf, false, 2, clbk, {} ); // $ExpectError filledarrayBy( buf, true, 2, clbk, {} ); // $ExpectError filledarrayBy( buf, null, 2, clbk, {} ); // $ExpectError filledarrayBy( buf, [], 2, clbk, {} ); // $ExpectError filledarrayBy( buf, {}, 2, clbk, {} ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 2, clbk, {} ); // $ExpectError filledarrayBy( buf, '5', 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, false, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, true, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, null, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, undefined, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, [], 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, {}, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 2, 'float64', clbk ); // $ExpectError filledarrayBy( buf, '5', 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, false, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, true, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, null, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, undefined, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, [], 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, {}, 2, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, ( x: number ): number => x, 2, 'float64', clbk, {} ); // $ExpectError } // The compiler throws an error if the function is provided a view length argument which is not a number... { const buf = new ArrayBuffer( 32 ); filledarrayBy( buf, 8, false, clbk ); // $ExpectError filledarrayBy( buf, 8, true, clbk ); // $ExpectError filledarrayBy( buf, 8, null, clbk ); // $ExpectError filledarrayBy( buf, 8, [], clbk ); // $ExpectError filledarrayBy( buf, 8, {}, clbk ); // $ExpectError filledarrayBy( buf, 8, false, clbk, {} ); // $ExpectError filledarrayBy( buf, 8, true, clbk, {} ); // $ExpectError filledarrayBy( buf, 8, null, clbk, {} ); // $ExpectError filledarrayBy( buf, 8, [], clbk, {} ); // $ExpectError filledarrayBy( buf, 8, {}, clbk, {} ); // $ExpectError filledarrayBy( buf, 8, ( x: number ): number => x, clbk, {} ); // $ExpectError filledarrayBy( buf, 8, '5', 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, false, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, true, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, null, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, undefined, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, [], 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, {}, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, ( x: number ): number => x, 'float64', clbk ); // $ExpectError filledarrayBy( buf, 8, '5', 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, false, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, true, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, null, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, undefined, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, [], 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, {}, 'float64', clbk, {} ); // $ExpectError filledarrayBy( buf, 8, ( x: number ): number => x, 'float64', clbk, {} ); // $ExpectError } // The compiler throws an error if the function is provided too many arguments... { const buf = new ArrayBuffer( 32 ); filledarrayBy( buf, 8, 2, 'float64', 1, clbk, {}, {} ); // $ExpectError }
the_stack
import {t} from '@lingui/macro' import {Action} from 'data/ACTIONS' import {ActionRoot} from 'data/ACTIONS/root' import {Status} from 'data/STATUSES' import {Event, Events} from 'event' import _ from 'lodash' import {Analyser} from 'parser/core/Analyser' import {filter, oneOf} from 'parser/core/filter' import {dependency} from 'parser/core/Injectable' import {Data} from 'parser/core/modules/Data' import {InitEvent} from 'parser/core/Parser' import {ARCANA_STATUSES, CELESTIAL_SEAL_ARCANA, DRAWN_ARCANA, LUNAR_SEAL_ARCANA, PLAY, SOLAR_SEAL_ARCANA} from '../ArcanaGroups' import DISPLAY_ORDER from '../DISPLAY_ORDER' const LINKED_EVENT_THRESHOLD = 20 const DEATH_EVENT_STATUS_DROP_DELAY = 2000 const CARD_GRANTING_ABILITIES: Array<keyof ActionRoot> = ['DRAW', 'REDRAW', ...PLAY] const CARD_ACTIONS: Array<keyof ActionRoot> = [ 'DRAW', 'REDRAW', 'UNDRAW', 'ASTRODYNE', ...PLAY, ] export enum SealType { NOTHING = 0, SOLAR = 1, LUNAR = 2, CELESTIAL = 3, } const CLEAN_SEAL_STATE = [SealType.NOTHING, SealType.NOTHING, SealType.NOTHING] export enum SleeveType { NOTHING = 0, ONE_STACK = 1, TWO_STACK = 2, } export interface CardState { lastEvent: InitEvent | Events['action'] | Events['death'] drawState?: number // typeof DRAWN_ARCANA status ID. Only loaded at runtime. TODO: Types sealState: SealType[] sleeveState: SleeveType } // TODO: Try to track for when a seal was not given on pull due to latency? export default class ArcanaTracking extends Analyser { static override handle = 'arcanaTracking' static override title = t('ast.arcana-tracking.title')`Arcana Tracking` static override displayOrder = DISPLAY_ORDER.ARCANA_TRACKING @dependency private data!: Data private play: Array<Action['id']> = [] private arcanaStatuses: Array<Status['id']> = [] private cardGrantingAbilities: Array<Action['id']> = [] private cardActions: Array<Action['id']> = [] private drawnArcana: Array<Status['id']> = [] private celestialSealArcana: Array<Action['id']> = [] private lunarSealArcana: Array<Action['id']> = [] private solarSealArcana: Array<Action['id']> = [] private playToStatusLookup: { [key: number]: number } = {} private statusToDrawnLookup: { [key: number]: number } = {} private statusToPlayLookup: { [key: number]: number } = {} private drawnToPlayLookup: { [key: number]: number } = {} private cardStateLog: CardState[] = [{ lastEvent: { type: 'init', timestamp: this.parser.pull.timestamp, }, drawState: undefined, sealState: CLEAN_SEAL_STATE, sleeveState: SleeveType.NOTHING, }] private lastDrawnBuff?: Events['statusApply'] private pullStateInitialized = false private pullIndex = 0 private on_prepullArcanas?: Array<Events['statusApply']> private off_prepullArcanas?: Array<Events['statusRemove']> override initialise() { // Initialize grouped reference to actions/statuses data this.play = PLAY.map(actionKey => this.data.actions[actionKey].id) this.arcanaStatuses = ARCANA_STATUSES.map(statusKey => this.data.statuses[statusKey].id) this.cardGrantingAbilities = CARD_GRANTING_ABILITIES.map(actionKey => this.data.actions[actionKey].id) this.cardActions = CARD_ACTIONS.map(actionKey => this.data.actions[actionKey].id) this.drawnArcana = DRAWN_ARCANA.map(statusKey => this.data.statuses[statusKey].id) this.celestialSealArcana = CELESTIAL_SEAL_ARCANA.map(actionKey => this.data.actions[actionKey].id) this.lunarSealArcana = LUNAR_SEAL_ARCANA.map(actionKey => this.data.actions[actionKey].id) this.solarSealArcana = SOLAR_SEAL_ARCANA.map(actionKey => this.data.actions[actionKey].id) this.playToStatusLookup = _.zipObject(this.play, this.drawnArcana) this.statusToDrawnLookup = _.zipObject(this.arcanaStatuses, this.drawnArcana) this.statusToPlayLookup = _.zipObject(this.arcanaStatuses, this.play) this.drawnToPlayLookup = _.zipObject(this.drawnArcana, this.play) const playerFilter = filter<Event>().source(this.parser.actor.id) this.addEventHook( playerFilter .type('action') .action(oneOf(this.cardActions)), this.onCast ) this.addEventHook( playerFilter .type('statusApply') .status(oneOf(this.arcanaStatuses)), this.onPrepullArcana ) this.addEventHook( playerFilter .type('statusRemove') .status(oneOf(this.arcanaStatuses)), this.offPrepullArcana ) this.addEventHook( playerFilter .type('statusApply') .status(oneOf(this.drawnArcana)), this.onDrawnStatus ) this.addEventHook( playerFilter .type('statusRemove') .status(oneOf(this.drawnArcana)), this.offDrawnStatus ) this.addEventHook({ type: 'death', actor: this.parser.actor.id, }, this.onDeath) } public get cardLogs() { return this.cardStateLog } /** * @param {number} timestamp - desired timestamp to get the state. Defaults to pull state. * @returns {CardState} - object containing the card state and last event */ public getCardState(timestamp = this.parser.pull.timestamp): CardState | undefined { const stateItem = this.cardStateLog.find(artifact => artifact.lastEvent && timestamp > artifact.lastEvent.timestamp) return stateItem } /** * @returns {CardState} - object containing the card state of the pull */ public getPullState(): CardState { const stateItem = this.cardStateLog.find(artifact => artifact.lastEvent && artifact.lastEvent.type === 'init') as CardState return stateItem } /** * Adds the Arcana Buff to _prepullArcanas if it was a precast status */ private onPrepullArcana(event: Events['statusApply']) { if (event.timestamp > this.parser.pull.timestamp) { return } if (this.on_prepullArcanas != null) { this.on_prepullArcanas.push(event) } } /** * Determine exactly when they casted their prepull arcana * If they had overwritten this buff, it will falsly pull back the timestamp of their prepull cast, but since we are guessing, it may as well be the same. */ private offPrepullArcana(event: Events['statusRemove']) { if (event.timestamp >= this.parser.pull.timestamp + this.data.statuses.THE_BALANCE.duration) { return } if (this.off_prepullArcanas != null) { this.off_prepullArcanas.forEach(arcanaBuff => { if (!(arcanaBuff.status === event.status && arcanaBuff.target === event.target)) { return } const cardStateItem: CardState = {..._.last(this.cardStateLog)} as CardState const arcanaAction = this.data.getAction(this.arcanaStatusToPlay(event.status)) if (arcanaAction == null) { return } const arcanaCastEvent: Events['action'] = { action: arcanaAction.id as number, timestamp: event.timestamp - this.data.statuses.THE_BALANCE.duration - this.parser.pull.timestamp, type: 'action', source: event.source, target: event.target, } cardStateItem.lastEvent = {...arcanaCastEvent} cardStateItem.drawState = undefined cardStateItem.sealState = CLEAN_SEAL_STATE this.cardStateLog.unshift(cardStateItem) this.pullIndex++ }) } } // Just saves a class var for the last drawn status buff event for reference, to help minor arcana plays private onDrawnStatus(event: Events['statusApply']) { if (!this.drawnArcana.includes(event.status)) { return } this.lastDrawnBuff = event } /** * This will run on removebuff. It will look for the loss of Arcanas Drawn statuses * 5.0: This was a lot more meaningful when we had multiple statuses to track like royal road, held, drawn, etc. * it's still useful now as it helps mitigate out-of-order log events (if that's still a thing anyway..) * * a) If it can't find any clear reason why the player had lost the buff, let's do a retconsearch to figure out since when they had it * * b) If they lost the buff with no link to any timestamp, it could be a /statusoff macro. * Creates a new entry as this is technically also a card action. * */ private offDrawnStatus(event: Events['statusRemove']) { if (!this.drawnArcana.includes(event.status)) { return } // a) check if this card was obtained legally, if not, retcon the logs this.retconSearch(this.arcanaDrawnToPlay(event.status)) // b) check if this was a standalone statusoff/undraw, if so, fab undraw event and add to logs const isPaired = this.cardStateLog.some(stateItem => stateItem.lastEvent && _.inRange(event.timestamp, stateItem.lastEvent.timestamp - LINKED_EVENT_THRESHOLD, stateItem.lastEvent.timestamp + LINKED_EVENT_THRESHOLD)) const isDeathPaired = this.cardStateLog.some(stateItem => stateItem.lastEvent && _.inRange(event.timestamp, stateItem.lastEvent.timestamp - LINKED_EVENT_THRESHOLD - DEATH_EVENT_STATUS_DROP_DELAY, stateItem.lastEvent.timestamp + DEATH_EVENT_STATUS_DROP_DELAY + LINKED_EVENT_THRESHOLD) && stateItem.lastEvent.type === 'death') // TODO: the above logic is ordered chronologically and for some reason doesn't capture deaths even with trying to account for death event types if (!isPaired && !isDeathPaired) { const cardStateItem: CardState = {..._.last(this.cardStateLog)} as CardState // fabbing an undraw cast event const lastEvent: Events['action'] = { action: this.data.actions.UNDRAW.id, timestamp: event.timestamp, type: 'action', source: event.source, target: event.target, } cardStateItem.lastEvent = lastEvent cardStateItem.drawState = undefined this.cardStateLog.push(cardStateItem) } } /** * MAIN DATA GATHERING LOOP * Creates a CardState duplicated from the previous known state of the Astrologian's spread, then modifies it based on the current action. * Adds the CardState to cardStateLog * */ private onCast(event: Events['action']) { // For now, we're not looking at any other precast action other than Plays, which is handled by offPrepullArcana() to check removebuff instead of cast for better estimation if (event.timestamp < this.parser.pull.timestamp) { return } const actionId = event.action // Piecing together what they have on prepull if (!this.pullStateInitialized && this.play.includes(actionId)) { this.initPullState(event) } const cardStateItem: CardState = {..._.last(this.cardStateLog)} as CardState cardStateItem.lastEvent = event if (this.play.includes(actionId)) { // Make sure they have been holding onto this from the last instance of a DRAW/REDRAW/MINOR_ARCANA this.retconSearch(actionId) cardStateItem.drawState = undefined // Work out what seal they got let sealObtained: SealType = SealType.NOTHING if (this.solarSealArcana.includes(actionId)) { sealObtained = SealType.SOLAR } else if (this.lunarSealArcana.includes(actionId)) { sealObtained = SealType.LUNAR } else if (this.celestialSealArcana.includes(actionId)) { sealObtained = SealType.CELESTIAL } const sealState = [...cardStateItem.sealState] cardStateItem.sealState = this.addSeal(sealObtained, sealState) } if (actionId === this.data.actions.ASTRODYNE.id) { cardStateItem.sealState = CLEAN_SEAL_STATE } if (actionId === this.data.actions.UNDRAW.id) { cardStateItem.drawState = undefined } this.cardStateLog.push(cardStateItem) } /** * Cards scattered all over the floor, covered with your blood * Inserts a new event into _cardStateLogs */ private onDeath(event: Events['death']) { // TODO: This is a duct tape fix // Checks on the previous event - it may be an erroneous drawnArcana flagged by offDrawnArcana. Statuses SEEM to drop 2s + 20ms earlier than the Death event. const lastCardState = {..._.last(this.cardStateLog)} as CardState if (lastCardState.lastEvent.type === 'action' && lastCardState.lastEvent.action === this.data.actions.UNDRAW.id && (event.timestamp - lastCardState.lastEvent.timestamp <= DEATH_EVENT_STATUS_DROP_DELAY + LINKED_EVENT_THRESHOLD)) { this.cardStateLog.pop() } // Fab a death event this.cardStateLog.push({ lastEvent: { ...event, }, drawState: undefined, sealState: CLEAN_SEAL_STATE, sleeveState: SleeveType.NOTHING, }) } /** * Initializes _cardStateLog pull entry for the first ever PLAY * Looks for a previous DRAW. If none, then DRAW was made prepull. Updates pull state. * */ private initPullState(event: Events['action']) { const actionId = event.action // First check that there's no DRAW between this and pullIndex const lookupLog = this.cardStateLog.slice(this.pullIndex + 1) if (lookupLog.length > 0) { lookupLog.forEach(cardState => { if (cardState.lastEvent.type === 'action' && this.cardGrantingAbilities.includes(cardState.lastEvent.action)) { // We're done since they had a DRAW return this.pullStateInitialized = true } }) } if (!this.pullStateInitialized && this.play.includes(actionId)) { // They had something in the draw slot const drawnStatus = this.arcanaActionToStatus(actionId) this.cardStateLog.forEach((cardState, index) => { if (cardState.lastEvent.type === 'init') { this.cardStateLog[index].drawState = drawnStatus ? drawnStatus : undefined return this.pullStateInitialized = true } }) } } /** * Loops back to see if the specified card was in possession without the possiblity of it being obtained via legal abilities. * This is presumed to mean they had it prepull, or since that latest ability. This function will then retcon the history since we know they had it. * The reason why this is necessary is because some logs come with draw/buff/play out of order. * Would be done in normaliser except we won't * * 5.0: Haha we only have one card slot now. * * @param actionId{array} The specified card drawn id * @return {void} null */ private retconSearch(cardActionId: number) { let searchLatest = true const lastLog = _.last(this.cardStateLog) as CardState const latestActionId = lastLog.lastEvent.type === 'action' ? lastLog.lastEvent.action : -1 // We can skip search+replace for the latest card event if that was a way to lose a card in draw slot. // 1. The standard ways of losing something in draw slot. // 2. If they used Draw while holding a Minor Arcana or Draw if ( [this.data.actions.UNDRAW.id, ...this.play, this.data.actions.REDRAW.id].includes(latestActionId) || (this.data.actions.DRAW.id === latestActionId && lastLog.drawState && this.drawnArcana.includes(lastLog.drawState)) ) { searchLatest = false } const searchLog = searchLatest ? this.cardStateLog : this.cardStateLog.slice(0, this.cardStateLog.length - 1) // Looking for those abilities in CARD_GRANTING_ABILITIES that could possibly get us this card let lastIndex = _.findLastIndex(searchLog, stateItem => stateItem.lastEvent.type === 'init' || stateItem.lastEvent.type === 'action' && this.cardGrantingAbilities.includes(stateItem.lastEvent.action), ) // There were no finds of specified abilities, OR it wasn't logged. if (lastIndex === -1 || this.cardStateLog[lastIndex].drawState === undefined) { // If none were found, they had it prepull, so assume this is pullIndex lastIndex = lastIndex < 0 ? this.pullIndex : lastIndex // Modify log, they were holding onto this card since index // Differenciate depending on searchLatest const arcanaStatus: number | undefined = this.arcanaActionToStatus(cardActionId) _.forEachRight(this.cardStateLog, (stateItem, index) => { if (searchLatest && index >= lastIndex) { stateItem.drawState = arcanaStatus } else if (index >= lastIndex && index !== this.cardStateLog.length - 1) { stateItem.drawState = arcanaStatus } }) } } // Helpers private addSeal(seal: SealType, sealState: SealType[]): SealType[] { if (!seal) { return sealState } sealState.shift() sealState.push(seal) return sealState } /** * Flips an arcana action id to the matching arcana status id * * @param arcanaId{int} The ID of an arcana. * @return {int} the ID of the arcana in status, or the same id received if it didn't match the flip lookup. */ public arcanaActionToStatus(arcanaId: number) { if (this.play.includes(arcanaId)) { return this.playToStatusLookup[arcanaId] } return undefined } /** * Flips an arcana status id to the matching arcana drawn id * * @param arcanaId{int} The ID of an arcana status. * @return {int} the ID of the arcana in drawn arcanas, or the same id received if it didn't match the flip lookup. */ public arcanaStatusToDrawn(arcanaId: number) { if (this.arcanaStatuses.includes(arcanaId)) { arcanaId = this.statusToDrawnLookup[arcanaId] } return arcanaId } /** * Flips an arcana status id to the matching arcana action id * * @param arcanaId{int} The ID of an arcana status. * @return {int} the ID of the arcana in play, or the same id received if it didn't match the flip lookup. */ public arcanaStatusToPlay(arcanaId: number) { if (this.arcanaStatuses.includes(arcanaId)) { arcanaId = this.statusToPlayLookup[arcanaId] } return arcanaId } /** * Flips a drawn arcana status id to the matching arcana action id * * @param arcanaId{int} The ID of an arcana drawn status. * @return {int} the ID of the arcana in play, or the same id received if it didn't match the flip lookup. */ public arcanaDrawnToPlay(arcanaId: number) { if (this.drawnArcana.includes(arcanaId)) { arcanaId = this.drawnToPlayLookup[arcanaId] } return arcanaId } }
the_stack
import * as util from "util"; import * as ld from "lodash"; import { OptionalPropertiesT, RequiredPropertiesT } from "type-ops"; import { Constructor, ExcludeInterface, isInstance, Message, MessageType, notNull, tagConstructor, toArray, } from "@adpt/utils"; import { printError as gqlPrintError } from "graphql"; import { DependsOn, DependsOnMethod, DeployedWhenMethod, DeployHelpers, GoalStatus, WaitStatus, } from "./deploy/deploy_types"; import { And, waiting } from "./deploy/relations"; import { BuildData } from "./dom"; import { BuildNotImplemented, InternalError } from "./error"; import { BuildId, Handle, handle, isHandleInternal } from "./handle"; import { Defaultize } from "./jsx_namespace"; import { ObserverNeedsData } from "./observers/errors"; import { ObserverManagerDeployment } from "./observers/obs_manager_deployment"; import { adaptGqlExecute } from "./observers/query_transforms"; import { findObserver } from "./observers/registry"; import { registerConstructor } from "./reanimate"; import { DeployOpID } from "./server/deployment_data"; import { applyStateUpdates, StateNamespace, StateStore, StateUpdater } from "./state"; import { defaultStatus, NoStatusAvailable, ObserveForStatus, Status } from "./status"; import { Children, ChildType } from "./type_support"; //dom.ts needs to set this since a direct import will cause a circular require // tslint:disable-next-line:variable-name export let ApplyStyle: ComponentType<any>; export function isApplyStyle(el: AdaptElement) { return el.componentType === ApplyStyle; } /** * An Adapt Element is an instance of an Adapt component. * * @remarks * The Adapt DOM is composed of Elements. * * @public * * @privateRemarks * NOTE(manishv): * This is broken, why does JSX.ElementClass correspond to both the type * a Component construtor has to return and what createElement has to return? * I don't think React actually adheres to this constraint. */ export interface AdaptElement<P extends object = AnyProps> { /** A copy of the props that the element was instantiated with */ readonly props: P & BuiltinProps; /** * The type of component that is associated with this element. * @remarks * For class components, this is the class (constructor) object. * For function components, this is the function object. */ readonly componentType: ComponentType<P>; /** * The name of the class or function in {@link AdaptElement.componentType}, * as returned by `componentType.name` or, the string `"anonymous"` if * no name is available. */ readonly componentName: string; /** * The name that a component author (optionally) associated with the * component using the `displayName` static property. If not set on a * component, defaults to {@link AdaptElement.componentName}. */ readonly displayName: string; /** * Adds a dependency for this Element. This Element will wait to deploy * until all `dependencies` have completed deployment. */ addDependency(dependencies: Handle | Handle[]): void; } export function isElement<P extends object = AnyProps>(val: any): val is AdaptElement<P> { return isInstance(val, AdaptElementImpl, "adapt"); } export function isElementImpl<P extends object = AnyProps>(val: any): val is AdaptElementImpl<P> { return isElement(val); } export type AdaptElementOrNull = AdaptElement<AnyProps> | null; export interface GenericInstanceMethods { dependsOn?: DependsOnMethod; deployedWhen?: DeployedWhenMethod; deployedWhenIsTrivial?: boolean; } export interface GenericInstance extends GenericInstanceMethods { [key: string]: any; } // Unique ID for an element. Currently AdaptElement.id. export type ElementID = string; /** * Interface that represents an AdaptElement that has been mounted during * the DOM build process. * @public */ export interface AdaptMountedElement<P extends object = AnyProps> extends AdaptElement<P> { readonly props: P & Required<BuiltinProps>; readonly id: ElementID; readonly path: string; readonly keyPath: KeyPath; readonly buildData: BuildData; readonly instance: GenericInstance; dependsOn: DependsOnMethod; deployedWhen: DeployedWhenMethod; /** * True if the Element's `deployedWhen` is considered trivial. * @remarks * This flag is a hint for user interfaces, such as the Adapt CLI. It * tells the user interface that this Element's `deployedWhen` function * is "trivial" and therefore its status should not typically be shown in * user interfaces unless the user has requested more detailed status * information on all components, or if there's an active action for * the component. * * This flag is `true` if the component does not have a custom * `deployedWhen` method or if the trivial flag was specifically set via * {@link useDeployedWhen} options (function component) or via * {@link Component.deployedWhenIsTrivial} (class component). */ readonly deployedWhenIsTrivial: boolean; status<T extends Status>(o?: ObserveForStatus): Promise<T>; built(): boolean; } export function isMountedElement<P extends object = AnyProps>(val: any): val is AdaptMountedElement<P> { return isElementImpl(val) && val.mounted; } export interface AdaptDeferredElement<P extends object = AnyProps> extends AdaptElement<P> { readonly componentType: PrimitiveClassComponentTyp<P>; } export function isDeferredElement<P extends object = AnyProps>(val: AdaptElement<P>): val is AdaptDeferredElement<P> { return isDeferred(val.componentType.prototype); } export function isDeferredElementImpl<P extends object = AnyProps>(val: AdaptElement<P>): val is AdaptDeferredElementImpl<P> { return isInstance(val, AdaptDeferredElementImpl, "adapt"); } export interface AdaptPrimitiveElement<P extends object = AnyProps> extends AdaptDeferredElement<P> { } export function isPrimitiveElement<P extends object>(elem: AdaptElement<P>): elem is AdaptPrimitiveElement<P> { return isPrimitive(elem.componentType.prototype); } export interface AdaptMountedPrimitiveElement<P extends object = AnyProps> extends AdaptPrimitiveElement<P>, AdaptMountedElement<P> { readonly props: P & Required<BuiltinProps>; readonly componentType: PrimitiveClassComponentTyp<P>; validate(): Message[]; } export function isMountedPrimitiveElement<P extends object>(elem: AdaptElement<P>): elem is AdaptMountedPrimitiveElement<P> { return isPrimitiveElement(elem) && isMountedElement(elem); } export interface AdaptComponentElement<P extends object = AnyProps> extends AdaptElement<P> { readonly componentType: ClassComponentTyp<P, AnyState>; } export function isComponentElement<P extends object = AnyProps>(val: any): val is AdaptComponentElement<P> { return isElement(val) && isComponent(val.componentType.prototype); } export interface AdaptSFCElement<P extends object = AnyProps> extends AdaptElement<P> { readonly componentType: FunctionComponentTyp<P>; } export function isSFCElement<P extends object = AnyProps>(val: any): val is AdaptSFCElement<P> { return isElement(val) && !isComponentElement(val); } /* * Type info for the Elements returned from dom.build. These types are * intended to convey semantic meaning--that whomever uses these types is * intending to deal with a built DOM. They also add a level of indirection, * should we choose to modify the types somehow in the future. */ export type FinalDomElement<P extends object = AnyProps> = AdaptMountedPrimitiveElement<P>; export type PartialFinalDomElement<P extends object = AnyProps> = AdaptMountedElement<P>; export const isFinalDomElement = isMountedPrimitiveElement; export const isPartialFinalDomElement = isMountedElement; export function componentStateNow< C extends Component<P, S>, P extends object, S extends object>(c: C): S | undefined { try { return c.state; } catch { return undefined; } } export interface DeployInfo { deployID: string; deployOpID: DeployOpID; } export interface BuildHelpers extends DeployInfo, BuildId { elementStatus<T = Status>(handle: Handle): Promise<T | undefined>; } export abstract class Component<Props extends object = {}, State extends object = {}> implements GenericInstanceMethods { deployInfo: DeployInfo; dependsOn?: DependsOnMethod; /** * A derived component's custom `deployedWhen` method. * * @remarks * Adding a custom `deployedWhen` method to a component allows the component to * directly control when the component can be considered deployed. * * For more information on using `deployedWhen` methods, see * {@link Adapt.DeployedWhenMethod}. * * For components that do not add a custom `deployedWhen` method, the * default behavior is that a component becomes deployed when all of it's * successors and children have been deployed. See {@link defaultDeployedWhen} * for more information. * @public */ deployedWhen?: DeployedWhenMethod; /** * A derived component can set this flag to `true` to indicate to user * interfaces that this component's status should not typically be shown * to the user, unless requested. * @remarks * This flag is a hint for user interfaces, such as the Adapt CLI. It * tells the user interface that this Element's `deployedWhen` function * is "trivial" and therefore its status should not typically be shown in * user interfaces unless the user has requested more detailed status * information on all components, or if there's an active action for * this component. */ deployedWhenIsTrivial?: boolean; // cleanup gets called after build of this component's // subtree has completed. cleanup?: (this: this) => void; private stateUpdates: StateUpdater<Props, State>[]; private getState?: () => any; get state(): Readonly<State> { if (this.getState == null) { throw new Error(`this.state cannot be accessed before calling super()`); } if (this.initialState == null) { throw new Error(`cannot access this.state in a Component that ` + `lacks an initialState method`); } return this.getState(); } set state(_: Readonly<State>) { throw new Error(`State for a component can only be changed by calling this.setState`); } // NOTE(mark): This really should be just BuiltinProps with both key // and handle required, but there's some strange interaction between // ElementClass and LibraryManagedAttributes in the JSX namespace that // I don't understand at the moment where I can't seem to make the // Component constructor require it without also making key and handle // unintentionally required in all JSX expressions. constructor(readonly props: Props & Partial<BuiltinProps>) { registerConstructor(this.constructor); const cData = getComponentConstructorData(); const curState = cData.getState(); if (curState === undefined && this.initialState != null) { const init = this.initialState(); if (init == null || !ld.isObject(init)) { throw new Error(`initialState function returned invalid value ` + `'${init}'. initialState must return an object.`); } cData.setInitialState(init); } this.stateUpdates = cData.stateUpdates as any; this.deployInfo = cData.deployInfo; // Prevent subclass constructors from accessing this.state too early // by waiting to init getState. this.getState = cData.getState; } setState(stateUpdate: Partial<State> | StateUpdater<Props, State>): void { if (this.initialState == null) { throw new Error(`Component ${this.constructor.name}: cannot access ` + `this.setState in a Component that lacks an ` + `initialState method`); } this.stateUpdates.push(ld.isFunction(stateUpdate) ? stateUpdate : () => stateUpdate); } // If a component uses state, it MUST define initialState initialState?(): State; abstract build(helpers: BuildHelpers): AdaptElementOrNull | Promise<AdaptElementOrNull>; status(observeForStatus: ObserveForStatus, buildData: BuildData): Promise<unknown> { return defaultStatus(this.props, observeForStatus, buildData); } } tagConstructor(Component, "adapt"); export type PropsType<Comp extends Constructor<Component<any, any>>> = Comp extends Constructor<Component<infer CProps, any>> ? CProps : never; export abstract class DeferredComponent<Props extends object = {}, State extends object = {}> extends Component<Props, State> { } tagConstructor(DeferredComponent, "adapt"); export function isDeferred<P extends object, S extends object>(component: Component<P, S>): component is DeferredComponent<P, S> { return isInstance(component, DeferredComponent, "adapt"); } export abstract class PrimitiveComponent<Props extends object = {}, State extends object = {}> extends DeferredComponent<Props, State> { build(): AdaptElementOrNull { throw new BuildNotImplemented(); } validate(): string | string[] | undefined { return; } } tagConstructor(PrimitiveComponent, "adapt"); export function isPrimitive<P extends object>(component: Component<P>): component is PrimitiveComponent<P> { return isInstance(component, PrimitiveComponent, "adapt"); } export interface SFC<Props extends object = AnyProps> { (props: Props & Partial<BuiltinProps>): AdaptElementOrNull; defaultProps?: Partial<Props>; status?: (props: Props & BuiltinProps, observe: ObserveForStatus, buildData: BuildData) => Promise<unknown>; } /** * Helper type for declaring the props argument of a function component. * (The type that users of your component will see.) * * @remarks * This helper type can be used to create the type for your function * component's `props` argument. It correctly handles the standard * set of {@link BuiltinProps} and your component's `defaultProps` so that * users of your component can pass in props like `key` and `handle` and also * not be required to pass in any props that are required, but have valid * default values in `defaultProps`. * * This type should **only** be used to describe the first argument to your * function component. * * It should typically be used along with {@link SFCBuildProps}. * * Type parameters: * * `Props` - The object type that describes the props your function * component takes, not including any {@link BuiltinProps}. For props that * your component requires, but has valid defaults set in `defaultProps`, * those properties should be required (not optional) in `Props`. * * `Defaults` - The object type of your component's `defaultProps`. * * @example * ```tsx * interface MyProps { * required: string; // User is required to always set this prop * hasDefault: string; // User can optionally set this prop or get default * optional?: string; // User can optionally set this prop, but no default * } * const defaultProps = { * hasDefault: "thedefault" * } * * // Types for the properties of the props argument below are: * // props.required string [required] * // props.hasDefault string [optional] * // props.optional string [optional] * // props.key string [optional] * // props.handle Handle [optional] * function MyComponent(props: SFCDeclProps<MyProps, typeof defaultProps) { * // Types for the properties of the buildProps variable below are: * // buildProps.required string * // buildProps.hasDefault string * // buildProps.optional string | undefined * // buildProps.key string * // buildProps.handle Handle * const buildProps = props as SFCBuildProps<MyProps, typeof defaultProps>; * ... * } * MyComponent.defaultProps = defaultProps; * ``` * @public */ export type SFCDeclProps<Props, Defaults extends object = object> = Defaultize<Props, Defaults> & Partial<BuiltinProps>; /** * Helper type for declaring the props available to use **inside** the body * of your function component. * * @remarks * This helper type can be used to create the type of the "build props", * which are the props available inside the body of your function component * when your component is built by Adapt. The type of "build props" in a * function component are different than the type that the user sees because * Adapt deals with setting the values of some props automatically when * a component gets built. * * This helper should **only** be used to describe the type of a function * component's props **inside** the function body. * * It should typically be used along with {@link SFCDeclProps}. See the * example usage of both helper types in {@link SFCDeclProps}. * * Type parameters: * * `Props` - The object type that describes the props your function * component takes, not including any {@link BuiltinProps}. For props that * your component requires, but has valid defaults set in `defaultProps`, * those properties should be required (not optional) in `Props`. * * `Defaults` - (optional) The object type of your component's `defaultProps`. */ export type SFCBuildProps<Props, Defaults extends object = object> = & {[K in Extract<keyof Props, keyof Defaults>]: Props[K]} & {[K in Exclude<RequiredPropertiesT<Props>, keyof Defaults>]: Props[K]} & {[K in Exclude<OptionalPropertiesT<Props>, keyof Defaults>]?: Props[K]} & Required<BuiltinProps>; export function isComponent<P extends object, S extends object>(func: SFC | Component<P, S>): func is Component<P, S> { return isInstance(func, Component, "adapt"); } export interface ComponentStatic<P> { defaultProps?: Partial<P>; displayName?: string; noPlugin?: boolean; } export interface FunctionComponentTyp<P> extends ComponentStatic<P> { (props: P & Partial<BuiltinProps>): AdaptElementOrNull; status?: (props: P, observe: ObserveForStatus, buildData: BuildData) => Promise<unknown>; } export interface ClassComponentTyp<P extends object, S extends object> extends ComponentStatic<P> { new(props: P & Partial<BuiltinProps>): Component<P, S>; } export interface DeferredClassComponentTyp<P extends object, S extends object> extends ComponentStatic<P> { new(props: P & Partial<BuiltinProps>): DeferredComponent<P, S>; } export interface PrimitiveClassComponentTyp<P extends object> extends ComponentStatic<P> { new(props: P & Partial<BuiltinProps>): PrimitiveComponent<P>; } export type ComponentType<P extends object> = FunctionComponentTyp<P> | ClassComponentTyp<P, AnyState> | DeferredClassComponentTyp<P, AnyState> | PrimitiveClassComponentTyp<P>; export interface AnyProps { [key: string]: any; } export interface BuiltinProps { handle: Handle; key?: string; } export interface AnyState { [key: string]: any; } export interface WithChildren { children?: any | any[]; } export type GenericComponent = Component<AnyProps, AnyState>; export type KeyPath = string[]; export type ElementPredicate = (el: AdaptElement) => boolean; /** * @internal */ export class AdaptElementImpl<Props extends object> implements AdaptElement<Props> { readonly props: Props & BuiltinProps & WithChildren; stateNamespace: StateNamespace = []; mounted = false; component: GenericComponent | null; instanceMethods: GenericInstance = {}; path?: string; keyPath?: KeyPath; buildData: Partial<BuildData> = {}; buildState = BuildState.initial; reanimated: boolean = false; stateUpdates: StateUpdater[] = []; private addlDependencies?: Set<Handle>; constructor( readonly componentType: ComponentType<Props>, props: Props & Partial<BuiltinProps>, children: any[]) { const hand = props.handle || handle(); if (!isHandleInternal(hand)) throw new InternalError(`handle is not a HandleImpl`); hand.associate(this); this.props = { // https://github.com/Microsoft/TypeScript/pull/13288 ...props as any, handle: hand, }; // Children passed as explicit parameter replace any on props if (children.length > 0) this.props.children = children; // Validate and flatten children. this.props.children = simplifyChildren(this.props.children); if (this.props.children === undefined) { delete this.props.children; } Object.freeze(this.props); } mount(parentNamespace: StateNamespace, path: string, keyPath: KeyPath, deployID: string, deployOpID: DeployOpID) { if (this.mounted) { throw new Error("Cannot remount elements!"); } if ("key" in this.props) { const propsWithKey = this.props as Props & { key: string }; this.stateNamespace = [...parentNamespace, propsWithKey.key]; } else { throw new InternalError(`props has no key at mount: ${util.inspect(this)}`); } this.path = path; this.keyPath = keyPath; this.mounted = true; this.buildData.id = this.id; this.buildData.deployID = deployID; this.buildData.deployOpID = deployOpID; } setBuilt = () => this.buildState = BuildState.built; shouldBuild = () => this.buildState === BuildState.initial; built = () => this.buildState === BuildState.built; setState = (stateUpdate: StateUpdater<Props, AnyState>): void => { this.stateUpdates.push(stateUpdate); } async postBuild(stateStore: StateStore): Promise<{ stateChanged: boolean }> { return { stateChanged: await applyStateUpdates(this.stateNamespace, stateStore, this.props, this.stateUpdates) }; } getStatusMethod = (): ((o: ObserveForStatus, b: BuildData) => Promise<any>) => { if (isSFCElement(this)) { const customStatus = this.componentType.status; if (customStatus) { return (observeForStatus, buildData) => customStatus(this.props, observeForStatus, buildData); } return (observeForStatus, buildData) => defaultStatus(this.props, observeForStatus, buildData); } return (o, b) => { if (!this.component) throw new NoStatusAvailable(`element.component === ${this.component}`); return this.component.status(o, b); }; } statusCommon = async (observeForStatus: ObserveForStatus) => { if (this.reanimated && !this.built()) { throw new NoStatusAvailable("status for reanimated elements not supported without a DOM build"); } if (!this.mounted) throw new NoStatusAvailable(`element is not mounted`); const buildData = this.buildData as BuildData; //After build, this type assertion should hold if (buildData === undefined) throw new Error(`Status requested but no buildData: ${this}`); const statusMethod = this.getStatusMethod(); return statusMethod(observeForStatus, buildData); } statusWithMgr = async (mgr: ObserverManagerDeployment) => { const observeForStatus: ObserveForStatus = async (observer, query, variables) => { const result = await mgr.executeQuery(observer, query, variables); if (result.errors) { const badErrors = result.errors.filter((e) => !e.message.startsWith("Adapt Observer Needs Data:")); if (badErrors.length !== 0) { const msgs = badErrors.map((e) => e.originalError ? e.stack : gqlPrintError(e)).join("\n"); throw new Error(msgs); } const needMsgs = result.errors.map((e) => e.originalError ? e.stack : gqlPrintError(e)).join("\n"); throw new ObserverNeedsData(needMsgs); } return result.data; }; return this.statusCommon(observeForStatus); } status = async (o?: ObserveForStatus) => { const observeForStatus: ObserveForStatus = async (observer, query, variables) => { //FIXME(manishv) Make this collect all queries and then observe only once - may require interface change const plugin = findObserver(observer); if (!plugin) throw new Error(`Cannot find observer ${observer.observerName}`); const observations = await plugin.observe([{ query, variables }]); const schema = plugin.schema; const result = await adaptGqlExecute<unknown>( schema, query, observations.data, observations.context, variables); if (result.errors) { const msgs = result.errors.map((e) => e.originalError ? e.stack : gqlPrintError(e)).join("\n"); throw new Error(msgs); } return result.data; }; return this.statusCommon(o || observeForStatus); } /** * Add one or more deploy dependencies to this Element. * @remarks * Intended to be called during the DOM build process. */ addDependency(dependencies: Handle | Handle[]) { const hands = toArray(dependencies); if (hands.length === 0) return; if (!this.addlDependencies) this.addlDependencies = new Set(); for (const h of hands) this.addlDependencies.add(h); } /** * Return all the dependencies of an Element. * @remarks * Intended to be called during the deployment phase from the execution * plan code only. * @internal */ dependsOn(goalStatus: GoalStatus, helpers: DeployHelpers): DependsOn | undefined { if (!this.mounted) { throw new InternalError(`dependsOn requested but element is not mounted`); } const method = this.instance.dependsOn; const methodDeps = method && method(goalStatus, helpers); if (!this.addlDependencies) return methodDeps; const finalHandles = [...this.addlDependencies] .map((h) => h.mountedOrig) .filter(notNull) .map((el) => el.props.handle); const addlDeps = helpers.dependsOn(finalHandles); if (methodDeps === undefined) return addlDeps; return And(methodDeps, addlDeps); } /** * Returns whether this Element (and ONLY this element) has completed * deployment. * @remarks * Intended to be called during the deployment phase from the execution * plan code only. * @internal */ deployedWhen(goalStatus: GoalStatus, helpers: DeployHelpers): WaitStatus | Promise<WaitStatus> { if (!this.mounted) { throw new InternalError(`deployedWhen requested but element is not mounted`); } const method = this.instance.deployedWhen || defaultDeployedWhen(this); return method(goalStatus, helpers); } /** * True if the Element's `deployedWhen` is considered trivial. * @remarks * This flag is a hint for user interfaces, such as the Adapt CLI. It * tells the user interface that this Element's `deployedWhen` function * is "trivial" and therefore its status should not typically be shown in * user interfaces unless the user has requested more detailed status * information on all components, or if there's an active action for * this component. * * This flag is `true` if the component does not have a custom * `deployedWhen` method or if the trivial flag was specifically set via * {@link useDeployedWhen} options (function component) or via * {@link Component.deployedWhenIsTrivial} (class component). */ get deployedWhenIsTrivial(): boolean { if (!this.mounted || !this.built()) { throw new InternalError(`deployedWhenIsTrivial can only be ` + `accessed on a built Element`); } const inst = this.instance; return inst.deployedWhen == null || this.instance.deployedWhenIsTrivial === true; } get componentName() { return this.componentType.name || "anonymous"; } get displayName() { return this.componentType.displayName || this.componentName; } get id() { return JSON.stringify(this.stateNamespace); } get instance(): GenericInstance { return this.component || this.instanceMethods; } } tagConstructor(AdaptElementImpl, "adapt"); /** * Creates a function that implements the default `deployedWhen` behavior for * an Element. * @remarks * When a component has not specified a custom `deployedWhen` * method, it will use this function to generate the default `deployedWhen` * method. * * The default `deployedWhen` behavior, implemented by this function, is to * return `true` (meaning the Element has reached the `goalStatus` and is deployed) * once the successor Element of `el` is deployed. If `el` has no successor, * it will return `true` once all of its children have become deployed. * * @param el - The Element for which a default `deployedWhen` function should * be created. * * @returns A `deployedWhen` function for Element `el` that implements the * default behavior. * @public */ export function defaultDeployedWhen(el: AdaptElement): DeployedWhenMethod { if (!isElement(el)) throw new Error(`Parameter must be an AdaptElement`); return (_goalStatus, helpers) => { if (!isElementImpl(el)) throw new InternalError(`Element is not an ElementImpl`); const succ = el.buildData.successor; // null means there's no successor and nothing in the final DOM for // this element--no primitive element and no children. if (succ === null) return true; // undefined means this element is the final one in the chain. If // this element has children, it's deployed when they are. if (succ === undefined) { const unready = childrenToArray(el.props.children) .filter(isMountedElement) .filter((k) => !helpers.isDeployed(k.props.handle)) .map((e) => e.props.handle); return unready.length === 0 ? true : waiting(`Waiting on ${unready.length} child elements`, unready); } return helpers.isDeployed(succ.props.handle) ? true : waiting(`Waiting on successor element (${succ.componentName})`, [succ.props.handle]); }; } enum BuildState { initial = "initial", deferred = "deferred", built = "built" } export class AdaptDeferredElementImpl<Props extends object> extends AdaptElementImpl<Props> { setDeferred = () => this.buildState = BuildState.deferred; shouldBuild = () => this.buildState === BuildState.deferred; //Build if we've deferred once } tagConstructor(AdaptDeferredElementImpl, "adapt"); export class AdaptPrimitiveElementImpl<Props extends object> extends AdaptDeferredElementImpl<Props> { component: PrimitiveComponent<Props> | null; constructor( readonly componentType: PrimitiveClassComponentTyp<Props>, props: Props & Partial<BuiltinProps>, children: any[] ) { super(componentType, props, children); } validate(): Message[] { if (!this.mounted) { throw new InternalError(`validate called on unmounted component at ${this.path}` ); } if (this.component == null) { throw new InternalError(`validate called but component instance not created at ${this.path}`); } let ret = this.component.validate(); if (ret === undefined) ret = []; else if (typeof ret === "string") ret = [ret]; else if (!Array.isArray(ret)) { throw new Error(`Incorrect type '${typeof ret}' returned from ` + `component validate at ${this.path}`); } return ret.map((m) => ({ type: MessageType.warning, timestamp: Date.now(), from: "DOM validate", content: `Component validation error. [${this.path}] cannot be ` + `built with current props: ${m}`, })); } } tagConstructor(AdaptPrimitiveElementImpl, "adapt"); export function createElement<Props extends object>( ctor: string | FunctionComponentTyp<Props> | ClassComponentTyp<Props, AnyState>, //props should never be null, but tsc will pass null when Props = {} in .js //See below for null workaround, exclude null here for explicit callers props: ExcludeInterface<Props, Children<any>> & Partial<BuiltinProps>, ...children: ChildType<Props>[]): AdaptElement { if (typeof ctor === "string") { throw new Error("createElement cannot called with string element type"); } let fixedProps = ((props === null) ? {} : props) as Props & Partial<BuiltinProps>; if (ctor.defaultProps) { // The 'as any' below is due to open TS bugs/PR: // https://github.com/Microsoft/TypeScript/pull/13288 fixedProps = { ...ctor.defaultProps as any, ...props as any }; } if (isPrimitive(ctor.prototype)) { return new AdaptPrimitiveElementImpl( ctor as PrimitiveClassComponentTyp<Props>, fixedProps, children); } else if (isDeferred(ctor.prototype)) { return new AdaptDeferredElementImpl( ctor as DeferredClassComponentTyp<Props, AnyState>, fixedProps, children ); } else { return new AdaptElementImpl(ctor, fixedProps, children); } } export function cloneElement( element: AdaptElement, props: AnyProps, ...children: any[]): AdaptElement { const elProps = { ...element.props }; // handle cannot be cloned delete (elProps as any).handle; const newProps = { ...elProps, ...props }; if (isPrimitiveElement(element)) { return new AdaptPrimitiveElementImpl(element.componentType, newProps, children); } else if (isDeferredElement(element)) { return new AdaptDeferredElementImpl(element.componentType, newProps, children); } else { return new AdaptElementImpl(element.componentType, newProps, children); } } export type PrimitiveChildType<T> = T extends (infer U | (infer U)[])[] ? U : T extends (infer V)[][] ? V : T extends (infer W)[] ? W : T; /** * See if props.children refers to any children * * @param propsChildren - The value of props.children to be checked * * @returns true if there are children, false otherwise * * @public */ export function childrenIsEmpty<T>(propsChildren: T | undefined): boolean { return childrenToArray(propsChildren).length === 0; } export function childrenToArray<T>(propsChildren: T | undefined): PrimitiveChildType<T>[] { const ret = simplifyChildren(propsChildren); if (ret == null) return []; if (!Array.isArray(ret)) return [ret]; return ret; } export function simplifyChildren(children: any | any[] | undefined): any | any[] | undefined { if (ld.isArray(children)) { const flatChildren = ld.flatten(children); children = flatChildren.filter((e) => e != null); if (children.length === 0) { return undefined; } else if (children.length === 1) { return children[0]; } } return children; } export interface ComponentConstructorData { deployInfo: DeployInfo; getState: () => any; setInitialState: <T extends object>(init: T) => void; stateUpdates: StateUpdater[]; observerManager: ObserverManagerDeployment; } let componentConstructorStack: ComponentConstructorData[] = []; // exported as support utility for testing only export function setComponentConstructorStack_(stack: ComponentConstructorData[]): ComponentConstructorData[] { const old = componentConstructorStack; componentConstructorStack = stack; return old; } export function pushComponentConstructorData(d: ComponentConstructorData) { componentConstructorStack.push(d); } export function popComponentConstructorData() { componentConstructorStack.pop(); } export function getComponentConstructorData(): ComponentConstructorData { const data = ld.last(componentConstructorStack); if (data == null) { throw new InternalError(`componentConstructorStack is empty`); } return data; }
the_stack
import { sr25519Verify, waitReady } from '@polkadot/wasm-crypto' import { PolkadotProtocol } from '../../../src/protocols/substrate/polkadot/PolkadotProtocol' import { SubstrateNetwork } from '../../../src/protocols/substrate/SubstrateNetwork' import { AirGapWalletStatus } from '../../../src/wallet/AirGapWallet' import { TestProtocolSpec } from '../implementations' import { PolkadotProtocolStub } from '../stubs/polkadot.stub' /* * Test Mnemonic: leopard crouch simple blind castle they elder enact slow rate mad blanket saddle tail silk fury quarter obscure interest exact veteran volcano fabric cherry * */ // Test Mnemonic: food talent voyage degree siege clever account medal film remind good kind // Private Key: d08bc6388fdeb30fc34a8e0286384bd5a84b838222bb9b012fc227d7473fc87aa2913d02297653ce859ccd6b2c057f7e57c9ef6cc359300a891c581fb6d03141 // Public Key: 52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10 // Hex Seed: 55a1417bbfacd64e069b4d07e47fb34ce9ff53b15556698038604f002524aec0 // Address (Polkadot SS58): 12sg1sXe71bazrBzAyEaF71puZbNJVaMZ92uBfMCfFNfSA9P export class PolkadotTestProtocolSpec extends TestProtocolSpec { public name = 'Polkadot' public lib = new PolkadotProtocol() public stub = new PolkadotProtocolStub() public validAddresses = [ '16CuDZEYc5oQkkNXvxq5Q3K44RVwW7DWbw8ZW83H2QG7kc4x', '15ajKAj3bAtjsKyVe55LvGok3fB2WGAC4K1g3zYsahzPumJr', '15VtKrtqtAiptfZwcpagQUNVSKgPTyF8JJJi32JXf4vSkSYC', '143RsnrR7y89kwDWvVWp6iNyGg8TiFUZXWVjSpCYaDMLqE1j', '1rqrUJQBhx6deZYLFd21LtNusPPf6kN8k7AAEanXqPrM58f', '13BjXUHsqAvLJrGDKcEbVzgdGMSobNPBjvLvd8NyiH9iaHCU', '1ZZpAwuPzyWxGTnkUNrA7Pjo6nFYRmMXLk6cwzzUk8Ua9Sv', '1N3hXfu4Ut4bPMq6ciWYAieCiZg5e4Kg5LjMPtMV4WaV7eF', '16Y64EP5JLiM29pCQzDHkdvsCuWA7tYvs7tqSaDs6w3BeJh4', '13wUHTgsup34hQ4e2Rye7sf6Ppn1V5coCZJxyU7jsVdp3uJw' ] public wallet = { privateKey: 'd08bc6388fdeb30fc34a8e0286384bd5a84b838222bb9b012fc227d7473fc87aa2913d02297653ce859ccd6b2c057f7e57c9ef6cc359300a891c581fb6d03141', publicKey: '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10', addresses: ['12sg1sXe71bazrBzAyEaF71puZbNJVaMZ92uBfMCfFNfSA9P'], masterFingerprint: 'f4e222fd', status: AirGapWalletStatus.ACTIVE } public txs = [ { from: this.wallet.addresses, to: this.wallet.addresses, amount: '1000000000000', fee: '1000000000', unsignedTx: { encoded: // tslint:disable-next-line: prefer-template '04' + // number of txs '2106' + // tx length '01' + // optional type (specVersion) '1e000000' + // specVersion '00' + // type '02286bee' + // fee // transaction '4102' + // length '84' + // signed flag (not signed) '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId signer '00' + // signature type (ed25519) '0000000000000000000000000000000000000000000000000000000000000000' + // signature '0000000000000000000000000000000000000000000000000000000000000000' + // signature '8503' + // era '04' + // nonce '00' + // tip '0400' + // moduleId + callId '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination '070010a5d4e8' + // value // payload 'a903' + // payload length Buffer.from( '0400' + // moduleId + callId '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination '070010a5d4e8' + // value '8503' + // era '04' + // nonce '00' + // tip '1e000000' + // specVersion '01000000' + // transactionVersion 'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash '33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash ).toString('hex') // payload }, signedTx: // tslint:disable-next-line: prefer-template '04' + // number of txs '2106' + // tx length '01' + // optional type (specVersion) '1e000000' + // specVersion '00' + // type '02286bee' + // fee // transaction '4102' + // length '84' + // signed flag (signed) '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId signer '00' + // signature type (ed25519) 'e209d71282bbff8af2f4362e4b478d156c9c1df81e2a7d733912525308909a16' + // signature 'adf7eb5602136d4b0a9a57acdd07a443f3bc4865c2455bf36f01ff9fa9b4478d' + // signature '8503' + // era '04' + // nonce '00' + // tip '0400' + // moduleId + callId '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination '070010a5d4e8' + // value // payload 'a903' + // payload length Buffer.from( '0400' + // moduleId + callId '00' + // MultiAddress type '52e1d70619678f95a0806fa5eb818fc938cd5f885a19c3fb242d0b0d0620ee10' + // AccountId destination '070010a5d4e8' + // value '8503' + // era '04' + // nonce '00' + // tip '1e000000' + // specVersion '01000000' + // transactionVersion 'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash '33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash ).toString('hex') // payload } ] public verifySignature = async (publicKey: string, tx: any): Promise<boolean> => { await waitReady() const decoded = this.lib.options.transactionController.decodeDetails(tx)[0] const signature = decoded.transaction.signature.signature.value const payload = Buffer.from(decoded.payload, 'hex') const publicKeyBuffer = Buffer.from(publicKey, 'hex') return sr25519Verify(signature, payload, publicKeyBuffer) } public seed(): string { return '55a1417bbfacd64e069b4d07e47fb34ce9ff53b15556698038604f002524aec0' } public mnemonic(): string { return 'food talent voyage degree siege clever account medal film remind good kind' } public messages = [ { message: 'example message', signature: '0x98160df00de787087cd9599ff5e59ac8c99af6c53a319a96b0a9e1f6e634ce5fed9db553b759a115c3d9d6fcdd0f11705656bad16ea3ee9f20390f253c7cd58a' } ] public encryptAES = [ { message: 'example message', encrypted: 'a3677b19a6ba036288ec2261b620a805!15a385b47009a2b55f587ed9f897e2!f649bbcb1c46c48b0078dc7d40a642a9' } ] public transactionResult = { transactions: [ { protocolIdentifier: 'polkadot', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: 'https://polkadot-node.prod.gke.papers.tech', blockExplorer: { blockExplorer: 'https://polkascan.io/polkadot' }, extras: { apiUrl: 'https://polkadot.subscan.io/api/scan', network: SubstrateNetwork.POLKADOT } }, from: ['16CuDZEYc5oQkkNXvxq5Q3K44RVwW7DWbw8ZW83H2QG7kc4x'], to: ['15ajKAj3bAtjsKyVe55LvGok3fB2WGAC4K1g3zYsahzPumJr'], isInbound: true, amount: '99977416667634', fee: '2583332366', timestamp: 1601036370, hash: '0x33482af443df63c3b0c9b5920b0723256a1e69602bba0bbe50cae3cb469084a5', blockHeight: 4200705, status: 'applied' }, { protocolIdentifier: 'polkadot', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: 'https://polkadot-node.prod.gke.papers.tech', blockExplorer: { blockExplorer: 'https://polkascan.io/polkadot' }, extras: { apiUrl: 'https://polkadot.subscan.io/api/scan', network: SubstrateNetwork.POLKADOT } }, from: ['16CuDZEYc5oQkkNXvxq5Q3K44RVwW7DWbw8ZW83H2QG7kc4x'], to: ['15ajKAj3bAtjsKyVe55LvGok3fB2WGAC4K1g3zYsahzPumJr'], isInbound: false, amount: '1020000000000', fee: '2583332366', timestamp: 1601034570, hash: '0xffef69ea4dbceef33bd904a2aaf92129cca4435642d7f71e85dbccb91d53c3af', blockHeight: 4200409, status: 'applied' } ], cursor: { page: 1 } } public nextTransactionResult = { transactions: [ { protocolIdentifier: 'polkadot', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: 'https://polkadot-node.prod.gke.papers.tech', blockExplorer: { blockExplorer: 'https://polkascan.io/polkadot' }, extras: { apiUrl: 'https://polkadot.subscan.io/api/scan', network: SubstrateNetwork.POLKADOT } }, from: ['16CuDZEYc5oQkkNXvxq5Q3K44RVwW7DWbw8ZW83H2QG7kc4x'], to: ['15ajKAj3bAtjsKyVe55LvGok3fB2WGAC4K1g3zYsahzPumJr'], isInbound: false, amount: '15966000000000', fee: '2599999026', timestamp: 1601030652, hash: '0xd02429787c9f28692018a2147ad093222857e686563c1166a1338fa9b624b9d3', blockHeight: 4199759, status: 'applied' }, { protocolIdentifier: 'polkadot', network: { name: 'Mainnet', type: 'MAINNET', rpcUrl: 'https://polkadot-node.prod.gke.papers.tech', blockExplorer: { blockExplorer: 'https://polkascan.io/polkadot' }, extras: { apiUrl: 'https://polkadot.subscan.io/api/scan', network: SubstrateNetwork.POLKADOT } }, from: ['16CuDZEYc5oQkkNXvxq5Q3K44RVwW7DWbw8ZW83H2QG7kc4x'], to: ['15ajKAj3bAtjsKyVe55LvGok3fB2WGAC4K1g3zYsahzPumJr'], isInbound: false, amount: '3800000000000', fee: '2599999026', timestamp: 1601030412, hash: '0x898a890d48861039715bd8d0671593ddf62c539f4b566fcab02859ff2b172c64', blockHeight: 4199719, status: 'applied' } ], cursor: { page: 2 } } }
the_stack
interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; signal?: AbortSignal; } interface CustomEventInit<T = any> extends EventInit { detail?: T; } interface ErrorEventInit extends EventInit { colno?: number; error?: any; filename?: string; lineno?: number; message?: string; } interface EventInit { bubbles?: boolean; cancelable?: boolean; composed?: boolean; } interface EventListenerOptions { capture?: boolean; } interface MessageEventInit<T = any> extends EventInit { data?: T; lastEventId?: string; origin?: string; ports?: MessagePort[]; source?: MessageEventSource | null; } interface PerformanceMarkOptions { detail?: any; startTime?: DOMHighResTimeStamp; } interface PerformanceMeasureOptions { detail?: any; duration?: DOMHighResTimeStamp; end?: string | DOMHighResTimeStamp; start?: string | DOMHighResTimeStamp; } interface PerformanceObserverInit { buffered?: boolean; entryTypes?: string[]; type?: string; } interface PromiseRejectionEventInit extends EventInit { promise: Promise<any>; reason?: any; } interface QueuingStrategy<T = any> { highWaterMark?: number; size?: QueuingStrategySize<T>; } interface QueuingStrategyInit { /** * Creates a new ByteLengthQueuingStrategy with the provided high water mark. * * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. */ highWaterMark: number; } interface ReadableStreamReadDoneResult { done: true; value?: undefined; } interface ReadableStreamReadValueResult<T> { done: false; value: T; } interface ReadableWritablePair<R = any, W = any> { readable: ReadableStream<R>; /** * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. */ writable: WritableStream<W>; } interface StreamPipeOptions { preventAbort?: boolean; preventCancel?: boolean; /** * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. * * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. * * Errors and closures of the source and destination streams propagate as follows: * * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. * * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. * * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. * * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. * * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. */ preventClose?: boolean; signal?: AbortSignal; } interface StructuredSerializeOptions { transfer?: Transferable[]; } interface TextDecodeOptions { stream?: boolean; } interface TextDecoderOptions { fatal?: boolean; ignoreBOM?: boolean; } interface TextEncoderEncodeIntoResult { read?: number; written?: number; } interface Transformer<I = any, O = any> { flush?: TransformerFlushCallback<O>; readableType?: undefined; start?: TransformerStartCallback<O>; transform?: TransformerTransformCallback<I, O>; writableType?: undefined; } interface UnderlyingSink<W = any> { abort?: UnderlyingSinkAbortCallback; close?: UnderlyingSinkCloseCallback; start?: UnderlyingSinkStartCallback; type?: undefined; write?: UnderlyingSinkWriteCallback<W>; } interface UnderlyingSource<R = any> { cancel?: UnderlyingSourceCancelCallback; pull?: UnderlyingSourcePullCallback<R>; start?: UnderlyingSourceStartCallback<R>; type?: undefined; } /** A controller object that allows you to abort one or more DOM requests as and when desired. */ interface AbortController { /** Returns the AbortSignal object associated with this object. */ readonly signal: AbortSignal; /** Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. */ abort(reason?: any): void; } declare var AbortController: { prototype: AbortController; new(): AbortController; }; interface AbortSignalEventMap { "abort": Event; } /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ interface AbortSignal extends EventTarget { /** Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. */ readonly aborted: boolean; onabort: ((this: AbortSignal, ev: Event) => any) | null; readonly reason: any; throwIfAborted(): void; addEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof AbortSignalEventMap>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var AbortSignal: { prototype: AbortSignal; new(): AbortSignal; abort(reason?: any): AbortSignal; }; interface AudioWorkletGlobalScope extends WorkletGlobalScope { readonly currentFrame: number; readonly currentTime: number; readonly sampleRate: number; registerProcessor(name: string, processorCtor: AudioWorkletProcessorConstructor): void; } declare var AudioWorkletGlobalScope: { prototype: AudioWorkletGlobalScope; new(): AudioWorkletGlobalScope; }; interface AudioWorkletProcessor { readonly port: MessagePort; } declare var AudioWorkletProcessor: { prototype: AudioWorkletProcessor; new(): AudioWorkletProcessor; }; interface AudioWorkletProcessorImpl extends AudioWorkletProcessor { process(inputs: Float32Array[][], outputs: Float32Array[][], parameters: Record<string, Float32Array>): boolean; } /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */ interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> { readonly highWaterMark: number; readonly size: QueuingStrategySize<ArrayBufferView>; } declare var ByteLengthQueuingStrategy: { prototype: ByteLengthQueuingStrategy; new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; }; /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */ interface CountQueuingStrategy extends QueuingStrategy { readonly highWaterMark: number; readonly size: QueuingStrategySize; } declare var CountQueuingStrategy: { prototype: CountQueuingStrategy; new(init: QueuingStrategyInit): CountQueuingStrategy; }; interface CustomEvent<T = any> extends Event { /** Returns any custom data event was created with. Typically used for synthetic events. */ readonly detail: T; /** @deprecated */ initCustomEvent(type: string, bubbles?: boolean, cancelable?: boolean, detail?: T): void; } declare var CustomEvent: { prototype: CustomEvent; new<T>(type: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>; }; /** Events providing information related to errors in scripts or in files. */ interface ErrorEvent extends Event { readonly colno: number; readonly error: any; readonly filename: string; readonly lineno: number; readonly message: string; } declare var ErrorEvent: { prototype: ErrorEvent; new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent; }; /** An event which takes place in the DOM. */ interface Event { /** Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. */ readonly bubbles: boolean; cancelBubble: boolean; /** Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. */ readonly cancelable: boolean; /** Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. */ readonly composed: boolean; /** Returns the object whose event listener's callback is currently being invoked. */ readonly currentTarget: EventTarget | null; /** Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. */ readonly defaultPrevented: boolean; /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. */ readonly eventPhase: number; /** Returns true if event was dispatched by the user agent, and false otherwise. */ readonly isTrusted: boolean; /** @deprecated */ returnValue: boolean; /** @deprecated */ readonly srcElement: EventTarget | null; /** Returns the object to which event is dispatched (its target). */ readonly target: EventTarget | null; /** Returns the event's timestamp as the number of milliseconds measured relative to the time origin. */ readonly timeStamp: DOMHighResTimeStamp; /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ readonly type: string; /** Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. */ composedPath(): EventTarget[]; /** @deprecated */ initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; /** If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. */ preventDefault(): void; /** Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. */ stopImmediatePropagation(): void; /** When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. */ stopPropagation(): void; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; readonly NONE: number; } declare var Event: { prototype: Event; new(type: string, eventInitDict?: EventInit): Event; readonly AT_TARGET: number; readonly BUBBLING_PHASE: number; readonly CAPTURING_PHASE: number; readonly NONE: number; }; interface EventListener { (evt: Event): void; } interface EventListenerObject { handleEvent(object: Event): void; } /** EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. */ interface EventTarget { /** * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. * * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. * * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. * * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. * * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. * * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. * * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. */ addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: AddEventListenerOptions | boolean): void; /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ dispatchEvent(event: Event): boolean; /** Removes the event listener in target's event listener list with the same type, callback, and options. */ removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; } declare var EventTarget: { prototype: EventTarget; new(): EventTarget; }; interface GenericTransformStream { readonly readable: ReadableStream; readonly writable: WritableStream; } /** A message received by a target object. */ interface MessageEvent<T = any> extends Event { /** Returns the data of the message. */ readonly data: T; /** Returns the last event ID string, for server-sent events. */ readonly lastEventId: string; /** Returns the origin of the message, for server-sent events and cross-document messaging. */ readonly origin: string; /** Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. */ readonly ports: ReadonlyArray<MessagePort>; /** Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. */ readonly source: MessageEventSource | null; /** @deprecated */ initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: MessagePort[]): void; } declare var MessageEvent: { prototype: MessageEvent; new<T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>; }; interface MessagePortEventMap { "message": MessageEvent; "messageerror": MessageEvent; } /** This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. */ interface MessagePort extends EventTarget { onmessage: ((this: MessagePort, ev: MessageEvent) => any) | null; onmessageerror: ((this: MessagePort, ev: MessageEvent) => any) | null; /** Disconnects the port, so that it is no longer active. */ close(): void; /** * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. * * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. */ postMessage(message: any, transfer: Transferable[]): void; postMessage(message: any, options?: StructuredSerializeOptions): void; /** Begins dispatching messages received on the port. */ start(): void; addEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var MessagePort: { prototype: MessagePort; new(): MessagePort; }; interface PerformanceEventMap { "resourcetimingbufferfull": Event; } /** Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API. */ interface Performance extends EventTarget { onresourcetimingbufferfull: ((this: Performance, ev: Event) => any) | null; readonly timeOrigin: DOMHighResTimeStamp; clearMarks(markName?: string): void; clearMeasures(measureName?: string): void; clearResourceTimings(): void; getEntries(): PerformanceEntryList; getEntriesByName(name: string, type?: string): PerformanceEntryList; getEntriesByType(type: string): PerformanceEntryList; mark(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; measure(measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions, endMark?: string): PerformanceMeasure; now(): DOMHighResTimeStamp; setResourceTimingBufferSize(maxSize: number): void; toJSON(): any; addEventListener<K extends keyof PerformanceEventMap>(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof PerformanceEventMap>(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var Performance: { prototype: Performance; new(): Performance; }; /** Encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image). */ interface PerformanceEntry { readonly duration: DOMHighResTimeStamp; readonly entryType: string; readonly name: string; readonly startTime: DOMHighResTimeStamp; toJSON(): any; } declare var PerformanceEntry: { prototype: PerformanceEntry; new(): PerformanceEntry; }; /** PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline. */ interface PerformanceMark extends PerformanceEntry { readonly detail: any; } declare var PerformanceMark: { prototype: PerformanceMark; new(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark; }; /** PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline. */ interface PerformanceMeasure extends PerformanceEntry { readonly detail: any; } declare var PerformanceMeasure: { prototype: PerformanceMeasure; new(): PerformanceMeasure; }; interface PerformanceObserver { disconnect(): void; observe(options?: PerformanceObserverInit): void; takeRecords(): PerformanceEntryList; } declare var PerformanceObserver: { prototype: PerformanceObserver; new(callback: PerformanceObserverCallback): PerformanceObserver; readonly supportedEntryTypes: ReadonlyArray<string>; }; interface PerformanceObserverEntryList { getEntries(): PerformanceEntryList; getEntriesByName(name: string, type?: string): PerformanceEntryList; getEntriesByType(type: string): PerformanceEntryList; } declare var PerformanceObserverEntryList: { prototype: PerformanceObserverEntryList; new(): PerformanceObserverEntryList; }; interface PromiseRejectionEvent extends Event { readonly promise: Promise<any>; readonly reason: any; } declare var PromiseRejectionEvent: { prototype: PromiseRejectionEvent; new(type: string, eventInitDict: PromiseRejectionEventInit): PromiseRejectionEvent; }; interface ReadableByteStreamController { readonly byobRequest: ReadableStreamBYOBRequest | null; readonly desiredSize: number | null; close(): void; enqueue(chunk: ArrayBufferView): void; error(e?: any): void; } declare var ReadableByteStreamController: { prototype: ReadableByteStreamController; new(): ReadableByteStreamController; }; /** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */ interface ReadableStream<R = any> { readonly locked: boolean; cancel(reason?: any): Promise<void>; getReader(): ReadableStreamDefaultReader<R>; pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>; pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>; tee(): [ReadableStream<R>, ReadableStream<R>]; } declare var ReadableStream: { prototype: ReadableStream; new<R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>; }; interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { read(view: ArrayBufferView): Promise<ReadableStreamReadResult<ArrayBufferView>>; releaseLock(): void; } declare var ReadableStreamBYOBReader: { prototype: ReadableStreamBYOBReader; new(stream: ReadableStream): ReadableStreamBYOBReader; }; interface ReadableStreamBYOBRequest { readonly view: ArrayBufferView | null; respond(bytesWritten: number): void; respondWithNewView(view: ArrayBufferView): void; } declare var ReadableStreamBYOBRequest: { prototype: ReadableStreamBYOBRequest; new(): ReadableStreamBYOBRequest; }; interface ReadableStreamDefaultController<R = any> { readonly desiredSize: number | null; close(): void; enqueue(chunk?: R): void; error(e?: any): void; } declare var ReadableStreamDefaultController: { prototype: ReadableStreamDefaultController; new(): ReadableStreamDefaultController; }; interface ReadableStreamDefaultReader<R = any> extends ReadableStreamGenericReader { read(): Promise<ReadableStreamReadResult<R>>; releaseLock(): void; } declare var ReadableStreamDefaultReader: { prototype: ReadableStreamDefaultReader; new<R = any>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>; }; interface ReadableStreamGenericReader { readonly closed: Promise<undefined>; cancel(reason?: any): Promise<void>; } /** A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */ interface TextDecoder extends TextDecoderCommon { /** * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. * * ``` * var string = "", decoder = new TextDecoder(encoding), buffer; * while(buffer = next_chunk()) { * string += decoder.decode(buffer, {stream:true}); * } * string += decoder.decode(); // end-of-queue * ``` * * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. */ decode(input?: BufferSource, options?: TextDecodeOptions): string; } declare var TextDecoder: { prototype: TextDecoder; new(label?: string, options?: TextDecoderOptions): TextDecoder; }; interface TextDecoderCommon { /** Returns encoding's name, lowercased. */ readonly encoding: string; /** Returns true if error mode is "fatal", otherwise false. */ readonly fatal: boolean; /** Returns the value of ignore BOM. */ readonly ignoreBOM: boolean; } interface TextDecoderStream extends GenericTransformStream, TextDecoderCommon { readonly readable: ReadableStream<string>; readonly writable: WritableStream<BufferSource>; } declare var TextDecoderStream: { prototype: TextDecoderStream; new(label?: string, options?: TextDecoderOptions): TextDecoderStream; }; /** TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. */ interface TextEncoder extends TextEncoderCommon { /** Returns the result of running UTF-8's encoder. */ encode(input?: string): Uint8Array; /** Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. */ encodeInto(source: string, destination: Uint8Array): TextEncoderEncodeIntoResult; } declare var TextEncoder: { prototype: TextEncoder; new(): TextEncoder; }; interface TextEncoderCommon { /** Returns "utf-8". */ readonly encoding: string; } interface TextEncoderStream extends GenericTransformStream, TextEncoderCommon { readonly readable: ReadableStream<Uint8Array>; readonly writable: WritableStream<string>; } declare var TextEncoderStream: { prototype: TextEncoderStream; new(): TextEncoderStream; }; interface TransformStream<I = any, O = any> { readonly readable: ReadableStream<O>; readonly writable: WritableStream<I>; } declare var TransformStream: { prototype: TransformStream; new<I = any, O = any>(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>): TransformStream<I, O>; }; interface TransformStreamDefaultController<O = any> { readonly desiredSize: number | null; enqueue(chunk?: O): void; error(reason?: any): void; terminate(): void; } declare var TransformStreamDefaultController: { prototype: TransformStreamDefaultController; new(): TransformStreamDefaultController; }; /** The URL interface represents an object providing static methods used for creating object URLs. */ interface URL { hash: string; host: string; hostname: string; href: string; toString(): string; readonly origin: string; password: string; pathname: string; port: string; protocol: string; search: string; readonly searchParams: URLSearchParams; username: string; toJSON(): string; } declare var URL: { prototype: URL; new(url: string | URL, base?: string | URL): URL; }; interface URLSearchParams { /** Appends a specified key/value pair as a new search parameter. */ append(name: string, value: string): void; /** Deletes the given search parameter, and its associated value, from the list of all search parameters. */ delete(name: string): void; /** Returns the first value associated to the given search parameter. */ get(name: string): string | null; /** Returns all the values association with a given search parameter. */ getAll(name: string): string[]; /** Returns a Boolean indicating if such a search parameter exists. */ has(name: string): boolean; /** Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. */ set(name: string, value: string): void; sort(): void; /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ toString(): string; forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; } declare var URLSearchParams: { prototype: URLSearchParams; new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams; toString(): string; }; /** Available only in secure contexts. */ interface WorkletGlobalScope { } declare var WorkletGlobalScope: { prototype: WorkletGlobalScope; new(): WorkletGlobalScope; }; /** This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. */ interface WritableStream<W = any> { readonly locked: boolean; abort(reason?: any): Promise<void>; close(): Promise<void>; getWriter(): WritableStreamDefaultWriter<W>; } declare var WritableStream: { prototype: WritableStream; new<W = any>(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>; }; /** This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. */ interface WritableStreamDefaultController { readonly signal: AbortSignal; error(e?: any): void; } declare var WritableStreamDefaultController: { prototype: WritableStreamDefaultController; new(): WritableStreamDefaultController; }; /** This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. */ interface WritableStreamDefaultWriter<W = any> { readonly closed: Promise<undefined>; readonly desiredSize: number | null; readonly ready: Promise<undefined>; abort(reason?: any): Promise<void>; close(): Promise<void>; releaseLock(): void; write(chunk?: W): Promise<void>; } declare var WritableStreamDefaultWriter: { prototype: WritableStreamDefaultWriter; new<W = any>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>; }; interface Console { assert(condition?: boolean, ...data: any[]): void; clear(): void; count(label?: string): void; countReset(label?: string): void; debug(...data: any[]): void; dir(item?: any, options?: any): void; dirxml(...data: any[]): void; error(...data: any[]): void; group(...data: any[]): void; groupCollapsed(...data: any[]): void; groupEnd(): void; info(...data: any[]): void; log(...data: any[]): void; table(tabularData?: any, properties?: string[]): void; time(label?: string): void; timeEnd(label?: string): void; timeLog(label?: string, ...data: any[]): void; timeStamp(label?: string): void; trace(...data: any[]): void; warn(...data: any[]): void; } declare var console: Console; declare namespace WebAssembly { interface CompileError extends Error { } var CompileError: { prototype: CompileError; new(message?: string): CompileError; (message?: string): CompileError; }; interface Global { value: any; valueOf(): any; } var Global: { prototype: Global; new(descriptor: GlobalDescriptor, v?: any): Global; }; interface Instance { readonly exports: Exports; } var Instance: { prototype: Instance; new(module: Module, importObject?: Imports): Instance; }; interface LinkError extends Error { } var LinkError: { prototype: LinkError; new(message?: string): LinkError; (message?: string): LinkError; }; interface Memory { readonly buffer: ArrayBuffer; grow(delta: number): number; } var Memory: { prototype: Memory; new(descriptor: MemoryDescriptor): Memory; }; interface Module { } var Module: { prototype: Module; new(bytes: BufferSource): Module; customSections(moduleObject: Module, sectionName: string): ArrayBuffer[]; exports(moduleObject: Module): ModuleExportDescriptor[]; imports(moduleObject: Module): ModuleImportDescriptor[]; }; interface RuntimeError extends Error { } var RuntimeError: { prototype: RuntimeError; new(message?: string): RuntimeError; (message?: string): RuntimeError; }; interface Table { readonly length: number; get(index: number): any; grow(delta: number, value?: any): number; set(index: number, value?: any): void; } var Table: { prototype: Table; new(descriptor: TableDescriptor, value?: any): Table; }; interface GlobalDescriptor { mutable?: boolean; value: ValueType; } interface MemoryDescriptor { initial: number; maximum?: number; shared?: boolean; } interface ModuleExportDescriptor { kind: ImportExportKind; name: string; } interface ModuleImportDescriptor { kind: ImportExportKind; module: string; name: string; } interface TableDescriptor { element: TableKind; initial: number; maximum?: number; } interface WebAssemblyInstantiatedSource { instance: Instance; module: Module; } type ImportExportKind = "function" | "global" | "memory" | "table"; type TableKind = "anyfunc" | "externref"; type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; type ExportValue = Function | Global | Memory | Table; type Exports = Record<string, ExportValue>; type ImportValue = ExportValue | number; type Imports = Record<string, ModuleImports>; type ModuleImports = Record<string, ImportValue>; function compile(bytes: BufferSource): Promise<Module>; function instantiate(bytes: BufferSource, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>; function instantiate(moduleObject: Module, importObject?: Imports): Promise<Instance>; function validate(bytes: BufferSource): boolean; } interface AudioWorkletProcessorConstructor { new (options: any): AudioWorkletProcessorImpl; } interface PerformanceObserverCallback { (entries: PerformanceObserverEntryList, observer: PerformanceObserver): void; } interface QueuingStrategySize<T = any> { (chunk: T): number; } interface TransformerFlushCallback<O> { (controller: TransformStreamDefaultController<O>): void | PromiseLike<void>; } interface TransformerStartCallback<O> { (controller: TransformStreamDefaultController<O>): any; } interface TransformerTransformCallback<I, O> { (chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>; } interface UnderlyingSinkAbortCallback { (reason?: any): void | PromiseLike<void>; } interface UnderlyingSinkCloseCallback { (): void | PromiseLike<void>; } interface UnderlyingSinkStartCallback { (controller: WritableStreamDefaultController): any; } interface UnderlyingSinkWriteCallback<W> { (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike<void>; } interface UnderlyingSourceCancelCallback { (reason?: any): void | PromiseLike<void>; } interface UnderlyingSourcePullCallback<R> { (controller: ReadableStreamController<R>): void | PromiseLike<void>; } interface UnderlyingSourceStartCallback<R> { (controller: ReadableStreamController<R>): any; } declare var currentFrame: number; declare var currentTime: number; declare var sampleRate: number; declare function registerProcessor(name: string, processorCtor: AudioWorkletProcessorConstructor): void; type BufferSource = ArrayBufferView | ArrayBuffer; type DOMHighResTimeStamp = number; type EventListenerOrEventListenerObject = EventListener | EventListenerObject; type MessageEventSource = MessagePort; type PerformanceEntryList = PerformanceEntry[]; type ReadableStreamController<T> = ReadableStreamDefaultController<T>; type ReadableStreamReadResult<T> = ReadableStreamReadValueResult<T> | ReadableStreamReadDoneResult; type ReadableStreamReader<T> = ReadableStreamDefaultReader<T>; type Transferable = ArrayBuffer | MessagePort;
the_stack
export interface PlanDetailInfo { /** * 默认策略,1为默认,0为非默认 */ IsDefault: number; /** * 策略id */ PlanId: number; /** * 策略名称 */ PlanName: string; /** * 策略信息 */ PlanInfo: PlanInfo; } /** * 加固后app的信息,包含基本信息和加固信息 */ export interface AppSetInfo { /** * 任务唯一标识 */ ItemId: string; /** * app的名称 */ AppName: string; /** * app的包名 */ AppPkgName: string; /** * app的版本号 */ AppVersion: string; /** * app的md5 */ AppMd5: string; /** * app的大小 */ AppSize: number; /** * 加固服务版本 */ ServiceEdition: string; /** * 加固结果返回码 */ ShieldCode: number; /** * 加固后的APP下载地址 */ AppUrl?: string; /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ TaskStatus: number; /** * 请求的客户端ip */ ClientIp: string; /** * 提交加固时间 */ TaskTime: number; /** * app的图标url */ AppIconUrl: string; /** * 加固后app的md5 */ ShieldMd5: string; /** * 加固后app的大小 */ ShieldSize: number; } /** * CreateShieldPlanInstance返回参数结构体 */ export interface CreateShieldPlanInstanceResponse { /** * 策略id */ PlanId?: number; /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 需要扫描的应用的服务信息 */ export interface ScanInfo { /** * 任务处理完成后的反向通知回调地址,批量提交app每扫描完成一个会通知一次,通知为POST请求,post信息{ItemId: */ CallbackUrl: string; /** * VULSCAN-漏洞扫描信息,VIRUSSCAN-返回病毒扫描信息, ADSCAN-广告扫描信息,PLUGINSCAN-插件扫描信息,PERMISSION-系统权限信息,SENSITIVE-敏感词信息,可以自由组合 */ ScanTypes: Array<string>; } /** * CreateResourceInstances请求参数结构体 */ export interface CreateResourceInstancesRequest { /** * 资源类型id。13624:加固专业版。 */ Pid: number; /** * 时间单位,取值为d,m,y,分别表示天,月,年。 */ TimeUnit: string; /** * 时间数量。 */ TimeSpan: number; /** * 资源数量。 */ ResourceNum: number; } /** * DescribeShieldInstances返回参数结构体 */ export interface DescribeShieldInstancesResponse { /** * 符合要求的app数量 */ TotalCount?: number; /** * 一个关于app详细信息的结构体,主要包括app的基本信息和加固信息。 */ AppSet?: Array<AppSetInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 插件信息 */ export interface PluginInfo { /** * 插件类型,分别为 1-通知栏广告,2-积分墙广告,3-banner广告,4- 悬浮窗图标广告,5-精品推荐列表广告, 6-插播广告 */ PluginType: number; /** * 插件名称 */ PluginName: string; /** * 插件描述 */ PluginDesc: string; } /** * 安全扫描敏感词列表 */ export interface ScanSensitiveList { /** * 敏感词列表 */ SensitiveList: Array<ScanSensitiveInfo>; } /** * DescribeShieldResult请求参数结构体 */ export interface DescribeShieldResultRequest { /** * 任务唯一标识 */ ItemId: string; } /** * CreateShieldInstance请求参数结构体 */ export interface CreateShieldInstanceRequest { /** * 待加固的应用信息 */ AppInfo: AppInfo; /** * 加固服务信息 */ ServiceInfo: ServiceInfo; } /** * CreateCosSecKeyInstance请求参数结构体 */ export interface CreateCosSecKeyInstanceRequest { /** * 地域信息,例如广州:ap-guangzhou,上海:ap-shanghai,默认为广州。 */ CosRegion?: string; /** * 密钥有效时间,默认为1小时。 */ Duration?: number; } /** * DescribeScanResults返回参数结构体 */ export interface DescribeScanResultsResponse { /** * 批量扫描的app结果集 */ ScanSet?: Array<ScanSetInfo>; /** * 批量扫描结果的个数 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateScanInstances请求参数结构体 */ export interface CreateScanInstancesRequest { /** * 待扫描的app信息列表,一次最多提交20个 */ AppInfos: Array<AppInfo>; /** * 扫描信息 */ ScanInfo: ScanInfo; } /** * DescribeUserBaseInfoInstance返回参数结构体 */ export interface DescribeUserBaseInfoInstanceResponse { /** * 用户uin信息 */ UserUin?: number; /** * 用户APPID信息 */ UserAppid?: number; /** * 系统时间戳 */ TimeStamp?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateShieldPlanInstance请求参数结构体 */ export interface CreateShieldPlanInstanceRequest { /** * 资源id */ ResourceId: string; /** * 策略名称 */ PlanName: string; /** * 策略具体信息 */ PlanInfo: PlanInfo; } /** * app扫描结果集 */ export interface ScanSetInfo { /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ TaskStatus: number; /** * app信息 */ AppDetailInfo: AppDetailInfo; /** * 病毒信息 */ VirusInfo: VirusInfo; /** * 漏洞信息 */ VulInfo: VulInfo; /** * 广告插件信息 */ AdInfo: AdInfo; /** * 提交扫描的时间 */ TaskTime: number; /** * 状态码,成功返回0,失败返回错误码 */ StatusCode: number; /** * 状态描述 */ StatusDesc: string; /** * 状态操作指引 */ StatusRef: string; /** * 系统权限信息 */ PermissionInfo: ScanPermissionList; /** * 敏感词列表 */ SensitiveInfo: ScanSensitiveList; } /** * 扫描后app的信息,包含基本信息和扫描状态信息 */ export interface AppScanSet { /** * 任务唯一标识 */ ItemId: string; /** * app的名称 */ AppName: string; /** * app的包名 */ AppPkgName: string; /** * app的版本号 */ AppVersion: string; /** * app的md5 */ AppMd5: string; /** * app的大小 */ AppSize: number; /** * 扫描结果返回码 */ ScanCode: number; /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ TaskStatus: number; /** * 提交扫描时间 */ TaskTime: number; /** * app的图标url */ AppIconUrl: string; /** * 标识唯一该app,主要用于删除 */ AppSid: string; /** * 安全类型:1-安全软件,2-风险软件,3病毒软件 */ SafeType: number; /** * 漏洞个数 */ VulCount: number; } /** * 加固策略信息 */ export interface ShieldPlanInfo { /** * 加固策略数量 */ TotalCount: number; /** * 加固策略具体信息数组 */ PlanSet: Array<PlanDetailInfo>; } /** * CreateBindInstance请求参数结构体 */ export interface CreateBindInstanceRequest { /** * 资源id,全局唯一 */ ResourceId: string; /** * app的icon的url */ AppIconUrl: string; /** * app的名称 */ AppName: string; /** * app的包名 */ AppPkgName: string; } /** * CreateShieldInstance返回参数结构体 */ export interface CreateShieldInstanceResponse { /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 任务唯一标识 */ ItemId?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteShieldInstances请求参数结构体 */ export interface DeleteShieldInstancesRequest { /** * 任务唯一标识ItemId的列表 */ ItemIds: Array<string>; } /** * 拉取某个用户的所有资源信息 */ export interface ResourceInfo { /** * 用户购买的资源id,全局唯一 */ ResourceId: string; /** * 资源的pid,MTP加固-12767,应用加固-12750 MTP反作弊-12766 源代码混淆-12736 */ Pid: number; /** * 购买时间戳 */ CreateTime: number; /** * 到期时间戳 */ ExpireTime: number; /** * 0-未绑定,1-已绑定 */ IsBind: number; /** * 用户绑定app的基本信息 */ BindInfo: BindInfo; /** * 资源名称,如应用加固,漏洞扫描 */ ResourceName: string; } /** * DescribeShieldInstances请求参数结构体 */ export interface DescribeShieldInstancesRequest { /** * 支持通过app名称,app包名,加固的服务版本,提交的渠道进行筛选。 */ Filters?: Array<Filter>; /** * 偏移量,默认为0。 */ Offset?: number; /** * 数量限制,默认为20,最大值为100。 */ Limit?: number; /** * 可以提供ItemId数组来查询一个或者多个结果。注意不可以同时指定ItemIds和Filters。 */ ItemIds?: Array<string>; /** * 按某个字段排序,目前仅支持TaskTime排序。 */ OrderField?: string; /** * 升序(asc)还是降序(desc),默认:desc。 */ OrderDirection?: string; } /** * CreateScanInstances返回参数结构体 */ export interface CreateScanInstancesResponse { /** * 任务唯一标识 */ ItemId?: string; /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 提交成功的app的md5集合 */ AppMd5s?: Array<string>; /** * 剩余可用次数 */ LimitCount?: number; /** * 到期时间 */ LimitTime?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeScanInstances返回参数结构体 */ export interface DescribeScanInstancesResponse { /** * 符合要求的app数量 */ TotalCount?: number; /** * 一个关于app详细信息的结构体,主要包括app的基本信息和扫描状态信息。 */ ScanSet?: Array<AppScanSet>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 漏洞信息 */ export interface VulInfo { /** * 漏洞列表 */ VulList: Array<VulList>; /** * 漏洞文件评分 */ VulFileScore: number; } /** * 提交的app基本信息 */ export interface AppInfo { /** * app的url,必须保证不用权限校验就可以下载 */ AppUrl: string; /** * app的md5,需要正确传递 */ AppMd5: string; /** * app的大小 */ AppSize?: number; /** * app的文件名 */ FileName?: string; /** * app的包名,需要正确的传递此字段 */ AppPkgName?: string; /** * app的版本号 */ AppVersion?: string; /** * app的图标url */ AppIconUrl?: string; /** * app的名称 */ AppName?: string; } /** * 提交app加固的服务信息 */ export interface ServiceInfo { /** * 服务版本,基础版basic,专业版professional,企业版enterprise。 */ ServiceEdition: string; /** * 任务处理完成后的反向通知回调地址,如果不需要通知请传递空字符串。通知为POST请求,post包体数据示例{"Response":{"ItemId":"4cdad8fb86f036b06bccb3f58971c306","ShieldCode":0,"ShieldMd5":"78701576793c4a5f04e1c9660de0aa0b","ShieldSize":11997354,"TaskStatus":1,"TaskTime":1539148141}},调用方需要返回如下信息,{"Result":"ok","Reason":"xxxxx"},如果Result字段值不等于ok会继续回调。 */ CallbackUrl: string; /** * 提交来源 YYB-应用宝 RDM-rdm MC-控制台 MAC_TOOL-mac工具 WIN_TOOL-window工具。 */ SubmitSource: string; /** * 加固策略编号,如果不传则使用系统默认加固策略。如果指定的plan不存在会返回错误。 */ PlanId?: number; } /** * so加固信息 */ export interface SoInfo { /** * so文件列表 */ SoFileNames: Array<string>; } /** * DescribeShieldPlanInstance返回参数结构体 */ export interface DescribeShieldPlanInstanceResponse { /** * 绑定资源信息 */ BindInfo?: BindInfo; /** * 加固策略信息 */ ShieldPlanInfo?: ShieldPlanInfo; /** * 加固资源信息 */ ResourceServiceInfo?: ResourceServiceInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 安全扫描敏感词 */ export interface ScanSensitiveInfo { /** * 敏感词 */ WordList: Array<string>; /** * 敏感词对应的文件信息 */ FilePath: string; /** * 文件sha1值 */ FileSha: string; } /** * 资源服务信息 */ export interface ResourceServiceInfo { /** * 创建时间戳 */ CreateTime: number; /** * 到期时间戳 */ ExpireTime: number; /** * 资源名称,如应用加固,源码混淆 */ ResourceName: string; } /** * DescribeResourceInstances请求参数结构体 */ export interface DescribeResourceInstancesRequest { /** * 资源类别id数组,13624:加固专业版,12750:企业版。空数组表示返回全部资源。 */ Pids: Array<number>; /** * 支持通过资源id,pid进行查询 */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 数量限制,默认为20,最大值为100。 */ Limit?: number; /** * 按某个字段排序,目前支持CreateTime、ExpireTime其中的一个排序。 */ OrderField?: string; /** * 升序(asc)还是降序(desc),默认:desc。 */ OrderDirection?: string; } /** * 广告信息 */ export interface AdInfo { /** * 插播广告列表 */ Spots: Array<PluginInfo>; /** * 精品推荐广告列表 */ BoutiqueRecommands: Array<PluginInfo>; /** * 悬浮窗广告列表 */ FloatWindowses: Array<PluginInfo>; /** * banner广告列表 */ Banners: Array<PluginInfo>; /** * 积分墙广告列表 */ IntegralWalls: Array<PluginInfo>; /** * 通知栏广告列表 */ NotifyBars: Array<PluginInfo>; } /** * DescribeShieldPlanInstance请求参数结构体 */ export interface DescribeShieldPlanInstanceRequest { /** * 资源id */ ResourceId: string; /** * 服务类别id */ Pid: number; } /** * 加固后app的信息 */ export interface ShieldInfo { /** * 加固结果的返回码 */ ShieldCode: number; /** * 加固后app的大小 */ ShieldSize?: number; /** * 加固后app的md5 */ ShieldMd5?: string; /** * 加固后的APP下载地址,该地址有效期为20分钟,请及时下载 */ AppUrl?: string; /** * 加固的提交时间 */ TaskTime: number; /** * 任务唯一标识 */ ItemId: string; /** * 加固版本,basic基础版,professional专业版,enterprise企业版 */ ServiceEdition: string; } /** * 安全扫描系统权限信息 */ export interface ScanPermissionList { /** * 系统权限信息 */ PermissionList: Array<ScanPermissionInfo>; } /** * CreateResourceInstances返回参数结构体 */ export interface CreateResourceInstancesResponse { /** * 新创建的资源列表。 */ ResourceSet?: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * app的详细基础信息 */ export interface AppDetailInfo { /** * app的名称 */ AppName: string; /** * app的包名 */ AppPkgName: string; /** * app的版本号 */ AppVersion: string; /** * app的大小 */ AppSize: number; /** * app的md5 */ AppMd5: string; /** * app的图标url */ AppIconUrl: string; /** * app的文件名称 */ FileName: string; } /** * DeleteScanInstances返回参数结构体 */ export interface DeleteScanInstancesResponse { /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 筛选数据结构 */ export interface Filter { /** * 需要过滤的字段 */ Name: string; /** * 需要过滤字段的值 */ Value?: string; } /** * DeleteShieldInstances返回参数结构体 */ export interface DeleteShieldInstancesResponse { /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeScanInstances请求参数结构体 */ export interface DescribeScanInstancesRequest { /** * 支持通过app名称,app包名进行筛选 */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 数量限制,默认为20,最大值为100。 */ Limit?: number; /** * 可以提供ItemId数组来查询一个或者多个结果。注意不可以同时指定ItemIds和Filters。 */ ItemIds?: Array<string>; /** * 按某个字段排序,目前仅支持TaskTime排序。 */ OrderField?: string; /** * 升序(asc)还是降序(desc),默认:desc。 */ OrderDirection?: string; } /** * DescribeUserBaseInfoInstance请求参数结构体 */ export declare type DescribeUserBaseInfoInstanceRequest = null; /** * DescribeResourceInstances返回参数结构体 */ export interface DescribeResourceInstancesResponse { /** * 符合要求的资源数量 */ TotalCount?: number; /** * 符合要求的资源数组 */ ResourceSet?: Array<ResourceInfo>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeScanResults请求参数结构体 */ export interface DescribeScanResultsRequest { /** * 任务唯一标识 */ ItemId: string; /** * 批量查询一个或者多个app的扫描结果,如果不传表示查询该任务下所提交的所有app */ AppMd5s?: Array<string>; } /** * CreateCosSecKeyInstance返回参数结构体 */ export interface CreateCosSecKeyInstanceResponse { /** * COS密钥对应的AppId */ CosAppid?: number; /** * COS密钥对应的存储桶名 */ CosBucket?: string; /** * 存储桶对应的地域 */ CosRegion?: string; /** * 密钥过期时间 */ ExpireTime?: number; /** * 密钥ID信息 */ CosId?: string; /** * 密钥KEY信息 */ CosKey?: string; /** * 密钥TOCKEN信息 */ CosTocken?: string; /** * 密钥可访问的文件前缀人。例如:CosPrefix=test/123/666,则该密钥只能操作test/123/666为前缀的文件,例如test/123/666/1.txt */ CosPrefix?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 病毒信息 */ export interface VirusInfo { /** * 软件安全类型,分别为0-未知、 1-安全软件、2-风险软件、3-病毒软件 */ SafeType: number; /** * 病毒名称, utf8编码,非病毒时值为空 */ VirusName: string; /** * 病毒描述,utf8编码,非病毒时值为空 */ VirusDesc: string; } /** * 安全扫描系统权限信息 */ export interface ScanPermissionInfo { /** * 系统权限 */ Permission: string; } /** * 加固策略信息 */ export interface PlanInfo { /** * apk大小优化,0关闭,1开启 */ ApkSizeOpt: number; /** * Dex加固,0关闭,1开启 */ Dex: number; /** * So加固,0关闭,1开启 */ So: number; /** * 数据收集,0关闭,1开启 */ Bugly: number; /** * 防止重打包,0关闭,1开启 */ AntiRepack: number; /** * Dex分离,0关闭,1开启 */ SeperateDex: number; /** * 内存保护,0关闭,1开启 */ Db: number; /** * Dex签名校验,0关闭,1开启 */ DexSig: number; /** * So文件信息 */ SoInfo: SoInfo; /** * vmp,0关闭,1开启 */ AntiVMP: number; /** * 保护so的强度, */ SoType: Array<string>; /** * 防日志泄漏,0关闭,1开启 */ AntiLogLeak: number; /** * root检测,0关闭,1开启 */ AntiQemuRoot: number; /** * 资源防篡改,0关闭,1开启 */ AntiAssets: number; /** * 防止截屏,0关闭,1开启 */ AntiScreenshot: number; /** * SSL证书防窃取,0关闭,1开启 */ AntiSSL: number; } /** * DescribeShieldResult返回参数结构体 */ export interface DescribeShieldResultResponse { /** * 任务状态: 0-请返回,1-已完成,2-处理中,3-处理出错,4-处理超时 */ TaskStatus?: number; /** * app加固前的详细信息 */ AppDetailInfo?: AppDetailInfo; /** * app加固后的详细信息 */ ShieldInfo?: ShieldInfo; /** * 状态描述 */ StatusDesc?: string; /** * 状态指引 */ StatusRef?: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateBindInstance返回参数结构体 */ export interface CreateBindInstanceResponse { /** * 任务状态: 1-已完成,2-处理中,3-处理出错,4-处理超时 */ Progress?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 漏洞信息 */ export interface VulList { /** * 漏洞id */ VulId: string; /** * 漏洞名称 */ VulName: string; /** * 漏洞代码 */ VulCode: string; /** * 漏洞描述 */ VulDesc: string; /** * 漏洞解决方案 */ VulSolution: string; /** * 漏洞来源类别,0默认自身,1第三方插件 */ VulSrcType: number; /** * 漏洞位置 */ VulFilepath: string; /** * 风险级别:1 低风险 ;2中等风险;3 高风险 */ RiskLevel: number; } /** * 用户绑定app的基本信息 */ export interface BindInfo { /** * app的icon的url */ AppIconUrl: string; /** * app的名称 */ AppName: string; /** * app的包名 */ AppPkgName: string; } /** * DeleteScanInstances请求参数结构体 */ export interface DeleteScanInstancesRequest { /** * 删除一个或多个扫描的app,最大支持20个 */ AppSids: Array<string>; }
the_stack
import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IgxGridModule } from './public_api'; import { IgxGridComponent } from './grid.component'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { UIInteractions, wait } from '../../test-utils/ui-interactions.spec'; import { setupGridScrollDetection } from '../../test-utils/helper-utils.spec'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { SelectionWithScrollsComponent, MRLTestComponent, ColumnGroupsNavigationTestComponent } from '../../test-utils/grid-samples.spec'; import { GridFunctions, GridSelectionFunctions } from '../../test-utils/grid-functions.spec'; import { GridSelectionMode, FilterMode } from '../common/enums'; import { IActiveNodeChangeEventArgs } from '../common/events'; import { IgxStringFilteringOperand } from '../../data-operations/filtering-condition'; import { IgxGridHeaderRowComponent } from '../headers/grid-header-row.component'; const DEBOUNCETIME = 30; describe('IgxGrid - Headers Keyboard navigation #grid', () => { describe('Headers Navigation', () => { let fix; let grid: IgxGridComponent; let gridHeader: IgxGridHeaderRowComponent; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ SelectionWithScrollsComponent ], imports: [NoopAnimationsModule, IgxGridModule], }); })); beforeEach(fakeAsync(/** height/width setter rAF */() => { fix = TestBed.createComponent(SelectionWithScrollsComponent); fix.detectChanges(); grid = fix.componentInstance.grid; setupGridScrollDetection(fix, grid); fix.detectChanges(); gridHeader = GridFunctions.getGridHeader(grid); })); it('when click on a header it should stay in the view', async () => { grid.headerContainer.getScroll().scrollLeft = 1000; await wait(100); fix.detectChanges(); let header = GridFunctions.getColumnHeader('OnPTO', fix); UIInteractions.simulateClickAndSelectEvent(header); await wait(200); fix.detectChanges(); header = GridFunctions.getColumnHeader('OnPTO', fix); expect(header).toBeDefined(); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should focus first header when the grid is scrolled', async () => { grid.navigateTo(7, 5); await wait(150); fix.detectChanges(); gridHeader.nativeElement.focus(); //('focus', {}); await wait(250); fix.detectChanges(); const header = GridFunctions.getColumnHeader('ID', fix); expect(header).not.toBeDefined(); expect(grid.navigation.activeNode.column).toEqual(3); expect(grid.navigation.activeNode.row).toEqual(-1); expect(grid.headerContainer.getScroll().scrollLeft).toBeGreaterThanOrEqual(200); expect(grid.verticalScrollContainer.getScroll().scrollTop).toBeGreaterThanOrEqual(100); }); it('should emit when activeNode ref is changed', () => { spyOn(grid.activeNodeChange, 'emit').and.callThrough(); const args: IActiveNodeChangeEventArgs = { row: -1, column: 0, level: 0, tag: 'headerCell' }; gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); expect(grid.activeNodeChange.emit).toHaveBeenCalledWith(args); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); args.column += 1; expect(grid.activeNodeChange.emit).toHaveBeenCalledWith(args); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); args.column -= 1; expect(grid.activeNodeChange.emit).toHaveBeenCalledWith(args); expect(grid.activeNodeChange.emit).toHaveBeenCalledTimes(3); }); it('should allow horizontal navigation', async () => { // Focus grid header gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); // Verify first header is focused let header = GridFunctions.getColumnHeader('ID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); for (let index = 0; index < 5; index++) { UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); } header = GridFunctions.getColumnHeader('OnPTO', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Press arrow right again UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); for (let index = 5; index > 1; index--) { UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); } header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate to first/last header', async () => { // Focus grid header let header = GridFunctions.getColumnHeader('ParentID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify header is focused GridFunctions.verifyHeaderIsFocused(header.parent); // Press end key UIInteractions.triggerEventHandlerKeyDown('End', gridHeader); await wait(100); fix.detectChanges(); header = GridFunctions.getColumnHeader('OnPTO', fix); expect(header).toBeTruthy(); expect(grid.navigation.activeNode.column).toEqual(5); expect(grid.navigation.activeNode.row).toEqual(-1); // Press Home ket UIInteractions.triggerEventHandlerKeyDown('home', gridHeader); await wait(100); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); expect(header).toBeTruthy(); expect(grid.navigation.activeNode.column).toEqual(0); expect(grid.navigation.activeNode.row).toEqual(-1); // Press Ctrl+ Arrow right UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, false, false, true); await wait(100); fix.detectChanges(); header = GridFunctions.getColumnHeader('OnPTO', fix); expect(header).toBeTruthy(); expect(grid.navigation.activeNode.column).toEqual(5); expect(grid.navigation.activeNode.row).toEqual(-1); // Press Ctrl+ Arrow left UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, false, false, true); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); expect(header).toBeTruthy(); expect(grid.navigation.activeNode.column).toEqual(0); expect(grid.navigation.activeNode.row).toEqual(-1); }); it('should not change active header on arrow up or down pressed', () => { // Focus grid header const header = GridFunctions.getColumnHeader('Name', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify header is focused GridFunctions.verifyHeaderIsFocused(header.parent); // Press arrow down key UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); // Press arrow up key UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); // Press pageUp key UIInteractions.triggerEventHandlerKeyDown('PageUp', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); // Press pageDown key UIInteractions.triggerEventHandlerKeyDown('PageUp', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('Verify navigation when there are pinned columns', async () => { grid.getColumnByName('ParentID').pinned = true; fix.detectChanges(); // Focus grid header gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); // Verify first header is focused let header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Navigate to last cell UIInteractions.triggerEventHandlerKeyDown('End', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('OnPTO', fix); expect(header).toBeTruthy(); expect(grid.navigation.activeNode.column).toEqual(5); expect(grid.navigation.activeNode.row).toEqual(-1); // Click on the pinned column header = GridFunctions.getColumnHeader('ParentID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Start navigating right for (let index = 0; index < 5; index++) { UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); } header = GridFunctions.getColumnHeader('OnPTO', fix); GridFunctions.verifyHeaderIsFocused(header.parent); const hScroll = grid.headerContainer.getScroll().scrollLeft; // Navigate with home key UIInteractions.triggerEventHandlerKeyDown('Home', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); expect(grid.headerContainer.getScroll().scrollLeft).toEqual(hScroll); }); it('Sorting: Should be able to sort a column with the keyboard', fakeAsync (() => { spyOn(grid.sorting, 'emit').and.callThrough(); spyOn(grid.sortingDone, 'emit').and.callThrough(); grid.getColumnByName('ID').sortable = true; fix.detectChanges(); // Focus grid header let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, true); expect(grid.sortingExpressions.length).toEqual(1); expect(grid.sortingExpressions[0].fieldName).toEqual('ID'); expect(grid.sortingExpressions[0].dir).toEqual(SortingDirection.Asc); expect(grid.sorting.emit).toHaveBeenCalledWith({ cancel: false, sortingExpressions: grid.sortingExpressions, owner: grid }); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, false, false); expect(grid.sortingExpressions.length).toEqual(0); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, true); expect(grid.sortingExpressions.length).toEqual(1); expect(grid.sortingExpressions[0].fieldName).toEqual('ID'); expect(grid.sortingExpressions[0].dir).toEqual(SortingDirection.Asc); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, false, true); expect(grid.sortingExpressions.length).toEqual(1); expect(grid.sortingExpressions[0].fieldName).toEqual('ID'); expect(grid.sortingExpressions[0].dir).toEqual(SortingDirection.Desc); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, false, false); expect(grid.sortingExpressions.length).toEqual(0); // select not sortable column UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, false, false, false); expect(grid.sortingExpressions.length).toEqual(0); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); tick(DEBOUNCETIME); fix.detectChanges(); GridFunctions.verifyHeaderSortIndicator(header, false, false, false); expect(grid.sortingExpressions.length).toEqual(0); expect(grid.sorting.emit).toHaveBeenCalledTimes(5); expect(grid.sortingDone.emit).toHaveBeenCalledTimes(5); })); it('Filtering: Should be able to open filter row with the keyboard', () => { // Focus grid header let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); // Test when grid does not have filtering UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); let filterRow = GridFunctions.getFilterRow(fix); expect(filterRow).toBeNull(); // Allow filtering grid.allowFiltering = true; grid.getColumnByName('ID').filterable = false; fix.detectChanges(); // Try to open filter row for not filterable column UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); filterRow = GridFunctions.getFilterRow(fix); expect(filterRow).toBeNull(); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Try to open filter row for not filterable column UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); filterRow = GridFunctions.getFilterRow(fix); expect(filterRow).not.toBeNull(); expect(grid.filteringRow.column.field).toEqual('ParentID'); }); it('Excel Style Filtering: Should be able to open ESF with the keyboard', () => { // Allow ESF grid.allowFiltering = true; grid.filterMode = FilterMode.excelStyleFilter; grid.getColumnByName('ID').filterable = false; fix.detectChanges(); let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Try to open filter for not filterable column UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); let filterDialog = GridFunctions.getExcelStyleFilteringComponent(fix); expect(filterDialog).toBeNull(); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Open filter UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); filterDialog = GridFunctions.getExcelStyleFilteringComponent(fix); expect(filterDialog).toBeDefined(); }); it('Advanced Filtering: Should be able to open Advanced filter', () => { const header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); // Test when advanced filtering is disabled UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, true); fix.detectChanges(); // Verify AF dialog is not opened. expect(GridFunctions.getAdvancedFilteringComponent(fix)).toBeNull(); // Enable Advanced Filtering grid.allowAdvancedFiltering = true; fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, true); fix.detectChanges(); // Verify AF dialog is opened. expect(GridFunctions.getAdvancedFilteringComponent(fix)).not.toBeNull(); }); it('Advanced Filtering: Should be able to close Advanced filtering with "escape"', fakeAsync(() => { // Enable Advanced Filtering grid.allowAdvancedFiltering = true; fix.detectChanges(); let header = GridFunctions.getColumnHeader('Name', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, true); fix.detectChanges(); // Verify AF dialog is opened. expect(GridFunctions.getAdvancedFilteringComponent(fix)).not.toBeNull(); const afDialog = fix.nativeElement.querySelector('.igx-advanced-filter'); UIInteractions.triggerKeyDownEvtUponElem('Escape', afDialog); tick(100); fix.detectChanges(); // Verify AF dialog is closed. header = GridFunctions.getColumnHeader('Name', fix); expect(GridFunctions.getAdvancedFilteringComponent(fix)).toBeNull(); GridFunctions.verifyHeaderIsFocused(header.parent); })); it('Column selection: Should be able to select columns when columnSelection is multi', () => { const columnID = grid.getColumnByName('ID'); const columnParentID = grid.getColumnByName('ParentID'); const columnName = grid.getColumnByName('Name'); columnName.selectable = false; expect(grid.columnSelection).toEqual(GridSelectionMode.none); let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); // Press space when the columnSelection is none UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID, false); grid.columnSelection = GridSelectionMode.multiple; fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID); GridSelectionFunctions.verifyColumnAndCellsSelected(columnParentID); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID); GridSelectionFunctions.verifyColumnAndCellsSelected(columnParentID, false); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Name', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Press Space on not selectable column UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID); GridSelectionFunctions.verifyColumnAndCellsSelected(columnName, false); }); it('Column selection: Should be able to select columns when columnSelection is single', () => { spyOn(grid.columnSelected, 'emit').and.callThrough(); const columnID = grid.getColumnByName('ID'); const columnParentID = grid.getColumnByName('ParentID'); const columnName = grid.getColumnByName('Name'); columnName.selectable = false; grid.columnSelection = GridSelectionMode.single; let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnID, false); GridSelectionFunctions.verifyColumnAndCellsSelected(columnParentID); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnParentID, false); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Name', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Press Space on not selectable column UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); GridSelectionFunctions.verifyColumnAndCellsSelected(columnName, false); expect(grid.columnSelected.emit).toHaveBeenCalledTimes(3); }); it('Group by: Should be able group columns with keyboard', () => { spyOn(grid.onGroupingDone, 'emit').and.callThrough(); grid.getColumnByName('ID').groupable = true; grid.getColumnByName('Name').groupable = true; let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(1); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); // Try to group not groupable column header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(1); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Name', fix); GridFunctions.verifyHeaderIsFocused(header.parent); // Press Space on not selectable column UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(2); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); expect(grid.groupingExpressions[1].fieldName).toEqual('Name'); // Ungroup column UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(1); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); // Ungroup not grouped column UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(1); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); expect(grid.onGroupingDone.emit).toHaveBeenCalled(); }); it('Group by: Should be able group columns with keyboard when hideGroupedColumns is true', fakeAsync(() => { grid.width = '1000px'; grid.hideGroupedColumns = true; grid.columns.forEach(c => c.groupable = true); fix.detectChanges(); tick(100); let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Group by first column UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); tick(100); fix.detectChanges(); header = GridFunctions.getColumnHeader('ParentID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); expect(grid.groupingExpressions.length).toEqual(1); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); GridFunctions.verifyColumnIsHidden(grid.getColumnByName('ID'), true, 5); // Go to last column UIInteractions.triggerEventHandlerKeyDown('End', gridHeader); fix.detectChanges(); // Try to group not groupable column header = GridFunctions.getColumnHeader('OnPTO', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); tick(100); fix.detectChanges(); header = GridFunctions.getColumnHeader('Age', fix); GridFunctions.verifyHeaderIsFocused(header.parent); expect(grid.groupingExpressions.length).toEqual(2); expect(grid.groupingExpressions[0].fieldName).toEqual('ID'); expect(grid.groupingExpressions[1].fieldName).toEqual('OnPTO'); GridFunctions.verifyColumnIsHidden(grid.getColumnByName('OnPTO'), true, 4); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('HireDate', fix); GridFunctions.verifyHeaderIsFocused(header.parent); })); }); describe('MRL Headers Navigation', () => { let fix; let grid: IgxGridComponent; let gridHeader: IgxGridHeaderRowComponent; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ MRLTestComponent ], imports: [NoopAnimationsModule, IgxGridModule], }); })); beforeEach(fakeAsync(/** height/width setter rAF */() => { fix = TestBed.createComponent(MRLTestComponent); fix.detectChanges(); grid = fix.componentInstance.grid; setupGridScrollDetection(fix, grid); fix.detectChanges(); gridHeader = GridFunctions.getGridHeader(grid); })); it('should navigate through a layout with right and left arrow keys in first level', async () => { let header = GridFunctions.getColumnHeader('CompanyName', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('City', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Country', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Phone', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Country', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('City', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate through a layout with right and left arrow keys in second level', async () => { let header = GridFunctions.getColumnHeader('ContactTitle', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('City', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Fax', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('City', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactTitle', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate through a layout with home and end keys', async () => { let header = GridFunctions.getColumnHeader('ContactTitle', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, false, false, true); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Fax', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, false, false, true); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); header = GridFunctions.getColumnHeader('Address', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('End', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Fax', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('home', gridHeader); await wait(DEBOUNCETIME); fix.detectChanges(); header = GridFunctions.getColumnHeader('Address', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate through a layout with up and down arrow keys', () => { let header = GridFunctions.getColumnHeader('ContactTitle', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactTitle', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Address', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactTitle', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should focus the first element when focus the header', () => { gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); const header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); }); describe('MCH Headers Navigation', () => { let fix; let grid: IgxGridComponent; let gridHeader: IgxGridHeaderRowComponent; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ ColumnGroupsNavigationTestComponent ], imports: [NoopAnimationsModule, IgxGridModule], }); })); beforeEach(fakeAsync(/** height/width setter rAF */() => { fix = TestBed.createComponent(ColumnGroupsNavigationTestComponent); fix.detectChanges(); grid = fix.componentInstance.grid; setupGridScrollDetection(fix, grid); fix.detectChanges(); gridHeader = GridFunctions.getGridHeader(grid); })); it('should navigate through groups with right and left arrow keys in first level', () => { let header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Address Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); }); it('should navigate through groups with right and left arrow keys in child level', () => { let header = GridFunctions.getColumnHeader('ContactTitle', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Region', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Country', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('City Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Country', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Region', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ID', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('ContactTitle', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate through groups with Home and End keys', () => { let header = GridFunctions.getColumnHeader('ID', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, false, false, true); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Address Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, false, false, true); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); header = GridFunctions.getColumnHeader('City', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('Home', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('End', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Address', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should navigate through groups with arrowUp and down keys', () => { let header = GridFunctions.getColumnHeader('City', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); // Verify first header is focused GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('City Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Country Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Address Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Country Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('City Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('City', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header.parent); // click on parent header = GridFunctions.getColumnGroupHeaderCell('Address Information', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader); fix.detectChanges(); header = GridFunctions.getColumnHeader('Region', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); it('should focus the first element when focus the header', () => { gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); let header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); // Verify children are not focused header = GridFunctions.getColumnGroupHeaderCell('Person Details', fix); GridFunctions.verifyHeaderIsFocused(header, false); header = GridFunctions.getColumnGroupHeaderCell('Person Details', fix); GridFunctions.verifyHeaderIsFocused(header, false); header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent, false); }); it('should be able to expand collapse column group with the keyboard', () => { const getInfGroup = GridFunctions.getColGroup(grid, 'General Information'); const personDetailsGroup = GridFunctions.getColGroup(grid, 'Person Details'); const companyName = grid.getColumnByName('CompanyName'); getInfGroup.collapsible = true; personDetailsGroup.visibleWhenCollapsed = true; companyName.visibleWhenCollapsed = false; fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, false, 10); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup); gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); const header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, true); fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, true, 12); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup, true, false); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true); fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, false, 10); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup); // set group not to be collapsible getInfGroup.collapsible = false; fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, false, 13); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup, false); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, true); fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, false, 13); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup, false); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, true); fix.detectChanges(); GridFunctions.verifyColumnIsHidden(companyName, false, 13); GridFunctions.verifyGroupIsExpanded(fix, getInfGroup, false); }); it('Column selection: should be possible to select column group with the keyboard', () => { grid.columnSelection = GridSelectionMode.multiple; fix.detectChanges(); gridHeader.nativeElement.focus(); //('focus', null); fix.detectChanges(); const header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); fix.detectChanges(); expect(grid.getColumnByName('CompanyName').selected).toBeTruthy(); expect(grid.getColumnByName('ContactName').selected).toBeTruthy(); expect(grid.getColumnByName('ContactTitle').selected).toBeTruthy(); UIInteractions.triggerEventHandlerKeyDown('Space', gridHeader); fix.detectChanges(); expect(grid.selectedColumns().length).toEqual(0); }); it('Features Integration: should nor be possible to sort, filter or groupBy column group', () => { grid.allowAdvancedFiltering = true; grid.columns.forEach(c => { c.sortable = true; c.groupable = true; }); fix.detectChanges(); const header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header); // Press Ctrl+ Arrow Up and down on group to sort it UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridHeader, false, false, true); fix.detectChanges(); expect(grid.sortingExpressions.length).toEqual(0); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, false, false, true); fix.detectChanges(); expect(grid.sortingExpressions.length).toEqual(0); // Press Shift + Alt + Arrow left on group to groupBy it UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, true, true); fix.detectChanges(); expect(grid.groupingExpressions.length).toEqual(0); // Press Ctrl + Shift + L on group to open filter row UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); expect(GridFunctions.getFilterRow(fix)).toBeNull(); // Change filter mode to be excel style filter grid.filterMode = FilterMode.excelStyleFilter; fix.detectChanges(); // Press Ctrl + Shift + L on group to open excel style filter UIInteractions.triggerEventHandlerKeyDown('L', gridHeader, false, true, true); fix.detectChanges(); expect(GridFunctions.getExcelStyleFilteringComponent(fix)).toBeNull(); }); it('MCH Grid with no data: should be able to navigate with arrow keys in the headers', () => { grid.filter('Country', 'Bulgaria', IgxStringFilteringOperand.instance().condition('contains'), true); fix.detectChanges(); expect(grid.rowList.length).toBe(0); let header = GridFunctions.getColumnGroupHeaderCell('General Information', fix); UIInteractions.simulateClickAndSelectEvent(header); fix.detectChanges(); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, false, false, true); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Address Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridHeader, false, false, false); fix.detectChanges(); header = GridFunctions.getColumnHeader('Region', fix); GridFunctions.verifyHeaderIsFocused(header.parent); UIInteractions.triggerEventHandlerKeyDown('ArrowRight', gridHeader, false, false, false); fix.detectChanges(); header = GridFunctions.getColumnGroupHeaderCell('Country Information', fix); GridFunctions.verifyHeaderIsFocused(header); UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', gridHeader, false, false, true); fix.detectChanges(); header = GridFunctions.getColumnHeader('CompanyName', fix); GridFunctions.verifyHeaderIsFocused(header.parent); }); }); });
the_stack
import { App, AppMode } from '../lib/app'; import { OAuth } from './oauth'; import { Application as ExpressApplication } from 'express'; import { FilesController } from './controllers/files.ctrl'; import { DatabaseController } from './controllers/database.ctrl'; import { AppController } from './controllers/app.ctrl'; import { GitController } from './controllers/git.ctrl'; import { ClientController } from './controllers/client.ctrl'; import { EndpointsController } from './controllers/endpoints.ctrl'; import { PackageManagerController } from './controllers/package-manager.ctrl'; import { AddonsController } from './controllers/addons.ctrl'; import { PermissionsController } from './controllers/permissions.ctrl'; import { BoilerplateController } from './controllers/boilerplate.ctrl'; import { WebsocketServers, WebsocketInstance } from '../lib/websocket'; export class MateriaApi { oauth: OAuth; websocket: WebsocketInstance | { instance: any; broadcast: (data) => any; }; databaseCtrl: DatabaseController; filesCtrl: FilesController; appCtrl: AppController; gitCtrl: GitController; endpointsCtrl: EndpointsController; packageManagerCtrl: PackageManagerController; addonsCtrl: AddonsController; permissionsCtrl: PermissionsController; boilerplateCtrl: BoilerplateController; clientCtrl: ClientController; get api(): ExpressApplication { return this.app.server.expressApp; } get websocketServers(): WebsocketServers { return this.app.server.websocket; } constructor(private app: App) { this.oauth = new OAuth(this.app); } initialize() { if (this.app.mode === AppMode.PRODUCTION && ! this.app.rootPassword ) { this.websocket = { broadcast: (data) => {}, instance: {} }; return false; } this.websocket = this.websocketServers.register('/materia/websocket', (info, cb) => { if ( ! this.app.rootPassword) { return cb(true); } return this.oauth.verifyToken(info.req.url.split('?token=')[1], (err, authorized) => { return cb(authorized); }); }); this.databaseCtrl = new DatabaseController(this.app, this.websocket); this.filesCtrl = new FilesController(this.app, this.websocket); this.appCtrl = new AppController(this.app, this.websocket); this.gitCtrl = new GitController(this.app, this.websocket); this.endpointsCtrl = new EndpointsController(this.app, this.websocket); this.packageManagerCtrl = new PackageManagerController(this.app, this.websocket); this.addonsCtrl = new AddonsController(this.app, this.websocket); this.permissionsCtrl = new PermissionsController(this.app, this.websocket); this.boilerplateCtrl = new BoilerplateController(this.app, this.websocket); this.clientCtrl = new ClientController(this.app, this.websocket); this.oauth.initialize(); /** * App Endpoints */ this.api.post('/materia/token', this.oauth.token); this.api.post('/materia/docker', this.oauth.isAuth, this.appCtrl.createDockerfile.bind(this.appCtrl)); this.api.post('/materia/restart', this.oauth.isAuth, this.appCtrl.restart.bind(this.appCtrl)); this.api.get('/materia/infos/minimal', this.oauth.isAuth, this.appCtrl.getInfos.bind(this.appCtrl)); this.api.get('/materia/infos', this.oauth.isAuth, this.appCtrl.getInfos.bind(this.appCtrl)); this.api.post('/materia/config', this.oauth.isAuth, this.appCtrl.config.bind(this.appCtrl)); this.api.delete('/materia/config', this.oauth.isAuth, this.appCtrl.deleteConfig.bind(this.appCtrl)); this.api.post('/materia/search', this.oauth.isAuth, this.appCtrl.search.bind(this.appCtrl)); /** * PackageManager Endpoints */ this.api.post('/materia/dependencies', this.oauth.isAuth, this.packageManagerCtrl.installAll.bind(this.packageManagerCtrl)); this.api.post('/materia/dependencies/:dependency*', this.oauth.isAuth, this.packageManagerCtrl.install.bind(this.packageManagerCtrl)); this.api.put('/materia/dependencies/:dependency*', this.oauth.isAuth, this.packageManagerCtrl.upgrade.bind(this.packageManagerCtrl)); this.api.delete('/materia/dependencies/:dependency*', this.oauth.isAuth, this.packageManagerCtrl.uninstall.bind(this.packageManagerCtrl)); /** * Files Endpoints */ this.api.get('/materia/is_directory/:path(.*)', this.oauth.isAuth, this.filesCtrl.isDirectory.bind(this.filesCtrl)); this.api.get('/materia/files', this.oauth.isAuth, this.filesCtrl.read.bind(this.filesCtrl)); // this.api.get('/materia/files/:path(.*)', this.oauth.isAuth, this.filesCtrl.read.bind(this.filesCtrl)); this.api.post('/materia/files', this.oauth.isAuth, this.filesCtrl.write.bind(this.filesCtrl)); this.api.put('/materia/files', this.oauth.isAuth, this.filesCtrl.move.bind(this.filesCtrl)); this.api.delete('/materia/files', this.oauth.isAuth, this.filesCtrl.remove.bind(this.filesCtrl)); /** * GIT Endpoints */ this.api.get('/materia/git', this.oauth.isAuth, this.gitCtrl.load.bind(this.gitCtrl)); this.api.post('/materia/git/clone', this.oauth.isAuth, this.gitCtrl.clone.bind(this.gitCtrl)); this.api.post('/materia/git/init', this.oauth.isAuth, this.gitCtrl.init.bind(this.gitCtrl)); this.api.post('/materia/git/fetch', this.oauth.isAuth, this.gitCtrl.fetch.bind(this.gitCtrl)); this.api.get('/materia/git/statuses', this.oauth.isAuth, this.gitCtrl.getStatus.bind(this.gitCtrl)); this.api.post('/materia/git/stage', this.oauth.isAuth, this.gitCtrl.stage.bind(this.gitCtrl)); this.api.delete('/materia/git/unstage', this.oauth.isAuth, this.gitCtrl.unstage.bind(this.gitCtrl)); this.api.post('/materia/git/stage_all', this.oauth.isAuth, this.gitCtrl.stage.bind(this.gitCtrl)); this.api.delete('/materia/git/unstage_all', this.oauth.isAuth, this.gitCtrl.unstage.bind(this.gitCtrl)); this.api.post('/materia/git/commit', this.oauth.isAuth, this.gitCtrl.commit.bind(this.gitCtrl)); this.api.post('/materia/git/pull', this.oauth.isAuth, this.gitCtrl.pull.bind(this.gitCtrl)); this.api.post('/materia/git/push', this.oauth.isAuth, this.gitCtrl.push.bind(this.gitCtrl)); this.api.post('/materia/git/publish', this.oauth.isAuth, this.gitCtrl.publish.bind(this.gitCtrl)); this.api.get('/materia/git/history', this.oauth.isAuth, this.gitCtrl.getHistory.bind(this.gitCtrl)); this.api.get('/materia/git/history/:hash', this.oauth.isAuth, this.gitCtrl.getCommit.bind(this.gitCtrl)); this.api.get('/materia/git/history/:hash/file', this.oauth.isAuth, this.gitCtrl.getHistoryFileDetail.bind(this.gitCtrl)); this.api.post('/materia/git/remotes', this.oauth.isAuth, this.gitCtrl.setupRemote.bind(this.gitCtrl)); this.api.put('/materia/git/branches', this.oauth.isAuth, this.gitCtrl.selectBranch.bind(this.gitCtrl)); this.api.post('/materia/git/branches', this.oauth.isAuth, this.gitCtrl.newBranch.bind(this.gitCtrl)); this.api.post('/materia/git/stash', this.oauth.isAuth, this.gitCtrl.stash.bind(this.gitCtrl)); this.api.post('/materia/git/stash/pop', this.oauth.isAuth, this.gitCtrl.stashPop.bind(this.gitCtrl)); // this.api.post('/materia/git/history/:sha/:path', this.oauth.isAuth, this.gitCtrl.getCommitDiff.bind(this.gitCtrl)); // this.api.post('/materia/git/checkout/:branch', this.oauth.isAuth, this.gitCtrl.checkout.bind(this.gitCtrl)); // this.api.post('/materia/git/merge/:branch', this.oauth.isAuth, this.gitCtrl.merge.bind(this.gitCtrl)); /** * Database & Entities Endpoints */ this.api.get('/materia/database/synchronize', this.oauth.isAuth, this.databaseCtrl.getDiffs.bind(this.databaseCtrl)); this.api.post('/materia/database/synchronize', this.oauth.isAuth, this.databaseCtrl.sync.bind(this.databaseCtrl)); this.api.post('/materia/database/try', this.oauth.isAuth, this.databaseCtrl.tryAuth.bind(this.databaseCtrl)); this.api.get('/materia/entities', this.oauth.isAuth, this.databaseCtrl.getEntities.bind(this.databaseCtrl)); this.api.post('/materia/entities', this.oauth.isAuth, this.databaseCtrl.createEntity.bind(this.databaseCtrl)); this.api.delete('/materia/entities/:entity', this.oauth.isAuth, this.databaseCtrl.removeEntity.bind(this.databaseCtrl)); this.api.put('/materia/entities/:entity', this.oauth.isAuth, this.databaseCtrl.renameEntity.bind(this.databaseCtrl)); this.api.put('/materia/entities/:entity/position', this.oauth.isAuth, this.databaseCtrl.moveEntity.bind(this.databaseCtrl)); // Fields this.api.post('/materia/entities/:entity/fields', this.oauth.isAuth, this.databaseCtrl.saveField.bind(this.databaseCtrl)); this.api.delete('/materia/entities/:entity/fields/:field', this.oauth.isAuth, this.databaseCtrl.removeField.bind(this.databaseCtrl)); // Queries this.api.get('/materia/models/:model', this.oauth.isAuth, this.databaseCtrl.loadModel.bind(this.databaseCtrl)); this.api.post('/materia/entities/:entity/queries', this.oauth.isAuth, this.databaseCtrl.createQuery.bind(this.databaseCtrl)); this.api.delete('/materia/entities/:entity/queries/:queryId', this.oauth.isAuth, this.databaseCtrl.removeQuery.bind(this.databaseCtrl)); this.api.post('/materia/entities/:entity/queries/:queryId', this.oauth.isAuth, this.databaseCtrl.runQuery.bind(this.databaseCtrl)); this.api.post('/materia/sql', this.oauth.isAuth, this.databaseCtrl.runSql.bind(this.databaseCtrl)); // Relations this.api.get('/materia/entities/relations', this.oauth.isAuth, this.databaseCtrl.getRelations.bind(this.databaseCtrl)); this.api.post('/materia/entities/relations', this.oauth.isAuth, this.databaseCtrl.createRelation.bind(this.databaseCtrl)); this.api.delete( '/materia/entities/:entity/relations/:type/:relationFieldOrEntity', this.oauth.isAuth, this.databaseCtrl.removeRelation.bind(this.databaseCtrl) ); // Actions this.api.get('/materia/actions', this.oauth.isAuth, this.databaseCtrl.listActions.bind(this.databaseCtrl)); this.api.post('/materia/actions', this.oauth.isAuth, this.databaseCtrl.addAction.bind(this.databaseCtrl)); this.api.put('/materia/actions/:id*', this.oauth.isAuth, this.databaseCtrl.updateAction.bind(this.databaseCtrl)); this.api.delete('/materia/actions/:id*', this.oauth.isAuth, this.databaseCtrl.removeAction.bind(this.databaseCtrl)); /** * API Endpoints */ this.api.get('/materia/endpoints', this.oauth.isAuth, this.endpointsCtrl.getEndpoints.bind(this.endpointsCtrl)); this.api.post('/materia/endpoints/generate', this.oauth.isAuth, this.endpointsCtrl.generate.bind(this.endpointsCtrl)); this.api.post('/materia/endpoints', this.oauth.isAuth, this.endpointsCtrl.add.bind(this.endpointsCtrl)); this.api.put('/materia/endpoints', this.oauth.isAuth, this.endpointsCtrl.update.bind(this.endpointsCtrl)); // Delete with id: btoa(endpoint.method + endpoint.url) this.api.delete('/materia/endpoints/:id', this.oauth.isAuth, this.endpointsCtrl.remove.bind(this.endpointsCtrl)); /** * Endpoints Controllers */ this.api.get('/materia/controllers', this.oauth.isAuth, this.endpointsCtrl.getControllers.bind(this.endpointsCtrl)); this.api.get('/materia/controllers/:name*', this.oauth.isAuth, this.endpointsCtrl.loadController.bind(this.endpointsCtrl)); /** * Endpoints Permissions */ this.api.get('/materia/permissions', this.oauth.isAuth, this.permissionsCtrl.list.bind(this.permissionsCtrl)); this.api.get('/materia/permissions/:permission', this.oauth.isAuth, this.permissionsCtrl.get.bind(this.permissionsCtrl)); this.api.post('/materia/permissions', this.oauth.isAuth, this.permissionsCtrl.add.bind(this.permissionsCtrl)); this.api.put('/materia/permissions/:permission', this.oauth.isAuth, this.permissionsCtrl.update.bind(this.permissionsCtrl)); this.api.delete('/materia/permissions/:permission', this.oauth.isAuth, this.permissionsCtrl.remove.bind(this.permissionsCtrl)); /** * Addon Endpoints */ this.api.get('/materia/addons/:pkg*/bundle.js', this.addonsCtrl.bundle.bind(this.addonsCtrl)); this.api.get('/materia/addons/:pkg*/setup', this.oauth.isAuth, this.addonsCtrl.getConfig.bind(this.addonsCtrl)); this.api.post('/materia/addons/:pkg*/setup', this.oauth.isAuth, this.addonsCtrl.setup.bind(this.addonsCtrl)); this.api.post('/materia/addons/:pkg*/enable', this.oauth.isAuth, this.addonsCtrl.enable.bind(this.addonsCtrl)); this.api.post('/materia/addons/:pkg*/disable', this.oauth.isAuth, this.addonsCtrl.disable.bind(this.addonsCtrl)); /** * Client Endpoints */ this.api.post('/materia/client/build', this.oauth.isAuth, this.clientCtrl.build.bind(this.clientCtrl)); this.api.post('/materia/client/dependencies', this.oauth.isAuth, this.clientCtrl.installAll.bind(this.clientCtrl)); this.api.post('/materia/client/dependencies/:dependency*', this.oauth.isAuth, this.clientCtrl.installAll.bind(this.clientCtrl)); this.api.post('/materia/client/watch/start', this.oauth.isAuth, this.clientCtrl.startWatching.bind(this.clientCtrl)); this.api.post('/materia/client/watch/stop', this.oauth.isAuth, this.clientCtrl.stopWatching.bind(this.clientCtrl)); this.api.post('/materia/client/boilerplate/init', this.oauth.isAuth, this.boilerplateCtrl.initMinimal.bind(this.boilerplateCtrl)); this.api.post( '/materia/client/boilerplate/init/:framework', this.oauth.isAuth, this.boilerplateCtrl.initBoilerplate.bind(this.boilerplateCtrl) ); this.api.all('/materia/*', this.oauth.isAuth, (req, res) => res.status(404).send()); } }
the_stack
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. import { encode } from "../encoding/utf8.ts"; import { BufReader, BufWriter } from "../io/bufio.ts"; import { assert } from "../_util/assert.ts"; import { Deferred, deferred, MuxAsyncIterator } from "../async/mod.ts"; import { bodyReader, chunkedBodyReader, emptyReader, readRequest, writeResponse, } from "./_io.ts"; export class ServerRequest { url!: string; method!: string; proto!: string; protoMinor!: number; protoMajor!: number; headers!: Headers; conn!: Deno.Conn; r!: BufReader; w!: BufWriter; done: Deferred<Error | undefined> = deferred(); private _contentLength: number | undefined | null = undefined; /** * Value of Content-Length header. * If null, then content length is invalid or not given (e.g. chunked encoding). */ get contentLength(): number | null { // undefined means not cached. // null means invalid or not provided. if (this._contentLength === undefined) { const cl = this.headers.get("content-length"); if (cl) { this._contentLength = parseInt(cl); // Convert NaN to null (as NaN harder to test) if (Number.isNaN(this._contentLength)) { this._contentLength = null; } } else { this._contentLength = null; } } return this._contentLength; } private _body: Deno.Reader | null = null; /** * Body of the request. The easiest way to consume the body is: * * const buf: Uint8Array = await Deno.readAll(req.body); */ get body(): Deno.Reader { if (!this._body) { if (this.contentLength != null) { this._body = bodyReader(this.contentLength, this.r); } else { const transferEncoding = this.headers.get("transfer-encoding"); if (transferEncoding != null) { const parts = transferEncoding .split(",") .map((e): string => e.trim().toLowerCase()); assert( parts.includes("chunked"), 'transfer-encoding must include "chunked" if content-length is not set', ); this._body = chunkedBodyReader(this.headers, this.r); } else { // Neither content-length nor transfer-encoding: chunked this._body = emptyReader(); } } } return this._body; } async respond(r: Response): Promise<void> { let err: Error | undefined; try { // Write our response! await writeResponse(this.w, r); } catch (e) { try { // Eagerly close on error. this.conn.close(); } catch { // Pass } err = e; } // Signal that this request has been processed and the next pipelined // request on the same connection can be accepted. this.done.resolve(err); if (err) { // Error during responding, rethrow. throw err; } } private finalized = false; async finalize(): Promise<void> { if (this.finalized) return; // Consume unread body const body = this.body; const buf = new Uint8Array(1024); while ((await body.read(buf)) !== null) { // Pass } this.finalized = true; } } export class Server implements AsyncIterable<ServerRequest> { private closing = false; private connections: Deno.Conn[] = []; constructor(public listener: Deno.Listener) {} close(): void { this.closing = true; this.listener.close(); for (const conn of this.connections) { try { conn.close(); } catch (e) { // Connection might have been already closed if (!(e instanceof Deno.errors.BadResource)) { throw e; } } } } // Yields all HTTP requests on a single TCP connection. private async *iterateHttpRequests( conn: Deno.Conn, ): AsyncIterableIterator<ServerRequest> { const reader = new BufReader(conn); const writer = new BufWriter(conn); while (!this.closing) { let request: ServerRequest | null; try { request = await readRequest(conn, reader); } catch (error) { if ( error instanceof Deno.errors.InvalidData || error instanceof Deno.errors.UnexpectedEof ) { // An error was thrown while parsing request headers. await writeResponse(writer, { status: 400, body: encode(`${error.message}\r\n\r\n`), }); } break; } if (request === null) { break; } request.w = writer; yield request; // Wait for the request to be processed before we accept a new request on // this connection. const responseError = await request.done; if (responseError) { // Something bad happened during response. // (likely other side closed during pipelined req) // req.done implies this connection already closed, so we can just return. this.untrackConnection(request.conn); return; } // Consume unread body and trailers if receiver didn't consume those data await request.finalize(); } this.untrackConnection(conn); try { conn.close(); } catch (e) { // might have been already closed } } private trackConnection(conn: Deno.Conn): void { this.connections.push(conn); } private untrackConnection(conn: Deno.Conn): void { const index = this.connections.indexOf(conn); if (index !== -1) { this.connections.splice(index, 1); } } // Accepts a new TCP connection and yields all HTTP requests that arrive on // it. When a connection is accepted, it also creates a new iterator of the // same kind and adds it to the request multiplexer so that another TCP // connection can be accepted. private async *acceptConnAndIterateHttpRequests( mux: MuxAsyncIterator<ServerRequest>, ): AsyncIterableIterator<ServerRequest> { if (this.closing) return; // Wait for a new connection. let conn: Deno.Conn; try { conn = await this.listener.accept(); } catch (error) { if ( error instanceof Deno.errors.BadResource || error instanceof Deno.errors.InvalidData || error instanceof Deno.errors.UnexpectedEof ) { return mux.add(this.acceptConnAndIterateHttpRequests(mux)); } throw error; } this.trackConnection(conn); // Try to accept another connection and add it to the multiplexer. mux.add(this.acceptConnAndIterateHttpRequests(mux)); // Yield the requests that arrive on the just-accepted connection. yield* this.iterateHttpRequests(conn); } [Symbol.asyncIterator](): AsyncIterableIterator<ServerRequest> { const mux: MuxAsyncIterator<ServerRequest> = new MuxAsyncIterator(); mux.add(this.acceptConnAndIterateHttpRequests(mux)); return mux.iterate(); } } /** Options for creating an HTTP server. */ export type HTTPOptions = Omit<Deno.ListenOptions, "transport">; /** * Parse addr from string * * const addr = "::1:8000"; * parseAddrFromString(addr); * * @param addr Address string */ export function _parseAddrFromStr(addr: string): HTTPOptions { let url: URL; try { const host = addr.startsWith(":") ? `0.0.0.0${addr}` : addr; url = new URL(`http://${host}`); } catch { throw new TypeError("Invalid address."); } if ( url.username || url.password || url.pathname != "/" || url.search || url.hash ) { throw new TypeError("Invalid address."); } return { hostname: url.hostname, port: url.port === "" ? 80 : Number(url.port), }; } /** * Create a HTTP server * * import { serve } from "https://deno.land/std/http/server.ts"; * const body = "Hello World\n"; * const server = serve({ port: 8000 }); * for await (const req of server) { * req.respond({ body }); * } */ export function serve(addr: string | HTTPOptions): Server { if (typeof addr === "string") { addr = _parseAddrFromStr(addr); } const listener = Deno.listen(addr); return new Server(listener); } /** * Start an HTTP server with given options and request handler * * const body = "Hello World\n"; * const options = { port: 8000 }; * listenAndServe(options, (req) => { * req.respond({ body }); * }); * * @param options Server configuration * @param handler Request handler */ export async function listenAndServe( addr: string | HTTPOptions, handler: (req: ServerRequest) => void, ): Promise<void> { const server = serve(addr); for await (const request of server) { handler(request); } } /** Options for creating an HTTPS server. */ export type HTTPSOptions = Omit<Deno.ListenTlsOptions, "transport">; /** * Create an HTTPS server with given options * * const body = "Hello HTTPS"; * const options = { * hostname: "localhost", * port: 443, * certFile: "./path/to/localhost.crt", * keyFile: "./path/to/localhost.key", * }; * for await (const req of serveTLS(options)) { * req.respond({ body }); * } * * @param options Server configuration * @return Async iterable server instance for incoming requests */ export function serveTLS(options: HTTPSOptions): Server { const tlsOptions: Deno.ListenTlsOptions = { ...options, transport: "tcp", }; const listener = Deno.listenTls(tlsOptions); return new Server(listener); } /** * Start an HTTPS server with given options and request handler * * const body = "Hello HTTPS"; * const options = { * hostname: "localhost", * port: 443, * certFile: "./path/to/localhost.crt", * keyFile: "./path/to/localhost.key", * }; * listenAndServeTLS(options, (req) => { * req.respond({ body }); * }); * * @param options Server configuration * @param handler Request handler */ export async function listenAndServeTLS( options: HTTPSOptions, handler: (req: ServerRequest) => void, ): Promise<void> { const server = serveTLS(options); for await (const request of server) { handler(request); } } /** * Interface of HTTP server response. * If body is a Reader, response would be chunked. * If body is a string, it would be UTF-8 encoded by default. */ export interface Response { status?: number; headers?: Headers; body?: Uint8Array | Deno.Reader | string; trailers?: () => Promise<Headers> | Headers; }
the_stack
import { addSubTask, addTask, addTimeSpent, convertToMainTask, deleteMainTasks, deleteTask, moveSubTask, moveSubTaskDown, moveSubTaskUp, moveToArchive, moveToOtherProject, removeTagsForAllTasks, removeTimeSpent, reScheduleTask, restoreTask, roundTimeSpentForDay, scheduleTask, setCurrentTask, setSelectedTask, toggleStart, toggleTaskShowSubTasks, unScheduleTask, unsetCurrentTask, updateTask, updateTaskTags, updateTaskUi, } from './task.actions'; import { ShowSubTasksMode, Task, TaskAdditionalInfoTargetPanel, TaskState, } from '../task.model'; import { calcTotalTimeSpent } from '../util/calc-total-time-spent'; import { addTaskRepeatCfgToTask } from '../../task-repeat-cfg/store/task-repeat-cfg.actions'; import { deleteTaskHelper, getTaskById, reCalcTimesForParentIfParent, reCalcTimeSpentForParentIfParent, removeTaskFromParentSideEffects, updateDoneOnForTask, updateTimeEstimateForTask, updateTimeSpentForTask, } from './task.reducer.util'; import { taskAdapter } from './task.adapter'; import { moveItemInList } from '../../work-context/store/work-context-meta.helper'; import { arrayMoveLeft, arrayMoveRight } from '../../../util/array-move'; import { filterOutId } from '../../../util/filter-out-id'; import { addTaskAttachment, deleteTaskAttachment, updateTaskAttachment, } from '../task-attachment/task-attachment.actions'; import { Update } from '@ngrx/entity'; import { unique } from '../../../util/unique'; import { roundDurationVanilla } from '../../../util/round-duration'; import { loadAllData } from '../../../root-store/meta/load-all-data.action'; import { migrateTaskState } from '../migrate-task-state.util'; import { createReducer, on } from '@ngrx/store'; export const TASK_FEATURE_NAME = 'tasks'; // REDUCER // ------- export const initialTaskState: TaskState = taskAdapter.getInitialState({ // overwrite entity model to avoid problems with typing ids: [], // TODO maybe at least move those properties to an ui property currentTaskId: null, selectedTaskId: null, taskAdditionalInfoTargetPanel: TaskAdditionalInfoTargetPanel.Default, lastCurrentTaskId: null, isDataLoaded: false, }) as TaskState; export const taskReducer = createReducer<TaskState>( initialTaskState, // META ACTIONS // ------------ on(loadAllData, (state, { appDataComplete }) => appDataComplete.task ? migrateTaskState({ ...appDataComplete.task, currentTaskId: null, lastCurrentTaskId: appDataComplete.task.currentTaskId, isDataLoaded: true, }) : state, ), // TODO check if working on(setCurrentTask, (state, { id }) => { if (id) { const task = getTaskById(id, state); const subTaskIds = task.subTaskIds; let taskToStartId = id; if (subTaskIds && subTaskIds.length) { const undoneTasks = subTaskIds .map((tid) => getTaskById(tid, state)) .filter((ta: Task) => !ta.isDone); taskToStartId = undoneTasks.length ? undoneTasks[0].id : subTaskIds[0]; } return { ...taskAdapter.updateOne( { id: taskToStartId, changes: { isDone: false, doneOn: null }, }, state, ), currentTaskId: taskToStartId, selectedTaskId: state.selectedTaskId && taskToStartId, }; } else { return { ...state, currentTaskId: null, }; } }), on(unsetCurrentTask, (state) => { return { ...state, currentTaskId: null, lastCurrentTaskId: state.currentTaskId }; }), on(setSelectedTask, (state, { id, taskAdditionalInfoTargetPanel }) => { return { ...state, taskAdditionalInfoTargetPanel: !id || id === state.selectedTaskId ? null : taskAdditionalInfoTargetPanel || null, selectedTaskId: id === state.selectedTaskId ? null : id, }; }), // Task Actions // ------------ on(addTask, (state, { task }) => { const newTask = { ...task, timeSpent: calcTotalTimeSpent(task.timeSpentOnDay), }; return taskAdapter.addOne(newTask, state); }), on(updateTask, (state, { task }) => { let stateCopy = state; const id = task.id as string; const { timeSpentOnDay, timeEstimate } = task.changes; stateCopy = timeSpentOnDay ? updateTimeSpentForTask(id, timeSpentOnDay, stateCopy) : stateCopy; stateCopy = updateTimeEstimateForTask(id, timeEstimate, stateCopy); stateCopy = updateDoneOnForTask(task, stateCopy); return taskAdapter.updateOne(task, stateCopy); }), on(updateTaskUi, (state, { task }) => { return taskAdapter.updateOne(task, state); }), on(updateTaskTags, (state, { task, newTagIds }) => { return taskAdapter.updateOne( { id: task.id, changes: { tagIds: newTagIds, }, }, state, ); }), on(removeTagsForAllTasks, (state, { tagIdsToRemove }) => { const updates: Update<Task>[] = state.ids.map((taskId) => ({ id: taskId, changes: { tagIds: getTaskById(taskId, state).tagIds.filter( (tagId) => !tagIdsToRemove.includes(tagId), ), }, })); return taskAdapter.updateMany(updates, state); }), // TODO simplify on(toggleTaskShowSubTasks, (state, { taskId, isShowLess, isEndless }) => { const task = getTaskById(taskId, state); const subTasks = task.subTaskIds.map((id) => getTaskById(id, state)); const doneTasksLength = subTasks.filter((t) => t.isDone).length; const isDoneTaskCaseNeeded = doneTasksLength && doneTasksLength < subTasks.length; const oldVal = +task._showSubTasksMode; let newVal; if (isDoneTaskCaseNeeded) { newVal = oldVal + (isShowLess ? -1 : 1); if (isEndless) { if (newVal > ShowSubTasksMode.Show) { newVal = ShowSubTasksMode.HideAll; } else if (newVal < ShowSubTasksMode.HideAll) { newVal = ShowSubTasksMode.Show; } } else { if (newVal > ShowSubTasksMode.Show) { newVal = ShowSubTasksMode.Show; } if (newVal < ShowSubTasksMode.HideAll) { newVal = ShowSubTasksMode.HideAll; } } } else { if (isEndless) { if (oldVal === ShowSubTasksMode.Show) { newVal = ShowSubTasksMode.HideAll; } if (oldVal !== ShowSubTasksMode.Show) { newVal = ShowSubTasksMode.Show; } } else { newVal = isShowLess ? ShowSubTasksMode.HideAll : ShowSubTasksMode.Show; } } // failsafe newVal = isNaN(newVal as any) ? ShowSubTasksMode.HideAll : newVal; return taskAdapter.updateOne( { id: taskId, changes: { _showSubTasksMode: newVal, }, }, state, ); }), on(deleteTask, (state, { task }) => { return deleteTaskHelper(state, task); }), on(deleteMainTasks, (state, { taskIds }) => { const allIds = taskIds.reduce((acc: string[], id: string) => { return [...acc, id, ...getTaskById(id, state).subTaskIds]; }, []); return taskAdapter.removeMany(allIds, state); }), on(moveSubTask, (state, { taskId, srcTaskId, targetTaskId, newOrderedIds }) => { let newState = state; const oldPar = getTaskById(srcTaskId, state); const newPar = getTaskById(targetTaskId, state); // for old parent remove newState = taskAdapter.updateOne( { id: oldPar.id, changes: { subTaskIds: oldPar.subTaskIds.filter(filterOutId(taskId)), }, }, newState, ); newState = reCalcTimesForParentIfParent(oldPar.id, newState); // for new parent add and move newState = taskAdapter.updateOne( { id: newPar.id, changes: { subTaskIds: moveItemInList(taskId, newPar.subTaskIds, newOrderedIds), }, }, newState, ); newState = reCalcTimesForParentIfParent(newPar.id, newState); // change parent id for moving task newState = taskAdapter.updateOne( { id: taskId, changes: { parentId: newPar.id, projectId: newPar.projectId, }, }, newState, ); return newState; }), on(moveSubTaskUp, (state, { id, parentId }) => { const parentSubTaskIds = getTaskById(parentId, state).subTaskIds; return taskAdapter.updateOne( { id: parentId, changes: { subTaskIds: arrayMoveLeft(parentSubTaskIds, id), }, }, state, ); }), on(moveSubTaskDown, (state, { id, parentId }) => { const parentSubTaskIds = getTaskById(parentId, state).subTaskIds; return taskAdapter.updateOne( { id: parentId, changes: { subTaskIds: arrayMoveRight(parentSubTaskIds, id), }, }, state, ); }), on(addTimeSpent, (state, { task, date, duration }) => { const currentTimeSpentForTickDay = (task.timeSpentOnDay && +task.timeSpentOnDay[date]) || 0; return updateTimeSpentForTask( task.id, { ...task.timeSpentOnDay, [date]: currentTimeSpentForTickDay + duration, }, state, ); }), on(removeTimeSpent, (state, { id, date, duration }) => { const task = getTaskById(id, state); const currentTimeSpentForTickDay = (task.timeSpentOnDay && +task.timeSpentOnDay[date]) || 0; return updateTimeSpentForTask( id, { ...task.timeSpentOnDay, [date]: Math.max(currentTimeSpentForTickDay - duration, 0), }, state, ); }), on(addSubTask, (state, { task, parentId }) => { const parentTask = getTaskById(parentId, state); // add item1 const stateCopy = taskAdapter.addOne( { ...task, parentId, // update timeSpent if first sub task and non present ...(parentTask.subTaskIds.length === 0 && Object.keys(task.timeSpentOnDay).length === 0 ? { timeSpentOnDay: parentTask.timeSpentOnDay, timeSpent: calcTotalTimeSpent(parentTask.timeSpentOnDay), } : {}), // update timeEstimate if first sub task and non present ...(parentTask.subTaskIds.length === 0 && !task.timeEstimate ? { timeEstimate: parentTask.timeEstimate } : {}), // should always be empty tagIds: [], // should always be the one of the parent projectId: parentTask.projectId, }, state, ); return { ...stateCopy, // update current task to new sub task if parent was current before ...(state.currentTaskId === parentId ? { currentTaskId: task.id } : {}), // also add to parent task entities: { ...stateCopy.entities, [parentId]: { ...parentTask, subTaskIds: [...parentTask.subTaskIds, task.id], }, }, }; }), on(convertToMainTask, (state, { task }) => { const par = state.entities[task.parentId as string]; if (!par) { throw new Error('No parent for sub task'); } const stateCopy = removeTaskFromParentSideEffects(state, task); return taskAdapter.updateOne( { id: task.id, changes: { parentId: null, tagIds: [...par.tagIds], }, }, stateCopy, ); }), on(toggleStart, (state) => { if (state.currentTaskId) { return { ...state, lastCurrentTaskId: state.currentTaskId, }; } return state; }), on(moveToOtherProject, (state, { targetProjectId, task }) => { const updates: Update<Task>[] = [task.id, ...task.subTaskIds].map((id) => ({ id, changes: { projectId: targetProjectId, }, })); return taskAdapter.updateMany(updates, state); }), on(roundTimeSpentForDay, (state, { day, taskIds, isRoundUp, roundTo, projectId }) => { const isLimitToProject: boolean = !!projectId || projectId === null; const idsToUpdateDirectly: string[] = taskIds.filter((id) => { const task: Task = getTaskById(id, state); return ( (task.subTaskIds.length === 0 || !!task.parentId) && (!isLimitToProject || task.projectId === projectId) ); }); const subTaskIds: string[] = idsToUpdateDirectly.filter( (id) => !!getTaskById(id, state).parentId, ); const parentTaskToReCalcIds: string[] = unique<string>( subTaskIds.map((id) => getTaskById(id, state).parentId as string), ); const updateSubsAndMainWithoutSubs: Update<Task>[] = idsToUpdateDirectly.map((id) => { const spentOnDayBefore = getTaskById(id, state).timeSpentOnDay; const timeSpentOnDayUpdated = { ...spentOnDayBefore, [day]: roundDurationVanilla(spentOnDayBefore[day], roundTo, isRoundUp), }; return { id, changes: { timeSpentOnDay: timeSpentOnDayUpdated, timeSpent: calcTotalTimeSpent(timeSpentOnDayUpdated), }, }; }); // // update subs const newState = taskAdapter.updateMany(updateSubsAndMainWithoutSubs, state); // reCalc parents return parentTaskToReCalcIds.reduce( (acc, parentId) => reCalcTimeSpentForParentIfParent(parentId, acc), newState, ); }), // TASK ARCHIVE STUFF // ------------------ // TODO fix on(moveToArchive, (state, { tasks }) => { let copyState = state; tasks.forEach((task) => { copyState = deleteTaskHelper(copyState, task); }); return { ...copyState, }; }), on(restoreTask, (state, { task, subTasks = [] }) => { const updatedTask = { ...task, isDone: false, doneOn: null, }; return taskAdapter.addMany([updatedTask, ...subTasks], state); }), // REPEAT STUFF // ------------ on(addTaskRepeatCfgToTask, (state, { taskRepeatCfg, taskId }) => { return taskAdapter.updateOne( { id: taskId, changes: { repeatCfgId: taskRepeatCfg.id, }, }, state, ); }), // TASK ATTACHMENTS // ---------------- on(addTaskAttachment, (state, { taskId, taskAttachment }) => { return taskAdapter.updateOne( { id: taskId, changes: { attachments: [...getTaskById(taskId, state).attachments, taskAttachment], }, }, state, ); }), on(updateTaskAttachment, (state, { taskId, taskAttachment }) => { const attachments = getTaskById(taskId, state).attachments; const updatedAttachments = attachments.map((attachment) => attachment.id === taskAttachment.id ? { ...attachment, ...taskAttachment.changes, } : attachment, ); return taskAdapter.updateOne( { id: taskId, changes: { attachments: updatedAttachments, }, }, state, ); }), on(deleteTaskAttachment, (state, { taskId, id }) => { return taskAdapter.updateOne( { id: taskId, changes: { attachments: getTaskById(taskId, state).attachments.filter( (at) => at.id !== id, ), }, }, state, ); }), // REMINDER STUFF // -------------- on(scheduleTask, (state, { task, plannedAt }) => { return taskAdapter.updateOne( { id: task.id, changes: { plannedAt, }, }, state, ); }), on(reScheduleTask, (state, { id, plannedAt }) => { return taskAdapter.updateOne( { id, changes: { plannedAt, }, }, state, ); }), on(unScheduleTask, (state, { id }) => { return taskAdapter.updateOne( { id, changes: { plannedAt: null, }, }, state, ); }), );
the_stack
import Database from '../..'; import { getDatabase } from '..'; import Model, { ModelCtor } from '../../model'; let db: Database; beforeEach(async () => { db = getDatabase(); }); afterEach(async () => { await db.close(); }); describe('model', () => { beforeEach(async () => { db.table({ name: 'users', tableName: 'user1234', fields: [ { type: 'string', name: 'name', }, { type: 'hasone', name: 'profile', }, { type: 'hasMany', name: 'posts', }, { type: 'hasMany', name: 'posts_title1', target: 'posts', scope: { title: 'title1', }, }, ], }); db.table({ name: 'profiles', tableName: 'profile1234', fields: [ { type: 'string', name: 'name', }, ], }); db.table({ name: 'posts', tableName: 'post123456', fields: [ { type: 'string', name: 'title', }, { type: 'belongsTo', name: 'user', }, { type: 'belongsToMany', name: 'tags', }, { type: 'belongsToMany', name: 'tags_name1', target: 'tags', scope: { name: 'name1', }, }, { type: 'hasMany', name: 'comments', }, { type: 'hasMany', name: 'current_user_comments', target: 'comments', }, ], }); db.table({ name: 'posts_tags', tableName: 'posts_tags1234', fields: [ { type: 'string', name: 'name', }, ], }); db.table({ name: 'tags', tableName: 'tag1234', fields: [ { type: 'string', name: 'name', }, { type: 'belongsToMany', name: 'posts', }, ], }); db.table({ name: 'comments', tableName: 'comment1234', fields: [ { type: 'belongsTo', name: 'user', }, { type: 'belongsTo', name: 'post', }, { type: 'string', name: 'content', }, ], }); db.table({ name: 'tables', fields: [ { type: 'string', name: 'name', primaryKey: true, autoIncrement: false, }, { type: 'hasMany', name: 'fields', }, ], }); db.table({ name: 'fields', fields: [ { type: 'belongsTo', name: 'table', }, { type: 'string', name: 'name', }, ], }); db.table({ name: 'rows', fields: [ { type: 'string', name: 'name', unique: true, }, { type: 'hasMany', name: 'columns', sourceKey: 'name', }, ], }); db.table({ name: 'columns', fields: [ { type: 'belongsTo', name: 'row', targetKey: 'name', }, { type: 'string', name: 'name', }, ], }); await db.sync({ force: true, }); }); describe('.updateAssociations', () => { describe('belongsTo', () => { it('update with primary key', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user = await User.create(); const post = await Post.create(); await post.updateAssociations({ user: user.id, }); const authorizedPost = await Post.findByPk(post.id); expect(authorizedPost.user_id).toBe(user.id); }); it('update with new object', async () => { const Post = db.getModel('posts'); const post = await Post.create(); await post.updateAssociations({ user: {}, }); const authorizedPost = await Post.findByPk(post.id); expect(authorizedPost.user_id).toBe(1); }); it('update with new model', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user = await User.create(); const post = await Post.create(); await post.updateAssociations({ user, }); const authorizedPost = await Post.findByPk(post.id); expect(authorizedPost.user_id).toBe(user.id); }); it('update with exist model', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user1 = await User.create(); const user2 = await Post.create(); const post = await Post.create(); await post.updateAssociations({ user: user1.id, }); await post.updateAssociations({ user: user2.id, }); const authorizedPost = await Post.findByPk(post.id); expect(authorizedPost.user_id).toBe(user2.id); }); }); describe('hasMany', () => { it('update with primary key', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments: comments.map((item) => item.id), }); const postComments = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id'], }); expect(postComments.map((item) => item.id)).toEqual([1, 2, 3, 4]); }); it('update with new object', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); await post.updateAssociations({ comments: [{}, {}, {}, {}], }); const postCommentIds = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id'], }); expect(postCommentIds.map((item) => item.id)).toEqual([1, 2, 3, 4]); }); it('update with new model', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments, }); const postCommentIds = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id'], }); expect(postCommentIds.map((item) => item.id)).toEqual([1, 2, 3, 4]); }); it('update with exist rows/primaryKeys', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments, }); await post.updateAssociations({ comments, }); await post.updateAssociations({ comments: comments.map((item) => item.id), }); const postCommentIds = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id'], }); expect(postCommentIds.map((item) => item.id)).toEqual([1, 2, 3, 4]); }); it('update with exist objects', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments, }); await post.updateAssociations({ comments: comments.map((item) => ({ ...item.get(), content: `content${item.id}`, })), }); const postComments = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id', 'content'], }); expect( postComments.map(({ id, content }) => ({ id, content })), ).toEqual([ { id: 1, content: 'content1' }, { id: 2, content: 'content2' }, { id: 3, content: 'content3' }, { id: 4, content: 'content4' }, ]); }); it('update another with exist objects', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const post2 = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments, }); const postComments = await Comment.findAll({ where: { post_id: post.id }, }); expect( postComments.map(({ id, post_id }) => ({ id, post_id })), ).toEqual([ { id: 1, post_id: post.id }, { id: 2, post_id: post.id }, { id: 3, post_id: post.id }, { id: 4, post_id: post.id }, ]); await post2.updateAssociations({ comments: postComments.map((item) => ({ ...item.get(), content: `content${item.id}`, })), }); const updatedComments = await Comment.findAll(); const post1CommentsCount = await Comment.count({ where: { post_id: post.id }, }); expect(post1CommentsCount).toBe(0); const post2Comments = await Comment.findAll({ where: { post_id: post2.id }, attributes: ['id', 'content'], }); expect( post2Comments.map(({ id, content }) => ({ id, content })), ).toEqual([ { id: 1, content: 'content1' }, { id: 2, content: 'content2' }, { id: 3, content: 'content3' }, { id: 4, content: 'content4' }, ]); }); it('update with different primaryKey/row/object', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comments = await Comment.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ comments, }); await post.updateAssociations({ comments: comments .filter(({ id }) => Boolean(id % 2)) .concat(...[await Comment.create()]), }); const postComments = await Comment.findAll({ where: { post_id: post.id }, attributes: ['id'], }); expect(postComments.map(({ id }) => id)).toEqual([1, 3, 5]); }); }); describe('belongsToMany', () => { it('update with primary key', async () => { const [Post, Tag, PostTag] = db.getModels([ 'posts', 'tags', 'posts_tags', ]); const post = await Post.create(); const tags = await Tag.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ tags: tags.map((item) => item.id), }); const tagged = await PostTag.findAll({ where: { post_id: post.id }, attributes: ['tag_id'], }); expect(tagged.map((item) => item.tag_id)).toEqual([1, 2, 3, 4]); }); it('update with exist rows/primaryKeys', async () => { const [Post, Tag, PostTag] = db.getModels([ 'posts', 'tags', 'posts_tags', ]); const post = await Post.create(); const tags = await Tag.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ tags: tags.map((item) => item.id), }); await post.updateAssociations({ tags: tags.map((item) => item.id), }); await post.updateAssociations({ tags, }); const tagged = await PostTag.findAll({ where: { post_id: post.id }, attributes: ['tag_id', 'post_id'], }); expect( tagged.map(({ post_id, tag_id }) => ({ post_id, tag_id })), ).toEqual([ { tag_id: 1, post_id: 1 }, { tag_id: 2, post_id: 1 }, { tag_id: 3, post_id: 1 }, { tag_id: 4, post_id: 1 }, ]); }); it('update with exist rows/primaryKeys and new objects', async () => { const [Post, Tag, PostTag] = db.getModels([ 'posts', 'tags', 'posts_tags', ]); const post = await Post.create(); const tags = await Tag.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ tags: tags.map((item) => item.id), }); await post.updateAssociations({ tags: tags .filter(({ id }) => Boolean(id % 2)) .concat(await Tag.create({})), }); const tagged = await PostTag.findAll({ where: { post_id: post.id }, attributes: ['tag_id'], }); expect(tagged.map(({ tag_id }) => tag_id)).toEqual([1, 3, 5]); }); it('update other with exist rows/primaryKeys', async () => { const [Post, Tag, PostTag] = db.getModels([ 'posts', 'tags', 'posts_tags', ]); const post = await Post.create(); const post2 = await Post.create(); const tags = await Tag.bulkCreate([{}, {}, {}, {}]); await post.updateAssociations({ tags: tags.map((item) => item.id), }); await post2.updateAssociations({ tags, }); const tagged = await PostTag.findAll(); expect( tagged.map(({ post_id, tag_id }) => ({ post_id, tag_id })), ).toEqual([ { tag_id: 1, post_id: 1 }, { tag_id: 2, post_id: 1 }, { tag_id: 3, post_id: 1 }, { tag_id: 4, post_id: 1 }, { tag_id: 1, post_id: 2 }, { tag_id: 2, post_id: 2 }, { tag_id: 3, post_id: 2 }, { tag_id: 4, post_id: 2 }, ]); }); }); it('through attributes', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tag = await Tag.create(); await post.updateAssociations({ tags: [ { name: 'xxx', posts_tags: { name: 'name134', }, }, { id: tag.id, posts_tags: { name: 'name234', }, }, ], }); const PostTag = db.getModel('posts_tags'); const [t1, t2] = await PostTag.findAll({ where: { post_id: post.id, }, order: ['tag_id'], }); expect(t1.name).toBe('name234'); expect(t2.name).toBe('name134'); }); }); describe('scope', () => { it('scope', async () => { const [User, Post, Comment] = db.getModels([ 'users', 'posts', 'comments', ]); const user1 = await User.create(); const user2 = await User.create(); const user3 = await User.create(); const user4 = await User.create(); const post = await Post.create(); const comment = await Comment.create(); comment.updateAssociations({ post: post, user: user1, }); await post.updateAssociations({ comments: [ { content: 'content1', user: user1, }, { content: 'content2', user: user2, }, { content: 'content3', user: user3, }, { content: 'content4', user: user4, }, ], }); try { const comments = await post.getCurrent_user_comments(); // TODO: no expect } catch (error) { console.error(error); } }); }); describe('query', () => { it('q', async () => { db.getModel('tags').addScope('scopeName', (name, ctx) => { expect(ctx.scopeName).toBe(name); return { where: { name: name, }, }; }); const [User, Post] = db.getModels(['users', 'posts']); const postData = []; for (let index = 0; index < 20; index++) { postData.push({ title: `title${index}`, }); } const user = await User.create({ name: 'name112233', }); await Post.create({ title: 'xxxx', }); const post = await Post.create({ title: 'title112233', }); await user.updateAssociations({ posts: post, }); await post.updateAssociations({ tags: [{ name: 'tag1' }, { name: 'tag2' }, { name: 'tag3' }], }); // where & include const options = Post.parseApiJson({ filter: { title: 'title112233', user: { // belongsTo name: 'name112233', }, tags: { // belongsToMany scopeName: 'tag3', }, }, fields: ['title', 'tags_count', 'tags.name', 'user.name'], sort: '-tags_count,tags.name,user.posts_count', context: { scopeName: 'tag3', }, }); console.log(options); try { // DatabaseError [SequelizeDatabaseError]: column tags.scopeName does not exist // SELECT count("posts"."id") AS "count" FROM "post123456" AS "posts" INNER JOIN ( "posts_tags1234" AS "tags->posts_tags" INNER JOIN "tag1234" AS "tags" ON "tags"."id" = "tags->posts_tags"."tag_id") ON "posts"."id" = "tags->posts_tags"."post_id" AND "tags"."scopeName" = 'tag3' INNER JOIN "user1234" AS "user" ON "posts"."user_id" = "user"."id" AND "user"."name" = 'name112233' WHERE "posts"."title" = 'title112233'; const { rows, count } = await Post.findAndCountAll({ ...options, // group: ['id'], // limit: 20, // offset: 20, }); // console.log(JSON.stringify(rows[0].toJSON(), null, 2)); rows.forEach((row) => { // expect(row.toJSON()).toEqual({ title: 'title112233', 'tags_count': 3, user: { name: 'name112233', posts_count: 1 } }); expect(row.get('title')).toBe('title112233'); expect(row.user.get('name')).toBe('name112233'); }); } catch (error) { console.error(error); } // console.log(count); // expect(count).toBe(1); }); it('to be explained', async () => { const [User, Post] = db.getModels(['users', 'posts']); const postData = []; for (let index = 0; index < 20; index++) { postData.push({ title: `title${index}`, }); } const user = await User.create(); let posts = await Post.bulkCreate(postData); await user.updateAssociations({ posts: posts, }); const userOne = await User.findOne({ attributes: { exclude: ['updated_at'], include: [ User.withCountAttribute('posts'), User.withCountAttribute('posts_title1'), ], }, where: { id: user.id, }, }); expect(userOne.get('posts_count')).toBe(20); expect(userOne.get('posts_title1_count')).toBe(1); }); it('to be explained', async () => { const [User, Post] = db.getModels(['users', 'posts']); const postData = []; for (let index = 0; index < 20; index++) { postData.push({ title: `title${index}`, }); } const user = await User.create(); let posts = await Post.bulkCreate(postData); await user.updateAssociations({ posts: posts, }); const userOne = await User.findOne({ attributes: { exclude: ['updated_at'], include: [ User.withCountAttribute({ association: 'posts', alias: 'posts2_count', }), ], }, where: { id: user.id, }, }); expect(userOne.get('posts2_count')).toBe(20); }); it('to be explained', async () => { const [Tag, Post, User] = db.getModels(['tags', 'posts', 'users']); const tagData = []; for (let index = 0; index < 5; index++) { tagData.push({ name: `name${index}`, }); } let post = await Post.create(); let tags = await Tag.bulkCreate(tagData); await post.updateAssociations({ user: { name: 'user1', }, tags, }); post = await Post.findOne({ attributes: { include: [ 'id', Post.withCountAttribute('tags'), Post.withCountAttribute('tags_name1'), ], }, where: { id: post.id, }, include: [ { association: 'user', attributes: [ 'id', 'name', User.withCountAttribute({ sourceAlias: 'user', association: 'posts', }), ], }, { association: 'tags', attributes: ['id', 'name', Tag.withCountAttribute('posts')], }, ], }); expect(post.get('tags_count')).toBe(5); expect(post.get('tags_name1_count')).toBe(1); expect(post.user.get('posts_count')).toBe(1); post.tags.forEach((tag) => { expect(tag.get('posts_count')).toBe(1); }); }); }); describe('hasOne', () => { it('shoud associated id when association is integer', async () => { const [User, Profile] = db.getModels(['users', 'profiles']); const user = await User.create(); const profile = await Profile.create(); await user.updateAssociations({ // 关联 id profile, }); const userProfile = await user.getProfile(); expect(userProfile.id).toBe(profile.id); }); it('shoud associated id when association is integer', async () => { const [User, Profile] = db.getModels(['users', 'profiles']); const user = await User.create(); const profile = await Profile.create(); await user.updateAssociations({ // 关联 id profile: profile.id, }); const userProfile = await user.getProfile(); expect(userProfile.id).toBe(profile.id); }); it('shoud associated id when association is integer', async () => { const [User, Profile] = db.getModels(['users', 'profiles']); const user = await User.create(); const profile = await Profile.create(); await user.updateAssociations({ // 关联 id profile: { id: profile.id, }, }); const userProfile = await user.getProfile(); expect(userProfile.id).toBe(profile.id); }); it('shoud associated id when association is integer', async () => { const [User, Profile] = db.getModels(['users', 'profiles']); const user = await User.create(); const profile = await Profile.create(); await user.updateAssociations({ // 关联 id profile: { id: profile.id, name: 'profile1', }, }); const userProfile = await user.getProfile(); expect(userProfile.id).toBe(profile.id); expect(userProfile.name).toBe('profile1'); }); it('shoud associated id when association is integer', async () => { const [User] = db.getModels(['users']); const user = await User.create(); await user.updateAssociations({ // 关联 id profile: { name: 'profile2', }, }); const userProfile = await user.getProfile(); expect(userProfile.name).toBe('profile2'); }); }); describe('hasMany', () => { it('@1', async () => { const [Comment, Post] = db.getModels(['comments', 'posts']); const comment = await Comment.create(); const post = await Post.create(); await post.updateAssociations({ comments: comment, }); const count = await post.countComments(); expect(count).toBe(1); }); it('@2', async () => { const [Comment, Post] = db.getModels(['comments', 'posts']); const comment = await Comment.create(); const post = await Post.create(); await post.updateAssociations({ comments: [comment], }); const count = await post.countComments(); expect(count).toBe(1); }); it('@3', async () => { const [Comment, Post] = db.getModels(['comments', 'posts']); const comment = await Comment.create(); const post = await Post.create(); await post.updateAssociations({ comments: [comment.id], }); const count = await post.countComments(); expect(count).toBe(1); }); it('@4', async () => { const [Comment, Post] = db.getModels(['comments', 'posts']); const comment = await Comment.create(); const post = await Post.create(); await post.updateAssociations({ comments: comment.id, }); const count = await post.countComments(); expect(count).toBe(1); }); it('@5', async () => { const [Post] = db.getModels(['posts']); const post = await Post.create(); await post.updateAssociations({ comments: { content: 'content1', }, }); const count = await post.countComments(); expect(count).toBe(1); }); it('@6', async () => { const [Post, Comment] = db.getModels(['posts', 'comments']); const post = await Post.create(); const comment1 = await Comment.create(); const comment2 = await Comment.create(); await post.updateAssociations({ comments: [ { content: 'content2', }, { content: 'content3', }, { id: comment1.id, }, comment2, ], }); const count = await post.countComments(); expect(count).toBe(4); }); it('shoud work1', async () => { const [Table, Field] = db.getModels(['tables', 'fields']); const table = await Table.create({ name: 'examples', }); await table.updateAssociations({ fields: [{ name: 'name' }], }); const field = await Field.findOne({ where: { table_name: 'examples', name: 'name', }, }); expect(field).toBeDefined(); expect(field.get('name')).toBe('name'); }); it('shoud work2', async () => { const [Row, Column] = db.getModels(['rows', 'columns']); const row = await Row.create({ name: 'examples', }); await row.updateAssociations({ columns: [{ name: 'name' }], }); const column = await Column.findOne({ where: { row_name: 'examples', name: 'name', }, }); expect(column).toBeDefined(); expect(column.get('name')).toBe('name'); }); it('shoud work3', async () => { const [Table, Field] = db.getModels(['tables', 'fields']); const table = await Table.create({ name: 'abcdef', }); const field = await Field.create({ name: 'name123' }); await table.updateAssociations({ fields: [ { id: field.id, name: 'nam1234', }, ], }); const f = await Field.findOne({ where: { table_name: 'abcdef', name: 'nam1234', }, }); expect(f).toBeDefined(); expect(f.id).toBe(field.id); const options = Table.parseApiJson({ fields: ['name', 'fields_count'], }); const t = await Table.findOne(options); expect(t.get('fields_count')).toBe(1); }); }); describe('blongsTo', () => { it('shoud associated id when association is integer', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user = await User.create(); const post = await Post.create(); await post.updateAssociations({ // 关联 id user, }); expect(user.id).toBe(post.user_id); const postUser = await post.getUser(); expect(user.id).toBe(postUser.id); }); it('shoud associated id when association is integer', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user = await User.create(); const post = await Post.create(); await post.updateAssociations({ // 关联 id user: user.id, }); expect(user.id).toBe(post.user_id); const postUser = await post.getUser(); expect(user.id).toBe(postUser.id); }); it('shoud associated id when association is object only id attribute', async () => { const [User, Tag, Post] = db.getModels(['users', 'tags', 'posts']); const user = await User.create(); const post = await Post.create(); await post.updateAssociations({ // 关联 id user: { id: user.id, }, }); expect(user.id).toBe(post.user_id); const postUser = await post.getUser(); expect(user.id).toBe(postUser.id); }); it('shoud associate and update other attributes', async () => { const [User, Post] = db.getModels(['users', 'posts']); const user = await User.create(); let post = await Post.create(); await post.updateAssociations({ // 关联并更新当前 id 的数据 user: { id: user.id, name: 'user1234', }, }); expect(user.id).toBe(post.user_id); const postUser = await post.getUser(); expect(user.id).toBe(postUser.id); expect(postUser.name).toBe('user1234'); }); it('shoud work', async () => { const [Post] = db.getModels(['posts']); const post = await Post.create(); await post.updateAssociations({ // 新建并关联 user user: { name: 'user123456', }, }); const postUser = await post.getUser(); expect(postUser.name).toBe('user123456'); }); it('shoud work', async () => { const [Table, Field] = db.getModels(['tables', 'fields']); const field = await Field.create({ name: 'fieldName', }); await Table.create({ name: 'demos' }); await field.updateAssociations({ table: 'demos', }); expect(field.table_name).toBe('demos'); }); it('shoud work', async () => { const [Row, Column] = db.getModels(['rows', 'columns']); await Row.create({ name: 't1_examples', }); const column = await Column.create(); await column.updateAssociations({ row: 't1_examples', }); }); it('shoud work', async () => { const [Row, Column] = db.getModels(['rows', 'columns']); await Row.create({ name: 't2_examples', }); const column = await Column.create(); await column.updateAssociations({ row: { name: 't2_examples', }, }); }); }); describe('belongsToMany', () => { it('@', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tag = await Tag.create(); await post.updateAssociations({ tags: tag, }); const count = await post.countTags(); expect(count).toBe(1); }); it('@', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tag = await Tag.create(); await post.updateAssociations({ tags: [tag], }); const count = await post.countTags(); expect(count).toBe(1); }); it('@', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tag = await Tag.create(); await post.updateAssociations({ tags: tag.id, }); const count = await post.countTags(); expect(count).toBe(1); }); it('@', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tag = await Tag.create(); await post.updateAssociations({ tags: [tag.id], }); const count = await post.countTags(); expect(count).toBe(1); }); it('@', async () => { const [Post, Tag] = db.getModels(['posts', 'tags']); const post = await Post.create(); const tags = await Tag.bulkCreate([{}, {}]); await post.updateAssociations({ tags: tags, }); const count = await post.countTags(); expect(count).toBe(2); }); it('@', async () => { const [Post] = db.getModels(['posts']); const post = await Post.create(); await post.updateAssociations({ tags: { name: 'tag1', }, }); const count = await post.countTags(); expect(count).toBe(1); }); it('@', async () => { const [Post] = db.getModels(['posts']); const post = await Post.create(); await post.updateAssociations({ tags: [ { name: 'tag2', }, { name: 'tag3', }, ], }); const count = await post.countTags(); expect(count).toBe(2); }); }); }); describe('belongsToMany', () => { let post: Model; let tag1: Model; let tag2: Model; beforeEach(async () => { db.table({ name: 'posts', tableName: 't333333_posts', fields: [ { type: 'string', name: 'slug', unique: true, }, { type: 'belongsToMany', name: 'tags', sourceKey: 'slug', targetKey: 'name', }, ], }); db.table({ name: 'tags', tableName: 't333333_tags', fields: [ { type: 'string', name: 'name', unique: true, }, { type: 'belongsToMany', name: 'posts', sourceKey: 'name', targetKey: 'slug', }, ], }); await db.sync({ force: true }); const [Post, Tag] = db.getModels(['posts', 'tags']); post = await Post.create({ slug: 'post1' }); tag1 = await Tag.create({ name: 'tag1' }); tag2 = await Tag.create({ name: 'tag2' }); }); it('update with targetKey', async () => { await post.updateAssociations({ tags: tag1.name, }); expect(await post.countTags()).toBe(1); }); it('update with model', async () => { await post.updateAssociations({ tags: [tag1, tag2], }); expect(await post.countTags()).toBe(2); }); it('update with targetKey', async () => { await post.updateAssociations({ tags: { name: 'tag2', }, }); expect(await post.countTags()).toBe(1); expect((await post.getTags())[0].id).toBe(tag2.id); }); it('update with new object', async () => { await post.updateAssociations({ tags: [ { name: 'tag3', }, ], }); expect(await post.countTags()).toBe(1); }); });
the_stack
import { JsPlumbDefaults } from "./defaults"; import { Connection, ConnectionOptions } from "./connector/connection-impl"; import { Endpoint } from "./endpoint/endpoint"; import { RedrawResult } from "./router/router"; import { RotatedPointXY, Rotations, PointXY, Size, Dictionary, Extents, EventGenerator } from "@jsplumb/util"; import { UpdateOffsetOptions, ConnectParams } from "./params"; import { SourceDefinition, BehaviouralTypeDescriptor, // <-- TypeDescriptor, ConnectionTypeDescriptor, EndpointTypeDescriptor } from './type-descriptors'; import { ConnectionMovedParams } from "./callbacks"; import { EndpointOptions } from "./endpoint/endpoint-options"; import { AddGroupOptions, GroupManager } from "./group/group-manager"; import { UIGroup } from "./group/group"; import { Router } from "./router/router"; import { EndpointSelection } from "./selection/endpoint-selection"; import { ConnectionSelection } from "./selection/connection-selection"; import { Viewport, ViewportElement } from "./viewport"; import { Component } from './component/component'; import { Overlay } from './overlay/overlay'; import { LabelOverlay } from './overlay/label-overlay'; import { AbstractConnector } from './connector/abstract-connector'; import { PaintStyle, AnchorPlacement, AnchorSpec, EndpointSpec } from '@jsplumb/common'; import { SourceSelector, TargetSelector } from "./source-selector"; import { InternalEndpointOptions } from "./endpoint/endpoint-options"; export interface jsPlumbElement<E> { _jsPlumbGroup: UIGroup<E>; _jsPlumbParentGroup: UIGroup<E>; _jsPlumbProxies: Array<[Connection, number]>; _isJsPlumbGroup: boolean; parentNode: jsPlumbElement<E>; } export declare type ElementSelectionSpecifier<E> = E | Array<E> | '*'; export declare type SelectionList = '*' | Array<string>; export interface AbstractSelectOptions<E> { scope?: SelectionList; source?: ElementSelectionSpecifier<E>; target?: ElementSelectionSpecifier<E>; } export interface SelectOptions<E> extends AbstractSelectOptions<E> { connections?: Array<Connection>; } export interface SelectEndpointOptions<E> extends AbstractSelectOptions<E> { element?: ElementSelectionSpecifier<E>; } /** * Optional parameters to the `DeleteConnection` method. */ export declare type DeleteConnectionOptions = { /** * if true, force deletion even if the connection tries to cancel the deletion. */ force?: boolean; /** * If false, an event won't be fired. Otherwise a `connection:detach` event will be fired. */ fireEvent?: boolean; /** * Optional original event that resulted in the connection being deleted. */ originalEvent?: Event; /** * internally when a connection is deleted, it may be because the endpoint it was on is being deleted. * in that case we want to ignore that endpoint. */ endpointToIgnore?: Endpoint; }; export declare type ManagedElement<E> = { el: jsPlumbElement<E>; viewportElement?: ViewportElement<E>; endpoints?: Array<Endpoint>; connections?: Array<Connection>; rotation?: number; group?: string; }; export declare abstract class JsPlumbInstance<T extends { E: unknown; } = any> extends EventGenerator { readonly _instanceIndex: number; defaults: JsPlumbDefaults<T["E"]>; private _initialDefaults; isConnectionBeingDragged: boolean; currentlyDragging: boolean; hoverSuspended: boolean; _suspendDrawing: boolean; _suspendedAt: string; connectorClass: string; connectorOutlineClass: string; connectedClass: string; endpointClass: string; endpointConnectedClass: string; endpointFullClass: string; endpointDropAllowedClass: string; endpointDropForbiddenClass: string; endpointAnchorClassPrefix: string; overlayClass: string; readonly connections: Array<Connection>; endpointsByElement: Dictionary<Array<Endpoint>>; private readonly endpointsByUUID; sourceSelectors: Array<SourceSelector>; targetSelectors: Array<TargetSelector>; allowNestedGroups: boolean; private _curIdStamp; readonly viewport: Viewport<T>; readonly router: Router<T, any>; readonly groupManager: GroupManager<T["E"]>; private _connectionTypes; private _endpointTypes; private _container; protected _managedElements: Dictionary<ManagedElement<T["E"]>>; private DEFAULT_SCOPE; readonly defaultScope: string; private _zoom; readonly currentZoom: number; constructor(_instanceIndex: number, defaults?: JsPlumbDefaults<T["E"]>); getContainer(): any; setZoom(z: number, repaintEverything?: boolean): boolean; _idstamp(): string; checkCondition<RetVal>(conditionName: string, args?: any): RetVal; getId(element: T["E"], uuid?: string): string; getConnections(options?: SelectOptions<T["E"]>, flat?: boolean): Dictionary<Connection> | Array<Connection>; select(params?: SelectOptions<T["E"]>): ConnectionSelection; selectEndpoints(params?: SelectEndpointOptions<T["E"]>): EndpointSelection; setContainer(c: T["E"]): void; private _set; /** * Change the source of the given connection to be the given endpoint or element. * @param connection * @param el */ setSource(connection: Connection, el: T["E"] | Endpoint): void; /** * Change the target of the given connection to be the given endpoint or element. * @param connection * @param el */ setTarget(connection: Connection, el: T["E"] | Endpoint): void; /** * Returns whether or not hover is currently suspended. */ isHoverSuspended(): boolean; /** * Sets whether or not drawing is suspended. * @param val - True to suspend, false to enable. * @param repaintAfterwards - If true, repaint everything afterwards. */ setSuspendDrawing(val?: boolean, repaintAfterwards?: boolean): boolean; getSuspendedAt(): string; /** * Suspend drawing, run the given function, and then re-enable drawing, optionally repainting everything. * @param fn - Function to run while drawing is suspended. * @param doNotRepaintAfterwards - Whether or not to repaint everything after drawing is re-enabled. */ batch(fn: Function, doNotRepaintAfterwards?: boolean): void; /** * Execute the given function for each of the given elements. * @param spec - An Element, or an element id, or an array of elements/element ids. * @param fn - The function to run on each element. */ each(spec: T["E"] | Array<T["E"]>, fn: (e: T["E"]) => any): JsPlumbInstance; /** * Update the cached offset information for some element. * @param params * @returns an UpdateOffsetResult containing the offset information for the given element. */ updateOffset(params?: UpdateOffsetOptions): ViewportElement<T["E"]>; /** * Delete the given connection. * @param connection - Connection to delete. * @param params - Optional extra parameters. */ deleteConnection(connection: Connection, params?: DeleteConnectionOptions): boolean; deleteEveryConnection(params?: DeleteConnectionOptions): number; /** * Delete all connections attached to the given element. * @param el * @param params */ deleteConnectionsForElement(el: T["E"], params?: DeleteConnectionOptions): JsPlumbInstance; private fireDetachEvent; fireMoveEvent(params?: ConnectionMovedParams, evt?: Event): void; /** * Manage a group of elements. * @param elements - Array-like object of strings or elements (can be an Array or a NodeList), or a CSS selector (which is applied with the instance's * container element as its context) * @param recalc - Maybe recalculate offsets for the element also. */ manageAll(elements: ArrayLike<T["E"]> | string, recalc?: boolean): void; /** * Manage an element. Adds the element to the viewport and sets up tracking for endpoints/connections for the element, as well as enabling dragging for the * element. This method is called internally by various methods of the jsPlumb instance, such as `connect`, `addEndpoint`, `makeSource` and `makeTarget`, * so if you use those methods to setup your UI then you may not need to call this. However, if you use the `addSourceSelector` and `addTargetSelector` methods * to configure your UI then you will need to register elements using this method, or they will not be draggable. * @param element - Element to manage. This method does not accept a DOM element ID as argument. If you wish to manage elements via their DOM element ID, * you should use `manageAll` and pass in an appropriate CSS selector that represents your element, eg `#myElementId`. * @param internalId - Optional ID for jsPlumb to use internally. If this is not supplied, one will be created. * @param recalc - Maybe recalculate offsets for the element also. It is not recommended that clients of the API use this parameter; it's used in * certain scenarios internally */ manage(element: T["E"], internalId?: string, _recalc?: boolean): ManagedElement<T["E"]>; /** * Gets the element with the given ID from the list managed elements, null if not currently managed. * @param id */ getManagedElement(id: string): T["E"]; /** * Stops managing the given element. * @param el - Element, or ID of the element to stop managing. * @param removeElement - If true, also remove the element from the renderer. */ unmanage(el: T["E"], removeElement?: boolean): void; /** * Sets rotation for the element to the given number of degrees (not radians). A value of null is treated as a * rotation of 0 degrees. * @param element - Element to rotate * @param rotation - Amount to totate * @param _doNotRepaint - For internal use. */ rotate(element: T["E"], rotation: number, _doNotRepaint?: boolean): RedrawResult; /** * Gets the current rotation for the element with the given ID. This method exists for internal use. * @param elementId - Internal ID of the element for which to retrieve rotation. * @internal */ _getRotation(elementId: string): number; /** * Returns a list of rotation transformations that apply to the given element. An element may have rotation applied * directly to it, and/or it may be within a group, which may itself be rotated, and that group may be inside a group * which is also rotated, etc. It's rotated turtles all the way down, or at least it could be. This method is intended * for internal use only. * @param elementId * @internal */ _getRotations(elementId: string): Rotations; /** * Applies the given set of Rotations to the given point, and returns a new PointXY. For internal use. * @param point - Point to rotate * @param rotations - Rotations to apply. * @internal */ _applyRotations(point: [number, number, number, number], rotations: Rotations): RotatedPointXY; /** * Applies the given set of Rotations to the given point, and returns a new PointXY. For internal use. * @param point - Point to rotate * @param rotations - Rotations to apply. * @internal */ _applyRotationsXY(point: PointXY, rotations: Rotations): PointXY; /** * Internal method to create an Endpoint from the given options, perhaps with the given id. Do not use this method * as a consumer of the API. If you wish to add an Endpoint to some element, use `addEndpoint` instead. * @param params - Options for the Endpoint. * @internal */ _internal_newEndpoint(params: InternalEndpointOptions<T["E"]>): Endpoint; /** * For internal use. For the given inputs, derive an appropriate anchor and endpoint definition. * @param type * @param dontPrependDefault * @internal */ _deriveEndpointAndAnchorSpec(type: string, dontPrependDefault?: boolean): { endpoints: [EndpointSpec, EndpointSpec]; anchors: [AnchorSpec, AnchorSpec]; }; /** * Updates position/size information for the given element and redraws its Endpoints and their Connections. Use this method when you've * made a change to some element that may have caused the element to change its position or size and you want to ensure the connections are * in the right place. * @param el - Element to revalidate. * @param timestamp - Optional, used internally to avoid recomputing position/size information if it has already been computed. */ revalidate(el: T["E"], timestamp?: string): RedrawResult; /** * Repaint every connection and endpoint in the instance. */ repaintEverything(): JsPlumbInstance; /** * Sets the position of the given element to be [x,y]. * @param el - Element to set the position for * @param x - Position in X axis * @param y - Position in Y axis * @returns The result of the redraw operation that follows the update of the viewport. */ setElementPosition(el: T["E"], x: number, y: number): RedrawResult; /** * Repaints all connections and endpoints associated with the given element, _without recomputing the element * size and position_. If you want to first recompute element size and position you should call `revalidate(el)` instead, * @param el - Element to repaint. * @param timestamp - Optional parameter used internally to avoid recalculating offsets multiple times in one paint. * @param offsetsWereJustCalculated - If true, we don't recalculate the offsets of child elements of the element we're repainting. */ repaint(el: T["E"], timestamp?: string, offsetsWereJustCalculated?: boolean): RedrawResult; /** * @internal * @param endpoint */ private unregisterEndpoint; /** * Potentially delete the endpoint from the instance, depending on the endpoint's internal state. Not for external use. * @param endpoint * @internal */ _maybePruneEndpoint(endpoint: Endpoint): boolean; /** * Delete the given endpoint. * @param object - Either an Endpoint, or the UUID of an Endpoint. */ deleteEndpoint(object: string | Endpoint): JsPlumbInstance; /** * Add an Endpoint to the given element. * @param el - Element to add the endpoint to. * @param params * @param referenceParams */ addEndpoint(el: T["E"], params?: EndpointOptions<T["E"]>, referenceParams?: EndpointOptions<T["E"]>): Endpoint; /** * Add a set of Endpoints to an element * @param el - Element to add the Endpoints to. * @param endpoints - Array of endpoint options. * @param referenceParams */ addEndpoints(el: T["E"], endpoints: Array<EndpointOptions<T["E"]>>, referenceParams?: EndpointOptions<T["E"]>): Array<Endpoint>; /** * Clears all endpoints and connections from the instance of jsplumb. Does not also clear out event listeners, selectors, or * connection/endpoint types - for that, use `destroy()`. */ reset(): void; /** * Clears the instance and unbinds any listeners on the instance. After you call this method you cannot use this * instance of jsPlumb again. */ destroy(): void; /** * Gets all registered endpoints for the given element. * @param el */ getEndpoints(el: T["E"]): Array<Endpoint>; /** * Retrieve an endpoint by its UUID. * @param uuid */ getEndpoint(uuid: string): Endpoint; /** * Set an endpoint's uuid, updating the internal map * @param endpoint * @param uuid */ setEndpointUuid(endpoint: Endpoint, uuid: string): void; /** * Connect one element to another. * @param params - At the very least you need to supply a source and target. * @param referenceParams - Optional extra parameters. This can be useful when you're creating multiple connections that have some things in common. */ connect(params: ConnectParams<T["E"]>, referenceParams?: ConnectParams<T["E"]>): Connection; /** * @param params * @param referenceParams * @internal */ private _prepareConnectionParams; /** * Creates and registers a new connection. For internal use only. Use `connect` to create Connections. * @param params * @internal */ _newConnection(params: ConnectionOptions<T["E"]>): Connection; /** * Adds the connection to the backing model, fires an event if necessary and then redraws. This is a package-private method, not intended to be * called by external code. * @param jpc - Connection to finalise * @param params * @param originalEvent - Optional original event that resulted in the creation of this connection. * @internal */ _finaliseConnection(jpc: Connection, params?: any, originalEvent?: Event): void; /** * Remove every endpoint registered to the given element. * @param el - Element to remove endpoints for. * @param recurse - If true, also remove endpoints for elements that are descendants of this element. */ removeAllEndpoints(el: T["E"], recurse?: boolean): JsPlumbInstance; protected _createSourceDefinition(params?: BehaviouralTypeDescriptor, referenceParams?: BehaviouralTypeDescriptor): SourceDefinition; /** * Registers a selector for connection drag on the instance. This is a newer version of the `makeSource` functionality * that has been in jsPlumb since the early days. With this approach, rather than calling `makeSource` on every element, you * can register a CSS selector on the instance that identifies something that is common to your elements. This will only respond to * mouse events on elements that are managed by the instance. * @param selector - CSS3 selector identifying child element(s) of some managed element that should act as a connection source. * @param params - Options for the source: connector type, behaviour, etc. * @param exclude - If true, the selector defines an 'exclusion': anything _except_ elements that match this. */ addSourceSelector(selector: string, params?: BehaviouralTypeDescriptor, exclude?: boolean): SourceSelector; /** * Unregister the given source selector. * @param selector */ removeSourceSelector(selector: SourceSelector): void; /** * Unregister the given target selector. * @param selector */ removeTargetSelector(selector: TargetSelector): void; /** * Registers a selector for connection drag on the instance. This is a newer version of the `makeTarget` functionality * that has been in jsPlumb since the early days. With this approach, rather than calling `makeTarget` on every element, you * can register a CSS selector on the instance that identifies something that is common to your elements. This will only respond to * mouse events on elements that are managed by the instance. * @param selector - CSS3 selector identifying child element(s) of some managed element that should act as a connection target. * @param params - Options for the target * @param exclude - If true, the selector defines an 'exclusion': anything _except_ elements that match this. */ addTargetSelector(selector: string, params?: BehaviouralTypeDescriptor, exclude?: boolean): TargetSelector; private _createTargetDefinition; show(el: T["E"], changeEndpoints?: boolean): JsPlumbInstance; hide(el: T["E"], changeEndpoints?: boolean): JsPlumbInstance; private _setVisible; /** * private method to do the business of toggling hiding/showing. */ toggleVisible(el: T["E"], changeEndpoints?: boolean): void; private _operation; registerConnectionType(id: string, type: ConnectionTypeDescriptor): void; registerConnectionTypes(types: Dictionary<ConnectionTypeDescriptor>): void; registerEndpointType(id: string, type: EndpointTypeDescriptor): void; registerEndpointTypes(types: Dictionary<EndpointTypeDescriptor>): void; getType(id: string, typeDescriptor: string): TypeDescriptor; getConnectionType(id: string): ConnectionTypeDescriptor; getEndpointType(id: string): EndpointTypeDescriptor; importDefaults(d: JsPlumbDefaults<T["E"]>): JsPlumbInstance; restoreDefaults(): JsPlumbInstance; getManagedElements(): Dictionary<ManagedElement<T["E"]>>; proxyConnection(connection: Connection, index: number, proxyEl: T["E"], endpointGenerator: (c: Connection, idx: number) => EndpointSpec, anchorGenerator: (c: Connection, idx: number) => AnchorSpec): void; unproxyConnection(connection: Connection, index: number): void; sourceOrTargetChanged(originalId: string, newId: string, connection: Connection, newElement: T["E"], index: number): void; abstract setGroupVisible(group: UIGroup, state: boolean): void; getGroup(groupId: string): UIGroup<T["E"]>; getGroupFor(el: T["E"]): UIGroup<T["E"]>; addGroup(params: AddGroupOptions<T["E"]>): UIGroup<T["E"]>; addToGroup(group: string | UIGroup<T["E"]>, ...el: Array<T["E"]>): void; collapseGroup(group: string | UIGroup<T["E"]>): void; expandGroup(group: string | UIGroup<T["E"]>): void; toggleGroup(group: string | UIGroup<T["E"]>): void; removeGroup(group: string | UIGroup<T["E"]>, deleteMembers?: boolean, manipulateView?: boolean, doNotFireEvent?: boolean): Dictionary<PointXY>; removeAllGroups(deleteMembers?: boolean, manipulateView?: boolean): void; removeFromGroup(group: string | UIGroup<T["E"]>, el: T["E"], doNotFireEvent?: boolean): void; paintEndpoint(endpoint: Endpoint, params: { timestamp?: string; offset?: ViewportElement<T["E"]>; recalc?: boolean; elementWithPrecedence?: string; connectorPaintStyle?: PaintStyle; anchorLoc?: AnchorPlacement; }): void; paintConnection(connection: Connection, params?: { timestamp?: string; }): void; refreshEndpoint(endpoint: Endpoint): void; makeConnector(connection: Connection<T["E"]>, name: string, args: any): AbstractConnector; /** * For some given element, find any other elements we want to draw whenever that element * is being drawn. for groups, for example, this means any child elements of the group. For an element that has child * elements that are also managed, it means those child elements. * @param el * @internal */ abstract _getAssociatedElements(el: T["E"]): Array<T["E"]>; abstract _removeElement(el: T["E"]): void; abstract _appendElement(el: T["E"], parent: T["E"]): void; abstract removeClass(el: T["E"] | ArrayLike<T["E"]>, clazz: string): void; abstract addClass(el: T["E"] | ArrayLike<T["E"]>, clazz: string): void; abstract toggleClass(el: T["E"] | ArrayLike<T["E"]>, clazz: string): void; abstract getClass(el: T["E"]): string; abstract hasClass(el: T["E"], clazz: string): boolean; abstract setAttribute(el: T["E"], name: string, value: string): void; abstract getAttribute(el: T["E"], name: string): string; abstract setAttributes(el: T["E"], atts: Dictionary<string>): void; abstract removeAttribute(el: T["E"], attName: string): void; abstract getSelector(ctx: string | T["E"], spec?: string): ArrayLike<T["E"]>; abstract getStyle(el: T["E"], prop: string): any; abstract getSize(el: T["E"]): Size; abstract getOffset(el: T["E"]): PointXY; abstract getOffsetRelativeToRoot(el: T["E"] | string): PointXY; abstract getGroupContentArea(group: UIGroup): T["E"]; abstract setPosition(el: T["E"], p: PointXY): void; abstract on(el: Document | T["E"] | ArrayLike<T["E"]>, event: string, callbackOrSelector: Function | string, callback?: Function): void; abstract off(el: Document | T["E"] | ArrayLike<T["E"]>, event: string, callback: Function): void; abstract trigger(el: Document | T["E"], event: string, originalEvent?: Event, payload?: any, detail?: number): void; getPathData(connector: AbstractConnector): any; abstract paintOverlay(o: Overlay, params: any, extents: any): void; abstract addOverlayClass(o: Overlay, clazz: string): void; abstract removeOverlayClass(o: Overlay, clazz: string): void; abstract setOverlayVisible(o: Overlay, visible: boolean): void; abstract destroyOverlay(o: Overlay): void; abstract updateLabel(o: LabelOverlay): void; abstract drawOverlay(overlay: Overlay, component: any, paintStyle: PaintStyle, absolutePosition?: PointXY): any; abstract reattachOverlay(o: Overlay, c: Component): void; abstract setOverlayHover(o: Overlay, hover: boolean): void; abstract setHover(component: Component, hover: boolean): void; abstract paintConnector(connector: AbstractConnector, paintStyle: PaintStyle, extents?: Extents): void; abstract destroyConnector(connection: Connection, force?: boolean): void; abstract setConnectorHover(connector: AbstractConnector, h: boolean, doNotCascade?: boolean): void; abstract addConnectorClass(connector: AbstractConnector, clazz: string): void; abstract removeConnectorClass(connector: AbstractConnector, clazz: string): void; abstract getConnectorClass(connector: AbstractConnector): string; abstract setConnectorVisible(connector: AbstractConnector, v: boolean): void; abstract applyConnectorType(connector: AbstractConnector, t: TypeDescriptor): void; abstract applyEndpointType(ep: Endpoint<T>, t: TypeDescriptor): void; abstract setEndpointVisible(ep: Endpoint<T>, v: boolean): void; abstract destroyEndpoint(ep: Endpoint<T>): void; abstract renderEndpoint(ep: Endpoint<T>, paintStyle: PaintStyle): void; abstract addEndpointClass(ep: Endpoint<T>, c: string): void; abstract removeEndpointClass(ep: Endpoint<T>, c: string): void; abstract getEndpointClass(ep: Endpoint<T>): string; abstract setEndpointHover(endpoint: Endpoint<T>, h: boolean, doNotCascade?: boolean): void; } //# sourceMappingURL=core.d.ts.map
the_stack
require("dotenv-safe").config(); import bodyParser from "body-parser"; import cors from "cors"; import express from "express"; import rateLimit from "express-rate-limit"; import helmet from "helmet"; import createError from "http-errors"; import isUUID from "is-uuid"; import jwt from "jsonwebtoken"; import passport from "passport"; import { Strategy as GitHubStrategy } from "passport-github"; import { join } from "path"; import "reflect-metadata"; import { createConnection, getConnection } from "typeorm"; import { __prod__, gifUploadLimit } from "./constants"; import { createTokens } from "./createTokens"; import { Favorite } from "./entities/Favorite"; import { GifStory } from "./entities/GifStory"; import { Like } from "./entities/Like"; import { TextStory } from "./entities/TextStory"; import { User } from "./entities/User"; import { isAuth } from "./isAuth"; import { Octokit } from "@octokit/rest"; import { fetchGifStories, fetchStories, fetchUserGifStories, fetchUserStories } from "./queryBuilder"; import { Bucket, GetSignedUrlConfig, Storage } from "@google-cloud/storage"; import path from "path"; const octokit = new Octokit(); const upgradeMessage = "Upgrade the VSCode Stories extension, I fixed it and changed the API."; const main = async () => { const credentials = { host: process.env.SOCKET_PATH ? process.env.SOCKET_PATH : process.env.DB_HOST, port: Number(process.env.DB_PORT), username: process.env.DB_USER, password: process.env.DB_PASSWORD, }; console.log("about to connect to db, host: ", credentials.host); const conn = await createConnection({ type: "postgres", database: "stories", entities: [join(__dirname, "./entities/*")], migrations: [join(__dirname, "./migrations/*")], // synchronize: !__prod__, logging: !__prod__, ...credentials, }); console.log("connected, running migrations now"); await conn.runMigrations(); console.log("migrations ran"); // google cloud const storage = new Storage({ keyFilename: path.join(__dirname, `../${process.env.STORAGE_CRED_FILE}`), projectId: process.env.STORAGE_PROJ_ID, }); const gifStoriesBucket = storage.bucket(`${process.env.STORAGE_BUCKET}`); // https://cloud.google.com/storage/docs/xml-api/reference-headers#xgoogcontentlengthrange async function configureBucketCors() { await gifStoriesBucket.setCorsConfiguration([ { maxAgeSeconds: 3600, method: ["PUT", "GET"], origin: [`${process.env.ORIGIN_URL}`], responseHeader: ["x-goog-content-length-range"], }, ]); } configureBucketCors(); // action.types read, write, delete const gcsSignedUrl = async ( bucket: Bucket, filename: string, minutesToExpiration: number, action: GetSignedUrlConfig["action"] ) => { const options: GetSignedUrlConfig = { version: "v4", action: action, expires: Date.now() + minutesToExpiration * 60 * 1000, extensionHeaders: { "x-goog-content-length-range": `1,${gifUploadLimit}`, }, }; const [url] = await bucket.file(filename).getSignedUrl(options); return url; }; passport.use( new GitHubStrategy( { scope: "user:follow", clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: `${process.env.SERVER_URL}/auth/github/callback`, }, async (githubAccessToken, _, profile, cb) => { if (profile.id === "32990164") { cb(new Error("you are banned")); return; } try { let user = await User.findOne({ githubId: profile.id }); const data = { githubAccessToken, displayName: profile.displayName, githubId: profile.id, photoUrl: profile.photos?.[0].value || (profile._json as any).avatar_url || "", other: profile._json, profileUrl: profile.profileUrl, username: profile.username, }; if (user) { await User.update(user.id, data); } else { user = await User.create(data).save(); } cb(undefined, createTokens(user)); } catch (err) { console.log(err); cb(new Error("internal error")); } } ) ); passport.serializeUser((user: any, done) => { done(null, user.accessToken); }); const app = express(); app.set("trust proxy", 1); app.use(helmet()); app.use(cors({ origin: "*", maxAge: 86400 })); app.use(bodyParser.json()); app.use(passport.initialize()); app.get("/auth/github", passport.authenticate("github", { session: false })); app.get( "/auth/github/callback", passport.authenticate("github"), (req: any, res) => { if (!req.user.accessToken || !req.user.refreshToken) { res.send(`something went wrong`); return; } res.redirect( `http://localhost:54321/callback/${req.user.accessToken}/${req.user.refreshToken}` ); } ); app.get("/user/username", isAuth(), async (req: any, res) => { res.send( await getConnection().query( `select u."username" from "user" u where u."id" = '${req.userId}';` ) ); }); app.get("/stories/user/:cursor?", isAuth(), async (req: any, res) => { let cursor = 0; if (req.params.cursor) { const nCursor = parseInt(req.params.cursor); if (!Number.isNaN(nCursor)) { cursor = nCursor; } } const limit = 5; const stories = await fetchUserStories(limit, cursor, req.userId); const gifStories = await fetchUserGifStories(limit, cursor, req.userId); const data = { stories: stories.slice(0, limit).concat(gifStories.slice(0, limit)), hasMore: (stories.length === limit + 1) ? true : gifStories.length === limit + 1, }; res.json(data); }); app.get( "/stories/friends/hot/:cursor?/:friendIds?", isAuth(), async (req: any, res) => { let friendIds: Array<string> = req.params.friendIds ? req.params.friendIds.split(",") : []; if (friendIds.length === 0) { let user = await User.findOne({ id: req.userId }); // Get the user objects the user (username) is following let result = await octokit.request("GET /users{/username}/following", { username: user?.username, headers: { accept: `application/vnd.github.v3+json`, authorization: `token ${user?.githubAccessToken}`, }, }); // Take the data array from the result, which is basically all the users in an array const { data } = result; if (data.length === 0) { const d = { stories: [], friendIds: [], hasMore: false, }; res.json(d); return; } // Create a string of WHERE conditions let add = ``; for (var i = 0; i < data.length; i++) { if (i != 0) { add += ` OR `; } add += `u."githubId" LIKE '${data[i]?.id}'`; } // Create the query and add the WHERE conditions // Only return the ids of the users let query = `select u."id" from "user" u where ${add};`; // Execute query const arr = await getConnection().query(query); //let friendIds: Array<string> = []; // Loop through all the id objects and add them to a list, // in order to have a clear json structure for the frontend arr.forEach((userId: { id: any }) => { friendIds.push(userId?.id); }); } if (friendIds.length === 0) { const d = { stories: [], friendIds: [], hasMore: false, }; res.json(d); return; } // Perform request to get friends stories let cursor = 0; if (req.params.cursor) { const nCursor = parseInt(req.params.cursor); if (!Number.isNaN(nCursor)) { cursor = nCursor; } } const limit = 11; const stories = await fetchStories(limit, cursor, friendIds); const gifStories = await fetchGifStories(limit, cursor, friendIds); const data = { stories: stories.slice(0, limit).concat(gifStories.slice(0, limit)), friendIds: friendIds, hasMore: (stories.length === limit + 1) ? true : gifStories.length === limit + 1, }; res.json(data); } ); if (process.env.LATENCY_ON === "true") { app.use(function (_req, _res, next) { setTimeout(next, Number(process.env.LATENCY_MS)); }); } app.get("/story/likes/:id", async (_req, _res, next) => { return next(createError(400, upgradeMessage)); }); app.get("/stories/hot/:cursor?", async (_, __, next) => { return next(createError(400, upgradeMessage)); }); app.get("/gif-story/:id", isAuth(false), async (req: any, res) => { const { id } = req.params; if (!id || !isUUID.v4(id)) { res.json({ story: null }); } else { const replacements = [id]; if (req.userId) { replacements.push(req.userId); } res.json({ story: ( await getConnection().query( ` select ts.*, l."gifStoryId" is not null "hasLiked" from gif_story ts left join "favorite" l on l."gifStoryId" = ts.id ${ req.userId ? `and l."userId" = $2` : "" } where id = $1 `, replacements ) )[0], }); } }); app.get("/text-story/:id", isAuth(false), async (req: any, res) => { const { id } = req.params; if (!id || !isUUID.v4(id)) { res.json({ story: null }); } else { const replacements = [id]; if (req.userId) { replacements.push(req.userId); } res.json({ story: ( await getConnection().query( ` select ts.*, l."textStoryId" is not null "hasLiked" from text_story ts left join "like" l on l."textStoryId" = ts.id ${ req.userId ? `and l."userId" = $2` : "" } where id = $1 `, replacements ) )[0], }); } }); app.get("/is-friend/:username", isAuth(), async (req: any, res) => { const { username } = req.params; let found: boolean = false; try { let user = await User.findOne({ id: req.userId }); let result = await octokit.request("GET /users{/username}/following", { username: user?.username, headers: { accept: `application/vnd.github.v3+json`, authorization: `token ${user?.githubAccessToken}`, }, }); const { data } = result; data.forEach((el: any) => { if (el.login === username) { found = true; } }); } catch (err) { console.log(err); } if (found) { res.send({ ok: true }); } else { res.send({ ok: false }); } }); app.get("/gif-stories/hot/:cursor?", async (req, res) => { let cursor = 0; if (req.params.cursor) { const nCursor = parseInt(req.params.cursor); if (!Number.isNaN(nCursor)) { cursor = nCursor; } } const limit = 21; const stories = await fetchGifStories(limit, cursor); const data = { stories: stories.slice(0, limit), hasMore: stories.length === limit + 1, }; res.json(data); }); app.get( "/text-stories/hot/:cursor?", isAuth(false), async (req: any, res) => { let cursor = 0; if (req.params.cursor) { const nCursor = parseInt(req.params.cursor); if (!Number.isNaN(nCursor)) { cursor = nCursor; } } const limit = 21; const stories = await fetchStories(limit, cursor); const data = { stories: stories.slice(0, limit), hasMore: stories.length === limit + 1, }; res.json(data); } ); app.get("/storage/write/:fileId", isAuth(), async (req: any, res) => { const fileId = req.params.fileId; try { const response = await gcsSignedUrl(gifStoriesBucket, fileId, 5, "write"); res.json(response).status(200); } catch (error) { res.send(error.message).status(404); } }); app.get("/storage/read/:fileId", isAuth(), async (req: any, res) => { const fileId = req.params.fileId; try { const response = await gcsSignedUrl(gifStoriesBucket, fileId, 5, "read"); res.json(response).status(200); } catch (error) { res.send(error.message).status(404); } }); app.post("/delete-gif-story/:id/:mediaId", isAuth(), async (req: any, res) => { const { id, mediaId } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } const criteria: Partial<GifStory> = { id }; if (req.userId !== "dac7eb0f-808b-4842-b193-5d68cc082609") { criteria.creatorId = req.userId; } await GifStory.delete(criteria); try { await gifStoriesBucket.file(`${mediaId}.gif`).delete(); } catch (error) { res.send(error.message).status(404); } res.send({ ok: true }); }); app.post("/delete-text-story/:id", isAuth(), async (req: any, res) => { const { id } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } const criteria: Partial<TextStory> = { id }; if (req.userId !== "dac7eb0f-808b-4842-b193-5d68cc082609") { criteria.creatorId = req.userId; } await TextStory.delete(criteria); res.send({ ok: true }); }); app.post( "/remove-friend/:username", isAuth(), async (req: any, res, next) => { const { username } = req.params; try { let user = await User.findOne({ id: req.userId }); await octokit.request(`DELETE /user/following{/username}`, { username: username, headers: { accept: `application/vnd.github.v3+json`, authorization: `token ${user?.githubAccessToken}`, }, }); } catch (err) { console.log(err); if (err.status === 404) { return next( createError( 404, "You probably need to reauthenticate in order to follow people" ) ); } return next(createError(400, "There's no such user")); } res.send({ ok: true }); } ); app.post("/add-friend/:username", isAuth(), async (req: any, res, next) => { const { username } = req.params; try { let user = await User.findOne({ id: req.userId }); await octokit.request(`PUT /user/following{/username}`, { username: username, headers: { accept: `application/vnd.github.v3+json`, authorization: `token ${user?.githubAccessToken}`, }, }); } catch (err) { console.log(err); if (err.status === 404) { return next( createError( 404, "You probably need to reauthenticate in order to follow people" ) ); } return next(createError(400, "There's no such user")); } res.send({ ok: true }); }); app.post("/unlike-text-story/:id", isAuth(), async (req: any, res, next) => { const { id } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } try { const currentLike = await Like.find({ textStoryId: id, userId: req.userId, }); if (currentLike.length !== 1) return; const { affected } = await Like.delete({ textStoryId: id, userId: req.userId, }); if (affected) { await TextStory.update(id, { numLikes: () => '"numLikes" - 1' }); } } catch (err) { console.log(err); return next(createError(400, "You probably already unliked this")); } res.send({ ok: true }); }); app.post("/unlike-gif-story/:id", isAuth(), async (req: any, res, next) => { const { id } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } try { const currentFavorite = await Favorite.find({ gifStoryId: id, userId: req.userId, }); if (currentFavorite.length !== 1) return; const { affected } = await Favorite.delete({ gifStoryId: id, userId: req.userId, }); if (affected) { await GifStory.update(id, { numLikes: () => '"numLikes" - 1' }); } } catch (err) { console.log(err); return next(createError(400, "You probably already unliked this")); } res.send({ ok: true }); }); app.post("/like-text-story/:id", isAuth(), async (req: any, res, next) => { const { id } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } try { const currentLike = await Like.find({ textStoryId: id, userId: req.userId, }); if (currentLike.length !== 0) return; await Like.insert({ textStoryId: id, userId: req.userId }); } catch (err) { console.log(err); return next(createError(400, "You probably already liked this")); } await TextStory.update(id, { numLikes: () => '"numLikes" + 1' }); res.send({ ok: true }); }); app.post("/like-gif-story/:id", isAuth(), async (req: any, res, next) => { const { id } = req.params; if (!isUUID.v4(id)) { res.send({ ok: false }); return; } try { const currentFavorite = await Favorite.find({ gifStoryId: id, userId: req.userId, }); if (currentFavorite.length !== 0) return; await Favorite.insert({ gifStoryId: id, userId: req.userId }); } catch (err) { console.log(err); return next(createError(400, "You probably already liked this")); } await GifStory.update(id, { numLikes: () => '"numLikes" + 1' }); res.send({ ok: true }); }); app.post("/like-story/:id/:username", async (_req, _res, next) => { return next(createError(400, upgradeMessage)); }); const maxTextLength = 20000; app.post( "/new-text-story", isAuth(), rateLimit({ keyGenerator: (req: any) => req.userId, windowMs: 43200000, // 12 hours message: "Limit reached. You can only post 10 stories a day.", max: 10, headers: false, }), async (req, res) => { let { text, programmingLanguageId, filename, recordingSteps } = req.body; if (text.length > maxTextLength) { text = text.slice(0, maxTextLength); } if (programmingLanguageId.length > 40) { programmingLanguageId = null; } if (filename.length > 100) { filename = "untitled"; } const ts = await TextStory.create({ text, filename, recordingSteps, programmingLanguageId, creatorId: (req as any).userId, }).save(); const currentUser = await User.findOneOrFail((req as any).userId); res.send({ id: ts.id, creatorUsername: currentUser.username, creatorAvatarUrl: currentUser.photoUrl, flair: currentUser.flair, }); } ); app.post( "/new-gif-story", isAuth(), rateLimit({ keyGenerator: (req: any) => req.userId, windowMs: 43200000, // 12 hours message: "Limit reached. You can only post 10 stories a day.", max: 10, headers: false, }), async (req, res) => { //add next here for error let { programmingLanguageId, filename, mediaId } = req.body; if (programmingLanguageId.length > 40) { programmingLanguageId = null; } // Flagged was coming from vision ML which we don't have on serverless // We can update flag if user is reported through ban system let flagged = null; // @todo if flagged ping me on slack const gs = await GifStory.create({ mediaId, filename, flagged, programmingLanguageId, creatorId: (req as any).userId, }).save(); const currentUser = await User.findOneOrFail((req as any).userId); res.send({ id: gs.id, mediaId: mediaId, creatorAvatarUrl: currentUser.photoUrl, creatorUsername: currentUser.username, flair: currentUser.flair, }); } ); app.post("/new-story", async (_req, _res, next) => { return next(createError(400, upgradeMessage)); }); app.post("/update-flair", isAuth(), async (req, res) => { if ( !req.body.flair || typeof req.body.flair !== "string" || req.body.flair.length > 40 ) { res.json({ ok: false }); return; } await User.update({ id: (req as any).userId }, { flair: req.body.flair }); res.json({ ok: true }); }); app.use((err: any, _: any, res: any, next: any) => { if (res.headersSent) { return next(err); } if (err.statusCode) { res.status(err.statusCode).send(err.message); } else { console.log(err); res.status(500).send("internal server error"); } }); app.listen(process.env.PORT || 8080, () => { console.log("server started"); }); }; main();
the_stack
import { BlocksoftBlockchainTypes } from '../BlocksoftBlockchainTypes' import BlocksoftCryptoLog from '../../common/BlocksoftCryptoLog' import BlocksoftUtils from '../../common/BlocksoftUtils' import DogeNetworkPrices from './basic/DogeNetworkPrices' import DogeUnspentsProvider from './providers/DogeUnspentsProvider' import DogeTxInputsOutputs from './tx/DogeTxInputsOutputs' import DogeTxBuilder from './tx/DogeTxBuilder' import DogeSendProvider from './providers/DogeSendProvider' import DogeRawDS from './stores/DogeRawDS' import { DogeLogs } from './basic/DogeLogs' import MarketingEvent from '../../../app/services/Marketing/MarketingEvent' import config from '../../../app/config/config' import { err } from 'react-native-svg/lib/typescript/xml' import { sublocale } from '../../../app/services/i18n' import settingsActions from '../../../app/appstores/Stores/Settings/SettingsActions' import BlocksoftExternalSettings from '@crypto/common/BlocksoftExternalSettings' const networksConstants = require('../../common/ext/networks-constants') export default class DogeTransferProcessor implements BlocksoftBlockchainTypes.TransferProcessor { _trezorServerCode = 'DOGE_TREZOR_SERVER' _builderSettings: BlocksoftBlockchainTypes.BuilderSettings = { minOutputDustReadable: 0.001, minChangeDustReadable: 0.5, feeMaxForByteSatoshi: 100000000, // for tx builder feeMaxAutoReadable2: 300, // for fee calc, feeMaxAutoReadable6: 150, // for fee calc feeMaxAutoReadable12: 100, // for fee calc changeTogether: true, minRbfStepSatoshi: 50, minSpeedUpMulti: 1.5, feeMinTotalReadable : 1 } _initedProviders: boolean = false _settings: BlocksoftBlockchainTypes.CurrencySettings _langPrefix: string // @ts-ignore networkPrices: BlocksoftBlockchainTypes.NetworkPrices // @ts-ignore unspentsProvider: BlocksoftBlockchainTypes.UnspentsProvider // @ts-ignore sendProvider: BlocksoftBlockchainTypes.SendProvider // @ts-ignore txPrepareInputsOutputs: BlocksoftBlockchainTypes.TxInputsOutputs // @ts-ignore txBuilder: BlocksoftBlockchainTypes.TxBuilder constructor(settings: BlocksoftBlockchainTypes.CurrencySettings) { this._settings = settings this._langPrefix = networksConstants[settings.network].langPrefix this.networkPrices = new DogeNetworkPrices() } _initProviders() { if (this._initedProviders) return false this.unspentsProvider = new DogeUnspentsProvider(this._settings, this._trezorServerCode) this.sendProvider = new DogeSendProvider(this._settings, this._trezorServerCode) this.txPrepareInputsOutputs = new DogeTxInputsOutputs(this._settings, this._builderSettings) this.txBuilder = new DogeTxBuilder(this._settings, this._builderSettings) this._initedProviders = true } needPrivateForFee(): boolean { return true } checkSendAllModal(data: { currencyCode: any }): boolean { return true } async getFeeRate(data: BlocksoftBlockchainTypes.TransferData, privateData: BlocksoftBlockchainTypes.TransferPrivateData, additionalData: BlocksoftBlockchainTypes.TransferAdditionalData = {}) : Promise<BlocksoftBlockchainTypes.FeeRateResult> { this._initProviders() let isStaticFee = this._settings.currencyCode === 'DOGE' && (typeof additionalData.isCustomFee === 'undefined' || !additionalData.isCustomFee) let feeStaticReadable if (isStaticFee) { feeStaticReadable = BlocksoftExternalSettings.getStatic('DOGE_STATIC') if (!feeStaticReadable['useStatic']) { isStaticFee = false } } let txRBF = false let transactionSpeedUp = false let transactionReplaceByFee = false let transactionRemoveByFee = false if (typeof data.transactionRemoveByFee !== 'undefined' && data.transactionRemoveByFee) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate remove started ' + data.addressFrom + ' => ' + data.amount) transactionRemoveByFee = data.transactionRemoveByFee txRBF = transactionRemoveByFee isStaticFee = false } else if (typeof data.transactionReplaceByFee !== 'undefined' && data.transactionReplaceByFee) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate resend started ' + data.addressFrom + ' => ' + data.amount) transactionReplaceByFee = data.transactionReplaceByFee txRBF = transactionReplaceByFee isStaticFee = false } else if (typeof data.transactionSpeedUp !== 'undefined' && data.transactionSpeedUp) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate speedup started ' + data.addressFrom + ' => ' + data.amount) transactionSpeedUp = data.transactionSpeedUp txRBF = transactionSpeedUp } else { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate started ' + data.addressFrom + ' => ' + data.amount) } if (txRBF) { const savedData = await DogeRawDS.getJson({ address: data.addressFrom, currencyCode: this._settings.currencyCode, transactionHash: txRBF }) // sometimes replaced in db or got from server if (savedData) { if (typeof data.transactionJson === 'undefined') { data.transactionJson = {} } for (const key in savedData) { // @ts-ignore data.transactionJson[key] = savedData[key] } } } let prices = {} let autocorrectFee = false if (typeof additionalData.feeForByte === 'undefined') { prices = typeof additionalData.prices !== 'undefined' ? additionalData.prices : await this.networkPrices.getNetworkPrices(this._settings.currencyCode) } else { // @ts-ignore prices.speed_blocks_12 = additionalData.feeForByte autocorrectFee = true } let unspents = [] if (transactionRemoveByFee) { if (typeof this.unspentsProvider.getTx === 'undefined') { throw new Error('No DogeTransferProcessor unspentsProvider.getTx for transactionRemoveByFee') } unspents = await this.unspentsProvider.getTx(data.transactionRemoveByFee, data.addressFrom, [], data.walletHash) data.isTransferAll = true } else { unspents = typeof additionalData.unspents !== 'undefined' ? additionalData.unspents : await this.unspentsProvider.getUnspents(data.addressFrom) if (transactionReplaceByFee) { if (typeof this.unspentsProvider.getTx === 'undefined') { throw new Error('No DogeTransferProcessor unspentsProvider.getTx for transactionReplaceByFee') } unspents = await this.unspentsProvider.getTx(data.transactionReplaceByFee, data.addressFrom, unspents, data.walletHash) } } if (unspents.length > 1) { unspents.sort((a, b) => { return BlocksoftUtils.diff(b.value, a.value) * 1 }) // @ts-ignore BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate unspents sorted', unspents) } else { // @ts-ignore BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate unspents no need to sort', unspents) } const result: BlocksoftBlockchainTypes.FeeRateResult = { selectedFeeIndex: -1, fees: [] as BlocksoftBlockchainTypes.Fee[] } as BlocksoftBlockchainTypes.FeeRateResult const keys = ['speed_blocks_12', 'speed_blocks_6', 'speed_blocks_2'] const checkedPrices = {} let prevFeeForByte = 0 if (transactionSpeedUp) { autocorrectFee = true } if (isStaticFee && feeStaticReadable) { const newPrices = {} for (const key of keys) { if (typeof feeStaticReadable[key] === 'undefined') continue newPrices[key] = prices[key] } prices = newPrices } const stepSatoshi = transactionRemoveByFee ? this._builderSettings.minRbfStepSatoshi * 2 : this._builderSettings.minRbfStepSatoshi let pricesTotal = 0 for (const key of keys) { // @ts-ignore if (typeof prices[key] === 'undefined' || !prices[key]) continue pricesTotal++ // @ts-ignore let feeForByte = prices[key] if (typeof additionalData.feeForByte === 'undefined') { if (transactionReplaceByFee || transactionRemoveByFee) { if (typeof data.transactionJson !== 'undefined' && data.transactionJson !== null && typeof data.transactionJson.feeForByte !== 'undefined') { if (feeForByte * 1 < data.transactionJson.feeForByte * 1) { feeForByte = Math.ceil(data.transactionJson.feeForByte * 1 + stepSatoshi) } } else { feeForByte = Math.ceil(feeForByte * 1 + stepSatoshi) } if (feeForByte * 1 <= prevFeeForByte * 1) { feeForByte = Math.ceil(prevFeeForByte * 1 + stepSatoshi) } } else if (transactionSpeedUp) { feeForByte = Math.ceil(feeForByte * this._builderSettings.minSpeedUpMulti) if (feeForByte * 1 <= prevFeeForByte * 1) { feeForByte = Math.ceil(prevFeeForByte * 1.2) } } } // @ts-ignore checkedPrices[key] = feeForByte prevFeeForByte = feeForByte } let uniqueFees = {} let isError = false for (const key of keys) { // @ts-ignore if (typeof checkedPrices[key] === 'undefined' || !checkedPrices[key]) continue // @ts-ignore const feeForByte = checkedPrices[key] let preparedInputsOutputs const subtitle = 'getFeeRate_' + key + ' ' + feeForByte let blocks = '2' let autoFeeLimitReadable = this._builderSettings.feeMaxAutoReadable2 if (key === 'speed_blocks_6') { blocks = '6' autoFeeLimitReadable = this._builderSettings.feeMaxAutoReadable6 } else if (key === 'speed_blocks_12') { blocks = '12' autoFeeLimitReadable = this._builderSettings.feeMaxAutoReadable12 } let logInputsOutputs, blockchainData, txSize, actualFeeForByte, actualFeeForByteNotRounded try { if (isStaticFee) { preparedInputsOutputs = await this.txPrepareInputsOutputs.getInputsOutputs(data, unspents, { feeForByte : 'none', feeForAll : BlocksoftUtils.fromUnified(feeStaticReadable['speed_blocks_' + blocks], this._settings.decimals), feeForAllInputs : feeStaticReadable.feeForAllInputs, autoFeeLimitReadable }, additionalData, subtitle) let newStatic = 0 if (!data.isTransferAll && preparedInputsOutputs.inputs && preparedInputsOutputs.inputs.length > feeStaticReadable.feeForAllInputs * 1) { newStatic = BlocksoftUtils.mul(feeStaticReadable['speed_blocks_' + blocks], Math.ceil(preparedInputsOutputs.inputs.length / feeStaticReadable.feeForAllInputs)) BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate_' + key + ' inputs ' + preparedInputsOutputs.inputs.length + ' newStatic ' + newStatic) preparedInputsOutputs = await this.txPrepareInputsOutputs.getInputsOutputs(data, unspents, { feeForByte : 'none', feeForAll : BlocksoftUtils.fromUnified(newStatic, this._settings.decimals), feeForAllInputs : feeStaticReadable.feeForAllInputs, autoFeeLimitReadable }, additionalData, subtitle) } } else { preparedInputsOutputs = await this.txPrepareInputsOutputs.getInputsOutputs(data, unspents, { feeForByte, autoFeeLimitReadable }, additionalData, subtitle) } if (typeof additionalData.feeForByte === 'undefined' && typeof this._builderSettings.feeMinTotalReadable !== 'undefined') { logInputsOutputs = DogeLogs.logInputsOutputs(data, unspents, preparedInputsOutputs, this._settings, subtitle) if (logInputsOutputs.diffInOutReadable * 1 < this._builderSettings.feeMinTotalReadable) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate_' + key + ' ' + feeForByte + ' less minTotalReadable ' + logInputsOutputs.diffInOutReadable ) preparedInputsOutputs = await this.txPrepareInputsOutputs.getInputsOutputs(data, unspents, { feeForAll : BlocksoftUtils.fromUnified(this._builderSettings.feeMinTotalReadable, this._settings.decimals), autoFeeLimitReadable }, additionalData, subtitle) autocorrectFee = false } } // @ts-ignore BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate_' + key + ' ' + feeForByte + ' preparedInputsOutputs addressTo' + data.addressTo, preparedInputsOutputs) if (preparedInputsOutputs.inputs.length === 0) { // do noting continue } } catch (e) { if (config.debug.cryptoErrors) { console.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate_' + key + ' ' + feeForByte + ' getInputsOutputs error', e) } // noinspection ES6MissingAwait MarketingEvent.logOnlyRealTime('v20_doge_error_getfeerate_' + key + ' ' + feeForByte + ' ' + this._settings.currencyCode + ' ' + data.addressFrom + ' => ' + data.addressTo + ' ' + e.message, unspents) throw e } try { let doBuild = false let actualFeeRebuild = false do { doBuild = false logInputsOutputs = DogeLogs.logInputsOutputs(data, unspents, preparedInputsOutputs, this._settings, subtitle) blockchainData = await this.txBuilder.getRawTx(data, privateData, preparedInputsOutputs) txSize = Math.ceil(blockchainData.rawTxHex.length / 2) actualFeeForByteNotRounded = BlocksoftUtils.div(logInputsOutputs.diffInOut, txSize) actualFeeForByte = Math.floor(actualFeeForByteNotRounded) let needAutoCorrect = false if (autocorrectFee && !isStaticFee) { needAutoCorrect = actualFeeForByte.toString() !== feeForByte.toString() } if (!actualFeeRebuild && needAutoCorrect) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate will correct as ' + actualFeeForByte.toString() + ' != ' + feeForByte.toString()) let outputForCorrecting = -1 for (let i = 0, ic = preparedInputsOutputs.outputs.length; i < ic; i++) { const output = preparedInputsOutputs.outputs[i] if (typeof output.isUsdt !== 'undefined') continue if (typeof output.isChange !== 'undefined' && output.isChange) { outputForCorrecting = i } } if (outputForCorrecting >= 0) { const diff = BlocksoftUtils.diff(actualFeeForByteNotRounded.toString(), feeForByte.toString()) const part = BlocksoftUtils.mul(txSize.toString(), diff.toString()).toString() let newAmount if (part.indexOf('-') === 0) { newAmount = BlocksoftUtils.diff(preparedInputsOutputs.outputs[outputForCorrecting].amount, part.replace('-', '')) } else { newAmount = BlocksoftUtils.add(preparedInputsOutputs.outputs[outputForCorrecting].amount, part) } BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate diff ' + diff + ' part ' + part + ' amount ' + preparedInputsOutputs.outputs[outputForCorrecting].amount + ' => ' + newAmount) // @ts-ignore if (newAmount * 1 < 0) { preparedInputsOutputs.outputs[outputForCorrecting].amount = 'removed' outputForCorrecting = -1 } else { preparedInputsOutputs.outputs[outputForCorrecting].amount = newAmount } } doBuild = true actualFeeRebuild = true if (outputForCorrecting === -1) { let foundToMore = false for (let i = 0, ic = unspents.length; i < ic; i++) { const unspent = unspents[i] if (unspent.confirmations > 0 && !unspent.isRequired) { unspents[i].isRequired = true foundToMore = true } } if (!foundToMore) { for (let i = 0, ic = unspents.length; i < ic; i++) { const unspent = unspents[i] if (!unspent.isRequired) { unspents[i].isRequired = true foundToMore = true } } } BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getFeeRate foundToMore ' + JSON.stringify(foundToMore)) if (foundToMore) { try { const preparedInputsOutputs2 = await this.txPrepareInputsOutputs.getInputsOutputs(data, unspents, { feeForByte, autoFeeLimitReadable }, additionalData, subtitle + ' foundToMore') actualFeeRebuild = false if (preparedInputsOutputs2.inputs.length > 0) { preparedInputsOutputs = preparedInputsOutputs2 } } catch (e) { // do nothing } } } } } while (doBuild) } catch (e) { if (config.debug.cryptoErrors) { console.log(this._settings.currencyCode + ' DogeTransferProcessor.getRawTx error ' + e.message) /* console.log('') console.log('') if (preparedInputsOutputs.inputs) { let i = 0 for (let input of preparedInputsOutputs.inputs) { console.log('ERR inputs [' + i + ']', JSON.parse(JSON.stringify(input))) i++ } } if (preparedInputsOutputs.outputs) { let i = 0 for (let output of preparedInputsOutputs.outputs) { console.log('ERR outputs [' + i + ']', JSON.parse(JSON.stringify(output))) i++ } } console.log('ERR fee msg ', preparedInputsOutputs.msg) console.log('ERR diffInOutS', logInputsOutputs.diffInOut) console.log('ERR diffInOutR', logInputsOutputs.diffInOutReadable) console.log('---------------------') console.log('') */ } BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.getRawTx error '+ e.message) MarketingEvent.logOnlyRealTime('v20_doge_error_tx_builder_fees ' + this._settings.currencyCode + ' ' + data.addressFrom + ' => ' + data.addressTo + ' ' + e.message.toString(), logInputsOutputs) if (e.message.indexOf('Transaction has absurd fees') !== -1) { isError = 'SERVER_RESPONSE_TOO_BIG_FEE_PER_BYTE_FOR_TRANSACTION' continue } else { throw e } } isError = false // @ts-ignore blockchainData.isTransferAll = data.isTransferAll blockchainData.isRBFed = { transactionRemoveByFee, transactionReplaceByFee, transactionSpeedUp } if (typeof uniqueFees[logInputsOutputs.diffInOut] !== 'undefined') { continue } result.fees.push( { langMsg: this._langPrefix + '_' + key, feeForByte: actualFeeForByte.toString(), needSpeed: feeForByte.toString(), feeForTx: logInputsOutputs.diffInOut, amountForTx: logInputsOutputs.sendBalance, addressToTx: data.addressTo, blockchainData } ) uniqueFees[logInputsOutputs.diffInOut] = true } if (isError) { throw new Error(isError) } result.selectedFeeIndex = result.fees.length - 1 if (!transactionReplaceByFee && !transactionRemoveByFee && !isStaticFee) { let foundFast = false for (const fee of result.fees) { if (fee.langMsg === this._langPrefix + '_speed_blocks_2') { foundFast = true } } if (!foundFast) { result.showSmallFeeNotice = new Date().getTime() } } if (result.fees.length === 0) { result.amountForTx = 0 } result.additionalData = { unspents } return result } async getTransferAllBalance(data: BlocksoftBlockchainTypes.TransferData, privateData: BlocksoftBlockchainTypes.TransferPrivateData, additionalData: BlocksoftBlockchainTypes.TransferAdditionalData = {}): Promise<BlocksoftBlockchainTypes.TransferAllBalanceResult> { data.isTransferAll = true const result = await this.getFeeRate(data, privateData, additionalData) // @ts-ignore if (!result || result.selectedFeeIndex < 0) { return { selectedTransferAllBalance: '0', selectedFeeIndex: -2, fees: [], countedForBasicBalance: data.amount } } // @ts-ignore return { ...result, selectedTransferAllBalance: result.fees[result.selectedFeeIndex].amountForTx, countedForBasicBalance: data.amount } } async sendTx(data: BlocksoftBlockchainTypes.TransferData, privateData: BlocksoftBlockchainTypes.TransferPrivateData, uiData: BlocksoftBlockchainTypes.TransferUiData): Promise<BlocksoftBlockchainTypes.SendTxResult> { if (typeof uiData.selectedFee.blockchainData === 'undefined' && typeof uiData.selectedFee.feeForTx === 'undefined') { throw new Error('SERVER_RESPONSE_PLEASE_SELECT_FEE') } if (typeof privateData.privateKey === 'undefined') { throw new Error('DOGE transaction required privateKey') } if (typeof data.addressTo === 'undefined') { throw new Error('DOGE transaction required addressTo') } let txRBFed = '' let txRBF = false if (typeof data.transactionRemoveByFee !== 'undefined' && data.transactionRemoveByFee) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx remove started ' + data.transactionRemoveByFee) txRBF = data.transactionRemoveByFee txRBFed = 'RBFremoved' } else if (typeof data.transactionReplaceByFee !== 'undefined' && data.transactionReplaceByFee) { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx resend started ' + data.transactionReplaceByFee) txRBF = data.transactionReplaceByFee txRBFed = 'RBFed' } else { BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx started') txRBFed = 'usualSend' } const logData = {} logData.currencyCode = this._settings.currencyCode logData.selectedFee = uiData.selectedFee logData.from = data.addressFrom logData.basicAddressTo = data.addressTo logData.basicAmount = data.amount logData.pushLocale = sublocale() logData.pushSetting = await settingsActions.getSetting('transactionsNotifs') if (typeof uiData !== 'undefined' && typeof uiData.selectedFee !== 'undefined' && typeof uiData.selectedFee.rawOnly !== 'undefined' && uiData.selectedFee.rawOnly) { return { rawOnly: uiData.selectedFee.rawOnly, raw : uiData.selectedFee.blockchainData.rawTxHex } } let result = {} as BlocksoftBlockchainTypes.SendTxResult try { result = await this.sendProvider.sendTx(uiData.selectedFee.blockchainData.rawTxHex, txRBFed, txRBF, logData) result.transactionFee = uiData.selectedFee.feeForTx result.transactionFeeCurrencyCode = this._settings.currencyCode result.transactionJson = { nSequence: uiData.selectedFee.blockchainData.nSequence, txAllowReplaceByFee: uiData.selectedFee.blockchainData.txAllowReplaceByFee, feeForByte: uiData.selectedFee.feeForByte } if (typeof uiData.selectedFee.amountForTx !== 'undefined' && uiData.selectedFee.amountForTx) { result.amountForTx = uiData.selectedFee.amountForTx } if (txRBF) { await DogeRawDS.cleanRaw({ address: data.addressFrom, currencyCode: this._settings.currencyCode, transactionHash: txRBF }) } const transactionLog = typeof result.logData !== 'undefined' ? result.logData : logData const inputsLog = JSON.stringify(uiData.selectedFee.blockchainData.preparedInputsOutputs.inputs) const transactionRaw = uiData.selectedFee.blockchainData.rawTxHex + '' //if (typeof transactionLog.selectedFee !== 'undefined' && typeof transactionLog.selectedFee.blockchainData !== 'undefined') { // transactionLog.selectedFee.blockchainData = '*' //} await DogeRawDS.saveRaw({ address: data.addressFrom, currencyCode: this._settings.currencyCode, transactionHash: result.transactionHash, transactionRaw, transactionLog }) BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx hex ', uiData.selectedFee.blockchainData.rawTxHex) // @ts-ignore BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx result ', result) await DogeRawDS.saveInputs({ address: data.addressFrom, currencyCode: this._settings.currencyCode, transactionHash: result.transactionHash, transactionRaw: inputsLog }) await DogeRawDS.saveJson({ address: data.addressFrom, currencyCode: this._settings.currencyCode, transactionHash: result.transactionHash, transactionRaw: JSON.stringify(result.transactionJson) }) BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sent ' + data.addressFrom + ' done ' + JSON.stringify(result.transactionJson)) } catch (e) { if (config.debug.cryptoErrors) { console.log(this._settings.currencyCode + ' DogeTransferProcessor.sent error', e, uiData) } BlocksoftCryptoLog.log(this._settings.currencyCode + ' DogeTransferProcessor.sent error '+ e.message) // noinspection ES6MissingAwait MarketingEvent.logOnlyRealTime('v20_doge_tx_error ' + this._settings.currencyCode + ' ' + data.addressFrom + ' => ' + data.addressTo + ' ' + e.message, logData) throw e } // noinspection ES6MissingAwait MarketingEvent.logOnlyRealTime('v20_doge_tx_success ' + this._settings.currencyCode + ' ' + data.addressFrom + ' => ' + data.addressTo, logData) if (config.debug.cryptoErrors) { console.log(this._settings.currencyCode + ' DogeTransferProcessor.sendTx result', JSON.parse(JSON.stringify(result))) } return result } async sendRawTx(data: BlocksoftBlockchainTypes.DbAccount, rawTxHex: string, txRBF : any, logData : any): Promise<string> { this._initProviders() const result = await this.sendProvider.sendTx(rawTxHex, 'rawSend', txRBF, logData) return result.transactionHash } async setMissingTx(data: BlocksoftBlockchainTypes.DbAccount, transaction: BlocksoftBlockchainTypes.DbTransaction): Promise<boolean> { DogeRawDS.cleanRaw({ address: data.address, transactionHash: transaction.transactionHash, currencyCode: this._settings.currencyCode }) MarketingEvent.logOnlyRealTime('v20_doge_tx_set_missing ' + this._settings.currencyCode + ' ' + data.address + ' => ' + transaction.addressTo, transaction) return true } canRBF(data: BlocksoftBlockchainTypes.DbAccount, transaction: BlocksoftBlockchainTypes.DbTransaction): boolean { if (transaction.transactionDirection === 'income') { return true } if (typeof transaction.transactionJson !== 'undefined') { // console.log('transaction.transactionJson', JSON.stringify(transaction.transactionJson)) } return true } }
the_stack
import { TSESLint } from '@typescript-eslint/experimental-utils'; import rule, { MAPPING_TO_USER_EVENT, MessageIds, Options, RULE_NAME, UserEventMethods, } from '../../../lib/rules/prefer-user-event'; import { LIBRARY_MODULES } from '../../../lib/utils'; import { createRuleTester } from '../test-utils'; function createScenarioWithImport< T extends | TSESLint.InvalidTestCase<MessageIds, Options> | TSESLint.ValidTestCase<Options> >(callback: (libraryModule: string, fireEventMethod: string) => T) { return LIBRARY_MODULES.reduce( (acc: Array<T>, libraryModule) => acc.concat( Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => callback(libraryModule, fireEventMethod) ) ), [] ); } const ruleTester = createRuleTester(); function formatUserEventMethodsMessage(fireEventMethod: string): string { const userEventMethods = MAPPING_TO_USER_EVENT[fireEventMethod].map( (methodName) => `userEvent.${methodName}` ); let joinedList = ''; for (let i = 0; i < userEventMethods.length; i++) { const item = userEventMethods[i]; if (i === 0) { joinedList += item; } else if (i + 1 === userEventMethods.length) { joinedList += `, or ${item}`; } else { joinedList += `, ${item}`; } } return joinedList; } ruleTester.run(RULE_NAME, rule, { valid: [ { code: ` import { screen } from '@testing-library/user-event' const element = screen.getByText(foo) `, }, { code: ` const utils = render(baz) const element = utils.getByText(foo) `, }, ...UserEventMethods.map((userEventMethod) => ({ code: ` import userEvent from '@testing-library/user-event' const node = document.createElement(elementType) userEvent.${userEventMethod}(foo) `, })), ...createScenarioWithImport<TSESLint.ValidTestCase<Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` import { fireEvent } from '${libraryModule}' const node = document.createElement(elementType) fireEvent.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], }) ), ...createScenarioWithImport<TSESLint.ValidTestCase<Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` import { fireEvent as fireEventAliased } from '${libraryModule}' const node = document.createElement(elementType) fireEventAliased.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], }) ), ...createScenarioWithImport<TSESLint.ValidTestCase<Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` import * as dom from '${libraryModule}' dom.fireEvent.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], }) ), ...LIBRARY_MODULES.map((libraryModule) => ({ // imported fireEvent and not used, code: ` import { fireEvent } from '${libraryModule}' import * as foo from 'someModule' foo.baz() `, })), ...LIBRARY_MODULES.map((libraryModule) => ({ // imported dom, but not using fireEvent code: ` import * as dom from '${libraryModule}' const button = dom.screen.getByRole('button') const foo = dom.screen.container.querySelector('baz') `, })), ...LIBRARY_MODULES.map((libraryModule) => ({ code: ` import { fireEvent as aliasedFireEvent } from '${libraryModule}' function fireEvent() { console.log('foo') } fireEvent() `, })), { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { screen } from 'test-utils' const element = screen.getByText(foo) `, }, { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { render } from 'test-utils' const utils = render(baz) const element = utils.getByText(foo) `, }, ...UserEventMethods.map((userEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import userEvent from 'test-utils' const node = document.createElement(elementType) userEvent.${userEventMethod}(foo) `, })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` // fireEvent method used but not imported from TL related module // (aggressive reporting opted out) import { fireEvent } from 'somewhere-else' fireEvent.${fireEventMethod}(foo) `, })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from 'test-utils' const node = document.createElement(elementType) fireEvent.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased } from 'test-utils' const node = document.createElement(elementType) fireEventAliased.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import * as dom from 'test-utils' dom.fireEvent.${fireEventMethod}(foo) `, options: [{ allowedMethods: [fireEventMethod] }], })), // edge case for coverage: // valid use case without call expression // so there is no innermost function scope found ` import { fireEvent } from '@testing-library/react'; test('edge case for no innermost function scope', () => { const click = fireEvent.click }) `, ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' const event = createEvent.${fireEventMethod}(node) fireEvent(node, event) `, options: [{ allowedMethods: [fireEventMethod] }], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased, createEvent } from 'test-utils' fireEventAliased(node, createEvent.${fireEventMethod}(node)) `, options: [{ allowedMethods: [fireEventMethod] }], })), { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' const event = createEvent.drop(node) fireEvent(node, event) `, }, { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' const event = createEvent('drop', node) fireEvent(node, event) `, }, { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased, createEvent as createEventAliased } from 'test-utils' const event = createEventAliased.drop(node) fireEventAliased(node, event) `, }, { settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased, createEvent as createEventAliased } from 'test-utils' const event = createEventAliased('drop', node) fireEventAliased(node, event) `, }, { code: ` const createEvent = () => 'Event'; const event = createEvent(); `, }, ], invalid: [ ...createScenarioWithImport<TSESLint.InvalidTestCase<MessageIds, Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` import { fireEvent } from '${libraryModule}' const node = document.createElement(elementType) fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 4, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], }) ), ...createScenarioWithImport<TSESLint.InvalidTestCase<MessageIds, Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` import * as dom from '${libraryModule}' dom.fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], }) ), ...createScenarioWithImport<TSESLint.InvalidTestCase<MessageIds, Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` const { fireEvent } = require('${libraryModule}') fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], }) ), ...createScenarioWithImport<TSESLint.InvalidTestCase<MessageIds, Options>>( (libraryModule: string, fireEventMethod: string) => ({ code: ` const rtl = require('${libraryModule}') rtl.fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], }) ), ...Object.keys(MAPPING_TO_USER_EVENT).map( (fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import * as dom from 'test-utils' dom.fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], } as const) ), ...Object.keys(MAPPING_TO_USER_EVENT).map( (fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from 'test-utils' fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], } as const) ), ...Object.keys(MAPPING_TO_USER_EVENT).map( (fireEventMethod: string) => ({ code: ` // same as previous group of test cases but without custom module set // (aggressive reporting) import { fireEvent } from 'test-utils' fireEvent.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 5, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], } as const) ), ...Object.keys(MAPPING_TO_USER_EVENT).map( (fireEventMethod: string) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased } from 'test-utils' fireEventAliased.${fireEventMethod}(foo) `, errors: [ { messageId: 'preferUserEvent', line: 3, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, }, ], } as const) ), { code: ` // simple test to check error in detail import { fireEvent } from '@testing-library/react' fireEvent.click(element) fireEvent.mouseOut(element) `, errors: [ { messageId: 'preferUserEvent', line: 4, endLine: 4, column: 7, endColumn: 22, data: { userEventMethods: 'userEvent.click, userEvent.type, userEvent.selectOptions, or userEvent.deselectOptions', fireEventMethod: 'click', }, }, { messageId: 'preferUserEvent', line: 5, endLine: 5, column: 7, endColumn: 25, data: { userEventMethods: 'userEvent.unhover', fireEventMethod: 'mouseOut', }, }, ], }, ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' fireEvent(node, createEvent('${fireEventMethod}', node)) `, errors: [ { messageId: 'preferUserEvent', line: 4, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' fireEvent(node, createEvent.${fireEventMethod}(node)) `, errors: [ { messageId: 'preferUserEvent', line: 4, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent, createEvent } from 'test-utils' const event = createEvent.${fireEventMethod}(node) fireEvent(node, event) `, errors: [ { messageId: 'preferUserEvent', line: 4, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent as fireEventAliased, createEvent as createEventAliased } from 'test-utils' const eventValid = createEventAliased.drop(node) fireEventAliased(node, eventValid) const eventInvalid = createEventAliased.${fireEventMethod}(node) fireEventAliased(node, eventInvalid) `, errors: [ { messageId: 'preferUserEvent', line: 6, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import * as dom from 'test-utils' const eventValid = dom.createEvent.drop(node) dom.fireEvent(node, eventValid) const eventInvalid = dom.createEvent.${fireEventMethod}(node) dom.fireEvent(node, eventInvalid) `, errors: [ { messageId: 'preferUserEvent', line: 6, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ...Object.keys(MAPPING_TO_USER_EVENT).map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import * as dom from 'test-utils' // valid event dom.fireEvent(node, dom.createEvent.drop(node)) // invalid event dom.fireEvent(node, dom.createEvent.${fireEventMethod}(node)) `, errors: [ { messageId: 'preferUserEvent', line: 6, column: 9, data: { userEventMethods: formatUserEventMethodsMessage(fireEventMethod), fireEventMethod, }, } as const, ], })), ], });
the_stack
import sdk, { MediaObject, Camera, ScryptedInterface, Setting, ScryptedDeviceType, Intercom, FFMpegInput, ScryptedMimeTypes, PictureOptions, VideoCameraConfiguration, MediaStreamOptions } from "@scrypted/sdk"; import { Stream, PassThrough } from "stream"; import { AmcrestCameraClient, AmcrestEvent, amcrestHttpsAgent } from "./amcrest-api"; import { RtspSmartCamera, RtspProvider, Destroyable, UrlMediaStreamOptions } from "../../rtsp/src/rtsp"; import { EventEmitter } from "stream"; import child_process, { ChildProcess } from 'child_process'; import { ffmpegLogInitialOutput } from '../../../common/src/media-helpers'; import net from 'net'; import { listenZero } from "../../../common/src/listen-cluster"; import { readLength } from "../../../common/src/read-length"; const { mediaManager } = sdk; const AMCREST_DOORBELL_TYPE = 'Amcrest Doorbell'; const DAHUA_DOORBELL_TYPE = 'Dahua Doorbell'; class AmcrestCamera extends RtspSmartCamera implements VideoCameraConfiguration, Camera, Intercom { eventStream: Stream; cp: ChildProcess; client: AmcrestCameraClient; maxExtraStreams: number; constructor(nativeId: string, provider: RtspProvider) { super(nativeId, provider); if (this.storage.getItem('amcrestDoorbell') === 'true') { this.storage.setItem('doorbellType', AMCREST_DOORBELL_TYPE); this.storage.removeItem('amcrestDoorbell'); } this.updateDeviceInfo(); } async updateDeviceInfo(): Promise<void> { var deviceInfo = {}; const deviceParameters = [ {"action":"getVendor","replace":"vendor=","parameter":"manufacturer"}, {"action":"getSerialNo","replace":"sn=","parameter":"serialNumber"}, {"action":"getDeviceType","replace":"type=","parameter":"model"}, {"action":"getSoftwareVersion","replace":"version=","parameter":"firmware"} ]; for (const element of deviceParameters) { try { const response = await this.getClient().digestAuth.request({ url: `http://${this.getHttpAddress()}/cgi-bin/magicBox.cgi?action=${element['action']}` }); const result = String(response.data).replace(element['replace'], ""); deviceInfo[element['parameter']] = result; } catch (e) { this.console.error('Error getting device parameter', element['action'], e); } } this.info = deviceInfo; } async setVideoStreamOptions(options: MediaStreamOptions): Promise<void> { let bitrate = options?.video?.bitrate; if (!bitrate) return; bitrate = Math.round(bitrate / 1000); // what is Encode[0]? Is that the camera number? const response = await this.getClient().digestAuth.request({ url: `http://${this.getHttpAddress()}/cgi-bin/configManager.cgi?action=setConfig&Encode[0].MainFormat[${this.getChannelFromMediaStreamOptionsId(options.id)}].Video.BitRate=${bitrate}` }); this.console.log('reconfigure result', response.data); } getClient() { if (!this.client) this.client = new AmcrestCameraClient(this.getHttpAddress(), this.getUsername(), this.getPassword(), this.console); return this.client; } listenEvents() { const ret = new EventEmitter() as (EventEmitter & Destroyable); ret.destroy = () => { }; (async () => { try { const client = new AmcrestCameraClient(this.getHttpAddress(), this.getUsername(), this.getPassword(), this.console); const events = await client.listenEvents(); const doorbellType = this.storage.getItem('doorbellType'); ret.destroy = () => { events.removeAllListeners(); events.destroy(); }; let pulseTimeout: NodeJS.Timeout; events.on('close', () => ret.emit('error', new Error('close'))); events.on('error', e => ret.emit('error', e)); events.on('data', (data: Buffer) => { if (this.storage.getItem('debug')) this.console.log('event', data.toString()); }); events.on('event', (event: AmcrestEvent, index: string) => { const channelNumber = this.getRtspChannel(); if (channelNumber) { const idx = parseInt(index) + 1; if (idx.toString() !== channelNumber) return; } if (event === AmcrestEvent.MotionStart) { this.motionDetected = true; } else if (event === AmcrestEvent.MotionStop) { this.motionDetected = false; } else if (event === AmcrestEvent.AudioStart) { this.audioDetected = true; } else if (event === AmcrestEvent.AudioStop) { this.audioDetected = false; } else if (event === AmcrestEvent.TalkInvite || event === AmcrestEvent.PhoneCallDetectStart || event === AmcrestEvent.AlarmIPCStart || event === AmcrestEvent.DahuaTalkInvite) { this.binaryState = true; } else if (event === AmcrestEvent.TalkHangup || event === AmcrestEvent.PhoneCallDetectStop || event === AmcrestEvent.AlarmIPCStop || event === AmcrestEvent.DahuaTalkHangup) { this.binaryState = false; } else if (event === AmcrestEvent.TalkPulse && doorbellType === AMCREST_DOORBELL_TYPE) { clearTimeout(pulseTimeout); pulseTimeout = setTimeout(() => this.binaryState = false, 30000); this.binaryState = true; } else if (event === AmcrestEvent.DahuaTalkPulse && doorbellType === DAHUA_DOORBELL_TYPE) { clearTimeout(pulseTimeout); pulseTimeout = setTimeout(() => this.binaryState = false, 3000); this.binaryState = true; } }) } catch (e) { ret.emit('error', e); } })(); return ret; } async getOtherSettings(): Promise<Setting[]> { return [ { title: 'Doorbell Type', choices: [ 'Not a Doorbell', AMCREST_DOORBELL_TYPE, DAHUA_DOORBELL_TYPE, ], description: 'If this device is a doorbell, select the appropriate doorbell type.', value: this.storage.getItem('doorbellType'), key: 'doorbellType', }, ]; } async takeSmartCameraPicture(option?: PictureOptions): Promise<MediaObject> { return mediaManager.createMediaObject(await this.getClient().jpegSnapshot(), 'image/jpeg'); } async getUrlSettings() { return [ ...await super.getUrlSettings(), { key: 'rtspChannel', title: 'Channel Number Override', description: "The channel number to use for snapshots and video. E.g., 1, 2, etc.", placeholder: '1', value: this.storage.getItem('rtspChannel'), }, ] } getRtspChannel() { return this.storage.getItem('rtspChannel'); } async getConstructedVideoStreamOptions(): Promise<UrlMediaStreamOptions[]> { let mas = this.maxExtraStreams; if (!this.maxExtraStreams) { const client = this.getClient(); try { const response = await client.digestAuth.request({ url: `http://${this.getHttpAddress()}/cgi-bin/magicBox.cgi?action=getProductDefinition&name=MaxExtraStream`, responseType: 'text', httpsAgent: amcrestHttpsAgent, }) this.maxExtraStreams = parseInt(response.data.split('=')[1].trim()); mas = this.maxExtraStreams; } catch (e) { this.console.error('error retrieving max extra streams', e); } } mas = mas || 1; const channel = this.getRtspChannel() || '1'; return [...Array(mas + 1).keys()].map(subtype => this.createRtspMediaStreamOptions(`rtsp://${this.getRtspAddress()}/cam/realmonitor?channel=${channel}&subtype=${subtype}`, subtype)); } async putSetting(key: string, value: string) { this.client = undefined; this.maxExtraStreams = undefined; const doorbellType = this.storage.getItem('doorbellType'); const isDoorbell = doorbellType === AMCREST_DOORBELL_TYPE || doorbellType === DAHUA_DOORBELL_TYPE; super.putSetting(key, value); if (isDoorbell) provider.updateDevice(this.nativeId, this.name, [...provider.getInterfaces(), ScryptedInterface.BinarySensor, ScryptedInterface.Intercom], ScryptedDeviceType.Doorbell); else provider.updateDevice(this.nativeId, this.name, provider.getInterfaces()); } async startIntercom(media: MediaObject): Promise<void> { // not sure if this all works, since i don't actually have a doorbell. // good luck! const channel = this.getRtspChannel() || '1'; const buffer = await mediaManager.convertMediaObjectToBuffer(media, ScryptedMimeTypes.FFmpegInput); const ffmpegInput = JSON.parse(buffer.toString()) as FFMpegInput; const args = ffmpegInput.inputArguments.slice(); args.unshift('-hide_banner'); const server = new net.Server(async (socket) => { server.close(); const url = `http://${this.getHttpAddress()}/cgi-bin/audio.cgi?action=postAudio&httptype=singlepart&channel=${channel}`; this.console.log('posting audio data to', url); // seems the dahua doorbells preferred 1024 chunks. should investigate adts // parsing and sending multipart chunks instead. const passthrough = new PassThrough(); this.getClient().digestAuth.request({ method: 'POST', url, headers: { 'Content-Type': 'Audio/AAC', 'Content-Length': '9999999' }, httpsAgent: amcrestHttpsAgent, data: passthrough, }); try { while (true) { const data = await readLength(socket, 1024); passthrough.push(data); } } catch (e) { this.console.error('audio finished with error', e); } finally { passthrough.end(); } this.cp.kill(); }); const port = await listenZero(server) args.push( "-vn", '-acodec', 'libfdk_aac', '-f', 'adts', `tcp://127.0.0.1:${port}`, ); this.console.log('ffmpeg intercom', args); const ffmpeg = await mediaManager.getFFmpegPath(); this.cp = child_process.spawn(ffmpeg, args); this.cp.on('exit', () => this.cp = undefined); ffmpegLogInitialOutput(this.console, this.cp); } async stopIntercom(): Promise<void> { this.cp?.kill(); this.cp = undefined; } showRtspUrlOverride() { return false; } } class AmcrestProvider extends RtspProvider { getAdditionalInterfaces() { return [ ScryptedInterface.VideoCameraConfiguration, ScryptedInterface.Camera, ScryptedInterface.AudioSensor, ScryptedInterface.MotionSensor, ]; } createCamera(nativeId: string) { return new AmcrestCamera(nativeId, this); } } const provider = new AmcrestProvider(); export default provider;
the_stack
import { getConnection, getRepository, In } from 'typeorm'; import { Team } from '../entity/Team'; import { User } from '../entity/User'; import { Response, Request } from 'express'; import { validate } from 'class-validator'; import { UserRequest } from '../interfaces/user-request.interface'; import { Asset } from '../entity/Asset'; import { Organization } from '../entity/Organization'; import { ROLE } from '../enums/roles-enum'; export const getAllTeams = async (req: Request, res: Response) => { const teams = await getConnection() .getRepository(Team) .createQueryBuilder('team') .leftJoinAndSelect('team.users', 'users') .leftJoinAndSelect('team.assets', 'assets') .leftJoinAndSelect('team.organization', 'organization') .select([ 'team', 'assets', 'organization', 'users.firstName', 'users.lastName', 'users.title', 'users.id', ]) .getMany(); return res.status(200).json(teams); }; export const fetchAssets = async (assetIds: number[]) => { const assetAry: Asset[] = []; for (const assetId of assetIds) { const asset = await getConnection().getRepository(Asset).findOne(assetId); if (asset) { assetAry.push(asset); } } return assetAry; }; export const fetchUsers = async (userIds: number[]) => { const userAry: User[] = []; for (const userId of userIds) { const user = await getConnection() .getRepository(User) .findOne(userId, { where: { active: true } }); if (user) { userAry.push(user); } } return userAry; }; export const fetchUsersAndUpdateTeam = async ( userIds: number[], teamUsers: User[] ) => { if (!userIds) { teamUsers = []; return teamUsers; } else { const newUsers = await fetchUsers(userIds); teamUsers = newUsers; return teamUsers; } }; export const fetchAssetsAndUpdateTeam = async ( assetIds: number[], teamAssets: Asset[] ) => { const newAssets = await fetchAssets(assetIds); teamAssets = newAssets; return teamAssets; }; export const getTeamById = async (req: UserRequest, res: Response) => { const { teamId } = req.params; if (isNaN(+teamId)) { return res.status(400).json('Invalid Team ID'); } const fetchedTeam = await getConnection() .getRepository(Team) .createQueryBuilder('team') .leftJoinAndSelect('team.users', 'users') .leftJoinAndSelect('team.assets', 'assets') .leftJoinAndSelect('assets.jira', 'jira') .leftJoinAndSelect('team.organization', 'organization') .where('team.id = :teamId', { teamId }) .select([ 'team', 'assets', 'jira.id', 'organization', 'users.firstName', 'users.lastName', 'users.title', 'users.id', ]) .getOne(); if (!fetchedTeam) { return res.status(404).json('Team not found'); } else { return res.status(200).json(fetchedTeam); } }; export const createTeam = async (req: UserRequest, res: Response) => { const { name, organization, role, assetIds, users } = req.body; const newTeam = new Team(); let fetchedOrg: Organization; if (role !== ROLE.ADMIN) { fetchedOrg = await getConnection() .getRepository(Organization) .findOne(organization, { relations: ['teams'] }); if (!fetchedOrg) { return res.status(404).json('Organization not found'); } } else { fetchedOrg = null; } newTeam.id = null; newTeam.name = name; newTeam.organization = fetchedOrg; newTeam.role = role; newTeam.createdBy = +req.user; newTeam.createdDate = new Date(); newTeam.lastUpdatedBy = +req.user; newTeam.lastUpdatedDate = new Date(); if (users && users.length) newTeam.users = await fetchUsers(users); if (assetIds && assetIds.length) newTeam.assets = await fetchAssets(assetIds); const errors = await validate(newTeam); if (errors.length > 0) { return res.status(400).json('Submitted Team is Invalid'); } else { await getConnection().getRepository(Team).save(newTeam); return res.status(200).json('The team has been successfully created'); } }; export const addTeamMember = async (req: UserRequest, res: Response) => { const { userIds, teamId } = req.body; // Verify team exists if (!teamId) { return res.status(400).json('Invalid Team ID'); } const team = await getConnection() .getRepository(Team) .findOne(teamId, { relations: ['users'] }); if (!team) { return res.status(404).json(`A Team with ID ${teamId} does not exist`); } // Verify each user ID links to a valid user team.users = await fetchUsers(userIds); // Save the team once valid users have been pushed to team await getConnection().getRepository(Team).save(team); return res.status(200).json('Team membership has been successfully updated'); }; export const removeTeamMember = async (req: UserRequest, res: Response) => { const userIds = req.body.userIds; const teamId = req.body.teamId; // Verify team exists if (!teamId) { return res.status(400).json('Invalid Team ID'); } const team = await getConnection() .getRepository(Team) .findOne(teamId, { relations: ['users'] }); if (!team) { return res.status(404).json(`A Team with ID ${teamId} does not exist`); } // Verify each user ID links to a valid user for (const userId of userIds) { const user = await getConnection().getRepository(User).findOne(userId); if (!user) { return res.status(404).json(`A User with ID ${userId} does not exist`); } else { team.users = team.users.filter((userIdx) => userIdx.id !== user.id); } } // Save the team once valid users have been pushed to team await getConnection().getRepository(Team).save(team); return res.status(200).json('Team membership has been successfully updated'); }; export const updateTeamInfo = async (req: Request, res: Response) => { const { name, role, id, users } = req.body; let organization: Organization = req.body.organization; let assetIds: number[] = req.body.assetIds; if (!(name || organization || role)) { return res.status(400).json('Team is invalid'); } if (!id) { return res.status(400).json('The Team ID is invalid'); } const team = await getConnection() .getRepository(Team) .createQueryBuilder('team') .leftJoinAndSelect('team.users', 'users') .leftJoinAndSelect('team.assets', 'assets') .leftJoinAndSelect('team.organization', 'organization') .leftJoinAndSelect('organization.asset', 'orgAssets') .where('team.id = :teamId', { teamId: id }) .select(['team', 'users', 'assets', 'organization', 'orgAssets']) .getOne(); if (!team) { return res.status(404).json(`A Team with ID ${id} does not exist`); } // If the incoming organization has changed // Remove all previous asset associations let fetchedOrg: Organization; if (role !== ROLE.ADMIN) { organization = await getConnection() .getRepository(Organization) .findOne(organization, { relations: ['teams'] }); if (!organization) { return res.status(404).json('Organization not found'); } if (+organization.id !== +team.organization.id) { for (const orgAsset of team.organization.asset) { assetIds = assetIds.filter((x) => x !== orgAsset.id); } } } else { organization = null; } team.users = await fetchUsersAndUpdateTeam(users, team.users); team.assets = await fetchAssetsAndUpdateTeam(assetIds, team.assets); team.name = name; team.organization = organization; team.role = role; const errors = await validate(team); if (errors.length > 0) { return res.status(400).json('Submitted Team is Invalid'); } else { await getConnection().getRepository(Team).save(team); return res.status(200).json('Team has been patched successfully'); } }; export const deleteTeam = async (req: Request, res: Response) => { const { teamId } = req.params; if (!teamId) { return res.status(400).json('Invalid Team ID'); } const team = await getConnection().getRepository(Team).findOne(teamId); if (!team) { return res.status(404).json(`A Team with ID ${teamId} does not exist`); } await getConnection().getRepository(Team).delete(team.id); return res .status(200) .json(`The Team ${team.name} has been successfully deleted`); }; export const getMyTeams = async (req: UserRequest, res: Response) => { const user = await getConnection() .getRepository(User) .findOne(req.user, { relations: ['teams'] }); return res.status(200).json(user.teams); }; export const addTeamAsset = async (req: Request, res: Response) => { const { assetIds, teamId } = req.body; if (!teamId) { return res.status(400).json('Invalid Team ID'); } const team = await getConnection() .getRepository(Team) .findOne(teamId, { relations: ['assets', 'organization'] }); if (!team) { return res.status(404).json(`A Team with ID ${teamId} does not exist`); } const org = await getConnection() .getRepository(Organization) .findOne(team.organization.id, { relations: ['asset'] }); const orgAssets = org.asset.map((asset) => asset.id); // Verify each asset ID links to a valid user for (const assetId of assetIds) { // Verify we are only associating assets of that organization if (!orgAssets.includes(assetId)) { return res .status(401) .json(`The Asset with ID ${assetId} is unauthorized`); } const asset = await getConnection().getRepository(Asset).findOne(assetId); team.assets.push(asset); } // Save the team once valid assets have been pushed to team await getConnection().getRepository(Team).save(team); return res.status(200).json('Team Assets has been successfully updated'); }; export const removeTeamAsset = async (req: Request, res: Response) => { const { assetIds, teamId } = req.body; if (!teamId) { return res.status(400).json('Invalid Team ID'); } const team = await getConnection() .getRepository(Team) .findOne(teamId, { relations: ['assets', 'organization'] }); if (!team) { return res.status(404).json(`A Team with ID ${teamId} does not exist`); } const org = await getConnection() .getRepository(Organization) .findOne(team.organization.id, { relations: ['asset'] }); const orgAssets = org.asset.map((asset) => asset.id); // Verify each asset ID links to a valid user for (const assetId of assetIds) { // Verify we are only associating assets of that organization if (!orgAssets.includes(assetId)) { return res .status(401) .json(`The Asset with ID ${assetId} is unauthorized`); } const asset = await getConnection().getRepository(Asset).findOne(assetId); team.assets = team.assets.filter((assetIdx) => assetIdx.id !== asset.id); } // Save the team once valid assets have been pushed to team await getConnection().getRepository(Team).save(team); return res.status(200).json('Team Assets has been successfully updated'); };
the_stack
* vConsole Basic Log Tab */ import * as tool from '../lib/tool'; import $ from '../lib/query'; import VConsolePlugin from '../lib/plugin'; import tplItem from './item.html'; import tplLineLog from './item_line_log.html'; import tplFold from './item_fold.html'; import tplFoldCode from './item_fold_code.html'; import VConsoleItemCopy from '../component/item_copy'; const DEFAULT_MAX_LOG_NUMBER = 1000; const ADDED_LOG_TAB_ID = []; type VConsoleLogArgs = any[]; type VConsoleLogType = 'log' | 'info' | 'warn' | 'debug' | 'error'; interface VConsoleLogItem { _id?: string; // random unique id tabName?: 'default' | 'system'; logType: VConsoleLogType; logs?: VConsoleLogArgs; // the params of console.log(); `logs` or `content` can't be empty content?: Element; // `logs` or `content` can't be empty noOrigin?: boolean; date?: number; style?: string; } interface VConsoleLogView { _id: string; logType: VConsoleLogType; logText: string; // plain string hasContent: boolean; hasFold: boolean; count: number; // repeated count } class VConsoleLogTab extends VConsolePlugin { static AddedLogID = []; tplTabbox: string = ''; // MUST be overwrite in child class allowUnformattedLog: boolean = true; // `[xxx]` format log isReady: boolean = false; isShow: boolean = false; $tabbox: Element = null; console: { [method: string]: any } = {}; // window.console logList: VConsoleLogItem[] = []; // save logs before ready cachedLogs: { [id: string]: string } = {}; // for copy text previousLog: VConsoleLogView = null; isInBottom: boolean = true; // whether the panel is in the bottom maxLogNumber: number = DEFAULT_MAX_LOG_NUMBER; logNumber: number = 0; constructor(...args) { super(...args); ADDED_LOG_TAB_ID.push(this.id); this.mockConsole(); } /** * when vConsole is ready, * this event will be triggered (after 'add' event) * @public */ onInit() { this.$tabbox = $.render(this.tplTabbox, {}); this.updateMaxLogNumber(); } /** * this event will make this plugin be registered as a tab * @public */ onRenderTab(callback: Function) { callback(this.$tabbox); } onAddTopBar(callback: Function) { const that = this; const types = ['All', 'Log', 'Info', 'Warn', 'Error']; const btnList = []; for (let i = 0; i < types.length; i++) { btnList.push({ name: types[i], data: { type: types[i].toLowerCase() }, className: '', onClick: function () { if (!$.hasClass(this, 'vc-actived')) { that.showLogType(this.dataset.type || 'all'); } else { return false; } } }); } btnList[0].className = 'vc-actived'; callback(btnList); } onAddTool(callback: Function) { const that = this; const toolList = [{ name: 'Clear', global: false, onClick: function () { that.clearLog(); that.vConsole.triggerEvent('clearLog'); } }]; callback(toolList); } /** * after init * @public */ onReady() { const that = this; that.isReady = true; // log type filter const $subTabs = $.all('.vc-subtab', that.$tabbox); $.bind($subTabs, 'click', function (e) { e.preventDefault(); if ($.hasClass(this, 'vc-actived')) { return false; } $.removeClass($subTabs, 'vc-actived'); $.addClass(this, 'vc-actived'); const logType: 'all' | VConsoleLogType = this.dataset.type; const $log = $.one('.vc-log', that.$tabbox); $.removeClass($log, 'vc-log-partly-log'); $.removeClass($log, 'vc-log-partly-info'); $.removeClass($log, 'vc-log-partly-warn'); $.removeClass($log, 'vc-log-partly-error'); if (logType === 'all') { $.removeClass($log, 'vc-log-partly'); } else { $.addClass($log, 'vc-log-partly'); $.addClass($log, 'vc-log-partly-' + logType); } }); const $content = $.one('.vc-content'); $.bind($content, 'scroll', function (e) { if (!that.isShow) { return; } if ($content.scrollTop + $content.offsetHeight >= $content.scrollHeight) { that.isInBottom = true; } else { that.isInBottom = false; } }); for (let i = 0; i < that.logList.length; i++) { that.printLog(that.logList[i]); } that.logList = []; // copy VConsoleItemCopy.delegate(this.$tabbox, (id) => { return that.cachedLogs[id]; }); } /** * before remove * @public */ onRemove() { window.console.log = this.console.log; window.console.info = this.console.info; window.console.warn = this.console.warn; window.console.debug = this.console.debug; window.console.error = this.console.error; window.console.time = this.console.time; window.console.timeEnd = this.console.timeEnd; window.console.clear = this.console.clear; this.console = null; const idx = ADDED_LOG_TAB_ID.indexOf(this.id); if (idx > -1) { ADDED_LOG_TAB_ID.splice(idx, 1); } this.cachedLogs = {}; } onShow() { this.isShow = true; if (this.isInBottom === true) { this.autoScrollToBottom(); } } onHide() { this.isShow = false; } onShowConsole() { if (this.isInBottom === true) { this.autoScrollToBottom(); } } onUpdateOption() { if (this.vConsole.option.maxLogNumber !== this.maxLogNumber) { this.updateMaxLogNumber(); this.limitMaxLogs(); } } updateMaxLogNumber() { this.maxLogNumber = this.vConsole.option.maxLogNumber || DEFAULT_MAX_LOG_NUMBER; this.maxLogNumber = Math.max(1, this.maxLogNumber); } limitMaxLogs() { if (!this.isReady) { return; } while (this.logNumber > this.maxLogNumber) { const $firstItem = $.one('.vc-item', this.$tabbox); if (!$firstItem) { break; } if (this.cachedLogs[$firstItem.id] !== undefined) { delete this.cachedLogs[$firstItem.id]; } $firstItem.parentNode.removeChild($firstItem); this.logNumber--; } } showLogType(logType: string) { const $log = $.one('.vc-log', this.$tabbox); $.removeClass($log, 'vc-log-partly-log'); $.removeClass($log, 'vc-log-partly-info'); $.removeClass($log, 'vc-log-partly-warn'); $.removeClass($log, 'vc-log-partly-error'); if (logType === 'all') { $.removeClass($log, 'vc-log-partly'); } else { $.addClass($log, 'vc-log-partly'); $.addClass($log, 'vc-log-partly-' + logType); } } autoScrollToBottom() { if (!this.vConsole.option.disableLogScrolling) { this.scrollToBottom(); } } scrollToBottom() { const $content = $.one('.vc-content'); if ($content) { $content.scrollTop = $content.scrollHeight - $content.offsetHeight; } } /** * replace window.console with vConsole method */ protected mockConsole() { const that = this; const methodList: VConsoleLogType[] = ['log', 'info', 'warn', 'debug', 'error']; if (!window.console) { (<any>window.console) = {}; } else { methodList.map(function (method) { that.console[method] = window.console[method]; }); that.console.time = window.console.time; that.console.timeEnd = window.console.timeEnd; that.console.clear = window.console.clear; } methodList.map((method) => { window.console[method] = (...args) => { this.printLog({ logType: method, logs: args, }); }; }); const timeLog = {} window.console.time = function (label) { timeLog[label] = Date.now(); }; window.console.timeEnd = function (label) { var pre = timeLog[label]; if (pre) { console.log(label + ':', (Date.now() - pre) + 'ms'); delete timeLog[label]; } else { console.log(label + ': 0ms'); } }; window.console.clear = (...args) => { that.clearLog(); that.console.clear.apply(window.console, args); }; } clearLog() { $.one('.vc-log', this.$tabbox).innerHTML = ''; this.logNumber = 0; this.previousLog = null; this.cachedLogs = {}; } beforeRenderLog($line: Element) { // do nothing } /** * print log to origin console * @protected */ printOriginLog(item: VConsoleLogItem) { if (typeof this.console[item.logType] === 'function') { this.console[item.logType].apply(window.console, item.logs); } } /** * print a log to log box */ protected printLog(item: VConsoleLogItem) { let logs = item.logs || []; if (!logs.length && !item.content) { return; } // copy logs as a new array logs = [].slice.call(logs || []); // check `[default]` format const pattern = /^\[(\w+)\]$/i; let shouldBeHere = true; let targetTabID = ''; let isInAddedTab = false; if (tool.isString(logs[0])) { let match = logs[0].match(pattern); if (match !== null && match.length > 0) { targetTabID = match[1].toLowerCase(); isInAddedTab = ADDED_LOG_TAB_ID.indexOf(targetTabID) > -1; } } if (targetTabID === this.id) { // target tab is current tab shouldBeHere = true; } else if (isInAddedTab === true) { // target tab is not current tab, but in added tab list // so throw this log to other tab shouldBeHere = false; } else { // target tab is not in added tab list if (this.id === 'default') { // show this log in default tab shouldBeHere = true; } else { shouldBeHere = false; } } if (!shouldBeHere) { // ignore this log and throw it to origin console if (!item.noOrigin) { this.printOriginLog(item); } return; } // add id if (!item._id) { item._id = this.getUniqueID(); } // save log date if (!item.date) { item.date = (+new Date()); } // if vConsole is not ready, save current log to logList if (!this.isReady) { this.logList.push(item); return; } // remove `[xxx]` format if (tool.isString(logs[0]) && isInAddedTab) { logs[0] = logs[0].replace(pattern, ''); if (logs[0] === '') { logs.shift(); } } // make for previous log const curLog: VConsoleLogView = { _id: item._id, logType: item.logType, logText: '', hasContent: !!item.content, hasFold: false, count: 1, }; const logText: string[] = []; for (let i = 0; i < logs.length; i++) { if (tool.isFunction(logs[i])) { logText.push(logs[i].toString()); } else if (tool.isObject(logs[i]) || tool.isArray(logs[i])) { logText.push(tool.SimpleJSONStringify(logs[i])); curLog.hasFold = true; } else { logText.push(logs[i]); } } curLog.logText = logText.join(' '); // check repeat if ( !curLog.hasContent && !curLog.hasFold && !!this.previousLog && this.previousLog.logType === curLog.logType && this.previousLog.logText === curLog.logText ) { this.printRepeatLog(); } else { this.printNewLog(item, logs); // save previous log this.previousLog = curLog; } // scroll to bottom if it is in the bottom before if (this.isInBottom && this.isShow) { this.autoScrollToBottom(); } // print log to origin console if (!item.noOrigin) { this.printOriginLog(item); } } /** * Render the count of a repeated log */ printRepeatLog() { const $item = $.one('#' + this.previousLog._id); let $repeat = $.one('.vc-item-repeat', $item); if (!$repeat) { $repeat = document.createElement('i'); $repeat.className = 'vc-item-repeat'; $item.insertBefore($repeat, $item.lastChild); } // if (!this.previousLog.count) { // this.previousLog.count = 1; // } this.previousLog.count++; $repeat.innerHTML = String(this.previousLog.count); return; } /** * Render a new log */ protected printNewLog(item: VConsoleLogItem, logs: VConsoleLogArgs) { // create line const $line = $.render(tplItem, { _id: item._id, logType: item.logType, style: item.style || '', btnCopy: VConsoleItemCopy.html, }); // find %c keyword in first log only const patternC = /(\%c )|( \%c)/g; const logStyle: string[] = []; if (tool.isString(logs[0]) && patternC.test(logs[0])) { // '%c aaa %c bbb' => ['aaa', 'bbb'] const _logs = logs[0].split(patternC).filter((val) => { return val !== undefined && val !== '' && !/ ?\%c ?/.test(val); }); const matchC = logs[0].match(patternC); // use the following string logs as style for (let i = 0; i < matchC.length; i++) { if (tool.isString(logs[i + 1])) { logStyle.push(logs[i + 1]); } } // add remain logs for (let i = matchC.length + 1; i < logs.length; i++) { _logs.push(logs[i]); } logs = _logs; } const $content = $.one('.vc-item-content', $line); const rawLogs: string[] = []; // generate content from item.logs for (let i = 0; i < logs.length; i++) { const curLog = logs[i]; let rawLog: string; let log: Element; try { if (curLog === '') { // ignore empty string continue; } else if (tool.isFunction(curLog)) { // convert function to string rawLog = curLog.toString(); // log = `<span> ${rawLog}</span>`; log = $.render(tplLineLog, { log: rawLog, logStyle: '', }); } else if (tool.isObject(curLog) || tool.isArray(curLog)) { // object or array rawLog = tool.JSONStringify(curLog, tool.circularReplacer(), 2) log = this.getFoldedLine(curLog); } else { // default rawLog = curLog; // log = (logStyle[i] ? `<span style="${logStyle[i]}"> ` : '<span> ') + tool.htmlEncode(curLog).replace(/\n/g, '<br/>') + '</span>'; log = $.render(tplLineLog, { log: curLog, logStyle: logStyle[i], }); } } catch (e) { rawLog = typeof curLog; // log = `<span> [${rawLog}]</span>`; log = $.render(tplLineLog, { log: ` [${rawLog}]`, logStyle: '' }); } if (log) { rawLogs.push(rawLog); if (typeof log === 'string') { $content.insertAdjacentHTML('beforeend', log); } else { $content.insertAdjacentElement('beforeend', log); } } } // for copy this.cachedLogs[item._id] = rawLogs.join(' '); // generate content from item.content if (tool.isObject(item.content)) { $content.insertAdjacentElement('beforeend', item.content); } // render to panel this.beforeRenderLog($line); $.one('.vc-log', this.$tabbox).insertAdjacentElement('beforeend', $line); // remove overflow logs this.logNumber++; this.limitMaxLogs(); } /** * generate the HTML element of a folded line */ protected getFoldedLine(obj: any, outer?: string) { const that = this; if (!outer) { const json = tool.SimpleJSONStringify(obj); let preview = json.substr(0, 36); outer = tool.getObjName(obj); if (json.length > 36) { preview += '...'; } outer = tool.invisibleTextEncode(tool.htmlEncode(outer + ' ' + preview)); } const $line = $.render(tplFold, { outer: outer, lineType: 'obj' }); $.bind($.one('.vc-fold-outer', $line), 'click', function (e) { e.preventDefault(); e.stopPropagation(); if ($.hasClass($line, 'vc-toggle')) { $.removeClass($line, 'vc-toggle'); $.removeClass($.one('.vc-fold-inner', $line), 'vc-toggle'); $.removeClass($.one('.vc-fold-outer', $line), 'vc-toggle'); } else { $.addClass($line, 'vc-toggle'); $.addClass($.one('.vc-fold-inner', $line), 'vc-toggle'); $.addClass($.one('.vc-fold-outer', $line), 'vc-toggle'); } const $content = $.one('.vc-fold-inner', $line); setTimeout(function () { if ($content.children.length == 0 && !!obj) { // render object's keys let keys = tool.getObjAllKeys(obj); for (let i = 0; i < keys.length; i++) { let val, valueType = 'undefined', keyType = ''; try { val = obj[keys[i]]; } catch (e) { continue; } // handle value if (tool.isString(val)) { valueType = 'string'; val = '"' + tool.invisibleTextEncode(val) + '"'; } else if (tool.isNumber(val)) { valueType = 'number'; } else if (tool.isBoolean(val)) { valueType = 'boolean'; } else if (tool.isNull(val)) { valueType = 'null'; val = 'null'; } else if (tool.isUndefined(val)) { valueType = 'undefined'; val = 'undefined'; } else if (tool.isFunction(val)) { valueType = 'function'; val = 'function()'; } else if (tool.isSymbol(val)) { valueType = 'symbol'; } // render let $sub; if (tool.isArray(val)) { let name = tool.getObjName(val) + '(' + val.length + ')'; $sub = that.getFoldedLine(val, $.render(tplFoldCode, { key: keys[i], keyType: keyType, value: name, valueType: 'array' }, true)); } else if (tool.isObject(val)) { let name = tool.getObjName(val); $sub = that.getFoldedLine(val, $.render(tplFoldCode, { // key: tool.htmlEncode(keys[i]), key: keys[i], keyType: keyType, value: name, valueType: 'object' }, true)); } else { if (obj.hasOwnProperty && !obj.hasOwnProperty(keys[i])) { keyType = 'private'; } let renderData = { lineType: 'kv', // key: tool.htmlEncode(keys[i]), key: keys[i], keyType: keyType, // value: tool.htmlEncode(val), value: val, valueType: valueType }; $sub = $.render(tplFold, renderData); } $content.insertAdjacentElement('beforeend', $sub); } // render object's prototype if (tool.isObject(obj)) { let proto = obj.__proto__, $proto; if (tool.isObject(proto)) { $proto = that.getFoldedLine(proto, $.render(tplFoldCode, { key: '__proto__', keyType: 'private', value: tool.getObjName(proto), valueType: 'object' }, true)); } else { // if proto is not an object, it should be `null` $proto = $.render(tplFoldCode, { key: '__proto__', keyType: 'private', value: 'null', valueType: 'null' }); } $content.insertAdjacentElement('beforeend', $proto); } } }) return false; }); return $line; } } // END class export default VConsoleLogTab;
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type AuctionResultTestsQueryVariables = { auctionResultInternalID: string; artistID: string; }; export type AuctionResultTestsQueryResponse = { readonly auctionResult: { readonly " $fragmentRefs": FragmentRefs<"AuctionResult_auctionResult">; } | null; readonly artist: { readonly " $fragmentRefs": FragmentRefs<"AuctionResult_artist">; } | null; }; export type AuctionResultTestsQuery = { readonly response: AuctionResultTestsQueryResponse; readonly variables: AuctionResultTestsQueryVariables; }; /* query AuctionResultTestsQuery( $auctionResultInternalID: String! $artistID: String! ) { auctionResult(id: $auctionResultInternalID) { ...AuctionResult_auctionResult id } artist(id: $artistID) { ...AuctionResult_artist id } } fragment AuctionResultListItem_auctionResult on AuctionResult { currency dateText id internalID artist { name id } images { thumbnail { url(version: "square140") height width aspectRatio } } estimate { low } mediumText organization boughtIn performance { mid } priceRealized { cents display displayUSD } saleDate title } fragment AuctionResult_artist on Artist { name href } fragment AuctionResult_auctionResult on AuctionResult { id internalID artistID boughtIn currency categoryText dateText dimensions { height width } dimensionText estimate { display high low } images { thumbnail { url(version: "square140") height width aspectRatio } } location mediumText organization performance { mid } priceRealized { cents centsUSD display displayUSD } saleDate saleTitle title ...ComparableWorks_auctionResult } fragment ComparableWorks_auctionResult on AuctionResult { comparableAuctionResults(first: 3) @optionalField { edges { cursor node { ...AuctionResultListItem_auctionResult artistID internalID id } } } } */ const node: ConcreteRequest = (function(){ var v0 = { "defaultValue": null, "kind": "LocalArgument", "name": "artistID" }, v1 = { "defaultValue": null, "kind": "LocalArgument", "name": "auctionResultInternalID" }, v2 = [ { "kind": "Variable", "name": "id", "variableName": "auctionResultInternalID" } ], v3 = [ { "kind": "Variable", "name": "id", "variableName": "artistID" } ], v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "artistID", "storageKey": null }, v7 = { "alias": null, "args": null, "kind": "ScalarField", "name": "boughtIn", "storageKey": null }, v8 = { "alias": null, "args": null, "kind": "ScalarField", "name": "currency", "storageKey": null }, v9 = { "alias": null, "args": null, "kind": "ScalarField", "name": "dateText", "storageKey": null }, v10 = { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, v11 = { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, v12 = { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null }, v13 = { "alias": null, "args": null, "kind": "ScalarField", "name": "low", "storageKey": null }, v14 = { "alias": null, "args": null, "concreteType": "AuctionLotImages", "kind": "LinkedField", "name": "images", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "thumbnail", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "square140" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"square140\")" }, (v10/*: any*/), (v11/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "aspectRatio", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, v15 = { "alias": null, "args": null, "kind": "ScalarField", "name": "mediumText", "storageKey": null }, v16 = { "alias": null, "args": null, "kind": "ScalarField", "name": "organization", "storageKey": null }, v17 = { "alias": null, "args": null, "concreteType": "AuctionLotPerformance", "kind": "LinkedField", "name": "performance", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "mid", "storageKey": null } ], "storageKey": null }, v18 = { "alias": null, "args": null, "kind": "ScalarField", "name": "cents", "storageKey": null }, v19 = { "alias": null, "args": null, "kind": "ScalarField", "name": "displayUSD", "storageKey": null }, v20 = { "alias": null, "args": null, "kind": "ScalarField", "name": "saleDate", "storageKey": null }, v21 = { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, v22 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v23 = { "enumValues": null, "nullable": true, "plural": false, "type": "Artist" }, v24 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v25 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v26 = { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResult" }, v27 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v28 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, v29 = { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotEstimate" }, v30 = { "enumValues": null, "nullable": true, "plural": false, "type": "Float" }, v31 = { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotImages" }, v32 = { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, v33 = { "enumValues": null, "nullable": false, "plural": false, "type": "Float" }, v34 = { "enumValues": null, "nullable": true, "plural": false, "type": "Int" }, v35 = { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotPerformance" }, v36 = { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResultPriceRealized" }; return { "fragment": { "argumentDefinitions": [ (v0/*: any*/), (v1/*: any*/) ], "kind": "Fragment", "metadata": null, "name": "AuctionResultTestsQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "AuctionResult", "kind": "LinkedField", "name": "auctionResult", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "AuctionResult_auctionResult" } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "AuctionResult_artist" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [ (v1/*: any*/), (v0/*: any*/) ], "kind": "Operation", "name": "AuctionResultTestsQuery", "selections": [ { "alias": null, "args": (v2/*: any*/), "concreteType": "AuctionResult", "kind": "LinkedField", "name": "auctionResult", "plural": false, "selections": [ (v4/*: any*/), (v5/*: any*/), (v6/*: any*/), (v7/*: any*/), (v8/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "categoryText", "storageKey": null }, (v9/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionLotDimensions", "kind": "LinkedField", "name": "dimensions", "plural": false, "selections": [ (v10/*: any*/), (v11/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "dimensionText", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ (v12/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "high", "storageKey": null }, (v13/*: any*/) ], "storageKey": null }, (v14/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "location", "storageKey": null }, (v15/*: any*/), (v16/*: any*/), (v17/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ (v18/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "centsUSD", "storageKey": null }, (v12/*: any*/), (v19/*: any*/) ], "storageKey": null }, (v20/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "saleTitle", "storageKey": null }, (v21/*: any*/), { "alias": null, "args": [ { "kind": "Literal", "name": "first", "value": 3 } ], "concreteType": "AuctionResultConnection", "kind": "LinkedField", "name": "comparableAuctionResults", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "AuctionResultEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AuctionResult", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v8/*: any*/), (v9/*: any*/), (v4/*: any*/), (v5/*: any*/), { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v22/*: any*/), (v4/*: any*/) ], "storageKey": null }, (v14/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionLotEstimate", "kind": "LinkedField", "name": "estimate", "plural": false, "selections": [ (v13/*: any*/) ], "storageKey": null }, (v15/*: any*/), (v16/*: any*/), (v7/*: any*/), (v17/*: any*/), { "alias": null, "args": null, "concreteType": "AuctionResultPriceRealized", "kind": "LinkedField", "name": "priceRealized", "plural": false, "selections": [ (v18/*: any*/), (v12/*: any*/), (v19/*: any*/) ], "storageKey": null }, (v20/*: any*/), (v21/*: any*/), (v6/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "comparableAuctionResults(first:3)" } ], "storageKey": null }, { "alias": null, "args": (v3/*: any*/), "concreteType": "Artist", "kind": "LinkedField", "name": "artist", "plural": false, "selections": [ (v22/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, (v4/*: any*/) ], "storageKey": null } ] }, "params": { "id": "947483109386ad8ff7057bbd29f7da2b", "metadata": { "relayTestingSelectionTypeInfo": { "artist": (v23/*: any*/), "artist.href": (v24/*: any*/), "artist.id": (v25/*: any*/), "artist.name": (v24/*: any*/), "auctionResult": (v26/*: any*/), "auctionResult.artistID": (v27/*: any*/), "auctionResult.boughtIn": (v28/*: any*/), "auctionResult.categoryText": (v24/*: any*/), "auctionResult.comparableAuctionResults": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionResultConnection" }, "auctionResult.comparableAuctionResults.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "AuctionResultEdge" }, "auctionResult.comparableAuctionResults.edges.cursor": (v27/*: any*/), "auctionResult.comparableAuctionResults.edges.node": (v26/*: any*/), "auctionResult.comparableAuctionResults.edges.node.artist": (v23/*: any*/), "auctionResult.comparableAuctionResults.edges.node.artist.id": (v25/*: any*/), "auctionResult.comparableAuctionResults.edges.node.artist.name": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.artistID": (v27/*: any*/), "auctionResult.comparableAuctionResults.edges.node.boughtIn": (v28/*: any*/), "auctionResult.comparableAuctionResults.edges.node.currency": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.dateText": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.estimate": (v29/*: any*/), "auctionResult.comparableAuctionResults.edges.node.estimate.low": (v30/*: any*/), "auctionResult.comparableAuctionResults.edges.node.id": (v25/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images": (v31/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images.thumbnail": (v32/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images.thumbnail.aspectRatio": (v33/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images.thumbnail.height": (v34/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images.thumbnail.url": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.images.thumbnail.width": (v34/*: any*/), "auctionResult.comparableAuctionResults.edges.node.internalID": (v25/*: any*/), "auctionResult.comparableAuctionResults.edges.node.mediumText": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.organization": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.performance": (v35/*: any*/), "auctionResult.comparableAuctionResults.edges.node.performance.mid": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.priceRealized": (v36/*: any*/), "auctionResult.comparableAuctionResults.edges.node.priceRealized.cents": (v30/*: any*/), "auctionResult.comparableAuctionResults.edges.node.priceRealized.display": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.priceRealized.displayUSD": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.saleDate": (v24/*: any*/), "auctionResult.comparableAuctionResults.edges.node.title": (v24/*: any*/), "auctionResult.currency": (v24/*: any*/), "auctionResult.dateText": (v24/*: any*/), "auctionResult.dimensionText": (v24/*: any*/), "auctionResult.dimensions": { "enumValues": null, "nullable": true, "plural": false, "type": "AuctionLotDimensions" }, "auctionResult.dimensions.height": (v30/*: any*/), "auctionResult.dimensions.width": (v30/*: any*/), "auctionResult.estimate": (v29/*: any*/), "auctionResult.estimate.display": (v24/*: any*/), "auctionResult.estimate.high": (v30/*: any*/), "auctionResult.estimate.low": (v30/*: any*/), "auctionResult.id": (v25/*: any*/), "auctionResult.images": (v31/*: any*/), "auctionResult.images.thumbnail": (v32/*: any*/), "auctionResult.images.thumbnail.aspectRatio": (v33/*: any*/), "auctionResult.images.thumbnail.height": (v34/*: any*/), "auctionResult.images.thumbnail.url": (v24/*: any*/), "auctionResult.images.thumbnail.width": (v34/*: any*/), "auctionResult.internalID": (v25/*: any*/), "auctionResult.location": (v24/*: any*/), "auctionResult.mediumText": (v24/*: any*/), "auctionResult.organization": (v24/*: any*/), "auctionResult.performance": (v35/*: any*/), "auctionResult.performance.mid": (v24/*: any*/), "auctionResult.priceRealized": (v36/*: any*/), "auctionResult.priceRealized.cents": (v30/*: any*/), "auctionResult.priceRealized.centsUSD": (v30/*: any*/), "auctionResult.priceRealized.display": (v24/*: any*/), "auctionResult.priceRealized.displayUSD": (v24/*: any*/), "auctionResult.saleDate": (v24/*: any*/), "auctionResult.saleTitle": (v24/*: any*/), "auctionResult.title": (v24/*: any*/) } }, "name": "AuctionResultTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '42d83eb35492ee598c741c20dc1235c5'; export default node;
the_stack
var Validation = require('../../src/validation/Validation.js'); var Validators = require('../../src/validation/BasicValidators.js'); var Utils = require('../../src/validation/Utils.js'); var sinon = require('sinon'); var expect = require('expect.js'); var _:UnderscoreStatic = require('underscore'); import Q = require('q'); interface IPerson{ Checked:boolean; FirstName:string; LastName:string; Job:string; } describe('notifications validation rules', function () { describe('simple property validators', function() { var callback = null; beforeEach(function() { //setup this.Data = {}; this.PersonValidator = personValidator.CreateRule("Person"); callback = sinon.spy(); this.PersonValidator.ValidationResult.Errors["FirstName"].ErrorsChanged.add(callback); this.PersonValidator.ValidationResult.Errors["LastName"].ErrorsChanged.add(callback); }); //create new validator for object with structure<IPerson> var personValidator = new Validation.AbstractValidator<IPerson>(); //basic validators var required =new Validators.RequiredValidator(); var maxLength = new Validators.MaxLengthValidator(15); //assigned validators to property personValidator.RuleFor("FirstName", required); personValidator.RuleFor("FirstName",maxLength); //assigned validators to property personValidator.RuleFor("LastName", required); personValidator.RuleFor("LastName",maxLength); it('fill correct data - no errors', function () { //when this.Data.FirstName = "John"; this.Data.LastName = "Smith"; //excercise var result = this.PersonValidator.Validate(this.Data); //verify by return result expect(result.HasErrors).to.equal(false); //verify by concrete validator properties expect(this.PersonValidator.ValidationResult.HasErrors).to.equal(false); //verify callback not called expect(callback.called).to.equal(false); //validator properties enables to check specific rule errors expect(result.Errors["FirstName"].ValidationFailures["required"].HasError).to.equal(false); expect(result.Errors["FirstName"].ValidationFailures["maxlength"].HasError).to.equal(false); expect(result.Errors["LastName"].ValidationFailures["required"].HasError).to.equal(false); expect(result.Errors["LastName"].ValidationFailures["maxlength"].HasError).to.equal(false); }); it('fill incorrect data - some errors', function () { //when this.Data.FirstName = ""; this.Data.LastName = "Smith toooooooooooooooooooooooooooooooo long"; //excercise var result = this.PersonValidator.Validate(this.Data); //verify by return result expect(result.HasErrors).to.equal(true); //verify by concrete validator properties expect(this.PersonValidator.ValidationResult.HasErrors).to.equal(true); //verify callback called expect(callback.called).to.equal(true); expect(callback.args[0][0].Name).to.equal("FirstName"); expect(callback.args[1][0].Name).to.equal("LastName"); //validator properties enables to check specific rule errors expect(result.Errors["FirstName"].ValidationFailures["required"].HasError).to.equal(true); expect(result.Errors["FirstName"].ValidationFailures["maxlength"].HasError).to.equal(false); expect(result.Errors["LastName"].ValidationFailures["required"].HasError).to.equal(false); expect(result.Errors["LastName"].ValidationFailures["maxlength"].HasError).to.equal(true); }); }); describe('simple async validators', function() { var callback = null; beforeEach(function(){ //setup this.Data = {}; this.PersonValidator = personValidator.CreateRule("Person"); callback = sinon.spy(); this.PersonValidator.ValidationResult.Errors["Job"].ErrorsChanged.add(callback); }); //create new validator for object with structure<IPerson> var personValidator = new Validation.AbstractValidator<IPerson>(); //async functions return list of values var optionsFce = function () { var deferral = Q.defer(); setTimeout(function () { deferral.resolve([ "business man", "unemployed", "construction worker", "programmer", "shop assistant" ]); }, 1000); return deferral.promise; }; //async basic validators - return true if specified param contains any value var param = new Validators.ContainsValidator(); param.Options = optionsFce(); //assigned validator to property personValidator.RuleFor("Job",param); it('fill correct data - no errors', function (done) { //when this.Data.Job = "programmer"; //excercise var promiseResult = this.PersonValidator.ValidateAsync(this.Data); var selfValidator = this.PersonValidator; promiseResult.then(function (response) { //verify by return result expect(response.HasErrors).to.equal(false); //verify by concrete validator properties expect(selfValidator.ValidationResult.HasErrors).to.equal(false); //verify callback not called expect(callback.called).to.equal(false); done(); }).done(null,done); }); it('fill incorrect data - some errors', function (done) { //when this.Data.Job ="unknow job"; //excercise var promiseResult = this.PersonValidator.ValidateAsync(this.Data); var selfValidator = this.PersonValidator; promiseResult.then(function (response) { //verify by return result expect(response.HasErrors).to.equal(true); //verify expect(selfValidator.ValidationResult.HasErrors).to.equal(true); //verify callback called var error = callback.args[0][0]; expect(error.Name).to.equal("Job"); expect(error.HasErrors).to.equal(true); done(); }).done(null,done); }); }); describe('shared validators', function() { var callback = null; beforeEach(function(){ //setup this.Data = {}; this.PersonValidator = personValidator.CreateRule("Person"); callback = sinon.spy(); this.PersonValidator.ValidationResult.Errors["OneSpaceForbidden"].ErrorsChanged.add(callback); }); //create new validator for object with structure<IPerson> var personValidator = new Validation.AbstractValidator<IPerson>(); //shared validation function var oneSpaceFce = function (args:any) { args.HasError = false; if (!this.Checked) return; if (this.FirstName.indexOf(' ') != -1 || this.LastName.indexOf(' ') != -1) { args.HasError = true; args.ErrorMessage = "Full name can contain only one space."; } }; //create named validation function var validatorFce = {Name: "OneSpaceForbidden", ValidationFce: oneSpaceFce}; //assign validation function to properties personValidator.ValidationFor("FirstName", validatorFce); personValidator.ValidationFor("LastName", validatorFce); it('fill correct data - no errors', function () { //when this.Data.Checked = true; this.Data.FirstName = "John"; this.Data.LastName = "Smith"; //excercise var result = this.PersonValidator.Validate(this.Data); //verify expect(result.HasErrors).to.equal(false); //verify callback not called expect(callback.called).to.equal(false); }); it('fill incorrect data - some errors', function () { //when this.Data.Checked = true; this.Data.FirstName = "John Junior"; this.Data.LastName = "Smith"; //excercise var result = this.PersonValidator.Validate(this.Data); //verify expect(result.HasErrors).to.equal(true); //verify callback called expect(callback.args[0][0].Name).to.equal("OneSpaceForbidden"); }); }); describe('shared validators - async', function() { var callback = sinon.spy(); beforeEach(function(){ //setup this.Data = {}; this.PersonValidator = personValidator.CreateRule("Person"); callback = sinon.spy(); this.PersonValidator.ValidationResult.Errors["OneSpaceForbidden"].ErrorsChanged.add(callback); }); //create new validator for object with structure<IPerson> var personValidator = new Validation.AbstractValidator<IPerson>(); //shared validation function var oneSpaceFce = function (args:any) { var deferred = Q.defer<any>(); var self = this; setTimeout(function () { args.HasError = false; args.ErrorMessage = ""; if (!self.Checked) { deferred.resolve(undefined); return; } if (self.FirstName.indexOf(' ') != -1 || self.LastName.indexOf(' ') != -1) { args.HasError = true; args.ErrorMessage = "Full name can contain only one space."; deferred.resolve(undefined); return; } deferred.resolve(undefined); },100); return deferred.promise; }; //create named validation function var validatorFce = {Name: "OneSpaceForbidden", AsyncValidationFce: oneSpaceFce}; //assign validation function to properties personValidator.ValidationFor("FirstName", validatorFce); personValidator.ValidationFor("LastName", validatorFce); it('fill correct data - no errors', function (done) { //when this.Data.Checked = true; this.Data.FirstName = "John"; this.Data.LastName = "Smith"; //excercise var promiseResult = this.PersonValidator.ValidateAsync(this.Data); var selfValidator = this.PersonValidator; promiseResult.then(function (response) { //verify expect(selfValidator.ValidationResult.HasErrors).to.equal(false); //verify callback called expect(callback.called).to.equal(false); done(); }).done(null,done); }); it('fill incorrect data - some errors', function (done) { //when this.Data.Checked = true; this.Data.FirstName = "John Junior"; this.Data.LastName = "Smith"; //excercise var promiseResult = this.PersonValidator.ValidateAsync(this.Data); var selfValidator = this.PersonValidator; promiseResult.then(function (response) { //verify expect(selfValidator.ValidationResult.HasErrors).to.equal(true); //verify callback called expect(callback.args[0][0].Name).to.equal("OneSpaceForbidden"); done(); }).done(null,done); }); }); describe("fill incorrect data - rule optional", function() { var callback = null; beforeEach(function(){ //setup this.Data = {}; this.PersonValidator = personValidator.CreateRule("Person"); callback = sinon.spy(); this.PersonValidator.ValidationResult.Errors["FirstName"].ErrorsChanged.add(callback); this.PersonValidator.ValidationResult.Errors["LastName"].ErrorsChanged.add(callback); //set rule optional when checked !=true; var optional = function () { return !this.Checked; }.bind(this.Data); this.PersonValidator.SetOptional(optional); this.Data.FirstName = ""; this.Data.LastName = "Smith toooooooooooooooooooooooooooooooo long"; }); //create new validator for object with structure<IPerson> var personValidator = new Validation.AbstractValidator<IPerson>(); //basic validators var required =new Validators.RequiredValidator(); var maxLength = new Validators.MaxLengthValidator(15); //assigned validators to property personValidator.RuleFor("FirstName", required); personValidator.RuleFor("FirstName",maxLength); //assigned validators to property personValidator.RuleFor("LastName", required); personValidator.RuleFor("LastName",maxLength); it('is optional -> no errors', function () { //when this.Data.Checked = false; //excercise var result = this.PersonValidator.Validate(this.Data); //verify expect(result.HasErrors).to.equal(false); //verify callback called expect(callback.called).to.equal(false); }); it('is not optional - some errors', function () { //when this.Data.Checked = true; //excercise var result = this.PersonValidator.Validate(this.Data); //verify expect(result.HasErrors).to.equal(true); //verify callback called expect(callback.args[0][0].Name).to.equal("FirstName"); expect(callback.args[1][0].Name).to.equal("LastName"); }); }); });
the_stack
import fs from "fs/promises"; import http from "http"; import { AddressInfo } from "net"; import path from "path"; import { text } from "stream/consumers"; import { setTimeout } from "timers/promises"; import { CachePlugin } from "@miniflare/cache"; import { BindingsPlugin, CorePlugin, MiniflareCore, MiniflareCoreContext, MiniflareCoreError, ReloadEvent, } from "@miniflare/core"; import { DurableObjectsPlugin } from "@miniflare/durable-objects"; import { HTTPPlugin, createServer } from "@miniflare/http-server"; import { KVPlugin } from "@miniflare/kv"; import { VMScriptRunner } from "@miniflare/runner-vm"; import { LogLevel, NoOpLog, StoredValueMeta } from "@miniflare/shared"; import { AsyncTestLog, MemoryStorageFactory, TestLog, TestPlugin, useMiniflare, useTmp, waitForReload, } from "@miniflare/shared-test"; import test, { Macro } from "ava"; import { MiniflareOptions } from "miniflare"; // Specific tests for `mounts` option const constantBodyScript = (body: string) => `addEventListener("fetch", (e) => e.respondWith(new Response("${body}")))`; test("MiniflareCore: #init: throws if mount has empty name", async (t) => { const mf = useMiniflare({}, { mounts: { "": {} } }); await t.throwsAsync(mf.getPlugins(), { instanceOf: MiniflareCoreError, code: "ERR_MOUNT_NO_NAME", message: "Mount name cannot be empty", }); }); test("MiniflareCore: #init: mounts string-optioned mounts", async (t) => { const tmp = await useTmp(t); const scriptPath = path.join(tmp, "worker.js"); const packagePath = path.join(tmp, "package.json"); const envPath = path.join(tmp, ".env"); const wranglerConfigPath = path.join(tmp, "wrangler.toml"); await fs.writeFile( scriptPath, "export default { fetch: (request, env) => new Response(`mounted:${env.KEY}`) }" ); await fs.writeFile(packagePath, '{ "module": "worker.js" }'); await fs.writeFile(envPath, "KEY=value"); await fs.writeFile( wranglerConfigPath, ` [build.upload] format = "modules" [miniflare] route = "localhost/tmp*" ` ); const mf = useMiniflare({ BindingsPlugin }, { watch: true, mounts: { tmp } }); let res = await mf.dispatchFetch("http://localhost/tmp"); t.is(await res.text(), "mounted:value"); // Check mounted worker files watched const reloadPromise = waitForReload(mf); await fs.writeFile(envPath, "KEY=value2"); await reloadPromise; res = await mf.dispatchFetch("http://localhost/tmp"); t.is(await res.text(), "mounted:value2"); }); test("MiniflareCore: #init: mounts object-optioned mounts", async (t) => { const mf = useMiniflare( {}, { script: 'addEventListener("fetch", (e) => e.respondWith(new Response("parent")))', mounts: { test: { modules: true, script: 'export default { fetch: () => new Response("mounted") }', routes: ["localhost/test*"], }, }, } ); let res = await mf.dispatchFetch("http://localhost"); t.is(await res.text(), "parent"); res = await mf.dispatchFetch("http://localhost/test"); t.is(await res.text(), "mounted"); }); test("MiniflareCore: #init: throws when attempting to mount recursively", async (t) => { const mf = useMiniflare( {}, // @ts-expect-error type definitions shouldn't allow this { mounts: { test: { mounts: { recursive: {} } } } } ); await t.throwsAsync(mf.getPlugins(), { instanceOf: MiniflareCoreError, code: "ERR_MOUNT_NESTED", message: "Nested mounts are unsupported", }); }); test("MiniflareCore: #init: updates existing mount options", async (t) => { const mf = useMiniflare( {}, { script: constantBodyScript("parent"), mounts: { a: { script: constantBodyScript("a1"), routes: ["localhost/a*"] }, }, } ); let res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "a1"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "parent"); await mf.setOptions({ mounts: { a: { script: constantBodyScript("a2"), routes: ["localhost/new-a*"] }, b: { script: constantBodyScript("b"), routes: ["localhost/b*"] }, }, }); res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "parent"); res = await mf.dispatchFetch("http://localhost/new-a"); t.is(await res.text(), "a2"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "b"); }); test("MiniflareCore: #init: reloads parent on all but initial mount reloads", async (t) => { const events: ReloadEvent<any>[] = []; const mf = useMiniflare( {}, { script: constantBodyScript("parent"), mounts: { test: { script: constantBodyScript("1"), routes: ["localhost/1*"], }, }, } ); mf.addEventListener("reload", (e) => events.push(e)); await mf.getPlugins(); t.is(events.length, 1); let res = await mf.dispatchFetch("http://localhost/1"); t.is(await res.text(), "1"); const mount = await mf.getMount("test"); await mount.setOptions({ script: constantBodyScript("2"), routes: ["localhost/2*"], }); await setTimeout(); // Wait for microtasks to finish t.is(events.length, 2); // Check routes reloaded too (even though we haven't called setOptions on parent) res = await mf.dispatchFetch("http://localhost/1"); t.is(await res.text(), "parent"); res = await mf.dispatchFetch("http://localhost/2"); t.is(await res.text(), "2"); }); test("MiniflareCore: #init: wraps error with mount name if mount setup throws", async (t) => { const mf = useMiniflare({}, { mounts: { test: { script: "(" } } }); let error: MiniflareCoreError | undefined; try { await mf.getPlugins(); } catch (e: any) { error = e; } t.is(error?.code, "ERR_MOUNT"); t.is(error?.message, 'Error mounting "test"'); t.is(error?.cause?.name, "SyntaxError"); }); test("MiniflareCore: #init: disposes removed mounts", async (t) => { const log = new TestLog(); const mf = useMiniflare( {}, { script: constantBodyScript("parent"), mounts: { a: { script: constantBodyScript("a"), routes: ["localhost/a*"] }, b: { script: constantBodyScript("b"), routes: ["localhost/b*"] }, }, }, log ); let res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "a"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "b"); log.logs = []; await mf.setOptions({ mounts: { b: { script: constantBodyScript("b") } }, }); t.true(log.logsAtLevel(LogLevel.DEBUG).includes('Unmounting "a"...')); res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "parent"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "b"); // Try removing mounts option completely log.logs = []; await mf.setOptions({ mounts: undefined }); t.true(log.logsAtLevel(LogLevel.DEBUG).includes('Unmounting "b"...')); res = await mf.dispatchFetch("http://localhost/a"); t.is(await res.text(), "parent"); res = await mf.dispatchFetch("http://localhost/b"); t.is(await res.text(), "parent"); }); test("MiniflareCore: #init: doesn't throw if script required, parent script not provided, but has mounts", async (t) => { const ctx: MiniflareCoreContext = { log: new NoOpLog(), storageFactory: new MemoryStorageFactory(), scriptRunner: new VMScriptRunner(), scriptRequired: true, }; const mf = new MiniflareCore({ CorePlugin }, ctx, { mounts: { a: { script: constantBodyScript("a") } }, }); await mf.getPlugins(); t.pass(); }); test("MiniflareCore: #init: logs reload errors when mount options update instead of unhandled rejection", async (t) => { const log = new AsyncTestLog(); const ctx: MiniflareCoreContext = { log, storageFactory: new MemoryStorageFactory(), scriptRunner: new VMScriptRunner(), }; const mf = new MiniflareCore({ CorePlugin, DurableObjectsPlugin }, ctx, { mounts: { a: { script: "//" } }, }); await mf.getPlugins(); // Simulate file change in mount that would throw const mount = await mf.getMount("a"); await mount.setOptions({ durableObjects: { TEST_OBJECT: "IDontExist" }, }); t.regex((await log.nextAtLevel(LogLevel.ERROR)) ?? "", /ERR_CLASS_NOT_FOUND/); }); test("MiniflareCore: #updateRouter: requires mounted name and service name to match", async (t) => { const mf = useMiniflare({}, { mounts: { a: { name: "b", script: "//" } } }); await t.throwsAsync(mf.getPlugins(), { instanceOf: MiniflareCoreError, code: "ERR_MOUNT_NAME_MISMATCH", message: 'Mounted name "a" must match service name "b"', }); }); test("MiniflareCore: #reload: includes mounts when calling plugin reload hooks", async (t) => { const mf = useMiniflare( { TestPlugin }, { mounts: { test: { modules: true, script: "export const thing = 42;" } } } ); const plugins = await mf.getPlugins(); t.is(plugins.TestPlugin.reloadMounts?.get("test")?.moduleExports?.thing, 42); }); test("MiniflareCore: #reload: runs all reload hooks after all workers reloaded", async (t) => { // This is required to allow mounts to access parent exports, or other mounts, // potentially in a cycle (e.g. service bindings) const constantExportScript = (x: string) => `export const x = ${JSON.stringify(x)};`; const log = new TestLog(); const mf = useMiniflare( { TestPlugin }, { name: "parent", modules: true, script: constantExportScript("parent"), hookLogIdentifier: "parent:", mounts: { a: { name: "a", modules: true, script: constantExportScript("a"), hookLogIdentifier: "a:", }, b: { name: "b", modules: true, script: constantExportScript("b"), hookLogIdentifier: "b:", }, }, }, log ); // Check on initial load await mf.getPlugins(); t.deepEqual(log.logsAtLevel(LogLevel.INFO), [ "parent:beforeSetup", "parent:setup", "a:beforeSetup", "a:setup", "a:beforeReload", // a beforeReload called, but not reload "Worker reloaded! (21B)", // a reload complete "b:beforeSetup", "b:setup", "b:beforeReload", // b beforeReload called, but not reload "Worker reloaded! (21B)", // b reload complete // All beforeReloads called... "parent:beforeReload", "a:beforeReload", "b:beforeReload", // ...followed by all reloads "parent:reload", "a:reload", "b:reload", "Worker reloaded! (26B)", // parent reload complete ]); // Check all exports included in mounts reload hooks called with let mounts = (await mf.getPlugins()).TestPlugin.reloadMounts; t.is(mounts?.get("parent")?.moduleExports?.x, "parent"); t.is(mounts?.get("a")?.moduleExports?.x, "a"); t.is(mounts?.get("b")?.moduleExports?.x, "b"); const a = await mf.getMount("a"); const b = await mf.getMount("b"); t.is((await a.getPlugins()).TestPlugin.reloadMounts, mounts); t.is((await b.getPlugins()).TestPlugin.reloadMounts, mounts); // Check when updating mount log.logs = []; await a.setOptions({ script: constantExportScript("a:updated") }); await waitForReload(mf); t.deepEqual(log.logsAtLevel(LogLevel.INFO), [ "a:beforeReload", // a beforeReload called, but not reload "Worker reloaded! (29B)", // a reload complete // All beforeReloads called... "parent:beforeReload", "a:beforeReload", "b:beforeReload", // ...followed by all reloads "parent:reload", "a:reload", "b:reload", "Worker reloaded! (26B)", // parent reload complete ]); // Check all exports included in mounts reload hooks called with again mounts = (await mf.getPlugins()).TestPlugin.reloadMounts; t.is(mounts?.get("parent")?.moduleExports?.x, "parent"); t.is(mounts?.get("a")?.moduleExports?.x, "a:updated"); t.is(mounts?.get("b")?.moduleExports?.x, "b"); t.is((await a.getPlugins()).TestPlugin.reloadMounts, mounts); t.is((await b.getPlugins()).TestPlugin.reloadMounts, mounts); }); test("MiniflareCore: getMount: gets mounted worker instance", async (t) => { const mf = useMiniflare( { BindingsPlugin }, { mounts: { test: { globals: { KEY: "value" } } } } ); const mount = await mf.getMount("test"); const globalScope = await mount.getGlobalScope(); t.is(globalScope.KEY, "value"); }); test("MiniflareCore: dispose: disposes of mounts too", async (t) => { const log = new TestLog(); const mf = useMiniflare({}, { mounts: { test: { script: "//" } } }, log); await mf.getPlugins(); t.deepEqual(log.logs, [ [LogLevel.DEBUG, "Initialising worker..."], [LogLevel.DEBUG, "Options:"], [LogLevel.DEBUG, "- Mounts: test"], [LogLevel.DEBUG, "Enabled Compatibility Flags: <none>"], [ LogLevel.WARN, "Mounts are experimental. There may be breaking changes in the future.", ], [LogLevel.VERBOSE, "- setup(CorePlugin)"], [LogLevel.DEBUG, 'Mounting "test"...'], [LogLevel.DEBUG, "Initialising worker..."], [LogLevel.DEBUG, "Options:"], [LogLevel.DEBUG, "Enabled Compatibility Flags: <none>"], [LogLevel.VERBOSE, "- setup(CorePlugin)"], [LogLevel.DEBUG, "Reloading worker..."], [LogLevel.VERBOSE, "Running script..."], [LogLevel.INFO, "Worker reloaded! (2B)"], [LogLevel.DEBUG, "Mount Routes: <none>"], [LogLevel.DEBUG, "Reloading worker..."], [LogLevel.INFO, "Worker reloaded!"], ]); log.logs = []; await mf.dispose(); t.deepEqual(log.logs, [[LogLevel.DEBUG, 'Unmounting "test"...']]); }); test("MiniflareCore: includes named parent worker when matching mount routes", async (t) => { const mf = useMiniflare( {}, { name: "parent", routes: ["localhost/api"], script: constantBodyScript("parent"), mounts: { a: { name: "a", routes: ["*localhost/api*"], // less specific than parent route script: constantBodyScript("a"), }, }, } ); // Check parent worker checked first let res = await mf.dispatchFetch("http://localhost/api"); t.is(await res.text(), "parent"); // Check mounted worker still accessible res = await mf.dispatchFetch("http://localhost/api2"); t.is(await res.text(), "a"); // Check fallback to parent worker res = await mf.dispatchFetch("http://localhost/notapi"); t.is(await res.text(), "parent"); }); test("MiniflareCore: uses original protocol and host when matching mount routes", async (t) => { const mf = useMiniflare( { HTTPPlugin }, { script: constantBodyScript("parent"), upstream: "https://miniflare.dev", mounts: { a: { modules: true, // Should use this upstream instead of parent upstream: "https://example.com", script: `export default { async fetch(request) { return new Response(\`\${request.url}:\${request.headers.get("host")}\`); } }`, // Should match against this host, not the upstream's routes: ["http://custom.mf/*"], }, }, } ); const server = await createServer(mf); const port = await new Promise<number>((resolve) => { server.listen(0, () => resolve((server.address() as AddressInfo).port)); }); const body = await new Promise<string>((resolve) => { http.get( { host: "localhost", port, path: "/a", headers: { host: "custom.mf" } }, async (res) => resolve(await text(res)) ); }); t.is(body, "https://example.com/a:custom.mf"); }); // Shared storage persistence tests type PersistOptions = Pick< MiniflareOptions, "kvPersist" | "cachePersist" | "durableObjectsPersist" >; const mountStorageMacro: Macro< [ parentPersist: PersistOptions | undefined, childPersist: PersistOptions | undefined, resolvedPersistFunction: ( tmp: string, mount: string ) => { kvPersist: string; cachePersist: string; durableObjectsPersist: string; } ] > = async (t, parentPersist, childPersist, resolvedPersistFunction) => { const tmp = await useTmp(t); const mount = path.join(tmp, "mount"); await fs.mkdir(mount); const scriptPath = path.join(mount, "worker.js"); const packagePath = path.join(mount, "package.json"); const wranglerConfigPath = path.join(mount, "wrangler.toml"); await fs.writeFile( scriptPath, ` export class TestObject { constructor(state) { this.storage = state.storage; } async fetch() { await this.storage.put("key", "value"); return new Response(); } } export default { async fetch(request, env) { const { TEST_NAMESPACE, TEST_OBJECT } = env; await TEST_NAMESPACE.put("key", "value"); await caches.default.put("http://localhost/", new Response("body", { headers: { "Cache-Control": "max-age=3600" } })); const id = TEST_OBJECT.idFromName("test"); const stub = TEST_OBJECT.get(id); await stub.fetch("http://localhost/"); return new Response(); } }` ); await fs.writeFile(packagePath, '{ "module": "worker.js" }'); let { kvPersist, cachePersist, durableObjectsPersist } = childPersist ?? {}; kvPersist &&= JSON.stringify(kvPersist); cachePersist &&= JSON.stringify(cachePersist); durableObjectsPersist &&= JSON.stringify(durableObjectsPersist); await fs.writeFile( wranglerConfigPath, ` kv_namespaces = [ { binding = "TEST_NAMESPACE" } ] [durable_objects] bindings = [ { name = "TEST_OBJECT", class_name = "TestObject" }, ] [build.upload] format = "modules" [miniflare] route = "localhost/mount*" ${kvPersist ? `kv_persist = ${kvPersist}` : ""} ${cachePersist ? `cache_persist = ${cachePersist}` : ""} ${ durableObjectsPersist ? `durable_objects_persist = ${durableObjectsPersist}` : "" } ` ); const kvMap = new Map<string, StoredValueMeta>(); const cacheMap = new Map<string, StoredValueMeta>(); const durableObjectsMap = new Map<string, StoredValueMeta>(); const resolvedPersist = resolvedPersistFunction(tmp, mount); const storageFactory = new MemoryStorageFactory({ [`${resolvedPersist.kvPersist}:TEST_NAMESPACE`]: kvMap, [`${resolvedPersist.cachePersist}:default`]: cacheMap, [`${resolvedPersist.durableObjectsPersist}:TEST_OBJECT:8f9973e23d7d465bb827b1ded10ae3e3d1e9b25f9e0763ab8ced46632d58ff07`]: durableObjectsMap, }); const mf = useMiniflare( { KVPlugin, CachePlugin, DurableObjectsPlugin }, { rootPath: tmp, ...parentPersist, mounts: { mount }, }, new NoOpLog(), storageFactory ); await mf.dispatchFetch("http://localhost/mount"); // Check data stored in persist maps t.is(kvMap.size, 1); t.is(cacheMap.size, 1); t.is(durableObjectsMap.size, 1); }; mountStorageMacro.title = (providedTitle) => `MiniflareCore: #init: ${providedTitle}`; // ...in parent test( "resolves boolean persistence in parent relative to working directory", mountStorageMacro, { kvPersist: true, cachePersist: true, durableObjectsPersist: true, }, undefined, () => ({ kvPersist: path.join(".mf", "kv"), cachePersist: path.join(".mf", "cache"), durableObjectsPersist: path.join(".mf", "durableobjects"), }) ); test( "resolves string persistence in parent relative to parent's root", mountStorageMacro, { kvPersist: "kv", cachePersist: "cache", durableObjectsPersist: "durable-objects", }, undefined, (tmp) => ({ kvPersist: path.join(tmp, "kv"), cachePersist: path.join(tmp, "cache"), durableObjectsPersist: path.join(tmp, "durable-objects"), }) ); test( "uses url persistence in parent as is", mountStorageMacro, { kvPersist: "test://kv", cachePersist: "test://cache", durableObjectsPersist: "test://durable-objects", }, undefined, () => ({ kvPersist: "test://kv", cachePersist: "test://cache", durableObjectsPersist: "test://durable-objects", }) ); // ...in mount test( "resolves boolean persistence in mount relative to working directory", mountStorageMacro, undefined, { kvPersist: true, cachePersist: true, durableObjectsPersist: true, }, () => ({ kvPersist: path.join(".mf", "kv"), cachePersist: path.join(".mf", "cache"), durableObjectsPersist: path.join(".mf", "durableobjects"), }) ); test( "resolves string persistence in mount relative to mount's root", mountStorageMacro, undefined, { kvPersist: "kv", cachePersist: "cache", durableObjectsPersist: "durable-objects", }, (tmp, mount) => ({ kvPersist: path.join(mount, "kv"), cachePersist: path.join(mount, "cache"), durableObjectsPersist: path.join(mount, "durable-objects"), }) ); test( "uses url persistence in mount as is", mountStorageMacro, undefined, { kvPersist: "test://kv", cachePersist: "test://cache", durableObjectsPersist: "test://durable-objects", }, () => ({ kvPersist: "test://kv", cachePersist: "test://cache", durableObjectsPersist: "test://durable-objects", }) ); // Durable Objects script_name integration tests test("MiniflareCore: reloads Durable Object classes used by parent when mounted worker reloads", async (t) => { const durableObjectScript = (body: string) => `export class TestObject { fetch() { return new Response("${body}"); } }`; const mf = useMiniflare( { DurableObjectsPlugin }, { modules: true, script: `export default { async fetch(request, { TEST_OBJECT }) { const id = TEST_OBJECT.idFromName("a"); const stub = TEST_OBJECT.get(id); return stub.fetch(request); } }`, durableObjects: { TEST_OBJECT: { className: "TestObject", scriptName: "test" }, }, mounts: { test: { modules: true, script: durableObjectScript("1") } }, } ); let res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "1"); // Update Durable Object script and check constructors in parent updated too const reloadPromise = waitForReload(mf); const mount = await mf.getMount("test"); await mount.setOptions({ script: durableObjectScript("2") }); await reloadPromise; res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "2"); }); test("MiniflareCore: runs mounted worker script for Durable Object classes used by parent if scriptRunForModuleExports set", async (t) => { const mf = new MiniflareCore( { CorePlugin, DurableObjectsPlugin }, { log: new NoOpLog(), storageFactory: new MemoryStorageFactory(), scriptRunner: new VMScriptRunner(), scriptRunForModuleExports: true, }, { modules: true, script: `export default { async fetch(request, { TEST_OBJECT }) { const id = TEST_OBJECT.idFromName("a"); const stub = TEST_OBJECT.get(id); return stub.fetch(request); } }`, durableObjects: { TEST_OBJECT: { className: "TestObject", scriptName: "test" }, }, mounts: { test: { modules: true, script: `export class TestObject { fetch() { return new Response("object"); } }`, }, }, } ); const res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "object"); }); test("MiniflareCore: can access Durable Objects defined in parent or other mounts in mount", async (t) => { const doScript = ( className: string, response: string ) => `export class ${className} { fetch() { return new Response("${response}"); } }`; const mf = new MiniflareCore( { CorePlugin, DurableObjectsPlugin }, { log: new NoOpLog(), storageFactory: new MemoryStorageFactory(), scriptRunner: new VMScriptRunner(), }, { name: "parent", modules: true, script: doScript("ParentObject", "parent object"), mounts: { a: { name: "a", modules: true, script: doScript("MountAObject", "mount a object"), }, b: { name: "b", durableObjects: { PARENT_OBJECT: { className: "ParentObject", scriptName: "parent" }, MOUNT_A_OBJECT: { className: "MountAObject", scriptName: "a" }, }, routes: ["*"], modules: true, script: `export default { async fetch(request, { PARENT_OBJECT, MOUNT_A_OBJECT }) { // Using named IDs to check object instances are reset const parentId = PARENT_OBJECT.idFromName("id"); const aId = MOUNT_A_OBJECT.idFromName("id"); const parentStub = PARENT_OBJECT.get(parentId); const aStub = MOUNT_A_OBJECT.get(aId); const parentRes = await parentStub.fetch("http://localhost/"); const aRes = await aStub.fetch("http://localhost/"); const parentText = await parentRes.text(); const aText = await aRes.text(); return new Response(parentText + ":" + aText); } }`, }, }, } ); let res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "parent object:mount a object"); // Check updates to mount A reflected in mount B const a = await mf.getMount("a"); await a.setOptions({ script: doScript("MountAObject", "mount a object 2") }); res = await mf.dispatchFetch("http://localhost/"); t.is(await res.text(), "parent object:mount a object 2"); // Check updates to parent reflected in mount B await mf.setOptions({ script: doScript("ParentObject", "parent object 2") }); res = await mf.dispatchFetch("http://localhost/"); // TODO (someday): this is a bug, should be "parent object 2:mount a object 2" // but setOptions in a mount doesn't update parent's previous options object. // setOptions in mounts shouldn't really be exposed to end-users, it's only // meant for testing. t.is(await res.text(), "parent object 2:mount a object"); });
the_stack
import { RegexSource, mergeObjects, basename, escapeRegExpCharacters, OrMask } from './utils'; import { IOnigLib, OnigScanner, IOnigCaptureIndex, FindOption, IOnigMatch, OnigString } from './onigLib'; import { ILocation, IRawGrammar, IRawRepository, IRawRule, IRawCaptures } from './rawGrammar'; import { IncludeReferenceKind, parseInclude } from './grammar/grammarDependencies'; const HAS_BACK_REFERENCES = /\\(\d+)/; const BACK_REFERENCING_END = /\\(\d+)/g; const ruleIdSymbol = Symbol('RuleId'); export type RuleId = { __brand: typeof ruleIdSymbol }; // This is a special constant to indicate that the end regexp matched. export const endRuleId = -1; // This is a special constant to indicate that the while regexp matched. export const whileRuleId = -2; export function ruleIdFromNumber(id: number): RuleId { return id as any as RuleId; } export function ruleIdToNumber(id: RuleId): number { return id as any as number; } export interface IRuleRegistry { getRule(ruleId: RuleId): Rule; registerRule<T extends Rule>(factory: (id: RuleId) => T): T; } export interface IGrammarRegistry { getExternalGrammar(scopeName: string, repository: IRawRepository): IRawGrammar | null | undefined; } export interface IRuleFactoryHelper extends IRuleRegistry, IGrammarRegistry { } export abstract class Rule { public readonly $location: ILocation | undefined; public readonly id: RuleId; private readonly _nameIsCapturing: boolean; private readonly _name: string | null; private readonly _contentNameIsCapturing: boolean; private readonly _contentName: string | null; constructor($location: ILocation | undefined, id: RuleId, name: string | null | undefined, contentName: string | null | undefined) { this.$location = $location; this.id = id; this._name = name || null; this._nameIsCapturing = RegexSource.hasCaptures(this._name); this._contentName = contentName || null; this._contentNameIsCapturing = RegexSource.hasCaptures(this._contentName); } public abstract dispose(): void; public get debugName(): string { const location = this.$location ? `${basename(this.$location.filename)}:${this.$location.line}` : 'unknown'; return `${(<any>this.constructor).name}#${this.id} @ ${location}`; } public getName(lineText: string | null, captureIndices: IOnigCaptureIndex[] | null): string | null { if (!this._nameIsCapturing || this._name === null || lineText === null || captureIndices === null) { return this._name; } return RegexSource.replaceCaptures(this._name, lineText, captureIndices); } public getContentName(lineText: string, captureIndices: IOnigCaptureIndex[]): string | null { if (!this._contentNameIsCapturing || this._contentName === null) { return this._contentName; } return RegexSource.replaceCaptures(this._contentName, lineText, captureIndices); } public abstract collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList): void; public abstract compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string | null): CompiledRule; public abstract compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string | null, allowA: boolean, allowG: boolean): CompiledRule; } export interface ICompilePatternsResult { readonly patterns: RuleId[]; readonly hasMissingPatterns: boolean; } export class CaptureRule extends Rule { public readonly retokenizeCapturedWithRuleId: RuleId | 0; constructor($location: ILocation | undefined, id: RuleId, name: string | null | undefined, contentName: string | null | undefined, retokenizeCapturedWithRuleId: RuleId | 0) { super($location, id, name, contentName); this.retokenizeCapturedWithRuleId = retokenizeCapturedWithRuleId; } public dispose(): void { // nothing to dispose } public collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList) { throw new Error('Not supported!'); } public compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): CompiledRule { throw new Error('Not supported!'); } public compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string, allowA: boolean, allowG: boolean): CompiledRule { throw new Error('Not supported!'); } } export class MatchRule extends Rule { private readonly _match: RegExpSource; public readonly captures: (CaptureRule | null)[]; private _cachedCompiledPatterns: RegExpSourceList | null; constructor($location: ILocation | undefined, id: RuleId, name: string | undefined, match: string, captures: (CaptureRule | null)[]) { super($location, id, name, null); this._match = new RegExpSource(match, this.id); this.captures = captures; this._cachedCompiledPatterns = null; } public dispose(): void { if (this._cachedCompiledPatterns) { this._cachedCompiledPatterns.dispose(); this._cachedCompiledPatterns = null; } } public get debugMatchRegExp(): string { return `${this._match.source}`; } public collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList) { out.push(this._match); } public compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): CompiledRule { return this._getCachedCompiledPatterns(grammar).compile(grammar); } public compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string, allowA: boolean, allowG: boolean): CompiledRule { return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG); } private _getCachedCompiledPatterns(grammar: IRuleRegistry & IOnigLib): RegExpSourceList { if (!this._cachedCompiledPatterns) { this._cachedCompiledPatterns = new RegExpSourceList(); this.collectPatterns(grammar, this._cachedCompiledPatterns); } return this._cachedCompiledPatterns; } } export class IncludeOnlyRule extends Rule { public readonly hasMissingPatterns: boolean; public readonly patterns: RuleId[]; private _cachedCompiledPatterns: RegExpSourceList | null; constructor($location: ILocation | undefined, id: RuleId, name: string | null | undefined, contentName: string | null | undefined, patterns: ICompilePatternsResult) { super($location, id, name, contentName); this.patterns = patterns.patterns; this.hasMissingPatterns = patterns.hasMissingPatterns; this._cachedCompiledPatterns = null; } public dispose(): void { if (this._cachedCompiledPatterns) { this._cachedCompiledPatterns.dispose(); this._cachedCompiledPatterns = null; } } public collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList) { for (const pattern of this.patterns) { const rule = grammar.getRule(pattern); rule.collectPatterns(grammar, out); } } public compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): CompiledRule { return this._getCachedCompiledPatterns(grammar).compile(grammar); } public compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string, allowA: boolean, allowG: boolean): CompiledRule { return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG); } private _getCachedCompiledPatterns(grammar: IRuleRegistry & IOnigLib): RegExpSourceList { if (!this._cachedCompiledPatterns) { this._cachedCompiledPatterns = new RegExpSourceList(); this.collectPatterns(grammar, this._cachedCompiledPatterns); } return this._cachedCompiledPatterns; } } export class BeginEndRule extends Rule { private readonly _begin: RegExpSource; public readonly beginCaptures: (CaptureRule | null)[]; private readonly _end: RegExpSource; public readonly endHasBackReferences: boolean; public readonly endCaptures: (CaptureRule | null)[]; public readonly applyEndPatternLast: boolean; public readonly hasMissingPatterns: boolean; public readonly patterns: RuleId[]; private _cachedCompiledPatterns: RegExpSourceList | null; constructor($location: ILocation | undefined, id: RuleId, name: string | null | undefined, contentName: string | null | undefined, begin: string, beginCaptures: (CaptureRule | null)[], end: string | undefined, endCaptures: (CaptureRule | null)[], applyEndPatternLast: boolean | undefined, patterns: ICompilePatternsResult) { super($location, id, name, contentName); this._begin = new RegExpSource(begin, this.id); this.beginCaptures = beginCaptures; this._end = new RegExpSource(end ? end : '\uFFFF', -1); this.endHasBackReferences = this._end.hasBackReferences; this.endCaptures = endCaptures; this.applyEndPatternLast = applyEndPatternLast || false; this.patterns = patterns.patterns; this.hasMissingPatterns = patterns.hasMissingPatterns; this._cachedCompiledPatterns = null; } public dispose(): void { if (this._cachedCompiledPatterns) { this._cachedCompiledPatterns.dispose(); this._cachedCompiledPatterns = null; } } public get debugBeginRegExp(): string { return `${this._begin.source}`; } public get debugEndRegExp(): string { return `${this._end.source}`; } public getEndWithResolvedBackReferences(lineText: string, captureIndices: IOnigCaptureIndex[]): string { return this._end.resolveBackReferences(lineText, captureIndices); } public collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList) { out.push(this._begin); } public compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): CompiledRule { return this._getCachedCompiledPatterns(grammar, endRegexSource).compile(grammar); } public compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string, allowA: boolean, allowG: boolean): CompiledRule { return this._getCachedCompiledPatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG); } private _getCachedCompiledPatterns(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): RegExpSourceList { if (!this._cachedCompiledPatterns) { this._cachedCompiledPatterns = new RegExpSourceList(); for (const pattern of this.patterns) { const rule = grammar.getRule(pattern); rule.collectPatterns(grammar, this._cachedCompiledPatterns); } if (this.applyEndPatternLast) { this._cachedCompiledPatterns.push(this._end.hasBackReferences ? this._end.clone() : this._end); } else { this._cachedCompiledPatterns.unshift(this._end.hasBackReferences ? this._end.clone() : this._end); } } if (this._end.hasBackReferences) { if (this.applyEndPatternLast) { this._cachedCompiledPatterns.setSource(this._cachedCompiledPatterns.length() - 1, endRegexSource); } else { this._cachedCompiledPatterns.setSource(0, endRegexSource); } } return this._cachedCompiledPatterns; } } export class BeginWhileRule extends Rule { private readonly _begin: RegExpSource; public readonly beginCaptures: (CaptureRule | null)[]; public readonly whileCaptures: (CaptureRule | null)[]; private readonly _while: RegExpSource<RuleId | typeof whileRuleId>; public readonly whileHasBackReferences: boolean; public readonly hasMissingPatterns: boolean; public readonly patterns: RuleId[]; private _cachedCompiledPatterns: RegExpSourceList | null; private _cachedCompiledWhilePatterns: RegExpSourceList<RuleId | typeof whileRuleId> | null; constructor($location: ILocation | undefined, id: RuleId, name: string | null | undefined, contentName: string | null | undefined, begin: string, beginCaptures: (CaptureRule | null)[], _while: string, whileCaptures: (CaptureRule | null)[], patterns: ICompilePatternsResult) { super($location, id, name, contentName); this._begin = new RegExpSource(begin, this.id); this.beginCaptures = beginCaptures; this.whileCaptures = whileCaptures; this._while = new RegExpSource(_while, whileRuleId); this.whileHasBackReferences = this._while.hasBackReferences; this.patterns = patterns.patterns; this.hasMissingPatterns = patterns.hasMissingPatterns; this._cachedCompiledPatterns = null; this._cachedCompiledWhilePatterns = null; } public dispose(): void { if (this._cachedCompiledPatterns) { this._cachedCompiledPatterns.dispose(); this._cachedCompiledPatterns = null; } if (this._cachedCompiledWhilePatterns) { this._cachedCompiledWhilePatterns.dispose(); this._cachedCompiledWhilePatterns = null; } } public get debugBeginRegExp(): string { return `${this._begin.source}`; } public get debugWhileRegExp(): string { return `${this._while.source}`; } public getWhileWithResolvedBackReferences(lineText: string, captureIndices: IOnigCaptureIndex[]): string { return this._while.resolveBackReferences(lineText, captureIndices); } public collectPatterns(grammar: IRuleRegistry, out: RegExpSourceList) { out.push(this._begin); } public compile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string): CompiledRule { return this._getCachedCompiledPatterns(grammar).compile(grammar); } public compileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string, allowA: boolean, allowG: boolean): CompiledRule { return this._getCachedCompiledPatterns(grammar).compileAG(grammar, allowA, allowG); } private _getCachedCompiledPatterns(grammar: IRuleRegistry & IOnigLib): RegExpSourceList { if (!this._cachedCompiledPatterns) { this._cachedCompiledPatterns = new RegExpSourceList(); for (const pattern of this.patterns) { const rule = grammar.getRule(pattern); rule.collectPatterns(grammar, this._cachedCompiledPatterns); } } return this._cachedCompiledPatterns; } public compileWhile(grammar: IRuleRegistry & IOnigLib, endRegexSource: string | null): CompiledRule<RuleId | typeof whileRuleId> { return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compile(grammar); } public compileWhileAG(grammar: IRuleRegistry & IOnigLib, endRegexSource: string | null, allowA: boolean, allowG: boolean): CompiledRule<RuleId | typeof whileRuleId> { return this._getCachedCompiledWhilePatterns(grammar, endRegexSource).compileAG(grammar, allowA, allowG); } private _getCachedCompiledWhilePatterns(grammar: IRuleRegistry & IOnigLib, endRegexSource: string | null): RegExpSourceList<RuleId | typeof whileRuleId> { if (!this._cachedCompiledWhilePatterns) { this._cachedCompiledWhilePatterns = new RegExpSourceList<RuleId | typeof whileRuleId>(); this._cachedCompiledWhilePatterns.push(this._while.hasBackReferences ? this._while.clone() : this._while); } if (this._while.hasBackReferences) { this._cachedCompiledWhilePatterns.setSource(0, endRegexSource ? endRegexSource : '\uFFFF'); } return this._cachedCompiledWhilePatterns; } } export class RuleFactory { public static createCaptureRule(helper: IRuleFactoryHelper, $location: ILocation | undefined, name: string | null | undefined, contentName: string | null | undefined, retokenizeCapturedWithRuleId: RuleId | 0): CaptureRule { return helper.registerRule((id) => { return new CaptureRule($location, id, name, contentName, retokenizeCapturedWithRuleId); }); } public static getCompiledRuleId(desc: IRawRule, helper: IRuleFactoryHelper, repository: IRawRepository): RuleId { if (!desc.id) { helper.registerRule((id) => { desc.id = id; if (desc.match) { return new MatchRule( desc.$vscodeTextmateLocation, desc.id, desc.name, desc.match, RuleFactory._compileCaptures(desc.captures, helper, repository) ); } if (typeof desc.begin === 'undefined') { if (desc.repository) { repository = mergeObjects({}, repository, desc.repository); } let patterns = desc.patterns; if (typeof patterns === 'undefined' && desc.include) { patterns = [{ include: desc.include }]; } return new IncludeOnlyRule( desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, RuleFactory._compilePatterns(patterns, helper, repository) ); } if (desc.while) { return new BeginWhileRule( desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, desc.begin, RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository), desc.while, RuleFactory._compileCaptures(desc.whileCaptures || desc.captures, helper, repository), RuleFactory._compilePatterns(desc.patterns, helper, repository) ); } return new BeginEndRule( desc.$vscodeTextmateLocation, desc.id, desc.name, desc.contentName, desc.begin, RuleFactory._compileCaptures(desc.beginCaptures || desc.captures, helper, repository), desc.end, RuleFactory._compileCaptures(desc.endCaptures || desc.captures, helper, repository), desc.applyEndPatternLast, RuleFactory._compilePatterns(desc.patterns, helper, repository) ); }); } return desc.id!; } private static _compileCaptures(captures: IRawCaptures | undefined, helper: IRuleFactoryHelper, repository: IRawRepository): (CaptureRule | null)[] { let r: (CaptureRule | null)[] = []; if (captures) { // Find the maximum capture id let maximumCaptureId = 0; for (const captureId in captures) { if (captureId === '$vscodeTextmateLocation') { continue; } const numericCaptureId = parseInt(captureId, 10); if (numericCaptureId > maximumCaptureId) { maximumCaptureId = numericCaptureId; } } // Initialize result for (let i = 0; i <= maximumCaptureId; i++) { r[i] = null; } // Fill out result for (const captureId in captures) { if (captureId === '$vscodeTextmateLocation') { continue; } const numericCaptureId = parseInt(captureId, 10); let retokenizeCapturedWithRuleId: RuleId | 0 = 0; if (captures[captureId].patterns) { retokenizeCapturedWithRuleId = RuleFactory.getCompiledRuleId(captures[captureId], helper, repository); } r[numericCaptureId] = RuleFactory.createCaptureRule(helper, captures[captureId].$vscodeTextmateLocation, captures[captureId].name, captures[captureId].contentName, retokenizeCapturedWithRuleId); } } return r; } private static _compilePatterns(patterns: IRawRule[] | undefined, helper: IRuleFactoryHelper, repository: IRawRepository): ICompilePatternsResult { let r: RuleId[] = []; if (patterns) { for (let i = 0, len = patterns.length; i < len; i++) { const pattern = patterns[i]; let ruleId: RuleId | -1 = -1; if (pattern.include) { const reference = parseInclude(pattern.include); switch (reference.kind) { case IncludeReferenceKind.Base: case IncludeReferenceKind.Self: ruleId = RuleFactory.getCompiledRuleId(repository[pattern.include], helper, repository); break; case IncludeReferenceKind.RelativeReference: // Local include found in `repository` let localIncludedRule = repository[reference.ruleName]; if (localIncludedRule) { ruleId = RuleFactory.getCompiledRuleId(localIncludedRule, helper, repository); } else { // console.warn('CANNOT find rule for scopeName: ' + pattern.include + ', I am: ', repository['$base'].name); } break; case IncludeReferenceKind.TopLevelReference: case IncludeReferenceKind.TopLevelRepositoryReference: const externalGrammarName = reference.scopeName; const externalGrammarInclude = reference.kind === IncludeReferenceKind.TopLevelRepositoryReference ? reference.ruleName : null; // External include const externalGrammar = helper.getExternalGrammar(externalGrammarName, repository); if (externalGrammar) { if (externalGrammarInclude) { let externalIncludedRule = externalGrammar.repository[externalGrammarInclude]; if (externalIncludedRule) { ruleId = RuleFactory.getCompiledRuleId(externalIncludedRule, helper, externalGrammar.repository); } else { // console.warn('CANNOT find rule for scopeName: ' + pattern.include + ', I am: ', repository['$base'].name); } } else { ruleId = RuleFactory.getCompiledRuleId(externalGrammar.repository.$self, helper, externalGrammar.repository); } } else { // console.warn('CANNOT find grammar for scopeName: ' + pattern.include + ', I am: ', repository['$base'].name); } break; } } else { ruleId = RuleFactory.getCompiledRuleId(pattern, helper, repository); } if (ruleId !== -1) { const rule = helper.getRule(ruleId); let skipRule = false; if (rule instanceof IncludeOnlyRule || rule instanceof BeginEndRule || rule instanceof BeginWhileRule) { if (rule.hasMissingPatterns && rule.patterns.length === 0) { skipRule = true; } } if (skipRule) { // console.log('REMOVING RULE ENTIRELY DUE TO EMPTY PATTERNS THAT ARE MISSING'); continue; } r.push(ruleId); } } } return { patterns: r, hasMissingPatterns: ((patterns ? patterns.length : 0) !== r.length) }; } } interface IRegExpSourceAnchorCache { readonly A0_G0: string; readonly A0_G1: string; readonly A1_G0: string; readonly A1_G1: string; } export class RegExpSource<TRuleId = RuleId | typeof endRuleId> { public source: string; public readonly ruleId: TRuleId; public hasAnchor: boolean; public readonly hasBackReferences: boolean; private _anchorCache: IRegExpSourceAnchorCache | null; constructor(regExpSource: string, ruleId: TRuleId) { if (regExpSource) { const len = regExpSource.length; let lastPushedPos = 0; let output: string[] = []; let hasAnchor = false; for (let pos = 0; pos < len; pos++) { const ch = regExpSource.charAt(pos); if (ch === '\\') { if (pos + 1 < len) { const nextCh = regExpSource.charAt(pos + 1); if (nextCh === 'z') { output.push(regExpSource.substring(lastPushedPos, pos)); output.push('$(?!\\n)(?<!\\n)'); lastPushedPos = pos + 2; } else if (nextCh === 'A' || nextCh === 'G') { hasAnchor = true; } pos++; } } } this.hasAnchor = hasAnchor; if (lastPushedPos === 0) { // No \z hit this.source = regExpSource; } else { output.push(regExpSource.substring(lastPushedPos, len)); this.source = output.join(''); } } else { this.hasAnchor = false; this.source = regExpSource; } if (this.hasAnchor) { this._anchorCache = this._buildAnchorCache(); } else { this._anchorCache = null; } this.ruleId = ruleId; this.hasBackReferences = HAS_BACK_REFERENCES.test(this.source); // console.log('input: ' + regExpSource + ' => ' + this.source + ', ' + this.hasAnchor); } public clone(): RegExpSource<TRuleId> { return new RegExpSource(this.source, this.ruleId); } public setSource(newSource: string): void { if (this.source === newSource) { return; } this.source = newSource; if (this.hasAnchor) { this._anchorCache = this._buildAnchorCache(); } } public resolveBackReferences(lineText: string, captureIndices: IOnigCaptureIndex[]): string { let capturedValues = captureIndices.map((capture) => { return lineText.substring(capture.start, capture.end); }); BACK_REFERENCING_END.lastIndex = 0; return this.source.replace(BACK_REFERENCING_END, (match, g1) => { return escapeRegExpCharacters(capturedValues[parseInt(g1, 10)] || ''); }); } private _buildAnchorCache(): IRegExpSourceAnchorCache { let A0_G0_result: string[] = []; let A0_G1_result: string[] = []; let A1_G0_result: string[] = []; let A1_G1_result: string[] = []; let pos: number, len: number, ch: string, nextCh: string; for (pos = 0, len = this.source.length; pos < len; pos++) { ch = this.source.charAt(pos); A0_G0_result[pos] = ch; A0_G1_result[pos] = ch; A1_G0_result[pos] = ch; A1_G1_result[pos] = ch; if (ch === '\\') { if (pos + 1 < len) { nextCh = this.source.charAt(pos + 1); if (nextCh === 'A') { A0_G0_result[pos + 1] = '\uFFFF'; A0_G1_result[pos + 1] = '\uFFFF'; A1_G0_result[pos + 1] = 'A'; A1_G1_result[pos + 1] = 'A'; } else if (nextCh === 'G') { A0_G0_result[pos + 1] = '\uFFFF'; A0_G1_result[pos + 1] = 'G'; A1_G0_result[pos + 1] = '\uFFFF'; A1_G1_result[pos + 1] = 'G'; } else { A0_G0_result[pos + 1] = nextCh; A0_G1_result[pos + 1] = nextCh; A1_G0_result[pos + 1] = nextCh; A1_G1_result[pos + 1] = nextCh; } pos++; } } } return { A0_G0: A0_G0_result.join(''), A0_G1: A0_G1_result.join(''), A1_G0: A1_G0_result.join(''), A1_G1: A1_G1_result.join('') }; } public resolveAnchors(allowA: boolean, allowG: boolean): string { if (!this.hasAnchor || !this._anchorCache) { return this.source; } if (allowA) { if (allowG) { return this._anchorCache.A1_G1; } else { return this._anchorCache.A1_G0; } } else { if (allowG) { return this._anchorCache.A0_G1; } else { return this._anchorCache.A0_G0; } } } } interface IRegExpSourceListAnchorCache<TRuleId> { A0_G0: CompiledRule<TRuleId> | null; A0_G1: CompiledRule<TRuleId> | null; A1_G0: CompiledRule<TRuleId> | null; A1_G1: CompiledRule<TRuleId> | null; } export class RegExpSourceList<TRuleId = RuleId | typeof endRuleId> { private readonly _items: RegExpSource<TRuleId>[]; private _hasAnchors: boolean; private _cached: CompiledRule<TRuleId> | null; private _anchorCache: IRegExpSourceListAnchorCache<TRuleId>; constructor() { this._items = []; this._hasAnchors = false; this._cached = null; this._anchorCache = { A0_G0: null, A0_G1: null, A1_G0: null, A1_G1: null }; } public dispose(): void { this._disposeCaches(); } private _disposeCaches(): void { if (this._cached) { this._cached.dispose(); this._cached = null; } if (this._anchorCache.A0_G0) { this._anchorCache.A0_G0.dispose(); this._anchorCache.A0_G0 = null; } if (this._anchorCache.A0_G1) { this._anchorCache.A0_G1.dispose(); this._anchorCache.A0_G1 = null; } if (this._anchorCache.A1_G0) { this._anchorCache.A1_G0.dispose(); this._anchorCache.A1_G0 = null; } if (this._anchorCache.A1_G1) { this._anchorCache.A1_G1.dispose(); this._anchorCache.A1_G1 = null; } } public push(item: RegExpSource<TRuleId>): void { this._items.push(item); this._hasAnchors = this._hasAnchors || item.hasAnchor; } public unshift(item: RegExpSource<TRuleId>): void { this._items.unshift(item); this._hasAnchors = this._hasAnchors || item.hasAnchor; } public length(): number { return this._items.length; } public setSource(index: number, newSource: string): void { if (this._items[index].source !== newSource) { // bust the cache this._disposeCaches(); this._items[index].setSource(newSource); } } public compile(onigLib: IOnigLib): CompiledRule<TRuleId> { if (!this._cached) { let regExps = this._items.map(e => e.source); this._cached = new CompiledRule<TRuleId>(onigLib, regExps, this._items.map(e => e.ruleId)); } return this._cached; } public compileAG(onigLib: IOnigLib, allowA: boolean, allowG: boolean): CompiledRule<TRuleId> { if (!this._hasAnchors) { return this.compile(onigLib); } else { if (allowA) { if (allowG) { if (!this._anchorCache.A1_G1) { this._anchorCache.A1_G1 = this._resolveAnchors(onigLib, allowA, allowG); } return this._anchorCache.A1_G1; } else { if (!this._anchorCache.A1_G0) { this._anchorCache.A1_G0 = this._resolveAnchors(onigLib, allowA, allowG); } return this._anchorCache.A1_G0; } } else { if (allowG) { if (!this._anchorCache.A0_G1) { this._anchorCache.A0_G1 = this._resolveAnchors(onigLib, allowA, allowG); } return this._anchorCache.A0_G1; } else { if (!this._anchorCache.A0_G0) { this._anchorCache.A0_G0 = this._resolveAnchors(onigLib, allowA, allowG); } return this._anchorCache.A0_G0; } } } } private _resolveAnchors(onigLib: IOnigLib, allowA: boolean, allowG: boolean): CompiledRule<TRuleId> { let regExps = this._items.map(e => e.resolveAnchors(allowA, allowG)); return new CompiledRule(onigLib, regExps, this._items.map(e => e.ruleId)); } } export class CompiledRule<TRuleId = RuleId | typeof endRuleId> { private readonly scanner: OnigScanner; constructor(onigLib: IOnigLib, private readonly regExps: string[], private readonly rules: TRuleId[]) { this.scanner = onigLib.createOnigScanner(regExps); } public dispose(): void { if (typeof this.scanner.dispose === "function") { this.scanner.dispose(); } } toString(): string { const r: string[] = []; for (let i = 0, len = this.rules.length; i < len; i++) { r.push(" - " + this.rules[i] + ": " + this.regExps[i]); } return r.join("\n"); } findNextMatchSync( string: string | OnigString, startPosition: number, options: OrMask<FindOption> ): IFindNextMatchResult<TRuleId> | null { const result = this.scanner.findNextMatchSync(string, startPosition, options); if (!result) { return null; } return { ruleId: this.rules[result.index], captureIndices: result.captureIndices, }; } } export interface IFindNextMatchResult<TRuleId = RuleId | typeof endRuleId> { ruleId: TRuleId; captureIndices: IOnigCaptureIndex[]; }
the_stack
import { Response, Request, Router } from 'express'; import fs from 'fs'; import path from 'path'; import { URL } from 'url'; import zlib from 'zlib'; import { ReposAppRequest, IAppSession, IReposError } from './interfaces'; import { getProviders } from './transitional'; export function daysInMilliseconds(days: number): number { return 1000 * 60 * 60 * 24 * days; } export function stringOrNumberAsString(value: any) { if (typeof (value) === 'number') { return (value as number).toString(); } else if (typeof (value) === 'string') { return value; } const typeName = typeof (value); throw new Error(`Unsupported type ${typeName} for value ${value} (stringOrNumberAsString)`); } export function stringOrNumberArrayAsStringArray(values: any[]) { return values.map(val => stringOrNumberAsString(val)); } export function requireJson(nameFromRoot: string): any { // In some situations TypeScript can load from JSON, but for the transition this is better to reach outside the out directory let file = path.resolve(__dirname, nameFromRoot); // If within the output directory if (fs.existsSync(file)) { const content = fs.readFileSync(file, 'utf8'); return JSON.parse(content); } file = path.resolve(__dirname, '..', nameFromRoot); if (!fs.existsSync(file)) { throw new Error(`Cannot find JSON file ${file} to read as a module`); } const content = fs.readFileSync(file, 'utf8'); console.warn(`JSON as module (${file}) from project root (NOT TypeScript 'dist' folder)`); return JSON.parse(content); } // ---------------------------------------------------------------------------- // Returns an integer, random, between low and high (exclusive) - [low, high) // ---------------------------------------------------------------------------- export function randomInteger(low: number, high: number) { return Math.floor(Math.random() * (high - low) + low); }; export function safeLocalRedirectUrl(path: string) { if (!path) { return; } const url = new URL(path, 'http://localhost'); if (url.host !== 'localhost') { return; } return url.search ? `${url.pathname}${url.search}` : url.pathname; } // ---------------------------------------------------------------------------- // Session utility: Store the referral URL, if present, and redirect to a new // location. // ---------------------------------------------------------------------------- interface IStoreReferrerEventDetails { method: string; reason: string; referer?: string; redirect?: string; } export function storeReferrer(req: ReposAppRequest, res, redirect, optionalReason) { const { insights } = getProviders(req); const eventDetails: IStoreReferrerEventDetails = { method: 'storeReferrer', reason: optionalReason || 'unknown reason', }; const session = req.session as IAppSession; if (session && req.headers && req.headers.referer && session.referer !== undefined && !req.headers.referer.includes('/signout') && !session.referer) { session.referer = req.headers.referer; eventDetails.referer = req.headers.referer; } if (redirect) { eventDetails.redirect = redirect; insights?.trackEvent({ name: 'RedirectWithReferrer', properties: eventDetails }); res.redirect(redirect); } }; export function sortByCaseInsensitive(a: string, b: string) { let nameA = a.toLowerCase(); let nameB = b.toLowerCase(); if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } return 0; } // ---------------------------------------------------------------------------- // Session utility: store the original URL // ---------------------------------------------------------------------------- export function storeOriginalUrlAsReferrer(req: Request, res: Response, redirect: string, optionalReason?: string) { storeOriginalUrlAsVariable(req, res, 'referer', redirect, optionalReason); }; export function redirectToReferrer(req, res, url, optionalReason) { url = url || '/'; const alternateUrl = popSessionVariable(req, res, 'referer'); const eventDetails = { method: 'redirectToReferrer', reason: optionalReason || 'unknown reason', }; if (req.insights) { req.insights.trackEvent({ name: 'RedirectToReferrer', properties: eventDetails }); } res.redirect(alternateUrl || url); }; export function storeOriginalUrlAsVariable(req, res, variable, redirect, optionalReason) { const eventDetails = { method: 'storeOriginalUrlAsVariable', variable: variable, redirect: redirect, reason: optionalReason || 'unknown reason', }; if (req.session && req.originalUrl) { req.session[variable] = req.originalUrl; eventDetails['ou'] = req.originalUrl; } if (redirect) { if (req.insights) { req.insights.trackEvent({ name: 'RedirectFromOriginalUrl', properties: eventDetails }); } res.redirect(redirect); } } export function popSessionVariable(req, res, variableName) { if (req.session && req.session[variableName] !== undefined) { const url = req.session[variableName]; delete req.session[variableName]; return url; } } // ---------------------------------------------------------------------------- // Provide our own error wrapper and message for an underlying thrown error. // Useful for the user-presentable version. // ---------------------------------------------------------------------------- const errorPropertiesToClone = [ 'stack', 'status', ]; export function wrapError(error, message, userIntendedMessage?: boolean): IReposError { const err: IReposError = new Error(message); err.innerError = error; if (error) { for (let i = 0; i < errorPropertiesToClone.length; i++) { const key = errorPropertiesToClone[i]; const value = error[key]; if (value && typeof value === 'number') { // Store as a string err[key] = value.toString(); } else if (value) { err[key] = value; } } } if (userIntendedMessage === true) { err.skipLog = true; } return err; }; // ---------------------------------------------------------------------------- // A destructive removal function for an object. Removes a single key. // ---------------------------------------------------------------------------- export function stealValue(obj, key) { if (obj[key] !== undefined) { var val = obj[key]; delete obj[key]; return val; } }; // ---------------------------------------------------------------------------- // Given a list of string values, check a string, using a case-insensitive // comparison. // ---------------------------------------------------------------------------- export function inListInsensitive(list, value) { value = value.toLowerCase(); for (var i = 0; i < list.length; i++) { if (list[i].toLowerCase() === value) { return true; } } return false; }; // ---------------------------------------------------------------------------- // Given a list of lowercase values, check whether a value is present. // ---------------------------------------------------------------------------- export function isInListAnycaseInLowercaseList(list, value) { value = value.toLowerCase(); for (var i = 0; i < list.length; i++) { if (list[i] === value) { return true; } } return false; }; // ---------------------------------------------------------------------------- // Given an array of things that have an `id` property, return a hash indexed // by that ID. // ---------------------------------------------------------------------------- export function arrayToHashById(inputArray) { var hash = {}; if (inputArray && inputArray.length) { for (var i = 0; i < inputArray.length; i++) { if (inputArray[i] && inputArray[i].id) { hash[inputArray[i].id] = inputArray[i]; } } } return hash; }; // ---------------------------------------------------------------------------- // Obfuscate a string value, optionally leaving a few characters visible. // ---------------------------------------------------------------------------- export function obfuscate(value, lastCharactersShowCount) { if (value === undefined || value === null || value.length === undefined) { return value; } var length = value.length; lastCharactersShowCount = lastCharactersShowCount || 0; lastCharactersShowCount = Math.min(Math.round(lastCharactersShowCount), length - 1); var obfuscated = ''; for (var i = 0; i < length - lastCharactersShowCount; i++) { obfuscated += '*'; } for (var j = length - lastCharactersShowCount; j < length; j++) { obfuscated += value[j]; } return obfuscated; }; // ---------------------------------------------------------------------------- // A very basic breadcrumb stack that ties in to an Express request object. // ---------------------------------------------------------------------------- export function addBreadcrumb(req, breadcrumbTitle, optionalBreadcrumbLink) { if (req === undefined || req.baseUrl === undefined) { throw new Error('addBreadcrumb: did you forget to provide a request object instance?'); } if (!optionalBreadcrumbLink && optionalBreadcrumbLink !== false) { optionalBreadcrumbLink = req.baseUrl; } if (!optionalBreadcrumbLink && optionalBreadcrumbLink !== false) { optionalBreadcrumbLink = '/'; } var breadcrumbs = req.breadcrumbs; if (breadcrumbs === undefined) { breadcrumbs = []; } breadcrumbs.push({ title: breadcrumbTitle, url: optionalBreadcrumbLink, }); req.breadcrumbs = breadcrumbs; }; export function stackSafeCallback(callback, err, item, extraItem) { // Works around RangeError: Maximum call stack size exceeded. setImmediate(() => { callback(err, item, extraItem); }); }; export function createSafeCallbackNoParams(cb) { return () => { exports.stackSafeCallback(cb); }; }; export function sleep(milliseconds: number): Promise<void> { return new Promise((resolve, reject) => { setTimeout(() => { process.nextTick(resolve); }, milliseconds); }); } export function ParseReleaseReviewWorkItemId(uri: string): string { const safeUrl = new URL(uri); const id = safeUrl.searchParams.get('id'); if (id) { return id; } const pathname = safeUrl.pathname; const editIndex = pathname.indexOf('edit/'); if (editIndex >= 0) { return pathname.substr(editIndex + 5); } if (safeUrl.host === 'osstool.microsoft.com') { return null; // Very legacy } throw new Error(`Unable to parse work item information from: ${uri}`); } export function readFileToText(filename: string): Promise<string> { return new Promise((resolve, reject) => { return fs.readFile(filename, 'utf8', (error, data) => { return error ? reject(error) : resolve(data); }); }); } export function writeTextToFile(filename: string, stringContent: string): Promise<void> { return new Promise((resolve, reject) => { return fs.writeFile(filename, stringContent, 'utf8', error => { if (error) { console.warn(`Trouble writing ${filename} ${error}`); } else { console.log(`Wrote ${filename}`); } return error ? reject(error) : resolve(); }); }); } export function quitInTenSeconds(successful: boolean) { console.log(`Quitting process in 10s... exit code=${successful ? 0 : 1}`); return setTimeout(() => { process.exit(successful ? 0 : 1); }, 1000 * 10 /* 10s */); } export function gzipString(value: string): Promise<Buffer> { return new Promise((resolve, reject) => { const val = Buffer.from(value); zlib.gzip(val, (gzipError, compressed: Buffer) => { return gzipError ? reject(gzipError) : resolve(compressed); }); }); } export function gunzipBuffer(buffer: Buffer): Promise<string> { return new Promise((resolve, reject) => { zlib.gunzip(buffer, (unzipError, unzipped) => { // Fallback if there is a data error (i.e. it's not compressed) if (unzipError && (unzipError as any)?.errno === zlib.Z_DATA_ERROR) { const originalValue = buffer.toString(); return resolve(originalValue); } else if (unzipError) { return reject(unzipError); } try { const unzippedValue = unzipped.toString(); return resolve(unzippedValue); } catch (otherError) { return reject(otherError); } }); }); } export function swapMap(map: Map<string, string>): Map<string, string> { const rm = new Map<string, string>(); for (const [key, value] of map.entries()) { rm.set(value, key); } return rm; } export function addArrayToSet<T>(set: Set<T>, array: T[]): Set<T> { for (const entry of array) { set.add(entry); } return set; }
the_stack
import * as assert from 'assert' import * as E from 'fp-ts/lib/Either' import * as Id from 'fp-ts/lib/Identity' import * as O from 'fp-ts/lib/Option' import { pipe } from 'fp-ts/lib/pipeable' import * as A from 'fp-ts/lib/ReadonlyArray' import { ReadonlyNonEmptyArray } from 'fp-ts/lib/ReadonlyNonEmptyArray' import { ReadonlyRecord } from 'fp-ts/lib/ReadonlyRecord' import * as Op from '../src/Optional' import * as _ from '../src/Prism' import * as T from '../src/Traversal' import * as U from './util' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- type Leaf = { readonly _tag: 'Leaf' } type Node = { readonly _tag: 'Node' readonly value: number readonly left: Tree readonly right: Tree } type Tree = Leaf | Node // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- const leaf: Tree = { _tag: 'Leaf' } const node = (value: number, left: Tree, right: Tree): Tree => ({ _tag: 'Node', value, left, right }) // ------------------------------------------------------------------------------------- // primitives // ------------------------------------------------------------------------------------- const value: _.Prism<Tree, number> = { getOption: (s) => (s._tag === 'Node' ? O.some(s.value) : O.none), reverseGet: (a) => node(a, leaf, leaf) } describe('Prism', () => { describe('pipeables', () => { it('imap', () => { const sa = pipe( value, _.imap( (n) => String(n), (s) => parseFloat(s) ) ) U.deepStrictEqual(sa.getOption(leaf), O.none) U.deepStrictEqual(sa.getOption(node(1, leaf, leaf)), O.some('1')) U.deepStrictEqual(sa.reverseGet('1'), node(1, leaf, leaf)) }) }) describe('instances', () => { it('compose', () => { type S = O.Option<Tree> const sa = pipe(_.id<S>(), _.some) const ab = value const sb = _.Category.compose(ab, sa) U.deepStrictEqual(sb.getOption(O.none), O.none) U.deepStrictEqual(sb.getOption(O.some(leaf)), O.none) U.deepStrictEqual(sb.getOption(O.some(node(1, leaf, leaf))), O.some(1)) U.deepStrictEqual(sb.reverseGet(1), O.some(node(1, leaf, leaf))) }) }) it('id', () => { const ss = _.id<Tree>() U.deepStrictEqual(ss.getOption(leaf), O.some(leaf)) U.deepStrictEqual(ss.reverseGet(leaf), leaf) }) it('modify', () => { const modify = pipe( value, _.modify((value) => value * 2) ) U.deepStrictEqual(modify(leaf), leaf) U.deepStrictEqual(modify(node(1, leaf, leaf)), node(2, leaf, leaf)) }) it('modifyOption', () => { const modifyOption = pipe( value, _.modifyOption((value) => value * 2) ) U.deepStrictEqual(modifyOption(leaf), O.none) U.deepStrictEqual(modifyOption(node(1, leaf, leaf)), O.some(node(2, leaf, leaf))) }) it('prop', () => { type S = O.Option<{ readonly a: string readonly b: number }> const sa = pipe(_.id<S>(), _.some, _.prop('a')) U.deepStrictEqual(sa.getOption(O.none), O.none) U.deepStrictEqual(sa.getOption(O.some({ a: 'a', b: 1 })), O.some('a')) }) it('props', () => { type S = O.Option<{ readonly a: string readonly b: number readonly c: boolean }> const sa = pipe(_.id<S>(), _.some, _.props('a', 'b')) U.deepStrictEqual(sa.getOption(O.none), O.none) U.deepStrictEqual(sa.getOption(O.some({ a: 'a', b: 1, c: true })), O.some({ a: 'a', b: 1 })) }) it('component', () => { type S = O.Option<readonly [string, number]> const sa = pipe(_.id<S>(), _.some, _.component(1)) U.deepStrictEqual(sa.getOption(O.none), O.none) U.deepStrictEqual(sa.getOption(O.some(['a', 1])), O.some(1)) }) it('index', () => { type S = ReadonlyArray<number> const optional = pipe(_.id<S>(), _.index(0)) U.deepStrictEqual(optional.getOption([]), O.none) U.deepStrictEqual(optional.getOption([1]), O.some(1)) U.deepStrictEqual(optional.set(2)([]), []) U.deepStrictEqual(optional.set(2)([1]), [2]) // should return the same reference const empty: S = [] const full: S = [1] assert.strictEqual(optional.set(1)(empty), empty) assert.strictEqual(optional.set(1)(full), full) }) it('indexNonEmpty', () => { type S = ReadonlyNonEmptyArray<number> const optional = pipe(_.id<S>(), _.indexNonEmpty(1)) U.deepStrictEqual(optional.getOption([1, 2]), O.some(2)) U.deepStrictEqual(optional.set(3)([1]), [1]) U.deepStrictEqual(optional.set(3)([1, 2]), [1, 3]) // should return the same reference const full: S = [1, 2] assert.strictEqual(optional.set(2)(full), full) }) it('key', () => { const sa = pipe(_.id<ReadonlyRecord<string, number>>(), _.key('k')) U.deepStrictEqual(sa.getOption({ k: 1, j: 2 }), O.some(1)) }) it('compose', () => { type S = O.Option<Tree> const sa = pipe(_.id<S>(), _.some) const ab = value const sb = pipe(sa, _.compose(ab)) U.deepStrictEqual(sb.getOption(O.none), O.none) U.deepStrictEqual(sb.getOption(O.some(leaf)), O.none) U.deepStrictEqual(sb.getOption(O.some(node(1, leaf, leaf))), O.some(1)) U.deepStrictEqual(sb.reverseGet(1), O.some(node(1, leaf, leaf))) }) it('composeOptional', () => { type S = O.Option<string> const sa = pipe(_.id<S>(), _.some) const ab: Op.Optional<string, string> = Op.optional( (s) => (s.length > 0 ? O.some(s[0]) : O.none), (a) => (s) => (s.length > 0 ? a + s.substring(1) : s) ) const sb = pipe(sa, _.composeOptional(ab)) U.deepStrictEqual(sb.getOption(O.none), O.none) U.deepStrictEqual(sb.getOption(O.some('')), O.none) U.deepStrictEqual(sb.getOption(O.some('ab')), O.some('a')) U.deepStrictEqual(sb.set('c')(O.none), O.none) U.deepStrictEqual(sb.set('c')(O.some('')), O.some('')) U.deepStrictEqual(sb.set('c')(O.some('ab')), O.some('cb')) }) it('composeTraversal', () => { type S = O.Option<ReadonlyArray<number>> const sa = pipe(_.id<S>(), _.some) const ab = T.fromTraversable(A.readonlyArray)<number>() const sb = pipe(sa, _.composeTraversal(ab)) U.deepStrictEqual(sb.modifyF(Id.identity)((n) => n * 2)(O.none), O.none) U.deepStrictEqual(sb.modifyF(Id.identity)((n) => n * 2)(O.some([1, 2, 3])), O.some([2, 4, 6])) }) it('right', () => { type S = E.Either<string, number> const sa = pipe(_.id<S>(), _.right) U.deepStrictEqual(sa.getOption(E.right(1)), O.some(1)) U.deepStrictEqual(sa.getOption(E.left('a')), O.none) U.deepStrictEqual(sa.reverseGet(2), E.right(2)) }) it('left', () => { type S = E.Either<string, number> const sa = pipe(_.id<S>(), _.left) U.deepStrictEqual(sa.getOption(E.right(1)), O.none) U.deepStrictEqual(sa.getOption(E.left('a')), O.some('a')) U.deepStrictEqual(sa.reverseGet('b'), E.left('b')) }) it('atKey', () => { type S = ReadonlyRecord<string, number> const sa = pipe(_.id<S>(), _.atKey('a')) U.deepStrictEqual(sa.getOption({ a: 1 }), O.some(O.some(1))) U.deepStrictEqual(sa.set(O.some(2))({ a: 1, b: 2 }), { a: 2, b: 2 }) U.deepStrictEqual(sa.set(O.some(1))({ b: 2 }), { a: 1, b: 2 }) U.deepStrictEqual(sa.set(O.none)({ a: 1, b: 2 }), { b: 2 }) }) it('filter', () => { type S = O.Option<number> const sa = pipe( _.id<S>(), _.some, _.filter((n) => n > 0) ) U.deepStrictEqual(sa.getOption(O.some(1)), O.some(1)) U.deepStrictEqual(sa.getOption(O.some(-1)), O.none) U.deepStrictEqual(sa.getOption(O.none), O.none) U.deepStrictEqual(sa.reverseGet(2), O.some(2)) U.deepStrictEqual(sa.reverseGet(-1), O.some(-1)) }) it('findFirst', () => { type S = O.Option<ReadonlyArray<number>> const optional = pipe( _.id<S>(), _.some, _.findFirst((n) => n > 0) ) U.deepStrictEqual(optional.getOption(O.none), O.none) U.deepStrictEqual(optional.getOption(O.some([])), O.none) U.deepStrictEqual(optional.getOption(O.some([-1, -2, -3])), O.none) U.deepStrictEqual(optional.getOption(O.some([-1, 2, -3])), O.some(2)) U.deepStrictEqual(optional.set(3)(O.none), O.none) U.deepStrictEqual(optional.set(3)(O.some([])), O.some([])) U.deepStrictEqual(optional.set(3)(O.some([-1, -2, -3])), O.some([-1, -2, -3])) U.deepStrictEqual(optional.set(3)(O.some([-1, 2, -3])), O.some([-1, 3, -3])) U.deepStrictEqual(optional.set(4)(O.some([-1, -2, 3])), O.some([-1, -2, 4])) }) it('findFirstNonEmpty', () => { type S = O.Option<ReadonlyNonEmptyArray<number>> const optional = pipe( _.id<S>(), _.some, _.findFirstNonEmpty((n) => n > 0) ) U.deepStrictEqual(optional.getOption(O.none), O.none) U.deepStrictEqual(optional.getOption(O.some([-1, -2, -3])), O.none) U.deepStrictEqual(optional.getOption(O.some([-1, 2, -3])), O.some(2)) U.deepStrictEqual(optional.set(3)(O.none), O.none) U.deepStrictEqual(optional.set(3)(O.some([-1, -2, -3])), O.some([-1, -2, -3] as const)) U.deepStrictEqual(optional.set(3)(O.some([-1, 2, -3])), O.some([-1, 3, -3] as const)) U.deepStrictEqual(optional.set(4)(O.some([-1, -2, 3])), O.some([-1, -2, 4] as const)) }) it('traverse', () => { type S = O.Option<ReadonlyArray<string>> const sa = pipe(_.id<S>(), _.some, _.traverse(A.readonlyArray)) const modify = pipe( sa, T.modify((s) => s.toUpperCase()) ) U.deepStrictEqual(modify(O.some(['a'])), O.some(['A'])) }) it('fromNullable', () => { type S = O.Option<number | undefined> const sa = pipe(_.id<S>(), _.some, _.fromNullable) U.deepStrictEqual(sa.getOption(O.none), O.none) U.deepStrictEqual(sa.getOption(O.some(undefined)), O.none) U.deepStrictEqual(sa.getOption(O.some(1)), O.some(1)) U.deepStrictEqual(sa.reverseGet(1), O.some(1)) }) it('modifyF', () => { const f = pipe( value, _.modifyF(O.option)((n) => (n > 0 ? O.some(n * 2) : O.none)) ) U.deepStrictEqual(f(node(1, leaf, leaf)), O.some(node(2, leaf, leaf))) U.deepStrictEqual(f(leaf), O.some(leaf)) U.deepStrictEqual(f(node(-1, leaf, leaf)), O.none) }) })
the_stack
* @module iTwinServiceClients */ import * as deepAssign from "deep-assign"; import * as _ from "lodash"; import * as https from "https"; import { IStringifyOptions, stringify } from "qs"; import * as sarequest from "superagent"; import { BentleyError, GetMetaDataFunction, HttpStatus, Logger, LogLevel } from "@itwin/core-bentley"; import { FrontendLoggerCategory } from "../FrontendLoggerCategory"; const loggerCategory: string = FrontendLoggerCategory.Request; // CMS TODO: Move this entire wrapper to the frontend for use in the map/tile requests. Replace it with // just using fetch directly as it is only ever used browser side. /** @internal */ export const requestIdHeaderName = "X-Correlation-Id"; /** @internal */ export interface RequestBasicCredentials { // axios: AxiosBasicCredentials user: string; // axios: username password: string; // axios: password } /** Typical option to query REST API. Note that services may not quite support these fields, * and the interface is only provided as a hint. * @internal */ export interface RequestQueryOptions { /** * Select string used by the query (use the mapped EC property names, and not TypeScript property names) * Example: "Name,Size,Description" */ $select?: string; /** * Filter string used by the query (use the mapped EC property names, and not TypeScript property names) * Example: "Name like '*.pdf' and Size lt 1000" */ $filter?: string; /** Sets the limit on the number of entries to be returned by the query */ $top?: number; /** Sets the number of entries to be skipped */ $skip?: number; /** * Orders the return values (use the mapped EC property names, and not TypeScript property names) * Example: "Size desc" */ $orderby?: string; /** * Sets the limit on the number of entries to be returned by a single response. * Can be used with a Top option. For example if Top is set to 1000 and PageSize * is set to 100 then 10 requests will be performed to get result. */ $pageSize?: number; } /** @internal */ export interface RequestQueryStringifyOptions { delimiter?: string; encode?: boolean; } /** Option to control the time outs * Use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow, * but reliable, networks. Note that both of these timers limit how long uploads of attached files are allowed to take. Use long * timeouts if you're uploading files. * @internal */ export interface RequestTimeoutOptions { /** Sets a deadline (in milliseconds) for the entire request (including all uploads, redirects, server processing time) to complete. * If the response isn't fully downloaded within that time, the request will be aborted */ deadline?: number; /** Sets maximum time (in milliseconds) to wait for the first byte to arrive from the server, but it does not limit how long the entire * download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because * it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data. */ response?: number; } /** @internal */ export interface RequestOptions { method: string; headers?: any; // {Mas-App-Guid, Mas-UUid, User-Agent} auth?: RequestBasicCredentials; body?: any; qs?: any | RequestQueryOptions; responseType?: string; timeout?: RequestTimeoutOptions; // Optional timeouts. If unspecified, an arbitrary default is setup. stream?: any; // Optional stream to read the response to/from (only for NodeJs applications) readStream?: any; // Optional stream to read input from (only for NodeJs applications) buffer?: any; parser?: any; accept?: string; redirects?: number; errorCallback?: (response: any) => ResponseError; retryCallback?: (error: any, response: any) => boolean; progressCallback?: ProgressCallback; agent?: https.Agent; retries?: number; useCorsProxy?: boolean; } /** Response object if the request was successful. Note that the status within the range of 200-299 are considered as a success. * @internal */ export interface Response { body: any; // Parsed body of response text: string | undefined; // Returned for responseType:text header: any; // Parsed headers of response status: number; // Status code of response } /** @internal */ export interface ProgressInfo { percent?: number; total?: number; loaded: number; } /** @internal */ export type ProgressCallback = (progress: ProgressInfo) => void; /** @internal */ export class RequestGlobalOptions { public static httpsProxy?: https.Agent = undefined; /** Creates an agent for any user defined proxy using the supplied additional options. Returns undefined if user hasn't defined a proxy. * @internal */ public static createHttpsProxy: (additionalOptions?: https.AgentOptions) => https.Agent | undefined = (_additionalOptions?: https.AgentOptions) => undefined; public static maxRetries: number = 4; public static timeout: RequestTimeoutOptions = { deadline: 25000, response: 10000, }; // Assume application is online or offline. This hint skip retry/timeout public static online: boolean = true; } /** Error object that's thrown/rejected if the Request fails due to a network error, or if the status is *not* in the range of 200-299 (inclusive) * @internal */ export class ResponseError extends BentleyError { protected _data?: any; public status?: number; public description?: string; public constructor(errorNumber: number | HttpStatus, message?: string, getMetaData?: GetMetaDataFunction) { super(errorNumber, message, getMetaData); } /** * Parses error from server's response * @param response Http response from the server. * @returns Parsed error. * @internal */ public static parse(response: any, log = true): ResponseError { const error = new ResponseError(ResponseError.parseHttpStatus(response.statusType)); if (!response) { error.message = "Couldn't get response object."; return error; } if (response.response) { if (response.response.error) { error.name = response.response.error.name || error.name; error.description = response.response.error.message; } if (response.response.res) { error.message = response.response.res.statusMessage; } if (response.response.body && Object.keys(response.response.body).length > 0) { error._data = {}; deepAssign.default(error._data, response.response.body); } else { error._data = response.response.text; } } error.status = response.status || response.statusCode; error.name = response.code || response.name || error.name; error.message = error.message || response.message || response.statusMessage; if (log) error.log(); return error; } /** * Decides whether request should be retried or not * @param error Error returned by request * @param response Response returned by request * @internal */ public static shouldRetry(error: any, response: any): boolean { if (error !== undefined && error !== null) { if ((error.status === undefined || error.status === null) && (error.res === undefined || error.res === null)) { return true; } } return (response !== undefined && response.statusType === HttpStatus.ServerError); } /** * @internal */ public static parseHttpStatus(statusType: number): HttpStatus { switch (statusType) { case 1: return HttpStatus.Info; case 2: return HttpStatus.Success; case 3: return HttpStatus.Redirection; case 4: return HttpStatus.ClientError; case 5: return HttpStatus.ServerError; default: return HttpStatus.Success; } } /** * @internal */ public logMessage(): string { return `${this.status} ${this.name}: ${this.message}`; } /** * Logs this error * @internal */ public log(): void { Logger.logError(loggerCategory, this.logMessage(), () => this.getMetaData()); } } const logResponse = (req: sarequest.SuperAgentRequest, startTime: number) => (res: sarequest.Response) => { const elapsed = new Date().getTime() - startTime; const elapsedTime = `${elapsed}ms`; Logger.logTrace(loggerCategory, `${req.method.toUpperCase()} ${res.status} ${req.url} (${elapsedTime})`); }; // eslint-disable-next-line @typescript-eslint/promise-function-async const logRequest = (req: sarequest.SuperAgentRequest): sarequest.SuperAgentRequest => { const startTime = new Date().getTime(); return req.on("response", logResponse(req, startTime)); }; /** Wrapper around making HTTP requests with the specific options. * * Usable in both a browser and node based environment. * * @param url Server URL to address the request * @param options Options to pass to the request * @returns Resolves to the response from the server * @throws ResponseError if the request fails due to network issues, or if the returned status is *outside* the range of 200-299 (inclusive) * @internal */ export async function request(url: string, options: RequestOptions): Promise<Response> { if (!RequestGlobalOptions.online) { throw new ResponseError(503, "Service unavailable"); } let sareq: sarequest.SuperAgentRequest = sarequest.default(options.method, url); const retries = typeof options.retries === "undefined" ? RequestGlobalOptions.maxRetries : options.retries; sareq = sareq.retry(retries, options.retryCallback); if (Logger.isEnabled(loggerCategory, LogLevel.Trace)) sareq = sareq.use(logRequest); if (options.headers) sareq = sareq.set(options.headers); let queryStr: string = ""; let fullUrl: string = ""; if (options.qs && Object.keys(options.qs).length > 0) { const stringifyOptions: IStringifyOptions = { delimiter: "&", encode: false }; queryStr = stringify(options.qs, stringifyOptions); sareq = sareq.query(queryStr); fullUrl = `${url}?${queryStr}`; } else { fullUrl = url; } Logger.logInfo(loggerCategory, fullUrl); if (options.auth) sareq = sareq.auth(options.auth.user, options.auth.password); if (options.accept) sareq = sareq.accept(options.accept); if (options.body) sareq = sareq.send(options.body); if (options.timeout) sareq = sareq.timeout(options.timeout); else sareq = sareq.timeout(RequestGlobalOptions.timeout); if (options.responseType) sareq = sareq.responseType(options.responseType); if (options.redirects) sareq = sareq.redirects(options.redirects); else sareq = sareq.redirects(0); if (options.buffer) sareq = sareq.buffer(options.buffer); if (options.parser) sareq = sareq.parse(options.parser); /** Default to any globally supplied proxy, unless an agent is specified in this call */ if (options.agent) sareq = sareq.agent(options.agent); else if (RequestGlobalOptions.httpsProxy) sareq = sareq.agent(RequestGlobalOptions.httpsProxy); if (options.progressCallback) { sareq = sareq.on("progress", (event: sarequest.ProgressEvent) => { if (event) { options.progressCallback!({ loaded: event.loaded, total: event.total, percent: event.percent, }); } }); } const errorCallback = options.errorCallback ? options.errorCallback : ResponseError.parse; if (options.readStream) { if (typeof window !== "undefined") throw new Error("This option is not supported on browsers"); return new Promise<Response>((resolve, reject) => { sareq = sareq.type("blob"); options .readStream .pipe(sareq) .on("error", (error: any) => { const parsedError = errorCallback(error); reject(parsedError); }) .on("end", () => { const retResponse: Response = { status: 201, header: undefined, body: undefined, text: undefined, }; resolve(retResponse); }); }); } if (options.stream) { if (typeof window !== "undefined") throw new Error("This option is not supported on browsers"); return new Promise<Response>((resolve, reject) => { sareq .on("response", (res: any) => { if (res.statusCode !== 200) { const parsedError = errorCallback(res); reject(parsedError); return; } }) .pipe(options.stream) .on("error", (error: any) => { const parsedError = errorCallback(error); reject(parsedError); }) .on("finish", () => { const retResponse: Response = { status: 200, header: undefined, body: undefined, text: undefined, }; resolve(retResponse); }); }); } // console.log("%s %s %s", url, options.method, queryStr); /** * Note: * Javascript's fetch returns status.OK if error is between 200-299 inclusive, and doesn't reject in this case. * Fetch only rejects if there's some network issue (permissions issue or similar) * Superagent rejects network issues, and errors outside the range of 200-299. We are currently using * superagent, but may eventually switch to JavaScript's fetch library. */ try { const response = await sareq; const retResponse: Response = { body: response.body, text: response.text, header: response.header, status: response.status, }; return retResponse; } catch (error) { const parsedError = errorCallback(error); throw parsedError; } } /** * fetch json from HTTP request * @param url server URL to address the request * @internal */ export async function getJson(url: string): Promise<any> { const options: RequestOptions = { method: "GET", responseType: "json", }; const data = await request(url, options); return data.body; }
the_stack
import { spawn, execSync } from "child_process"; import { sleep, waitUntil } from "./utilities"; import * as kill from "tree-kill"; import * as cp from "child_process"; import { SmokeTestLogger } from "./smokeTestLogger"; import { ExpoClientData } from "./androidEmulatorManager"; const XDL = require("xdl"); interface IiOSSimulator { system: string; name: string; id: string; state: DeviceState; } enum DeviceState { Booted = "Booted", Shutdown = "Shutdown", Unknown = "Unknown", } interface RunResult { Successful: boolean; FailedState?: DeviceState; } export default class IosSimulatorManager { private static readonly SIMULATOR_START_TIMEOUT = 300_000; private static readonly SIMULATOR_TERMINATE_TIMEOUT = 30_000; private static readonly APP_INSTALL_AND_BUILD_TIMEOUT = 600_000; private static readonly APP_INIT_TIMEOUT = 40_000; private simulator: IiOSSimulator; constructor( name: string | undefined = process.env.IOS_SIMULATOR, iosVersion: string | undefined = process.env.IOS_VERSION, ) { if (!name) { throw new Error( "Passed iOS simulator name and process.env.IOS_SIMULATOR is not defined!", ); } if (process.platform === "darwin") { if (iosVersion) { iosVersion = `iOS ${iosVersion}`; } this.updateSimulatorState(name, iosVersion); } } public getSimulator(): IiOSSimulator { return this.simulator; } public static getIOSBuildPath( iosProjectRoot: string, projectWorkspaceConfigName: string, configuration: string, scheme: string, sdkType: string, ): string { const buildSettings = cp.execFileSync( "xcodebuild", [ "-workspace", projectWorkspaceConfigName, "-scheme", scheme, "-sdk", sdkType, "-configuration", configuration, "-showBuildSettings", ], { encoding: "utf8", cwd: iosProjectRoot, }, ); const targetBuildDir = this.getTargetBuildDir(<string>buildSettings); if (!targetBuildDir) { throw new Error("Failed to get the target build directory."); } return targetBuildDir; } private updateSimulatorState(name: string, iosVersion?: string) { const simulators = IosSimulatorManager.collectSimulators(); const simulator = this.findSimulator(simulators, name, iosVersion); if (!simulator) { throw new Error( `Could not find simulator with name: '${name}'${ iosVersion ? ` and iOS version: '${iosVersion}'` : "" } in system. Exiting...`, ); } this.simulator = simulator; } public async runIosSimulator(): Promise<void> { await this.shutdownSimulator(); // Wipe data on simulator await this.eraseSimulator(); SmokeTestLogger.info( `*** Executing iOS simulator with 'xcrun simctl boot "${this.simulator.name}"' command...`, ); await this.bootSimulator(); await sleep(15 * 1000); } public async bootSimulator(): Promise<void> { const cmd = "boot"; const result = await IosSimulatorManager.runSimCtlCommand([cmd, this.simulator.name]); if (!result.Successful) { if (result.FailedState === DeviceState.Booted) { // That's okay, it means simulator is already booted } else { throw IosSimulatorManager.getRunError(cmd, result.FailedState); } } this.updateSimulatorState(this.simulator.name, this.simulator.system); } public async shutdownSimulator(): Promise<void> { await IosSimulatorManager.shutdownSimulator(this.simulator.name); this.updateSimulatorState(this.simulator.name, this.simulator.system); } public async eraseSimulator(): Promise<void> { const cmd = "erase"; const result = await IosSimulatorManager.runSimCtlCommand([cmd, this.simulator.name]); if (!result.Successful) { throw IosSimulatorManager.getRunError(cmd, result.FailedState); } this.updateSimulatorState(this.simulator.name, this.simulator.system); } public async waitUntilIosSimulatorStarting(): Promise<boolean> { const condition = () => { this.updateSimulatorState(this.simulator.name, this.simulator.system); if (this.simulator.state === DeviceState.Booted) { return true; } else return false; }; const result = await waitUntil(condition, IosSimulatorManager.SIMULATOR_START_TIMEOUT); if (result) { SmokeTestLogger.success(`*** iOS simulator ${this.simulator.name} has been started.`); } else { SmokeTestLogger.error( `*** Could not start iOS simulator ${this.simulator.name} after ${IosSimulatorManager.SIMULATOR_START_TIMEOUT}.`, ); } return result; } public async waitUntilIosSimulatorTerminating(): Promise<boolean> { const condition = () => { this.updateSimulatorState(this.simulator.name, this.simulator.system); if (this.simulator.state === DeviceState.Shutdown) { return true; } else return false; }; const result = await waitUntil(condition, IosSimulatorManager.SIMULATOR_TERMINATE_TIMEOUT); if (result) { SmokeTestLogger.success( `*** iOS simulator ${this.simulator.name} has been terminated.`, ); } else { SmokeTestLogger.error( `*** Could not terminate iOS simulator ${this.simulator.name} after ${IosSimulatorManager.SIMULATOR_TERMINATE_TIMEOUT}.`, ); } return result; } public async waitUntilIosAppIsInstalled(appBundleId: string): Promise<void> { // Start watcher for launch events console logs in simulator and wait until needed app is launched // TODO is not compatible with parallel test run (race condition) let launched = false; const predicate = `eventMessage contains "Launch successful for '${appBundleId}'"`; const args = [ "simctl", "spawn", this.simulator.name, "log", "stream", "--predicate", predicate, ]; const proc = spawn("xcrun", args, { stdio: "pipe" }); proc.stdout.on("data", (data: string) => { data = data.toString(); SmokeTestLogger.info(data); if (data.startsWith("Filtering the log data")) { return; } const regexp = new RegExp(`Launch successful for '${appBundleId}'`); if (regexp.test(data)) { launched = true; } }); proc.stderr.on("error", (data: string) => { SmokeTestLogger.error(data.toString()); }); proc.on("error", err => { SmokeTestLogger.error(err); kill(proc.pid); }); let awaitRetries: number = IosSimulatorManager.APP_INSTALL_AND_BUILD_TIMEOUT / 1000; let retry = 1; await new Promise<void>((resolve, reject) => { const check = setInterval(async () => { if (retry % 5 === 0) { SmokeTestLogger.info( `*** Check if app with bundleId ${appBundleId} is installed, ${retry} attempt`, ); } if (launched) { clearInterval(check); const initTimeout = IosSimulatorManager.APP_INIT_TIMEOUT || 10000; SmokeTestLogger.success( `*** Installed ${appBundleId} app found, await ${initTimeout}ms for initializing...`, ); await sleep(initTimeout); resolve(); } else { retry++; if (retry >= awaitRetries) { clearInterval(check); kill(proc.pid, () => { reject( `${appBundleId} not found after ${IosSimulatorManager.APP_INSTALL_AND_BUILD_TIMEOUT}ms`, ); }); } } }, 1000); }); } public async getExpoAndroidClientForSDK(expoSdkMajorVersion: string): Promise<ExpoClientData> { const sdkVersion = (await XDL.Versions.sdkVersionsAsync())[`${expoSdkMajorVersion}.0.0`]; return { url: sdkVersion.iosClientUrl, version: sdkVersion.iosClientVersion, }; } public async installExpoAppOnIos(): Promise<void> { this.updateSimulatorState(this.simulator.name, this.simulator.system); if (this.simulator.state === DeviceState.Booted) { const expoClientData = await this.getExpoAndroidClientForSDK( process.env.EXPO_SDK_MAJOR_VERSION || "", ); SmokeTestLogger.projectPatchingLog( `*** Installing Expo app v${expoClientData.version} on iOS simulator using Expo XDL function`, ); await XDL.Simulator.installExpoOnSimulatorAsync({ simulator: { name: this.simulator.name || "", udid: this.simulator.id || "", }, url: expoClientData.url, version: expoClientData.version, }); } else { throw new Error( "*** Could not install Expo app on iOS simulator because it is not booted", ); } } private findSimulator( simulators: IiOSSimulator[], name: string, system?: string, ): IiOSSimulator | null { const foundSimulator = simulators.find( value => value.name === name && (!system || value.system === system), ); if (!foundSimulator) { return null; } return foundSimulator; } private static getBootedDevices(): IiOSSimulator[] { const simulators = this.collectSimulators(); const bootedSimulators = simulators.filter(sim => sim.state === DeviceState.Booted); return bootedSimulators; } private static collectSimulators(): IiOSSimulator[] { const simulators: IiOSSimulator[] = []; const res = execSync("xcrun simctl list --json devices available").toString(); const simulatorsJson = JSON.parse(res); Object.keys(simulatorsJson.devices).forEach(rawSystem => { const temp = rawSystem.split(".").slice(-1)[0].split("-"); // "com.apple.CoreSimulator.SimRuntime.iOS-11-4" -> ["iOS", "11", "4"] const system = `${temp[0]} ${temp.slice(1).join(".")}`; // ["iOS", "11", "4"] -> iOS 11.4 simulatorsJson.devices[rawSystem].forEach((device: any) => { simulators.push({ name: device.name, id: device.udid, system, state: device.state, }); }); }); return simulators; } private static async runSimCtlCommand(args: string[]): Promise<RunResult> { return new Promise<RunResult>((resolve, reject) => { let stderr = ""; const command = "xcrun"; const commandArgs = ["simctl"].concat(args); const cp = spawn(command, commandArgs); cp.on("close", () => { const lines = stderr.split("\n").filter(value => value); // filter empty lines if (lines.length === 0) { // No error output resolve({ Successful: true, }); return; } const lastLine = lines[lines.length - 1]; if (lastLine.startsWith(`Unable to ${args[0]}`)) { const match = lastLine.match(/in current state: (.+)/); if (!match || match.length !== 2) { reject( new Error( `Error parsing ${[command].concat(commandArgs).join(" ")} output`, ), ); } const state = DeviceState[match![1]]; if (!state) { SmokeTestLogger.warn(`Unknown state: ${match![1]}`); resolve({ Successful: false, FailedState: DeviceState.Unknown, }); } else { resolve({ Successful: false, FailedState: state, }); } resolve({ Successful: true, }); } else { reject( new Error( `Error occurred while running ${[command] .concat(commandArgs) .join(" ")}`, ), ); } }); cp.stderr.on("data", (chunk: string | Buffer) => { stderr += chunk; process.stderr.write(chunk); }); cp.stdout.on("data", (chunk: string | Buffer) => { process.stdout.write(chunk); }); }); } private static getRunError(command: string, failedState?: DeviceState) { return new Error( `Couldn't run ${command} simulator` + failedState ? `, because it in ${failedState} state` : "", ); } public static async shutdownAllSimulators(): Promise<boolean> { const promises: Promise<void>[] = []; IosSimulatorManager.getBootedDevices().forEach(device => { promises.push(IosSimulatorManager.shutdownSimulator(device.name)); }); await Promise.all(promises); return this.waitUntilAllIosSimulatorsTerminating(); } private static async shutdownSimulator(simulatorName: string): Promise<void> { const cmd = "shutdown"; const result = await IosSimulatorManager.runSimCtlCommand([cmd, simulatorName]); if (!result.Successful) { if (result.FailedState === DeviceState.Shutdown) { // That's okay, it means simulator is already shutted down } else { throw IosSimulatorManager.getRunError(cmd, result.FailedState); } } SmokeTestLogger.success( `*** iOS simulators with name "${simulatorName}" has been terminated.`, ); } public static async waitUntilAllIosSimulatorsTerminating(): Promise<boolean> { const condition = () => { if (IosSimulatorManager.getBootedDevices().length === 0) { return true; } else return false; }; const result = await waitUntil(condition, IosSimulatorManager.SIMULATOR_TERMINATE_TIMEOUT); if (result) { SmokeTestLogger.success(`*** All iOS simulators has been terminated.`); } else { SmokeTestLogger.error( `*** Could not terminate all iOS simulators after ${IosSimulatorManager.SIMULATOR_TERMINATE_TIMEOUT}.`, ); } return result; } /** * * The function was taken from https://github.com/react-native-community/cli/blob/master/packages/platform-ios/src/commands/runIOS/index.ts#L369-L374 * * @param {string} buildSettings * @returns {string | null} */ private static getTargetBuildDir(buildSettings: string) { const targetBuildMatch = /TARGET_BUILD_DIR = (.+)$/m.exec(buildSettings); return targetBuildMatch && targetBuildMatch[1] ? targetBuildMatch[1].trim() : null; } }
the_stack
import { __assign } from "tslib"; /** An interface for representing a readonly pair */ export type Pair<S, T = S> = readonly [S, T]; export const pair = <S, T = S>(left: S, right: T): Pair<S, T> => [left, right]; // using this polyfill, because `Object.assign` is not supported in IE. const ObjectAssign: typeof Object.assign = __assign; export enum SetKind { Dense, Empty, } interface TreeNode<Left, Right> { readonly left: Left; readonly right: Right; } interface KeyNode<Key, Exact> { readonly key: Key; readonly pathKey: Key; readonly isExact: Exact; } export type Empty = SetKind.Empty; /** The term *Dense* means that a given subset contains all the elements of its particular * bounds. E.g. the whole set would be dense w.r.t. the bounds of the whole space. Or * if a set represents an interval [a, b), then it would be dense, if there are no holes in it, * i.e. the set is represented exactly using the current bounds. */ export type Dense = SetKind.Dense; export const dense = SetKind.Dense; export const empty = SetKind.Empty; type KeyUnexact<Key> = KeyNode<Key, false>; /** In the BSP-set, each node carries with it implicit bounds just by the position in the tree. * Furthermore, it can carry around a key. The key can either be an approximation, i.e. an upper bound * or it can be *exact*. Exact means, that the whole set can be exactly represented in terms of just the key. * * One might wonder, why we don't prune the tree at this point. This has to do with the fact that we are * representing arbitrary sets and so even though one of two sets could be represented exactly the other * might not be able to yet. In this case we need to unfold the key by splitting further. In order to avoid * excessive splitting and pruning, we just carry around the key but allow the tree to also be materialized, on-demand. */ type KeyExact<Key> = KeyNode<Key, true>; type KeyUndefined = KeyNode<undefined, false>; type KeyDefined<Key> = KeyUnexact<Key> | KeyExact<Key>; type BalancePropertyHelper<Key, Left, Right> = TreeNode<UntypedSparse<Key> | Left, UntypedSparse<Key> | Right>; type TreeDefined<Key> = | BalancePropertyHelper<Key, Empty, Dense> | BalancePropertyHelper<Key, Dense, Empty>; type TreeUndefined = TreeNode<undefined, undefined>; type KeyDefinednessProperty<Key> = KeyDefined<Key> | KeyUndefined; export type UntypedSparse<Key> = | (KeyDefinednessProperty<Key> & TreeDefined<Key>) | (KeyDefined<Key> & TreeUndefined); /** The term *untyped* refers to the tree representation of a BSP set. Because BSP set trees are only compared in terms * of their structure, we need to ensure that cuts occur at the same exact points across all possible sets. This is * enforced by the fact, that at construction time, we attach an `Id` to each BSP set and only allow operations to * occur on sets with the same `Id`. * * The BSP set becomes *untyped*, when we drop that `Id`; now it is possible to operate on sets that are incompatible. * Doing this, however, allows us to store the set operations only once per set as opposed to carrying them around with * every node. */ export type UntypedBspSet<Key> = Empty | Dense | UntypedSparse<Key>; /** A set is considred *sparse*, if we know that w.r.t. to it's bounds it is neither empty, nor dense. */ interface Sparse<Key extends Cachable<Key>, Id> { setOperations: SetOperations<Key, Id>; root: UntypedSparse<Key>; } export type BspSet<Key extends Cachable<Key>, Id> = | Empty | Dense | Sparse<Key, Id>; export interface KeyCache<T> { depth?: number; split?: Pair<Pair<CachedKey<T>, number>>; } export type CachedKey<T> = T & KeyCache<T>; export type Cachable<T> = Disjoint<keyof T, keyof KeyCache<T>>; export type Disjoint<T, U> = [T, U] extends [Exclude<T, U>, Exclude<U, T>] ? any : never; export type RequireAtLeastOne<T> = { [K in keyof T]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<keyof T, K>>>; }[keyof T]; /** This is a concrete set operations implementation, tagged with an arbitrary id. */ export interface SetOperations<Key extends Cachable<Key>, Id> { /** Id here is just a phantom type, so that we can associate the various set instances together */ readonly id: Id; /** Split the key into two. This will only be called when the current key is incomparable with an element. * E.g. this would never be called if the key is already a 1x1 rectangle. */ readonly split: (key: CachedKey<Key>) => Pair<Pair<CachedKey<Key>, number>>; /** Tells, if a given key can be split further */ readonly canSplit: (key: CachedKey<Key>) => boolean; /** Tells if two keys overlap at all. */ readonly meets: (key1: Key, key2: Key) => boolean; /** Intersect the keys, if it is possible to exactly respresent their intersection. * An implementation is never required to compute the intersection as this is just an optimization. * Precondition: It is guaranteed that the keys meet and that they are incomparable. */ readonly intersect: (key1: Key, key2: Key) => Key | undefined; /** Unions the keys, if it is possible to exactly represent their union. * An implementation is never required to compute the union as this is just an optimization. * Precondition: It is guaranteed that the keys are incomparable. */ readonly union: (key1: Key, key2: Key) => Key | undefined; /** Computes the set difference between two keys, if it is possible to exactly represent their set difference. * An implementation is never required to compute the difference as this is just an optimization. * Precondition: It is guaranteed that the keys meet. */ readonly except: (key1: Key, key2: Key) => Key | undefined; /** Compare two keys */ readonly compare: (key1: Key, key2: Key) => -1 | 0 | 1 | undefined; /** The top element of the set. */ readonly top: Key; } export const cacheKeySplitting = <Key>( splitFunction: (key: CachedKey<Key>) => Pair<Pair<CachedKey<Key>, number>>, top: CachedKey<Key>, maxDepth: number = 10, ) => (key: CachedKey<Key>) => { if (key.split !== undefined) { return key.split; } const split = splitFunction(key); const depth = key === top ? 0 : key.depth; if (depth !== undefined && depth < maxDepth) { key.split = split; split[0][0].depth = depth + 1; split[1][0].depth = depth + 1; } return split; }; export function fromUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, root: UntypedBspSet<Key>, ): BspSet<Key, Id> { if (root === empty || root === dense) { return root; } return { setOperations, root }; } const sparse = <Key, Exact, Left, Right>( left: Left, right: Right, pathKey: Key, key: Key, isExact: Exact, ) => ({ key, pathKey, left, right, isExact }); function fromKey<Key>( pathKey: Key, key: Key, isExact: boolean, ): UntypedSparse<Key> { if (isExact) { return sparse(undefined, undefined, pathKey, key, true as const); } return sparse(undefined, undefined, pathKey, key, false as const); } export function lazy<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, pathKey: Key, key: Key, ): UntypedBspSet<Key> { if (!setOperations.meets(pathKey, key)) { return empty; } const cmp = setOperations.compare(pathKey, key); if (cmp !== undefined) { if (cmp <= 0) { return dense; } return fromKey(pathKey, key, true); } // this is not exactly necessary, but increases the amount of exact nodes and thus we can often // prune earlier. // Also, having intersect always work guarantees exact nodes, thus allowing for more efficient // storage and computation. const newKey = setOperations.intersect(pathKey, key); if (newKey !== undefined) { return fromKey(pathKey, newKey, true); } return fromKey(pathKey, key, false); } export function createFromKey<Key extends Cachable<Key>, Id>( uncachedSetOperations: SetOperations<Key, Id>, ) { const setOperations = { ...uncachedSetOperations, split: cacheKeySplitting( uncachedSetOperations.split, uncachedSetOperations.top, ), }; return (key: Key) => fromUntyped(setOperations, lazy(setOperations, setOperations.top, key)); } function unionExact<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key> & KeyExact<Key>, right: UntypedBspSet<Key> & KeyExact<Key>, ) { const { pathKey, key: leftKey } = left; const { key: rightKey } = right; const cmp = setOperations.compare(leftKey, rightKey); if (cmp !== undefined) { return cmp < 0 ? right : left; } const combinedKey = setOperations.union(leftKey, rightKey); if (combinedKey !== undefined) { const combinedCmp = setOperations.compare(combinedKey, pathKey); if (combinedCmp !== undefined && combinedCmp === 0) { return dense; } return fromKey(pathKey, combinedKey, true); } return undefined; } /** This is an local combination, not a proper union. We use it to have simpler code elsewhere */ function combineChildren<Key>( left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): Empty | Dense | (UntypedSparse<Key> & TreeDefined<Key>) { if (left === empty) { if (right === empty) { return empty; } return sparse(left, right, undefined, undefined, false as const); } if (right === empty) { return sparse(left, right, undefined, undefined, false as const); } if (left === dense) { if (right === dense) { return dense; } return sparse(left, right, undefined, undefined, false as const); } return sparse(left, right, undefined, undefined, false as const); } function materialize<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, set: UntypedSparse<Key>, ): UntypedSparse<Key> & TreeDefined<Key> { if (set.left !== undefined) { return set; } const [[left], [right]] = setOperations.split(set.pathKey); const lChild = lazy(setOperations, left, set.key); const rChild = lazy(setOperations, right, set.key); const res = combineChildren<Key>(lChild, rChild); if (res === empty || res === dense) { throw new Error("incorrect set operations implementation"); } // first check, that res actually has the desired type const typeCheck: TreeDefined<Key> = res; const setAlias: UntypedSparse<Key> = set; return ObjectAssign(setAlias, { left: typeCheck.left, right: typeCheck.right, }); } export function unionUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): UntypedBspSet<Key> { if (right === empty) { return left; } if (right === dense) { return right; } if (left === empty) { return right; } if (left === dense) { return left; } if (left.isExact && right.isExact) { const res = unionExact<Key, Id>(setOperations, left, right); if (res !== undefined) { return res; } } const newLeft = materialize<Key, Id>(setOperations, left); const newRight = materialize<Key, Id>(setOperations, right); const lChild = unionUntyped(setOperations, newLeft.left, newRight.left); const rChild = unionUntyped(setOperations, newLeft.right, newRight.right); return combineChildren(lChild, rChild); } export function union<Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ): BspSet<Key, Id> { if (right === empty) { return left; } if (right === dense) { return right; } if (left === empty) { return right; } if (left === dense) { return left; } return fromUntyped( left.setOperations, unionUntyped<Key, Id>(left.setOperations, left.root, right.root), ); } function intersectExact<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key> & KeyExact<Key>, right: UntypedBspSet<Key> & KeyExact<Key>, ) { const { pathKey, key: leftKey } = left; const { key: rightKey } = right; if (!setOperations.meets(leftKey, rightKey)) { return empty; } const cmp = setOperations.compare(leftKey, rightKey); if (cmp !== undefined) { return cmp < 0 ? left : right; } const combinedKey = setOperations.intersect(leftKey, rightKey); if (combinedKey !== undefined) { return fromKey(pathKey, combinedKey, true); } return undefined; } export function intersectUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): UntypedBspSet<Key> { if (left === empty) { return left; } if (right === empty) { return right; } if (left === dense) { return right; } if (right === dense) { return left; } if (left.isExact && right.isExact) { const res = intersectExact<Key, Id>(setOperations, left, right); if (res !== undefined) { return res; } } const newLeft = materialize<Key, Id>(setOperations, left); const newRight = materialize<Key, Id>(setOperations, right); const lChild = intersectUntyped(setOperations, newLeft.left, newRight.left); const rChild = intersectUntyped( setOperations, newLeft.right, newRight.right, ); return combineChildren(lChild, rChild); } export function intersect<Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ): BspSet<Key, Id> { if (left === empty) { return left; } if (right === empty) { return right; } if (left === dense) { return right; } if (right === dense) { return left; } return fromUntyped( left.setOperations, intersectUntyped<Key, Id>(left.setOperations, left.root, right.root), ); } export function meetsUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): boolean { if (left === empty || right === empty) { return false; } if (left === dense || right === dense) { return true; } if (left.isExact && right.isExact) { return setOperations.meets(left.key, right.key); } const newLeft = materialize<Key, Id>(setOperations, left); const newRight = materialize<Key, Id>(setOperations, right); return ( meetsUntyped(setOperations, newLeft.left, newRight.left) || meetsUntyped(setOperations, newLeft.right, newRight.right) ); } export function meets<Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ): boolean { if (left === empty || right === empty) { return false; } if (left === dense || right === dense) { return true; } return meetsUntyped<Key, Id>(left.setOperations, left.root, right.root); } function exceptExact<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedSparse<Key> & KeyExact<Key>, right: KeyExact<Key>, ) { const { pathKey, key: leftKey } = left; const { key: rightKey } = right; if (!setOperations.meets(leftKey, rightKey)) { return left; } const combinedKey = setOperations.except(leftKey, rightKey); if (combinedKey !== undefined) { return fromKey(pathKey, combinedKey, true); } return undefined; } export function exceptUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): UntypedBspSet<Key> { if (left === empty) { return left; } if (right === empty) { return left; } if (right === dense) { return empty; } if (left === dense) { const newRight_inner = materialize<Key, Id>(setOperations, right); const lChild_inner = exceptUntyped(setOperations, dense, newRight_inner.left); const rChild_inner = exceptUntyped(setOperations, dense, newRight_inner.right); return combineChildren(lChild_inner, rChild_inner); } if (left.isExact && right.isExact) { const res = exceptExact<Key, Id>(setOperations, left, right); if (res !== undefined) { return res; } } const newLeft = materialize<Key, Id>(setOperations, left); const newRight = materialize<Key, Id>(setOperations, right); const lChild = exceptUntyped(setOperations, newLeft.left, newRight.left); const rChild = exceptUntyped(setOperations, newLeft.right, newRight.right); return combineChildren(lChild, rChild); } export function except<Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ): BspSet<Key, Id> { if (left === empty) { return left; } if (right === empty) { return left; } if (right === dense) { return empty; } if (left === dense) { return fromUntyped( right.setOperations, exceptUntyped<Key, Id>(right.setOperations, left, right.root), ); } return fromUntyped( left.setOperations, exceptUntyped<Key, Id>(left.setOperations, left.root, right.root), ); } const compareExact = <Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: KeyExact<Key>, right: KeyExact<Key>, ) => setOperations.compare(left.key, right.key); export function combineCmp( left: -1 | 0 | 1 | undefined, right: -1 | 0 | 1 | undefined, ) { if (left === undefined || right === undefined) { return undefined; } if (left === 0) { return right; } if (right === 0) { return left; } return left === right ? left : undefined; } export function compareUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, left: UntypedBspSet<Key>, right: UntypedBspSet<Key>, ): -1 | 0 | 1 | undefined { if (left === right) { return 0; } if (left === empty) { return -1; } if (right === empty) { return 1; } if (left === dense) { if (right === dense) { return 0; } return 1; } if (right === dense) { return -1; } if (left.isExact && right.isExact) { return compareExact(setOperations, left, right); } const newLeft = materialize<Key, Id>(setOperations, left); const newRight = materialize<Key, Id>(setOperations, right); const lCmp = compareUntyped(setOperations, newLeft.left, newRight.left); if (lCmp === undefined) { return undefined; } const rCmp = compareUntyped(setOperations, newLeft.right, newRight.right); if (rCmp === undefined) { return undefined; } return combineCmp(lCmp, rCmp); } export function compare<Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ) { if (left === right) { return 0; } if (left === empty) { return -1; } if (right === empty) { return 1; } if (left === dense) { if (right === dense) { return 0; } return 1; } if (right === dense) { return -1; } return compareUntyped<Key, Id>(left.setOperations, left.root, right.root); } export const symmetricDiff = <Key extends Cachable<Key>, Id>( left: BspSet<Key, Id>, right: BspSet<Key, Id>, ) => union(except(left, right), except(right, left)); export const complement = <Key extends Cachable<Key>, Id>( set: BspSet<Key, Id>, ) => except(dense, set); function getNodeCountUntyped<T>(set: UntypedBspSet<T> | undefined): number { if (set === undefined || set === empty || set === dense) { return 0; } return getNodeCountUntyped(set.left) + getNodeCountUntyped(set.right) + 1; } export function getNodeCount<Key extends Cachable<Key>, Id>( set: BspSet<Key, Id>, ) { if (set === empty || set === dense) { return 0; } return getNodeCountUntyped(set.root); } function forEachKeyUntyped<Key extends Cachable<Key>, Id>( setOperations: SetOperations<Key, Id>, set: UntypedBspSet<Key>, f: (key: Key) => boolean, ): boolean { function loop(pathKey: Key, set_inner: UntypedBspSet<Key>): boolean { if (set_inner === empty) { return true; } if (set_inner === dense) { return f(pathKey); } if (set_inner.isExact) { return f(set_inner.key); } const newSet = materialize<Key, Id>(setOperations, set_inner); const [[left], [right]] = setOperations.split(pathKey); return loop(left, newSet.left) && loop(right, newSet.right); } return loop(setOperations.top, set); } export function forEachKey<Key extends Cachable<Key>, Id>( set: Empty | Sparse<Key, Id>, f: (key: Key) => boolean, ): boolean { if (set === empty) { return true; } return forEachKeyUntyped(set.setOperations, set.root, f); }
the_stack
import { Injectable } from '@angular/core'; import { isEqual, isObject } from 'lodash'; import { DYNAMIC_FORM_CONTROL_TYPE_ARRAY, DYNAMIC_FORM_CONTROL_TYPE_GROUP, DynamicFormArrayGroupModel, DynamicFormControlEvent, DynamicFormControlModel, isDynamicFormControlEvent } from '@ng-dynamic-forms/core'; import { hasValue, isNotEmpty, isNotNull, isNotUndefined, isNull, isUndefined } from '../../../shared/empty.util'; import { JsonPatchOperationPathCombiner } from '../../../core/json-patch/builder/json-patch-operation-path-combiner'; import { FormFieldPreviousValueObject } from '../../../shared/form/builder/models/form-field-previous-value-object'; import { JsonPatchOperationsBuilder } from '../../../core/json-patch/builder/json-patch-operations-builder'; import { FormFieldLanguageValueObject } from '../../../shared/form/builder/models/form-field-language-value.model'; import { DsDynamicInputModel } from '../../../shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model'; import { VocabularyEntry } from '../../../core/submission/vocabularies/models/vocabulary-entry.model'; import { FormBuilderService } from '../../../shared/form/builder/form-builder.service'; import { FormFieldMetadataValueObject } from '../../../shared/form/builder/models/form-field-metadata-value.model'; import { DynamicQualdropModel } from '../../../shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-qualdrop.model'; import { DynamicRelationGroupModel } from '../../../shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.model'; import { VocabularyEntryDetail } from '../../../core/submission/vocabularies/models/vocabulary-entry-detail.model'; import { deepClone } from 'fast-json-patch'; import { dateToString, isNgbDateStruct } from '../../../shared/date.util'; import { DynamicRowArrayModel } from '../../../shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-row-array-model'; /** * The service handling all form section operations */ @Injectable() export class SectionFormOperationsService { /** * Initialize service variables * * @param {FormBuilderService} formBuilder * @param {JsonPatchOperationsBuilder} operationsBuilder */ constructor( private formBuilder: FormBuilderService, private operationsBuilder: JsonPatchOperationsBuilder) { } /** * Dispatch properly method based on form operation type * * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation * @param hasStoredValue * representing if field value related to the specified operation has stored value */ public dispatchOperationsFromEvent(pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent, previousValue: FormFieldPreviousValueObject, hasStoredValue: boolean): void { switch (event.type) { case 'remove': this.dispatchOperationsFromRemoveEvent(pathCombiner, event, previousValue); break; case 'change': this.dispatchOperationsFromChangeEvent(pathCombiner, event, previousValue, hasStoredValue); break; case 'move': this.dispatchOperationsFromMoveEvent(pathCombiner, event, previousValue); break; default: break; } } /** * Return index if specified field is part of fields array * * @param event * the [[DynamicFormControlEvent]] | CustomEvent for the specified operation * @return number * the array index is part of array, zero otherwise */ public getArrayIndexFromEvent(event: DynamicFormControlEvent | any): number { let fieldIndex: number; if (isNotEmpty(event)) { if (isDynamicFormControlEvent(event)) { // This is the case of a default insertItem/removeItem event if (isNull(event.context)) { // Check whether model is part of an Array of group if (this.isPartOfArrayOfGroup(event.model)) { fieldIndex = (event.model.parent as any).parent.index; } } else { fieldIndex = event.context.index; } } else { // This is the case of a custom event which contains indexes information fieldIndex = event.index as any; } } // if field index is undefined model is not part of array of fields return isNotUndefined(fieldIndex) ? fieldIndex : 0; } /** * Check if specified model is part of array of group * * @param model * the [[DynamicFormControlModel]] model * @return boolean * true if is part of array, false otherwise */ public isPartOfArrayOfGroup(model: DynamicFormControlModel): boolean { return (isNotNull(model.parent) && (model.parent as any).type === DYNAMIC_FORM_CONTROL_TYPE_GROUP && (model.parent as any).parent && (model.parent as any).parent.context && (model.parent as any).parent.context.type === DYNAMIC_FORM_CONTROL_TYPE_ARRAY); } /** * Return a map for the values of a Qualdrop field * * @param event * the [[DynamicFormControlEvent]] for the specified operation * @return Map<string, any> * the map of values */ public getQualdropValueMap(event: DynamicFormControlEvent): Map<string, any> { const metadataValueMap = new Map(); const context = this.formBuilder.isQualdropGroup(event.model) ? (event.model.parent as DynamicFormArrayGroupModel).context : (event.model.parent.parent as DynamicFormArrayGroupModel).context; context.groups.forEach((arrayModel: DynamicFormArrayGroupModel) => { const groupModel = arrayModel.group[0] as DynamicQualdropModel; const metadataValueList = metadataValueMap.get(groupModel.qualdropId) ? metadataValueMap.get(groupModel.qualdropId) : []; if (groupModel.value) { metadataValueList.push(groupModel.value); metadataValueMap.set(groupModel.qualdropId, metadataValueList); } }); return metadataValueMap; } /** * Return the absolute path for the field interesting in the specified operation * * @param event * the [[DynamicFormControlEvent]] for the specified operation * @return string * the field path */ public getFieldPathFromEvent(event: DynamicFormControlEvent): string { const fieldIndex = this.getArrayIndexFromEvent(event); const fieldId = this.getFieldPathSegmentedFromChangeEvent(event); return (isNotUndefined(fieldIndex)) ? fieldId + '/' + fieldIndex : fieldId; } /** * Return the absolute path for the Qualdrop field interesting in the specified operation * * @param event * the [[DynamicFormControlEvent]] for the specified operation * @return string * the field path */ public getQualdropItemPathFromEvent(event: DynamicFormControlEvent): string { const fieldIndex = this.getArrayIndexFromEvent(event); const metadataValueMap = new Map(); let path = null; const context = this.formBuilder.isQualdropGroup(event.model) ? (event.model.parent as DynamicFormArrayGroupModel).context : (event.model.parent.parent as DynamicFormArrayGroupModel).context; context.groups.forEach((arrayModel: DynamicFormArrayGroupModel, index: number) => { const groupModel = arrayModel.group[0] as DynamicQualdropModel; const metadataValueList = metadataValueMap.get(groupModel.qualdropId) ? metadataValueMap.get(groupModel.qualdropId) : []; if (groupModel.value) { metadataValueList.push(groupModel.value); metadataValueMap.set(groupModel.qualdropId, metadataValueList); } if (index === fieldIndex) { path = groupModel.qualdropId + '/' + (metadataValueList.length - 1); } }); return path; } /** * Return the segmented path for the field interesting in the specified change operation * * @param event * the [[DynamicFormControlEvent]] for the specified operation * @return string * the field path */ public getFieldPathSegmentedFromChangeEvent(event: DynamicFormControlEvent): string { let fieldId; if (this.formBuilder.isQualdropGroup(event.model as DynamicFormControlModel)) { fieldId = (event.model as any).qualdropId; } else if (this.formBuilder.isQualdropGroup(event.model.parent as DynamicFormControlModel)) { fieldId = (event.model.parent as any).qualdropId; } else { fieldId = this.formBuilder.getId(event.model); } return fieldId; } /** * Return the value of the field interesting in the specified change operation * * @param event * the [[DynamicFormControlEvent]] for the specified operation * @return any * the field value */ public getFieldValueFromChangeEvent(event: DynamicFormControlEvent): any { let fieldValue; const value = (event.model as any).value; if (this.formBuilder.isModelInCustomGroup(event.model)) { fieldValue = (event.model.parent as any).value; } else if (this.formBuilder.isRelationGroup(event.model)) { fieldValue = (event.model as DynamicRelationGroupModel).getGroupValue(); } else if ((event.model as any).hasLanguages) { const language = (event.model as any).language; if ((event.model as DsDynamicInputModel).hasAuthority) { if (Array.isArray(value)) { value.forEach((authority, index) => { authority = Object.assign(new VocabularyEntry(), authority, { language }); value[index] = authority; }); fieldValue = value; } else { fieldValue = Object.assign(new VocabularyEntry(), value, { language }); } } else { // Language without Authority (input, textArea) fieldValue = new FormFieldMetadataValueObject(value, language); } } else if (isNgbDateStruct(value)) { fieldValue = new FormFieldMetadataValueObject(dateToString(value)); } else if (value instanceof FormFieldLanguageValueObject || value instanceof VocabularyEntry || value instanceof VocabularyEntryDetail || isObject(value)) { fieldValue = value; } else { fieldValue = new FormFieldMetadataValueObject(value); } return fieldValue; } /** * Return a map for the values of an array of field * * @param items * the list of items * @return Map<string, any> * the map of values */ public getValueMap(items: any[]): Map<string, any> { const metadataValueMap = new Map(); items.forEach((item) => { Object.keys(item) .forEach((key) => { const metadataValueList = metadataValueMap.get(key) ? metadataValueMap.get(key) : []; metadataValueList.push(item[key]); metadataValueMap.set(key, metadataValueList); }); }); return metadataValueMap; } /** * Handle form remove operations * * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation */ protected dispatchOperationsFromRemoveEvent(pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent, previousValue: FormFieldPreviousValueObject): void { const path = this.getFieldPathFromEvent(event); const value = this.getFieldValueFromChangeEvent(event); if (this.formBuilder.isQualdropGroup(event.model as DynamicFormControlModel)) { this.dispatchOperationsFromMap(this.getQualdropValueMap(event), pathCombiner, event, previousValue); } else if (event.context && event.context instanceof DynamicFormArrayGroupModel) { // Model is a DynamicRowArrayModel this.handleArrayGroupPatch(pathCombiner, event, (event as any).context.context, previousValue); } else if ((isNotEmpty(value) && typeof value === 'string') || (isNotEmpty(value) && value instanceof FormFieldMetadataValueObject && value.hasValue())) { this.operationsBuilder.remove(pathCombiner.getPath(path)); } } /** * Handle form add operations * * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation */ protected dispatchOperationsFromAddEvent( pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent ): void { const path = this.getFieldPathSegmentedFromChangeEvent(event); const value = deepClone(this.getFieldValueFromChangeEvent(event)); if (isNotEmpty(value)) { value.place = this.getArrayIndexFromEvent(event); if (hasValue(event.group) && hasValue(event.group.value)) { const valuesInGroup = event.group.value .map((g) => Object.values(g)) .reduce((accumulator, currentValue) => accumulator.concat(currentValue)) .filter((v) => isNotEmpty(v)); if (valuesInGroup.length === 1) { // The first add for a field needs to be a different PATCH operation // for some reason this.operationsBuilder.add( pathCombiner.getPath([path]), [value], false); } else { this.operationsBuilder.add( pathCombiner.getPath([path, '-']), value, false); } } } } /** * Handle form change operations * * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation * @param hasStoredValue * representing if field value related to the specified operation has stored value */ protected dispatchOperationsFromChangeEvent(pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent, previousValue: FormFieldPreviousValueObject, hasStoredValue: boolean): void { if (event.context && event.context instanceof DynamicFormArrayGroupModel) { // Model is a DynamicRowArrayModel this.handleArrayGroupPatch(pathCombiner, event, (event as any).context.context, previousValue); return; } const path = this.getFieldPathFromEvent(event); const segmentedPath = this.getFieldPathSegmentedFromChangeEvent(event); const value = this.getFieldValueFromChangeEvent(event); // Detect which operation must be dispatched if (this.formBuilder.isQualdropGroup(event.model.parent as DynamicFormControlModel) || this.formBuilder.isQualdropGroup(event.model as DynamicFormControlModel)) { // It's a qualdrup model this.dispatchOperationsFromMap(this.getQualdropValueMap(event), pathCombiner, event, previousValue); } else if (this.formBuilder.isRelationGroup(event.model)) { // It's a relation model this.dispatchOperationsFromMap(this.getValueMap(value), pathCombiner, event, previousValue); } else if (this.formBuilder.hasArrayGroupValue(event.model)) { // Model has as value an array, so dispatch an add operation with entire block of values this.operationsBuilder.add( pathCombiner.getPath(segmentedPath), value, true); } else if (previousValue.isPathEqual(this.formBuilder.getPath(event.model)) || (hasStoredValue && isNotEmpty(previousValue.value)) ) { // Here model has a previous value changed or stored in the server if (hasValue(event.$event) && hasValue(event.$event.previousIndex)) { if (event.$event.previousIndex < 0) { this.operationsBuilder.add( pathCombiner.getPath(segmentedPath), value, true); } else { const moveTo = pathCombiner.getPath(path); const moveFrom = pathCombiner.getPath(segmentedPath + '/' + event.$event.previousIndex); if (isNotEmpty(moveFrom.path) && isNotEmpty(moveTo.path) && moveFrom.path !== moveTo.path) { this.operationsBuilder.move( moveTo, moveFrom.path ); } } } else if (!value.hasValue()) { // New value is empty, so dispatch a remove operation if (this.getArrayIndexFromEvent(event) === 0) { this.operationsBuilder.remove(pathCombiner.getPath(segmentedPath)); } else { this.operationsBuilder.remove(pathCombiner.getPath(path)); } } else { // New value is not equal from the previous one, so dispatch a replace operation this.operationsBuilder.replace( pathCombiner.getPath(path), value); } previousValue.delete(); } else if (value.hasValue()) { // Here model has no previous value but a new one if (isUndefined(this.getArrayIndexFromEvent(event)) || this.getArrayIndexFromEvent(event) === 0) { // Model is single field or is part of an array model but is the first item, // so dispatch an add operation that initialize the values of a specific metadata this.operationsBuilder.add( pathCombiner.getPath(segmentedPath), value, true); } else { // Model is part of an array model but is not the first item, // so dispatch an add operation that add a value to an existent metadata this.operationsBuilder.add( pathCombiner.getPath(path), value); } } } /** * Handle form operations interesting a field with a map as value * * @param valueMap * map of values * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation */ protected dispatchOperationsFromMap(valueMap: Map<string, any>, pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent, previousValue: FormFieldPreviousValueObject): void { const currentValueMap = valueMap; if (event.type === 'remove') { const path = this.getQualdropItemPathFromEvent(event); this.operationsBuilder.remove(pathCombiner.getPath(path)); } else { if (previousValue.isPathEqual(this.formBuilder.getPath(event.model))) { previousValue.value.forEach((entry, index) => { const currentValue = currentValueMap.get(index); if (currentValue) { if (!isEqual(entry, currentValue)) { this.operationsBuilder.add(pathCombiner.getPath(index), currentValue, true); } currentValueMap.delete(index); } else if (!currentValue) { this.operationsBuilder.remove(pathCombiner.getPath(index)); } }); } currentValueMap.forEach((entry: any[], index) => { if (entry.length === 1 && isNull(entry[0])) { // The last item of the group has been deleted so make a remove op this.operationsBuilder.remove(pathCombiner.getPath(index)); } else { this.operationsBuilder.add(pathCombiner.getPath(index), entry, true); } }); } previousValue.delete(); } /** * Handle form move operations * * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation */ private dispatchOperationsFromMoveEvent(pathCombiner: JsonPatchOperationPathCombiner, event: DynamicFormControlEvent, previousValue: FormFieldPreviousValueObject) { return this.handleArrayGroupPatch(pathCombiner, event.$event, (event as any).$event.arrayModel, previousValue); } /** * Specific patch handler for a DynamicRowArrayModel. * Configure a Patch ADD with the current array value. * @param pathCombiner * the [[JsonPatchOperationPathCombiner]] object for the specified operation * @param event * the [[DynamicFormControlEvent]] for the specified operation * @param model * the [[DynamicRowArrayModel]] model * @param previousValue * the [[FormFieldPreviousValueObject]] for the specified operation */ private handleArrayGroupPatch(pathCombiner: JsonPatchOperationPathCombiner, event, model: DynamicRowArrayModel, previousValue: FormFieldPreviousValueObject) { const arrayValue = this.formBuilder.getValueFromModel([model]); const segmentedPath = this.getFieldPathSegmentedFromChangeEvent(event); if (isNotEmpty(arrayValue)) { this.operationsBuilder.add( pathCombiner.getPath(segmentedPath), arrayValue[segmentedPath], false ); } else if (previousValue.isPathEqual(this.formBuilder.getPath(event.model))) { this.operationsBuilder.remove(pathCombiner.getPath(segmentedPath)); } } }
the_stack
import assert from 'assert'; import * as Grammar from '../syntax_api'; import { NotCompilableError } from '../utils/errors'; import * as Ast from '../ast'; import { TypeMap } from '../type'; import * as JSIr from './jsir'; import { compileActionToOps, compileStatementToOp, compileTableToOps } from './ast-to-ops'; import { QueryInvocationHints } from './ops'; import { getDefaultProjection } from './utils'; import OpCompiler from './ops-to-jsir'; import Scope from './scope'; import { CompiledProgram, CompiledStatement } from '../runtime/exec_environment'; import type SchemaRetriever from '../schema'; type TopLevelScope = { [key : string] : CompiledStatement|string }; interface StatementCompileOptions { hasAnyStream : boolean; forProcedure : boolean; } export default class AppCompiler { private _testMode : boolean; private _declarations : Scope; private _toplevelscope : TopLevelScope; private _schemaRetriever : SchemaRetriever; private _nextStateVar : number; private _nextProcId : number; private _astVars : Ast.Node[]; constructor(schemaRetriever : SchemaRetriever, testMode = false) { this._testMode = testMode; this._declarations = new Scope; this._toplevelscope = {}; this._schemaRetriever = schemaRetriever; this._nextStateVar = 0; this._nextProcId = 0; this._astVars = []; } compileCode(code : string, options : Grammar.ParseOptions = { timezone: undefined }) : Promise<CompiledProgram> { const parsed = Grammar.parse(code, Grammar.SyntaxType.Normal, options); if (!(parsed instanceof Ast.Program)) throw new Error(`Not an executable program`); return this.compileProgram(parsed); } _allocState() : number { return this._nextStateVar++; } _allocAst(v : Ast.Node) : number { this._astVars.push(v); return this._astVars.length-1; } private _declareArguments(args : TypeMap, scope : Scope, irBuilder : JSIr.IRBuilder) { const compiledArgs = []; for (const name in args) { const reg = irBuilder.allocArgument(); scope.set(name, { type: 'scalar', tt_type: args[name], register: reg, direction: 'input', isInVarScopeNames: false }); compiledArgs.push(name); } return compiledArgs; } private _compileAssignment(assignment : Ast.Assignment, irBuilder : JSIr.IRBuilder, { hasAnyStream, forProcedure } : StatementCompileOptions) { const opCompiler = new OpCompiler(this, this._declarations, irBuilder); // at the top level, assignments can be referred to by streams, so // they need to be persistent (save to disk) such that when the program // is restarted, the result can be reused. // (this is only needed in top-level since stream is not allowed within // procedures) const isPersistent = hasAnyStream; let register; if (assignment.isAction) { const action = compileActionToOps(assignment.value, new Set, null); register = opCompiler.compileActionAssignment(action, isPersistent); } else { const schema = assignment.value.schema; assert(schema); const hints = new QueryInvocationHints(new Set(getDefaultProjection(schema))); const tableop = compileTableToOps(assignment.value, hints); register = opCompiler.compileAssignment(tableop, isPersistent); } const schema = assignment.schema; assert(schema); this._declarations.set(assignment.name, { type: 'assignment', isPersistent, register, schema }); } private _compileProcedure(decl : Ast.FunctionDeclaration, parentIRBuilder : JSIr.IRBuilder|null) { const saveScope = this._declarations; const irBuilder = new JSIr.IRBuilder(parentIRBuilder ? parentIRBuilder.nextRegister : 0, ['__emit']); const procid = this._nextProcId++; irBuilder.setBeginEndHooks( new JSIr.EnterProcedure(procid, decl.name), new JSIr.ExitProcedure(procid, decl.name) ); const procedureScope = new Scope(this._declarations); const args = this._declareArguments(decl.args, procedureScope, irBuilder); this._declarations = procedureScope; this._compileInScope(decl.declarations, decl.statements, irBuilder, { hasAnyStream: false, forProcedure: true }); let code; let register; if (parentIRBuilder) { parentIRBuilder.skipRegisterRange(irBuilder.registerRange); register = parentIRBuilder.allocRegister(); parentIRBuilder.add(new JSIr.AsyncFunctionDeclaration(register, irBuilder)); code = null; } else { register = null; code = this._testMode ? irBuilder.codegen() : irBuilder.compile(this._toplevelscope, this._astVars); this._toplevelscope[decl.name] = code; } this._declarations = saveScope; assert(decl.schema); this._declarations.set(decl.name, { type: 'procedure', args, code, register, schema: decl.schema, }); } private _doCompileStatement(stmt : Ast.ExpressionStatement|Ast.ReturnStatement, irBuilder : JSIr.IRBuilder, forProcedure : boolean, returnResult : boolean) { const opCompiler = new OpCompiler(this, this._declarations, irBuilder); const ruleop = compileStatementToOp(stmt); if (forProcedure) opCompiler.compileProcedureStatement(ruleop, returnResult); else opCompiler.compileStatement(ruleop); } private _compileRule(rule : Ast.ExpressionStatement) : CompiledStatement { // each rule goes into its own JS function const irBuilder = new JSIr.IRBuilder(); this._doCompileStatement(rule, irBuilder, false, false); return this._testMode ? irBuilder.codegen() as unknown as CompiledStatement : irBuilder.compile(this._toplevelscope, this._astVars); } private _compileInScope(declarations : Ast.FunctionDeclaration[], stmts : Ast.ExecutableStatement[], irBuilder : JSIr.IRBuilder|null, { hasAnyStream, forProcedure } : StatementCompileOptions) { for (const decl of declarations) this._compileProcedure(decl, irBuilder); if (stmts.length === 0) return null; // all immediate statements are compiled into a single function, so we // create a single irBuilder that we share if (!irBuilder) { irBuilder = new JSIr.IRBuilder(); const procid = this._nextProcId++; irBuilder.setBeginEndHooks( new JSIr.EnterProcedure(procid), new JSIr.ExitProcedure(procid) ); } // compute which statement will produce the procedure return value // // - if there is an explicit "return" statement, that's the one to use // (this is the "new" way to do things) // - if there is a query statement, the last one wins // - otherwise, the last statement wins let returnStmtIdx = -1, resultStmtIdx = -1; for (let i = 0; i < stmts.length; i++) { const stmt = stmts[i]; if (stmt instanceof Ast.ReturnStatement) { returnStmtIdx = i; } else if (stmt instanceof Ast.ExpressionStatement) { if (stmt.expression.schema!.functionType === 'query') { resultStmtIdx = i; } else { if (resultStmtIdx < 0) resultStmtIdx = i; } } } if (returnStmtIdx < 0) returnStmtIdx = resultStmtIdx; for (let i = 0; i < stmts.length; i++) { // if this is not the first statement, clear the get cache before running it if (i !== 0) irBuilder.add(new JSIr.ClearGetCache()); const stmt = stmts[i]; if (stmt instanceof Ast.Assignment) this._compileAssignment(stmt, irBuilder, { hasAnyStream, forProcedure }); else this._doCompileStatement(stmt, irBuilder, forProcedure, i === returnStmtIdx); } return irBuilder; } private _verifyCompilable(program : Ast.Program) { if (program.principal !== null) throw new NotCompilableError(`Remote programs cannot be compiled, they must be sent to a different runtime instead`); for (const slot of program.iterateSlots2()) { if (slot instanceof Ast.DeviceSelector) { if (slot.principal !== null) throw new NotCompilableError(`Remote primitives cannot be compiled, they must be lowered and sent to a different runtime instead`); continue; } if (!slot.isCompilable()) throw new NotCompilableError(`Programs with slots or unresolved values cannot be compiled, and must be slot-filled first`); } } async compileProgram(program : Ast.Program) : Promise<CompiledProgram> { await program.typecheck(this._schemaRetriever); this._verifyCompilable(program); const compiledRules : CompiledStatement[] = []; const immediate : Array<Ast.Assignment|Ast.ExpressionStatement> = []; const rules : Ast.ExpressionStatement[] = []; for (const stmt of program.statements) { if (stmt instanceof Ast.Assignment || !stmt.stream) immediate.push(stmt); else rules.push(stmt); } this._declarations = new Scope; const commandIRBuilder = this._compileInScope(program.declarations, immediate, null, { hasAnyStream: rules.length > 0, forProcedure: false }); let compiledCommand; if (commandIRBuilder !== null) { // HACK: in test mode, we compile a string instead of a function // we use an unsound cast to avoid exposing this in the compiler public API if (this._testMode) compiledCommand = commandIRBuilder.codegen() as unknown as CompiledStatement; else compiledCommand = commandIRBuilder.compile(this._toplevelscope, this._astVars); } else { compiledCommand = null; } for (const rule of rules) compiledRules.push(this._compileRule(rule)); return new CompiledProgram(this._nextStateVar, compiledCommand, compiledRules); } }
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "@swim/component"; import type {AnyController, Controller} from "./Controller"; import {ControllerRelationInit, ControllerRelationClass, ControllerRelation} from "./ControllerRelation"; /** @internal */ export type ControllerSetType<F extends ControllerSet<any, any>> = F extends ControllerSet<any, infer C> ? C : never; /** @public */ export interface ControllerSetInit<C extends Controller = Controller> extends ControllerRelationInit<C> { extends?: {prototype: ControllerSet<any, any>} | string | boolean | null; key?(controller: C): string | undefined; compare?(a: C, b: C): number; sorted?: boolean; willSort?(parent: Controller | null): void; didSort?(parent: Controller | null): void; sortChildren?(parent: Controller): void; compareChildren?(a: Controller, b: Controller): number; } /** @public */ export type ControllerSetDescriptor<O = unknown, C extends Controller = Controller, I = {}> = ThisType<ControllerSet<O, C> & I> & ControllerSetInit<C> & Partial<I>; /** @public */ export interface ControllerSetClass<F extends ControllerSet<any, any> = ControllerSet<any, any>> extends ControllerRelationClass<F> { /** @internal */ readonly SortedFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ControllerSetFactory<F extends ControllerSet<any, any> = ControllerSet<any, any>> extends ControllerSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ControllerSetFactory<F> & I; define<O, C extends Controller = Controller>(className: string, descriptor: ControllerSetDescriptor<O, C>): ControllerSetFactory<ControllerSet<any, C>>; define<O, C extends Controller = Controller>(className: string, descriptor: {observes: boolean} & ControllerSetDescriptor<O, C, ObserverType<C>>): ControllerSetFactory<ControllerSet<any, C>>; define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown} & ControllerSetDescriptor<O, C, I>): ControllerSetFactory<ControllerSet<any, C> & I>; define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ControllerSetDescriptor<O, C, I & ObserverType<C>>): ControllerSetFactory<ControllerSet<any, C> & I>; <O, C extends Controller = Controller>(descriptor: ControllerSetDescriptor<O, C>): PropertyDecorator; <O, C extends Controller = Controller>(descriptor: {observes: boolean} & ControllerSetDescriptor<O, C, ObserverType<C>>): PropertyDecorator; <O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown} & ControllerSetDescriptor<O, C, I>): PropertyDecorator; <O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown; observes: boolean} & ControllerSetDescriptor<O, C, I & ObserverType<C>>): PropertyDecorator; } /** @public */ export interface ControllerSet<O = unknown, C extends Controller = Controller> extends ControllerRelation<O, C> { (controller: AnyController<C>): O; /** @override */ get fastenerType(): Proto<ControllerSet<any, any>>; /** @internal */ readonly controllers: {readonly [controllerId: number]: C | undefined}; readonly controllerCount: number; hasController(controller: Controller): boolean; addController(controller?: AnyController<C>, target?: Controller | null, key?: string): C; attachController(controller?: AnyController<C>, target?: Controller | null): C; detachController(controller: C): C | null; insertController(parent?: Controller | null, controller?: AnyController<C>, target?: Controller | null, key?: string): C; removeController(controller: C): C | null; deleteController(controller: C): C | null; /** @internal @override */ bindController(controller: Controller, target: Controller | null): void; /** @internal @override */ unbindController(controller: Controller): void; /** @override */ detectController(controller: Controller): C | null; /** @internal @protected */ key(controller: C): string | undefined; get sorted(): boolean; /** @internal */ initSorted(sorted: boolean): void; sort(sorted?: boolean): this; /** @protected */ willSort(parent: Controller | null): void; /** @protected */ onSort(parent: Controller | null): void; /** @protected */ didSort(parent: Controller | null): void; /** @internal @protected */ sortChildren(parent: Controller): void; /** @internal */ compareChildren(a: Controller, b: Controller): number; /** @internal @protected */ compare(a: C, b: C): number; } /** @public */ export const ControllerSet = (function (_super: typeof ControllerRelation) { const ControllerSet: ControllerSetFactory = _super.extend("ControllerSet"); Object.defineProperty(ControllerSet.prototype, "fastenerType", { get: function (this: ControllerSet): Proto<ControllerSet<any, any>> { return ControllerSet; }, configurable: true, }); ControllerSet.prototype.hasController = function (this: ControllerSet, controller: Controller): boolean { return this.controllers[controller.uid] !== void 0; }; ControllerSet.prototype.addController = function <C extends Controller>(this: ControllerSet<unknown, C>, newController?: AnyController<C>, target?: Controller | null, key?: string): C { if (newController !== void 0 && newController !== null) { newController = this.fromAny(newController); } else { newController = this.createController(); } if (target === void 0) { target = null; } let parent: Controller | null; if (this.binds && (parent = this.parentController, parent !== null)) { if (key === void 0) { key = this.key(newController); } this.insertChild(parent, newController, target, key); } const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (controllers[newController.uid] === void 0) { this.willAttachController(newController, target); controllers[newController.uid] = newController; (this as Mutable<typeof this>).controllerCount += 1; this.onAttachController(newController, target); this.initController(newController); this.didAttachController(newController, target); } return newController; }; ControllerSet.prototype.attachController = function <C extends Controller>(this: ControllerSet<unknown, C>, newController?: AnyController<C>, target?: Controller | null): C { if (newController !== void 0 && newController !== null) { newController = this.fromAny(newController); } else { newController = this.createController(); } const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (controllers[newController.uid] === void 0) { if (target === void 0) { target = null; } this.willAttachController(newController, target); controllers[newController.uid] = newController; (this as Mutable<typeof this>).controllerCount += 1; this.onAttachController(newController, target); this.initController(newController); this.didAttachController(newController, target); } return newController; }; ControllerSet.prototype.detachController = function <C extends Controller>(this: ControllerSet<unknown, C>, oldController: C): C | null { const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (controllers[oldController.uid] !== void 0) { this.willDetachController(oldController); (this as Mutable<typeof this>).controllerCount -= 1; delete controllers[oldController.uid]; this.onDetachController(oldController); this.deinitController(oldController); this.didDetachController(oldController); return oldController; } return null; }; ControllerSet.prototype.insertController = function <C extends Controller>(this: ControllerSet<unknown, C>, parent?: Controller | null, newController?: AnyController<C>, target?: Controller | null, key?: string): C { if (newController !== void 0 && newController !== null) { newController = this.fromAny(newController); } else { newController = this.createController(); } if (parent === void 0 || parent === null) { parent = this.parentController; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key(newController); } if (parent !== null && (newController.parent !== parent || newController.key !== key)) { this.insertChild(parent, newController, target, key); } const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (controllers[newController.uid] === void 0) { this.willAttachController(newController, target); controllers[newController.uid] = newController; (this as Mutable<typeof this>).controllerCount += 1; this.onAttachController(newController, target); this.initController(newController); this.didAttachController(newController, target); } return newController; }; ControllerSet.prototype.removeController = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: C): C | null { if (this.hasController(controller)) { controller.remove(); return controller; } return null; }; ControllerSet.prototype.deleteController = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: C): C | null { const oldController = this.detachController(controller); if (oldController !== null) { oldController.remove(); } return oldController; }; ControllerSet.prototype.bindController = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: Controller, target: Controller | null): void { if (this.binds) { const newController = this.detectController(controller); const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (newController !== null && controllers[newController.uid] === void 0) { this.willAttachController(newController, target); controllers[newController.uid] = newController; (this as Mutable<typeof this>).controllerCount += 1; this.onAttachController(newController, target); this.initController(newController); this.didAttachController(newController, target); } } }; ControllerSet.prototype.unbindController = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: Controller): void { if (this.binds) { const oldController = this.detectController(controller); const controllers = this.controllers as {[comtrollerId: number]: C | undefined}; if (oldController !== null && controllers[oldController.uid] !== void 0) { this.willDetachController(oldController); (this as Mutable<typeof this>).controllerCount -= 1; delete controllers[oldController.uid]; this.onDetachController(oldController); this.deinitController(oldController); this.didDetachController(oldController); } } }; ControllerSet.prototype.detectController = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: Controller): C | null { if (typeof this.type === "function" && controller instanceof this.type) { return controller as C; } return null; }; ControllerSet.prototype.key = function <C extends Controller>(this: ControllerSet<unknown, C>, controller: C): string | undefined { return void 0; }; Object.defineProperty(ControllerSet.prototype, "sorted", { get(this: ControllerSet): boolean { return (this.flags & ControllerSet.SortedFlag) !== 0; }, configurable: true, }); ControllerSet.prototype.initInherits = function (this: ControllerSet, sorted: boolean): void { if (sorted) { (this as Mutable<typeof this>).flags = this.flags | ControllerSet.SortedFlag; } else { (this as Mutable<typeof this>).flags = this.flags & ~ControllerSet.SortedFlag; } }; ControllerSet.prototype.sort = function (this: ControllerSet, sorted?: boolean): typeof this { if (sorted === void 0) { sorted = true; } const flags = this.flags; if (sorted && (flags & ControllerSet.SortedFlag) === 0) { const parent = this.parentController; this.willSort(parent); this.setFlags(flags | ControllerSet.SortedFlag); this.onSort(parent); this.didSort(parent); } else if (!sorted && (flags & ControllerSet.SortedFlag) !== 0) { this.setFlags(flags & ~ControllerSet.SortedFlag); } return this; }; ControllerSet.prototype.willSort = function (this: ControllerSet, parent: Controller | null): void { // hook }; ControllerSet.prototype.onSort = function (this: ControllerSet, parent: Controller | null): void { if (parent !== null) { this.sortChildren(parent); } }; ControllerSet.prototype.didSort = function (this: ControllerSet, parent: Controller | null): void { // hook }; ControllerSet.prototype.sortChildren = function <C extends Controller>(this: ControllerSet<unknown, C>, parent: Controller): void { parent.sortChildren(this.compareChildren.bind(this)); }; ControllerSet.prototype.compareChildren = function <C extends Controller>(this: ControllerSet<unknown, C>, a: Controller, b: Controller): number { const controllers = this.controllers; const x = controllers[a.uid]; const y = controllers[b.uid]; if (x !== void 0 && y !== void 0) { return this.compare(x, y); } else { return x !== void 0 ? 1 : y !== void 0 ? -1 : 0; } }; ControllerSet.prototype.compare = function <C extends Controller>(this: ControllerSet<unknown, C>, a: C, b: C): number { return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0; }; ControllerSet.construct = function <F extends ControllerSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (newController: AnyController<ControllerSetType<F>>): FastenerOwner<F> { fastener!.addController(newController); return fastener!.owner; } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).controllers = {}; (fastener as Mutable<typeof fastener>).controllerCount = 0; return fastener; }; ControllerSet.define = function <O, C extends Controller>(className: string, descriptor: ControllerSetDescriptor<O, C>): ControllerSetFactory<ControllerSet<any, C>> { let superClass = descriptor.extends as ControllerSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: ControllerSet<any, any>}, fastener: ControllerSet<O, C> | null, owner: O): ControllerSet<O, C> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; (ControllerSet as Mutable<typeof ControllerSet>).SortedFlag = 1 << (_super.FlagShift + 0); (ControllerSet as Mutable<typeof ControllerSet>).FlagShift = _super.FlagShift + 1; (ControllerSet as Mutable<typeof ControllerSet>).FlagMask = (1 << ControllerSet.FlagShift) - 1; return ControllerSet; })(ControllerRelation);
the_stack
import { AccountInfo, AuthenticationResult, AuthError, AuthorizationCodeRequest, AuthorizationUrlRequest, Configuration, ICachePlugin, LogLevel, PublicClientApplication } from '@azure/msal-node'; import { AuthenticationProviderOptions } from '@microsoft/microsoft-graph-client/lib/es/IAuthenticationProviderOptions'; import { BrowserWindow, ipcMain } from 'electron'; import { CustomFileProtocolListener } from './CustomFileProtocol'; import { REDIRECT_URI, COMMON_AUTHORITY_URL } from './Constants'; /** * base config for MSAL authentication * * @interface MsalElectronConfig */ export interface MsalElectronConfig { /** * Client ID alphanumeric code * * @type {string} * @memberof MsalElectronConfig */ clientId: string; /** * Main window instance * * @type {BrowserWindow} * @memberof MsalElectronConfig */ mainWindow: BrowserWindow; /** * Config authority * * @type {string} * @memberof MsalElectronConfig */ authority?: string; /** * List of scopes * * @type {string[]} * @memberof MsalElectronConfig */ scopes?: string[]; /** * Cache plugin to enable persistent caching * * @type {ICachePlugin} * @memberof MsalElectronConfig */ cachePlugin?: ICachePlugin; } /** * Prompt type for consent or login * * @enum {number} */ enum promptType { SELECT_ACCOUNT = 'select_account' } /** * State of Authentication Provider * * @enum {number} */ enum AuthState { LOGGED_IN = 'logged_in', LOGGED_OUT = 'logged_out' } /** * ElectronAuthenticator class to be instantiated in the main process. * Responsible for MSAL authentication flow and token acqusition. * * @export * @class ElectronAuthenticator */ export class ElectronAuthenticator { /** * Configuration for MSAL Authentication * * @private * @type {Configuration} * @memberof ElectronAuthenticator */ private ms_config: Configuration; /** * Application instance * * @type {PublicClientApplication} * @memberof ElectronAuthenticator */ public clientApplication: PublicClientApplication; /** * Mainwindow instance * * @type {BrowserWindow} * @memberof ElectronAuthenticator */ public mainWindow: BrowserWindow; //Popup which will take the user through the login/consent process /** * * * @type {BrowserWindow} * @memberof ElectronAuthenticator */ public authWindow: BrowserWindow; /** * Logged in account * * @private * @type {AccountInfo} * @memberof ElectronAuthenticator */ private account: AccountInfo; /** * Params to generate the URL for MSAL auth * * @private * @type {AuthorizationUrlRequest} * @memberof ElectronAuthenticator */ private authCodeUrlParams: AuthorizationUrlRequest; /** * Request for authentication call * * @private * @type {AuthorizationCodeRequest} * @memberof ElectronAuthenticator */ private authCodeRequest: AuthorizationCodeRequest; /** * Listener that will listen for auth code in response * * @private * @type {CustomFileProtocolListener} * @memberof ElectronAuthenticator */ private authCodeListener: CustomFileProtocolListener; /** * Instance of the authenticator * * @private * @static * @type {ElectronAuthenticator} * @memberof ElectronAuthenticator */ private static authInstance: ElectronAuthenticator; /** * Creates an instance of ElectronAuthenticator. * @param {MsalElectronConfig} config * @memberof ElectronAuthenticator */ private constructor(config: MsalElectronConfig) { this.setConfig(config); this.account = null; this.mainWindow = config.mainWindow; this.setRequestObjects(config.scopes); this.setupProvider(); } /** * Initialize the authenticator. Call this method in your main process to create an instance of ElectronAuthenticator. * * @static * @param {MsalElectronConfig} config * @memberof ElectronAuthenticator */ public static initialize(config: MsalElectronConfig) { if (!ElectronAuthenticator.instance) { ElectronAuthenticator.authInstance = new ElectronAuthenticator(config); } } /** * Getter for the ElectronAuthenticator instance. * * @readonly * @memberof ElectronAuthenticator */ public static get instance() { return this.authInstance; } /** * Setting up config for MSAL auth * * @private * @param {MsalElectronConfig} config * @memberof ElectronAuthenticator */ private async setConfig(config: MsalElectronConfig) { this.ms_config = { auth: { clientId: config.clientId, authority: config.authority ? config.authority : COMMON_AUTHORITY_URL }, cache: config.cachePlugin ? { cachePlugin: config.cachePlugin } : null, system: { loggerOptions: { loggerCallback(loglevel, message, containsPii) {}, piiLoggingEnabled: false, logLevel: LogLevel.Warning } } }; this.clientApplication = new PublicClientApplication(this.ms_config); } /** * Set up request parameters * * @protected * @param {*} [scopes] * @memberof ElectronAuthenticator */ protected setRequestObjects(scopes?): void { const requestScopes = scopes ? scopes : []; const redirectUri = REDIRECT_URI; this.authCodeUrlParams = { scopes: requestScopes, redirectUri: redirectUri }; this.authCodeRequest = { scopes: requestScopes, redirectUri: redirectUri, code: null }; } /** * Set up an auth window with an option to be visible (invisible during silent sign in) * * @protected * @param {boolean} visible * @memberof ElectronAuthenticator */ protected setAuthWindow(visible: boolean) { this.authWindow = new BrowserWindow({ show: visible }); } /** * Set up messaging between authenticator and provider * @protected * @memberof ElectronAuthenticator */ protected setupProvider() { this.mainWindow.webContents.on('did-finish-load', async () => { await this.attemptSilentLogin(); }); ipcMain.handle('login', async () => { const account = await this.login(); if (account) { this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_IN); } else { this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_OUT); } }); ipcMain.handle('token', async (e, options: AuthenticationProviderOptions) => { try { const token = await this.getAccessToken(options); return token; } catch (e) { throw e; } }); ipcMain.handle('logout', async () => { await this.logout(); this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_OUT); }); } /** * Get access token * * @protected * @param {AuthenticationProviderOptions} [options] * @return {*} {Promise<string>} * @memberof ElectronAuthenticator */ protected async getAccessToken(options?: AuthenticationProviderOptions): Promise<string> { let authResponse; const scopes = options && options.scopes ? options.scopes : this.authCodeUrlParams.scopes; const account = this.account || (await this.getAccount()); if (account) { const request = { account, scopes, forceRefresh: false }; authResponse = await this.getTokenSilent(request, scopes); } if (authResponse) { return authResponse.accessToken; } } /** * Get token silently if available * * @protected * @param {*} tokenRequest * @param {*} [scopes] * @return {*} {Promise<AuthenticationResult>} * @memberof ElectronAuthenticator */ protected async getTokenSilent(tokenRequest, scopes?): Promise<AuthenticationResult> { try { return await this.clientApplication.acquireTokenSilent(tokenRequest); } catch (error) { return null; } } /** * Login (open popup and allow user to select account/login) * @private * @return {*} * @memberof ElectronAuthenticator */ protected async login() { const authResponse = await this.getTokenInteractive(promptType.SELECT_ACCOUNT); return this.setAccountFromResponse(authResponse); } /** * Logout * * @private * @return {*} {Promise<void>} * @memberof ElectronAuthenticator */ protected async logout(): Promise<void> { if (this.account) { await this.clientApplication.getTokenCache().removeAccount(this.account); this.account = null; } } /** * Set this.account to current logged in account * * @private * @param {AuthenticationResult} response * @return {*} * @memberof ElectronAuthenticator */ private async setAccountFromResponse(response: AuthenticationResult) { if (response !== null) { this.account = response.account; } else { this.account = await this.getAccount(); } return this.account; } /** * Get token interactively and optionally allow prompt to select account * * @protected * @param {promptType} prompt_type * @param {*} [scopes] * @return {*} {Promise<AuthenticationResult>} * @memberof ElectronAuthenticator */ protected async getTokenInteractive(prompt_type: promptType, scopes?): Promise<AuthenticationResult> { let authResult; const requestScopes = scopes ? scopes : this.authCodeUrlParams.scopes; const authCodeUrlParams = { ...this.authCodeUrlParams, scopes: requestScopes, prompt: prompt_type.toString() }; const authCodeUrl = await this.clientApplication.getAuthCodeUrl(authCodeUrlParams); this.authCodeListener = new CustomFileProtocolListener('msal'); this.authCodeListener.start(); const authCode = await this.listenForAuthCode(authCodeUrl, prompt_type); authResult = await this.clientApplication .acquireTokenByCode({ ...this.authCodeRequest, scopes: requestScopes, code: authCode }) .catch((e: AuthError) => { throw e; }); return authResult; } /** * Listen for the auth code in API response * * @private * @param {string} navigateUrl * @param {promptType} prompt_type * @return {*} {Promise<string>} * @memberof ElectronAuthenticator */ private async listenForAuthCode(navigateUrl: string, prompt_type: promptType): Promise<string> { this.setAuthWindow(true); await this.authWindow.loadURL(navigateUrl); return new Promise((resolve, reject) => { this.authWindow.webContents.on('will-redirect', (event, responseUrl) => { try { const parsedUrl = new URL(responseUrl); const authCode = parsedUrl.searchParams.get('code'); resolve(authCode); } catch (err) { this.authWindow.destroy(); reject(err); } this.authWindow.destroy(); }); }); } /** * Attempt to Silently Sign In * * @protected * @memberof ElectronAuthenticator */ protected async attemptSilentLogin() { this.account = this.account || (await this.getAccount()); if (this.account) { const token = await this.getAccessToken(); if (token) { this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_IN); } else { this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_OUT); } } else { this.mainWindow.webContents.send('mgtAuthState', AuthState.LOGGED_OUT); } } /** * Get logged in Account details * * @private * @return {*} {Promise<AccountInfo>} * @memberof ElectronAuthenticator */ private async getAccount(): Promise<AccountInfo> { const cache = this.clientApplication.getTokenCache(); const currentAccounts = await cache.getAllAccounts(); if (currentAccounts === null) { return null; } if (currentAccounts.length > 1) { return currentAccounts[0]; } else if (currentAccounts.length === 1) { return currentAccounts[0]; } else { return null; } } }
the_stack
import { Class } from './../Class'; import { GameEvent, GamepadConnectEvent, GamepadDisconnectEvent, GamepadButtonEvent, GamepadAxisEvent } from '../Events'; import * as Events from '../Events'; /** * Excalibur leverages the HTML5 Gamepad API [where it is supported](http://caniuse.com/#feat=gamepad) * to provide controller support for your games. */ export class Gamepads extends Class { /** * Whether or not to poll for Gamepad input (default: `false`) */ public enabled = false; /** * Whether or not Gamepad API is supported */ public supported = !!(<any>navigator).getGamepads; /** * The minimum value an axis has to move before considering it a change */ public static MinAxisMoveThreshold = 0.05; private _gamePadTimeStamps = [0, 0, 0, 0]; private _oldPads: Gamepad[] = []; private _pads: Gamepad[] = []; private _initSuccess: boolean = false; private _navigator: NavigatorGamepads = <any>navigator; private _minimumConfiguration: GamepadConfiguration = null; constructor() { super(); } public init() { if (!this.supported) { return; } if (this._initSuccess) { return; } // In Chrome, this will return 4 undefined items until a button is pressed // In FF, this will not return any items until a button is pressed this._oldPads = this._clonePads(this._navigator.getGamepads()); if (this._oldPads.length && this._oldPads[0]) { this._initSuccess = true; } } /** * Sets the minimum gamepad configuration, for example {axis: 4, buttons: 4} means * this game requires at minimum 4 axis inputs and 4 buttons, this is not restrictive * all other controllers with more axis or buttons are valid as well. If no minimum * configuration is set all pads are valid. */ public setMinimumGamepadConfiguration(config: GamepadConfiguration): void { this._enableAndUpdate(); // if config is used, implicitly enable this._minimumConfiguration = config; } /** * When implicitly enabled, set the enabled flag and run an update so information is updated */ private _enableAndUpdate() { if (!this.enabled) { this.enabled = true; this.update(); } } /** * Checks a navigator gamepad against the minimum configuration if present. */ private _isGamepadValid(pad: NavigatorGamepad): boolean { if (!this._minimumConfiguration) { return true; } if (!pad) { return false; } const axesLength = pad.axes.filter((value) => { return typeof value !== undefined; }).length; const buttonLength = pad.buttons.filter((value) => { return typeof value !== undefined; }).length; return axesLength >= this._minimumConfiguration.axis && buttonLength >= this._minimumConfiguration.buttons && pad.connected; } public on(eventName: Events.connect, handler: (event: GamepadConnectEvent) => void): void; public on(eventName: Events.disconnect, handler: (event: GamepadDisconnectEvent) => void): void; public on(eventName: Events.button, handler: (event: GamepadButtonEvent) => void): void; public on(eventName: Events.axis, handler: (event: GamepadAxisEvent) => void): void; public on(eventName: string, handler: (event: GameEvent<any>) => void): void; public on(eventName: string, handler: (event: any) => void): void { this._enableAndUpdate(); // implicitly enable super.on(eventName, handler); } public off(eventName: string, handler?: (event: GameEvent<any>) => void) { this._enableAndUpdate(); // implicitly enable super.off(eventName, handler); } /** * Updates Gamepad state and publishes Gamepad events */ public update() { if (!this.enabled || !this.supported) { return; } this.init(); const gamepads = this._navigator.getGamepads(); for (let i = 0; i < gamepads.length; i++) { if (!gamepads[i]) { const gamepad = this.at(i); // If was connected, but now isn't emit the disconnect event if (gamepad.connected) { this.eventDispatcher.emit('disconnect', new GamepadDisconnectEvent(i, gamepad)); } // Reset connection status gamepad.connected = false; continue; } else { if (!this.at(i).connected && this._isGamepadValid(gamepads[i])) { this.eventDispatcher.emit('connect', new GamepadConnectEvent(i, this.at(i))); } // Set connection status this.at(i).connected = true; } // Only supported in Chrome if (gamepads[i].timestamp && gamepads[i].timestamp === this._gamePadTimeStamps[i]) { continue; } this._gamePadTimeStamps[i] = gamepads[i].timestamp; // Add reference to navigator gamepad this.at(i).navigatorGamepad = gamepads[i]; // Buttons let b: string, bi: number, a: string, ai: number, value: number; for (b in Buttons) { bi = <any>Buttons[b]; if (typeof bi === 'number') { if (gamepads[i].buttons[bi]) { value = gamepads[i].buttons[bi].value; if (value !== this._oldPads[i].getButton(bi)) { if (gamepads[i].buttons[bi].pressed) { this.at(i).updateButton(bi, value); this.at(i).eventDispatcher.emit('button', new GamepadButtonEvent(bi, value, this.at(i))); } else { this.at(i).updateButton(bi, 0); } } } } } // Axes for (a in Axes) { ai = <any>Axes[a]; if (typeof ai === 'number') { value = gamepads[i].axes[ai]; if (value !== this._oldPads[i].getAxes(ai)) { this.at(i).updateAxes(ai, value); this.at(i).eventDispatcher.emit('axis', new GamepadAxisEvent(ai, value, this.at(i))); } } } this._oldPads[i] = this._clonePad(gamepads[i]); } } /** * Safely retrieves a Gamepad at a specific index and creates one if it doesn't yet exist */ public at(index: number): Gamepad { this._enableAndUpdate(); // implicitly enable gamepads when at() is called if (index >= this._pads.length) { // Ensure there is a pad to retrieve for (let i = this._pads.length - 1, max = index; i < max; i++) { this._pads.push(new Gamepad()); this._oldPads.push(new Gamepad()); } } return this._pads[index]; } /** * Returns a list of all valid gamepads that meet the minimum configuration requirement. */ public getValidGamepads(): Gamepad[] { this._enableAndUpdate(); const result: Gamepad[] = []; for (let i = 0; i < this._pads.length; i++) { if (this._isGamepadValid(this.at(i).navigatorGamepad) && this.at(i).connected) { result.push(this.at(i)); } } return result; } /** * Gets the number of connected gamepads */ public count() { return this._pads.filter((p) => p.connected).length; } private _clonePads(pads: NavigatorGamepad[]): Gamepad[] { const arr = []; for (let i = 0, len = pads.length; i < len; i++) { arr.push(this._clonePad(pads[i])); } return arr; } /** * Fastest way to clone a known object is to do it yourself */ private _clonePad(pad: NavigatorGamepad): Gamepad { let i, len; const clonedPad = new Gamepad(); if (!pad) { return clonedPad; } for (i = 0, len = pad.buttons.length; i < len; i++) { if (pad.buttons[i]) { clonedPad.updateButton(i, pad.buttons[i].value); } } for (i = 0, len = pad.axes.length; i < len; i++) { clonedPad.updateAxes(i, pad.axes[i]); } return clonedPad; } } /** * Gamepad holds state information for a connected controller. See [[Gamepads]] * for more information on handling controller input. */ export class Gamepad extends Class { public connected = false; public navigatorGamepad: NavigatorGamepad; private _buttons: number[] = new Array(16); private _axes: number[] = new Array(4); constructor() { super(); for (let i = 0; i < this._buttons.length; i++) { this._buttons[i] = 0; } for (let i = 0; i < this._axes.length; i++) { this._axes[i] = 0; } } /** * Whether or not the given button is pressed * @param button The button to query * @param threshold The threshold over which the button is considered to be pressed */ public isButtonPressed(button: Buttons, threshold: number = 1) { return this._buttons[button] >= threshold; } /** * Gets the given button value between 0 and 1 */ public getButton(button: Buttons) { return this._buttons[button]; } /** * Gets the given axis value between -1 and 1. Values below * [[MinAxisMoveThreshold]] are considered 0. */ public getAxes(axes: Axes) { const value = this._axes[axes]; if (Math.abs(value) < Gamepads.MinAxisMoveThreshold) { return 0; } else { return value; } } public updateButton(buttonIndex: number, value: number) { this._buttons[buttonIndex] = value; } public updateAxes(axesIndex: number, value: number) { this._axes[axesIndex] = value; } } /** * Gamepad Buttons enumeration */ export enum Buttons { /** * Face 1 button (e.g. A) */ Face1 = 0, /** * Face 2 button (e.g. B) */ Face2 = 1, /** * Face 3 button (e.g. X) */ Face3 = 2, /** * Face 4 button (e.g. Y) */ Face4 = 3, /** * Left bumper button */ LeftBumper = 4, /** * Right bumper button */ RightBumper = 5, /** * Left trigger button */ LeftTrigger = 6, /** * Right trigger button */ RightTrigger = 7, /** * Select button */ Select = 8, /** * Start button */ Start = 9, /** * Left analog stick press (e.g. L3) */ LeftStick = 10, /** * Right analog stick press (e.g. R3) */ RightStick = 11, /** * D-pad up */ DpadUp = 12, /** * D-pad down */ DpadDown = 13, /** * D-pad left */ DpadLeft = 14, /** * D-pad right */ DpadRight = 15 } /** * Gamepad Axes enumeration */ export enum Axes { /** * Left analogue stick X direction */ LeftStickX = 0, /** * Left analogue stick Y direction */ LeftStickY = 1, /** * Right analogue stick X direction */ RightStickX = 2, /** * Right analogue stick Y direction */ RightStickY = 3 } /** * @internal */ export interface NavigatorGamepads { getGamepads(): NavigatorGamepad[]; } /** * @internal */ export interface NavigatorGamepad { axes: number[]; buttons: NavigatorGamepadButton[]; connected: boolean; id: string; index: number; mapping: string; timestamp: number; } /** * @internal */ export interface NavigatorGamepadButton { pressed: boolean; value: number; } /** * @internal */ export interface NavigatorGamepadEvent { gamepad: NavigatorGamepad; } /** * @internal */ export interface GamepadConfiguration { axis: number; buttons: number; }
the_stack
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NotifierAction } from '../models/notifier-action.model'; import { NotifierConfig } from '../models/notifier-config.model'; import { NotifierConfigToken } from '../notifier.tokens'; import { NotifierService } from '../services/notifier.service'; import { NotifierQueueService } from '../services/notifier-queue.service'; import { NotifierContainerComponent } from './notifier-container.component'; /** * Notifier Container Component - Unit Test */ describe('Notifier Container Component', () => { let componentFixture: ComponentFixture<NotifierContainerComponent>; let componentInstance: NotifierContainerComponent; let queueService: MockNotifierQueueService; it('should instantiate', () => { // Setup test module beforeEachWithConfig(new NotifierConfig()); expect(componentInstance).toBeDefined(); }); it('should render', () => { // Setup test module beforeEachWithConfig(new NotifierConfig()); componentFixture.detectChanges(); }); it('should ignore unknown actions', fakeAsync(() => { // Setup test module beforeEachWithConfig(new NotifierConfig()); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); queueService.push(<any>{ payload: 'STUFF', type: 'WHATEVS', }); componentFixture.detectChanges(); tick(); expect(queueService.continue).toHaveBeenCalled(); })); describe('(show)', () => { it('should show the first notification', fakeAsync(() => { // Setup test module beforeEachWithConfig(new NotifierConfig()); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); expect(listElements.length).toBe(1); const mockNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockNotificationComponent, 'show'); // Continue componentInstance.onNotificationReady(<any>mockNotificationComponent); // Trigger the ready event manually tick(); expect(mockNotificationComponent.show).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalled(); })); it('should switch out the old notification with the new one when stacking is disabled', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ behaviour: { stacking: false, }, }), ); componentFixture.detectChanges(); // Create the first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually tick(); // Create the second notification queueService.push({ payload: { message: 'Blubberfish.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'show'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually tick(); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.show).toHaveBeenCalled(); })); it('should hide and shift before showing the notification when stacking is enabled', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { stacking: 2, }, }), ); componentFixture.detectChanges(); // Create the first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually tick(); // Create the second notification queueService.push({ payload: { message: 'Blubberfish.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually tick(); // Create the third notification queueService.push({ payload: { message: 'This. Is. Angular!', type: 'INFO', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockThirdNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockThirdNotificationComponent, 'show'); // Continue componentInstance.onNotificationReady(<any>mockThirdNotificationComponent); // Trigger the ready event manually tick(); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.shift).toHaveBeenCalled(); expect(mockThirdNotificationComponent.show).toHaveBeenCalled(); })); it('should hide and shift before showing the notification, when stacking is enabled (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { overlap: false, }, behaviour: { stacking: 2, }, }); beforeEachWithConfig(testNotifierConfig); componentFixture.detectChanges(); // Create the first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually tick(); // Create the second notification queueService.push({ payload: { message: 'Blubberfish.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually tick(); // Create the third notification queueService.push({ payload: { message: 'This. Is. Angular!', type: 'INFO', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockThirdNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockThirdNotificationComponent, 'show'); // Continue componentInstance.onNotificationReady(<any>mockThirdNotificationComponent); // Trigger the ready event manually tick(); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.shift).toHaveBeenCalled(); expect(mockThirdNotificationComponent.show).toHaveBeenCalled(); })); it('should hide and shift before showing the notification, when tacking is enabled (with overlapping animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ behaviour: { stacking: 2, }, }); beforeEachWithConfig(testNotifierConfig); componentFixture.detectChanges(); // Create the first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually tick(); // Create the second notification queueService.push({ payload: { message: 'Blubberfish.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually tick(); // Create the third notification queueService.push({ payload: { message: 'This. Is. Angular!', type: 'INFO', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockThirdNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockThirdNotificationComponent, 'show'); // Continue componentInstance.onNotificationReady(<any>mockThirdNotificationComponent); // Trigger the ready event manually tick( testNotifierConfig.animations.hide.speed + testNotifierConfig.animations.shift.speed - <number>testNotifierConfig.animations.overlap, ); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.shift).toHaveBeenCalled(); expect(mockThirdNotificationComponent.show).toHaveBeenCalled(); })); }); describe('(hide)', () => { it('should hide one notification', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); const testNotificationId = 'FAKE_ID'; // Show notification queueService.push({ payload: { id: testNotificationId, message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockNotificationComponent); // Trigger the ready event manually tick(); // Hide notification queueService.push({ payload: testNotificationId, type: 'HIDE', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); expect(listElements.length).toBe(0); expect(mockNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalled(); })); it('should skip if the notification to hide does not exist', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { id: 'FAKE_ID', message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockNotificationComponent); // Trigger the ready event manually tick(); // Hide notification queueService.push({ payload: 'NOT_EXISTING_ID', type: 'HIDE', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); expect(listElements.length).toBe(1); expect(mockNotificationComponent.hide).not.toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalled(); })); it('should shift before hiding the notification if necessary', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show second notification const testNotificationId = 'FAKE_ID'; queueService.push({ payload: { id: testNotificationId, message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ payload: testNotificationId, type: 'HIDE', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(1); expect(mockFirstNotificationComponent.shift).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should shift before hiding the notification if necessary (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { overlap: false, }, }); beforeEachWithConfig(testNotifierConfig); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show second notification const testNotificationId = 'FAKE_ID'; queueService.push({ payload: { id: testNotificationId, message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ payload: testNotificationId, type: 'HIDE', }); componentFixture.detectChanges(); tick(testNotifierConfig.animations.hide.speed); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(1); expect(mockFirstNotificationComponent.shift).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should shift before hiding the notification if necessary (with overlapping animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig(); beforeEachWithConfig(testNotifierConfig); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'shift'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show second notification const testNotificationId = 'FAKE_ID'; queueService.push({ payload: { id: testNotificationId, message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ payload: testNotificationId, type: 'HIDE', }); componentFixture.detectChanges(); tick(testNotifierConfig.animations.hide.speed - <number>testNotifierConfig.animations.overlap); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(1); expect(mockFirstNotificationComponent.shift).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should hide the notification when the dismiss event gets dispatched', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show second notification const testNotificationId = 'FAKE_ID'; queueService.push({ payload: { id: testNotificationId, message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockNotificationComponent); // Trigger the ready event manually // Hide second notification componentInstance.onNotificationDismiss(testNotificationId); tick(); componentFixture.detectChanges(); const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 2; expect(listElements.length).toBe(0); expect(mockNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); }); describe('(hide oldest / newest)', () => { it('should hide the oldest notification', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { id: 'FAKE_ID', message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ type: 'HIDE_OLDEST', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(1); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).not.toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should skip hiding the oldest notification if there are no notifications', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Hide notification queueService.push({ type: 'HIDE_OLDEST', }); componentFixture.detectChanges(); tick(); expect(queueService.continue).toHaveBeenCalled(); })); it('should hide the newest notification', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show first notification queueService.push({ payload: { id: 'FAKE_ID', message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ type: 'HIDE_NEWEST', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(1); expect(mockFirstNotificationComponent.hide).not.toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should skip hiding the newest notification if there are no notifications', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Hide notification queueService.push({ type: 'HIDE_NEWEST', }); componentFixture.detectChanges(); tick(); expect(queueService.continue).toHaveBeenCalled(); })); }); describe('(hide all)', () => { it('should hide all notifications', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ type: 'HIDE_ALL', }); componentFixture.detectChanges(); tick(); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(0); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should hide all notifications (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig(); beforeEachWithConfig(testNotifierConfig); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Show first notification queueService.push({ payload: { message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockFirstNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockFirstNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockFirstNotificationComponent); // Trigger the ready event manually // Show first notification queueService.push({ payload: { message: 'Whut.', type: 'ERROR', }, type: 'SHOW', }); componentFixture.detectChanges(); const mockSecondNotificationComponent: MockNotifierNotificationComponent = new MockNotifierNotificationComponent(); jest.spyOn(mockSecondNotificationComponent, 'hide'); // Continue componentInstance.onNotificationReady(<any>mockSecondNotificationComponent); // Trigger the ready event manually // Hide second notification queueService.push({ type: 'HIDE_ALL', }); componentFixture.detectChanges(); const numberOfNotifications = 2; tick(testNotifierConfig.animations.hide.speed + numberOfNotifications * <number>testNotifierConfig.animations.hide.offset); componentFixture.detectChanges(); // Run a second change detection (to update the template) const listElements: Array<DebugElement> = componentFixture.debugElement.queryAll(By.css('.notifier__container-list-item')); const expectedCallTimes = 3; expect(listElements.length).toBe(0); expect(mockFirstNotificationComponent.hide).toHaveBeenCalled(); expect(mockSecondNotificationComponent.hide).toHaveBeenCalled(); expect(queueService.continue).toHaveBeenCalledTimes(expectedCallTimes); })); it('should skip hiding all notification if there are no notifications', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, }), ); componentFixture.detectChanges(); jest.spyOn(queueService, 'continue'); // Hide notification queueService.push({ type: 'HIDE_ALL', }); componentFixture.detectChanges(); tick(); expect(queueService.continue).toHaveBeenCalled(); })); }); /** * Helper for upfront configuration */ function beforeEachWithConfig(testNotifierConfig: NotifierConfig): void { TestBed.configureTestingModule({ declarations: [NotifierContainerComponent], providers: [ { provide: NotifierService, useValue: { getConfig: () => testNotifierConfig, }, }, { // No idea why this is *actually* necessary -- it shouldn't be ... provide: NotifierConfigToken, useValue: {}, }, { provide: NotifierQueueService, useClass: MockNotifierQueueService, }, ], schemas: [ NO_ERRORS_SCHEMA, // Ignore sub-components (inknown tags in the HTML template) ], }); componentFixture = TestBed.createComponent(NotifierContainerComponent); componentInstance = componentFixture.componentInstance; queueService = TestBed.inject(NotifierQueueService); } }); /** * Mock Notifier Queue Service */ class MockNotifierQueueService extends NotifierQueueService { /** * Push a new action to the queue, and try to run it * * @param {NotifierAction} action Action object * * @override */ public push(action: NotifierAction): void { this.actionStream.next(action); } /** * Continue with the next action (called when the current action is finished) * * @override */ public continue(): void { // Do nothing } } /** * Random notification height */ const randomHeight = 42; /** * Mock Notifier Notification Component */ class MockNotifierNotificationComponent { // Don't extend to prevent DI null issues /** * Get notification element height (in px) * * @returns {number} Notification element height (in px) * * @override */ public getHeight(): number { return randomHeight; // Random ... } /** * Show a notification * * @override */ public show(): Promise<void> { return new Promise<void>((resolve) => { resolve(); // Do nothing }); } /** * Shift a notification * * @override */ public shift(): Promise<void> { return new Promise<void>((resolve) => { resolve(); // Do nothing }); } /** * Hide a notification * * @override */ public hide(): Promise<void> { return new Promise<void>((resolve) => { resolve(); // Do nothing }); } }
the_stack
import * as coreClient from "@azure/core-client"; /** I am root, and I ref a model with no meta */ export interface RootWithRefAndNoMeta { /** XML will use RefToModel */ refToModel?: ComplexTypeNoMeta; /** Something else (just to avoid flattening) */ something?: string; } /** I am a complex type with no XML node */ export interface ComplexTypeNoMeta { /** The id of the res */ id?: string; } /** I am root, and I ref a model WITH meta */ export interface RootWithRefAndMeta { /** XML will use XMLComplexTypeWithMeta */ refToModel?: ComplexTypeWithMeta; /** Something else (just to avoid flattening) */ something?: string; } /** I am a complex type with XML node */ export interface ComplexTypeWithMeta { /** The id of the res */ id?: string; } /** Data about a slideshow */ export interface Slideshow { title?: string; date?: string; author?: string; slides?: Slide[]; } /** A slide in a slideshow */ export interface Slide { type?: string; title?: string; items?: string[]; } export interface ErrorModel { status?: number; message?: string; } /** A barrel of apples. */ export interface AppleBarrel { goodApples?: string[]; badApples?: string[]; } /** A banana. */ export interface Banana { name?: string; flavor?: string; /** The time at which you should reconsider eating this banana */ expiration?: Date; } /** An enumeration of containers */ export interface ListContainersResponse { serviceEndpoint: string; prefix: string; marker?: string; maxResults: number; containers?: Container[]; nextMarker: string; } /** An Azure Storage container */ export interface Container { name: string; /** Properties of a container */ properties: ContainerProperties; /** Dictionary of <string> */ metadata?: { [propertyName: string]: string }; } /** Properties of a container */ export interface ContainerProperties { lastModified: Date; etag: string; leaseStatus?: LeaseStatusType; leaseState?: LeaseStateType; leaseDuration?: LeaseDurationType; publicAccess?: PublicAccessType; } /** Storage Service Properties. */ export interface StorageServiceProperties { /** Azure Analytics Logging settings */ logging?: Logging; /** A summary of request statistics grouped by API in hourly aggregates for blobs */ hourMetrics?: Metrics; /** a summary of request statistics grouped by API in minute aggregates for blobs */ minuteMetrics?: Metrics; /** The set of CORS rules. */ cors?: CorsRule[]; /** The default version to use for requests to the Blob service if an incoming request's version is not specified. Possible values include version 2008-10-27 and all more recent versions */ defaultServiceVersion?: string; /** The Delete Retention Policy for the service */ deleteRetentionPolicy?: RetentionPolicy; } /** Azure Analytics Logging settings. */ export interface Logging { /** The version of Storage Analytics to configure. */ version: string; /** Indicates whether all delete requests should be logged. */ delete: boolean; /** Indicates whether all read requests should be logged. */ read: boolean; /** Indicates whether all write requests should be logged. */ write: boolean; /** the retention policy */ retentionPolicy: RetentionPolicy; } /** the retention policy */ export interface RetentionPolicy { /** Indicates whether a retention policy is enabled for the storage service */ enabled: boolean; /** Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted */ days?: number; } export interface Metrics { /** The version of Storage Analytics to configure. */ version?: string; /** Indicates whether metrics are enabled for the Blob service. */ enabled: boolean; /** Indicates whether metrics should generate summary statistics for called API operations. */ includeAPIs?: boolean; /** the retention policy */ retentionPolicy?: RetentionPolicy; } /** CORS is an HTTP feature that enables a web application running under one domain to access resources in another domain. Web browsers implement a security restriction known as same-origin policy that prevents a web page from calling APIs in a different domain; CORS provides a secure way to allow one domain (the origin domain) to call APIs in another domain */ export interface CorsRule { /** The origin domains that are permitted to make a request against the storage service via CORS. The origin domain is the domain from which the request originates. Note that the origin must be an exact case-sensitive match with the origin that the user age sends to the service. You can also use the wildcard character '*' to allow all origin domains to make requests via CORS. */ allowedOrigins: string; /** The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated) */ allowedMethods: string; /** the request headers that the origin domain may specify on the CORS request. */ allowedHeaders: string; /** The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer */ exposedHeaders: string; /** The maximum amount time that a browser should cache the preflight OPTIONS request. */ maxAgeInSeconds: number; } /** signed identifier */ export interface SignedIdentifier { /** a unique id */ id: string; /** The access policy */ accessPolicy: AccessPolicy; } /** An Access policy */ export interface AccessPolicy { /** the date-time the policy is active */ start: Date; /** the date-time the policy expires */ expiry: Date; /** the permissions for the acl policy */ permission: string; } /** An enumeration of blobs */ export interface ListBlobsResponse { serviceEndpoint?: string; containerName: string; prefix: string; marker: string; maxResults: number; delimiter: string; blobs: Blobs; nextMarker: string; } export interface Blobs { blobPrefix?: BlobPrefix[]; blob?: Blob[]; } export interface BlobPrefix { name: string; } /** An Azure Storage blob */ export interface Blob { name: string; deleted: boolean; snapshot: string; /** Properties of a blob */ properties: BlobProperties; /** Dictionary of <string> */ metadata?: { [propertyName: string]: string }; } /** Properties of a blob */ export interface BlobProperties { lastModified: Date; etag: string; /** Size in bytes */ contentLength?: number; contentType?: string; contentEncoding?: string; contentLanguage?: string; contentMD5?: string; contentDisposition?: string; cacheControl?: string; blobSequenceNumber?: number; blobType?: BlobType; leaseStatus?: LeaseStatusType; leaseState?: LeaseStateType; leaseDuration?: LeaseDurationType; copyId?: string; copyStatus?: CopyStatusType; copySource?: string; copyProgress?: string; copyCompletionTime?: Date; copyStatusDescription?: string; serverEncrypted?: boolean; incrementalCopy?: boolean; destinationSnapshot?: string; deletedTime?: Date; remainingRetentionDays?: number; accessTier?: AccessTier; accessTierInferred?: boolean; archiveStatus?: ArchiveStatus; } export interface JsonInput { id?: number; } export interface JsonOutput { id?: number; } /** Contans property */ export interface ObjectWithXMsTextProperty { /** Returned value should be 'english' */ language?: string; /** Returned value should be 'I am text' */ content?: string; } export interface ModelWithByteProperty { bytes?: Uint8Array; } export interface ModelWithUrlProperty { url?: string; } /** Defines headers for Xml_getHeaders operation. */ export interface XmlGetHeadersHeaders { /** A custom response header. */ customHeader?: string; } /** Known values of {@link PublicAccessType} that the service accepts. */ export enum KnownPublicAccessType { Container = "container", Blob = "blob" } /** * Defines values for PublicAccessType. \ * {@link KnownPublicAccessType} can be used interchangeably with PublicAccessType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **container** \ * **blob** */ export type PublicAccessType = string; /** Known values of {@link AccessTier} that the service accepts. */ export enum KnownAccessTier { P4 = "P4", P6 = "P6", P10 = "P10", P20 = "P20", P30 = "P30", P40 = "P40", P50 = "P50", Hot = "Hot", Cool = "Cool", Archive = "Archive" } /** * Defines values for AccessTier. \ * {@link KnownAccessTier} can be used interchangeably with AccessTier, * this enum contains the known values that the service supports. * ### Known values supported by the service * **P4** \ * **P6** \ * **P10** \ * **P20** \ * **P30** \ * **P40** \ * **P50** \ * **Hot** \ * **Cool** \ * **Archive** */ export type AccessTier = string; /** Known values of {@link ArchiveStatus} that the service accepts. */ export enum KnownArchiveStatus { RehydratePendingToHot = "rehydrate-pending-to-hot", RehydratePendingToCool = "rehydrate-pending-to-cool" } /** * Defines values for ArchiveStatus. \ * {@link KnownArchiveStatus} can be used interchangeably with ArchiveStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **rehydrate-pending-to-hot** \ * **rehydrate-pending-to-cool** */ export type ArchiveStatus = string; /** Defines values for LeaseStatusType. */ export type LeaseStatusType = "locked" | "unlocked"; /** Defines values for LeaseStateType. */ export type LeaseStateType = | "available" | "leased" | "expired" | "breaking" | "broken"; /** Defines values for LeaseDurationType. */ export type LeaseDurationType = "infinite" | "fixed"; /** Defines values for BlobType. */ export type BlobType = "BlockBlob" | "PageBlob" | "AppendBlob"; /** Defines values for CopyStatusType. */ export type CopyStatusType = "pending" | "success" | "aborted" | "failed"; /** Optional parameters. */ export interface XmlGetComplexTypeRefNoMetaOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexTypeRefNoMeta operation. */ export type XmlGetComplexTypeRefNoMetaResponse = RootWithRefAndNoMeta; /** Optional parameters. */ export interface XmlPutComplexTypeRefNoMetaOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetComplexTypeRefWithMetaOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getComplexTypeRefWithMeta operation. */ export type XmlGetComplexTypeRefWithMetaResponse = RootWithRefAndMeta; /** Optional parameters. */ export interface XmlPutComplexTypeRefWithMetaOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetSimpleOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getSimple operation. */ export type XmlGetSimpleResponse = Slideshow; /** Optional parameters. */ export interface XmlPutSimpleOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetWrappedListsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getWrappedLists operation. */ export type XmlGetWrappedListsResponse = AppleBarrel; /** Optional parameters. */ export interface XmlPutWrappedListsOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetHeadersOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getHeaders operation. */ export type XmlGetHeadersResponse = XmlGetHeadersHeaders; /** Optional parameters. */ export interface XmlGetEmptyListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyList operation. */ export type XmlGetEmptyListResponse = Slideshow; /** Optional parameters. */ export interface XmlPutEmptyListOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetEmptyWrappedListsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyWrappedLists operation. */ export type XmlGetEmptyWrappedListsResponse = AppleBarrel; /** Optional parameters. */ export interface XmlPutEmptyWrappedListsOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetRootListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getRootList operation. */ export type XmlGetRootListResponse = Banana[]; /** Optional parameters. */ export interface XmlPutRootListOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetRootListSingleItemOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getRootListSingleItem operation. */ export type XmlGetRootListSingleItemResponse = Banana[]; /** Optional parameters. */ export interface XmlPutRootListSingleItemOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetEmptyRootListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyRootList operation. */ export type XmlGetEmptyRootListResponse = Banana[]; /** Optional parameters. */ export interface XmlPutEmptyRootListOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetEmptyChildElementOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyChildElement operation. */ export type XmlGetEmptyChildElementResponse = Banana; /** Optional parameters. */ export interface XmlPutEmptyChildElementOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlListContainersOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listContainers operation. */ export type XmlListContainersResponse = ListContainersResponse; /** Optional parameters. */ export interface XmlGetServicePropertiesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getServiceProperties operation. */ export type XmlGetServicePropertiesResponse = StorageServiceProperties; /** Optional parameters. */ export interface XmlPutServicePropertiesOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetAclsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getAcls operation. */ export type XmlGetAclsResponse = SignedIdentifier[]; /** Optional parameters. */ export interface XmlPutAclsOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlListBlobsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listBlobs operation. */ export type XmlListBlobsResponse = ListBlobsResponse; /** Optional parameters. */ export interface XmlJsonInputOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlJsonOutputOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the jsonOutput operation. */ export type XmlJsonOutputResponse = JsonOutput; /** Optional parameters. */ export interface XmlGetXMsTextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getXMsText operation. */ export type XmlGetXMsTextResponse = ObjectWithXMsTextProperty; /** Optional parameters. */ export interface XmlGetBytesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getBytes operation. */ export type XmlGetBytesResponse = ModelWithByteProperty; /** Optional parameters. */ export interface XmlPutBinaryOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlGetUriOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getUri operation. */ export type XmlGetUriResponse = ModelWithUrlProperty; /** Optional parameters. */ export interface XmlPutUriOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface XmlServiceClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import * as PromiseExtensions from '../Promise.extensions'; import * as assert from 'assert'; import { find, each, times, values, keys, some, uniqueId } from 'lodash'; import * as sinon from 'sinon'; import { KeyComponentType, DbSchema, DbProvider, openListOfProviders, QuerySortOrder, FullTextTermResolution } from '../NoSqlProvider'; import { defer, IDeferred } from '../defer'; // import { CordovaNativeSqliteProvider } from '../CordovaNativeSqliteProvider'; import { InMemoryProvider } from '../InMemoryProvider'; import { IndexedDbProvider } from '../IndexedDbProvider'; import { WebSqlProvider } from '../WebSqlProvider'; import { serializeValueToOrderableString, isSafari } from '../NoSqlProviderUtils'; import { SqlTransaction } from '../SqlProviderBase'; import { getWindow } from '../get-window'; import Sinon = require('sinon'); let cleanupFile = false; type TestObj = { id?: string, val: string }; function openProvider(providerName: string, schema: DbSchema, wipeFirst: boolean) { let provider: DbProvider; if (providerName === 'sqlite3memory') { const NSPNodeSqlite3DbProvider = require('../NodeSqlite3DbProvider'); provider = new NSPNodeSqlite3DbProvider.default(); } else if (providerName === 'sqlite3memorynofts3') { const NSPNodeSqlite3DbProvider = require('../NodeSqlite3DbProvider'); provider = new NSPNodeSqlite3DbProvider.default(false); } else if (providerName === 'sqlite3disk') { cleanupFile = true; const NSPNodeSqlite3DbProvider = require('../NodeSqlite3DbProvider'); provider = new NSPNodeSqlite3DbProvider.default(); } else if (providerName === 'sqlite3disknofts3') { cleanupFile = true; const NSPNodeSqlite3DbProvider = require('../NodeSqlite3DbProvider'); provider = new NSPNodeSqlite3DbProvider.default(false); } else if (providerName === 'memory') { provider = new InMemoryProvider(); } else if (providerName === 'indexeddb') { provider = new IndexedDbProvider(); } else if (providerName === 'indexeddbfakekeys') { provider = new IndexedDbProvider(undefined, false); } else if (providerName === 'websql') { provider = new WebSqlProvider(); } else if (providerName === 'websqlnofts3') { provider = new WebSqlProvider(false); // } else if (providerName === 'reactnative') { // var reactNativeSqliteProvider = require('react-native-sqlite-storage'); // provider = new CordovaNativeSqliteProvider(reactNativeSqliteProvider); } else { throw new Error('Provider not found for name: ' + providerName); } const dbName = providerName.indexOf('sqlite3memory') !== -1 ? ':memory:' : 'test'; return openListOfProviders([provider], dbName, schema, wipeFirst, false); } function sleep(timeMs: number): Promise<void> { let deferred = defer<void>(); setTimeout(() => { deferred.resolve(void 0); }, timeMs); return deferred.promise; } describe('defer', () => { it('is resolved', async () => { const d: IDeferred<number> = defer(); function succeeded(n: number) { d.resolve(n); return d.promise; } const val = await succeeded(10); assert.equal(val, 10); }); it('is rejected', async () => { const d: IDeferred<number> = defer(); function failed(err: Error) { d.reject(err); return d.promise; } try { await failed(new Error('async op failed')); } catch (err) { assert.equal(err.message, 'async op failed'); } }); }); describe('PromiseExtensions', () => { it('Promise.always, always throws an exception', done => { const promise = new Promise((_, reject) => { reject('foo'); }); promise.always(() => undefined).then(() => { throw new Error('foo'); }, () => done()); }); describe('registerPromiseGlobalHandlers', () => { let config: PromiseExtensions.PromiseConfig; let consoleErrorSpy: Sinon.SinonSpy; beforeEach(() => { config = { catchExceptions: false, exceptionHandler: sinon.stub().returns(undefined), exceptionsToConsole: true, unhandledErrorHandler: sinon.stub().returns(undefined) }; consoleErrorSpy = sinon.spy(console, 'error'); }); afterEach(() => { PromiseExtensions.unRegisterPromiseGlobalHandlers(); consoleErrorSpy.restore(); }); it('logs handled errors to console if logging is enabled', () => { PromiseExtensions.registerPromiseGlobalHandlers(config); getWindow().dispatchEvent(new Event('rejectionhandled')); assert(consoleErrorSpy.calledOnce); }); it('does not log handled errors to console if logging is disabled', () => { PromiseExtensions.registerPromiseGlobalHandlers({ ...config, exceptionsToConsole: false }); getWindow().dispatchEvent(new Event('rejectionhandled')); assert(consoleErrorSpy.notCalled); }); it('logs unhandled errors to console if logging is enabled', () => { PromiseExtensions.registerPromiseGlobalHandlers(config); getWindow().dispatchEvent(new Event('unhandledrejection')); assert(consoleErrorSpy.calledOnce); }); it('does not log unhandled errors to console if logging is disabled', () => { PromiseExtensions.registerPromiseGlobalHandlers({ ...config, exceptionsToConsole: false }); getWindow().dispatchEvent(new Event('unhandledrejection')); assert(consoleErrorSpy.notCalled); }); it('invokes unhandled error handler on unhandled errors', () => { PromiseExtensions.registerPromiseGlobalHandlers(config); getWindow().dispatchEvent(new Event('unhandledrejection')); assert((config.unhandledErrorHandler as sinon.SinonStub).calledOnce); }); it('invokes exception error handler on handled errors', () => { PromiseExtensions.registerPromiseGlobalHandlers(config); getWindow().dispatchEvent(new Event('rejectionhandled')); assert((config.exceptionHandler as sinon.SinonStub).calledOnce); }); it('catches all exceptions and invokes unhandled error handler', async () => { PromiseExtensions.registerPromiseGlobalHandlers({ ...config, catchExceptions: true }); const event = new Event('unhandledrejection'); const eventSpy = sinon.spy(event, 'preventDefault'); getWindow().dispatchEvent(event); assert((config.unhandledErrorHandler as sinon.SinonStub).calledOnce); assert(eventSpy.calledOnce); }); }); }); describe('NoSqlProvider', function () { after('Cleaning up sqllite files', done => { if (cleanupFile) { var fs = require('fs'); fs.unlink('./test', (err: any) => { if (err) { throw err; } console.log('test was deleted'); done(); }); } else { done(); } }); let provsToTest: string[]; if (typeof window === 'undefined') { // Non-browser environment... provsToTest = ['memory', 'sqlite3memory', 'sqlite3memorynofts3', 'sqlite3disk', 'sqlite3disknofts3']; } else { provsToTest = ['memory']; if (!isSafari()) { // Safari has broken indexeddb support, so let's not test it there. Everywhere else should have it. // In IE, indexeddb will auto-run in fake keys mode, so if all is working, this is 2x the same test (but let's make sure!) provsToTest.push('indexeddb', 'indexeddbfakekeys'); } if (window.openDatabase !== undefined) { // WebSQL theoretically supported! provsToTest.push('websql', 'websqlnofts3'); } } it('Number/value/type sorting', () => { const pairsToTest = [ [0, 1], [-1, 1], [100, 100.1], [-123456.789, -123456.78], [-123456.789, 0], [-123456.789, 123456.789], [0.000012345, 8], [0.000012345, 0.00002], [-0.000012345, 0.000000001], [1, Date.now()], [new Date(0), new Date(2)], [new Date(1), new Date(2)], [new Date(-1), new Date(1)], [new Date(-2), new Date(-1)], [new Date(-2), new Date(0)], [1, 'hi'], [-1, 'hi'], [Date.now(), 'hi'], ['hi', 'hi2'], ['a', 'b'] ]; pairsToTest.forEach(pair => { assert(serializeValueToOrderableString(pair[0]) < serializeValueToOrderableString(pair[1]), 'failed for pair: ' + pair); }); try { serializeValueToOrderableString([4, 5] as any as KeyComponentType); assert(false, 'Should reject this key'); } catch (e) { // Should throw -- expecting this result. } }); provsToTest.forEach(provName => { describe('Provider: ' + provName, () => { describe('Delete database', () => { if (provName.indexOf('memory') !== -1) { xit('Skip delete test for in memory DB', () => { //noop }); } else if (provName.indexOf('indexeddb') === 0) { it('Deletes the database', () => { const schema = { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }; return openProvider(provName, schema, true) .then(prov => { // insert some stuff return prov.put('test', { id: 'a', val: 'b' }) //then delete .then(() => prov.deleteDatabase()); }) .then(() => openProvider(provName, schema, false)) .then(prov => { return prov.get('test', 'a').then(retVal => { const ret = retVal as TestObj; // not found assert(!ret); return prov.close(); }); }); }); } else { it('Rejects with an error', () => { const schema = { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }; return openProvider(provName, schema, true). then(prov => { // insert some stuff return prov.put('test', { id: 'a', val: 'b' }) .then(() => prov.deleteDatabase()); }) .then(() => { //this should not happen assert(false, 'Should fail'); }).catch(() => { // as expected, didn't delete anything return openProvider(provName, schema, false) .then(prov => prov.get('test', 'a').then(retVal => { const ret = retVal as TestObj; assert.equal(ret.val, 'b'); return prov.close(); })); }); }); } }); describe('Data Manipulation', () => { // Setter should set the testable parameter on the first param to the value in the second param, and third param to the // second index column for compound indexes. var tester = (prov: DbProvider, indexName: string | undefined, compound: boolean, setter: (obj: any, indexval1: string, indexval2: string) => void) => { var putters = [1, 2, 3, 4, 5].map(v => { var obj: TestObj = { val: 'val' + v }; if (indexName) { obj.id = 'id' + v; } setter(obj, 'indexa' + v, 'indexb' + v); return prov.put('test', obj); }); return Promise.all(putters).then(rets => { let formIndex = (i: number, i2: number = i): string | string[] => { if (compound) { return ['indexa' + i, 'indexb' + i2]; } else { return 'indexa' + i; } }; let t1 = prov.getAll('test', indexName).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 5, 'getAll'); [1, 2, 3, 4, 5].forEach(v => { assert(find(ret, r => r.val === 'val' + v), 'cant find ' + v); }); }); let t1count = prov.countAll('test', indexName).then(ret => { assert.equal(ret, 5, 'countAll'); }); let t1b = prov.getAll('test', indexName, false, 3).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 3, 'getAll lim3'); [1, 2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v), 'cant find ' + v); }); }); let t1c = prov.getAll('test', indexName, false, 3, 1).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 3, 'getAll lim3 off1'); [2, 3, 4].forEach(v => { assert(find(ret, r => r.val === 'val' + v), 'cant find ' + v); }); }); let t2 = prov.getOnly('test', indexName, formIndex(3)).then(ret => { assert.equal(ret.length, 1, 'getOnly'); assert.equal((ret[0] as TestObj).val, 'val3'); }); let t2count = prov.countOnly('test', indexName, formIndex(3)).then(ret => { assert.equal(ret, 1, 'countOnly'); }); let t3 = prov.getRange('test', indexName, formIndex(2), formIndex(4)).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 3, 'getRange++'); [2, 3, 4].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3count = prov.countRange('test', indexName, formIndex(2), formIndex(4)).then(ret => { assert.equal(ret, 3, 'countRange++'); }); let t3b = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, false, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange++ lim1'); [2].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3b2 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, false, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange++ lim1'); [2].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3b3 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, QuerySortOrder.Forward, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange++ lim1'); [2].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3b4 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, QuerySortOrder.Reverse, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange++ lim1 rev'); [4].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3c = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, false, 1, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange++ lim1 off1'); [3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3d = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, false, 2, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange++ lim2 off1'); [3, 4].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3d2 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, QuerySortOrder.Forward, 2, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange++ lim2 off1'); [3, 4].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3d3 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, true, 2, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange++ lim2 off1 rev'); assert.equal((ret[0] as TestObj).val, 'val3'); [2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t3d4 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, false, QuerySortOrder.Reverse, 2, 1) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange++ lim2 off1 rev'); assert.equal((ret[0] as TestObj).val, 'val3'); [2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t4 = prov.getRange('test', indexName, formIndex(2), formIndex(4), true, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange-+'); [3, 4].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t4count = prov.countRange('test', indexName, formIndex(2), formIndex(4), true, false).then(ret => { assert.equal(ret, 2, 'countRange-+'); }); let t5 = prov.getRange('test', indexName, formIndex(2), formIndex(4), false, true).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange+-'); [2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t5count = prov.countRange('test', indexName, formIndex(2), formIndex(4), false, true).then(ret => { assert.equal(ret, 2, 'countRange+-'); }); let t6 = prov.getRange('test', indexName, formIndex(2), formIndex(4), true, true).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange--'); [3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let t6count = prov.countRange('test', indexName, formIndex(2), formIndex(4), true, true).then(ret => { assert.equal(ret, 1, 'countRange--'); }); return Promise.all([t1, t1count, t1b, t1c, t2, t2count, t3, t3count, t3b, t3b2, t3b3, t3b4, t3c, t3d, t3d2, t3d3, t3d4, t4, t4count, t5, t5count, t6, t6count]).then(() => { if (compound) { let tt1 = prov.getRange('test', indexName, formIndex(2, 2), formIndex(4, 3)) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange2++'); [2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let tt1count = prov.countRange('test', indexName, formIndex(2, 2), formIndex(4, 3)) .then(ret => { assert.equal(ret, 2, 'countRange2++'); }); let tt2 = prov.getRange('test', indexName, formIndex(2, 2), formIndex(4, 3), false, true) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2, 'getRange2+-'); [2, 3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let tt2count = prov.countRange('test', indexName, formIndex(2, 2), formIndex(4, 3), false, true) .then(ret => { assert.equal(ret, 2, 'countRange2+-'); }); let tt3 = prov.getRange('test', indexName, formIndex(2, 2), formIndex(4, 3), true, false) .then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1, 'getRange2-+'); [3].forEach(v => { assert(find(ret, r => r.val === 'val' + v)); }); }); let tt3count = prov.countRange('test', indexName, formIndex(2, 2), formIndex(4, 3), true, false) .then(ret => { assert.equal(ret, 1, 'countRange2-+'); }); return Promise.all([tt1, tt1count, tt2, tt2count, tt3, tt3count]).then(() => { return prov.close(); }); } else { return prov.close(); } }); }); }; it('Simple primary key put/get/getAll', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'a', val: 'b' }).then(() => { return prov.get('test', 'a').then(retVal => { const ret = retVal as TestObj; assert.equal(ret.val, 'b'); return prov.getAll('test', undefined).then(ret2Val => { const ret2 = ret2Val as TestObj[]; assert.equal(ret2.length, 1); assert.equal(ret2[0].val, 'b'); return prov.close(); }); }); }); }); }); it('Empty gets/puts', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', []).then(() => { return prov.getAll('test', undefined).then(rets => { assert(!!rets); assert.equal(rets.length, 0); return prov.getMultiple('test', []).then(rets => { assert(!!rets); assert.equal(rets.length, 0); return prov.close(); }); }); }); }); }); it('getMultiple with blank', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', [1, 3].map(i => { return { id: 'a' + i }; })).then(() => { return prov.getMultiple('test', ['a1', 'a2', 'a3']).then(rets => { assert(!!rets); assert.equal(rets.length, 2); return prov.close(); }); }); }); }); it('Removing items', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', [1, 2, 3, 4, 5].map(i => { return { id: 'a' + i }; })).then(() => { return prov.getAll('test', undefined).then(rets => { assert(!!rets); assert.equal(rets.length, 5); return prov.remove('test', 'a1').then(() => { return prov.getAll('test', undefined).then(rets => { assert(!!rets); assert.equal(rets.length, 4); return prov.remove('test', ['a3', 'a4', 'a2']).then(() => { return prov.getAll('test', undefined).then(retVals => { const rets = retVals as TestObj[]; assert(!!rets); assert.equal(rets.length, 1); assert.equal(rets[0].id, 'a5'); return prov.close(); }); }); }); }); }); }); }); }); it('Invalid Key Type', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: { x: 'a' }, val: 'b' }).then(() => { assert(false, 'Shouldn\'t get here'); }, (err) => { // Woot, failed like it's supposed to return prov.close(); }); }); }); it('Primary Key Basic KeyPath', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return tester(prov, undefined, false, (obj, v) => { obj.id = v; }); }); }); for (let i = 0; i <= 1; i++) { it('Simple index put/get, getAll, getOnly, and getRange' + (i === 0 ? '' : ' (includeData)'), () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'index', keyPath: 'a', includeDataInIndex: i === 1 } ] } ] }, true).then(prov => { return tester(prov, 'index', false, (obj, v) => { obj.a = v; }); }); }); } it('Multipart primary key basic test', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'a.b' } ] }, true).then(prov => { return tester(prov, undefined, false, (obj, v) => { obj.a = { b: v }; }); }); }); it('Multipart index basic test', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'index', keyPath: 'a.b' } ] } ] }, true).then(prov => { return tester(prov, 'index', false, (obj, v) => { obj.a = { b: v }; }); }); }); it('Compound primary key basic test', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: ['a', 'b'] } ] }, true).then(prov => { return tester(prov, undefined, true, (obj, v1, v2) => { obj.a = v1; obj.b = v2; }); }); }); it('Compound index basic test', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'index', keyPath: ['a', 'b'] } ] } ] }, true).then(prov => { return tester(prov, 'index', true, (obj, v1, v2) => { obj.a = v1; obj.b = v2; }); }); }); for (let i = 0; i <= 1; i++) { it('MultiEntry multipart indexed tests' + (i === 0 ? '' : ' (includeData)'), () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'key', multiEntry: true, keyPath: 'k.k', includeDataInIndex: i === 1 } ] } ] }, true).then(prov => { return prov.put('test', { id: 'a', val: 'b', k: { k: ['w', 'x', 'y', 'z'] } }) // Insert data without multi-entry key defined .then(() => prov.put('test', { id: 'c', val: 'd', k: [] })) .then(() => prov.put('test', { id: 'e', val: 'f' })) .then(() => { var g1 = prov.get('test', 'a').then(retVal => { const ret = retVal as TestObj; assert.equal(ret.val, 'b'); }); var g2 = prov.getAll('test', 'key').then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 4); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g2b = prov.getAll('test', 'key', false, 2).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g2c = prov.getAll('test', 'key', false, 2, 1).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g3 = prov.getOnly('test', 'key', 'x').then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1); assert.equal(ret[0].val, 'b'); }); var g4 = prov.getRange('test', 'key', 'x', 'y', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); return Promise.all([g1, g2, g2b, g2c, g3, g4]).then(() => { return prov.close(); }); }); }); }); } it('MultiEntry multipart indexed - update index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'key', multiEntry: true, keyPath: 'k.k' } ] } ] }, true).then(prov => { return prov.put('test', { id: 'a', val: 'b', k: { k: ['w', 'x', 'y', 'z'] } }) .then(() => { return prov.getRange('test', 'key', 'x', 'y', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); }) .then(() => { return prov.put('test', { id: 'a', val: 'b', k: { k: ['z'] } }); }) .then(() => { return prov.getRange('test', 'key', 'x', 'y', false, false).then(ret => { assert.equal(ret.length, 0); }); }) .then(() => { return prov.getRange('test', 'key', 'x', 'z', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1); assert.equal(ret[0].val, 'b'); }); }) .then(() => { return prov.remove('test', 'a'); }) .then(() => { return prov.getRange('test', 'key', 'x', 'z', false, false).then(ret => { assert.equal(ret.length, 0); }); }) .then(() => { return prov.close(); }); }); }); // Ensure that we properly batch multi-key sql inserts if (provName.indexOf('sql') !== -1) { it('MultiEntry multipart index - large index put', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'key', multiEntry: true, keyPath: 'k.k', } ] } ] }, true).then(prov => { const keys: string[] = []; times(1000, () => { keys.push(uniqueId('multipartKey')); }); return prov.put('test', { id: 'a', val: 'b', k: { k: keys } }); }); }); } it('MultiEntry multipart indexed tests - Compound Key', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: ['id', 'id2'], indexes: [ { name: 'key', multiEntry: true, keyPath: 'k.k' } ] } ] }, true).then(prov => { return prov.put('test', { id: 'a', id2: '1', val: 'b', k: { k: ['w', 'x', 'y', 'z'] } }) // Insert data without multi-entry key defined .then(() => prov.put('test', { id: 'c', id2: '2', val: 'd', k: [] })) .then(() => prov.put('test', { id: 'e', id2: '3', val: 'f' })) .then(() => { var g1 = prov.get('test', ['a', '1']).then(retVal => { const ret = retVal as TestObj; assert.equal(ret.val, 'b'); }); var g2 = prov.getAll('test', 'key').then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 4); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g2b = prov.getAll('test', 'key', false, 2).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g2c = prov.getAll('test', 'key', false, 2, 1).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); var g3 = prov.getOnly('test', 'key', 'x').then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1); assert.equal(ret[0].val, 'b'); }); var g4 = prov.getRange('test', 'key', 'x', 'y', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); return Promise.all([g1, g2, g2b, g2c, g3, g4]).then(() => { return prov.close(); }); }); }); }); it('MultiEntry multipart indexed - update index - Compound', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: ['id', 'id2'], indexes: [ { name: 'key', multiEntry: true, keyPath: 'k.k' } ] } ] }, true).then(prov => { return prov.put('test', { id: 'a', id2: '1', val: 'b', k: { k: ['w', 'x', 'y', 'z'] } }) .then(() => { return prov.getRange('test', 'key', 'x', 'y', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 2); ret.forEach(r => { assert.equal(r.val, 'b'); }); }); }) .then(() => { return prov.put('test', { id: 'a', id2: '1', val: 'b', k: { k: ['z'] } }); }) .then(() => { return prov.getRange('test', 'key', 'x', 'y', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 0); }); }) .then(() => { return prov.getRange('test', 'key', 'x', 'z', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 1); assert.equal(ret[0].val, 'b'); }); }) .then(() => { return prov.remove('test', ['a', '1']); }) .then(() => { return prov.getRange('test', 'key', 'x', 'z', false, false).then(retVal => { const ret = retVal as TestObj[]; assert.equal(ret.length, 0); }); }) .then(() => { return prov.close(); }); }); }); describe('Transaction Semantics', () => { it('Testing transaction expiration', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.openTransaction(['test'], true).then(trans => { let promise = trans.getCompletionPromise(); let check1 = false; promise.then(() => { check1 = true; }, err => { assert.ok(false, 'Bad'); }); return sleep(200).then(() => { assert.ok(check1); const store = trans.getStore('test'); return store.put({ id: 'abc', a: 'a' }); }); }).then(() => { assert.ok(false, 'Should fail'); return Promise.reject<void>(); }, err => { // woot return undefined; }).then(() => { return prov.close(); }); }); }); it('Testing aborting', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { let checked = false; return prov.openTransaction(['test'], true).then(trans => { let promise = trans.getCompletionPromise(); const store = trans.getStore('test'); return store.put({ id: 'abc', a: 'a' }).then(() => { trans.abort(); return promise.then(() => { assert.ok(false, 'Should fail'); }, err => { return prov.get('test', 'abc').then(res => { assert.ok(!res); checked = true; }); }); }); }).then(() => { assert.ok(checked); return prov.close(); }); }); }); it('Testing read/write transaction locks', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', a: 'a' }).then(() => { let check1 = false, check2 = false; let started1 = false; let closed1 = false; const p1 = prov.openTransaction(['test'], true).then(trans => { trans.getCompletionPromise().then(() => { closed1 = true; }); started1 = true; const store = trans.getStore('test'); return store.put({ id: 'abc', a: 'b' }).then(() => { return store.get('abc').then((val: any) => { assert.ok(val && val.a === 'b'); assert.ok(!closed1); check1 = true; }); }); }); assert.ok(!closed1); const p2 = prov.openTransaction(['test'], false).then(trans => { assert.ok(closed1); assert.ok(started1 && check1); const store = trans.getStore('test'); return store.get('abc').then((val: any) => { assert.ok(val && val.a === 'b'); check2 = true; }); }); return Promise.all([p1, p2]).then(() => { assert.ok(check1 && check2); }); }).then(() => { return prov.close(); }); }); }); }); }); if (provName.indexOf('memory') === -1) { describe('Schema Upgrades', () => { it('Opening an older DB version', () => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.close(); }).then(() => { return openProvider(provName, { version: 1, stores: [ { name: 'test2', primaryKeyPath: 'id' } ] }, false).then(prov => { return prov.get('test', 'abc').then(item => { return prov.close().then(() => { return Promise.reject<void>('Shouldn\'t have worked'); }); }, () => { // Expected to fail, so chain from failure to success return prov.close(); }); }); }); }); it('Basic NOOP schema upgrade path', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, false).then(prov => { return prov.get('test', 'abc').then(item => { assert(!!item); return prov.close(); }); }); }); }); it('Adding new store', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' }, { name: 'test2', primaryKeyPath: 'ttt' } ] }, false).then(prov => { return prov.put('test2', { id: 'def', ttt: 'ghi' }).then(() => { const p1 = prov.get('test', 'abc').then(itemVal => { const item = itemVal as TestObj; assert(!!item); assert.equal(item.id, 'abc'); }); const p2 = prov.get('test2', 'abc').then(item => { assert(!item); }); const p3 = prov.get('test2', 'def').then(item => { assert(!item); }); const p4 = prov.get('test2', 'ghi').then(itemVal => { const item = itemVal as TestObj; assert(!!item); assert.equal(item.id, 'def'); }); return Promise.all([p1, p2, p3, p4]).then(() => { return prov.close(); }); }); }); }); }); it('Removing old store', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test2', primaryKeyPath: 'id' } ] }, false).then(prov => { return prov.get('test', 'abc').then(item => { return prov.close().then(() => { return Promise.reject<void>('Shouldn\'t have worked'); }); }, () => { // Expected to fail, so chain from failure to success return prov.close(); }); }); }); }); it('Remove store with index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'abc' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test2', primaryKeyPath: 'id' } ] }, false).then(prov => { return prov.get('test', 'abc').then(item => { return prov.close().then(() => { return Promise.reject<void>('Shouldn\'t have worked'); }); }, () => { // Expected to fail, so chain from failure to success return prov.close(); }); }); }); }); it('Add index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); }); }); }); function testBatchUpgrade(expectedCallCount: number, itemByteSize: number): Promise<void> { const recordCount = 5000; const data: { [id: string]: { id: string, tt: string } } = {}; times(recordCount, num => { data[num.toString()] = { id: num.toString(), tt: 'tt' + num.toString() }; }); return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', estimatedObjBytes: itemByteSize } ] }, true).then(prov => { return prov.put('test', values(data)).then(() => { return prov.close(); }); }).then(() => { let transactionSpy: sinon.SinonSpy | undefined; if (provName.indexOf('sql') !== -1) { // Check that we batch the upgrade by spying on number of queries indirectly // This only affects sql-based tests transactionSpy = sinon.spy(SqlTransaction.prototype, 'internal_getResultsFromQuery') as any; } return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', estimatedObjBytes: itemByteSize, indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, false).then(prov => { if (transactionSpy) { assert.equal(transactionSpy.callCount, expectedCallCount, 'Incorrect transaction count'); transactionSpy.restore(); } return prov.getAll('test', undefined).then((records: any) => { assert.equal(records.length, keys(data).length, 'Incorrect record count'); each(records, dbRecordToValidate => { const originalRecord = data[dbRecordToValidate.id]; assert.ok(!!originalRecord); assert.equal(originalRecord.id, dbRecordToValidate.id); assert.equal(originalRecord.tt, dbRecordToValidate.tt); }); }).then(() => { return prov.close(); }); }); }); } it('Add index - Large records - batched upgrade', () => { return testBatchUpgrade(51, 10000); }); it('Add index - small records - No batch upgrade', () => { return testBatchUpgrade(1, 1); }); if (provName.indexOf('indexeddb') !== 0) { // This migration works on indexeddb because we don't check the types and the browsers silently accept it but just // neglect to index the field... it('Add index to boolean field should fail', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: true }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, false).then(() => { return Promise.reject('Should not work'); }, err => { return Promise.resolve(); }); }); }); } it('Add multiEntry index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: ['a', 'b'] }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p1b = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p1b, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Changing multiEntry index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: ['x', 'y'], ttb: ['a', 'b'] }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'ttb', multiEntry: true }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p1b = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p1c = prov.getOnly('test', 'ind1', 'x').then(items => { assert.equal(items.length, 0); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p1b, p1c, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Removing old index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, false).then(prov => { return prov.getOnly('test', 'ind1', 'a').then(items => { return prov.close().then(() => { return Promise.reject<void>('Shouldn\'t have worked'); }); }, () => { // Expected to fail, so chain from failure to success return prov.close(); }); }); }); }); it('Changing index keypath', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a', ttb: 'b' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'ttb' }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then(items => { assert.equal(items.length, 0); }); const p2 = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].ttb, 'b'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Change non-multientry index to includeDataInIndex', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt' }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', includeDataInIndex: true }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Change non-multientry index from includeDataInIndex', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', includeDataInIndex: true }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', includeDataInIndex: false }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Change multientry index to includeDataInIndex', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: ['a', 'b'] }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true, includeDataInIndex: true }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p1b = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p1b, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Change multientry index from includeDataInIndex', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true, includeDataInIndex: true }] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: ['a', 'b'] }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', multiEntry: true, includeDataInIndex: false }] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p1b = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); const p3 = prov.getOnly('test', 'ind1', 'abc').then(items => { assert.equal(items.length, 0); }); return Promise.all([p1, p1b, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Adding new FTS store', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' }, { name: 'test2', primaryKeyPath: 'id', indexes: [ { name: 'a', keyPath: 'content', fullText: true } ] } ] }, false).then(prov => { return prov.put('test2', { id: 'def', content: 'ghi' }).then(() => { const p1 = prov.get('test', 'abc').then((item: any) => { assert.ok(item); assert.equal(item.id, 'abc'); }); const p2 = prov.get('test2', 'abc').then(item => { assert.ok(!item); }); const p3 = prov.get('test2', 'def').then(item => { assert.ok(item); }); const p4 = prov.fullTextSearch('test2', 'a', 'ghi').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'def'); }); return Promise.all([p1, p2, p3, p4]).then(() => { return prov.close(); }); }); }); }); }); it('Adding new FTS index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', content: 'ghi' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'a', keyPath: 'content', fullText: true } ] } ] }, false).then(prov => { const p1 = prov.get('test', 'abc').then((item: any) => { assert.ok(item); assert.equal(item.id, 'abc'); }); const p2 = prov.fullTextSearch('test', 'a', 'ghi').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }); }); it('Removing FTS index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'a', keyPath: 'content', fullText: true } ] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', content: 'ghi' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, false).then(prov => { const p1 = prov.get('test', 'abc').then((item: any) => { assert.ok(item); assert.equal(item.id, 'abc'); assert.equal(item.content, 'ghi'); }); const p2 = prov.fullTextSearch('test', 'a', 'ghi').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }).then(() => { assert.ok(false, 'should not work'); }, err => { return Promise.resolve(); }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }); }); // indexed db might backfill anyway behind the scenes if (provName.indexOf('indexeddb') !== 0) { it('Adding an index that does not require backfill', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }] } ] }, false).then(prov => prov.put('test', { id: 'bcd', tt: 'b' }).then(() => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { // item not found, we didn't backfill the first item assert.equal(items.length, 0); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); }); const p3 = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { // index works properly for the new item assert.equal(items.length, 1); assert.equal(items[0].id, 'bcd'); assert.equal(items[0].tt, 'b'); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); })); }); }); it('Adding two indexes at once - backfill and not', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'b' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'ind1', keyPath: 'tt', doNotBackfill: true, }, { name: 'ind2', keyPath: 'zz', } ] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { // we had to backfill, so we filled all assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'b'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'b'); }); const p3 = prov.getOnly('test', 'ind2', 'b').then((items: any[]) => { // index works properly for the second index assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'b'); }); return Promise.all([p1, p2, p3]).then(() => { return prov.close(); }); }); }); }); it('Change no backfill index into a normal index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'ind1', keyPath: 'tt', doNotBackfill: true, }, ] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'b' }).then(() => { return prov.close(); }); }).then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'ind1', keyPath: 'tt', }, ] } ] }, false).then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { // we backfilled assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'b'); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'b'); }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }); }); it('Perform two updates which require no backfill', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, true) .then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'aa' }).then(() => { return prov.close(); }); }) .then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }] } ] }, false) .then(prov => { return prov.put('test', { id: 'bcd', tt: 'b', zz: 'bb' }).then(() => { return prov.close(); }); }); }) .then(() => { return openProvider(provName, { version: 3, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }, { name: 'ind2', keyPath: 'zz', doNotBackfill: true }] } ] }, false) .then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { // item not found, we didn't backfill the first item assert.equal(items.length, 0); }); const p2 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'aa'); }); const p3 = prov.getOnly('test', 'ind1', 'b').then((items: any[]) => { // first index works properly for the second item assert.equal(items.length, 1); assert.equal(items[0].id, 'bcd'); assert.equal(items[0].tt, 'b'); }); const p4 = prov.getOnly('test', 'ind2', 'bb').then((items: any[]) => { // second index wasn't backfilled assert.equal(items.length, 0); }); return Promise.all([p1, p2, p3, p4]).then(() => { return prov.close(); }); }); }); }); it('Removes index without pulling data to JS', () => { let storeSpy: sinon.SinonSpy | undefined; return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'ind1', keyPath: 'content', } ] } ] }, true).then(prov => { return prov.put('test', { id: 'abc', content: 'ghi' }).then(() => { return prov.close(); }); }).then(() => { storeSpy = sinon.spy(SqlTransaction.prototype, 'getStore') as any; return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, false) .then(prov => { // NOTE - the line below tests an implementation detail sinon.assert.notCalled(storeSpy!!!); // check the index was actually removed const p1 = prov.get('test', 'abc').then((item: any) => { assert.ok(item); assert.equal(item.id, 'abc'); assert.equal(item.content, 'ghi'); }); const p2 = prov.getOnly('test', 'ind1', 'ghi').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); }).then(() => { assert.ok(false, 'should not work'); }, err => { return Promise.resolve(); }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }).finally(() => { if (storeSpy) { storeSpy.restore(); } }); }); it('Cleans up stale indices from metadata', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [ { name: 'ind1', keyPath: 'content', }, { name: 'ind2', keyPath: 'content', } ] } ] }, true) .then(prov => prov.close()) .then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id' } ] }, false); }) .then(prov => { return prov.openTransaction(undefined, false).then(trans => { return (trans as SqlTransaction).runQuery('SELECT name, value from metadata').then(fullMeta => { each(fullMeta, (meta: any) => { let metaObj = JSON.parse(meta.value); if (metaObj.storeName === 'test' && !!metaObj.index && metaObj.index.name === 'ind1') { assert.fail('Removed index should not exist in the meta!'); } }); }); }).then(() => { return prov.close(); }); }); }); it('Add and remove index in the same upgrade', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }] } ] }, true) .then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'aa' }).then(() => { return prov.close(); }); }) .then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind2', keyPath: 'zz', doNotBackfill: true }] } ] }, false) .then(prov => { const p1 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'aa'); }); const p2 = prov.getOnly('test', 'ind1', 'a').then(items => { return Promise.reject<void>('Shouldn\'t have worked'); }, () => { // Expected to fail, so chain from failure to success return undefined; }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }); }); it('Recreates missing indices', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }] } ] }, true) .then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'aa' }) .then(() => { return prov.openTransaction(['test'], true).then(trans => { // simulate broken index return (trans as SqlTransaction).runQuery('DROP INDEX test_ind1'); }); }) .then(() => { return prov.close(); }); }) .then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }] } ] }, false) .then(prov => { const p1 = prov.getOnly('test', 'ind1', 'a').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'aa'); }); const p2 = prov.openTransaction(undefined, false).then(trans => { return (trans as SqlTransaction).runQuery('SELECT type, name, tbl_name, sql from sqlite_master') .then(fullMeta => { const oldIndexReallyExists = some(fullMeta, (metaObj: any) => { if (metaObj.type === 'index' && metaObj.tbl_name === 'test' && metaObj.name === 'test_ind1') { return true; } return false; }); if (!oldIndexReallyExists) { return Promise.reject('Unchanged index should still exist!'); } return Promise.resolve(undefined); }); }); return Promise.all([p1, p2]).then(() => { return prov.close(); }); }); }); }); it('Add remove index in the same upgrade, while preserving other indices', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind1', keyPath: 'tt', doNotBackfill: true }, { name: 'ind2', keyPath: 'zz', doNotBackfill: true }] } ] }, true) .then(prov => { return prov.put('test', { id: 'abc', tt: 'a', zz: 'aa' }).then(() => { return prov.close(); }); }) .then(() => { return openProvider(provName, { version: 2, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'ind2', keyPath: 'zz', doNotBackfill: true }, { name: 'ind3', keyPath: 'zz', doNotBackfill: true }] } ] }, false) .then(prov => { const p1 = prov.getOnly('test', undefined, 'abc').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'aa'); }); const p2 = prov.getOnly('test', 'ind2', 'aa').then((items: any[]) => { assert.equal(items.length, 1); assert.equal(items[0].id, 'abc'); assert.equal(items[0].tt, 'a'); assert.equal(items[0].zz, 'aa'); }); const p3 = prov.getOnly('test', 'ind1', 'a').then(items => { return Promise.reject<void>('Shouldn\'t have worked'); }, () => { // Expected to fail, so chain from failure to success return undefined; }); const p4 = prov.openTransaction(undefined, false).then(trans => { return (trans as SqlTransaction).runQuery('SELECT type, name, tbl_name, sql from sqlite_master') .then(fullMeta => { const oldIndexReallyExists = some(fullMeta, (metaObj: any) => { if (metaObj.type === 'index' && metaObj.tbl_name === 'test' && metaObj.name === 'test_ind2') { return true; } return false; }); if (!oldIndexReallyExists) { return Promise.reject('Unchanged index should still exist!'); } return Promise.resolve(undefined); }); }); return Promise.all([p1, p2, p3, p4]).then(() => { return prov.close(); }); }); }); }); } }); } it('Full Text Index', () => { return openProvider(provName, { version: 1, stores: [ { name: 'test', primaryKeyPath: 'id', indexes: [{ name: 'i', keyPath: 'txt', fullText: true }] } ] }, true).then(prov => { return prov.put('test', [ { id: 'a1', txt: 'the quick brown fox jumps over the lăzy dog who is a bro with brows' }, { id: 'a2', txt: 'bob likes his dog' }, { id: 'a3', txt: 'tes>ter' }, { id: 'a4', txt: 'Бывает проснешься как птица,' + ' крылатой пружиной на взводе и хочется жить и трудиться, но к завтраку это проходит!' }, { id: 'a5', txt: '漁夫從遠處看見漁夫' }, { // i18n digits test case id: 'a6', txt: '߂i18nDigits߂' }, { // Test data to make sure that we don't search for empty strings (... used to put empty string to the index) id: 'a7', txt: 'User1, User2, User3 ...' } ]).then(() => { const p1 = prov.fullTextSearch('test', 'i', 'brown').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p2 = prov.fullTextSearch('test', 'i', 'dog').then(res => { assert.equal(res.length, 2); }); const p3 = prov.fullTextSearch('test', 'i', 'do').then(res => { assert.equal(res.length, 2); }); const p4 = prov.fullTextSearch('test', 'i', 'LiKe').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a2'); }); const p5 = prov.fullTextSearch('test', 'i', 'azy').then(res => { assert.equal(res.length, 0); }); const p6 = prov.fullTextSearch('test', 'i', 'lazy dog').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p7 = prov.fullTextSearch('test', 'i', 'dog lazy').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p8 = prov.fullTextSearch('test', 'i', 'DOG lăzy').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p9 = prov.fullTextSearch('test', 'i', 'lĄzy').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p10 = prov.fullTextSearch('test', 'i', 'brown brown brown').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p11 = prov.fullTextSearch('test', 'i', 'brown brOwn browN').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p12 = prov.fullTextSearch('test', 'i', 'brow').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p13 = prov.fullTextSearch('test', 'i', 'bro').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p14 = prov.fullTextSearch('test', 'i', 'br').then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p15 = prov.fullTextSearch('test', 'i', 'b').then(res => { assert.equal(res.length, 2); }); const p16 = prov.fullTextSearch('test', 'i', 'b z').then(res => { assert.equal(res.length, 0); }); const p17 = prov.fullTextSearch('test', 'i', 'b z', FullTextTermResolution.Or).then((res: any[]) => { assert.equal(res.length, 2); assert.ok(some(res, r => r.id === 'a1') && some(res, r => r.id === 'a2')); }); const p18 = prov.fullTextSearch('test', 'i', 'q h', FullTextTermResolution.Or).then((res: any[]) => { assert.equal(res.length, 2); assert.ok(some(res, r => r.id === 'a1') && some(res, r => r.id === 'a2')); }); const p19 = prov.fullTextSearch('test', 'i', 'fox nopers', FullTextTermResolution.Or) .then((res: any[]) => { assert.equal(res.length, 1); assert.equal(res[0].id, 'a1'); }); const p20 = prov.fullTextSearch('test', 'i', 'foxers nopers', FullTextTermResolution.Or) .then(res => { assert.equal(res.length, 0); }); const p21 = prov.fullTextSearch('test', 'i', 'fox)', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); const p22 = prov.fullTextSearch('test', 'i', 'fox*', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); const p23 = prov.fullTextSearch('test', 'i', 'fox* fox( <fox>', FullTextTermResolution.Or) .then(res => { assert.equal(res.length, 1); }); const p24 = prov.fullTextSearch('test', 'i', 'f)ox', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 0); }); const p25 = prov.fullTextSearch('test', 'i', 'fo*x', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 0); }); const p26 = prov.fullTextSearch('test', 'i', 'tes>ter', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); const p27 = prov.fullTextSearch('test', 'i', 'f*x', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 0); }); const p28 = prov.fullTextSearch('test', 'i', 'бывает', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); const p29 = prov.fullTextSearch('test', 'i', '漁', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); const p30 = prov.fullTextSearch('test', 'i', '߂i18nDigits߂', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 1); }); // This is an empty string test. All special symbols will be replaced so this is technically empty string search. const p31 = prov.fullTextSearch('test', 'i', '!@#$%$', FullTextTermResolution.Or).then(res => { assert.equal(res.length, 0); }); return Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, p27, p28, p29, p30, p31]).then(() => { return prov.close(); }); }); }); }); }); }); });
the_stack
* Hyperledger Cactus Example - Supply Chain App * Demonstrates how a business use case can be satisfied with Cactus when multiple distinct ledgers are involved. * * The version of the OpenAPI document: 0.2.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * * @export * @interface BambooHarvest */ export interface BambooHarvest { /** * * @type {string} * @memberof BambooHarvest */ id: string; /** * * @type {string} * @memberof BambooHarvest */ location: string; /** * * @type {string} * @memberof BambooHarvest */ startedAt: string; /** * * @type {string} * @memberof BambooHarvest */ endedAt: string; /** * * @type {string} * @memberof BambooHarvest */ harvester: string; } /** * * @export * @interface Bookshelf */ export interface Bookshelf { /** * * @type {string} * @memberof Bookshelf */ id: string; /** * The number of shelves the bookshelf comes with. * @type {number} * @memberof Bookshelf */ shelfCount: number; /** * The foreign key ID referencing the bamboo harvest that yielded the wood material for the construction of the bookshelf. * @type {string} * @memberof Bookshelf */ bambooHarvestId: string; } /** * * @export * @interface InsertBambooHarvestRequest */ export interface InsertBambooHarvestRequest { /** * * @type {BambooHarvest} * @memberof InsertBambooHarvestRequest */ bambooHarvest: BambooHarvest; } /** * * @export * @interface InsertBambooHarvestResponse */ export interface InsertBambooHarvestResponse { /** * * @type {{ [key: string]: object; }} * @memberof InsertBambooHarvestResponse */ callOutput?: { [key: string]: object; }; /** * * @type {{ [key: string]: object; }} * @memberof InsertBambooHarvestResponse */ transactionReceipt?: { [key: string]: object; }; } /** * * @export * @interface InsertBookshelfRequest */ export interface InsertBookshelfRequest { /** * * @type {Bookshelf} * @memberof InsertBookshelfRequest */ bookshelf: Bookshelf; } /** * * @export * @interface InsertBookshelfResponse */ export interface InsertBookshelfResponse { /** * * @type {{ [key: string]: object; }} * @memberof InsertBookshelfResponse */ callOutput?: { [key: string]: object; }; /** * * @type {{ [key: string]: object; }} * @memberof InsertBookshelfResponse */ transactionReceipt?: { [key: string]: object; }; } /** * * @export * @interface InsertShipmentRequest */ export interface InsertShipmentRequest { /** * * @type {Shipment} * @memberof InsertShipmentRequest */ shipment: Shipment; } /** * * @export * @interface InsertShipmentResponse */ export interface InsertShipmentResponse { /** * * @type {{ [key: string]: object; }} * @memberof InsertShipmentResponse */ callOutput?: { [key: string]: object; }; /** * * @type {{ [key: string]: object; }} * @memberof InsertShipmentResponse */ transactionReceipt?: { [key: string]: object; }; } /** * * @export * @interface ListBambooHarvestResponse */ export interface ListBambooHarvestResponse { /** * * @type {Array<BambooHarvest>} * @memberof ListBambooHarvestResponse */ data: Array<BambooHarvest>; } /** * * @export * @interface ListBookshelfResponse */ export interface ListBookshelfResponse { /** * * @type {Array<Bookshelf>} * @memberof ListBookshelfResponse */ data: Array<Bookshelf>; } /** * * @export * @interface ListShipmentResponse */ export interface ListShipmentResponse { /** * * @type {Array<Shipment>} * @memberof ListShipmentResponse */ data: Array<Shipment>; } /** * * @export * @interface Shipment */ export interface Shipment { /** * * @type {string} * @memberof Shipment */ id: string; /** * The foreign key ID referencing the bookshelfId that will go in the shipment. * @type {string} * @memberof Shipment */ bookshelfId: string; } /** * DefaultApi - axios parameter creator * @export */ export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * * @summary Inserts the provided BambooHarvest entity to the ledger. * @param {InsertBambooHarvestRequest} [insertBambooHarvestRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertBambooHarvestV1: async (insertBambooHarvestRequest?: InsertBambooHarvestRequest, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/insert-bamboo-harvest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(insertBambooHarvestRequest, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Inserts the provided Bookshelf entity to the ledger. * @param {InsertBookshelfRequest} [insertBookshelfRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertBookshelfV1: async (insertBookshelfRequest?: InsertBookshelfRequest, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/insert-bookshelf`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(insertBookshelfRequest, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Inserts the provided Shipment entity to the ledger. * @param {InsertShipmentRequest} [insertShipmentRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertShipmentV1: async (insertShipmentRequest?: InsertShipmentRequest, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/insert-shipment`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(insertShipmentRequest, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Lists all the BambooHarvest entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listBambooHarvestV1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/list-bamboo-harvest`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Lists all the Bookshelf entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listBookshelfV1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/list-bookshelf`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Lists all the Shipments entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listShipmentV1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-example-supply-chain-backend/list-shipment`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * DefaultApi - functional programming interface * @export */ export const DefaultApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration) return { /** * * @summary Inserts the provided BambooHarvest entity to the ledger. * @param {InsertBambooHarvestRequest} [insertBambooHarvestRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async insertBambooHarvestV1(insertBambooHarvestRequest?: InsertBambooHarvestRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<InsertBambooHarvestResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.insertBambooHarvestV1(insertBambooHarvestRequest, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Inserts the provided Bookshelf entity to the ledger. * @param {InsertBookshelfRequest} [insertBookshelfRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async insertBookshelfV1(insertBookshelfRequest?: InsertBookshelfRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<InsertBookshelfResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.insertBookshelfV1(insertBookshelfRequest, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Inserts the provided Shipment entity to the ledger. * @param {InsertShipmentRequest} [insertShipmentRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async insertShipmentV1(insertShipmentRequest?: InsertShipmentRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<InsertShipmentResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.insertShipmentV1(insertShipmentRequest, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Lists all the BambooHarvest entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async listBambooHarvestV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListBambooHarvestResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.listBambooHarvestV1(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Lists all the Bookshelf entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async listBookshelfV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListBookshelfResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.listBookshelfV1(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Lists all the Shipments entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async listShipmentV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListShipmentResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.listShipmentV1(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * DefaultApi - factory interface * @export */ export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = DefaultApiFp(configuration) return { /** * * @summary Inserts the provided BambooHarvest entity to the ledger. * @param {InsertBambooHarvestRequest} [insertBambooHarvestRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertBambooHarvestV1(insertBambooHarvestRequest?: InsertBambooHarvestRequest, options?: any): AxiosPromise<InsertBambooHarvestResponse> { return localVarFp.insertBambooHarvestV1(insertBambooHarvestRequest, options).then((request) => request(axios, basePath)); }, /** * * @summary Inserts the provided Bookshelf entity to the ledger. * @param {InsertBookshelfRequest} [insertBookshelfRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertBookshelfV1(insertBookshelfRequest?: InsertBookshelfRequest, options?: any): AxiosPromise<InsertBookshelfResponse> { return localVarFp.insertBookshelfV1(insertBookshelfRequest, options).then((request) => request(axios, basePath)); }, /** * * @summary Inserts the provided Shipment entity to the ledger. * @param {InsertShipmentRequest} [insertShipmentRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} */ insertShipmentV1(insertShipmentRequest?: InsertShipmentRequest, options?: any): AxiosPromise<InsertShipmentResponse> { return localVarFp.insertShipmentV1(insertShipmentRequest, options).then((request) => request(axios, basePath)); }, /** * * @summary Lists all the BambooHarvest entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listBambooHarvestV1(options?: any): AxiosPromise<ListBambooHarvestResponse> { return localVarFp.listBambooHarvestV1(options).then((request) => request(axios, basePath)); }, /** * * @summary Lists all the Bookshelf entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listBookshelfV1(options?: any): AxiosPromise<ListBookshelfResponse> { return localVarFp.listBookshelfV1(options).then((request) => request(axios, basePath)); }, /** * * @summary Lists all the Shipments entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listShipmentV1(options?: any): AxiosPromise<ListShipmentResponse> { return localVarFp.listShipmentV1(options).then((request) => request(axios, basePath)); }, }; }; /** * DefaultApi - object-oriented interface * @export * @class DefaultApi * @extends {BaseAPI} */ export class DefaultApi extends BaseAPI { /** * * @summary Inserts the provided BambooHarvest entity to the ledger. * @param {InsertBambooHarvestRequest} [insertBambooHarvestRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public insertBambooHarvestV1(insertBambooHarvestRequest?: InsertBambooHarvestRequest, options?: any) { return DefaultApiFp(this.configuration).insertBambooHarvestV1(insertBambooHarvestRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Inserts the provided Bookshelf entity to the ledger. * @param {InsertBookshelfRequest} [insertBookshelfRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public insertBookshelfV1(insertBookshelfRequest?: InsertBookshelfRequest, options?: any) { return DefaultApiFp(this.configuration).insertBookshelfV1(insertBookshelfRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Inserts the provided Shipment entity to the ledger. * @param {InsertShipmentRequest} [insertShipmentRequest] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public insertShipmentV1(insertShipmentRequest?: InsertShipmentRequest, options?: any) { return DefaultApiFp(this.configuration).insertShipmentV1(insertShipmentRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Lists all the BambooHarvest entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public listBambooHarvestV1(options?: any) { return DefaultApiFp(this.configuration).listBambooHarvestV1(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Lists all the Bookshelf entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public listBookshelfV1(options?: any) { return DefaultApiFp(this.configuration).listBookshelfV1(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Lists all the Shipments entities stored on the ledger. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public listShipmentV1(options?: any) { return DefaultApiFp(this.configuration).listShipmentV1(options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import { useContentGqlHandler } from "../utils/useContentGqlHandler"; import { mocks as changeRequestMock } from "./mocks/changeRequest"; import { createContentReviewSetup } from "../utils/helpers"; const richTextMock = [ { tag: "h1", content: "Testing H1 tags" }, { tag: "p", content: "Some small piece of text to test P tags" }, { tag: "div", content: [ { tag: "p", text: "Text inside the div > p" }, { tag: "a", href: "https://www.webiny.com", text: "Webiny" } ] } ]; const expectedComment = expect.objectContaining({ id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: expect.any(String), displayName: expect.any(String), type: "admin" }, body: richTextMock, changeRequest: expect.any(String) }); describe("Comment on a change request test", () => { const options = { path: "manage/en-US" }; const gqlHandler = useContentGqlHandler({ ...options }); const { createChangeRequestMutation, createCommentMutation, listCommentsQuery, deleteChangeRequestMutation, until } = gqlHandler; const getChangeRequestStep = async () => { const { contentReview } = await createContentReviewSetup(gqlHandler); return `${contentReview.id}#${contentReview.steps[0].id}`; }; test("should able to comment on a change request", async () => { const { contentReview } = await createContentReviewSetup(gqlHandler); const changeRequestStep = `${contentReview.id}#${contentReview.steps[0].id}`; /* * Create a new change request entry. */ const [createChangeRequestResponse] = await createChangeRequestMutation({ data: changeRequestMock.createChangeRequestInput({ step: changeRequestStep }) }); const changeRequested = createChangeRequestResponse.data.apw.createChangeRequest.data; /** * Add a comment to this change request. */ const [createCommentResponse] = await createCommentMutation({ data: { body: richTextMock, changeRequest: changeRequested.id } }); const firstComment = createCommentResponse.data.apw.createComment.data; expect(createCommentResponse).toEqual({ data: { apw: { createComment: { data: { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: expect.any(String), displayName: expect.any(String), type: "admin" }, body: richTextMock, changeRequest: changeRequested.id, media: null }, error: null } } } }); await until( () => listCommentsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listComments.data.length === 1, { name: "Wait for entry to be available via list query" } ); /** * List all comments for a given change request. */ const [listCommentsResponse] = await listCommentsQuery({ where: { changeRequest: { id: changeRequested.id } } }); expect(listCommentsResponse).toEqual({ data: { apw: { listComments: { data: [ { id: firstComment.id, createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: expect.any(String), displayName: expect.any(String), type: "admin" }, body: richTextMock, changeRequest: changeRequested.id, media: null } ], error: null, meta: { hasMoreItems: false, totalCount: 1, cursor: null } } } } }); /** * Add another comment to the change request. */ const [anotherCreateCommentResponse] = await createCommentMutation({ data: { body: richTextMock, changeRequest: changeRequested.id } }); const secondComment = anotherCreateCommentResponse.data.apw.createComment.data; await until( () => listCommentsQuery({}).then(([data]) => data), (response: any) => response.data.apw.listComments.data.length === 2, { name: "Wait for entry to be available via list query" } ); /** * Again, list all comments for a given change request. */ const [listCommentsResponse2] = await listCommentsQuery({ where: { changeRequest: { id: changeRequested.id } }, sort: ["createdOn_DESC"] }); expect(listCommentsResponse2).toEqual({ data: { apw: { listComments: { data: [ { id: secondComment.id, createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: expect.any(String), displayName: expect.any(String), type: "admin" }, body: richTextMock, changeRequest: changeRequested.id, media: null }, { id: firstComment.id, createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: expect.any(String), displayName: expect.any(String), type: "admin" }, body: richTextMock, changeRequest: changeRequested.id, media: null } ], error: null, meta: { hasMoreItems: false, totalCount: 2, cursor: null } } } } }); }); test("should able to delete all comments when a change request gets deleted", async () => { const changeRequestStep = await getChangeRequestStep(); /* * Create two new change request entries. */ const changesRequested: { id: string }[] = []; for (let i = 0; i < 2; i++) { const [createChangeRequestResponse] = await createChangeRequestMutation({ data: changeRequestMock.createChangeRequestInput({ step: changeRequestStep }) }); changesRequested.push(createChangeRequestResponse.data.apw.createChangeRequest.data); } const totalChangeRequest = 2; const commentsPerChangeRequest = 20; const totalComments = totalChangeRequest * commentsPerChangeRequest; /** * Add two comments on each change request. */ const comments = []; for (let i = 0; i < changesRequested.length; i++) { for (let j = 0; j < commentsPerChangeRequest; j++) { const [createCommentResponse] = await createCommentMutation({ data: { body: richTextMock, changeRequest: changesRequested[i].id } }); comments.push(createCommentResponse.data.apw.createComment.data); } } await until( () => listCommentsQuery({}).then(([data]) => data), (response: any) => { return response.data.apw.listComments.meta.totalCount === totalComments; }, { name: "Wait for entry to be available via list query" } ); /** * List all comments. */ let [listCommentsResponse] = await listCommentsQuery({ sort: ["createdOn_DESC"] }); expect(listCommentsResponse).toEqual({ data: { apw: { listComments: { data: expect.arrayContaining([expectedComment]), error: null, meta: { hasMoreItems: true, totalCount: totalComments, cursor: expect.any(String) } } } } }); /** * Let's delete the first change request. */ const [deleteChangeRequest] = await deleteChangeRequestMutation({ id: changesRequested[0].id }); expect(deleteChangeRequest).toEqual({ data: { apw: { deleteChangeRequest: { data: true, error: null } } } }); await until( () => listCommentsQuery({ where: { changeRequest: { id: changesRequested[0].id } } }).then(([data]) => data), (response: any) => { return response.data.apw.listComments.meta.totalCount === 0; }, { name: "Wait for entry to be removed from list query" } ); /** * List all the comments associated with the deleted change request. */ [listCommentsResponse] = await listCommentsQuery({ where: { changeRequest: { id: changesRequested[0].id } } }); expect(listCommentsResponse).toEqual({ data: { apw: { listComments: { data: [], error: null, meta: { hasMoreItems: false, totalCount: 0, cursor: null } } } } }); /** * List all the comments without any filters. */ [listCommentsResponse] = await listCommentsQuery({ sort: ["createdOn_DESC"], limit: commentsPerChangeRequest }); expect(listCommentsResponse).toEqual({ data: { apw: { listComments: { data: expect.arrayContaining([expectedComment]), error: null, meta: { hasMoreItems: false, totalCount: commentsPerChangeRequest, cursor: null } } } } }); }); test(`should return error when trying commenting on non-existing change request`, async () => { /** * Try adding a comment to a non-existing change request. */ let [createCommentResponse] = await createCommentMutation({ data: { body: richTextMock, changeRequest: "" } }); expect(createCommentResponse).toEqual({ data: { apw: { createComment: { data: null, error: { code: "MALFORMED_CHANGE_REQUEST_ID", message: expect.any(String), data: expect.any(Object) } } } } }); [createCommentResponse] = await createCommentMutation({ data: { body: richTextMock, changeRequest: "6205072093e05300095591a2#0001" } }); expect(createCommentResponse).toEqual({ data: { apw: { createComment: { data: null, error: { code: "NOT_FOUND", message: expect.any(String), data: expect.any(Object) } } } } }); }); });
the_stack
import axios from 'axios'; import { CommandLineOptions } from 'command-line-args'; import * as fs from 'fs'; import * as path from 'path'; import * as util from 'util'; import { getFileInfo } from 'pyright-internal/analyzer/analyzerNodeInfo'; import { AnalyzerService } from 'pyright-internal/analyzer/service'; import { ConfigOptions } from 'pyright-internal/common/configOptions'; import { ConsoleInterface } from 'pyright-internal/common/console'; import { combinePaths, ensureTrailingDirectorySeparator, getDirectoryPath, getPathComponents, normalizePath, } from 'pyright-internal/common/pathUtils'; import { convertOffsetToPosition } from 'pyright-internal/common/positionUtils'; import { ParseNode, ParseNodeType } from 'pyright-internal/parser/parseNodes'; import { fetchAddr } from '../backend/backUtils'; import { Constraint, ConstraintType, CtrAnd, CtrBroad, CtrEq, CtrExpBool, CtrFail, CtrForall, CtrLt, CtrLte, CtrNeq, CtrNot, CtrOr, } from '../backend/constraintType'; import { ContextSet } from '../backend/context'; import { ShHeap } from '../backend/sharpEnvironments'; import { CodeRange, CodeSource, ShValue, SVObject, SVSize, SVType } from '../backend/sharpValues'; import { ExpBool, ExpNum, ExpShape, ExpString, SymExp, SymInt, SymVal } from '../backend/symExpressions'; import { TorchIRFrontend } from '../frontend/torchFrontend'; import { ThStmt } from '../frontend/torchStatements'; import { FilePathStore } from './executionPaths'; import { PyteaOptions } from './pyteaOptions'; export const enum PyZ3RPCResultType { Unreachable = 0, Valid = 1, Sat = 2, Unsat = 3, DontKnow = 4, Timeout = -1, } export interface PyZ3RPCResult { type: PyZ3RPCResultType; extras?: { conflict?: number; // first index of conflicted constraint (type == Invalid) undecide?: number; // first index of undecidable constraint (type == Undecidable) }; } export interface PyZ3RPCRespond { jsonrpc: 2.0; id: number; result: PyZ3RPCResult[]; log: string; } export class NodeConsole implements ConsoleInterface { logger: ReturnType<typeof util.debuglog>; constructor(loggerName: string) { this.logger = util.debuglog(loggerName); } warn(message: string) { this.logger('\n' + message + '\n'); } info(message: string) { this.logger('\n' + message + '\n'); } log(message: string) { this.logger('\n' + message + '\n'); } error(message: string) { this.logger('\nERROR: ' + message + '\n'); } } export function getPyteaLibPath() { const pylibDir = 'pylib'; let moduleDirectory = (global as any).__rootDirectory; if (!moduleDirectory) { return undefined; } moduleDirectory = getDirectoryPath(ensureTrailingDirectorySeparator(normalizePath(moduleDirectory))); const pylibPath = combinePaths(moduleDirectory, pylibDir); if (fs.existsSync(pylibPath)) { return pylibPath; } // In the debug version of Pytea, the code is one level // deeper, so we need to look one level up for the typeshed fallback. const debugPylibPath = combinePaths(getDirectoryPath(moduleDirectory), pylibDir); if (fs.existsSync(debugPylibPath)) { return debugPylibPath; } return undefined; } export function buildPyteaOption( args?: CommandLineOptions, basePath?: string, baseOptions?: PyteaOptions ): PyteaOptions | string { const cwd = basePath ?? path.normalize(process.cwd()); args = args ?? {}; const rawEntryPath: string = args['file']; const rawConfigPath: string = args['configPath']; const rawLibPath: string = args.libPath ? normalizePath(combinePaths(cwd, args.libPath)) : baseOptions?.pyteaLibPath ?? ''; const entryPath: string = rawEntryPath ? normalizePath(combinePaths(cwd, rawEntryPath)) : baseOptions?.entryPath ?? ''; let configPath: string = rawConfigPath ? normalizePath(combinePaths(cwd, rawConfigPath)) : baseOptions?.configPath ?? ''; if (!configPath && !entryPath) { return `neither configPath nor file path is found: ${entryPath}`; } if (entryPath && !fs.existsSync(entryPath)) { return `file path '${entryPath}' does not exist`; } let options: Partial<PyteaOptions> = {}; options.configPath = configPath; // find config by entryPath if configPath is not set let isDir = false; if (!configPath && entryPath) { if (fs.lstatSync(entryPath).isDirectory()) { isDir = true; } const dirPath = isDir ? entryPath : path.dirname(entryPath); configPath = combinePaths(dirPath, 'pyteaconfig.json'); } if (configPath && !fs.existsSync(configPath)) { console.log(`config json '${configPath}' does not exist. use default options`); configPath = ''; } let dirPath: string; try { if (configPath) { dirPath = path.dirname(configPath); options = JSON.parse(fs.readFileSync(configPath).toString()); if (options.entryPath) options.entryPath = normalizePath(combinePaths(dirPath, options.entryPath)); } else { options = { ...baseOptions }; } } catch (e) { throw `'${configPath}' is not a valid JSON file`; } // entry path is explicitly given && given path is not dir -> set entry path explicitly if (entryPath && !isDir) options.entryPath = entryPath; // found config by directory, but entryPath is not set if (isDir && configPath && fs.existsSync(configPath) && !options.entryPath) { return `'entryPath' is not set from '${configPath}'`; } if (!options.entryPath || !fs.existsSync(options.entryPath)) { return `file path '${options.entryPath}' does not exist`; } dirPath = path.dirname(options.entryPath); if (rawLibPath) { options.pyteaLibPath = rawLibPath; } else if (!options.pyteaLibPath) { // default libpath should be bundled with pytea.js options.pyteaLibPath = getPyteaLibPath(); if (!options.pyteaLibPath) options.pyteaLibPath = path.join(__dirname, 'pylib'); } else { options.pyteaLibPath = normalizePath(combinePaths(dirPath, options.pyteaLibPath)); } if (!fs.existsSync(options.pyteaLibPath)) { return `pytea library path '${options.pyteaLibPath}' does not exist`; } options = { ...baseOptions, ...options }; // override by runtime node args if (args.logLevel !== undefined) options.logLevel = args.logLevel; if (args.extractIR !== undefined) options.extractIR = args.extractIR; return options as PyteaOptions; } // search every directory recursively and return every .py file paths (relative to projectPath) // e.g.) ['LibCall.py', 'torch/__init__.py', ...] export function getScriptRelPaths(projectPath: string, configOptions: ConfigOptions): string[] { const fileNames: string[] = []; const venvPath = configOptions.venvPath ? combinePaths(configOptions.projectRoot, configOptions.venvPath) : undefined; function iterDir(dirPath: string, prefix: string): void { fs.readdirSync(dirPath, { withFileTypes: true }).forEach((dirent) => { const fullPath = path.join(dirPath, dirent.name); const relPath = path.join(prefix, dirent.name); // ignore venv if (venvPath && fullPath === venvPath) { return; } if (dirent.isDirectory()) { // ignore venv if (fs.existsSync(path.join(fullPath, 'pyvenv.cfg'))) { return; } iterDir(fullPath, relPath); } else if (dirent.isFile()) { if (path.extname(dirent.name) === '.py') { fileNames.push(relPath); } } }); } iterDir(projectPath, ''); return fileNames; } // filePath should be relative to import base directory. // e.g.) torch/functional.py => torch.functional // torch/__init__.py => torch export function filePathToQualId(path: string): string { const dotPaths = getPathComponents(path) .filter((comp) => !['', '.', '..'].includes(comp)) .join('.'); if (dotPaths.endsWith('.py')) { return dotPaths.slice(0, -3); } else if (dotPaths.endsWith('.__init__.py')) { return dotPaths.slice(0, -12); } return dotPaths; } // return 'module qualPath => [file full path, ThStmt]' // e.g.) "torch.functional" => <some statement> export function getStmtsFromDir(service: AnalyzerService, dirPath: string): Map<string, [string, ThStmt]> { // Always enable "test mode". const parser = new TorchIRFrontend(); const configOptions = service.getConfigOptions(); const libFileNames = getScriptRelPaths(dirPath, configOptions); const libFilePaths = libFileNames.map((fn) => path.resolve(dirPath, fn)); const program = service.backgroundAnalysisProgram.program; program.addTrackedFiles(libFilePaths); while (program.analyze()) { // Continue to call analyze until it completes. Since we're not // specifying a timeout, it should complete the first time. } // analyze single pytorch entry file const libMap: Map<string, [string, ThStmt]> = new Map(); for (const fpId in libFilePaths) { const fp = libFilePaths[fpId]; const fn = libFileNames[fpId]; if (fp.endsWith('LibCall.py')) { continue; } const sourceFile = program.getSourceFile(fp); if (!sourceFile) { console.log(`Source file not found for ${fp}`); continue; } let stmt: ThStmt | undefined; try { const parseResult = service.getParseResult(fp); if (parseResult?.parseTree) { stmt = parser.translate(parseResult.parseTree); } } catch (e) { console.log(`Frontend parse failed: ${fp}\n${e}`); continue; } if (!stmt) { console.log(`library script parse error: ${fp}`); } else { libMap.set(filePathToQualId(fn), [fp, stmt]); } } return libMap; } // 'src.module.A' -> ['src', 'src.module', 'src.module.A'] // '..A.B' (from ..A import B) -> ['..', '..A', '..A.B'] // '.A.B', 'C.D' -> ['C', 'C.A', 'C.A.B'] // '..A', 'C.D.E' -> ['C', 'C.A'] export function scanQualPath(qualPath: string, currPath?: string): string[] { let leadingDots = 0; while (leadingDots < qualPath.length && qualPath[leadingDots] === '.') { leadingDots++; } const paths = qualPath.substr(leadingDots).split('.'); for (let i = 0; i < paths.length - 1; i++) { paths[i + 1] = `${paths[i]}.${paths[i + 1]}`; } if (leadingDots > 0) { if (currPath === undefined) { const dots = '.'.repeat(leadingDots); return [dots, ...paths.map((p) => dots + p)]; } else { const basePaths = scanQualPath(currPath); basePaths.splice(-leadingDots, leadingDots); if (basePaths.length === 0) { return paths; } else { const base = basePaths[basePaths.length - 1]; paths.forEach((p) => basePaths.push(`${base}.${p}`)); return basePaths; } } } else { return paths; } } export function exportConstraintSet<T>(result: ContextSet<T>, path: string): void { const jsonList: string[] = []; result.getList().forEach((ctx) => { jsonList.push(ctx.ctrSet.getConstraintJSON()); }); result.getStopped().forEach((ctx) => { jsonList.push(ctx.ctrSet.getConstraintJSON()); }); const jsonStr = `[\n${jsonList.join(',\n')}\n]`; fs.writeFileSync(path, jsonStr); } export type CustomObjectPrinter = [ShValue, (value: SVObject) => string]; // if value is address, return fetchAddr(value, heap) // if that object has attr 'shape' and that is SVSize, return `Tensor ${value.size}` // also reduce some classes with 'customObjectPrinter', list of pairs of class mro and printer. export function reducedToString( value: ShValue, heap: ShHeap, customObjectPrinter?: CustomObjectPrinter[], attrMax?: number ): string { attrMax = attrMax ?? 8; const obj = fetchAddr(value, heap); if (obj) { if (obj.type === SVType.Object) { if (obj instanceof SVSize) { return `SVSize(${SymExp.toString(obj.shape)})`; } const shape = fetchAddr(obj.getAttr('shape'), heap); if (shape && shape instanceof SVSize) { return `tensor: ${SymExp.toString(shape.shape)}`; } const mro = fetchAddr(obj.getAttr('__mro__'), heap); if (customObjectPrinter && mro) { for (const [pmro, printer] of customObjectPrinter) { if (pmro.equals(mro)) { return printer(obj); } } } const attrStr = obj.attrs.count() > attrMax ? `<${obj.attrs.count()} attrs>` : `${ShValue.toStringStrMap(obj.attrs)}`; const indStr = obj.indices.count() > attrMax ? `<${obj.indices.count()} indexed values>` : `${ShValue.toStringNumMap(obj.indices)}`; const kvStr = obj.keyValues.count() > attrMax ? `<${obj.keyValues.count()} keyed values>` : `${ShValue.toStringStrMap(obj.keyValues)}`; const shapeStr = obj.shape ? `, ${ExpShape.toString(obj.shape)}` : ''; return `[${obj.addr.addr}]{ ${attrStr}, ${indStr}, ${kvStr}${shapeStr} }`; } return obj.toString(); } else { return value.toString(); } } // make ParseNode to CodeRange export namespace CodeSourcePositioner { export function cleanConstraint(ctr: Constraint, pathStore: FilePathStore): Constraint { switch (ctr.type) { case ConstraintType.ExpBool: return { ...ctr, exp: cleanSymExp(ctr.exp, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrExpBool; case ConstraintType.Equal: return { ...ctr, left: cleanSymExp(ctr.left, pathStore), right: cleanSymExp(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrEq; case ConstraintType.NotEqual: return { ...ctr, left: cleanSymExp(ctr.left, pathStore), right: cleanSymExp(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrNeq; case ConstraintType.And: return { ...ctr, left: cleanConstraint(ctr.left, pathStore), right: cleanConstraint(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrAnd; case ConstraintType.Or: return { ...ctr, left: cleanConstraint(ctr.left, pathStore), right: cleanConstraint(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrOr; case ConstraintType.Not: return { ...ctr, constraint: cleanConstraint(ctr.constraint, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrNot; case ConstraintType.LessThan: return { ...ctr, left: cleanSymExp(ctr.left, pathStore), right: cleanSymExp(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrLt; case ConstraintType.LessThanOrEqual: return { ...ctr, left: cleanSymExp(ctr.left, pathStore), right: cleanSymExp(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrLte; case ConstraintType.Forall: return { ...ctr, symbol: cleanSymbol(ctr.symbol, pathStore), range: [cleanSymExp(ctr.range[0], pathStore), cleanSymExp(ctr.range[1], pathStore)], constraint: cleanConstraint(ctr.constraint, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrForall; case ConstraintType.Broadcastable: return { ...ctr, left: cleanSymExp(ctr.left, pathStore), right: cleanSymExp(ctr.right, pathStore), source: cleanSource(ctr.source, pathStore), } as CtrBroad; case ConstraintType.Fail: return { ...ctr, source: cleanSource(ctr.source, pathStore), } as CtrFail; } } export function cleanSymExp(exp: number | ExpNum, pathStore: FilePathStore): number | ExpNum; export function cleanSymExp(exp: boolean | ExpBool, pathStore: FilePathStore): boolean | ExpBool; export function cleanSymExp(exp: string | ExpString, pathStore: FilePathStore): string | ExpString; export function cleanSymExp(exp: ExpShape, pathStore: FilePathStore): ExpShape; export function cleanSymExp(exp: SymExp, pathStore: FilePathStore): SymExp; export function cleanSymExp( exp: number | boolean | string | SymExp, pathStore: FilePathStore ): number | boolean | string | SymExp { if (typeof exp === 'object') { // force cast const retVal: any = { ...exp }; // recursively remove source Object.entries(retVal).forEach(([key, value]) => { if (key === 'source') { retVal.source = cleanSource(retVal.source, pathStore); } if (Array.isArray(value)) { retVal[key] = value.map((v) => cleanSymExp(v, pathStore)); } else if (typeof value === 'object') { retVal[key] = cleanSymExp(value as SymExp, pathStore); } }); return retVal; } return exp; } export function cleanSymbol(symbol: SymInt, pathStore: FilePathStore): SymInt; export function cleanSymbol(symbol: SymVal, pathStore: FilePathStore): SymVal { const source = cleanSource(symbol.source, pathStore); return { ...symbol, source }; } export function cleanSource(source: CodeSource | undefined, pathStore: FilePathStore): CodeRange | undefined { if (!source) return source; if ('fileId' in source) return source; let moduleNode = source; while (moduleNode.nodeType !== ParseNodeType.Module) { moduleNode = moduleNode.parent!; } const fileInfo = getFileInfo(moduleNode)!; const filePath = fileInfo.filePath; const lines = fileInfo.lines; const start = convertOffsetToPosition(source.start, lines); const end = convertOffsetToPosition(source.start + source.length, lines); const fileId = pathStore.addPath(filePath); return { fileId, range: { start, end } }; } } export function formatParseNodeRange(node: ParseNode): string { let moduleNode = node; while (moduleNode.nodeType !== ParseNodeType.Module) { moduleNode = moduleNode.parent!; } const fileInfo = getFileInfo(moduleNode)!; const filePath = fileInfo.filePath; const lines = fileInfo.lines; const start = convertOffsetToPosition(node.start, lines); const end = convertOffsetToPosition(node.start + node.length, lines); const location = `${start.line + 1}:${start.character}`; return `[${location} - ${end.line + 1}:${end.character}] (${filePath}:${location})`; } export function formatCodeSource(node?: CodeSource, pathStore?: FilePathStore): string { if (!node) return 'internal'; // check ParseNode or not if (pathStore) { const range = pathStore.toCodeRange(node); if (!range) return 'internal'; const filePath = pathStore.getPath(range.fileId); const { start, end } = range.range; const location = `${start.line + 1}:${start.character}`; return `[${location} - ${end.line + 1}:${end.character}] (${filePath}:${location})`; } if (!('fileId' in node)) { return formatParseNodeRange(node); } else { const { start, end } = node.range; return `[${start.line + 1}:${start.character} - ${end.line + 1}:${end.character}] (file ${node.fileId})`; } } export async function postJsonRpc(address: string, id: number, method: string, params: any) { const respond = await axios.post( address, { jsonrpc: '2.0', id, method, params, }, { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); return respond.data.result; }
the_stack
import { parse as parseUrl } from 'url'; export * from './schemas'; export * from './types'; import { Route, Handler, NormalizedRoutes, GetRoutesProps, RouteApiError, Redirect, HasField, } from './types'; import { convertCleanUrls, convertRewrites, convertRedirects, convertHeaders, convertTrailingSlash, sourceToRegex, collectHasSegments, } from './superstatic'; export { getCleanUrls } from './superstatic'; export { mergeRoutes } from './merge'; export { appendRoutesToPhase } from './append'; const VALID_HANDLE_VALUES = [ 'filesystem', 'hit', 'miss', 'rewrite', 'error', 'resource', ] as const; const validHandleValues = new Set<string>(VALID_HANDLE_VALUES); export type HandleValue = typeof VALID_HANDLE_VALUES[number]; export function isHandler(route: Route): route is Handler { return typeof (route as Handler).handle !== 'undefined'; } export function isValidHandleValue(handle: string): handle is HandleValue { return validHandleValues.has(handle); } export function normalizeRoutes(inputRoutes: Route[] | null): NormalizedRoutes { if (!inputRoutes || inputRoutes.length === 0) { return { routes: inputRoutes, error: null }; } const routes: Route[] = []; const handling: HandleValue[] = []; const errors: string[] = []; inputRoutes.forEach((r, i) => { const route = { ...r }; routes.push(route); const keys = Object.keys(route); if (isHandler(route)) { const { handle } = route; if (keys.length !== 1) { const unknownProp = keys.find(prop => prop !== 'handle'); errors.push( `Route at index ${i} has unknown property \`${unknownProp}\`.` ); } else if (!isValidHandleValue(handle)) { errors.push( `Route at index ${i} has unknown handle value \`handle: ${handle}\`.` ); } else if (handling.includes(handle)) { errors.push( `Route at index ${i} is a duplicate. Please use one \`handle: ${handle}\` at most.` ); } else { handling.push(handle); } } else if (route.src) { // Route src should always start with a '^' if (!route.src.startsWith('^')) { route.src = `^${route.src}`; } // Route src should always end with a '$' if (!route.src.endsWith('$')) { route.src = `${route.src}$`; } // Route src should strip escaped forward slash, its not special route.src = route.src.replace(/\\\//g, '/'); const regError = checkRegexSyntax('Route', i, route.src); if (regError) { errors.push(regError); } // The last seen handling is the current handler const handleValue = handling[handling.length - 1]; if (handleValue === 'hit') { if (route.dest) { errors.push( `Route at index ${i} cannot define \`dest\` after \`handle: hit\`.` ); } if (route.status) { errors.push( `Route at index ${i} cannot define \`status\` after \`handle: hit\`.` ); } if (!route.continue) { errors.push( `Route at index ${i} must define \`continue: true\` after \`handle: hit\`.` ); } } else if (handleValue === 'miss') { if (route.dest && !route.check) { errors.push( `Route at index ${i} must define \`check: true\` after \`handle: miss\`.` ); } else if (!route.dest && !route.continue) { errors.push( `Route at index ${i} must define \`continue: true\` after \`handle: miss\`.` ); } } } else { errors.push( `Route at index ${i} must define either \`handle\` or \`src\` property.` ); } }); const error = errors.length > 0 ? createError( 'invalid_route', errors, 'https://vercel.link/routes-json', 'Learn More' ) : null; return { routes, error }; } type ErrorMessageType = 'Header' | 'Rewrite' | 'Redirect'; function checkRegexSyntax( type: ErrorMessageType | 'Route', index: number, src: string ): string | null { try { new RegExp(src); } catch (err) { const prop = type === 'Route' ? 'src' : 'source'; return `${type} at index ${index} has invalid \`${prop}\` regular expression "${src}".`; } return null; } function checkPatternSyntax( type: ErrorMessageType, index: number, { source, destination, has, }: { source: string; has?: HasField; destination?: string; } ): { message: string; link: string } | null { let sourceSegments = new Set<string>(); const destinationSegments = new Set<string>(); try { sourceSegments = new Set(sourceToRegex(source).segments); } catch (err) { return { message: `${type} at index ${index} has invalid \`source\` pattern "${source}".`, link: 'https://vercel.link/invalid-route-source-pattern', }; } if (destination) { try { const { hostname, pathname, query } = parseUrl(destination, true); sourceToRegex(hostname || '').segments.forEach(name => destinationSegments.add(name) ); sourceToRegex(pathname || '').segments.forEach(name => destinationSegments.add(name) ); for (const strOrArray of Object.values(query)) { const value = Array.isArray(strOrArray) ? strOrArray[0] : strOrArray; sourceToRegex(value || '').segments.forEach(name => destinationSegments.add(name) ); } } catch (err) { // Since checkPatternSyntax() is a validation helper, we don't want to // replicate all possible URL parsing here so we consume the error. // If this really is an error, we'll throw later in convertRedirects(). } const hasSegments = collectHasSegments(has); for (const segment of destinationSegments) { if (!sourceSegments.has(segment) && !hasSegments.includes(segment)) { return { message: `${type} at index ${index} has segment ":${segment}" in \`destination\` property but not in \`source\` or \`has\` property.`, link: 'https://vercel.link/invalid-route-destination-segment', }; } } } return null; } function checkRedirect(r: Redirect, index: number) { if ( typeof r.permanent !== 'undefined' && typeof r.statusCode !== 'undefined' ) { return `Redirect at index ${index} cannot define both \`permanent\` and \`statusCode\` properties.`; } return null; } function createError( code: string, allErrors: string | string[], link: string, action: string ): RouteApiError | null { const errors = Array.isArray(allErrors) ? allErrors : [allErrors]; const message = errors[0]; const error: RouteApiError = { name: 'RouteApiError', code, message, link, action, errors, }; return error; } function notEmpty<T>(value: T | null | undefined): value is T { return value !== null && value !== undefined; } export function getTransformedRoutes({ nowConfig, }: GetRoutesProps): NormalizedRoutes { const { cleanUrls, rewrites, redirects, headers, trailingSlash } = nowConfig; let { routes = null } = nowConfig; if (routes) { const hasNewProperties = typeof cleanUrls !== 'undefined' || typeof trailingSlash !== 'undefined' || typeof redirects !== 'undefined' || typeof headers !== 'undefined' || typeof rewrites !== 'undefined'; if (hasNewProperties) { const error = createError( 'invalid_mixed_routes', 'If `rewrites`, `redirects`, `headers`, `cleanUrls` or `trailingSlash` are used, then `routes` cannot be present.', 'https://vercel.link/mix-routing-props', 'Learn More' ); return { routes, error }; } return normalizeRoutes(routes); } if (typeof cleanUrls !== 'undefined') { const normalized = normalizeRoutes( convertCleanUrls(cleanUrls, trailingSlash) ); if (normalized.error) { normalized.error.code = 'invalid_clean_urls'; return { routes, error: normalized.error }; } routes = routes || []; routes.push(...(normalized.routes || [])); } if (typeof trailingSlash !== 'undefined') { const normalized = normalizeRoutes(convertTrailingSlash(trailingSlash)); if (normalized.error) { normalized.error.code = 'invalid_trailing_slash'; return { routes, error: normalized.error }; } routes = routes || []; routes.push(...(normalized.routes || [])); } if (typeof redirects !== 'undefined') { const code = 'invalid_redirect'; const regexErrorMessage = redirects .map((r, i) => checkRegexSyntax('Redirect', i, r.source)) .find(notEmpty); if (regexErrorMessage) { return { routes, error: createError( 'invalid_redirect', regexErrorMessage, 'https://vercel.link/invalid-route-source-pattern', 'Learn More' ), }; } const patternError = redirects .map((r, i) => checkPatternSyntax('Redirect', i, r)) .find(notEmpty); if (patternError) { return { routes, error: createError( code, patternError.message, patternError.link, 'Learn More' ), }; } const redirectErrorMessage = redirects.map(checkRedirect).find(notEmpty); if (redirectErrorMessage) { return { routes, error: createError( code, redirectErrorMessage, 'https://vercel.link/redirects-json', 'Learn More' ), }; } const normalized = normalizeRoutes(convertRedirects(redirects)); if (normalized.error) { normalized.error.code = code; return { routes, error: normalized.error }; } routes = routes || []; routes.push(...(normalized.routes || [])); } if (typeof headers !== 'undefined') { const code = 'invalid_header'; const regexErrorMessage = headers .map((r, i) => checkRegexSyntax('Header', i, r.source)) .find(notEmpty); if (regexErrorMessage) { return { routes, error: createError( code, regexErrorMessage, 'https://vercel.link/invalid-route-source-pattern', 'Learn More' ), }; } const patternError = headers .map((r, i) => checkPatternSyntax('Header', i, r)) .find(notEmpty); if (patternError) { return { routes, error: createError( code, patternError.message, patternError.link, 'Learn More' ), }; } const normalized = normalizeRoutes(convertHeaders(headers)); if (normalized.error) { normalized.error.code = code; return { routes, error: normalized.error }; } routes = routes || []; routes.push(...(normalized.routes || [])); } if (typeof rewrites !== 'undefined') { const code = 'invalid_rewrite'; const regexErrorMessage = rewrites .map((r, i) => checkRegexSyntax('Rewrite', i, r.source)) .find(notEmpty); if (regexErrorMessage) { return { routes, error: createError( code, regexErrorMessage, 'https://vercel.link/invalid-route-source-pattern', 'Learn More' ), }; } const patternError = rewrites .map((r, i) => checkPatternSyntax('Rewrite', i, r)) .find(notEmpty); if (patternError) { return { routes, error: createError( code, patternError.message, patternError.link, 'Learn More' ), }; } const normalized = normalizeRoutes(convertRewrites(rewrites)); if (normalized.error) { normalized.error.code = code; return { routes, error: normalized.error }; } routes = routes || []; routes.push({ handle: 'filesystem' }); routes.push(...(normalized.routes || [])); } return { routes, error: null }; }
the_stack
import fetch from 'node-fetch'; import {Analysis, Document, ParsedHtmlDocument, Severity, Warning} from 'polymer-analyzer'; import {filesJsonObjectToMap, PackageScanResultJson, serializePackageScanResult} from './conversion-manifest'; import {ConversionSettings} from './conversion-settings'; import {DocumentConverter} from './document-converter'; import {ScanResult} from './document-scanner'; import {DocumentScanner} from './document-scanner'; import {isImportWithDocument} from './import-with-document'; import {JsExport} from './js-module'; import {lookupDependencyMapping} from './package-manifest'; import {OriginalDocumentUrl} from './urls/types'; import {UrlHandler} from './urls/url-handler'; // These types represent the data surfaced from a package scan. The full // PackageScanResult object contains both a mapping of all files from old->new, // and a mapping of all exports from implicit global namespace references to // new ES6 imports by name. export type PackageScanFiles = Map<OriginalDocumentUrl, ScanResult>; export type PackageScanExports = Map<string, JsExport>; export interface PackageScanResult { files: PackageScanFiles; exports: PackageScanExports; } /** * PackageScanner provides the top-level interface for scanning any single * package. Scanning packages allows us to detect the new ES Module * external interface(s) across a project so that we can properly rewrite and * convert our files. */ export class PackageScanner { private readonly packageName: string; private readonly analysis: Analysis; private readonly urlHandler: UrlHandler; private readonly conversionSettings: ConversionSettings; private readonly topLevelEntrypoints: Set<OriginalDocumentUrl> = new Set(); /** * A set of all external dependencies (by name) actually detected as JS * imported by this package. */ readonly externalDependencies = new Set<string>(); /** * All JS Exports for a single package registered by namespaced identifier, * to map implicit HTML imports to explicit named JS imports. */ private readonly namespacedExports: PackageScanExports = new Map(); /** * All Scan Results for a single package registered by document URL, so that * the conversion process knows how to treat each file. */ private readonly results: PackageScanFiles = new Map(); constructor( packageName: string, analysis: Analysis, urlHandler: UrlHandler, conversionSettings: ConversionSettings, topLevelEntrypoints: Set<OriginalDocumentUrl>) { this.packageName = packageName; this.analysis = analysis; this.urlHandler = urlHandler; this.conversionSettings = conversionSettings; this.topLevelEntrypoints = topLevelEntrypoints; } /** * Scan a package and return the scan result. This method will first try to * fetch a package manifest from npm. Failing that (no manifest exists, npm * cannot be reached, etc.) it will scan the package manually. */ async scanPackage(forceScan = false): Promise<PackageScanResult> { let resultsFromManifest; if (forceScan !== false) { resultsFromManifest = await this.getResultsFromManifest(); } if (resultsFromManifest !== undefined) { this.scanPackageFromManifest(resultsFromManifest); } else { this.scanPackageManually(); } return this.getResults(); } /** * Get a package manifest (a serializable version of the scanner results) for * a package. */ private scanPackageFromManifest(packageScanManifest: PackageScanResult) { for (const [originalUrl, scanResult] of packageScanManifest.files) { this.results.set(originalUrl, scanResult); if (scanResult.type === 'js-module') { for (const expr of scanResult.exportMigrationRecords) { if (!this.namespacedExports.has(expr.oldNamespacedName)) { this.namespacedExports.set( expr.oldNamespacedName, new JsExport(scanResult.convertedUrl, expr.es6ExportName)); } } } } } /** * Scan each document in a package manually. The scan document format (JS * Module or HTML Document) is determined by whether the file is included in * the entry for this package in `conversionSettings.packageEntrypoints` which * is assigned to `this.topLevelEntrypoints`. */ scanPackageManually() { // Scan top-level entrypoints first, to make sure their dependencies are // properly converted to JS modules as well. for (const document of this.getPackageHtmlDocuments()) { if (this.topLevelEntrypoints.has( this.urlHandler.getDocumentUrl(document))) { this.scanDocument(document, 'js-module'); } } // Scan all other documents, to be converted as top-level HTML files. for (const document of this.getPackageHtmlDocuments()) { // If the document was scanned above, don't scan it again. (`scanDocument` // also checks this.) if (this.shouldScanDocument(document)) { this.scanDocument(document, 'html-document'); } } } /** * Fetch a conversion manifest from NPM. If none can be found, return null. */ async getResultsFromManifest(): Promise<PackageScanResult|undefined> { const npmPackageInfo = lookupDependencyMapping(this.packageName); if (!npmPackageInfo) { return undefined; } try { const unpkgResponse = await fetch(`https://unpkg.com/${ npmPackageInfo.npm}@${npmPackageInfo.semver}/manifest.json`); const manifestJson: PackageScanResultJson = await unpkgResponse.json(); const [allFiles, allExports] = filesJsonObjectToMap( this.packageName, npmPackageInfo.npm, manifestJson, this.urlHandler); return { files: allFiles, exports: allExports, }; } catch (err) { return undefined; } } /** * Get all relevant HTML documents from a package that should be scanned, * coverted, or otherwise handled by the modulizer. */ getPackageHtmlDocuments() { return [ ...this.analysis.getFeatures({ // Set externalPackages=true so that this method works on dependencies // packages as well. We filter out files from outside this package in // the method below. externalPackages: true, kind: 'html-document', }) ].filter((d) => { // Filter out any inline documents returned by the analyzer if (d.isInline === true) { return false; } // Filter out any excluded documents const documentUrl = this.urlHandler.getDocumentUrl(d); if (this.conversionSettings.excludes.has(documentUrl)) { return false; } // Filter out any documents external *to this package* const packageName = this.urlHandler.getOriginalPackageNameForUrl(documentUrl); return packageName === this.packageName; }); } /** * Return the results of the package scan. */ getResults(): PackageScanResult { return { files: this.results, exports: this.namespacedExports, }; } /** * Get a package manifest (a serializable version of the scanner results) for * a package. */ getConversionManifest(): PackageScanResultJson { return serializePackageScanResult( this.results, this.namespacedExports, this.urlHandler); } /** * Scan a document and any of its dependency packages. */ private scanDocument( document: Document<ParsedHtmlDocument>, scanAs: 'js-module'|'html-document') { console.assert( document.kinds.has('html-document'), `scanDocument() must be called with an HTML document, but got ${ document.kinds}`); if (!this.shouldScanDocument(document)) { return; } const documentScanner = new DocumentScanner( document, this.packageName, this.urlHandler, this.conversionSettings); let scanResult: ScanResult; try { scanResult = scanAs === 'js-module' ? documentScanner.scanJsModule() : documentScanner.scanTopLevelHtmlDocument(); } catch (e) { console.error(`Error in ${document.url}`, e); return; } this.results.set(scanResult.originalUrl, scanResult); this.scanDependencies(document); if (scanResult.type === 'js-module') { for (const expr of scanResult.exportMigrationRecords) { if (!this.namespacedExports.has(expr.oldNamespacedName)) { this.namespacedExports.set( expr.oldNamespacedName, new JsExport(scanResult.convertedUrl, expr.es6ExportName)); } } } } /** * Check if a document is explicitly excluded or has already been scanned * to decide if it should be skipped. */ private shouldScanDocument(document: Document): boolean { const documentUrl = this.urlHandler.getDocumentUrl(document); return !this.results.has(documentUrl) && !this.conversionSettings.excludes.has(documentUrl); } /** * Scan dependency files of a document. If a file is external to this package, * add that dependency to the externalDependencies set to be scanned * seperately. */ private scanDependencies(document: Document) { const documentUrl = this.urlHandler.getDocumentUrl(document); const packageName = this.urlHandler.getOriginalPackageNameForUrl(documentUrl); for (const htmlImport of DocumentConverter.getAllHtmlImports(document)) { if (!isImportWithDocument(htmlImport)) { console.warn( new Warning({ code: 'import-ignored', message: `Import could not be loaded and will be ignored.`, parsedDocument: document.parsedDocument, severity: Severity.WARNING, sourceRange: htmlImport.sourceRange!, }).toString()); continue; } const importDocumentUrl = this.urlHandler.getDocumentUrl(htmlImport); const importPackageName = this.urlHandler.getOriginalPackageNameForUrl(importDocumentUrl); if (importPackageName === packageName) { this.scanDocument( htmlImport.document as Document<ParsedHtmlDocument>, 'js-module'); } else { this.externalDependencies.add(importPackageName); } } } }
the_stack
import { FieldDefinitionNode, GraphQLBoolean, GraphQLFloat, GraphQLID, GraphQLInt, GraphQLString } from 'graphql'; import memorize from 'memorize-decorator'; import { IDENTITY_ANALYZER, NORM_CI_ANALYZER } from '../../database/arangodb/schema-migration/arango-search-helpers'; import { ACCESS_GROUP_FIELD, CALC_MUTATIONS_OPERATORS, COLLECT_AGGREGATE_ARG, COLLECT_DIRECTIVE, FLEX_SEARCH_CASE_SENSITIVE_ARGUMENT, FLEX_SEARCH_INCLUDED_IN_SEARCH_ARGUMENT, PARENT_DIRECTIVE, REFERENCE_DIRECTIVE, RELATION_DIRECTIVE, ROOT_DIRECTIVE } from '../../schema/constants'; import { GraphQLDateTime } from '../../schema/scalars/date-time'; import { GraphQLInt53 } from '../../schema/scalars/int53'; import { GraphQLLocalDate } from '../../schema/scalars/local-date'; import { GraphQLLocalTime } from '../../schema/scalars/local-time'; import { GraphQLOffsetDateTime } from '../../schema/scalars/offset-date-time'; import { AggregationOperator, CalcMutationsOperator, FieldConfig, FlexSearchLanguage, RelationDeleteAction, TypeKind } from '../config'; import { collectEmbeddingEntityTypes, collectEmbeddingRootEntityTypes } from '../utils/emedding-entity-types'; import { findRecursiveCascadePath } from '../utils/recursive-cascade'; import { ValidationMessage } from '../validation'; import { ModelComponent, ValidationContext } from '../validation/validation-context'; import { numberTypeNames } from './built-in-types'; import { CollectPath } from './collect-path'; import { FieldLocalization } from './i18n'; import { Model } from './model'; import { PermissionProfile } from './permission-profile'; import { Relation, RelationSide } from './relation'; import { RolesSpecifier } from './roles-specifier'; import { ScalarType } from './scalar-type'; import { InvalidType, ObjectType, Type } from './type'; import { ValueObjectType } from './value-object-type'; export interface SystemFieldConfig extends FieldConfig { readonly isSystemField?: boolean; readonly isNonNull?: boolean; } export class Field implements ModelComponent { readonly model: Model; readonly name: string; description: string | undefined; readonly deprecationReason: string | undefined; readonly astNode: FieldDefinitionNode | undefined; readonly isList: boolean; readonly isReference: boolean; readonly isRelation: boolean; readonly isCollectField: boolean; readonly collectPath: CollectPath | undefined; readonly aggregationOperator: AggregationOperator | undefined; readonly defaultValue?: any; readonly calcMutationOperators: ReadonlySet<CalcMutationsOperator>; readonly isParentField: boolean; readonly isRootField: boolean; readonly roles: RolesSpecifier | undefined; private _type: Type | undefined; /** * Indicates if this is an inherent field of the declaring type that will be maintained by the system and thus can * only be queried */ readonly isSystemField: boolean; constructor(private readonly input: SystemFieldConfig, public readonly declaringType: ObjectType) { this.model = declaringType.model; this.name = input.name; this.description = input.description; this.deprecationReason = input.deprecationReason; this.astNode = input.astNode; this.defaultValue = input.defaultValue; this.isReference = input.isReference || false; this.isRelation = input.isRelation || false; this.isParentField = input.isParentField || false; this.isRootField = input.isRootField || false; this.isCollectField = !!input.collect; if (input.collect) { this.collectPath = new CollectPath(input.collect, this.declaringType); if (input.collect) { this.aggregationOperator = input.collect.aggregationOperator; } } this.isList = input.isList || false; this.calcMutationOperators = new Set(input.calcMutationOperators || []); this.roles = input.permissions && input.permissions.roles ? new RolesSpecifier(input.permissions.roles) : undefined; this.isSystemField = input.isSystemField || false; } /** * Indicates if this field can never be set manually (independent of permissions) */ get isReadOnly(): boolean { return this.isSystemField; } get isDeprecated(): boolean { return !!this.deprecationReason; } /** * Specifies whether this field (or items within the list if this is a list) is never null */ get isNonNull(): boolean { // list items and entity extensions are never null if (this.input.isNonNull || this.type.isEntityExtensionType || this.isList) { return true; } if (this.aggregationOperator && !canAggregationBeNull(this.aggregationOperator)) { return true; } // regular fields are nullable return false; } public get type(): Type { // cache this because getType is a lookup by string if (this._type) { return this._type; } const type = this.model.getType(this.input.typeName); if (type) { this._type = type; return type; } return new InvalidType(this.input.typeName, this.model); } public get hasValidType(): boolean { return !!this.model.getType(this.input.typeName); } public get hasDefaultValue(): boolean { return this.defaultValue !== undefined; } public get permissionProfile(): PermissionProfile | undefined { if (!this.input.permissions || this.input.permissions.permissionProfileName == undefined) { return undefined; } return this.declaringType.namespace.getPermissionProfile(this.input.permissions.permissionProfileName); } public get inverseOf(): Field | undefined { if (this.input.inverseOfFieldName == undefined) { return undefined; } const type = this.type; if (!type.isObjectType) { return undefined; } return type.getField(this.input.inverseOfFieldName); } public get inverseField(): Field | undefined { return this.type.isObjectType ? this.type.fields.find(field => field.inverseOf === this) : undefined; } public get relation(): Relation | undefined { const relationSide = this.relationSide; if (!relationSide) { return undefined; } return relationSide.relation; } @memorize() public get relationSide(): RelationSide | undefined { if (!this.isRelation || !this.declaringType.isRootEntityType || !this.type.isRootEntityType) { return undefined; } if (this.inverseOf) { // this is the to side return new Relation({ fromType: this.type, fromField: this.inverseOf, toType: this.declaringType, toField: this }).toSide; } else { // this is the from side return new Relation({ fromType: this.declaringType, fromField: this, toType: this.type, toField: this.inverseField }).fromSide; } } public getRelationSideOrThrow(): RelationSide { if (this.type.kind != TypeKind.ROOT_ENTITY) { throw new Error( `Expected the type of field "${this.declaringType.name}.${this.name}" to be a root entity, but "${this.type.name}" is a ${this.type.kind}` ); } if (this.declaringType.kind != TypeKind.ROOT_ENTITY) { throw new Error( `Expected "${this.declaringType.name}" to be a root entity, but is ${this.declaringType.kind}` ); } const relationSide = this.relationSide; if (!relationSide) { throw new Error(`Expected "${this.declaringType.name}.${this}" to be a relation`); } return relationSide; } public getRelationOrThrow(): Relation { return this.getRelationSideOrThrow().relation; } get relationDeleteAction(): RelationDeleteAction { return this.input.relationDeleteAction ?? RelationDeleteAction.REMOVE_EDGES; } /** * The field that holds the key if this is a reference * * If this is a reference without an explicit key field, returns this (reference) field */ @memorize() get referenceKeyField(): Field | undefined { if (!this.isReference) { return undefined; } if (!this.input.referenceKeyField) { return this; } return this.declaringType.getField(this.input.referenceKeyField); } getReferenceKeyFieldOrThrow(): Field { const keyField = this.referenceKeyField; if (!keyField) { throw new Error(`Expected "${this.declaringType.name}.${this.name}" to be a reference but it is not`); } return keyField; } /** * A reference field within the same type that uses this field as its key field */ @memorize() get referenceField(): Field | undefined { return this.declaringType.fields.filter(f => f.referenceKeyField === this)[0]; } public getLocalization(resolutionOrder: ReadonlyArray<string>): FieldLocalization { return this.model.i18n.getFieldLocalization(this, resolutionOrder); } validate(context: ValidationContext) { this.validateName(context); this.validateType(context); this.validatePermissions(context); this.validateRootEntityType(context); this.validateEntityExtensionType(context); this.validateChildEntityType(context); this.validateRelation(context); this.validateReference(context); this.validateCollect(context); this.validateDefaultValue(context); this.validateCalcMutations(context); this.validateParentField(context); this.validateRootField(context); this.validateFlexSearch(context); } private validateName(context: ValidationContext) { if (!this.name) { context.addMessage(ValidationMessage.error(`Field name is empty.`, this.astNode)); return; } // Leading underscores are reserved for internal names, like ArangoDB's _key field if (this.name.startsWith('_')) { context.addMessage(ValidationMessage.error(`Field names cannot start with an underscore.`, this.astNode)); return; } // some naming convention rules if (this.name.includes('_')) { context.addMessage(ValidationMessage.warn(`Field names should not include underscores.`, this.astNode)); return; } if (!this.name.match(/^[a-z]/)) { context.addMessage( ValidationMessage.warn(`Field names should start with a lowercase character.`, this.astNode) ); } } private validateType(context: ValidationContext) { if (!this.model.getType(this.input.typeName)) { context.addMessage( ValidationMessage.error( `Type "${this.input.typeName}" not found.`, this.input.typeNameAST || this.astNode ) ); } } private validateRootEntityType(context: ValidationContext) { // this does not fit anywhere else properly if (this.isReference && this.isRelation) { context.addMessage(ValidationMessage.error(`@reference and @relation cannot be combined.`, this.astNode)); } if (this.type.kind !== TypeKind.ROOT_ENTITY) { return; } // root entities are not embeddable if (!this.isRelation && !this.isReference && !this.isCollectField && !this.isParentField && !this.isRootField) { const suggestions = [REFERENCE_DIRECTIVE]; if (this.declaringType.kind === TypeKind.ROOT_ENTITY) { suggestions.push(RELATION_DIRECTIVE); } if (this.declaringType.kind === TypeKind.CHILD_ENTITY) { if (!this.declaringType.fields.some(f => f.isParentField)) { suggestions.push(PARENT_DIRECTIVE); } if (!this.declaringType.fields.some(f => f.isRootField)) { suggestions.push(PARENT_DIRECTIVE); } } const names = suggestions.map(n => '@' + n); const list = names.length === 1 ? names : names.slice(0, -1).join(', ') + ' or ' + names[names.length - 1]; context.addMessage( ValidationMessage.error( `Type "${this.type.name}" is a root entity type and cannot be embedded. Consider adding ${list}.`, this.astNode ) ); } } private validateRelation(context: ValidationContext) { if (!this.isRelation) { return; } if (!this.declaringType.isRootEntityType) { context.addMessage( ValidationMessage.error( `Relations can only be defined on root entity types. Consider using @reference instead.`, this.astNode ) ); } // do target type validations only if it resolved correctly if (!this.hasValidType) { return; } if (!this.type.isRootEntityType) { context.addMessage( ValidationMessage.error( `Type "${this.type.name}" cannot be used with @relation because it is not a root entity type.`, this.astNode ) ); return; } if (this.input.inverseOfFieldName != undefined) { const inverseOf = this.type.getField(this.input.inverseOfFieldName); const inverseFieldDesc = `Field "${this.type.name}.${this.input.inverseOfFieldName}" used as inverse field of "${this.declaringType.name}.${this.name}"`; if (!inverseOf) { context.addMessage( ValidationMessage.error( `Field "${this.input.inverseOfFieldName}" does not exist on type "${this.type.name}".`, this.input.inverseOfASTNode || this.astNode ) ); } else if (inverseOf.type && inverseOf.type !== this.declaringType) { context.addMessage( ValidationMessage.error( `${inverseFieldDesc} has named type "${inverseOf.type.name}" but should be of type "${this.declaringType.name}".`, this.input.inverseOfASTNode || this.astNode ) ); } else if (!inverseOf.isRelation) { context.addMessage( ValidationMessage.error( `${inverseFieldDesc} does not have the @relation directive.`, this.input.inverseOfASTNode || this.astNode ) ); } else if (inverseOf.inverseOf != undefined) { context.addMessage( ValidationMessage.error( `${inverseFieldDesc} should not declare inverseOf itself.`, this.input.inverseOfASTNode || this.astNode ) ); } if (this.input.relationDeleteAction) { context.addMessage( ValidationMessage.error( `"onDelete" cannot be specified on inverse relations.`, this.input.relationDeleteActionASTNode || this.astNode ) ); } } else { // look for @relation(inverseOf: "thisField") in the target type const inverseFields = this.type.fields.filter(field => field.inverseOf === this); if (inverseFields.length === 0) { // no @relation(inverseOf: "thisField") - should be ok, but is suspicious if there is a matching @relation back to this type // (look for inverseOfFieldName instead of inverseOf so that we don't emit this warning if the inverseOf config is invalid) const matchingRelation = this.type.fields.find( field => field !== this && field.isRelation && field.type === this.declaringType && field.input.inverseOfFieldName == undefined ); if (matchingRelation) { context.addMessage( ValidationMessage.warn( `This field and "${matchingRelation.declaringType.name}.${matchingRelation.name}" define separate relations. Consider using the "inverseOf" argument to add a backlink to an existing relation.`, this.astNode ) ); } } else if (inverseFields.length > 1) { const names = inverseFields.map(f => `"${this.type.name}.${f.name}"`).join(', '); // found multiple inverse fields - this is an error // check this here and not in the inverse fields so we don't report stuff twice for (const inverseField of inverseFields) { context.addMessage( ValidationMessage.error( `Multiple fields (${names}) declare inverseOf to "${this.declaringType.name}.${this.name}".`, inverseField.astNode ) ); } return; // no more errors that depend on the inverse fields } const inverseField: Field | undefined = inverseFields[0]; if (this.relationDeleteAction === RelationDeleteAction.CASCADE) { // recursive CASCADE is not supported. It would be pretty complicated to implement in all but the // simplest cases (would result in pretty complicated traversal statements, or we would need to do // a dynamic number of statements by resolving the relations imperatively). // For simplicity, we also forbid it for simpler recursion (like a single self-recursive field) // first, simple self-recursion check to not confuse with a complicated error message if (this.type === this.declaringType) { context.addMessage( ValidationMessage.error( `"CASCADE" cannot be used on recursive fields. Use "RESTRICT" instead.`, this.input.relationDeleteActionASTNode ) ); return; } else { const recursivePath = findRecursiveCascadePath(this); if (recursivePath) { context.addMessage( ValidationMessage.error( `The path "${recursivePath .map(f => f.name) .join( '.' )}" is a loop with "onDelete: CASCADE" on each relation, which is not supported. Break the loop by replacing "CASCADE" with "RESTRICT" on any of these relations.`, this.input.relationDeleteActionASTNode ) ); return; } } // cascading delete is only allowed if this is a 1-to-* relation. If we would support it for n-to-* // relations, we would need to decide between two behaviors: // - delete the related object as soon as one of the referencing object is deleted -> this would cause // unexpected data loss because deleting one object would clear the children of a *sibling* object. That // would be very confusing. // - delete the related object once *all* of the referencing objects are deleted. This would avoid th // data loss mentioned above, but it would be pretty complicated both to implement and to understand. // better use RESTRICT and do it manually. // this also means that relations without inverse relations can't be used with CASCADE. That's a good thing // because the dependency that could cause an object to be deleted should be explicit. if (!inverseField) { context.addMessage( ValidationMessage.error( `"CASCADE" is only supported on 1-to-n and 1-to-1 relations. Use "RESTRICT" instead or change this to a 1-to-${ this.isList ? 'n' : '1' } relation by adding a field with the @relation(inverseOf: "${ this.name }") directive to the target type "${this.type.name}".`, this.input.relationDeleteActionASTNode ) ); return; } else if (inverseField.isList) { context.addMessage( ValidationMessage.error( `"CASCADE" is only supported on 1-to-n and 1-to-1 relations. Use "RESTRICT" instead or change this to a 1-to-${ this.isList ? 'n' : '1' } relation by changing the type of "${this.type.name}.${inverseField.name}" to "${ inverseField.type.name }".`, this.input.relationDeleteActionASTNode ) ); } } } } private validateReference(context: ValidationContext) { if (!this.isReference) { return; } // do target type validations only if it resolved correctly if (!this.hasValidType) { return; } if (this.type.kind !== TypeKind.ROOT_ENTITY) { context.addMessage( ValidationMessage.error( `"${this.type.name}" cannot be used as @reference type because is not a root entity type.`, this.astNode ) ); return; } if (this.isList) { context.addMessage( ValidationMessage.error( `@reference is not supported with list types. Consider wrapping the reference in a child entity or value object type.`, this.astNode ) ); } if (!this.type.keyField) { context.addMessage( ValidationMessage.error( `"${this.type.name}" cannot be used as @reference type because it does not have a field annotated with @key.`, this.astNode ) ); } this.validateReferenceKeyField(context); } private validateCollect(context: ValidationContext) { if (!this.input.collect) { return; } if (this.isRelation) { context.addMessage( ValidationMessage.error( `@${COLLECT_DIRECTIVE} and @${RELATION_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (this.isReference) { context.addMessage( ValidationMessage.error( `@${COLLECT_DIRECTIVE} and @${REFERENCE_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (!this.collectPath) { context.addMessage(ValidationMessage.error(`The path cannot be empty.`, this.input.collect.pathASTNode)); return; } if (!this.collectPath.validate(context)) { // path validation failed already return; } const resultingType = this.collectPath.resultingType; if (!this.collectPath.resultIsList) { context.addMessage( ValidationMessage.error(`The path does not result in a list.`, this.input.collect.pathASTNode) ); return; } if (this.aggregationOperator) { const typeInfo = getAggregatorTypeInfo(this.aggregationOperator); if (typeInfo.lastSegmentShouldBeList) { const lastSegment = this.collectPath.segments[this.collectPath.segments.length - 1]; if (lastSegment && !lastSegment.isListSegment) { // we checked for resultIsList before, so there needs to be a list segment somewhere - so we can suggest to remove a segment if (lastSegment.field.type.name === GraphQLBoolean.name) { // for boolean fields, redirect to the boolean variants context.addMessage( ValidationMessage.error( `Aggregation operator "${ this.aggregationOperator }" is only allowed if the last path segment is a list field. "${ lastSegment.field.name }" is of type "Boolean", so you may want to use "${this.aggregationOperator + '_TRUE'}".`, this.input.collect.aggregationOperatorASTNode ) ); } else if (lastSegment.isNullableSegment) { // show extended hint - user might have wanted to use e.g. "COUNT_NOT_NULL". context.addMessage( ValidationMessage.error( `Aggregation operator "${ this.aggregationOperator }" is only allowed if the last path segment is a list field. If you want to exclude objects where "${ lastSegment.field.name }" is null, use "${this.aggregationOperator + '_NOT_NULL'}; otherwise, remove "${ lastSegment.field.name }" from the path.`, this.input.collect.aggregationOperatorASTNode ) ); } else { context.addMessage( ValidationMessage.error( `Aggregation operator "${this.aggregationOperator}" is only allowed if the last path segment is a list field. Please remove "${lastSegment.field.name}" from the path.`, this.input.collect.aggregationOperatorASTNode ) ); } return; } // even for boolean lists, we show a warning because boolean lists are sparingly used and e.g. using EVERY might be misleading there if (lastSegment && lastSegment.field.type.name === GraphQLBoolean.name) { context.addMessage( ValidationMessage.warn( `Aggregation operator "${this.aggregationOperator}" only checks the number of items. "${ lastSegment.field.name }" is of type "Boolean", so you may want to use the operator "${this.aggregationOperator + '_TRUE'}" instead which specifically checks for boolean "true".`, this.input.collect.aggregationOperatorASTNode ) ); } } if (typeInfo.shouldBeNullable && !this.collectPath.resultIsNullable) { let addendum = ''; const operatorName = this.aggregationOperator.toString(); if (operatorName.endsWith('_NOT_NULL')) { addendum = ` Consider using "${operatorName.substr(0, operatorName.length - '_NOT_NULL'.length)}`; } context.addMessage( ValidationMessage.error( `Aggregation operator "${this.aggregationOperator}" is only supported on nullable types, but the path does not result in a nullable type.` + addendum, this.input.collect.aggregationOperatorASTNode ) ); return; } if (resultingType && typeInfo.typeNames && !typeInfo.typeNames.includes(resultingType.name)) { context.addMessage( ValidationMessage.error( `Aggregation operator "${this.aggregationOperator}" is not supported on type "${ resultingType.name }" (supported types: ${typeInfo.typeNames.map(t => `"${t}"`).join(', ')}).`, this.input.collect.aggregationOperatorASTNode ) ); return; } if (typeInfo.usesDistinct && resultingType) { if (!isDistinctAggregationSupported(resultingType)) { let typeHint; if (resultingType.isValueObjectType) { const offendingFields = getOffendingValueObjectFieldsForDistinctAggregation(resultingType); const offendingFieldNames = offendingFields.map(f => `"${f.name}"`).join(', '); typeHint = `value object type "${resultingType.name}" because its field${ offendingFields.length !== 1 ? 's' : '' } ${offendingFieldNames} has a type that does not support this operator`; } else if (resultingType.isEntityExtensionType) { typeHint = `entity extension types. You can instead collect the parent objects by removing the last path segment`; } else { typeHint = `type "${ resultingType.name }" (supported scalar types: ${scalarTypesThatSupportDistinctAggregation .map(t => `"${t}"`) .join(', ')})`; } context.addMessage( ValidationMessage.error( `Aggregation operator "${this.aggregationOperator}" is not supported on ${typeHint}.`, this.input.collect.aggregationOperatorASTNode ) ); return; } // the operator is useless if it's an entity type and it can neither be null nor have duplicates if ( (resultingType.isRootEntityType || resultingType.isChildEntityType) && !this.collectPath.resultIsNullable && !this.collectPath.resultMayContainDuplicateEntities ) { const suggestedOperator = getAggregatorWithoutDistinct(this.aggregationOperator); if (this.aggregationOperator === AggregationOperator.DISTINCT) { // this one can just be removed context.addMessage( ValidationMessage.error( `Aggregation operator "${this.aggregationOperator}" is not needed because the collect result can neither contain duplicate entities nor null values. Please remove the "${COLLECT_AGGREGATE_ARG}" argument".`, this.input.collect.aggregationOperatorASTNode ) ); return; } else if (suggestedOperator) { // the count operator should be replaced by the non-distinct count context.addMessage( ValidationMessage.error( `Please use the operator "${suggestedOperator}" because the collect result can neither contain duplicate entities nor null values.".`, this.input.collect.aggregationOperatorASTNode ) ); return; } } } let expectedResultingTypeName: string | undefined; if (typeof typeInfo.resultTypeName === 'string') { expectedResultingTypeName = typeInfo.resultTypeName; } else if (typeof typeInfo.resultTypeName === 'function' && resultingType) { expectedResultingTypeName = typeInfo.resultTypeName(resultingType.name); } else { expectedResultingTypeName = resultingType && resultingType.name; } // undefined means that the aggregation results in the item's type if (expectedResultingTypeName && this.type.name !== expectedResultingTypeName) { context.addMessage( ValidationMessage.error( `The aggregation results in type "${expectedResultingTypeName}", but this field is declared with type "${this.type.name}".`, this.astNode && this.astNode.type ) ); return; } if (!typeInfo.resultIsList && this.isList) { context.addMessage( ValidationMessage.error( `This aggregation field should not be declared as a list.`, this.astNode && this.astNode.type ) ); return; } if (typeInfo.resultIsList && !this.isList) { context.addMessage( ValidationMessage.error( `This aggregation field should be declared as a list because "${this.aggregationOperator}" results in a list.`, this.astNode && this.astNode.type ) ); return; } } else { // not an aggregation if (resultingType) { if (resultingType.isEntityExtensionType) { // treat these separate from the list below because we can't even aggregate entity extensions (they're not nullable and not lists) context.addMessage( ValidationMessage.error( `The collect path results in entity extension type "${resultingType.name}", but entity extensions cannot be collected. You can either collect the parent entity by removing the last path segment, or collect values within the entity extension by adding a path segment.`, this.input.collect.pathASTNode ) ); return; } if (resultingType.isEnumType || resultingType.isScalarType || resultingType.isValueObjectType) { // this is a modeling design choice - it does not really make sense to "collect" non-entities without a link to the parent and without aggregating them const typeKind = resultingType.isEnumType ? 'enum' : resultingType.isValueObjectType ? 'value object' : 'scalar'; const suggestion = isDistinctAggregationSupported(resultingType) ? ` You may want to use the "${AggregationOperator.DISTINCT}" aggregation.` : `You can either collect the parent entity by removing the last path segment, or add the "aggregate" argument to aggregate the values.`; context.addMessage( ValidationMessage.error( `The collect path results in ${typeKind} type "${resultingType.name}", but ${typeKind}s cannot be collected without aggregating them. ` + suggestion, this.input.collect.pathASTNode ) ); return; } if (this.collectPath.resultMayContainDuplicateEntities) { const minimumAmbiguousPathEndIndex = this.collectPath.segments.findIndex( s => s.resultMayContainDuplicateEntities ); const firstAmgiguousSegment = this.collectPath.segments[minimumAmbiguousPathEndIndex]; const minimumAmbiguousPathPrefix = minimumAmbiguousPathEndIndex >= 0 ? this.collectPath.path .split('.') .slice(0, minimumAmbiguousPathEndIndex + 1) .join('.') : ''; const firstAmbiguousSegment = this.collectPath.segments.find( s => s.resultMayContainDuplicateEntities ); const path = minimumAmbiguousPathPrefix && minimumAmbiguousPathPrefix !== this.collectPath.path ? `path prefix "${minimumAmbiguousPathPrefix}"` : 'path'; const entityType = firstAmgiguousSegment ? `${firstAmgiguousSegment.field.type.name} entities` : `entities`; let reason = ''; if (firstAmbiguousSegment && firstAmbiguousSegment.kind === 'relation') { if (firstAmbiguousSegment.relationSide.targetField) { reason = ` (because "${firstAmbiguousSegment.relationSide.targetType.name}.${firstAmbiguousSegment.relationSide.targetField.name}", which is the inverse relation field to "${firstAmgiguousSegment.field.declaringType.name}.${firstAmbiguousSegment.field.name}", is declared as a list)`; } else { reason = ` (because the relation target type "${firstAmbiguousSegment.relationSide.targetType.name}" does not declare a inverse relation field to "${firstAmgiguousSegment.field.declaringType.name}.${firstAmbiguousSegment.field.name}")`; } } context.addMessage( ValidationMessage.error( `The ${path} can produce duplicate ${entityType}${reason}. Please set argument "${COLLECT_AGGREGATE_ARG}" to "${AggregationOperator.DISTINCT}" to filter out duplicates and null items if you don't want any other aggregation.`, this.input.collect.pathASTNode ) ); return; } if (this.collectPath.resultIsNullable) { let fieldHint = ''; const lastNullableSegment = [...this.collectPath.segments].reverse().find(s => s.isNullableSegment); if (lastNullableSegment) { fieldHint = ` because "${lastNullableSegment.field.declaringType.name}.${lastNullableSegment.field.name}" can be null`; } context.addMessage( ValidationMessage.error( `The collect path can produce items that are null${fieldHint}. Please set argument "${COLLECT_AGGREGATE_ARG}" to "${AggregationOperator.DISTINCT}" to filter out null items if you don't want any other aggregation.`, this.input.collect.pathASTNode ) ); return; } if (resultingType !== this.type) { context.addMessage( ValidationMessage.error( `The collect path results in type "${resultingType.name}", but this field is declared with type "${this.type.name}".`, this.astNode && this.astNode.type ) ); return; } } if (!this.isList) { context.addMessage( ValidationMessage.error( `This collect field should be a declared as a list.`, this.astNode && this.astNode.type ) ); return; } } } private validateReferenceKeyField(context: ValidationContext) { if (!this.input.referenceKeyField) { return; } const keyField = this.declaringType.getField(this.input.referenceKeyField); if (!keyField) { context.addMessage( ValidationMessage.error( `Field "${this.declaringType.name}.${this.input.referenceKeyField}" not found.`, this.input.referenceKeyFieldASTNode ) ); return; } if (keyField.isSystemField) { context.addMessage( ValidationMessage.error( `"${this.declaringType.name}.${this.input.referenceKeyField}" is a system field and cannot be used as keyField of a @reference.`, this.input.referenceKeyFieldASTNode ) ); return; } // the following can only be validated if the target type is valid if (!this.type.isRootEntityType || !this.type.keyField) { return; } const targetKeyField = this.type.keyField; if (targetKeyField.type !== keyField.type) { context.addMessage( ValidationMessage.error( `The type of the keyField "${this.declaringType.name}.${this.input.referenceKeyField}" ("${keyField.type.name}") must be the same as the type of the @key-annotated field "${this.type.name}.${targetKeyField.name}" ("${targetKeyField.type.name}")`, this.input.referenceKeyFieldASTNode ) ); return; } // we leave type validation (scalar etc.) to the @key annotation // there can only be one reference for each key field // each reference just reports an error on itself so that all fields are highlighted if (this.declaringType.fields.some(f => f !== this && f.referenceKeyField === keyField)) { context.addMessage( ValidationMessage.error( `There are multiple references declared for keyField "${this.input.referenceKeyField}".`, this.input.referenceKeyFieldASTNode ) ); } } private validateEntityExtensionType(context: ValidationContext) { if (this.type.kind !== TypeKind.ENTITY_EXTENSION) { return; } if (this.declaringType.kind === TypeKind.VALUE_OBJECT) { context.addMessage( ValidationMessage.error( `Type "${this.type.name}" is an entity extension type and cannot be used within value object types. Change "${this.declaringType.name}" to an entity extension type or use a value object type for "${this.name}".`, this.astNode ) ); return; } if (this.isList && !this.isCollectField) { // don't print this error if it's used with @collect - it will fail due to @collect, and the message here would not be helpful. context.addMessage( ValidationMessage.error( `Type "${this.type.name}" is an entity extension type and cannot be used in a list. Change the field type to "${this.type.name}" (without brackets), or use a child entity or value object type instead.`, this.astNode ) ); } } private validateChildEntityType(context: ValidationContext) { if (this.type.kind !== TypeKind.CHILD_ENTITY) { return; } if (this.declaringType.kind === TypeKind.VALUE_OBJECT) { context.addMessage( ValidationMessage.error( `Type "${this.type.name}" is a child entity type and cannot be used within value object types. Change "${this.declaringType.name}" to an entity extension type or use a value object type for "${this.name}".`, this.astNode ) ); return; } if (!this.isList && !this.isParentField) { context.addMessage( ValidationMessage.error( `Type "${this.type.name}" is a child entity type and can only be used in a list. Change the field type to "[${this.type.name}]", or use an entity extension or value object type instead.`, this.astNode ) ); } } private validatePermissions(context: ValidationContext) { const permissions = this.input.permissions || {}; if (this.isCollectField && (permissions.permissionProfileName || permissions.roles)) { context.addMessage( ValidationMessage.error( `Permissions to @traversal fields cannot be restricted explicitly (permissions of traversed fields and types are applied automatically).`, this.astNode ) ); return; } if (permissions.permissionProfileName != undefined && permissions.roles != undefined) { const message = `Permission profile and explicit role specifiers cannot be combined.`; context.addMessage( ValidationMessage.error(message, permissions.permissionProfileNameAstNode || this.input.astNode) ); context.addMessage(ValidationMessage.error(message, permissions.roles.astNode || this.input.astNode)); } if ( permissions.permissionProfileName != undefined && !this.declaringType.namespace.getPermissionProfile(permissions.permissionProfileName) ) { context.addMessage( ValidationMessage.error( `Permission profile "${permissions.permissionProfileName}" not found.`, permissions.permissionProfileNameAstNode || this.input.astNode ) ); } if (this.roles) { this.roles.validate(context); } } private validateDefaultValue(context: ValidationContext) { if (this.input.defaultValue === undefined) { return; } if (this.isRelation) { context.addMessage( ValidationMessage.error( `Default values are not supported on relations.`, this.input.defaultValueASTNode || this.astNode ) ); return; } if (this.isCollectField) { context.addMessage( ValidationMessage.error( `Default values are not supported on collect fields.`, this.input.defaultValueASTNode || this.astNode ) ); return; } if (this.isParentField) { context.addMessage( ValidationMessage.error( `Default values are not supported on parent fields.`, this.input.defaultValueASTNode || this.astNode ) ); return; } if (this.isRootField) { context.addMessage( ValidationMessage.error( `Default values are not supported on root fields.`, this.input.defaultValueASTNode || this.astNode ) ); return; } if (this.isReference) { context.addMessage( ValidationMessage.error( `Default values are not supported on reference fields.`, this.input.defaultValueASTNode || this.astNode ) ); return; } context.addMessage( ValidationMessage.info( `Take care, there are no type checks for default values yet.`, this.input.defaultValueASTNode || this.astNode ) ); } private validateCalcMutations(context: ValidationContext) { if (!this.calcMutationOperators.size) { return; } if (this.isList) { context.addMessage( ValidationMessage.error(`Calc mutations are not supported on list fields.`, this.astNode) ); return; } const supportedOperators = CALC_MUTATIONS_OPERATORS.filter(op => op.supportedTypes.includes(this.type.name)); const supportedOperatorsDesc = supportedOperators.map(op => '"' + op.name + '"').join(', '); if (this.calcMutationOperators.size > 0 && !supportedOperators.length) { context.addMessage( ValidationMessage.error( `Type "${this.type.name}" does not support any calc mutation operators.`, this.astNode ) ); return; } for (const operator of this.calcMutationOperators) { const desc = CALC_MUTATIONS_OPERATORS.find(op => op.name == operator); if (!desc) { // this is caught in the graphql-rules validator continue; } if (!desc.supportedTypes.includes(this.type.name)) { context.addMessage( ValidationMessage.error( `Calc mutation operator "${operator}" is not supported on type "${this.type.name}" (supported operators: ${supportedOperatorsDesc}).`, this.astNode ) ); } } } private validateParentField(context: ValidationContext) { if (!this.isParentField) { return; } if (this.declaringType.kind !== 'CHILD_ENTITY') { context.addMessage( ValidationMessage.error( `@${PARENT_DIRECTIVE} can only be used on fields of child entity types.`, this.input.parentDirectiveNode ) ); return; } if (this.isReference) { context.addMessage( ValidationMessage.error( `@${PARENT_DIRECTIVE} and @${REFERENCE_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (this.isCollectField) { context.addMessage( ValidationMessage.error( `@${PARENT_DIRECTIVE} and @${COLLECT_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (this.isList) { context.addMessage( ValidationMessage.error(`A parent field cannot be a list.`, this.input.parentDirectiveNode) ); return; } if (this.declaringType.fields.some(f => f !== this && f.isParentField)) { context.addMessage( ValidationMessage.error(`There can only be one parent field per type.`, this.input.astNode) ); return; } const { embeddingEntityTypes, otherEmbeddingTypes } = collectEmbeddingEntityTypes(this.declaringType); if (!embeddingEntityTypes.size) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is not used by any entity type and therefore cannot have a parent field.`, this.input.parentDirectiveNode ) ); return; } if (embeddingEntityTypes.has(this.declaringType)) { let suggestion = ''; // maybe @parent can just be swapped out for @root? if (this.type.isRootEntityType && !this.declaringType.fields.some(f => f.isRootField)) { const { embeddingRootEntityTypes } = collectEmbeddingRootEntityTypes(this.declaringType); if (embeddingRootEntityTypes.size === 1 && Array.from(embeddingRootEntityTypes)[0] === this.type) { suggestion = ' Use the @root directive instead.'; } } // parent on recursive child entities just does not work because they always have two parents - make this clear context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is a recursive child entity type and therefore cannot have a parent field.${suggestion}`, this.input.parentDirectiveNode ) ); return; } if (embeddingEntityTypes.size > 1) { // a little nicer error message if (embeddingEntityTypes.has(this.type)) { const otherTypes = Array.from(embeddingEntityTypes).filter(t => t !== this.type); if (otherTypes.length === 1) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in entity type "${otherTypes[0].name}" as well and thus cannot have a parent field.`, this.input.parentDirectiveNode ) ); } else { const names = otherTypes.map(t => `"${t.name}"`); const nameList = names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in entity types ${nameList} as well and thus cannot have a parent field.`, this.input.parentDirectiveNode ) ); } } else { const names = Array.from(embeddingEntityTypes).map(t => `"${t.name}"`); const nameList = names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in multiple entity types (${nameList}) and thus cannot have a parent field.`, this.input.parentDirectiveNode ) ); } return; } const embeddingEntityType = Array.from(embeddingEntityTypes)[0]; if (embeddingEntityType !== this.type) { if (otherEmbeddingTypes.has(this.type)) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in type "${this.type.name}", but the closest entity type in the hierarchy is "${embeddingEntityType.name}", so the type of this parent field should be "${embeddingEntityType.name}".`, this.input.parentDirectiveNode ) ); } else { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in entity type "${embeddingEntityType.name}", so the type of this parent field should be "${embeddingEntityType.name}".`, this.input.parentDirectiveNode ) ); } return; } if (!this.type.isRootEntityType) { let rootNote = ''; if (!this.declaringType.fields.some(f => f.isRootField)) { const { embeddingRootEntityTypes } = collectEmbeddingRootEntityTypes(this.declaringType); if (embeddingRootEntityTypes.size === 1) { const rootType = Array.from(embeddingRootEntityTypes)[0]; rootNote = ` You could add a @root field (of type "${rootType.name}") instead.`; } } context.addMessage( ValidationMessage.warn( `Parent fields currently can't be selected within collect fields, so this field will probably be useless.${rootNote}`, this.input.parentDirectiveNode ) ); } } private validateRootField(context: ValidationContext) { if (!this.isRootField) { return; } if (this.isParentField) { context.addMessage( ValidationMessage.error(`@${PARENT_DIRECTIVE} and @${ROOT_DIRECTIVE} cannot be combined.`, this.astNode) ); return; } if (this.declaringType.kind !== 'CHILD_ENTITY') { context.addMessage( ValidationMessage.error( `@${ROOT_DIRECTIVE} can only be used on fields of child entity types.`, this.input.rootDirectiveNode ) ); return; } if (this.isReference) { context.addMessage( ValidationMessage.error( `@${ROOT_DIRECTIVE} and @${REFERENCE_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (this.isCollectField) { context.addMessage( ValidationMessage.error( `@${ROOT_DIRECTIVE} and @${COLLECT_DIRECTIVE} cannot be combined.`, this.astNode ) ); return; } if (this.isList) { context.addMessage(ValidationMessage.error(`A root field cannot be a list.`, this.input.rootDirectiveNode)); return; } if (this.declaringType.fields.some(f => f !== this && f.isRootField)) { context.addMessage( ValidationMessage.error(`There can only be one root field per type.`, this.input.astNode) ); return; } const { embeddingRootEntityTypes } = collectEmbeddingRootEntityTypes(this.declaringType); if (!embeddingRootEntityTypes.size) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is not used by any root entity type and therefore cannot have a root field.`, this.input.rootDirectiveNode ) ); return; } if (embeddingRootEntityTypes.size > 1) { // a little nicer error message if (embeddingRootEntityTypes.has(this.type)) { const otherTypes = Array.from(embeddingRootEntityTypes).filter(t => t !== this.type); if (otherTypes.length === 1) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in root entity type "${otherTypes[0].name}" as well and thus cannot have a root field.`, this.input.rootDirectiveNode ) ); } else { const names = otherTypes.map(t => `"${t.name}"`); const nameList = names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in root entity types ${nameList} as well and thus cannot have a root field.`, this.input.rootDirectiveNode ) ); } } else { const names = Array.from(embeddingRootEntityTypes).map(t => `"${t.name}"`); const nameList = names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1]; context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in multiple root entity types (${nameList}) and thus cannot have a root field.`, this.input.rootDirectiveNode ) ); } return; } const embeddingRootEntityType = Array.from(embeddingRootEntityTypes)[0]; if (embeddingRootEntityType !== this.type) { context.addMessage( ValidationMessage.error( `Type "${this.declaringType.name}" is used in root entity type "${embeddingRootEntityType.name}", so the type of this root field should be "${embeddingRootEntityType.name}".`, this.input.rootDirectiveNode ) ); return; } } private validateFlexSearch(context: ValidationContext) { const notSupportedOn = `@flexSearch is not supported on`; if (this.isFlexSearchIndexed) { if (this.isReference) { context.addMessage( ValidationMessage.error(`${notSupportedOn} references.`, this.input.isFlexSearchIndexedASTNode) ); return; } if (this.isRelation) { context.addMessage( ValidationMessage.error(`${notSupportedOn} relations.`, this.input.isFlexSearchIndexedASTNode) ); return; } if (this.isCollectField) { context.addMessage( ValidationMessage.error(`${notSupportedOn} collect fields.`, this.input.isFlexSearchIndexedASTNode) ); return; } if (this.isParentField) { context.addMessage( ValidationMessage.error(`${notSupportedOn} parent fields.`, this.input.isFlexSearchIndexedASTNode) ); return; } if (this.isRootField) { context.addMessage( ValidationMessage.error(`${notSupportedOn} root fields.`, this.input.isFlexSearchIndexedASTNode) ); return; } } if (this.isFlexSearchFulltextIndexed && !(this.type.isScalarType && this.type.name === 'String')) { context.addMessage( ValidationMessage.error( `@flexSearchFulltext is not supported on type "${this.type.name}".`, this.input.isFlexSearchFulltextIndexedASTNode ) ); return; } if (this.isFlexSearchFulltextIndexed && this.isCollectField) { context.addMessage( ValidationMessage.error( `${notSupportedOn} collect fields.`, this.input.isFlexSearchFulltextIndexedASTNode ) ); return; } if ( this.isFlexSearchIndexed && (this.type.isEntityExtensionType || this.type.isValueObjectType) && !this.type.fields.some(value => value.isFlexSearchIndexed || value.isFlexSearchFulltextIndexed) ) { context.addMessage( ValidationMessage.error( `At least one field on type "${this.type.name}" must be annotated with @flexSearch or @flexSearchFulltext if @flexSearch is specified on the type declaration.`, this.input.isFlexSearchIndexedASTNode ) ); } if ( this.name === ACCESS_GROUP_FIELD && this.declaringType.isRootEntityType && this.declaringType.permissionProfile && this.declaringType.permissionProfile.permissions.some(value => value.restrictToAccessGroups) && this.declaringType.isFlexSearchIndexed && !this.isFlexSearchIndexed ) { context.addMessage( ValidationMessage.error( `The permission profile "${this.declaringType.permissionProfile.name}" uses "restrictToAccessGroups", ` + `and this fields defining type is marked with "flexSearch: true", but this field is not marked with "@flexSearch".`, this.astNode ) ); } if ( this.isIncludedInSearch && !this.type.isObjectType && !(this.type.isScalarType && this.type.name === 'String') ) { context.addMessage( ValidationMessage.error( `"${FLEX_SEARCH_INCLUDED_IN_SEARCH_ARGUMENT}: true" is only supported on the types "String", "[String]" and object types.`, this.input.isFlexSearchIndexedASTNode ) ); return; } if ( this.input.isFlexSearchIndexCaseSensitive !== undefined && !(this.type.isScalarType && this.type.name === 'String') ) { context.addMessage( ValidationMessage.error( `"${FLEX_SEARCH_CASE_SENSITIVE_ARGUMENT}" is only supported on the types "String" and "[String]".`, this.input.flexSearchIndexCaseSensitiveASTNode ) ); return; } } get isFlexSearchIndexed(): boolean { return !!this.input.isFlexSearchIndexed; } get isFlexSearchIndexCaseSensitive(): boolean { return this.input.isFlexSearchIndexCaseSensitive ?? true; } get flexSearchAnalyzer(): string | undefined { if (!this.isFlexSearchIndexed) { return undefined; } if (!(this.type.isScalarType && this.type.name === 'String')) { return undefined; } return this.isFlexSearchIndexCaseSensitive ? IDENTITY_ANALYZER : NORM_CI_ANALYZER; } get flexSearchFulltextAnalyzer(): string | undefined { if (!this.flexSearchLanguage) { return undefined; } return 'text_' + this.flexSearchLanguage.toLocaleLowerCase(); } getFlexSearchFulltextAnalyzerOrThrow(): string { const analyzer = this.flexSearchFulltextAnalyzer; if (!analyzer) { throw new Error( `Expected field ${this.declaringType.name}.${this.name} to have a flexSearch fulltext language, but it does not` ); } return analyzer; } get isFlexSearchFulltextIndexed(): boolean { return !!this.input.isFlexSearchFulltextIndexed; } get isIncludedInSearch(): boolean { return !!this.input.isIncludedInSearch && this.isFlexSearchIndexed; } get isFulltextIncludedInSearch(): boolean { return !!this.input.isFulltextIncludedInSearch && this.isFlexSearchFulltextIndexed; } get flexSearchLanguage(): FlexSearchLanguage | undefined { return this.input.flexSearchLanguage || this.declaringType.flexSearchLanguage; } } function getAggregatorWithoutDistinct(aggregator: AggregationOperator): AggregationOperator | undefined { switch (aggregator) { case AggregationOperator.DISTINCT: return undefined; case AggregationOperator.COUNT_DISTINCT: return AggregationOperator.COUNT; default: return undefined; } } function getAggregatorTypeInfo( aggregator: AggregationOperator ): { readonly typeNames?: ReadonlyArray<string> | undefined; readonly lastSegmentShouldBeList?: boolean; readonly shouldBeNullable?: boolean; readonly resultTypeName?: string | ((typeName: string) => string); readonly resultIsList?: boolean; readonly usesDistinct?: boolean; } { switch (aggregator) { case AggregationOperator.COUNT: return { lastSegmentShouldBeList: true, resultTypeName: GraphQLInt.name }; case AggregationOperator.SOME: case AggregationOperator.NONE: return { lastSegmentShouldBeList: true, resultTypeName: GraphQLBoolean.name }; case AggregationOperator.COUNT_NULL: case AggregationOperator.COUNT_NOT_NULL: return { shouldBeNullable: true, resultTypeName: GraphQLInt.name }; case AggregationOperator.SOME_NULL: case AggregationOperator.SOME_NOT_NULL: case AggregationOperator.EVERY_NULL: case AggregationOperator.NONE_NULL: return { shouldBeNullable: true, resultTypeName: GraphQLBoolean.name }; case AggregationOperator.MAX: case AggregationOperator.MIN: return { typeNames: [ ...numberTypeNames, GraphQLDateTime.name, GraphQLLocalDate.name, GraphQLLocalTime.name, GraphQLOffsetDateTime.name ], resultTypeName: typeName => (typeName === GraphQLOffsetDateTime.name ? GraphQLDateTime.name : typeName) }; case AggregationOperator.AVERAGE: case AggregationOperator.SUM: return { typeNames: numberTypeNames }; case AggregationOperator.COUNT_TRUE: case AggregationOperator.COUNT_NOT_TRUE: return { typeNames: [GraphQLBoolean.name], resultTypeName: GraphQLInt.name }; case AggregationOperator.SOME_TRUE: case AggregationOperator.SOME_NOT_TRUE: case AggregationOperator.EVERY_TRUE: case AggregationOperator.NONE_TRUE: return { typeNames: [GraphQLBoolean.name], resultTypeName: GraphQLBoolean.name }; case AggregationOperator.DISTINCT: return { usesDistinct: true, resultIsList: true }; case AggregationOperator.COUNT_DISTINCT: return { usesDistinct: true, resultTypeName: GraphQLInt.name }; default: // this is caught in the graphql-rules validator return {}; } } function canAggregationBeNull(operator: AggregationOperator): boolean { switch (operator) { case AggregationOperator.MAX: case AggregationOperator.MIN: case AggregationOperator.AVERAGE: return true; default: return false; } } const scalarTypesThatSupportDistinctAggregation: ReadonlyArray<string> = [ GraphQLString.name, GraphQLID.name, GraphQLBoolean.name, GraphQLInt.name, GraphQLLocalDate.name ]; function isDistinctAggregationSupported(type: Type) { // "simple" value object types are supported to support cases like two-field identifiers (e.g. type + key) if (type.isValueObjectType) { return getOffendingValueObjectFieldsForDistinctAggregation(type).length === 0; } return ( type.isRootEntityType || type.isChildEntityType || type.isEnumType || scalarTypesThatSupportDistinctAggregation.includes(type.name) ); } function getOffendingValueObjectFieldsForDistinctAggregation(type: ValueObjectType) { return type.fields.filter( field => !field.type.isEnumType && !field.type.isRootEntityType && !scalarTypesThatSupportDistinctAggregation.includes(field.type.name) ); }
the_stack
import { HTML, SVG } from "imperative-html/dist/esm/elements-strict"; import { Prompt } from "./Prompt"; import { SongDocument } from "./SongDocument"; import { ColorConfig } from "./ColorConfig"; import { ChangeCustomWave } from "./changes"; import { SongEditor } from "./SongEditor"; //namespace beepbox { const { button, div, h2 } = HTML; export class CustomChipPromptCanvas { private readonly _doc: SongDocument; private _mouseX: number = 0; private _mouseY: number = 0; private _lastIndex: number = 0; private _lastAmp: number = 0; private _mouseDown: boolean = false; public chipData: Float64Array = new Float64Array(64); public startingChipData: Float64Array = new Float64Array(64); private _undoHistoryState: number = 0; private _changeQueue: Float64Array[] = []; private readonly _editorWidth: number = 768; // 64*12 private readonly _editorHeight: number = 294; // 49*6 private readonly _fill: SVGPathElement = SVG.path({ fill: ColorConfig.uiWidgetBackground, "pointer-events": "none" }); private readonly _ticks: SVGSVGElement = SVG.svg({ "pointer-events": "none" }); private readonly _subticks: SVGSVGElement = SVG.svg({ "pointer-events": "none" }); private readonly _blocks: SVGSVGElement = SVG.svg({ "pointer-events": "none" }); private readonly _svg: SVGSVGElement = SVG.svg({ style: `background-color: ${ColorConfig.editorBackground}; touch-action: none; overflow: visible;`, width: "100%", height: "100%", viewBox: "0 0 " + this._editorWidth + " " + this._editorHeight, preserveAspectRatio: "none" }, this._fill, this._ticks, this._subticks, this._blocks, ); public readonly container: HTMLElement = HTML.div({ class: "", style: "height: 294px; width: 768px; padding-bottom: 1.5em;" }, this._svg); constructor(doc: SongDocument) { this._doc = doc; for (let i: number = 0; i <= 4; i += 2) { this._ticks.appendChild(SVG.rect({ fill: ColorConfig.tonic, x: (i * this._editorWidth / 4) - 1, y: 0, width: 2, height: this._editorHeight })); } for (let i: number = 1; i <= 8; i++) { this._subticks.appendChild(SVG.rect({ fill: ColorConfig.fifthNote, x: (i * this._editorWidth / 8) - 1, y: 0, width: 1, height: this._editorHeight })); } // Horiz. ticks this._ticks.appendChild(SVG.rect({ fill: ColorConfig.tonic, x: 0, y: (this._editorHeight / 2) - 1, width: this._editorWidth, height: 2 })); for (let i: number = 0; i < 3; i++) { this._subticks.appendChild(SVG.rect({ fill: ColorConfig.fifthNote, x: 0, y: i * 8 * (this._editorHeight / 49), width: this._editorWidth, height: 1 })); this._subticks.appendChild(SVG.rect({ fill: ColorConfig.fifthNote, x: 0, y: this._editorHeight - 1 - i * 8 * (this._editorHeight / 49), width: this._editorWidth, height: 1 })); } let col: string = ColorConfig.getChannelColor(this._doc.song, this._doc.channel).primaryNote; for (let i: number = 0; i <= 64; i++) { let val: number = this._doc.song.channels[this._doc.channel].instruments[this._doc.getCurrentInstrument()].customChipWave[i]; this.chipData[i] = val; this.startingChipData[i] = val; this._blocks.appendChild(SVG.rect({ fill: col, x: (i * this._editorWidth / 64), y: (val + 24) * (this._editorHeight / 49), width: this._editorWidth / 64, height: this._editorHeight / 49 })); } // Record initial state of the chip data queue this._storeChange(); this.container.addEventListener("mousedown", this._whenMousePressed); document.addEventListener("mousemove", this._whenMouseMoved); document.addEventListener("mouseup", this._whenCursorReleased); this.container.addEventListener("touchstart", this._whenTouchPressed); this.container.addEventListener("touchmove", this._whenTouchMoved); this.container.addEventListener("touchend", this._whenCursorReleased); this.container.addEventListener("touchcancel", this._whenCursorReleased); this._svg.addEventListener("keydown", this._whenKeyPressed); this.container.addEventListener("keydown", this._whenKeyPressed); } private _storeChange = (): void => { // Check if change is unique compared to the current history state var sameCheck = true; if (this._changeQueue.length > 0) { for (var i = 0; i < 64; i++) { if (this._changeQueue[this._undoHistoryState][i] != this.chipData[i]) { sameCheck = false; i = 64; } } } if (sameCheck == false || this._changeQueue.length == 0) { // Create new branch in history, removing all after this in time this._changeQueue.splice(0, this._undoHistoryState); this._undoHistoryState = 0; this._changeQueue.unshift(this.chipData.slice()); // 32 undo max if (this._changeQueue.length > 32) { this._changeQueue.pop(); } } } public undo = (): void => { // Go backward, if there is a change to go back to if (this._undoHistoryState < this._changeQueue.length - 1) { this._undoHistoryState++; this.chipData = this._changeQueue[this._undoHistoryState].slice(); new ChangeCustomWave(this._doc, this.chipData); this.render(); } } public redo = (): void => { // Go forward, if there is a change to go to if (this._undoHistoryState > 0) { this._undoHistoryState--; this.chipData = this._changeQueue[this._undoHistoryState].slice(); new ChangeCustomWave(this._doc, this.chipData); this.render(); } } private _whenKeyPressed = (event: KeyboardEvent): void => { if (event.keyCode == 90) { // z this.undo(); event.stopPropagation(); } if (event.keyCode == 89) { // y this.redo(); event.stopPropagation(); } } private _whenMousePressed = (event: MouseEvent): void => { event.preventDefault(); this._mouseDown = true; const boundingRect: ClientRect = this._svg.getBoundingClientRect(); this._mouseX = ((event.clientX || event.pageX) - boundingRect.left) * this._editorWidth / (boundingRect.right - boundingRect.left); this._mouseY = ((event.clientY || event.pageY) - boundingRect.top) * this._editorHeight / (boundingRect.bottom - boundingRect.top); if (isNaN(this._mouseX)) this._mouseX = 0; if (isNaN(this._mouseY)) this._mouseY = 0; this._lastIndex = -1; this._whenCursorMoved(); } private _whenTouchPressed = (event: TouchEvent): void => { event.preventDefault(); this._mouseDown = true; const boundingRect: ClientRect = this._svg.getBoundingClientRect(); this._mouseX = (event.touches[0].clientX - boundingRect.left) * this._editorWidth / (boundingRect.right - boundingRect.left); this._mouseY = (event.touches[0].clientY - boundingRect.top) * this._editorHeight / (boundingRect.bottom - boundingRect.top); if (isNaN(this._mouseX)) this._mouseX = 0; if (isNaN(this._mouseY)) this._mouseY = 0; this._lastIndex = -1; this._whenCursorMoved(); } private _whenMouseMoved = (event: MouseEvent): void => { if (this.container.offsetParent == null) return; const boundingRect: ClientRect = this._svg.getBoundingClientRect(); this._mouseX = ((event.clientX || event.pageX) - boundingRect.left) * this._editorWidth / (boundingRect.right - boundingRect.left); this._mouseY = ((event.clientY || event.pageY) - boundingRect.top) * this._editorHeight / (boundingRect.bottom - boundingRect.top); if (isNaN(this._mouseX)) this._mouseX = 0; if (isNaN(this._mouseY)) this._mouseY = 0; this._whenCursorMoved(); } private _whenTouchMoved = (event: TouchEvent): void => { if (this.container.offsetParent == null) return; if (!this._mouseDown) return; event.preventDefault(); const boundingRect: ClientRect = this._svg.getBoundingClientRect(); this._mouseX = (event.touches[0].clientX - boundingRect.left) * this._editorWidth / (boundingRect.right - boundingRect.left); this._mouseY = (event.touches[0].clientY - boundingRect.top) * this._editorHeight / (boundingRect.bottom - boundingRect.top); if (isNaN(this._mouseX)) this._mouseX = 0; if (isNaN(this._mouseY)) this._mouseY = 0; this._whenCursorMoved(); } private _whenCursorMoved(): void { if (this._mouseDown) { const index: number = Math.min(63, Math.max(0, Math.floor(this._mouseX * 64 / this._editorWidth))); const amp: number = Math.min(48, Math.max(0, Math.floor(this._mouseY * 49 / this._editorHeight))); // Paint between mouse drag indices unless a click just happened. if (this._lastIndex != -1 && this._lastIndex != index) { var lowest = index; var highest = this._lastIndex; var startingAmp = amp; var endingAmp = this._lastAmp; if (this._lastIndex < index) { lowest = this._lastIndex; highest = index; startingAmp = this._lastAmp; endingAmp = amp; } for (var i = lowest; i <= highest; i++) { const medAmp: number = Math.round(startingAmp + (endingAmp - startingAmp) * ((i - lowest) / (highest - lowest))); this.chipData[i] = medAmp - 24; this._blocks.children[i].setAttribute("y", "" + (medAmp * (this._editorHeight / 49))); } } else { this.chipData[index] = amp - 24; this._blocks.children[index].setAttribute("y", "" + (amp * (this._editorHeight / 49))); } // Make a change to the data but don't record it, since this prompt uses its own undo/redo queue new ChangeCustomWave(this._doc, this.chipData); this._lastIndex = index; this._lastAmp = amp; } } private _whenCursorReleased = (event: Event): void => { // Add current data into queue, if it is unique from last data this._storeChange(); this._mouseDown = false; } public render(): void { for (var i = 0; i < 64; i++) { this._blocks.children[i].setAttribute("y", "" + ((this.chipData[i] + 24) * (this._editorHeight / 49))); } } } export class CustomChipPrompt implements Prompt { public customChipCanvas: CustomChipPromptCanvas = new CustomChipPromptCanvas(this._doc); public readonly _playButton: HTMLButtonElement = button({ style: "width: 55%;", type: "button" }); private readonly _cancelButton: HTMLButtonElement = button({ class: "cancelButton" }); private readonly _okayButton: HTMLButtonElement = button({ class: "okayButton", style: "width:45%;" }, "Okay"); public readonly container: HTMLDivElement = div({ class: "prompt noSelection", style: "width: 600px;" }, h2("Edit Custom Chip Instrument"), div({ style: "display: flex; width: 55%; align-self: center; flex-direction: row; align-items: center; justify-content: center;" }, this._playButton, ), div({ style: "display: flex; flex-direction: row; align-items: center; justify-content: center;" }, this.customChipCanvas.container, ), div({ style: "display: flex; flex-direction: row-reverse; justify-content: space-between;" }, this._okayButton, ), this._cancelButton, ); constructor(private _doc: SongDocument, private _songEditor: SongEditor) { this._okayButton.addEventListener("click", this._saveChanges); this._cancelButton.addEventListener("click", this._close); this.container.addEventListener("keydown", this.whenKeyPressed); this._playButton.addEventListener("click", this._togglePlay); this.updatePlayButton(); setTimeout(() => this._playButton.focus()); this.customChipCanvas.render(); } private _togglePlay = (): void => { if (this._doc.synth.playing) { this._songEditor._pause(); this.updatePlayButton(); } else { this._doc.synth.snapToBar(); this._songEditor._play(); this.updatePlayButton(); } } public updatePlayButton(): void { if (this._doc.synth.playing) { this._playButton.classList.remove("playButton"); this._playButton.classList.add("pauseButton"); this._playButton.title = "Pause (Space)"; this._playButton.innerText = "Pause"; } else { this._playButton.classList.remove("pauseButton"); this._playButton.classList.add("playButton"); this._playButton.title = "Play (Space)"; this._playButton.innerText = "Play"; } } private _close = (): void => { this._doc.prompt = null; this._doc.undo(); } public cleanUp = (): void => { this._okayButton.removeEventListener("click", this._saveChanges); this._cancelButton.removeEventListener("click", this._close); this.container.removeEventListener("keydown", this.whenKeyPressed); this._playButton.removeEventListener("click", this._togglePlay); } public whenKeyPressed = (event: KeyboardEvent): void => { if ((<Element>event.target).tagName != "BUTTON" && event.keyCode == 13) { // Enter key this._saveChanges(); } if (event.keyCode == 32) { this._togglePlay(); event.preventDefault(); } if (event.keyCode == 90) { // z this.customChipCanvas.undo(); event.stopPropagation(); } if (event.keyCode == 89) { // y this.customChipCanvas.redo(); event.stopPropagation(); } } private _saveChanges = (): void => { this._doc.prompt = null; // Restore custom chip to starting values new ChangeCustomWave(this._doc, this.customChipCanvas.startingChipData); this._doc.record(new ChangeCustomWave(this._doc, this.customChipCanvas.chipData), true); } } //}
the_stack
import { CurrencyManager, UnsupportedCurrencyError } from '@requestnetwork/currency'; import { ExtensionTypes, IdentityTypes, RequestLogicTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import DeclarativePaymentNetwork from './declarative'; /** * Core of the address based payment networks * This module is called by the address based payment networks to avoid code redundancy */ export default abstract class AddressBasedPaymentNetwork< TCreationParameters extends ExtensionTypes.PnAddressBased.ICreationParameters = ExtensionTypes.PnAddressBased.ICreationParameters, > extends DeclarativePaymentNetwork<TCreationParameters> { public constructor( public extensionId: ExtensionTypes.ID, public currentVersion: string, public supportedNetworks: string[], public supportedCurrencyType: RequestLogicTypes.CURRENCY, ) { super(extensionId, currentVersion); this.actions = { ...this.actions, [ExtensionTypes.PnAddressBased.ACTION.ADD_PAYMENT_ADDRESS]: this.applyAddPaymentAddress.bind(this), [ExtensionTypes.PnAddressBased.ACTION.ADD_REFUND_ADDRESS]: this.applyAddRefundAddress.bind(this), }; } /** * Creates the extensionsData for address based payment networks * * @param extensions extensions parameters to create * * @returns IExtensionCreationAction the extensionsData to be stored in the request */ public createCreationAction( creationParameters: TCreationParameters, ): ExtensionTypes.IAction<TCreationParameters> { if ( creationParameters.paymentAddress && !this.isValidAddress(creationParameters.paymentAddress) ) { throw new InvalidPaymentAddressError(creationParameters.paymentAddress); } if ( creationParameters.refundAddress && !this.isValidAddress(creationParameters.refundAddress) ) { throw new InvalidPaymentAddressError(creationParameters.refundAddress, 'refundAddress'); } return super.createCreationAction( creationParameters, ) as ExtensionTypes.IAction<TCreationParameters>; } /** * Creates the extensionsData to add a payment address * * @param extensions extensions parameters to create * * @returns IAction the extensionsData to be stored in the request */ public createAddPaymentAddressAction( addPaymentAddressParameters: ExtensionTypes.PnAddressBased.IAddPaymentAddressParameters, ): ExtensionTypes.IAction { const paymentAddress = addPaymentAddressParameters.paymentAddress; if (paymentAddress && !this.isValidAddress(paymentAddress)) { throw new InvalidPaymentAddressError(paymentAddress); } return { action: ExtensionTypes.PnAddressBased.ACTION.ADD_PAYMENT_ADDRESS, id: this.extensionId, parameters: { paymentAddress, }, }; } /** * Creates the extensionsData to add a refund address * * @param extensions extensions parameters to create * * @returns IAction the extensionsData to be stored in the request */ public createAddRefundAddressAction( addRefundAddressParameters: ExtensionTypes.PnAddressBased.IAddRefundAddressParameters, ): ExtensionTypes.IAction { const refundAddress = addRefundAddressParameters.refundAddress; if (refundAddress && !this.isValidAddress(refundAddress)) { throw new InvalidPaymentAddressError(refundAddress, 'refundAddress'); } return { action: ExtensionTypes.PnAddressBased.ACTION.ADD_REFUND_ADDRESS, id: this.extensionId, parameters: { refundAddress, }, }; } protected applyCreation( extensionAction: ExtensionTypes.IAction, timestamp: number, ): ExtensionTypes.IState { const paymentAddress = extensionAction.parameters.paymentAddress; const refundAddress = extensionAction.parameters.refundAddress; if (paymentAddress && !this.isValidAddress(paymentAddress)) { throw new InvalidPaymentAddressError(paymentAddress); } if (refundAddress && !this.isValidAddress(refundAddress)) { throw new InvalidPaymentAddressError(refundAddress, 'refundAddress'); } const genericCreationAction = super.applyCreation(extensionAction, timestamp); return { ...genericCreationAction, events: [ { name: 'create', parameters: { paymentAddress, refundAddress, }, timestamp, }, ], id: this.extensionId, type: this.extensionType, values: { ...genericCreationAction.values, paymentAddress, refundAddress, }, }; } protected isValidAddress(address: string, networkName?: string): boolean { if (networkName) { return this.isValidAddressForNetwork(address, networkName); } return this.supportedNetworks.some((network) => this.isValidAddressForNetwork(address, network), ); } protected isValidAddressForNetwork(address: string, network: string): boolean { switch (this.supportedCurrencyType) { case RequestLogicTypes.CURRENCY.BTC: return this.isValidAddressForSymbolAndNetwork( address, network === 'testnet' ? 'BTC-testnet' : 'BTC', network, ); case RequestLogicTypes.CURRENCY.ETH: case RequestLogicTypes.CURRENCY.ERC20: case RequestLogicTypes.CURRENCY.ERC777: return this.isValidAddressForSymbolAndNetwork(address, 'ETH', 'mainnet'); default: throw new Error( `Default implementation of isValidAddressForNetwork() does not support currency type ${this.supportedCurrencyType}. Please override this method if needed.`, ); } } protected isValidAddressForSymbolAndNetwork( address: string, symbol: string, network: string, ): boolean { const currencyManager = CurrencyManager.getDefault(); const currency = currencyManager.from(symbol, network); if (!currency) { throw new UnsupportedCurrencyError({ value: symbol, network }); } return CurrencyManager.validateAddress(address, currency); } /** * Applies add payment address * * @param extensionState previous state of the extension * @param extensionAction action to apply * @param requestState request state read-only * @param actionSigner identity of the signer * * @returns state of the extension updated */ protected applyAddPaymentAddress( extensionState: ExtensionTypes.IState, extensionAction: ExtensionTypes.IAction, requestState: RequestLogicTypes.IRequest, actionSigner: IdentityTypes.IIdentity, timestamp: number, ): ExtensionTypes.IState { if ( extensionAction.parameters.paymentAddress && !this.isValidAddress(extensionAction.parameters.paymentAddress, requestState.currency.network) ) { throw new InvalidPaymentAddressError(extensionAction.parameters.paymentAddress); } if (extensionState.values.paymentAddress) { throw Error(`Payment address already given`); } if (!requestState.payee) { throw Error(`The request must have a payee`); } if (!Utils.identity.areEqual(actionSigner, requestState.payee)) { throw Error(`The signer must be the payee`); } const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); // update payment address copiedExtensionState.values.paymentAddress = extensionAction.parameters.paymentAddress; // update events copiedExtensionState.events.push({ name: ExtensionTypes.PnAddressBased.ACTION.ADD_PAYMENT_ADDRESS, parameters: { paymentAddress: extensionAction.parameters.paymentAddress }, timestamp, }); return copiedExtensionState; } /** * Applies add refund address * * @param extensionState previous state of the extension * @param extensionAction action to apply * @param requestState request state read-only * @param actionSigner identity of the signer * * @returns state of the extension updated */ protected applyAddRefundAddress( extensionState: ExtensionTypes.IState, extensionAction: ExtensionTypes.IAction, requestState: RequestLogicTypes.IRequest, actionSigner: IdentityTypes.IIdentity, timestamp: number, ): ExtensionTypes.IState { if ( extensionAction.parameters.refundAddress && !this.isValidAddress(extensionAction.parameters.refundAddress, requestState.currency.network) ) { throw Error('refundAddress is not a valid address'); } if (extensionState.values.refundAddress) { throw Error(`Refund address already given`); } if (!requestState.payer) { throw Error(`The request must have a payer`); } if (!Utils.identity.areEqual(actionSigner, requestState.payer)) { throw Error(`The signer must be the payer`); } const copiedExtensionState: ExtensionTypes.IState = Utils.deepCopy(extensionState); // update refund address copiedExtensionState.values.refundAddress = extensionAction.parameters.refundAddress; // update events copiedExtensionState.events.push({ name: ExtensionTypes.PnAddressBased.ACTION.ADD_REFUND_ADDRESS, parameters: { refundAddress: extensionAction.parameters.refundAddress }, timestamp, }); return copiedExtensionState; } protected validate( request: RequestLogicTypes.IRequest, // eslint-disable-next-line @typescript-eslint/no-unused-vars _extensionAction: ExtensionTypes.IAction, ): void { if (request.currency.type !== this.supportedCurrencyType) { throw Error(`This extension can be used only on ${this.supportedCurrencyType} requests`); } if (request.currency.network && !this.supportedNetworks.includes(request.currency.network)) { throw new UnsupportedNetworkError(request.currency.network, this.supportedNetworks); } } } export class InvalidPaymentAddressError extends Error { constructor(address?: string, addressReference = 'paymentAddress') { const formattedAddress = address ? ` '${address}'` : ''; super(`${addressReference}${formattedAddress} is not a valid address`); } } export class UnsupportedNetworkError extends Error { constructor(unsupportedNetworkName: string, supportedNetworks?: string[]) { const supportedNetworkDetails = supportedNetworks ? ` (only ${supportedNetworks.join(', ')})` : ''; super( `Payment network '${unsupportedNetworkName}' is not supported by this extension${supportedNetworkDetails}`, ); } }
the_stack
import { extend } from '@syncfusion/ej2-base'; import { Chart } from '../../chart'; import { AccumulationChart } from '../../accumulation-chart/accumulation'; import { AccPoints, AccumulationSeries } from '../../accumulation-chart/model/acc-base'; import { PointData, ChartLocation, withInBounds } from '../../common/utils/helper'; import { Rect, Size, measureText, TooltipPlacement } from '@syncfusion/ej2-svg-base'; import { stopTimer, AccPointData, removeElement } from '../../common/utils/helper'; import { ChartData } from '../../chart/utils/get-data'; import { Tooltip } from '../../chart/user-interaction/tooltip'; import { AccumulationTooltip } from '../../accumulation-chart/user-interaction/tooltip'; import { Series, Points } from '../../chart/series/chart-series'; import { FontModel } from '../../common/model/base-model'; import { Tooltip as SVGTooltip, ITooltipAnimationCompleteArgs } from '@syncfusion/ej2-svg-base'; import { ChartShape } from '../../chart/utils/enum'; import { AccumulationSelection } from '../../accumulation-chart'; /** * Tooltip Module used to render the tooltip for series. */ export class BaseTooltip extends ChartData { //Internal variables public element: HTMLElement; public elementSize: Size; public textStyle: FontModel; public isRemove: boolean; public toolTipInterval: number; public textElements: Element[]; public inverted: boolean; public formattedText: string[]; public header: string; /** @private */ public valueX: number; /** @private */ public valueY: number; public control: AccumulationChart | Chart; public text: string[]; public svgTooltip: SVGTooltip; public headerText: string; /** * Constructor for tooltip module. * * @private */ constructor(chart: Chart | AccumulationChart) { super(chart as Chart); this.element = this.chart.element; this.textStyle = chart.tooltip.textStyle; this.control = chart; } public getElement(id: string): HTMLElement { return document.getElementById(id); } /** * Renders the tooltip. * * @returns {void} * @private */ public getTooltipElement(isTooltip: boolean): HTMLDivElement { this.inverted = this.chart.requireInvertedAxis; this.header = (this.control.tooltip.header === null) ? ((this.control.tooltip.shared) ? '<b>${point.x}</b>' : '<b>${series.name}</b>') : (this.control.tooltip.header); this.formattedText = []; const tooltipDiv: HTMLElement = document.getElementById(this.chart.element.id + '_tooltip'); const isStockChart: boolean = this.chart.element.id.indexOf('stockChart') > -1; if (!isTooltip && !tooltipDiv || isStockChart) { return this.createElement(); } return null; } public createElement(): HTMLDivElement { const tooltipDiv: HTMLDivElement = document.createElement('div'); tooltipDiv.id = this.element.id + '_tooltip'; tooltipDiv.className = 'ejSVGTooltip'; tooltipDiv.setAttribute('style', 'pointer-events:none; position:absolute;z-index: 1'); return tooltipDiv; } public pushData(data: PointData | AccPointData, isFirst: boolean, tooltipDiv: HTMLDivElement, isChart: boolean): boolean { if (data.series.enableTooltip) { if (isChart) { (<PointData[]>this.currentPoints).push(<PointData>data); } else { (<AccPointData[]>this.currentPoints).push(<AccPointData>data); } this.stopAnimation(); if (tooltipDiv && !document.getElementById(tooltipDiv.id)) { if (!this.chart.stockChart) { document.getElementById(this.element.id + '_Secondary_Element').appendChild(tooltipDiv); } else { document.getElementById(this.chart.stockChart.element.id + '_Secondary_Element').appendChild(tooltipDiv); } } return true; } return false; } public removeHighlight(): void { let item: PointData | AccPointData; let series: Series; for (let i: number = 0, len: number = this.previousPoints.length; i < len; i++) { item = this.previousPoints[i]; if (item.series.isRectSeries) { if (item.series.visible) { this.highlightPoint(item.series, item.point.index, false); } continue; } series = item.series as Series; if (!series.marker.visible && item.series.type !== 'Scatter' && item.series.type !== 'Bubble') { this.previousPoints.shift(); len -= 1; } } } public highlightPoint(series: Series | AccumulationSeries, pointIndex: number, highlight: boolean): void { const element: HTMLElement = this.getElement(this.element.id + '_Series_' + series.index + '_Point_' + pointIndex); const selectionModule: AccumulationSelection = (this.control as AccumulationChart).accumulationSelectionModule; const isSelectedElement: boolean = selectionModule && selectionModule.selectedDataIndexes.length > 0 ? true : false; if (element) { if ((!isSelectedElement || isSelectedElement && element.getAttribute('class') && element.getAttribute('class').indexOf('_ej2_chart_selection_series_') === -1)) { element.setAttribute('opacity', (highlight ? series.opacity / 2 : series.opacity).toString()); } else { element.setAttribute('opacity', series.opacity.toString()); } } } public highlightPoints(): void { for (const item of this.currentPoints) { if (item.series.isRectSeries && item.series.category === 'Series') { this.highlightPoint(item.series, item.point.index, true); } } } // tslint:disable-next-line:max-func-body-length public createTooltip( chart: Chart | AccumulationChart, isFirst: boolean, location: ChartLocation, clipLocation: ChartLocation, point: Points | AccPoints, shapes: ChartShape[], offset: number, bounds: Rect, extraPoints: PointData[] = null, templatePoint: Points | AccPoints = null, customTemplate?: string ): void { const series: Series = <Series>this.currentPoints[0].series; const module: AccumulationTooltip | Tooltip = (<Chart>chart).tooltipModule || (<AccumulationChart>chart).accumulationTooltipModule; if (!module) { // For the tooltip enable is false. return; } let isNegative: boolean = (series.isRectSeries && series.type !== 'Waterfall' && point && point.y < 0); let inverted: boolean = this.chart.requireInvertedAxis && series.isRectSeries; let position: TooltipPlacement = null; if (this.text.length <= 1) { let contentSize: Size; let headerSize: Size; let tooltipTemplate: string = !customTemplate ? chart.tooltip.template : customTemplate; if (tooltipTemplate && chart.getModuleName() === 'chart' && tooltipTemplate[0] !== '#' && typeof tooltipTemplate === 'string') { const templateDiv: HTMLDivElement = document.createElement('div'); templateDiv.id = 'testing_template'; templateDiv.className = 'ejSVGTooltip'; templateDiv.setAttribute('style', 'pointer-events:none; position:absolute;z-index: 1'); document.getElementById(this.chart.element.id + '_Secondary_Element').appendChild(templateDiv); const template: string = ((tooltipTemplate as any).replaceAll('${x}', point.x as string) as any).replaceAll('${y}', point.y as string); templateDiv.innerHTML = template; contentSize = new Size( (templateDiv.firstElementChild as HTMLElement).offsetWidth, (templateDiv.firstElementChild as HTMLElement).offsetHeight); headerSize = new Size(0, 0); templateDiv.remove(); } else { contentSize = measureText(this.text[0], chart.tooltip.textStyle); headerSize = (!(this.header === '' || this.header === '<b></b>')) ? measureText(this.header, this.textStyle) : new Size(0, 0); } // marker size + arrowpadding + 2 * padding + markerpadding const markerSize: number = 10 + 12 + (2 * 10) + 5; contentSize.width = Math.max(contentSize.width, headerSize.width) + ((shapes.length > 0) ? markerSize : 0); const heightPadding: number = 12 + (2 * 10) + (headerSize.height > 0 ? (2 * 10) : 0); contentSize.height = contentSize.height + headerSize.height + heightPadding; position = this.getCurrentPosition(isNegative, inverted); position = this.getPositionBySize(contentSize, new Rect(0, 0, bounds.width, bounds.height), location, position); isNegative = (position === 'Left') || (position === 'Bottom'); inverted = (position === 'Left') || (position === 'Right'); } // else if (tooltipPosition !== 'None' && this.text.length <= 1) { // position = tooltipPosition as TooltipPlacement; // isNegative = (position === 'Left') || (position === 'Bottom'); // inverted = (position === 'Left') || (position === 'Right'); // } if (isFirst) { this.svgTooltip = new SVGTooltip( { opacity: chart.tooltip.opacity, header: this.headerText, content: this.text, fill: chart.tooltip.fill, border: chart.tooltip.border, enableAnimation: chart.tooltip.enableAnimation, location: location, shared: chart.tooltip.shared, shapes: shapes, clipBounds: this.chart.chartAreaType === 'PolarRadar' ? new ChartLocation(0, 0) : clipLocation, areaBounds: bounds, palette: this.findPalette(), template: customTemplate || chart.tooltip.template, data: templatePoint, theme: chart.theme, offset: offset, textStyle: chart.tooltip.textStyle, isNegative: isNegative, inverted: inverted, arrowPadding: this.text.length > 1 || this.chart.stockChart ? 0 : 12, availableSize: chart.availableSize, duration: this.chart.tooltip.duration, isCanvas: this.chart.enableCanvas, isTextWrap: chart.tooltip.enableTextWrap && chart.getModuleName() === 'chart', blazorTemplate: { name: 'Template', parent: this.chart.tooltip }, controlInstance: this.chart, tooltipPlacement: position, tooltipRender: () => { module.removeHighlight(); module.highlightPoints(); module.updatePreviousPoint(extraPoints); }, animationComplete: (args: ITooltipAnimationCompleteArgs) => { if (args.tooltip.fadeOuted) { module.fadeOut(<PointData[]>module.previousPoints); } } }, '#' + this.element.id + '_tooltip'); } else { if (this.svgTooltip) { this.svgTooltip.location = location; this.svgTooltip.content = this.text; this.svgTooltip.header = this.headerText; this.svgTooltip.offset = offset; this.svgTooltip.palette = this.findPalette(); this.svgTooltip.shapes = shapes; this.svgTooltip.data = templatePoint; this.svgTooltip.template = chart.tooltip.template; this.svgTooltip.textStyle = chart.tooltip.textStyle; this.svgTooltip.isNegative = isNegative; this.svgTooltip.inverted = inverted; this.svgTooltip.clipBounds = this.chart.chartAreaType === 'PolarRadar' ? new ChartLocation(0, 0) : clipLocation; this.svgTooltip.arrowPadding = this.text.length > 1 || this.chart.stockChart ? 0 : 12; this.svgTooltip.tooltipPlacement = position; this.svgTooltip.dataBind(); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((this.chart as any).isReact) { (this.chart as any).renderReactTemplates(); } } private getPositionBySize(textSize: Size, bounds: Rect, arrowLocation: ChartLocation, position: TooltipPlacement): TooltipPlacement { const isTop: boolean = this.isTooltipFitPosition('Top', new Rect(0, 0, bounds.width, bounds.height), arrowLocation, textSize); const isBottom: boolean = this.isTooltipFitPosition('Bottom', new Rect(0, 0, bounds.width, bounds.height), arrowLocation, textSize); const isRight: boolean = this.isTooltipFitPosition('Right', new Rect(0, 0, bounds.width, bounds.height), arrowLocation, textSize); const isLeft: boolean = this.isTooltipFitPosition('Left', new Rect(0, 0, bounds.width, bounds.height), arrowLocation, textSize); let tooltipPos: TooltipPlacement; if (isTop || isBottom || isRight || isLeft) { if (position === 'Top') { tooltipPos = isTop ? 'Top' : (isBottom ? 'Bottom' : (isRight ? 'Right' : 'Left')); } else if (position === 'Bottom') { tooltipPos = isBottom ? 'Bottom' : (isTop ? 'Top' : (isRight ? 'Right' : 'Left')); } else if (position === 'Right') { tooltipPos = isRight ? 'Right' : (isLeft ? 'Left' : (isTop ? 'Top' : 'Bottom')); } else { tooltipPos = isLeft ? 'Left' : (isRight ? 'Right' : (isTop ? 'Top' : 'Bottom')); } } else { const size: number[] = [(arrowLocation.x - bounds.x), ((bounds.x + bounds.width) - arrowLocation.x), (arrowLocation.y - bounds.y), ((bounds.y + bounds.height) - arrowLocation.y)]; const index: number = size.indexOf(Math.max.apply(this, size)); position = (index === 0) ? 'Left' : (index === 1) ? 'Right' : (index === 2) ? 'Top' : 'Bottom'; return position; } return tooltipPos; } private isTooltipFitPosition(position: TooltipPlacement, bounds: Rect, location: ChartLocation, size: Size): boolean { const start: ChartLocation = new ChartLocation(0, 0); const end: ChartLocation = new ChartLocation(0, 0); switch (position) { case 'Top': start.x = location.x - (size.width / 2); start.y = location.y - size.height; end.x = location.x + (size.width / 2); end.y = location.y; break; case 'Bottom': start.x = location.x - (size.width / 2); start.y = location.y; end.x = location.x + (size.width / 2); end.y = location.y + size.height; break; case 'Right': start.x = location.x; start.y = location.y - (size.height / 2); end.x = location.x + size.width; end.y = location.y + (size.height / 2); break; case 'Left': start.x = location.x - size.width; start.y = location.y - (size.height / 2); end.x = location.x; end.y = location.y + (size.height / 2); break; } return (withInBounds(start.x, start.y, bounds) && withInBounds(end.x, end.y, bounds)); } private getCurrentPosition(isNegative: boolean, inverted: boolean): TooltipPlacement { let position: TooltipPlacement; if (inverted) { position = isNegative ? 'Left' : 'Right'; } else { position = isNegative ? 'Bottom' : 'Top'; } return position; } private findPalette() : string[] { const colors : string[] = []; for (const data of this.currentPoints) { colors.push(this.findColor(data, <Series>data.series)); } return colors; } private findColor(data: PointData | AccPointData, series: Series) : string { if (series.isRectSeries && (series.type === 'Candle' || series.type === 'Hilo' || series.type === 'HiloOpenClose')) { return data.point.color; } else { return (data.point.color && data.point.color !== '#ffffff' ? data.point.color : (<Points>data.point).interior) || series.marker.fill || series.interior; } } public updatePreviousPoint(extraPoints: PointData[]): void { if (extraPoints) { this.currentPoints = (<PointData[]>this.currentPoints).concat(extraPoints); } this.previousPoints = <PointData[]>extend([], this.currentPoints, null, true); } public fadeOut(data: PointData[]): void { const svgElement: HTMLElement = this.chart.enableCanvas ? this.getElement(this.element.id + '_tooltip_group') : this.getElement(this.element.id + '_tooltip_svg'); const isTooltip: boolean = (svgElement && parseInt(svgElement.getAttribute('opacity'), 10) > 0); if (!isTooltip) { this.valueX = null; this.valueY = null; this.currentPoints = []; this.removeHighlight(); this.removeHighlightedMarker(data); this.svgTooltip = null; this.control.trigger('animationComplete', {}); } } /* * @hidden */ public removeHighlightedMarker(data: PointData[]): void { if (this.chart.markerRender) { for (const item of data) { removeElement(this.element.id + '_Series_' + item.series.index + '_Point_' + item.point.index + '_Trackball'); } this.chart.markerRender.removeHighlightedMarker(); } this.previousPoints = []; } // public triggerEvent(point: PointData | AccPointData, isFirst: boolean, textCollection: string, firstText: boolean = true): boolean { // let argsData: ITooltipRenderEventArgs = { // cancel: false, name: tooltipRender, text: textCollection, // point: point.point, series: point.series, textStyle: this.textStyle // }; // this.chart.trigger(tooltipRender, argsData); // if (!argsData.cancel) { // if (point.series.type === 'BoxAndWhisker') { // this.removeText(); // isFirst = true; // } // this.formattedText = this.formattedText.concat(argsData.text); // this.text = this.formattedText; // } // return !argsData.cancel; // } public removeText(): void { this.textElements = []; const element: Element = this.getElement(this.element.id + '_tooltip_group'); if (element && element.childNodes.length > 0) { while (element.lastChild && element.childNodes.length !== 1) { element.removeChild(element.lastChild); } } } public stopAnimation(): void { stopTimer(this.toolTipInterval); } /** * Removes the tooltip on mouse leave. * * @returns {void} * @private */ public removeTooltip(duration: number): void { const tooltipElement: HTMLElement = this.getElement(this.element.id + '_tooltip'); const tooltipTemplate: HTMLElement = tooltipElement ? this.getElement(tooltipElement.id + 'parent_template') : null; const isTemplateRendered: boolean = tooltipTemplate && tooltipTemplate.innerHTML !== '<div></div>'; this.stopAnimation(); // eslint-disable-next-line @typescript-eslint/no-explicit-any if ((this.chart as any).isReact && isTemplateRendered) { (this.chart as any).clearTemplate([tooltipTemplate.id], [0]); } if (tooltipElement && this.previousPoints.length > 0) { this.toolTipInterval = +setTimeout( (): void => { if (this.svgTooltip) { this.svgTooltip.fadeOut(); } }, duration); } } }
the_stack
import { CodeMaker } from 'codemaker'; import { Method, ClassType, Initializer } from 'jsii-reflect'; import { jsiiToPascalCase } from '../../../naming-util'; import * as comparators from '../comparators'; import { SpecialDependencies } from '../dependencies'; import { EmitContext } from '../emit-context'; import { Package } from '../package'; import { ClassConstructor, JSII_RT_ALIAS, MethodCall, slugify, StaticGetProperty, StaticSetProperty, } from '../runtime'; import { getMemberDependencies, getParamDependencies } from '../util'; import { GoType } from './go-type'; import { GoTypeRef } from './go-type-reference'; import { GoInterface } from './interface'; import { GoMethod, GoProperty, GoTypeMember } from './type-member'; /* * GoClass wraps a Typescript class as a Go custom struct type */ export class GoClass extends GoType<ClassType> { public readonly methods: ClassMethod[]; public readonly staticMethods: StaticMethod[]; public readonly properties: GoProperty[]; public readonly staticProperties: GoProperty[]; private _extends?: GoClass | null; private _implements?: readonly GoInterface[]; private readonly initializer?: GoClassConstructor; public constructor(pkg: Package, type: ClassType) { super(pkg, type); const methods = new Array<ClassMethod>(); const staticMethods = new Array<StaticMethod>(); for (const method of type.allMethods) { if (method.static) { staticMethods.push(new StaticMethod(this, method)); } else { methods.push(new ClassMethod(this, method)); } } // Ensure consistent order, mostly cosmetic. this.methods = methods.sort(comparators.byName); this.staticMethods = staticMethods.sort(comparators.byName); const properties = new Array<GoProperty>(); const staticProperties = new Array<GoProperty>(); for (const prop of type.allProperties) { if (prop.static) { staticProperties.push(new GoProperty(this, prop)); } else { properties.push(new GoProperty(this, prop)); } } // Ensure consistent order, mostly cosmetic. this.properties = properties.sort(comparators.byName); this.staticProperties = staticProperties.sort(comparators.byName); if (type.initializer) { this.initializer = new GoClassConstructor(this, type.initializer); } } public get extends(): GoClass | undefined { // Cannot compute in constructor, as dependencies may not have finished // resolving just yet. if (this._extends === undefined) { this._extends = this.type.base ? (this.pkg.root.findType(this.type.base.fqn) as GoClass) : null; } return this._extends == null ? undefined : this._extends; } public get implements(): readonly GoInterface[] { // Cannot compute in constructor, as dependencies may not have finished // resolving just yet. if (this._implements === undefined) { this._implements = this.type.interfaces .map((iface) => this.pkg.root.findType(iface.fqn) as GoInterface) // Ensure consistent order, mostly cosmetic. .sort((l, r) => l.fqn.localeCompare(r.fqn)); } return this._implements; } public get baseTypes(): ReadonlyArray<GoClass | GoInterface> { return [...(this.extends ? [this.extends] : []), ...this.implements]; } public emit(context: EmitContext): void { this.emitInterface(context); this.emitStruct(context); this.emitGetters(context); if (this.initializer) { this.initializer.emit(context); } this.emitSetters(context); for (const method of this.staticMethods) { method.emit(context); } for (const prop of this.staticProperties) { this.emitStaticProperty(context, prop); } for (const method of this.methods) { method.emit(context); } } public emitRegistration(code: CodeMaker): void { code.open(`${JSII_RT_ALIAS}.RegisterClass(`); code.line(`"${this.fqn}",`); code.line(`reflect.TypeOf((*${this.name})(nil)).Elem(),`); const allMembers = [ ...this.type.allMethods .filter((method) => !method.static) .map((method) => new ClassMethod(this, method)), ...this.type.allProperties .filter((property) => !property.static) .map((property) => new GoProperty(this, property)), ].sort(comparators.byName); if (allMembers.length === 0) { code.line('nil, // no members'); } else { code.open(`[]${JSII_RT_ALIAS}.Member{`); for (const member of allMembers) { code.line(`${member.override},`); } code.close('},'); } this.emitProxyMakerFunction(code, this.baseTypes); code.close(')'); } public get members(): GoTypeMember[] { return [ ...(this.initializer ? [this.initializer] : []), ...this.methods, ...this.properties, ...this.staticMethods, ...this.staticProperties, ]; } public get specialDependencies(): SpecialDependencies { return { runtime: this.initializer != null || this.members.length > 0, init: this.initializer != null || this.members.some((m) => m.specialDependencies.init), internal: this.baseTypes.some((base) => this.pkg.isExternalType(base)), time: !!this.initializer?.specialDependencies.time || this.members.some((m) => m.specialDependencies.time), }; } protected emitInterface(context: EmitContext): void { const { code, documenter } = context; documenter.emit(this.type.docs, this.apiLocation); code.openBlock(`type ${this.name} interface`); // embed extended interfaces if (this.extends) { code.line( new GoTypeRef(this.pkg.root, this.extends.type.reference).scopedName( this.pkg, ), ); } for (const iface of this.implements) { code.line( new GoTypeRef(this.pkg.root, iface.type.reference).scopedName(this.pkg), ); } for (const property of this.properties) { property.emitGetterDecl(context); property.emitSetterDecl(context); } for (const method of this.methods) { method.emitDecl(context); } code.closeBlock(); code.line(); } private emitGetters(context: EmitContext) { if (this.properties.length === 0) { return; } for (const property of this.properties) { property.emitGetterProxy(context); } context.code.line(); } private emitStruct({ code }: EmitContext): void { code.line(`// The jsii proxy struct for ${this.name}`); code.openBlock(`type ${this.proxyName} struct`); // Make sure this is not 0-width if (this.baseTypes.length === 0) { code.line('_ byte // padding'); } else { for (const base of this.baseTypes) { code.line(this.pkg.resolveEmbeddedType(base).embed); } } code.closeBlock(); code.line(); } private emitStaticProperty({ code }: EmitContext, prop: GoProperty): void { const getCaller = new StaticGetProperty(prop); const propertyName = jsiiToPascalCase(prop.name); const name = `${this.name}_${propertyName}`; code.openBlock(`func ${name}() ${prop.returnType}`); getCaller.emit(code); code.closeBlock(); code.line(); if (!prop.immutable) { const setCaller = new StaticSetProperty(prop); const name = `${this.name}_Set${propertyName}`; code.openBlock(`func ${name}(val ${prop.returnType})`); setCaller.emit(code); code.closeBlock(); code.line(); } } // emits the implementation of the setters for the struct private emitSetters(context: EmitContext): void { for (const property of this.properties) { property.emitSetterProxy(context); } } public get dependencies(): Package[] { // need to add dependencies of method arguments and constructor arguments return [ ...this.baseTypes.map((ref) => ref.pkg), ...getMemberDependencies(this.members), ...getParamDependencies(this.members.filter(isGoMethod)), ]; } /* * Get fqns of interfaces the class implements */ public get interfaces(): string[] { return this.type.interfaces.map((iFace) => iFace.fqn); } } export class GoClassConstructor extends GoMethod { private readonly constructorRuntimeCall: ClassConstructor; public constructor( public readonly parent: GoClass, private readonly type: Initializer, ) { super(parent, type); this.constructorRuntimeCall = new ClassConstructor(this); } public get specialDependencies(): SpecialDependencies { return { runtime: true, init: true, internal: false, time: this.parameters.some((p) => p.reference.specialDependencies.time), }; } public emit(context: EmitContext) { // Abstract classes cannot be directly created if (!this.parent.type.abstract) { this.emitNew(context); } // Subclassable classes (the default) get an _Overrides constructor if (this.parent.type.spec.docs?.subclassable ?? true) { this.emitOverride(context); } } private emitNew({ code, documenter }: EmitContext) { const constr = `New${this.parent.name}`; const paramString = this.parameters.length === 0 ? '' : this.parameters.map((p) => p.toString()).join(', '); documenter.emit(this.type.docs, this.apiLocation); code.openBlock(`func ${constr}(${paramString}) ${this.parent.name}`); this.constructorRuntimeCall.emit(code); code.closeBlock(); code.line(); } private emitOverride({ code, documenter }: EmitContext) { const constr = `New${this.parent.name}_Override`; const params = this.parameters.map((p) => p.toString()); const instanceVar = slugify(this.parent.name[0].toLowerCase(), params); params.unshift(`${instanceVar} ${this.parent.name}`); documenter.emit(this.type.docs, this.apiLocation); code.openBlock(`func ${constr}(${params.join(', ')})`); this.constructorRuntimeCall.emitOverride(code, instanceVar); code.closeBlock(); code.line(); } } export class ClassMethod extends GoMethod { public readonly runtimeCall: MethodCall; public constructor( public readonly parent: GoClass, public readonly method: Method, ) { super(parent, method); this.runtimeCall = new MethodCall(this); } /* emit generates method implementation on the class */ public emit({ code }: EmitContext) { const name = this.name; const returnTypeString = this.reference?.void ? '' : ` ${this.returnType}`; code.openBlock( `func (${this.instanceArg} *${ this.parent.proxyName }) ${name}(${this.paramString()})${returnTypeString}`, ); this.runtimeCall.emit(code); code.closeBlock(); code.line(); } /* emitDecl generates method declaration in the class interface */ public emitDecl({ code, documenter }: EmitContext) { const returnTypeString = this.reference?.void ? '' : ` ${this.returnType}`; documenter.emit(this.method.docs, this.apiLocation); code.line(`${this.name}(${this.paramString()})${returnTypeString}`); } public get instanceArg(): string { return this.parent.name.substring(0, 1).toLowerCase(); } public get specialDependencies(): SpecialDependencies { return { runtime: true, init: this.method.static, internal: false, time: !!this.parameters.some((p) => p.reference.specialDependencies.time) || !!this.reference?.specialDependencies.time, }; } } export class StaticMethod extends ClassMethod { public constructor( public readonly parent: GoClass, public readonly method: Method, ) { super(parent, method); } public emit({ code, documenter }: EmitContext) { const name = `${this.parent.name}_${this.name}`; const returnTypeString = this.reference?.void ? '' : ` ${this.returnType}`; documenter.emit(this.method.docs, this.apiLocation); code.openBlock(`func ${name}(${this.paramString()})${returnTypeString}`); this.runtimeCall.emit(code); code.closeBlock(); code.line(); } } function isGoMethod(m: GoTypeMember): m is GoMethod { return m instanceof GoMethod; }
the_stack
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnDestroy, Output, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import { ConnectedPosition, FlexibleConnectedPositionStrategy, Overlay, OverlayConfig, OverlayPositionBuilder, OverlayRef, } from '@angular/cdk/overlay'; import { TemplatePortal } from '@angular/cdk/portal'; import { fromEvent, Observable, Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; import { ContentChild } from '@angular/core'; import { MdbDropdownToggleDirective } from './dropdown-toggle.directive'; import { MdbDropdownMenuDirective } from './dropdown-menu.directive'; import { animate, state, style, transition, trigger, AnimationEvent } from '@angular/animations'; import { BreakpointObserver } from '@angular/cdk/layout'; import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion'; @Component({ // eslint-disable-next-line @angular-eslint/component-selector selector: '[mdbDropdown]', templateUrl: 'dropdown.component.html', changeDetection: ChangeDetectionStrategy.OnPush, animations: [ trigger('fade', [ state('visible', style({ opacity: 1 })), state('hidden', style({ opacity: 0 })), transition('visible => hidden', animate('150ms linear')), transition('hidden => visible', [style({ opacity: 0 }), animate('150ms linear')]), ]), ], }) // eslint-disable-next-line @angular-eslint/component-class-suffix export class MdbDropdownDirective implements OnDestroy, AfterContentInit { @ViewChild('dropdownTemplate') _template: TemplateRef<any>; @ContentChild(MdbDropdownToggleDirective, { read: ElementRef }) _dropdownToggle: ElementRef; @ContentChild(MdbDropdownMenuDirective, { read: ElementRef }) _dropdownMenu: ElementRef; @Input() get animation(): boolean { return this._animation; } set animation(value: boolean) { this._animation = coerceBooleanProperty(value); } private _animation = true; @Input() offset = 0; @Output() dropdownShow: EventEmitter<MdbDropdownDirective> = new EventEmitter(); @Output() dropdownShown: EventEmitter<MdbDropdownDirective> = new EventEmitter(); @Output() dropdownHide: EventEmitter<MdbDropdownDirective> = new EventEmitter(); @Output() dropdownHidden: EventEmitter<MdbDropdownDirective> = new EventEmitter(); private _overlayRef: OverlayRef; private _portal: TemplatePortal; private _open = false; private _isDropUp: boolean; private _isDropStart: boolean; private _isDropEnd: boolean; private _isDropdownMenuEnd: boolean; private _xPosition: string; private _breakpoints = { isSm: this._breakpointObserver.isMatched('(min-width: 576px)'), isMd: this._breakpointObserver.isMatched('(min-width: 768px)'), isLg: this._breakpointObserver.isMatched('(min-width: 992px)'), isXl: this._breakpointObserver.isMatched('(min-width: 1200px)'), isXxl: this._breakpointObserver.isMatched('(min-width: 1400px)'), }; readonly _destroy$: Subject<void> = new Subject<void>(); _breakpointSubscription: any; _animationState = 'hidden'; constructor( private _overlay: Overlay, private _overlayPositionBuilder: OverlayPositionBuilder, private _elementRef: ElementRef, private _vcr: ViewContainerRef, private _breakpointObserver: BreakpointObserver, private _cdRef: ChangeDetectorRef ) {} ngAfterContentInit(): void { this._bindDropdownToggleClick(); } ngOnDestroy(): void { if (this._overlayRef) { this._overlayRef.detach(); this._overlayRef.dispose(); } this._destroy$.next(); this._destroy$.complete(); } private _bindDropdownToggleClick(): void { fromEvent(this._dropdownToggle.nativeElement, 'click') .pipe(takeUntil(this._destroy$)) .subscribe(() => this.toggle()); } private _createOverlayConfig(): OverlayConfig { return new OverlayConfig({ hasBackdrop: false, scrollStrategy: this._overlay.scrollStrategies.reposition(), positionStrategy: this._createPositionStrategy(), }); } private _createOverlay(): void { this._overlayRef = this._overlay.create(this._createOverlayConfig()); } private _createPositionStrategy(): FlexibleConnectedPositionStrategy { const positionStrategy = this._overlayPositionBuilder .flexibleConnectedTo(this._dropdownToggle) .withPositions(this._getPosition()) .withFlexibleDimensions(false); return positionStrategy; } private _getPosition(): ConnectedPosition[] { this._isDropUp = this._elementRef.nativeElement.classList.contains('dropup'); this._isDropStart = this._elementRef.nativeElement.classList.contains('dropstart'); this._isDropEnd = this._elementRef.nativeElement.classList.contains('dropend'); this._isDropdownMenuEnd = this._dropdownMenu.nativeElement.classList.contains('dropdown-menu-end'); this._xPosition = this._isDropdownMenuEnd ? 'end' : 'start'; const regex = new RegExp(/dropdown-menu-(sm|md|lg|xl|xxl)-(start|end)/, 'g'); const responsiveClass = this._dropdownMenu.nativeElement.className.match(regex); if (responsiveClass) { this._subscribeBrakpoints(); const positionRegex = new RegExp(/start|end/, 'g'); const breakpointRegex = new RegExp(/(sm|md|lg|xl|xxl)/, 'g'); const dropdownPosition = positionRegex.exec(responsiveClass)[0]; const breakpoint = breakpointRegex.exec(responsiveClass)[0]; switch (true) { case breakpoint === 'xxl' && this._breakpoints.isXxl: this._xPosition = dropdownPosition; break; case breakpoint === 'xl' && this._breakpoints.isXl: this._xPosition = dropdownPosition; break; case breakpoint === 'lg' && this._breakpoints.isLg: this._xPosition = dropdownPosition; break; case breakpoint === 'md' && this._breakpoints.isMd: this._xPosition = dropdownPosition; break; case breakpoint === 'sm' && this._breakpoints.isSm: this._xPosition = dropdownPosition; break; default: break; } } let position; const positionDropup = { originX: this._xPosition, originY: 'top', overlayX: this._xPosition, overlayY: 'bottom', offsetY: -this.offset, }; const positionDropdown = { originX: this._xPosition, originY: 'bottom', overlayX: this._xPosition, overlayY: 'top', offsetY: this.offset, }; const positionDropstart = { originX: 'start', originY: 'top', overlayX: 'end', overlayY: 'top', offsetX: this.offset, }; const positionDropend = { originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top', offsetX: -this.offset, }; switch (true) { case this._isDropEnd: position = [positionDropend, positionDropstart]; break; case this._isDropStart: position = [positionDropstart, positionDropend]; break; case this._isDropUp: position = [positionDropup, positionDropdown]; break; default: position = [positionDropdown, positionDropup]; break; } return position; } private _listenToOutSideCick( overlayRef: OverlayRef, origin: HTMLElement ): Observable<MouseEvent> { return fromEvent(document, 'click').pipe( filter((event: MouseEvent) => { const target = event.target as HTMLElement; const isInsideMenu = this._dropdownMenu.nativeElement.contains(target); const notTogglerIcon = !this._dropdownToggle.nativeElement.contains(target); const notCustomContent = !isInsideMenu || (target.classList && target.classList.contains('dropdown-item')); const notOrigin = target !== origin; return notOrigin && notTogglerIcon && notCustomContent; }), takeUntil(overlayRef.detachments()) ); } public onAnimationEnd(event: AnimationEvent): void { if (event.fromState === 'visible' && event.toState === 'hidden') { this._overlayRef.detach(); this._open = false; this.dropdownHidden.emit(this); } if (event.fromState === 'hidden' && event.toState === 'visible') { this.dropdownShown.emit(this); } } private _subscribeBrakpoints(): void { const brakpoints = [ '(min-width: 576px)', '(min-width: 768px)', '(min-width: 992px)', '(min-width: 1200px)', '(min-width: 1400px)', ]; this._breakpointSubscription = this._breakpointObserver .observe(brakpoints) .pipe(takeUntil(this._destroy$)) .subscribe((result) => { Object.keys(this._breakpoints).forEach((key, index) => { const brakpointValue = brakpoints[index]; const newBreakpoint = result.breakpoints[brakpointValue]; const isBreakpointChanged = newBreakpoint !== this._breakpoints[key]; if (!isBreakpointChanged) { return; } this._breakpoints[key] = newBreakpoint; if (this._open) { this._overlayRef.updatePositionStrategy(this._createPositionStrategy()); } }); }); } show(): void { this._cdRef.markForCheck(); if (this._open) { return; } if (!this._overlayRef) { this._createOverlay(); } this._portal = new TemplatePortal(this._template, this._vcr); this.dropdownShow.emit(this); this._open = true; this._overlayRef.attach(this._portal); this._listenToOutSideCick(this._overlayRef, this._dropdownToggle.nativeElement).subscribe(() => this.hide() ); this._animationState = 'visible'; } hide(): void { this._cdRef.markForCheck(); if (!this._open) { return; } this.dropdownHide.emit(this); this._animationState = 'hidden'; } toggle(): void { this._cdRef.markForCheck(); if (this._open) { this.hide(); } else { this.show(); } } static ngAcceptInputType_animation: BooleanInput; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormImportfile { interface tab_failureTab_Sections { failureSection: DevKit.Controls.Section; } interface tab_partialFailureTab_Sections { partialFailureSection: DevKit.Controls.Section; } interface tab_successTab_Sections { successSection: DevKit.Controls.Section; } interface tab_failureTab extends DevKit.Controls.ITab { Section: tab_failureTab_Sections; } interface tab_partialFailureTab extends DevKit.Controls.ITab { Section: tab_partialFailureTab_Sections; } interface tab_successTab extends DevKit.Controls.ITab { Section: tab_successTab_Sections; } interface Tabs { failureTab: tab_failureTab; partialFailureTab: tab_partialFailureTab; successTab: tab_successTab; } interface Body { Tab: Tabs; /** Shows the date and time when the import associated with the import file was completed. */ CompletedOn: DevKit.Controls.Date; /** Shows who created the record. */ CreatedBy: DevKit.Controls.Lookup; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn: DevKit.Controls.DateTime; /** Select whether duplicate-detection rules should be run against the import job. */ EnableDuplicateDetection: DevKit.Controls.Boolean; /** Shows the number of records in the import file that cannot be imported. */ FailureCount: DevKit.Controls.Integer; import_Logs_Failure: DevKit.Controls.ActionCards; import_Logs_Failures: DevKit.Controls.ActionCards; import_Logs_Succes: DevKit.Controls.ActionCards; /** Choose a data map to match the import file and its column headers with the record types and fields in Microsoft Dynamics 365. If the column headers in the file match the display names of the target fields in Microsoft Dynamics 365, we import the data automatically. If not, you can manually define matches during import. */ ImportMapId: DevKit.Controls.Lookup; /** Shows the name of the import file. This name is based on the name of the uploaded file. */ Name: DevKit.Controls.String; /** Shows the number of records in this file that had failures during the import. */ PartialFailureCount: DevKit.Controls.Integer; /** Choose the user that the records created during the import job should be assigned to. */ RecordsOwnerId: DevKit.Controls.Lookup; /** Shows the size of the import file, in kilobytes. */ Size: DevKit.Controls.String; /** Shows the name of the data source file uploaded in the import job. */ Source: DevKit.Controls.String; /** Shows the reason code that explains the import file's status to identify the stage of the import process, from parsing the data to completed. */ StatusCode: DevKit.Controls.OptionSet; /** Shows the number of records in the import file that are imported successfully. */ SuccessCount: DevKit.Controls.Integer; /** Select the target record type (entity) for the records that will be created during the import job. */ TargetEntityName: DevKit.Controls.String; /** Shows the total number of records in the import file. */ TotalCount: DevKit.Controls.Integer; } interface Footer extends DevKit.Controls.IFooter { /** Shows the reason code that explains the import file's status to identify the stage of the import process, from parsing the data to completed. */ StatusCode: DevKit.Controls.OptionSet; } } class FormImportfile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Importfile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Importfile */ Body: DevKit.FormImportfile.Body; /** The Footer section of form Importfile */ Footer: DevKit.FormImportfile.Footer; } class ImportFileApi { /** * DynamicsCrm.DevKit ImportFileApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Shows the secondary column headers. The additional headers are used during the process of transforming the import file into import data records. */ AdditionalHeaderRow: DevKit.WebApi.StringValueReadonly; /** Shows the date and time when the import associated with the import file was completed. */ CompletedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** Stores the content of the import file, stored as comma-separated values. */ Content: DevKit.WebApi.StringValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Select the single-character data delimiter used in the import file. This is typically a single or double quotation mark. */ DataDelimiterCode: DevKit.WebApi.OptionSetValue; /** Select whether duplicate-detection rules should be run against the import job. */ EnableDuplicateDetection: DevKit.WebApi.BooleanValue; /** Unique identifier of the Alternate key Id */ EntityKeyId: DevKit.WebApi.GuidValue; /** Shows the number of records in the import file that cannot be imported. */ FailureCount: DevKit.WebApi.IntegerValueReadonly; /** Select the character that is used to separate each field in the import file. Typically, it is a comma. */ FieldDelimiterCode: DevKit.WebApi.OptionSetValue; /** Shows the type of source file that is uploaded for import. */ FileTypeCode: DevKit.WebApi.OptionSetValue; /** Shows a list of each column header in the import file separated by a comma. The header is used for parsing the file during the import job. */ HeaderRow: DevKit.WebApi.StringValueReadonly; /** Unique identifier of the import file. */ ImportFileId: DevKit.WebApi.GuidValue; /** Choose the import job that the file was uploaded for. */ ImportId: DevKit.WebApi.LookupValue; /** Choose a data map to match the import file and its column headers with the record types and fields in Microsoft Dynamics 365. If the column headers in the file match the display names of the target fields in Microsoft Dynamics 365, we import the data automatically. If not, you can manually define matches during import. */ ImportMapId: DevKit.WebApi.LookupValue; /** Select whether the first row of the import file contains column headings, which are used for data mapping during the import job. */ IsFirstRowHeader: DevKit.WebApi.BooleanValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the name of the import file. This name is based on the name of the uploaded file. */ Name: DevKit.WebApi.StringValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the import file. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the import file. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Shows the prefix applied to each column after the import file is parsed. */ ParsedTableColumnPrefix: DevKit.WebApi.StringValueReadonly; /** Shows the number of columns included in the parsed import file. */ ParsedTableColumnsNumber: DevKit.WebApi.IntegerValueReadonly; /** Shows the name of the table that contains the parsed data from the import file. */ ParsedTableName: DevKit.WebApi.StringValueReadonly; /** Shows the number of records in this file that had failures during the import. */ PartialFailureCount: DevKit.WebApi.IntegerValueReadonly; /** Tells whether the import file should be ignored or processed during the import. */ ProcessCode: DevKit.WebApi.OptionSetValue; /** Shows the import file's processing status code. This indicates whether the data in the import file has been parsed, transformed, or imported. */ ProcessingStatus: DevKit.WebApi.OptionSetValueReadonly; /** Shows the progress code for the processing of the import file. This field is used when a paused import job is resumed. */ ProgressCounter: DevKit.WebApi.IntegerValueReadonly; /** Choose the user that the records created during the import job should be assigned to. */ recordsownerid_systemuser: DevKit.WebApi.LookupValue; /** Choose the user that the records created during the import job should be assigned to. */ recordsownerid_team: DevKit.WebApi.LookupValue; /** Shows the columns that are mapped to a related record type (entity) of the primary record type (entity) included in the import file. */ RelatedEntityColumns: DevKit.WebApi.StringValue; /** Shows the size of the import file, in kilobytes. */ Size: DevKit.WebApi.StringValue; /** Shows the name of the data source file uploaded in the import job. */ Source: DevKit.WebApi.StringValue; /** Shows the record type (entity) of the source data. */ SourceEntityName: DevKit.WebApi.StringValue; /** Shows the status of the import file record. By default, all records are active and can't be deactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Shows the reason code that explains the import file's status to identify the stage of the import process, from parsing the data to completed. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Shows the number of records in the import file that are imported successfully. */ SuccessCount: DevKit.WebApi.IntegerValueReadonly; /** Select the target record type (entity) for the records that will be created during the import job. */ TargetEntityName: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the total number of records in the import file. */ TotalCount: DevKit.WebApi.IntegerValueReadonly; /** Select the value which is used for identify the upsert mode. By Default, it is a Create. */ UpsertModeCode: DevKit.WebApi.OptionSetValue; /** Tells whether an automatic system map was applied to the import file, which automatically maps the import data to the target entity in Microsoft Dynamics 365. */ UseSystemMap: DevKit.WebApi.BooleanValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; } } declare namespace OptionSet { namespace ImportFile { enum DataDelimiterCode { /** 1 */ DoubleQuote, /** 2 */ None, /** 3 */ SingleQuote } enum FieldDelimiterCode { /** 1 */ Colon, /** 2 */ Comma, /** 4 */ Semicolon, /** 3 */ Tab } enum FileTypeCode { /** 2 */ Attachment, /** 0 */ CSV, /** 3 */ XLSX, /** 1 */ XML_Spreadsheet_2003 } enum ProcessCode { /** 2 */ Ignore, /** 3 */ Internal, /** 1 */ Process } enum ProcessingStatus { /** 4 */ Complex_Transformation, /** 11 */ Import_Complete, /** 9 */ Import_Pass_1, /** 10 */ Import_Pass_2, /** 5 */ Lookup_Transformation, /** 1 */ Not_Started, /** 7 */ Owner_Transformation, /** 2 */ Parsing, /** 3 */ Parsing_Complete, /** 6 */ Picklist_Transformation, /** 12 */ Primary_Key_Transformation, /** 8 */ Transformation_Complete } enum StateCode { /** 0 */ Active } enum StatusCode { /** 4 */ Completed, /** 5 */ Failed, /** 3 */ Importing, /** 1 */ Parsing, /** 0 */ Submitted, /** 2 */ Transforming } enum UpsertModeCode { /** 0 */ Create, /** 2 */ Ignore, /** 1 */ Update } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Importfile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [appflow](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonappflow.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Appflow extends PolicyStatement { public servicePrefix = 'appflow'; /** * Statement provider for service [appflow](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonappflow.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create a login profile to be used with Amazon AppFlow flows * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_CreateConnectorProfile.html */ public toCreateConnectorProfile() { return this.to('CreateConnectorProfile'); } /** * Grants permission to create an Amazon AppFlow flow * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_CreateFlow.html */ public toCreateFlow() { return this.to('CreateFlow'); } /** * Grants permission to delete a login profile configured in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeConnectorProfiles.html */ public toDeleteConnectorProfile() { return this.to('DeleteConnectorProfile'); } /** * Grants permission to delete an Amazon AppFlow flow * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DeleteFlow.html */ public toDeleteFlow() { return this.to('DeleteFlow'); } /** * Grants permission to describe all fields for an object in a login profile configured in Amazon AppFlow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeConnectorEntity.html */ public toDescribeConnectorEntity() { return this.to('DescribeConnectorEntity'); } /** * Grants permission to describe all fields for an object in a login profile configured in Amazon AppFlow (Console Only) * * Access Level: Read * * https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html#appflow-api-actions */ public toDescribeConnectorFields() { return this.to('DescribeConnectorFields'); } /** * Grants permission to describe all login profiles configured in Amazon AppFlow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeConnectorProfiles.html */ public toDescribeConnectorProfiles() { return this.to('DescribeConnectorProfiles'); } /** * Grants permission to describe all connectors supported by Amazon AppFlow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeConnectors.html */ public toDescribeConnectors() { return this.to('DescribeConnectors'); } /** * Grants permission to describe a specific flow configured in Amazon AppFlow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeFlow.html */ public toDescribeFlow() { return this.to('DescribeFlow'); } /** * Grants permission to describe all flow executions for a flow configured in Amazon AppFlow (Console Only) * * Access Level: Read * * https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html#appflow-api-actions */ public toDescribeFlowExecution() { return this.to('DescribeFlowExecution'); } /** * Grants permission to describe all flow executions for a flow configured in Amazon AppFlow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_DescribeFlowExecutionRecords.html */ public toDescribeFlowExecutionRecords() { return this.to('DescribeFlowExecutionRecords'); } /** * Grants permission to describe all flows configured in Amazon AppFlow (Console Only) * * Access Level: Read * * https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html#appflow-api-actions */ public toDescribeFlows() { return this.to('DescribeFlows'); } /** * Grants permission to list all objects for a login profile configured in Amazon AppFlow * * Access Level: List * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_ListConnectorEntities.html */ public toListConnectorEntities() { return this.to('ListConnectorEntities'); } /** * Grants permission to list all objects for a login profile configured in Amazon AppFlow (Console Only) * * Access Level: Read * * https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html#appflow-api-actions */ public toListConnectorFields() { return this.to('ListConnectorFields'); } /** * Grants permission to list all flows configured in Amazon AppFlow * * Access Level: List * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_ListFlows.html */ public toListFlows() { return this.to('ListFlows'); } /** * Grants permission to list tags for a flow * * Access Level: Read * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to run a flow configured in Amazon AppFlow (Console Only) * * Access Level: Write * * https://docs.aws.amazon.com/appflow/latest/userguide/identity-access-management.html#appflow-api-actions */ public toRunFlow() { return this.to('RunFlow'); } /** * Grants permission to activate (for scheduled and event-triggered flows) or run (for on-demand flows) a flow configured in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_StartFlow.html */ public toStartFlow() { return this.to('StartFlow'); } /** * Grants permission to deactivate a scheduled or event-triggered flow configured in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_StopFlow.html */ public toStopFlow() { return this.to('StopFlow'); } /** * Grants permission to tag a flow * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag a flow * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a login profile configured in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_UpdateConnectorProfile.html */ public toUpdateConnectorProfile() { return this.to('UpdateConnectorProfile'); } /** * Grants permission to update a flow configured in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_UpdateFlow.html */ public toUpdateFlow() { return this.to('UpdateFlow'); } /** * Grants permission to use a connector profile while creating a flow in Amazon AppFlow * * Access Level: Write * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_UseConnectorProfile.html */ public toUseConnectorProfile() { return this.to('UseConnectorProfile'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateConnectorProfile", "CreateFlow", "DeleteConnectorProfile", "DeleteFlow", "RunFlow", "StartFlow", "StopFlow", "UpdateConnectorProfile", "UpdateFlow", "UseConnectorProfile" ], "Read": [ "DescribeConnectorEntity", "DescribeConnectorFields", "DescribeConnectorProfiles", "DescribeConnectors", "DescribeFlow", "DescribeFlowExecution", "DescribeFlowExecutionRecords", "DescribeFlows", "ListConnectorFields", "ListTagsForResource" ], "List": [ "ListConnectorEntities", "ListFlows" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type connectorprofile to the statement * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_ConnectorProfile.html * * @param profileName - Identifier for the profileName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onConnectorprofile(profileName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appflow:${Region}:${Account}:connectorprofile/${ProfileName}'; arn = arn.replace('${ProfileName}', profileName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type flow to the statement * * https://docs.aws.amazon.com/appflow/1.0/APIReference/API_FlowDefinition.html * * @param flowName - Identifier for the flowName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFlow(flowName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appflow:${Region}:${Account}:flow/${FlowName}'; arn = arn.replace('${FlowName}', flowName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { StorageClientContext } from "../storageClientContext"; import { FileCreateOptionalParams, FileCreateResponse, FileDownloadOptionalParams, FileDownloadResponse, FileGetPropertiesOptionalParams, FileGetPropertiesResponse, FileDeleteOptionalParams, FileDeleteResponse, FileSetHttpHeadersOptionalParams, FileSetHttpHeadersResponse, FileSetMetadataOptionalParams, FileSetMetadataResponse, FileAcquireLeaseOptionalParams, FileAcquireLeaseResponse, FileReleaseLeaseOptionalParams, FileReleaseLeaseResponse, FileChangeLeaseOptionalParams, FileChangeLeaseResponse, FileBreakLeaseOptionalParams, FileBreakLeaseResponse, FileRangeWriteType, FileUploadRangeOptionalParams, FileUploadRangeResponse, FileUploadRangeFromURLOptionalParams, FileUploadRangeFromURLResponse, FileGetRangeListOptionalParams, FileGetRangeListResponse, FileStartCopyOptionalParams, FileStartCopyResponse, FileAbortCopyOptionalParams, FileAbortCopyResponse, FileListHandlesOptionalParams, FileListHandlesResponse, FileForceCloseHandlesOptionalParams, FileForceCloseHandlesResponse } from "../models"; /** Class representing a File. */ export class File { private readonly client: StorageClientContext; /** * Initialize a new instance of the class File class. * @param client Reference to the service client */ constructor(client: StorageClientContext) { this.client = client; } /** * Creates a new file or replaces a file. Note it only initializes the file with no content. * @param fileContentLength Specifies the maximum size for the file, up to 4 TB. * @param fileAttributes If specified, the provided file attributes shall be set. Default value: * ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreatedOn Creation time for the file/directory. Default value: Now. * @param fileLastWriteOn Last write time for the file/directory. Default value: Now. * @param options The options parameters. */ create( fileContentLength: number, fileAttributes: string, fileCreatedOn: string, fileLastWriteOn: string, options?: FileCreateOptionalParams ): Promise<FileCreateResponse> { const operationArguments: coreHttp.OperationArguments = { fileContentLength, fileAttributes, fileCreatedOn, fileLastWriteOn, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createOperationSpec ) as Promise<FileCreateResponse>; } /** * Reads or downloads a file from the system, including its metadata and properties. * @param options The options parameters. */ download( options?: FileDownloadOptionalParams ): Promise<FileDownloadResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, downloadOperationSpec ) as Promise<FileDownloadResponse>; } /** * Returns all user-defined metadata, standard HTTP properties, and system properties for the file. It * does not return the content of the file. * @param options The options parameters. */ getProperties( options?: FileGetPropertiesOptionalParams ): Promise<FileGetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getPropertiesOperationSpec ) as Promise<FileGetPropertiesResponse>; } /** * removes the file from the storage account. * @param options The options parameters. */ delete(options?: FileDeleteOptionalParams): Promise<FileDeleteResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, deleteOperationSpec ) as Promise<FileDeleteResponse>; } /** * Sets HTTP headers on the file. * @param fileAttributes If specified, the provided file attributes shall be set. Default value: * ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreatedOn Creation time for the file/directory. Default value: Now. * @param fileLastWriteOn Last write time for the file/directory. Default value: Now. * @param options The options parameters. */ setHttpHeaders( fileAttributes: string, fileCreatedOn: string, fileLastWriteOn: string, options?: FileSetHttpHeadersOptionalParams ): Promise<FileSetHttpHeadersResponse> { const operationArguments: coreHttp.OperationArguments = { fileAttributes, fileCreatedOn, fileLastWriteOn, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setHttpHeadersOperationSpec ) as Promise<FileSetHttpHeadersResponse>; } /** * Updates user-defined metadata for the specified file. * @param options The options parameters. */ setMetadata( options?: FileSetMetadataOptionalParams ): Promise<FileSetMetadataResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setMetadataOperationSpec ) as Promise<FileSetMetadataResponse>; } /** * [Update] The Lease File operation establishes and manages a lock on a file for write and delete * operations * @param options The options parameters. */ acquireLease( options?: FileAcquireLeaseOptionalParams ): Promise<FileAcquireLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, acquireLeaseOperationSpec ) as Promise<FileAcquireLeaseResponse>; } /** * [Update] The Lease File operation establishes and manages a lock on a file for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ releaseLease( leaseId: string, options?: FileReleaseLeaseOptionalParams ): Promise<FileReleaseLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, releaseLeaseOperationSpec ) as Promise<FileReleaseLeaseResponse>; } /** * [Update] The Lease File operation establishes and manages a lock on a file for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ changeLease( leaseId: string, options?: FileChangeLeaseOptionalParams ): Promise<FileChangeLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, changeLeaseOperationSpec ) as Promise<FileChangeLeaseResponse>; } /** * [Update] The Lease File operation establishes and manages a lock on a file for write and delete * operations * @param options The options parameters. */ breakLease( options?: FileBreakLeaseOptionalParams ): Promise<FileBreakLeaseResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, breakLeaseOperationSpec ) as Promise<FileBreakLeaseResponse>; } /** * Upload a range of bytes to a file. * @param range Specifies the range of bytes to be written. Both the start and end of the range must be * specified. For an update operation, the range can be up to 4 MB in size. For a clear operation, the * range can be up to the value of the file's full size. The File service accepts only a single byte * range for the Range and 'x-ms-range' headers, and the byte range must be specified in the following * format: bytes=startByte-endByte. * @param fileRangeWrite Specify one of the following options: - Update: Writes the bytes specified by * the request body into the specified range. The Range and Content-Length headers must match to * perform the update. - Clear: Clears the specified range and releases the space used in storage for * that range. To clear a range, set the Content-Length header to zero, and set the Range header to a * value that indicates the range to clear, up to maximum file size. * @param contentLength Specifies the number of bytes being transmitted in the request body. When the * x-ms-write header is set to clear, the value of this header must be set to zero. * @param options The options parameters. */ uploadRange( range: string, fileRangeWrite: FileRangeWriteType, contentLength: number, options?: FileUploadRangeOptionalParams ): Promise<FileUploadRangeResponse> { const operationArguments: coreHttp.OperationArguments = { range, fileRangeWrite, contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, uploadRangeOperationSpec ) as Promise<FileUploadRangeResponse>; } /** * Upload a range of bytes to a file where the contents are read from a URL. * @param range Writes data to the specified byte range in the file. * @param copySource Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file * to another file within the same storage account, you may use Shared Key to authenticate the source * file. If you are copying a file from another storage account, or if you are copying a blob from the * same storage account or another storage account, then you must authenticate the source file or blob * using a shared access signature. If the source is a public blob, no authentication is required to * perform the copy operation. A file in a share snapshot can also be specified as a copy source. * @param contentLength Specifies the number of bytes being transmitted in the request body. When the * x-ms-write header is set to clear, the value of this header must be set to zero. * @param options The options parameters. */ uploadRangeFromURL( range: string, copySource: string, contentLength: number, options?: FileUploadRangeFromURLOptionalParams ): Promise<FileUploadRangeFromURLResponse> { const operationArguments: coreHttp.OperationArguments = { range, copySource, contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, uploadRangeFromURLOperationSpec ) as Promise<FileUploadRangeFromURLResponse>; } /** * Returns the list of valid ranges for a file. * @param options The options parameters. */ getRangeList( options?: FileGetRangeListOptionalParams ): Promise<FileGetRangeListResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getRangeListOperationSpec ) as Promise<FileGetRangeListResponse>; } /** * Copies a blob or file to a destination file within the storage account. * @param copySource Specifies the URL of the source file or blob, up to 2 KB in length. To copy a file * to another file within the same storage account, you may use Shared Key to authenticate the source * file. If you are copying a file from another storage account, or if you are copying a blob from the * same storage account or another storage account, then you must authenticate the source file or blob * using a shared access signature. If the source is a public blob, no authentication is required to * perform the copy operation. A file in a share snapshot can also be specified as a copy source. * @param options The options parameters. */ startCopy( copySource: string, options?: FileStartCopyOptionalParams ): Promise<FileStartCopyResponse> { const operationArguments: coreHttp.OperationArguments = { copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, startCopyOperationSpec ) as Promise<FileStartCopyResponse>; } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full * metadata. * @param copyId The copy identifier provided in the x-ms-copy-id header of the original Copy File * operation. * @param options The options parameters. */ abortCopy( copyId: string, options?: FileAbortCopyOptionalParams ): Promise<FileAbortCopyResponse> { const operationArguments: coreHttp.OperationArguments = { copyId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, abortCopyOperationSpec ) as Promise<FileAbortCopyResponse>; } /** * Lists handles for file * @param options The options parameters. */ listHandles( options?: FileListHandlesOptionalParams ): Promise<FileListHandlesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, listHandlesOperationSpec ) as Promise<FileListHandlesResponse>; } /** * Closes all handles open for given file * @param handleId Specifies handle ID opened on the file or directory to be closed. Asterisk (‘*’) is * a wildcard that specifies all handles. * @param options The options parameters. */ forceCloseHandles( handleId: string, options?: FileForceCloseHandlesOptionalParams ): Promise<FileForceCloseHandlesResponse> { const operationArguments: coreHttp.OperationArguments = { handleId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, forceCloseHandlesOperationSpec ) as Promise<FileForceCloseHandlesResponse>; } } // Operation Specifications const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); const createOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.FileCreateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileCreateExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.leaseId, Parameters.filePermission, Parameters.filePermissionKey1, Parameters.fileAttributes, Parameters.fileCreatedOn, Parameters.fileLastWriteOn, Parameters.fileContentLength, Parameters.fileTypeConstant, Parameters.fileContentType, Parameters.fileContentEncoding, Parameters.fileContentLanguage, Parameters.fileCacheControl, Parameters.fileContentMD5, Parameters.fileContentDisposition ], isXML: true, serializer: xmlSerializer }; const downloadOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: Mappers.FileDownloadHeaders }, 206: { bodyMapper: { type: { name: "Stream" }, serializedName: "parsedResponse" }, headersMapper: Mappers.FileDownloadHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileDownloadExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.range, Parameters.rangeGetContentMD5 ], isXML: true, serializer: xmlSerializer }; const getPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "HEAD", responses: { 200: { headersMapper: Mappers.FileGetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileGetPropertiesExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.shareSnapshot], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const deleteOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "DELETE", responses: { 202: { headersMapper: Mappers.FileDeleteHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileDeleteExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const setHttpHeadersOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.FileSetHttpHeadersHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileSetHttpHeadersExceptionHeaders } }, queryParameters: [Parameters.comp, Parameters.timeoutInSeconds], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.filePermission, Parameters.filePermissionKey1, Parameters.fileAttributes, Parameters.fileCreatedOn, Parameters.fileLastWriteOn, Parameters.fileContentType, Parameters.fileContentEncoding, Parameters.fileContentLanguage, Parameters.fileCacheControl, Parameters.fileContentMD5, Parameters.fileContentDisposition, Parameters.fileContentLength1 ], isXML: true, serializer: xmlSerializer }; const setMetadataOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.FileSetMetadataHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileSetMetadataExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp5], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.leaseId ], isXML: true, serializer: xmlSerializer }; const acquireLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.FileAcquireLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileAcquireLeaseExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.action, Parameters.duration, Parameters.proposedLeaseId, Parameters.requestId ], isXML: true, serializer: xmlSerializer }; const releaseLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.FileReleaseLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileReleaseLeaseExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.requestId, Parameters.action1, Parameters.leaseId1 ], isXML: true, serializer: xmlSerializer }; const changeLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.FileChangeLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileChangeLeaseExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.proposedLeaseId, Parameters.requestId, Parameters.leaseId1, Parameters.action2 ], isXML: true, serializer: xmlSerializer }; const breakLeaseOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 202: { headersMapper: Mappers.FileBreakLeaseHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileBreakLeaseExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.requestId, Parameters.action4 ], isXML: true, serializer: xmlSerializer }; const uploadRangeOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.FileUploadRangeHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileUploadRangeExceptionHeaders } }, requestBody: Parameters.body, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp11], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.leaseId, Parameters.contentType1, Parameters.accept3, Parameters.range1, Parameters.fileRangeWrite, Parameters.contentLength, Parameters.contentMD5 ], contentType: "application/octet-stream", isXML: true, serializer: xmlSerializer }; const uploadRangeFromURLOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.FileUploadRangeFromURLHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileUploadRangeFromURLExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.comp11], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.range1, Parameters.contentLength, Parameters.copySource, Parameters.sourceRange, Parameters.fileRangeWriteFromUrl, Parameters.sourceContentCrc64, Parameters.sourceIfMatchCrc64, Parameters.sourceIfNoneMatchCrc64, Parameters.copySourceAuthorization ], isXML: true, serializer: xmlSerializer }; const getRangeListOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ShareFileRangeList, headersMapper: Mappers.FileGetRangeListHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileGetRangeListExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.shareSnapshot, Parameters.comp12, Parameters.prevsharesnapshot ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.range ], isXML: true, serializer: xmlSerializer }; const startCopyOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 202: { headersMapper: Mappers.FileStartCopyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileStartCopyExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.leaseId, Parameters.filePermission, Parameters.filePermissionKey1, Parameters.copySource, Parameters.filePermissionCopyMode, Parameters.ignoreReadOnly, Parameters.fileAttributes1, Parameters.fileCreationTime, Parameters.fileLastWriteTime, Parameters.setArchiveAttribute ], isXML: true, serializer: xmlSerializer }; const abortCopyOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 204: { headersMapper: Mappers.FileAbortCopyHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileAbortCopyExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp13, Parameters.copyId ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.leaseId, Parameters.copyActionAbortConstant ], isXML: true, serializer: xmlSerializer }; const listHandlesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ListHandlesResponse, headersMapper: Mappers.FileListHandlesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileListHandlesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.marker, Parameters.maxResults, Parameters.shareSnapshot, Parameters.comp9 ], urlParameters: [Parameters.url], headerParameters: [Parameters.version, Parameters.accept1], isXML: true, serializer: xmlSerializer }; const forceCloseHandlesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}/{fileName}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.FileForceCloseHandlesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.FileForceCloseHandlesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.marker, Parameters.shareSnapshot, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.handleId ], isXML: true, serializer: xmlSerializer };
the_stack
export * from './accountInfo'; export * from './acctInfo'; export * from './achDetails'; export * from './additionalData3DSecure'; export * from './additionalDataAirline'; export * from './additionalDataCarRental'; export * from './additionalDataCommon'; export * from './additionalDataLevel23'; export * from './additionalDataLodging'; export * from './additionalDataOpenInvoice'; export * from './additionalDataOpi'; export * from './additionalDataRatepay'; export * from './additionalDataRetry'; export * from './additionalDataRisk'; export * from './additionalDataRiskStandalone'; export * from './additionalDataSubMerchant'; export * from './additionalDataTemporaryServices'; export * from './additionalDataWallets'; export * from './address'; export * from './afterpayDetails'; export * from './amazonPayDetails'; export * from './amount'; export * from './androidPayDetails'; export * from './applePayDetails'; export * from './applicationInfo'; export * from './avs'; export * from './bacsDirectDebitDetails'; export * from './bankAccount'; export * from './billDeskDetails'; export * from './blikDetails'; export * from './browserInfo'; export * from './card'; export * from './cardDetails'; export * from './cellulantDetails'; export * from './checkoutAwaitAction'; export * from './checkoutBalanceCheckRequest'; export * from './checkoutBalanceCheckResponse'; export * from './checkoutBankTransferAction'; export * from './checkoutCancelOrderRequest'; export * from './checkoutCancelOrderResponse'; export * from './checkoutCreateOrderRequest'; export * from './checkoutCreateOrderResponse'; export * from './checkoutDonationAction'; export * from './checkoutOneTimePasscodeAction'; export * from './checkoutOrder'; export * from './checkoutOrderResponse'; export * from './checkoutQrCodeAction'; export * from './checkoutRedirectAction'; export * from './checkoutSDKAction'; export * from './checkoutThreeDS2Action'; export * from './checkoutUtilityRequest'; export * from './checkoutUtilityResponse'; export * from './checkoutVoucherAction'; export * from './commonField'; export * from './company'; export * from './configuration'; export * from './createCheckoutSessionRequest'; export * from './createCheckoutSessionResponse'; export * from './createPaymentAmountUpdateRequest'; export * from './createPaymentCancelRequest'; export * from './createPaymentCaptureRequest'; export * from './createPaymentLinkRequest'; export * from './createPaymentRefundRequest'; export * from './createPaymentReversalRequest'; export * from './createStandalonePaymentCancelRequest'; export * from './detailsRequest'; export * from './deviceRenderOptions'; export * from './dokuDetails'; export * from './donationResponse'; export * from './dotpayDetails'; export * from './dragonpayDetails'; export * from './econtextVoucherDetails'; export * from './externalPlatform'; export * from './forexQuote'; export * from './fraudCheckResult'; export * from './fraudResult'; export * from './genericIssuerPaymentMethodDetails'; export * from './giropayDetails'; export * from './googlePayDetails'; export * from './idealDetails'; export * from './inputDetail'; export * from './installmentOption'; export * from './installments'; export * from './installmentsNumber'; export * from './item'; export * from './klarnaDetails'; export * from './lianLianPayDetails'; export * from './lineItem'; export * from './mandate'; export * from './masterpassDetails'; export * from './mbwayDetails'; export * from './merchantDevice'; export * from './merchantRiskIndicator'; export * from './mobilePayDetails'; export * from './molPayDetails'; export * from './name'; export * from './openInvoiceDetails'; export * from './payPalDetails'; export * from './payUUpiDetails'; export * from './payWithGoogleDetails'; export * from './paymentAmountUpdateResource'; export * from './paymentCancelResource'; export * from './paymentCaptureResource'; export * from './paymentCompletionDetails'; export * from './paymentDetails'; export * from './paymentDetailsResponse'; export * from './paymentDonationRequest'; export * from './paymentLinkResource'; export * from './paymentMethod'; export * from './paymentMethodGroup'; export * from './paymentMethodIssuer'; export * from './paymentMethodsRequest'; export * from './paymentMethodsResponse'; export * from './paymentRefundResource'; export * from './paymentRequest'; export * from './paymentResponse'; export * from './paymentReversalResource'; export * from './paymentSetupRequest'; export * from './paymentSetupResponse'; export * from './paymentVerificationRequest'; export * from './paymentVerificationResponse'; export * from './phone'; export * from './ratepayDetails'; export * from './recurring'; export * from './recurringDetail'; export * from './redirect'; export * from './responseAdditionalData3DSecure'; export * from './responseAdditionalDataBillingAddress'; export * from './responseAdditionalDataCard'; export * from './responseAdditionalDataCommon'; export * from './responseAdditionalDataDeliveryAddress'; export * from './responseAdditionalDataInstallments'; export * from './responseAdditionalDataNetworkTokens'; export * from './responseAdditionalDataOpi'; export * from './responseAdditionalDataSepa'; export * from './riskData'; export * from './sDKEphemPubKey'; export * from './samsungPayDetails'; export * from './sepaDirectDebitDetails'; export * from './serviceError'; export * from './serviceError2'; export * from './shopperInput'; export * from './shopperInteractionDevice'; export * from './split'; export * from './splitAmount'; export * from './standalonePaymentCancelResource'; export * from './storedDetails'; export * from './storedPaymentMethod'; export * from './storedPaymentMethodDetails'; export * from './subInputDetail'; export * from './threeDS2RequestData'; export * from './threeDS2ResponseData'; export * from './threeDS2Result'; export * from './threeDSRequestorAuthenticationInfo'; export * from './threeDSRequestorPriorAuthenticationInfo'; export * from './threeDSecureData'; export * from './updatePaymentLinkRequest'; export * from './upiDetails'; export * from './vippsDetails'; export * from './visaCheckoutDetails'; export * from './weChatPayDetails'; export * from './weChatPayMiniProgramDetails'; export * from './zipDetails'; import * as fs from 'fs'; export interface RequestDetailedFile { value: Buffer; options?: { filename?: string; contentType?: string; } } export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; import { AccountInfo } from './accountInfo'; import { AcctInfo } from './acctInfo'; import { AchDetails } from './achDetails'; import { AdditionalData3DSecure } from './additionalData3DSecure'; import { AdditionalDataAirline } from './additionalDataAirline'; import { AdditionalDataCarRental } from './additionalDataCarRental'; import { AdditionalDataCommon } from './additionalDataCommon'; import { AdditionalDataLevel23 } from './additionalDataLevel23'; import { AdditionalDataLodging } from './additionalDataLodging'; import { AdditionalDataOpenInvoice } from './additionalDataOpenInvoice'; import { AdditionalDataOpi } from './additionalDataOpi'; import { AdditionalDataRatepay } from './additionalDataRatepay'; import { AdditionalDataRetry } from './additionalDataRetry'; import { AdditionalDataRisk } from './additionalDataRisk'; import { AdditionalDataRiskStandalone } from './additionalDataRiskStandalone'; import { AdditionalDataSubMerchant } from './additionalDataSubMerchant'; import { AdditionalDataTemporaryServices } from './additionalDataTemporaryServices'; import { AdditionalDataWallets } from './additionalDataWallets'; import { Address } from './address'; import { AfterpayDetails } from './afterpayDetails'; import { AmazonPayDetails } from './amazonPayDetails'; import { Amount } from './amount'; import { AndroidPayDetails } from './androidPayDetails'; import { ApplePayDetails } from './applePayDetails'; import { ApplicationInfo } from './applicationInfo'; import { Avs } from './avs'; import { BacsDirectDebitDetails } from './bacsDirectDebitDetails'; import { BankAccount } from './bankAccount'; import { BillDeskDetails } from './billDeskDetails'; import { BlikDetails } from './blikDetails'; import { BrowserInfo } from './browserInfo'; import { Card } from './card'; import { CardDetails } from './cardDetails'; import { CellulantDetails } from './cellulantDetails'; import { CheckoutAwaitAction } from './checkoutAwaitAction'; import { CheckoutBalanceCheckRequest } from './checkoutBalanceCheckRequest'; import { CheckoutBalanceCheckResponse } from './checkoutBalanceCheckResponse'; import { CheckoutBankTransferAction } from './checkoutBankTransferAction'; import { CheckoutCancelOrderRequest } from './checkoutCancelOrderRequest'; import { CheckoutCancelOrderResponse } from './checkoutCancelOrderResponse'; import { CheckoutCreateOrderRequest } from './checkoutCreateOrderRequest'; import { CheckoutCreateOrderResponse } from './checkoutCreateOrderResponse'; import { CheckoutDonationAction } from './checkoutDonationAction'; import { CheckoutOneTimePasscodeAction } from './checkoutOneTimePasscodeAction'; import { CheckoutOrder } from './checkoutOrder'; import { CheckoutOrderResponse } from './checkoutOrderResponse'; import { CheckoutQrCodeAction } from './checkoutQrCodeAction'; import { CheckoutRedirectAction } from './checkoutRedirectAction'; import { CheckoutSDKAction } from './checkoutSDKAction'; import { CheckoutThreeDS2Action } from './checkoutThreeDS2Action'; import { CheckoutUtilityRequest } from './checkoutUtilityRequest'; import { CheckoutUtilityResponse } from './checkoutUtilityResponse'; import { CheckoutVoucherAction } from './checkoutVoucherAction'; import { CommonField } from './commonField'; import { Company } from './company'; import { Configuration } from './configuration'; import { CreateCheckoutSessionRequest } from './createCheckoutSessionRequest'; import { CreateCheckoutSessionResponse } from './createCheckoutSessionResponse'; import { CreatePaymentAmountUpdateRequest } from './createPaymentAmountUpdateRequest'; import { CreatePaymentCancelRequest } from './createPaymentCancelRequest'; import { CreatePaymentCaptureRequest } from './createPaymentCaptureRequest'; import { CreatePaymentLinkRequest } from './createPaymentLinkRequest'; import { CreatePaymentRefundRequest } from './createPaymentRefundRequest'; import { CreatePaymentReversalRequest } from './createPaymentReversalRequest'; import { CreateStandalonePaymentCancelRequest } from './createStandalonePaymentCancelRequest'; import { DetailsRequest } from './detailsRequest'; import { DeviceRenderOptions } from './deviceRenderOptions'; import { DokuDetails } from './dokuDetails'; import { DonationResponse } from './donationResponse'; import { DotpayDetails } from './dotpayDetails'; import { DragonpayDetails } from './dragonpayDetails'; import { EcontextVoucherDetails } from './econtextVoucherDetails'; import { ExternalPlatform } from './externalPlatform'; import { ForexQuote } from './forexQuote'; import { FraudCheckResult } from './fraudCheckResult'; import { FraudResult } from './fraudResult'; import { GenericIssuerPaymentMethodDetails } from './genericIssuerPaymentMethodDetails'; import { GiropayDetails } from './giropayDetails'; import { GooglePayDetails } from './googlePayDetails'; import { IdealDetails } from './idealDetails'; import { InputDetail } from './inputDetail'; import { InstallmentOption } from './installmentOption'; import { Installments } from './installments'; import { InstallmentsNumber } from './installmentsNumber'; import { Item } from './item'; import { KlarnaDetails } from './klarnaDetails'; import { LianLianPayDetails } from './lianLianPayDetails'; import { LineItem } from './lineItem'; import { Mandate } from './mandate'; import { MasterpassDetails } from './masterpassDetails'; import { MbwayDetails } from './mbwayDetails'; import { MerchantDevice } from './merchantDevice'; import { MerchantRiskIndicator } from './merchantRiskIndicator'; import { MobilePayDetails } from './mobilePayDetails'; import { MolPayDetails } from './molPayDetails'; import { Name } from './name'; import { OpenInvoiceDetails } from './openInvoiceDetails'; import { PayPalDetails } from './payPalDetails'; import { PayUUpiDetails } from './payUUpiDetails'; import { PayWithGoogleDetails } from './payWithGoogleDetails'; import { PaymentAmountUpdateResource } from './paymentAmountUpdateResource'; import { PaymentCancelResource } from './paymentCancelResource'; import { PaymentCaptureResource } from './paymentCaptureResource'; import { PaymentCompletionDetails } from './paymentCompletionDetails'; import { PaymentDetails } from './paymentDetails'; import { PaymentDetailsResponse } from './paymentDetailsResponse'; import { PaymentDonationRequest } from './paymentDonationRequest'; import { PaymentLinkResource } from './paymentLinkResource'; import { PaymentMethod } from './paymentMethod'; import { PaymentMethodGroup } from './paymentMethodGroup'; import { PaymentMethodIssuer } from './paymentMethodIssuer'; import { PaymentMethodsRequest } from './paymentMethodsRequest'; import { PaymentMethodsResponse } from './paymentMethodsResponse'; import { PaymentRefundResource } from './paymentRefundResource'; import { PaymentRequest } from './paymentRequest'; import { PaymentResponse } from './paymentResponse'; import { PaymentReversalResource } from './paymentReversalResource'; import { PaymentSetupRequest } from './paymentSetupRequest'; import { PaymentSetupResponse } from './paymentSetupResponse'; import { PaymentVerificationRequest } from './paymentVerificationRequest'; import { PaymentVerificationResponse } from './paymentVerificationResponse'; import { Phone } from './phone'; import { RatepayDetails } from './ratepayDetails'; import { Recurring } from './recurring'; import { RecurringDetail } from './recurringDetail'; import { Redirect } from './redirect'; import { ResponseAdditionalData3DSecure } from './responseAdditionalData3DSecure'; import { ResponseAdditionalDataBillingAddress } from './responseAdditionalDataBillingAddress'; import { ResponseAdditionalDataCard } from './responseAdditionalDataCard'; import { ResponseAdditionalDataCommon } from './responseAdditionalDataCommon'; import { ResponseAdditionalDataDeliveryAddress } from './responseAdditionalDataDeliveryAddress'; import { ResponseAdditionalDataInstallments } from './responseAdditionalDataInstallments'; import { ResponseAdditionalDataNetworkTokens } from './responseAdditionalDataNetworkTokens'; import { ResponseAdditionalDataOpi } from './responseAdditionalDataOpi'; import { ResponseAdditionalDataSepa } from './responseAdditionalDataSepa'; import { RiskData } from './riskData'; import { SDKEphemPubKey } from './sDKEphemPubKey'; import { SamsungPayDetails } from './samsungPayDetails'; import { SepaDirectDebitDetails } from './sepaDirectDebitDetails'; import { ServiceError } from './serviceError'; import { ServiceError2 } from './serviceError2'; import { ShopperInput } from './shopperInput'; import { ShopperInteractionDevice } from './shopperInteractionDevice'; import { Split } from './split'; import { SplitAmount } from './splitAmount'; import { StandalonePaymentCancelResource } from './standalonePaymentCancelResource'; import { StoredDetails } from './storedDetails'; import { StoredPaymentMethod } from './storedPaymentMethod'; import { StoredPaymentMethodDetails } from './storedPaymentMethodDetails'; import { SubInputDetail } from './subInputDetail'; import { ThreeDS2RequestData } from './threeDS2RequestData'; import { ThreeDS2ResponseData } from './threeDS2ResponseData'; import { ThreeDS2Result } from './threeDS2Result'; import { ThreeDSRequestorAuthenticationInfo } from './threeDSRequestorAuthenticationInfo'; import { ThreeDSRequestorPriorAuthenticationInfo } from './threeDSRequestorPriorAuthenticationInfo'; import { ThreeDSecureData } from './threeDSecureData'; import { UpdatePaymentLinkRequest } from './updatePaymentLinkRequest'; import { UpiDetails } from './upiDetails'; import { VippsDetails } from './vippsDetails'; import { VisaCheckoutDetails } from './visaCheckoutDetails'; import { WeChatPayDetails } from './weChatPayDetails'; import { WeChatPayMiniProgramDetails } from './weChatPayMiniProgramDetails'; import { ZipDetails } from './zipDetails'; /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; let enumsMap: {[index: string]: any} = { "AccountInfo.AccountAgeIndicatorEnum": AccountInfo.AccountAgeIndicatorEnum, "AccountInfo.AccountChangeIndicatorEnum": AccountInfo.AccountChangeIndicatorEnum, "AccountInfo.AccountTypeEnum": AccountInfo.AccountTypeEnum, "AccountInfo.DeliveryAddressUsageIndicatorEnum": AccountInfo.DeliveryAddressUsageIndicatorEnum, "AccountInfo.PasswordChangeIndicatorEnum": AccountInfo.PasswordChangeIndicatorEnum, "AccountInfo.PaymentAccountIndicatorEnum": AccountInfo.PaymentAccountIndicatorEnum, "AchDetails.TypeEnum": AchDetails.TypeEnum, "AdditionalDataCommon.IndustryUsageEnum": AdditionalDataCommon.IndustryUsageEnum, "AfterpayDetails.TypeEnum": AfterpayDetails.TypeEnum, "AmazonPayDetails.TypeEnum": AmazonPayDetails.TypeEnum, "AndroidPayDetails.TypeEnum": AndroidPayDetails.TypeEnum, "ApplePayDetails.FundingSourceEnum": ApplePayDetails.FundingSourceEnum, "ApplePayDetails.TypeEnum": ApplePayDetails.TypeEnum, "Avs.EnabledEnum": Avs.EnabledEnum, "BacsDirectDebitDetails.TypeEnum": BacsDirectDebitDetails.TypeEnum, "BillDeskDetails.TypeEnum": BillDeskDetails.TypeEnum, "BlikDetails.TypeEnum": BlikDetails.TypeEnum, "CardDetails.FundingSourceEnum": CardDetails.FundingSourceEnum, "CardDetails.TypeEnum": CardDetails.TypeEnum, "CellulantDetails.TypeEnum": CellulantDetails.TypeEnum, "CheckoutAwaitAction.TypeEnum": CheckoutAwaitAction.TypeEnum, "CheckoutBalanceCheckRequest.RecurringProcessingModelEnum": CheckoutBalanceCheckRequest.RecurringProcessingModelEnum, "CheckoutBalanceCheckRequest.ShopperInteractionEnum": CheckoutBalanceCheckRequest.ShopperInteractionEnum, "CheckoutBalanceCheckResponse.ResultCodeEnum": CheckoutBalanceCheckResponse.ResultCodeEnum, "CheckoutBankTransferAction.TypeEnum": CheckoutBankTransferAction.TypeEnum, "CheckoutCancelOrderResponse.ResultCodeEnum": CheckoutCancelOrderResponse.ResultCodeEnum, "CheckoutCreateOrderResponse.ResultCodeEnum": CheckoutCreateOrderResponse.ResultCodeEnum, "CheckoutDonationAction.TypeEnum": CheckoutDonationAction.TypeEnum, "CheckoutOneTimePasscodeAction.TypeEnum": CheckoutOneTimePasscodeAction.TypeEnum, "CheckoutQrCodeAction.TypeEnum": CheckoutQrCodeAction.TypeEnum, "CheckoutRedirectAction.TypeEnum": CheckoutRedirectAction.TypeEnum, "CheckoutSDKAction.TypeEnum": CheckoutSDKAction.TypeEnum, "CheckoutThreeDS2Action.TypeEnum": CheckoutThreeDS2Action.TypeEnum, "CheckoutVoucherAction.TypeEnum": CheckoutVoucherAction.TypeEnum, "Configuration.CardHolderNameEnum": Configuration.CardHolderNameEnum, "CreateCheckoutSessionRequest.ChannelEnum": CreateCheckoutSessionRequest.ChannelEnum, "CreateCheckoutSessionRequest.RecurringProcessingModelEnum": CreateCheckoutSessionRequest.RecurringProcessingModelEnum, "CreateCheckoutSessionRequest.ShopperInteractionEnum": CreateCheckoutSessionRequest.ShopperInteractionEnum, "CreateCheckoutSessionResponse.ChannelEnum": CreateCheckoutSessionResponse.ChannelEnum, "CreateCheckoutSessionResponse.RecurringProcessingModelEnum": CreateCheckoutSessionResponse.RecurringProcessingModelEnum, "CreateCheckoutSessionResponse.ShopperInteractionEnum": CreateCheckoutSessionResponse.ShopperInteractionEnum, "CreatePaymentAmountUpdateRequest.ReasonEnum": CreatePaymentAmountUpdateRequest.ReasonEnum, "CreatePaymentLinkRequest.RecurringProcessingModelEnum": CreatePaymentLinkRequest.RecurringProcessingModelEnum, "CreatePaymentLinkRequest.RequiredShopperFieldsEnum": CreatePaymentLinkRequest.RequiredShopperFieldsEnum, "CreatePaymentLinkRequest.StorePaymentMethodModeEnum": CreatePaymentLinkRequest.StorePaymentMethodModeEnum, "DeviceRenderOptions.SdkInterfaceEnum": DeviceRenderOptions.SdkInterfaceEnum, "DeviceRenderOptions.SdkUiTypeEnum": DeviceRenderOptions.SdkUiTypeEnum, "DokuDetails.TypeEnum": DokuDetails.TypeEnum, "DonationResponse.StatusEnum": DonationResponse.StatusEnum, "DotpayDetails.TypeEnum": DotpayDetails.TypeEnum, "DragonpayDetails.TypeEnum": DragonpayDetails.TypeEnum, "EcontextVoucherDetails.TypeEnum": EcontextVoucherDetails.TypeEnum, "GenericIssuerPaymentMethodDetails.TypeEnum": GenericIssuerPaymentMethodDetails.TypeEnum, "GiropayDetails.TypeEnum": GiropayDetails.TypeEnum, "GooglePayDetails.FundingSourceEnum": GooglePayDetails.FundingSourceEnum, "GooglePayDetails.TypeEnum": GooglePayDetails.TypeEnum, "IdealDetails.TypeEnum": IdealDetails.TypeEnum, "InstallmentOption.PlansEnum": InstallmentOption.PlansEnum, "Installments.PlanEnum": Installments.PlanEnum, "KlarnaDetails.TypeEnum": KlarnaDetails.TypeEnum, "LianLianPayDetails.TypeEnum": LianLianPayDetails.TypeEnum, "Mandate.AmountRuleEnum": Mandate.AmountRuleEnum, "Mandate.BillingAttemptsRuleEnum": Mandate.BillingAttemptsRuleEnum, "Mandate.FrequencyEnum": Mandate.FrequencyEnum, "MasterpassDetails.FundingSourceEnum": MasterpassDetails.FundingSourceEnum, "MasterpassDetails.TypeEnum": MasterpassDetails.TypeEnum, "MbwayDetails.TypeEnum": MbwayDetails.TypeEnum, "MerchantRiskIndicator.DeliveryAddressIndicatorEnum": MerchantRiskIndicator.DeliveryAddressIndicatorEnum, "MerchantRiskIndicator.DeliveryTimeframeEnum": MerchantRiskIndicator.DeliveryTimeframeEnum, "MobilePayDetails.TypeEnum": MobilePayDetails.TypeEnum, "MolPayDetails.TypeEnum": MolPayDetails.TypeEnum, "OpenInvoiceDetails.TypeEnum": OpenInvoiceDetails.TypeEnum, "PayPalDetails.SubtypeEnum": PayPalDetails.SubtypeEnum, "PayPalDetails.TypeEnum": PayPalDetails.TypeEnum, "PayUUpiDetails.TypeEnum": PayUUpiDetails.TypeEnum, "PayWithGoogleDetails.FundingSourceEnum": PayWithGoogleDetails.FundingSourceEnum, "PayWithGoogleDetails.TypeEnum": PayWithGoogleDetails.TypeEnum, "PaymentAmountUpdateResource.ReasonEnum": PaymentAmountUpdateResource.ReasonEnum, "PaymentAmountUpdateResource.StatusEnum": PaymentAmountUpdateResource.StatusEnum, "PaymentCancelResource.StatusEnum": PaymentCancelResource.StatusEnum, "PaymentCaptureResource.StatusEnum": PaymentCaptureResource.StatusEnum, "PaymentDetails.TypeEnum": PaymentDetails.TypeEnum, "PaymentDetailsResponse.ResultCodeEnum": PaymentDetailsResponse.ResultCodeEnum, "PaymentDonationRequest.ChannelEnum": PaymentDonationRequest.ChannelEnum, "PaymentDonationRequest.EntityTypeEnum": PaymentDonationRequest.EntityTypeEnum, "PaymentDonationRequest.RecurringProcessingModelEnum": PaymentDonationRequest.RecurringProcessingModelEnum, "PaymentDonationRequest.ShopperInteractionEnum": PaymentDonationRequest.ShopperInteractionEnum, "PaymentLinkResource.RecurringProcessingModelEnum": PaymentLinkResource.RecurringProcessingModelEnum, "PaymentLinkResource.StatusEnum": PaymentLinkResource.StatusEnum, "PaymentLinkResource.StorePaymentMethodModeEnum": PaymentLinkResource.StorePaymentMethodModeEnum, "PaymentMethod.FundingSourceEnum": PaymentMethod.FundingSourceEnum, "PaymentMethodsRequest.ChannelEnum": PaymentMethodsRequest.ChannelEnum, "PaymentRefundResource.StatusEnum": PaymentRefundResource.StatusEnum, "PaymentRequest.ChannelEnum": PaymentRequest.ChannelEnum, "PaymentRequest.EntityTypeEnum": PaymentRequest.EntityTypeEnum, "PaymentRequest.RecurringProcessingModelEnum": PaymentRequest.RecurringProcessingModelEnum, "PaymentRequest.ShopperInteractionEnum": PaymentRequest.ShopperInteractionEnum, "PaymentResponse.ResultCodeEnum": PaymentResponse.ResultCodeEnum, "PaymentReversalResource.StatusEnum": PaymentReversalResource.StatusEnum, "PaymentSetupRequest.ChannelEnum": PaymentSetupRequest.ChannelEnum, "PaymentSetupRequest.EntityTypeEnum": PaymentSetupRequest.EntityTypeEnum, "PaymentSetupRequest.ShopperInteractionEnum": PaymentSetupRequest.ShopperInteractionEnum, "PaymentVerificationResponse.ResultCodeEnum": PaymentVerificationResponse.ResultCodeEnum, "RatepayDetails.TypeEnum": RatepayDetails.TypeEnum, "Recurring.ContractEnum": Recurring.ContractEnum, "Recurring.TokenServiceEnum": Recurring.TokenServiceEnum, "RecurringDetail.FundingSourceEnum": RecurringDetail.FundingSourceEnum, "Redirect.MethodEnum": Redirect.MethodEnum, "ResponseAdditionalDataCommon.FraudResultTypeEnum": ResponseAdditionalDataCommon.FraudResultTypeEnum, "ResponseAdditionalDataCommon.MerchantAdviceCodeEnum": ResponseAdditionalDataCommon.MerchantAdviceCodeEnum, "ResponseAdditionalDataCommon.RecurringProcessingModelEnum": ResponseAdditionalDataCommon.RecurringProcessingModelEnum, "SamsungPayDetails.FundingSourceEnum": SamsungPayDetails.FundingSourceEnum, "SamsungPayDetails.TypeEnum": SamsungPayDetails.TypeEnum, "SepaDirectDebitDetails.TypeEnum": SepaDirectDebitDetails.TypeEnum, "ShopperInput.BillingAddressEnum": ShopperInput.BillingAddressEnum, "ShopperInput.DeliveryAddressEnum": ShopperInput.DeliveryAddressEnum, "ShopperInput.PersonalDetailsEnum": ShopperInput.PersonalDetailsEnum, "Split.TypeEnum": Split.TypeEnum, "StandalonePaymentCancelResource.StatusEnum": StandalonePaymentCancelResource.StatusEnum, "StoredPaymentMethodDetails.TypeEnum": StoredPaymentMethodDetails.TypeEnum, "ThreeDS2RequestData.ChallengeIndicatorEnum": ThreeDS2RequestData.ChallengeIndicatorEnum, "ThreeDS2RequestData.TransactionTypeEnum": ThreeDS2RequestData.TransactionTypeEnum, "ThreeDS2Result.ChallengeIndicatorEnum": ThreeDS2Result.ChallengeIndicatorEnum, "ThreeDS2Result.ExemptionIndicatorEnum": ThreeDS2Result.ExemptionIndicatorEnum, "ThreeDSecureData.AuthenticationResponseEnum": ThreeDSecureData.AuthenticationResponseEnum, "ThreeDSecureData.DirectoryResponseEnum": ThreeDSecureData.DirectoryResponseEnum, "UpdatePaymentLinkRequest.StatusEnum": UpdatePaymentLinkRequest.StatusEnum, "UpiDetails.TypeEnum": UpiDetails.TypeEnum, "VippsDetails.TypeEnum": VippsDetails.TypeEnum, "VisaCheckoutDetails.FundingSourceEnum": VisaCheckoutDetails.FundingSourceEnum, "VisaCheckoutDetails.TypeEnum": VisaCheckoutDetails.TypeEnum, "WeChatPayDetails.TypeEnum": WeChatPayDetails.TypeEnum, "WeChatPayMiniProgramDetails.TypeEnum": WeChatPayMiniProgramDetails.TypeEnum, "ZipDetails.TypeEnum": ZipDetails.TypeEnum, } let typeMap: {[index: string]: any} = { "AccountInfo": AccountInfo, "AcctInfo": AcctInfo, "AchDetails": AchDetails, "AdditionalData3DSecure": AdditionalData3DSecure, "AdditionalDataAirline": AdditionalDataAirline, "AdditionalDataCarRental": AdditionalDataCarRental, "AdditionalDataCommon": AdditionalDataCommon, "AdditionalDataLevel23": AdditionalDataLevel23, "AdditionalDataLodging": AdditionalDataLodging, "AdditionalDataOpenInvoice": AdditionalDataOpenInvoice, "AdditionalDataOpi": AdditionalDataOpi, "AdditionalDataRatepay": AdditionalDataRatepay, "AdditionalDataRetry": AdditionalDataRetry, "AdditionalDataRisk": AdditionalDataRisk, "AdditionalDataRiskStandalone": AdditionalDataRiskStandalone, "AdditionalDataSubMerchant": AdditionalDataSubMerchant, "AdditionalDataTemporaryServices": AdditionalDataTemporaryServices, "AdditionalDataWallets": AdditionalDataWallets, "Address": Address, "AfterpayDetails": AfterpayDetails, "AmazonPayDetails": AmazonPayDetails, "Amount": Amount, "AndroidPayDetails": AndroidPayDetails, "ApplePayDetails": ApplePayDetails, "ApplicationInfo": ApplicationInfo, "Avs": Avs, "BacsDirectDebitDetails": BacsDirectDebitDetails, "BankAccount": BankAccount, "BillDeskDetails": BillDeskDetails, "BlikDetails": BlikDetails, "BrowserInfo": BrowserInfo, "Card": Card, "CardDetails": CardDetails, "CellulantDetails": CellulantDetails, "CheckoutAwaitAction": CheckoutAwaitAction, "CheckoutBalanceCheckRequest": CheckoutBalanceCheckRequest, "CheckoutBalanceCheckResponse": CheckoutBalanceCheckResponse, "CheckoutBankTransferAction": CheckoutBankTransferAction, "CheckoutCancelOrderRequest": CheckoutCancelOrderRequest, "CheckoutCancelOrderResponse": CheckoutCancelOrderResponse, "CheckoutCreateOrderRequest": CheckoutCreateOrderRequest, "CheckoutCreateOrderResponse": CheckoutCreateOrderResponse, "CheckoutDonationAction": CheckoutDonationAction, "CheckoutOneTimePasscodeAction": CheckoutOneTimePasscodeAction, "CheckoutOrder": CheckoutOrder, "CheckoutOrderResponse": CheckoutOrderResponse, "CheckoutQrCodeAction": CheckoutQrCodeAction, "CheckoutRedirectAction": CheckoutRedirectAction, "CheckoutSDKAction": CheckoutSDKAction, "CheckoutThreeDS2Action": CheckoutThreeDS2Action, "CheckoutUtilityRequest": CheckoutUtilityRequest, "CheckoutUtilityResponse": CheckoutUtilityResponse, "CheckoutVoucherAction": CheckoutVoucherAction, "CommonField": CommonField, "Company": Company, "Configuration": Configuration, "CreateCheckoutSessionRequest": CreateCheckoutSessionRequest, "CreateCheckoutSessionResponse": CreateCheckoutSessionResponse, "CreatePaymentAmountUpdateRequest": CreatePaymentAmountUpdateRequest, "CreatePaymentCancelRequest": CreatePaymentCancelRequest, "CreatePaymentCaptureRequest": CreatePaymentCaptureRequest, "CreatePaymentLinkRequest": CreatePaymentLinkRequest, "CreatePaymentRefundRequest": CreatePaymentRefundRequest, "CreatePaymentReversalRequest": CreatePaymentReversalRequest, "CreateStandalonePaymentCancelRequest": CreateStandalonePaymentCancelRequest, "DetailsRequest": DetailsRequest, "DeviceRenderOptions": DeviceRenderOptions, "DokuDetails": DokuDetails, "DonationResponse": DonationResponse, "DotpayDetails": DotpayDetails, "DragonpayDetails": DragonpayDetails, "EcontextVoucherDetails": EcontextVoucherDetails, "ExternalPlatform": ExternalPlatform, "ForexQuote": ForexQuote, "FraudCheckResult": FraudCheckResult, "FraudResult": FraudResult, "GenericIssuerPaymentMethodDetails": GenericIssuerPaymentMethodDetails, "GiropayDetails": GiropayDetails, "GooglePayDetails": GooglePayDetails, "IdealDetails": IdealDetails, "InputDetail": InputDetail, "InstallmentOption": InstallmentOption, "Installments": Installments, "InstallmentsNumber": InstallmentsNumber, "Item": Item, "KlarnaDetails": KlarnaDetails, "LianLianPayDetails": LianLianPayDetails, "LineItem": LineItem, "Mandate": Mandate, "MasterpassDetails": MasterpassDetails, "MbwayDetails": MbwayDetails, "MerchantDevice": MerchantDevice, "MerchantRiskIndicator": MerchantRiskIndicator, "MobilePayDetails": MobilePayDetails, "MolPayDetails": MolPayDetails, "Name": Name, "OpenInvoiceDetails": OpenInvoiceDetails, "PayPalDetails": PayPalDetails, "PayUUpiDetails": PayUUpiDetails, "PayWithGoogleDetails": PayWithGoogleDetails, "PaymentAmountUpdateResource": PaymentAmountUpdateResource, "PaymentCancelResource": PaymentCancelResource, "PaymentCaptureResource": PaymentCaptureResource, "PaymentCompletionDetails": PaymentCompletionDetails, "PaymentDetails": PaymentDetails, "PaymentDetailsResponse": PaymentDetailsResponse, "PaymentDonationRequest": PaymentDonationRequest, "PaymentLinkResource": PaymentLinkResource, "PaymentMethod": PaymentMethod, "PaymentMethodGroup": PaymentMethodGroup, "PaymentMethodIssuer": PaymentMethodIssuer, "PaymentMethodsRequest": PaymentMethodsRequest, "PaymentMethodsResponse": PaymentMethodsResponse, "PaymentRefundResource": PaymentRefundResource, "PaymentRequest": PaymentRequest, "PaymentResponse": PaymentResponse, "PaymentReversalResource": PaymentReversalResource, "PaymentSetupRequest": PaymentSetupRequest, "PaymentSetupResponse": PaymentSetupResponse, "PaymentVerificationRequest": PaymentVerificationRequest, "PaymentVerificationResponse": PaymentVerificationResponse, "Phone": Phone, "RatepayDetails": RatepayDetails, "Recurring": Recurring, "RecurringDetail": RecurringDetail, "Redirect": Redirect, "ResponseAdditionalData3DSecure": ResponseAdditionalData3DSecure, "ResponseAdditionalDataBillingAddress": ResponseAdditionalDataBillingAddress, "ResponseAdditionalDataCard": ResponseAdditionalDataCard, "ResponseAdditionalDataCommon": ResponseAdditionalDataCommon, "ResponseAdditionalDataDeliveryAddress": ResponseAdditionalDataDeliveryAddress, "ResponseAdditionalDataInstallments": ResponseAdditionalDataInstallments, "ResponseAdditionalDataNetworkTokens": ResponseAdditionalDataNetworkTokens, "ResponseAdditionalDataOpi": ResponseAdditionalDataOpi, "ResponseAdditionalDataSepa": ResponseAdditionalDataSepa, "RiskData": RiskData, "SDKEphemPubKey": SDKEphemPubKey, "SamsungPayDetails": SamsungPayDetails, "SepaDirectDebitDetails": SepaDirectDebitDetails, "ServiceError": ServiceError, "ServiceError2": ServiceError2, "ShopperInput": ShopperInput, "ShopperInteractionDevice": ShopperInteractionDevice, "Split": Split, "SplitAmount": SplitAmount, "StandalonePaymentCancelResource": StandalonePaymentCancelResource, "StoredDetails": StoredDetails, "StoredPaymentMethod": StoredPaymentMethod, "StoredPaymentMethodDetails": StoredPaymentMethodDetails, "SubInputDetail": SubInputDetail, "ThreeDS2RequestData": ThreeDS2RequestData, "ThreeDS2ResponseData": ThreeDS2ResponseData, "ThreeDS2Result": ThreeDS2Result, "ThreeDSRequestorAuthenticationInfo": ThreeDSRequestorAuthenticationInfo, "ThreeDSRequestorPriorAuthenticationInfo": ThreeDSRequestorPriorAuthenticationInfo, "ThreeDSecureData": ThreeDSecureData, "UpdatePaymentLinkRequest": UpdatePaymentLinkRequest, "UpiDetails": UpiDetails, "VippsDetails": VippsDetails, "VisaCheckoutDetails": VisaCheckoutDetails, "WeChatPayDetails": WeChatPayDetails, "WeChatPayMiniProgramDetails": WeChatPayMiniProgramDetails, "ZipDetails": ZipDetails, } export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap[expectedType]) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { var discriminatorType = data[discriminatorProperty]; if(typeMap[discriminatorType]){ return discriminatorType; // use the type given in the discriminator } else { return expectedType; // discriminator did not map to a type } } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index = 0; index < data.length; index++) { let datum = data[index]; transformedData.push(ObjectSerializer.serialize(datum, subType)); } return transformedData; } else if (type === "Date") { return data.toISOString(); } else { if (enumsMap[type]) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // Get the actual type of this object type = this.findCorrectType(data, type); // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index = 0; index < attributeTypes.length; index++) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); } return instance; } } public static deserialize(data: any, type: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index = 0; index < data.length; index++) { let datum = data[index]; transformedData.push(ObjectSerializer.deserialize(datum, subType)); } return transformedData; } else if (type === "Date") { return new Date(data); } else { if (enumsMap[type]) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index = 0; index < attributeTypes.length; index++) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); } return instance; } } }
the_stack
import { JsplumbConfigService } from './jsplumb-config.service'; import { JsplumbBridge } from './jsplumb-bridge.service'; import { Injectable } from '@angular/core'; import { InvocablePipelineElementUnion, PipelineElementConfig, PipelineElementConfigurationStatus, PipelineElementUnion } from '../model/editor.model'; import { PipelineElementTypeUtils } from '../utils/editor.utils'; import { DataProcessorInvocation, DataSinkInvocation, Pipeline, SpDataSet, SpDataStream, SpDataStreamUnion } from '@streampipes/platform-services'; import { JsplumbEndpointService } from './jsplumb-endpoint.service'; import { JsplumbFactoryService } from './jsplumb-factory.service'; import { EditorService } from './editor.service'; @Injectable() export class JsplumbService { idCounter = 0; constructor(private jsplumbConfigService: JsplumbConfigService, private jsplumbFactory: JsplumbFactoryService, private jsplumbEndpointService: JsplumbEndpointService, private editorService: EditorService) { } isFullyConnected(pipelineElementConfig: PipelineElementConfig, previewConfig: boolean) { const jsplumbBridge = this.jsplumbFactory.getJsplumbBridge(previewConfig); const payload = pipelineElementConfig.payload as InvocablePipelineElementUnion; return payload.inputStreams == null || jsplumbBridge.getConnections({target: document.getElementById(payload.dom)}).length == payload.inputStreams.length; } makeRawPipeline(pipelineModel: Pipeline, isPreview: boolean) { return pipelineModel .streams .map(s => this.toConfig(s, 'stream', isPreview)) .concat(pipelineModel.sepas.map(s => this.toConfig(s, 'sepa', isPreview))) .concat(pipelineModel.actions.map(s => this.toConfig(s, 'action', isPreview))); } toConfig(pe: PipelineElementUnion, type: string, isPreview: boolean) { (pe as any).type = type; return this.createNewPipelineElementConfig(pe, {x: 100, y: 100}, isPreview, true); } createElementWithoutConnection(pipelineModel: PipelineElementConfig[], pipelineElement: PipelineElementUnion, x: number, y: number) { const pipelineElementConfig = this.createNewPipelineElementConfigAtPosition(x, y, pipelineElement, false); pipelineModel.push(pipelineElementConfig); if (pipelineElementConfig.payload instanceof SpDataSet) { this.editorService.updateDataSet(pipelineElement).subscribe(data => { (pipelineElementConfig.payload as SpDataSet).eventGrounding = data.eventGrounding; (pipelineElementConfig.payload as SpDataSet).datasetInvocationId = data.invocationId; setTimeout(() => { this.elementDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload, true, false); }, 1); }); } else { setTimeout(() => { this.elementDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload, true, false); }, 100); } } createElement(pipelineModel: PipelineElementConfig[], pipelineElement: InvocablePipelineElementUnion, sourceElementDomId: string) { const sourceElement = $('#' + sourceElementDomId); const pipelineElementConfig = this.createNewPipelineElementConfigWithFixedCoordinates(sourceElement, pipelineElement, false); pipelineModel.push(pipelineElementConfig); setTimeout(() => { this.createAssemblyElement(pipelineElementConfig.payload.dom, pipelineElementConfig.payload as InvocablePipelineElementUnion, sourceElement, false); }); } createAssemblyElement(pipelineElementDomId: string, pipelineElement: InvocablePipelineElementUnion, sourceElement, previewConfig: boolean) { let targetElementId; if (pipelineElement instanceof DataProcessorInvocation) { targetElementId = this.dataProcessorDropped(pipelineElementDomId, pipelineElement as DataProcessorInvocation, true, false); this.connectNodes(sourceElement, targetElementId, previewConfig); } else { targetElementId = this.dataSinkDropped(pipelineElementDomId, pipelineElement, true, false); this.connectNodes(sourceElement, targetElementId, previewConfig); } } connectNodes(sourceElementSelector, targetElementId, previewConfig: boolean) { let options; const sourceElement = sourceElementSelector.get()[0]; const jsplumbBridge = this.getBridge(previewConfig); const jsplumbConfig = this.jsplumbEndpointService.getJsplumbConfig(true); options = sourceElementSelector.hasClass('stream') ? jsplumbConfig.streamEndpointOptions : jsplumbConfig.sepaEndpointOptions; let sourceEndPoint; const selectedEndpoints = jsplumbBridge.selectEndpoints({source: sourceElement}); sourceEndPoint = selectedEndpoints.length > 0 ? !(selectedEndpoints.get(0).isFull()) ? jsplumbBridge.selectEndpoints({source: sourceElement}).get(0) : jsplumbBridge.addEndpoint(sourceElement, options) : jsplumbBridge.addEndpoint(sourceElement, options); const targetElement = document.getElementById(targetElementId); const targetEndPoint = jsplumbBridge.selectEndpoints({target: targetElement}).get(0); jsplumbBridge.connect({source: sourceEndPoint, target: targetEndPoint, detachable: true}); jsplumbBridge.repaintEverything(); } createNewPipelineElementConfigWithFixedCoordinates(sourceElement, pipelineElement: InvocablePipelineElementUnion, isPreview): PipelineElementConfig { const x = sourceElement.position().left; const y = sourceElement.position().top; return this.createNewPipelineElementConfigAtPosition(x, y, pipelineElement, isPreview); } createNewPipelineElementConfigAtPosition(x: number, y: number, json: any, isPreview: boolean): PipelineElementConfig { const coord = {'x': x + 200, 'y': y}; return this.createNewPipelineElementConfig(json, coord, isPreview, false); } createNewPipelineElementConfig(pipelineElement: PipelineElementUnion, coordinates, isPreview: boolean, isCompleted: boolean, newElementId?: string): PipelineElementConfig { const displaySettings = isPreview ? 'connectable-preview' : 'connectable-editor'; const connectable = 'connectable'; const pipelineElementConfig = {} as PipelineElementConfig; pipelineElementConfig.type = PipelineElementTypeUtils .toCssShortHand(PipelineElementTypeUtils.fromType(pipelineElement)); pipelineElementConfig.payload = this.clone(pipelineElement, newElementId); pipelineElementConfig.settings = { connectable, openCustomize: !(pipelineElement as any).configured, preview: isPreview, completed: (pipelineElement instanceof SpDataStream || pipelineElement instanceof SpDataSet || isPreview || isCompleted) ? PipelineElementConfigurationStatus.OK : PipelineElementConfigurationStatus.INCOMPLETE, disabled: false, loadingStatus: false, displaySettings, position: { x: coordinates.x, y: coordinates.y } }; if (!pipelineElementConfig.payload.dom) { pipelineElementConfig.payload.dom = 'jsplumb_' + this.idCounter + '_' + this.makeId(4); this.idCounter++; } return pipelineElementConfig; } clone(pipelineElement: PipelineElementUnion, newElementId?: string) { if (pipelineElement instanceof SpDataSet) { return SpDataSet.fromData(pipelineElement, new SpDataSet()); } else if (pipelineElement instanceof SpDataStream) { const cloned = SpDataStream.fromData(pipelineElement, new SpDataStream()); return cloned; } else if (pipelineElement instanceof DataProcessorInvocation) { const clonedPe = DataProcessorInvocation.fromData(pipelineElement, new DataProcessorInvocation()); if (newElementId) { this.updateElementIds(clonedPe, newElementId); } return clonedPe; } else if (pipelineElement instanceof DataSinkInvocation) { const clonedPe = DataSinkInvocation.fromData(pipelineElement as DataSinkInvocation, new DataSinkInvocation()); if (newElementId) { this.updateElementIds(clonedPe, newElementId); } return clonedPe; } } updateElementIds(pipelineElement: PipelineElementUnion, newElementId: string) { pipelineElement.elementId = newElementId; pipelineElement.uri = newElementId; } makeId(count: number) { let text = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < count; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } elementDropped(pipelineElementDomId: string, pipelineElement: PipelineElementUnion, endpoints: boolean, preview: boolean): string { if (pipelineElement instanceof SpDataStream) { return this.dataStreamDropped(pipelineElementDomId, pipelineElement as SpDataStream, endpoints, preview); } else if (pipelineElement instanceof SpDataSet) { return this.dataSetDropped(pipelineElementDomId, pipelineElement as SpDataSet, endpoints, preview); } else if (pipelineElement instanceof DataProcessorInvocation) { return this.dataProcessorDropped(pipelineElementDomId, pipelineElement, endpoints, preview); } else if (pipelineElement instanceof DataSinkInvocation) { return this.dataSinkDropped(pipelineElementDomId, pipelineElement, endpoints, preview); } } dataSetDropped(pipelineElementDomId: string, pipelineElement: SpDataSet, endpoints: boolean, preview: boolean) { const jsplumbBridge = this.getBridge(preview); if (endpoints) { const endpointOptions = this.jsplumbEndpointService.getStreamEndpoint(preview, pipelineElementDomId); jsplumbBridge.addEndpoint(pipelineElementDomId, endpointOptions); } return pipelineElementDomId; } dataStreamDropped(pipelineElementDomId: string, pipelineElement: SpDataStreamUnion, endpoints: boolean, preview: boolean) { const jsplumbBridge = this.getBridge(preview); if (endpoints) { const endpointOptions = this.jsplumbEndpointService.getStreamEndpoint(preview, pipelineElementDomId); jsplumbBridge.addEndpoint(pipelineElementDomId, endpointOptions); } return pipelineElementDomId; } dataProcessorDropped(pipelineElementDomId: string, pipelineElement: DataProcessorInvocation, endpoints: boolean, preview: boolean): string { const jsplumbBridge = this.getBridge(preview); this.dataSinkDropped(pipelineElementDomId, pipelineElement, endpoints, preview); if (endpoints) { jsplumbBridge.addEndpoint(pipelineElementDomId, this.jsplumbEndpointService.getOutputEndpoint(preview, pipelineElementDomId)); } return pipelineElementDomId; } dataSinkDropped(pipelineElementDomId: string, pipelineElement: InvocablePipelineElementUnion, endpoints: boolean, preview: boolean): string { const jsplumbBridge = this.getBridge(preview); if (endpoints) { if (pipelineElement.inputStreams.length < 2) { // 1 InputNode jsplumbBridge.addEndpoint(pipelineElementDomId, this.jsplumbEndpointService.getInputEndpoint(preview, pipelineElementDomId, 0)); } else { jsplumbBridge.addEndpoint(pipelineElementDomId, this.jsplumbEndpointService.getNewTargetPoint(preview, 0, 0.3, pipelineElementDomId, 0)); jsplumbBridge.addEndpoint(pipelineElementDomId, this.jsplumbEndpointService.getNewTargetPoint(preview, 0, 0.7, pipelineElementDomId, 1)); } } return pipelineElementDomId; } getBridge(previewConfig: boolean): JsplumbBridge { return this.jsplumbFactory.getJsplumbBridge(previewConfig); } }
the_stack
import { EllipsisOutlined } from '@ant-design/icons' import { debounce } from 'lodash' // import { Tree } from '../../tree' import { TModel } from '../../type/model' import { RootInstance } from '../../type' // import _ from 'lodash' import React, { useCallback, useEffect, useState, useMemo } from 'react' import Scroll from 'react-custom-scrollbars' import { CreateComponent } from '../../util' import { useMst } from '../../context' import './style.scss' // import mst from '@antv/g6/lib/algorithm/mst'; console.log('hezk test ======='); type IModelNaviProps = { modules?: [] model?: [] } const getTreeNodeTitle = ( model: TModel, root: RootInstance, OptionBuilder: any ) => { return ( <OptionBuilder data={{ title: root.renderModelTitle(model), options: [ { title: <span> {root.intl('定位模型')}</span>, key: 1, click: e => { root.sys.centerCurrentModel([model.id]) e.stopPropagation() } }, { key: 2, title: <span> {root.intl('查看')}</span>, click: e => { root.sys.openModel(model.id) e.stopPropagation() } } // { // title: <span> {intlLiteral('移除')}</span> // }, ] }} /> ) } export default CreateComponent<IModelNaviProps>({ render(_) { const mst = useMst() const intl = mst.intl const { Input, Button, Dropdown, Menu, Select, Tree } = mst.Ui as any const { TreeNode, OptionBuilder } = Tree as any const treeNodes = useMemo( () => !mst.sys.tabOrTree ? mst.moduleList.map(m => { return ( <TreeNode title={ mst.sys.showNameOrLabel ? m.name : m.label } key={m.id} > {[...m.models.values()] .filter(model => model.filterModel()) .map(model => { return ( <TreeNode key={model.id} title={getTreeNodeTitle( model, mst, OptionBuilder )} /> ) })} </TreeNode> ) }) : [...mst.Models.values()] .filter( model => (!mst.sys.currentModule || model.moduleId === mst.sys.currentModule) && model.filterModel() ) .map(model => { return ( <TreeNode key={model.id} title={getTreeNodeTitle( model, mst, OptionBuilder )} /> ) }), [ mst.sys.tabOrTree, mst.moduleList, mst.sys.showNameOrLabel, mst.sys.currentModule, mst.sys.search //打包后没有执行,添加search确保执行 ] ) useEffect(() => { }, [mst.Ui.update]) const { search, onExpand, checkAllFun, checkAllCancleFun, toggleShowNameOrLabel, toggleTabOrTree, Sys, changeModuleValue, setSearch } = useLocal() return ( <div className='console-models-tree' style={{ height: mst.sys.height }} > <div className='header'> <div className='console-erd-search'> <Input allowClear value={search} size='small' onChange={e => setSearch(e.target.value)} addonAfter={ Sys.tabOrTree && ( <Select size='small' defaultValue={Sys.currentModule} value={Sys.currentModule} className='select-after' onChange={changeModuleValue} > {[ <Select.Option value={''}> {intl('所有')} </Select.Option>, ...[...mst.Modules.values()].map( module => { return ( <Select.Option value={module.id} key={module.id} > {module.label} </Select.Option> ) } ) ]} </Select> ) } /> </div> <div className='console-erd-search btns'> {mst.sys.tabOrTree && ( <Button size='small' type='text' onClick={checkAllFun} > {intl('选择所有')} </Button> )} {mst.sys.tabOrTree && ( <Button size='small' type='text' onClick={checkAllCancleFun} > {intl('清除所有')} </Button> )} {/* {!mst.sys.tabOrTree && <Button size="small" type="link" onClick={toggleTabOrTree}>{mst.sys.tabOrTree?'分类':'树形'}模式</Button>} */} <Button size='small' type='text' onClick={toggleShowNameOrLabel} > {intl('显示')} {!mst.sys.showNameOrLabel ? intl('名称') : intl('标签')} </Button> { !Sys.onlyMode && <Dropdown className='right' overlay={ <Menu> <Menu.Item key='1' onClick={toggleTabOrTree} > {!Sys.tabOrTree ? intl('分类') : intl('树形')}{' '} {intl('模式')} </Menu.Item> </Menu> } > <span> <EllipsisOutlined /> </span> </Dropdown> } </div> </div> <div className='navitree-warp'> <Scroll autoHide autoHeight autoHideTimeout={1000} autoHideDuration={200} autoHeightMin={'100%'} autoHeightMax={'100%'} > <Tree showIcon={false} className='console-models-tree-tree' onSelect={mst.sys.setCurrentModel.bind(mst.sys)} selectedKeys={[mst.sys.currentModel]} checkedKeys={[...mst.sys.checkedKeys]} onCheck={mst.setCheckedKeys.bind(mst)} checkable onExpand={onExpand} multiple expandedKeys={[...mst.sys.expandedKeys]} > {treeNodes} </Tree> </Scroll> </div> </div> ) }, displayName: 'navi' }) const useLocal = () => { const mst = useMst() const [text, setText] = useState(mst.sys.search) const [texting, setTexting] = useState(false) // 重复setText 导致快速输入时inputValue显示异常 // useEffect(() => { // if (!texting) debounce(() => { // setText(mst.sys.search); // }, 1000)()//时间设置太长导致input框未能即使更新设置值 // }, [mst.sys.search]) const setSearch = useCallback( val => { setTexting(true) setText(val) debounce(() => { mst.sys.setSearch(val) setTexting(false) }, 500)() }, [mst.sys.setSearch, setText] ) // const setSearch = mst.sys.setSearch; return { search: text, get modules() { return mst.moduleList }, onExpand(expandedKeys: string[]) { mst.sys.setExpandedKeys(expandedKeys) }, get expandedKeys() { return mst.sys.expandedKeys }, checkAllFun() { return mst.checkAllFun() }, checkAllCancleFun() { return mst.checkAllCancleFun() }, toggleShowNameOrLabel: mst.sys.toggleShowNameOrLabel, toggleTabOrTree: mst.sys.toggleTabOrTree.bind(mst.sys), get Sys() { return mst.sys }, changeModuleValue: mst.sys.changeModuleValue.bind(mst.sys), setSearch } }
the_stack
import { Nes } from "./nes"; import { BitHelper } from "./bithelper"; import { ToneJS } from "./tonejs"; declare var Tone; export class APU { audioContext: AudioContext; nes: Nes; masterGainNode: GainNode; useDuty = true; _soundDisabled = true; //for performance, don't process registers if disabled FREQUENCY_RANGE_HIGH = 2000; FREQUENCY_RANGE_LOW = 10; //channels square1: SoundChannel; square2: SoundChannel; triangle: SoundChannel; noise: SoundChannel; lengthCounterTable = [10, 254, 20, 2, 40, 4, 80, 6, 160, 8, 60, 10, 14, 12, 26, 14, 12, 16, 24, 18, 48, 20, 96, 22, 192, 24, 72, 26, 16, 28, 32, 30]; frameCounterMode = 0; constructor(nes: Nes) { this.nes = nes; this.square1 = new SoundChannel(this, "square"); this.square2 = new SoundChannel(this, "square"); this.triangle = new SoundChannel(this, "triangle"); this.noise = new SoundChannel(this, "noise"); } muteAll() { this.square1.disable(); this.square2.disable(); this.triangle.disable(); this.noise.disable(); this._soundDisabled = true; } unMuteAll() { this.square1.enable(); this.square2.enable(); this.triangle.enable(); // this.noise.enable(); this._soundDisabled = false; } initialize(audioContext: AudioContext) { Tone.context.resume(); //currently disable noise channel by default this.noise.disable(); /* this.audioContext = audioContext; //gain node this.masterGainNode = this.audioContext.createGain(); this.masterGainNode.connect(this.audioContext.destination); this.masterGainNode.gain.value = .2; //50% volume */ } writeRegister(address: number, value: number) { if (this._soundDisabled) return; // Reference // $4000-$4003 First square wave // $4004-$4007 Second square wave // $4008-$400B Triangle wave // $400C-$400F Noise // $4010-$4013 DMC //square 1 if (address >= 0x4000 && address < 0x4004) { this.square1.processRegister(address, value); } //square 2 if (address >= 0x4004 && address < 0x4008) { this.square2.processRegister(address, value); } //triangle if (address >= 0x4008 && address < 0x400C) { this.triangle.processRegister(address, value); } //noise if (address >= 0x400C && address < 0x4010) { this.noise.processRegister(address, value); } if (address == 0x4015) { //enable or disable channels let squareEnable1 = BitHelper.getBit(value, 0); let squareEnable2 = BitHelper.getBit(value, 1); let triangleEnable = BitHelper.getBit(value, 2); let noiseEnable = BitHelper.getBit(value, 3); if (squareEnable1 == 1) this.square1.registerEnable(); else this.square1.registerDisable(); if (squareEnable2 == 1) this.square2.registerEnable(); else this.square2.registerDisable(); if (triangleEnable == 1) { this.triangle.registerEnable(); } else { //Use $4015 to turn off the channel, which will clear its length counter. //To resume, turn it back on via $4015, then write to $400B to reload the length counter. this.triangle.lengthCounter = 0; this.triangle.triangleLinearCounterReloadFlag = false; this.triangle.registerDisable(); } if (noiseEnable == 1) this.noise.registerEnable(); else this.noise.registerDisable(); } //frame counter //mode 0 = 4 step, mode 1 = 5 step // https://wiki.nesdev.com/w/index.php/APU#Triangle_.28.244008-400B.29 if (address == 0x4017){ //TODO need to add a fifth frame for framecountermode = 1 //this is why percussion is off in mario noise channel //lengthCounter entry of 2 should play instead of //decrememnting to zero during the same frame this.frameCounterMode = BitHelper.getBit(value,7); } } //one nes half frame halfFrame() { if (this._soundDisabled) return; //half frames this.square1.sweepProcess(); this.square2.sweepProcess(); //quarter frame this.square1.envelopeProcess(); this.square1.envelopeProcess(); this.square2.envelopeProcess(); this.square2.envelopeProcess(); //half frame this.square1.countersProcess(); this.square2.countersProcess(); this.triangle.countersProcess(); this.noise.countersProcess(); } abruptTriangleVolumeHalt = false; //only set the volumes after alls said and done adjustVolumes(){ if (this._soundDisabled) return; if (this.square1.enabled) this.square1.tone.volume.value = this.square1.volume; if (this.square2.enabled) this.square2.tone.volume.value = this.square2.volume; if (this.triangle.enabled){ let triggerAttack = false; let triggerRelease = false; //apply amplitude filter to help with triangle popping noises if (this.triangle.amplitudeFilterMode){ if (this.triangle.amplitudeVolumeHolder==-100 && this.triangle.volume==this.triangle.TRIANGLE_VOLUME) triggerAttack = true; if (this.triangle.amplitudeVolumeHolder==this.triangle.TRIANGLE_VOLUME && this.triangle.volume==-100) triggerRelease = true; this.triangle.amplitudeVolumeHolder = this.triangle.volume; //abrupt halt causes a popping noise //because of abrupt volume cutoff //adjusted release stage to be .01 //in order to compensate if (this.abruptTriangleVolumeHalt) this.triangle.tone.volume.value = this.triangle.volume; else this.triangle.tone.volume.value = this.triangle.TRIANGLE_VOLUME; if (triggerAttack) this.triangle.amplitudeEnvelope.triggerAttack(); if (triggerRelease) this.triangle.amplitudeEnvelope.triggerRelease(); }else this.triangle.tone.volume.value = this.triangle.volume; } if (this.noise.enabled) this.noise.tone.volume.value = this.noise.volume; } } export class SoundChannel { apu: APU; tone: ToneJS; //ToneJS Oscillator waveType: string; soundTimingLowByte = 0; soundTimingHighByte = 0; soundTiming = 0; dutyCycle = 0.5; volume = -100; sweepMode = false; sweepShiftAmount = 0; sweepNegate = 0; sweepPeriod = 0; sweepFrameCounter = 0; CPU_SPEED = 1789773; debugCurrentFrequency = 0; //for debugging lengthCounterHalt = 0; triangleLinearCounter = 0; triangleLinearCounterMax = 0; triangleLinearCounterReloadFlag = false; constantVolume = 0; lengthCounter = 0; enabled = true; //for my debugging, turning channels on and off registerEnabled = false; //wait until enable or disable from $4015 register SQUARE_VOLUME = -20; TRIANGLE_VOLUME = -10; NOISE_VOLUME = -25; //ADSR to help filter out some of the popping noise of the triangle channel amplitudeFilterMode = true; amplitudeEnvelope:any; amplitudeVolumeHolder:number = 0; envelopeRestart = false; envelopeDividerPeriod = 0; //how long the envelope will last envelopeDividerCounter = 0; //count down of the envelope divider period envelopeCounter = 0; //the current volume to set envelopeLoop = 0; //if we are looping registerVolume = 0; //volume that comes from register, don't think this is being used constructor(apu: APU, waveType: string) { this.apu = apu; this.waveType = waveType; //Initial state try { if (waveType == "square") { this.tone = new Tone.Oscillator(440, "square"); this.tone.volume.value = -100; this.tone.toMaster(); this.tone.start(); //TODO bring back duty cycle //currently disabled tone width //beacause tone.oscillator doesn't have that property //however the square wave sounds better than the tone.pulseoscillator // this.tone = new Tone.PulseOscillator(440, 0.5); // this.tone.width.value = .5; // this.tone.volume.value = -100; // this.tone.toMaster(); // this.tone.start(); } if (waveType == "triangle") { this.tone = new Tone.Oscillator(440, "triangle"); this.tone.volume.value = -100; if (this.amplitudeFilterMode){ // this.env = new Tone.AmplitudeEnvelope(.5,.1,.5,.5); // this.amplitudeEnvelope = new Tone.AmplitudeEnvelope(.01,.1,.8,.5); this.amplitudeEnvelope = new Tone.AmplitudeEnvelope(); this.tone.connect(this.amplitudeEnvelope); this.amplitudeEnvelope.toMaster(); this.tone.volume.value = this.TRIANGLE_VOLUME; this.amplitudeEnvelope.release=.01; } else{ this.TRIANGLE_VOLUME -= 10; this.tone.toMaster(); } this.tone.start(); } if (waveType == "noise") { this.tone = new Tone.Noise("white"); this.tone.volume.value = -100; this.tone.toMaster(); this.tone.start(); } } catch (error) { //in case Tone doesn't work } } disable() { this.enabled = false; this.tone.volume.value = -100; this.debugCurrentFrequency = 0; this.stop(); } enable() { this.enabled = true; } //fix for double dragon while paused should be silent //comes from $4015 registerDisable(){ this.stop(); this.registerEnabled = false; } registerEnable(){ this.registerEnabled = true; //has to be in this order this.start(); } //will be twice a frame countersProcess() { if (this.lengthCounterHalt==0) //as long as length counter halt is not set this.lengthCounter--; if (this.waveType == "square" || this.waveType=="noise"){ if (this.lengthCounter<=0) { this.stop(); this.lengthCounter = 0; } } if (this.waveType == "triangle"){ //holy crap this was complex - (from nesdev) //When the frame counter generates a linear counter clock, the following actions occur in order: //If the linear counter reload flag is set, the linear counter is reloaded with the //counter reload value, otherwise if the linear counter is non-zero, it is decremented. //If the control flag is clear, the linear counter reload flag is cleared. if (this.triangleLinearCounterReloadFlag) { this.triangleLinearCounter = this.triangleLinearCounterMax; } else if (this.triangleLinearCounter) { this.triangleLinearCounter-=2; //runs 4 times a frame } if (this.lengthCounterHalt==0) { this.triangleLinearCounterReloadFlag = false; } //stops take priority over starts //you will see sometimes it's constantly starting/stopping //the triangle channel however via the adjustVolumes() function //will ultimately silence the channel if EITHER //triangleLinearCounter or lengthCounter reach 0 if (this.lengthCounter<=0) { this.stop(); this.lengthCounter = 0; } //or linear counter reaches zero if (this.triangleLinearCounter<=0){ this.stop(); this.triangleLinearCounter=0; } } } //adjusts frequency up or down automatically over time //to produce interesting sound effects like mario jumping sweepProcess() { if (this.sweepMode) { this.sweepFrameCounter++; if (this.sweepFrameCounter % this.sweepPeriod == 0) { if (this.sweepNegate == 1) this.soundTiming -= this.soundTiming >> this.sweepShiftAmount; else this.soundTiming += this.soundTiming >> this.sweepShiftAmount; this.setFrequency(); this.sweepFrameCounter = 0; } } } envelopeProcess(){ if (this.envelopeRestart) { this.envelopeRestart = false; this.envelopeCounter = 15; this.envelopeDividerCounter = this.envelopeDividerPeriod; } else{ //this is basically two loops //outer loop is envelopeDividerCounter //inner loop is envelopeCounter which we set to our volume if (this.envelopeDividerCounter>0){ this.envelopeDividerCounter--; if (this.envelopeDividerCounter==0){ this.envelopeCounter--; //volume decay //if we are looping if (this.envelopeCounter==0 && this.envelopeLoop){ this.envelopeCounter = 15; } //also reload the outer loop this.envelopeDividerCounter = this.envelopeDividerPeriod; } } if (this.envelopeDividerCounter==0) this.envelopeCounter=0; } if(this.constantVolume) { //envelope disabled return; } else{ //TODO slowly silence the volume instead of instantaneously if (this.envelopeCounter==0) this.volume = -100; } } processRegister(address: number, value: number) { if (this.enabled == false || this.registerEnabled==false) return; if (this.waveType == "square") { this.processRegisterSquare(address, value); } if (this.waveType == "triangle") { this.processRegisterTriangle(address, value); } if (this.waveType == "noise") { this.processRegisterNoise(address, value); } } processRegisterSquare(address: number, value: number) { let mode = address % 4; switch (mode) { //Volume, Envelope, length counter, duty cycle case 0: //parse duty cycle or "width" of square wave let duty = value >> 6; if (duty == 0) this.dutyCycle = .125; if (duty == 1) this.dutyCycle = .25; if (duty == 2) this.dutyCycle = .50; if (duty == 3) this.dutyCycle = .75; // this.tone.width.value = this.dutyCycle; //parse length counter halt flag this.lengthCounterHalt = BitHelper.getBit(value, 5); this.envelopeLoop = BitHelper.getBit(value, 5); //same bit as lengthCounterHalt this.constantVolume = BitHelper.getBit(value, 4); //parse volume let vol = value & 15; //extract first 4 bits if (vol == 0) this.volume = -100; else { this.volume = this.SQUARE_VOLUME - (15-vol); //adjust volume down accordingly } this.registerVolume = this.volume; //envelope this.envelopeRestart = true; this.envelopeDividerPeriod = vol + 1; this.setFrequency(); break; //sweep, direction, update rate, enabled case 1: let sweepEnabled = BitHelper.getBit(value, 7); if (sweepEnabled) { //EPPP.NSSS this.sweepShiftAmount = value & 7; //right 3 bits this.sweepNegate = BitHelper.getBit(value, 3) //4th bit this.sweepPeriod = ((value >> 4) & 7) + 1; //bits 5,6,7 this.sweepMode = true; this.sweepFrameCounter = 0; } else this.sweepMode = false; break; //Frequency Low Byte case 2: // this.soundPlaying = false; this.soundTimingLowByte = value; this.soundTiming = (this.soundTimingHighByte << 8) | this.soundTimingLowByte; this.setFrequency(); break; //Frequency High Byte (rightmost 3 bits), length counter case 3: this.envelopeRestart = true; this.soundTimingHighByte = 0; this.soundTimingHighByte = value & 7; //extract first 3 bits this.soundTiming = (this.soundTimingHighByte << 8) | this.soundTimingLowByte; this.lengthCounter = this.apu.lengthCounterTable[value >> 3]; //left 5 bits this.setFrequency(); break; } } processRegisterTriangle(address: number, value: number) { let mode = address % 4; switch (mode) { //length counter halt/linear counter control, linear counter load case 0: this.lengthCounterHalt = BitHelper.getBit(value, 7); this.triangleLinearCounterMax = value & 127; this.setFrequency(); break; //unused case 1: break; //Frequency Low Byte case 2: // this.soundPlaying = false; this.soundTimingLowByte = value; this.soundTiming = (this.soundTimingHighByte << 8) | this.soundTimingLowByte; this.setFrequency(); break; //Frequency High Byte (rightmost 3 bits), length counter case 3: this.triangleLinearCounterReloadFlag = true; //first reset values this.soundTimingHighByte = 0; this.soundTimingHighByte = value & 7; //extract first 3 bits this.soundTiming = (this.soundTimingHighByte << 8) | this.soundTimingLowByte; this.lengthCounter = this.apu.lengthCounterTable[value >> 3]; //left 5 bits this.setFrequency(); break; } } processRegisterNoise(address: number, value: number) { let mode = address % 4; switch (mode) { //Volume, Envelope, length counter case 0: //parse length counter halt flag this.lengthCounterHalt = BitHelper.getBit(value, 5); this.envelopeLoop = BitHelper.getBit(value, 5); //same bit as lengthCounterHalt this.constantVolume = BitHelper.getBit(value, 4); //parse volume let vol = value & 15; //extract first 4 bits if (vol == 0) this.volume = -100; else { this.volume = this.NOISE_VOLUME - (15-vol); //adjust volume down accordingly } this.registerVolume = vol; //envelope this.envelopeRestart = true; this.envelopeDividerPeriod = vol + 1; this.setFrequency(); break; //not used case 1: break; //mode and period case 2: this.setFrequency(); break; //length counter case 3: this.envelopeRestart = true; this.lengthCounter = this.apu.lengthCounterTable[value >> 3]; //left 5 bits //CURRENTLY A HACK FOR MARIO //otherwise percussion timing is off if (this.lengthCounter==2) this.lengthCounter=4; this.setFrequency(); break; } } start() { if (this.enabled == false || this.registerEnabled==false) return; //this causes sounds to continue when unwanted //like in zelda name select screen //or when walking down the steps // if (this.waveType=="square"){ // this.volume=this.registerVolume; // } if (this.waveType == "triangle") { if (this.lengthCounter>0 || this.triangleLinearCounter>0) { this.volume = this.TRIANGLE_VOLUME; } } } stop() { this.volume = -100; } setFrequency() { //currently not setting frequency of noise if (this.waveType=="noise") { this.start(); return; } //FORMULA // f = CPU / (16 * (t + 1)) //protect from divide by zero let frequency = 0; if ((16 * (this.soundTiming + 1)) != 0) { frequency = this.CPU_SPEED / (16 * (this.soundTiming + 1)); } //triangle plays one octave lower, divide frequency by 2 if (this.waveType == "triangle") frequency = frequency / 2; //TODO is 2000 the boundary? //protect against very high/low frequencies if ( (frequency > this.apu.FREQUENCY_RANGE_HIGH || frequency < this.apu.FREQUENCY_RANGE_LOW)) { // console.log('frequency out of range: ' + frequency) this.debugCurrentFrequency = 0; this.tone.frequency.value = 0; this.sweepMode = false; this.stop(); } else { this.debugCurrentFrequency = Math.floor(frequency); this.tone.frequency.value = frequency; this.start(); //otherwise double dragon doesn't work } } } export class Note { public static getNote(frequency:number):string{ if (frequency==0) return ''; let note = ''; let counter = 0; for(let i = 0;i<this.allNotes.length/2;i++){ let noteString = this.allNotes[counter] as string; let noteNumber = this.allNotes[counter+1] as number; if (frequency<=noteNumber){ note = noteString; //compare to see if it's closer to the next note if (counter>0){ let lastNoteNumber = this.allNotes[counter-1] as number; let diff = noteNumber-lastNoteNumber; let diff2 = noteNumber-frequency; if (diff2>diff/2) note = this.allNotes[counter-2] as string; } break; } counter+=2; } return note; } static allNotes: any[] = [ 'C0', 16.35, 'C#0', 17.32, 'D0', 18.35, 'D#0', 19.45, 'E0', 20.60, 'F0', 21.83, 'F#0', 23.12, 'G0', 24.50, 'G#0', 25.96, 'A0', 27.50, 'A#0', 29.14, 'B0', 30.87, 'C1', 32.70, 'C#1', 34.65, 'D1', 36.71, 'D#1', 38.89, 'E1', 41.20, 'F1', 43.65, 'F#1', 46.25, 'G1', 49.00, 'G#1', 51.91, 'A1', 55.00, 'A#1', 58.27, 'B1', 61.74, 'C2', 65.41, 'C#2', 69.30, 'D2', 73.42, 'D#2', 77.78, 'E2', 82.41, 'F2', 87.31, 'F#2', 92.50, 'G2', 98.00, 'G#2', 103.83, 'A2', 110.00, 'A#2', 116.54, 'B2', 123.47, 'C3', 130.81, 'C#3', 138.59, 'D3', 146.83, 'D#3', 155.56, 'E3', 164.81, 'F3', 174.61, 'F#3', 185.00, 'G3', 196.00, 'G#3', 207.65, 'A3', 220.00, 'A#3', 233.08, 'B3', 246.94, 'C4', 261.63, 'C#4', 277.18, 'D4', 293.66, 'D#4', 311.13, 'E4', 329.63, 'F4', 349.23, 'F#4', 369.99, 'G4', 392.00, 'G#4', 415.30, 'A4', 440.00, 'A#4', 466.16, 'B4', 493.88, 'C5', 523.25, 'C#5', 554.37, 'D5', 587.33, 'D#5', 622.25, 'E5', 659.26, 'F5', 698.46, 'F#5', 739.99, 'G5', 783.99, 'G#5', 830.61, 'A5', 880.00, 'A#5', 932.33, 'B5', 987.77, 'C6', 1046.50, 'C#6', 1108.73, 'D6', 1174.66, 'D#6', 1244.51, 'E6', 1318.51, 'F6', 1396.91, 'F#6', 1479.98, 'G6', 1567.98, 'G#6', 1661.22, 'A6', 1760.00, 'A#6', 1864.66, 'B6', 1975.53, 'C7', 2093.00, 'C#7', 2217.46, 'D7', 2349.32, 'D#7', 2489.02, 'E7', 2637.02, 'F7', 2793.83, 'F#7', 2959.96, 'G7', 3135.96, 'G#7', 3322.44, 'A7', 3520.00, 'A#7', 3729.31, 'B7', 3951.07, 'C8', 4186.01, 'C#8', 4434.92, 'D8', 4698.64, 'D#8', 4978.03, 'E8', 5274.04, 'F8', 5587.65, 'F#8', 5919.91, 'G8', 6271.93, 'G#8', 6644.88, 'A8', 7040.00, 'A#8', 7458.62, 'B8', 7902.13, ]; }
the_stack
import InternalMouseEvent from '../event/InternalMouseEvent'; import { NONE, OUTLINE_COLOR, OUTLINE_HANDLE_FILLCOLOR, OUTLINE_HANDLE_STROKECOLOR, OUTLINE_STROKEWIDTH, } from '../../util/Constants'; import Point from '../geometry/Point'; import Rectangle from '../geometry/Rectangle'; import RectangleShape from '../geometry/node/RectangleShape'; import { Graph, defaultPlugins } from '../Graph'; import ImageShape from '../geometry/node/ImageShape'; import InternalEvent from '../event/InternalEvent'; import Image from '../image/ImageBox'; import EventObject from '../event/EventObject'; import { getSource, isMouseEvent } from '../../util/EventUtils'; import EventSource from '../event/EventSource'; import { hasScrollbars } from '../../util/styleUtils'; import { Listenable } from '../../types'; /** * @class Outline * * Implements an outline (aka overview) for a graph. Set {@link updateOnPan} to true * to enable updates while the source graph is panning. * * ### Example * * ```javascript * var outline = new mxOutline(graph, div); * ``` * * If an outline is used in an {@link MaxWindow} in IE8 standards mode, the following * code makes sure that the shadow filter is not inherited and that any * transparent elements in the graph do not show the page background, but the * background of the graph container. * * ```javascript * if (document.documentMode == 8) * { * container.style.filter = 'progid:DXImageTransform.Microsoft.alpha(opacity=100)'; * } * ``` * * To move the graph to the top, left corner the following code can be used. * * ```javascript * var scale = graph.view.scale; * var bounds = graph.getGraphBounds(); * graph.view.setTranslate(-bounds.x / scale, -bounds.y / scale); * ``` * * To toggle the suspended mode, the following can be used. * * ```javascript * outline.suspended = !outln.suspended; * if (!outline.suspended) * { * outline.update(true); * } * ``` */ class Outline { constructor(source: Graph, container: HTMLElement | null = null) { this.source = source; if (container != null) { this.init(container); } } /** * Initializes the outline inside the given container. */ init(container: HTMLElement): void { this.outline = this.createGraph(container); // Do not repaint when suspended const outlineGraphModelChanged = this.outline.graphModelChanged; this.outline.graphModelChanged = (changes: any) => { if (!this.suspended && this.outline != null) { outlineGraphModelChanged.apply(this.outline, [changes]); } }; // Enable faster painting in SVG //const node = <SVGElement>this.outline.getView().getCanvas().parentNode; //node.setAttribute('shape-rendering', 'optimizeSpeed'); //node.setAttribute('image-rendering', 'optimizeSpeed'); // Hides cursors and labels this.outline.labelsVisible = this.labelsVisible; this.outline.setEnabled(false); this.updateHandler = (sender: any, evt: EventObject) => { if (!this.suspended && !this.active) { this.update(); } }; // Updates the scale of the outline after a change of the main graph this.source.getDataModel().addListener(InternalEvent.CHANGE, this.updateHandler); this.outline.addMouseListener(this); // Adds listeners to keep the outline in sync with the source graph const view = this.source.getView(); view.addListener(InternalEvent.SCALE, this.updateHandler); view.addListener(InternalEvent.TRANSLATE, this.updateHandler); view.addListener(InternalEvent.SCALE_AND_TRANSLATE, this.updateHandler); view.addListener(InternalEvent.DOWN, this.updateHandler); view.addListener(InternalEvent.UP, this.updateHandler); // Updates blue rectangle on scroll // @ts-ignore because sender and evt don't seem used InternalEvent.addListener(this.source.container, 'scroll', this.updateHandler); this.panHandler = (sender: any, evt: EventObject) => { if (this.updateOnPan) { (<Function>this.updateHandler)(sender, evt); } }; this.source.addListener(InternalEvent.PAN, this.panHandler); // Refreshes the graph in the outline after a refresh of the main graph this.refreshHandler = (sender: any) => { const outline = <Graph>this.outline; outline.setStylesheet(this.source.getStylesheet()); outline.refresh(); }; this.source.addListener(InternalEvent.REFRESH, this.refreshHandler); // Creates the blue rectangle for the viewport this.bounds = new Rectangle(0, 0, 0, 0); this.selectionBorder = new RectangleShape( this.bounds, NONE, OUTLINE_COLOR, OUTLINE_STROKEWIDTH ); this.selectionBorder.dialect = this.outline.dialect; this.selectionBorder.init(this.outline.getView().getOverlayPane()); const selectionBorderNode = <SVGGElement>this.selectionBorder.node; // Handles event by catching the initial pointer start and then listening to the // complete gesture on the event target. This is needed because all the events // are routed via the initial element even if that element is removed from the // DOM, which happens when we repaint the selection border and zoom handles. const handler = (evt: MouseEvent) => { const t = getSource(evt); const redirect = (evt: MouseEvent) => { const outline = <Graph>this.outline; outline.fireMouseEvent(InternalEvent.MOUSE_MOVE, new InternalMouseEvent(evt)); }; var redirect2 = (evt: MouseEvent) => { const outline = <Graph>this.outline; InternalEvent.removeGestureListeners(<Listenable>t, null, redirect, redirect2); outline.fireMouseEvent(InternalEvent.MOUSE_UP, new InternalMouseEvent(evt)); }; const outline = <Graph>this.outline; InternalEvent.addGestureListeners(<Listenable>t, null, redirect, redirect2); outline.fireMouseEvent(InternalEvent.MOUSE_DOWN, new InternalMouseEvent(evt)); }; InternalEvent.addGestureListeners(this.selectionBorder.node, handler); // Creates a small blue rectangle for sizing (sizer handle) const sizer = (this.sizer = this.createSizer()); const sizerNode = <SVGGElement>sizer.node; sizer.init(this.outline.getView().getOverlayPane()); if (this.enabled) { sizerNode.style.cursor = 'nwse-resize'; } InternalEvent.addGestureListeners(this.sizer.node, handler); selectionBorderNode.style.display = this.showViewport ? '' : 'none'; sizerNode.style.display = selectionBorderNode.style.display; selectionBorderNode.style.cursor = 'move'; this.update(false); } // TODO: Document me!! sizer: RectangleShape | null = null; selectionBorder: RectangleShape | null = null; updateHandler: ((sender: any, evt: EventObject) => void) | null = null; refreshHandler: ((sender: any, evt: EventObject) => void) | null = null; panHandler: ((sender: any, evt: EventObject) => void) | null = null; active: boolean | null = null; bounds: Rectangle | null = null; zoom: boolean = false; startX: number | null = null; startY: number | null = null; dx0: number | null = null; dy0: number | null = null; index: number | null = null; /** * Reference to the source {@link graph}. */ source: Graph; /** * Reference to the {@link graph} that renders the outline. */ outline: Graph | null = null; /** * Renderhint to be used for the outline graph. * @default faster */ graphRenderHint: string = 'exact'; /** * Specifies if events are handled. * @default true */ enabled: boolean = true; /** * Specifies a viewport rectangle should be shown. * @default true */ showViewport: boolean = true; /** * Border to be added at the bottom and right. * @default 10 */ border: number = 10; /** * Specifies the size of the sizer handler. * @default 8 */ sizerSize: number = 8; /** * Specifies if labels should be visible in the outline. * @default false */ labelsVisible: boolean = false; /** * Specifies if {@link update} should be called for {@link InternalEvent.PAN} in the source * graph. * @default false */ updateOnPan: boolean = false; /** * Optional {@link Image} to be used for the sizer. * @default null */ sizerImage: Image | null = null; /** * Minimum scale to be used. * @default 0.0001 */ minScale: number = 0.0001; /** * Optional boolean flag to suspend updates. This flag will * also suspend repaints of the outline. To toggle this switch, use the * following code. * * @default false * * @example * ```javascript * nav.suspended = !nav.suspended; * * if (!nav.suspended) * { * nav.update(true); * } * ``` */ suspended: boolean = false; /** * Creates the {@link graph} used in the outline. */ createGraph(container: HTMLElement): Graph { const graph = new Graph( container, this.source.getDataModel(), defaultPlugins, this.source.getStylesheet() ); graph.foldingEnabled = false; graph.autoScroll = false; return graph; } /** * Returns true if events are handled. This implementation * returns {@link enabled}. */ isEnabled(): boolean { return this.enabled; } /** * Enables or disables event handling. This implementation * updates {@link enabled}. * * @param value Boolean that specifies the new enabled state. */ setEnabled(value: boolean): void { this.enabled = value; } /** * Enables or disables the zoom handling by showing or hiding the respective * handle. * * @param value Boolean that specifies the new enabled state. */ setZoomEnabled(value: boolean): void { // @ts-ignore this.sizer.node.style.visibility = value ? 'visible' : 'hidden'; } /** * Invokes {@link update} and revalidate the outline. This method is deprecated. */ refresh(): void { this.update(true); } /** * Creates the shape used as the sizer. */ // createSizer(): mxShape; createSizer(): RectangleShape { const outline = <Graph>this.outline; if (this.sizerImage != null) { const sizer = new ImageShape( new Rectangle(0, 0, this.sizerImage.width, this.sizerImage.height), this.sizerImage.src ); sizer.dialect = outline.dialect; return sizer; } const sizer = new RectangleShape( new Rectangle(0, 0, this.sizerSize, this.sizerSize), OUTLINE_HANDLE_FILLCOLOR, OUTLINE_HANDLE_STROKECOLOR ); sizer.dialect = outline.dialect; return sizer; } /** * Returns the size of the source container. */ getSourceContainerSize(): Rectangle { return new Rectangle( 0, 0, (<HTMLElement>this.source.container).scrollWidth, (<HTMLElement>this.source.container).scrollHeight ); } /** * Returns the offset for drawing the outline graph. */ getOutlineOffset(scale?: number): Point | null { // TODO: Should number -> mxPoint? return null; } /** * Returns the offset for drawing the outline graph. */ getSourceGraphBounds(): Rectangle { return this.source.getGraphBounds(); } /** * Updates the outline. */ update(revalidate: boolean = false): void { if ( this.source != null && this.source.container != null && this.outline != null && this.outline.container != null ) { const sourceScale = this.source.view.scale; const scaledGraphBounds = this.getSourceGraphBounds(); const unscaledGraphBounds = new Rectangle( scaledGraphBounds.x / sourceScale + this.source.panDx, scaledGraphBounds.y / sourceScale + this.source.panDy, scaledGraphBounds.width / sourceScale, scaledGraphBounds.height / sourceScale ); const unscaledFinderBounds = new Rectangle( 0, 0, this.source.container.clientWidth / sourceScale, this.source.container.clientHeight / sourceScale ); const union = unscaledGraphBounds.clone(); union.add(unscaledFinderBounds); // Zooms to the scrollable area if that is bigger than the graph const size = this.getSourceContainerSize(); const completeWidth = Math.max(size.width / sourceScale, union.width); const completeHeight = Math.max(size.height / sourceScale, union.height); const availableWidth = Math.max( 0, this.outline.container.clientWidth - this.border ); const availableHeight = Math.max( 0, this.outline.container.clientHeight - this.border ); const outlineScale = Math.min( availableWidth / completeWidth, availableHeight / completeHeight ); let scale = Number.isNaN(outlineScale) ? this.minScale : Math.max(this.minScale, outlineScale); if (scale > 0) { if (this.outline.getView().scale !== scale) { this.outline.getView().scale = scale; revalidate = true; } const navView = this.outline.getView(); if (navView.currentRoot !== this.source.getView().currentRoot) { navView.setCurrentRoot(this.source.getView().currentRoot); } const t = this.source.view.translate; let tx = t.x + this.source.panDx; let ty = t.y + this.source.panDy; const off = this.getOutlineOffset(scale); if (off != null) { tx += off.x; ty += off.y; } if (unscaledGraphBounds.x < 0) { tx -= unscaledGraphBounds.x; } if (unscaledGraphBounds.y < 0) { ty -= unscaledGraphBounds.y; } if (navView.translate.x !== tx || navView.translate.y !== ty) { navView.translate.x = tx; navView.translate.y = ty; revalidate = true; } // Prepares local variables for computations const t2 = navView.translate; scale = this.source.getView().scale; const scale2 = scale / navView.scale; const scale3 = 1.0 / navView.scale; const { container } = this.source; // Updates the bounds of the viewrect in the navigation this.bounds = new Rectangle( (t2.x - t.x - this.source.panDx) / scale3, (t2.y - t.y - this.source.panDy) / scale3, container.clientWidth / scale2, container.clientHeight / scale2 ); // Adds the scrollbar offset to the finder this.bounds.x += (this.source.container.scrollLeft * navView.scale) / scale; this.bounds.y += (this.source.container.scrollTop * navView.scale) / scale; const selectionBorder = <RectangleShape>this.selectionBorder; let b = <Rectangle>selectionBorder.bounds; if ( b.x !== this.bounds.x || b.y !== this.bounds.y || b.width !== this.bounds.width || b.height !== this.bounds.height ) { selectionBorder.bounds = this.bounds; selectionBorder.redraw(); } // Updates the bounds of the zoom handle at the bottom right const sizer = <RectangleShape>this.sizer; b = <Rectangle>sizer.bounds; const b2 = new Rectangle( this.bounds.x + this.bounds.width - b.width / 2, this.bounds.y + this.bounds.height - b.height / 2, b.width, b.height ); if ( b.x !== b2.x || b.y !== b2.y || b.width !== b2.width || b.height !== b2.height ) { sizer.bounds = b2; // Avoids update of visibility in redraw for VML if ((<SVGGElement>sizer.node).style.visibility !== 'hidden') { sizer.redraw(); } } if (revalidate) { this.outline.view.revalidate(); } } } } /** * Handles the event by starting a translation or zoom. */ mouseDown(sender: EventSource, me: InternalMouseEvent): void { if (this.enabled && this.showViewport) { const tol = !isMouseEvent(me.getEvent()) ? this.source.tolerance : 0; const hit = tol > 0 ? new Rectangle(me.getGraphX() - tol, me.getGraphY() - tol, 2 * tol, 2 * tol) : null; this.zoom = me.isSource(this.sizer) || // @ts-ignore (hit != null && intersects(this.sizer.bounds, hit)); this.startX = me.getX(); this.startY = me.getY(); this.active = true; const sourceContainer = <HTMLElement>this.source.container; if (this.source.useScrollbarsForPanning && hasScrollbars(this.source.container)) { this.dx0 = sourceContainer.scrollLeft; this.dy0 = sourceContainer.scrollTop; } else { this.dx0 = 0; this.dy0 = 0; } } me.consume(); } /** * Handles the event by previewing the viewrect in {@link graph} and updating the * rectangle that represents the viewrect in the outline. */ mouseMove(sender: EventSource, me: InternalMouseEvent): void { if (this.active) { const myBounds = <Rectangle>this.bounds; const sizer = <RectangleShape>this.sizer; const sizerNode = <SVGGElement>sizer.node; const selectionBorder = <RectangleShape>this.selectionBorder; const selectionBorderNode = <SVGGElement>selectionBorder.node; const source = <Graph>this.source; const outline = <Graph>this.outline; selectionBorderNode.style.display = this.showViewport ? '' : 'none'; sizerNode.style.display = selectionBorderNode.style.display; const delta = this.getTranslateForEvent(me); let dx = delta.x; let dy = delta.y; let bounds = null; if (!this.zoom) { // Previews the panning on the source graph const { scale } = outline.getView(); bounds = new Rectangle( myBounds.x + dx, myBounds.y + dy, myBounds.width, myBounds.height ); selectionBorder.bounds = bounds; selectionBorder.redraw(); dx /= scale; dx *= source.getView().scale; dy /= scale; dy *= source.getView().scale; source.panGraph(-dx - <number>this.dx0, -dy - <number>this.dy0); } else { // Does *not* preview zooming on the source graph const { container } = <Graph>this.source; // @ts-ignore const viewRatio = container.clientWidth / container.clientHeight; dy = dx / viewRatio; bounds = new Rectangle( myBounds.x, myBounds.y, Math.max(1, myBounds.width + dx), Math.max(1, myBounds.height + dy) ); selectionBorder.bounds = bounds; selectionBorder.redraw(); } // Updates the zoom handle const b = <Rectangle>sizer.bounds; sizer.bounds = new Rectangle( bounds.x + bounds.width - b.width / 2, bounds.y + bounds.height - b.height / 2, b.width, b.height ); // Avoids update of visibility in redraw for VML if (sizerNode.style.visibility !== 'hidden') { sizer.redraw(); } me.consume(); } } /** * Gets the translate for the given mouse event. Here is an example to limit * the outline to stay within positive coordinates: * * @example * ```javascript * outline.getTranslateForEvent(me) * { * var pt = new mxPoint(me.getX() - this.startX, me.getY() - this.startY); * * if (!this.zoom) * { * var tr = this.source.view.translate; * pt.x = Math.max(tr.x * this.outline.view.scale, pt.x); * pt.y = Math.max(tr.y * this.outline.view.scale, pt.y); * } * * return pt; * }; * ``` */ getTranslateForEvent(me: InternalMouseEvent): Point { return new Point(me.getX() - <number>this.startX, me.getY() - <number>this.startY); } /** * Handles the event by applying the translation or zoom to {@link graph}. */ mouseUp(sender: EventSource, me: InternalMouseEvent): void { if (this.active) { const delta = this.getTranslateForEvent(me); let dx = delta.x; let dy = delta.y; const source = <Graph>this.source; const outline = <Graph>this.outline; const selectionBorder = <RectangleShape>this.selectionBorder; if (Math.abs(dx) > 0 || Math.abs(dy) > 0) { if (!this.zoom) { // Applies the new translation if the source // has no scrollbars if (!source.useScrollbarsForPanning || !hasScrollbars(source.container)) { source.panGraph(0, 0); dx /= outline.getView().scale; dy /= outline.getView().scale; const t = source.getView().translate; source.getView().setTranslate(t.x - dx, t.y - dy); } } else { // Applies the new zoom const w = (<Rectangle>selectionBorder.bounds).width; const { scale } = source.getView(); source.zoomTo(Math.max(this.minScale, scale - (dx * scale) / w), false); } this.update(); me.consume(); } // Resets the state of the handler this.index = null; this.active = false; } } /** * Destroy this outline and removes all listeners from {@link source}. */ destroy(): void { if (this.source != null) { // @ts-ignore this.source.removeListener(this.panHandler); // @ts-ignore this.source.removeListener(this.refreshHandler); // @ts-ignore this.source.getDataModel().removeListener(this.updateHandler); // @ts-ignore this.source.getView().removeListener(this.updateHandler); // @ts-ignore InternalEvent.removeListener(this.source.container, 'scroll', this.updateHandler); // @ts-ignore this.source = null; } if (this.outline != null) { this.outline.removeMouseListener(this); this.outline.destroy(); this.outline = null; } if (this.selectionBorder != null) { this.selectionBorder.destroy(); this.selectionBorder = null; } if (this.sizer != null) { this.sizer.destroy(); this.sizer = null; } } } export default Outline;
the_stack
namespace PE { export const CHARACTERS_PER_LINE = 55; export enum Battle_Phase { Start = "Start", Input = "Input", Turn = "Turn", Action = "Action", BatledEnd = "BatledEnd" } export enum InputPhases { Action = "Action", Move = "Move", Item = "Item", Party = "Party", PartySwitchFainted = "PartySwitchFainted" } export enum WaitModes { Animation = "Animation", None = "None" } export enum BattleActionType { UseMove, UseItem, Switch, Run } export interface IBattleAction { type: BattleActionType; /** The tragets slot indexes */ targets: number[]; move?: PE.Battle.Moves.Move; item?: PE.ITEMDEX; switchInIndex?: number; } export class Battle_Manager { private static _actionsQueue: Battle_Battler[] = []; private static _battlers: Battle_Battler[] = []; private static _actives: Battle_Battler[] = []; /** The current active battler performing his selected action */ private static _subject: Battle_Battler = undefined; private static _currentAction: IBattleAction = undefined; static sides: { player: Battle_Side; foe: Battle_Side }; public static phase: Battle_Phase | InputPhases = undefined; static turn: number; /** * */ private static _activeMove: Battle_Move; private static _activeSource: Battle_Battler; private static _activeTarget: Battle_Battler; public static weather: WEATHERS; static init(p1: PE.Pokemon.Pokemon[], p2: PE.Pokemon.Pokemon[]) { console.log("Player Pokemons"); console.log("=========================================================="); console.log(p1.map(p => p.name)); console.log("Foe Pokemons"); console.log("=========================================================="); console.log(p2.map(p => p.name)); this.sides = { player: new Battle_Side(), foe: new Battle_Side() }; for (const pokemon of p1) { let battler = new Battle_Battler(pokemon); battler.partyIndex = this.sides.player.party.length; battler.sides.own = this.sides.player; battler.sides.foe = this.sides.foe; this.sides.player.party.push(battler); } for (const pokemon of p2) { let battler = new Battle_Battler(pokemon); battler.partyIndex = this.sides.foe.party.length; battler.sides.own = this.sides.foe; battler.sides.foe = this.sides.player; this.sides.foe.party.push(battler); } this.turn = 0; BattleEventQueue.waitMode = WaitModes.None; } static get actives() { return this.sides.player.slots.concat(this.sides.foe.slots); } static update() { BattleEventQueue.update(); if (BattleEventQueue.isBusy()) return; switch (this.phase) { case Battle_Phase.Start: this.startInput(); break; case Battle_Phase.Turn: this.updateTurn(); break; case Battle_Phase.Action: this.updateAction(); break; case Battle_Phase.BatledEnd: SceneManager.goto(PE.TitleScenes.CustomScene); break; } } static startBattle() { this.changePhase(Battle_Phase.Start); this.switchInStartBattlers(); this.showStartMessages(); } static switchInStartBattlers() { let battlers: Battle_Battler[] = []; battlers = battlers.concat(this.actives); battlers.sort((a, b) => this.getPriority(a, b)); // for (const b of battlers) { // b.sides.own.switchInStartBattlers(); // } this.sides.player.switchInStartBattlers(); this.sides.foe.switchInStartBattlers(); } static showStartMessages() { // this.showPausedMessage("This is a battle test scenario, open the devtools press the F12 key to see the battle log"); // this.showPausedMessage("press the enter key to avance turns"); } static startInput() { // IA select moves // the battler actions input is handle in the battle scene this.changePhase(Battle_Phase.Input); } static endActionsSelection() { this.dummyActionSelection(); this.startTurn(); } static startTurn() { this.turn++; console.log("----------------------------------------------------------"); console.log(`# Turn ${this.turn}`); this.makeTurnOrder(); this.changePhase(Battle_Phase.Turn); } static updateTurn() { if (!this._subject) { this._subject = this.getNextSubject(); } if (this._subject) { this.processTurn(); } else { this.endTurn(); } } static processTurn() { let action = this._subject.getAction(); if (action) { this.startAction(action); } else { this._subject = this.getNextSubject(); } } static endTurn() { this.checkFaints(); this.checkBattleEnd(); this.changePhase(Battle_Phase.Input); } static getNextSubject() { let battler = this._actionsQueue.shift(); if (!battler) return null; if (!battler.isFainted()) return battler; return this.getNextSubject(); } static makeTurnOrder() { let battlers = []; battlers = battlers.concat(this.actives); battlers.sort((a, b) => this.getPriority(a, b)); this._actionsQueue = battlers; } static startAction(action) { this._currentAction = action; this.changePhase(Battle_Phase.Action); } static updateAction() { switch (this._currentAction.type) { case BattleActionType.Switch: this.switchBattlers(this._currentAction.switchInIndex); this.endAction(); break; case BattleActionType.UseMove: let target = this._currentAction.targets.shift(); if (target != undefined) { this.useMove(this._currentAction.move, target); } else { this.endAction(); } break; case BattleActionType.UseItem: this.endAction(); break; } } static endAction() { this._subject.clearAction(); this._currentAction = undefined; this._subject = undefined; this.changePhase(Battle_Phase.Turn); } static switchBattlers(partyIndex) { // this._subject.sides.own.switchBattlers(this._subject.slotIndex, partyIndex); let change = this._subject.sides.own.nextUnfaited(this._subject.partyIndex); this._subject.sides.own.switchBattlers(this._subject.slotIndex, change.partyIndex); } static useMove(move: PE.Battle.Moves.Move, target) { console.log(`> ${this._subject.species} used ${move.name} --> ${this._subject.sides.foe.slots[target].species}`); this.showMessage(`${this._subject.name} used ${move.name}!`); console.log(`: [${move.name}] accuracy ${move.accuracy}`); let hit = PE.Utils.chance(move.accuracy); if (move.accuracy === true || hit) { let foe = this._subject.sides.foe.slots[target]; let damage = this.calculateDamage(this._subject, foe, move); if (damage > 0) foe.damage(damage); } else { console.log("But failed!"); this.showMessage("But failed!"); } } static getPriority(a: Battle_Battler, b: Battle_Battler) { if (b.getAction().type - a.getAction().type) { return b.getAction().type - a.getAction().type; } if (b.speed - a.speed) { return b.speed - a.speed; } return Math.random() - 0.5; } static checkFaints() { for (const battler of this.sides.player.actives) { if (battler.isFainted() && !battler.sides.own.areAllFainted()) { // this.changePhase(InputPhases.PartySwitchFainted); let change = battler.sides.own.nextUnfaited(); battler.sides.own.switchBattlers(battler.slotIndex, change.partyIndex); } } for (const battler of this.sides.foe.actives) { if (battler.isFainted() && !battler.sides.own.areAllFainted()) { let change = battler.sides.own.nextUnfaited(); battler.sides.own.switchBattlers(battler.slotIndex, change.partyIndex); } } } static checkBattleEnd() { if (this.sides.foe.areAllFainted()) { this.processVictory(); } if (this.sides.player.areAllFainted()) { this.processDefead(); } } static processVictory() { console.log("# VICTORY"); console.log("=========================================================="); this.showPausedMessage("Visctory"); this.changePhase(Battle_Phase.BatledEnd); } static processDefead() { console.log("# DEFEAT"); console.log("=========================================================="); this.showPausedMessage("defeat"); this.changePhase(Battle_Phase.BatledEnd); } static changePhase(phase: Battle_Phase | InputPhases) { BattleEventQueue.push(() => { this.phase = phase; }, this); } static dummyActionSelection() { for (const battler of this.actives) { let action: IBattleAction = undefined; if (PE.Utils.chance(20) && battler.sides.own.nextUnfaited(battler.partyIndex)) { action = { targets: [0], type: BattleActionType.Switch, switchInIndex: 0 }; } else { action = { targets: [0], type: BattleActionType.UseMove, move: battler.getFirstDamageMove() }; } battler.setAction(action); } } static calculateDamage(source: Battle_Battler, target: Battle_Battler, move: PE.Battle.Moves.Move) { let basePower = move.basePower; console.log(`: [${move.name}] Base Power ${basePower}`); basePower = EventManager.run("BasePower", source, target, { move: move }, basePower); let atk = 0; let def = 0; if (move.category == PE.Battle.Moves.Categories.Special) { atk = source.spatk; def = target.spdef; } else if (move.category == PE.Battle.Moves.Categories.Physical) { atk = source.attack; def = target.defense; } else { return 0; } let effectiveness = PE.Types.effectiveness(move.type, target.types); let msg = null; if (effectiveness <= 0.5) { msg = `It's not very effective...`; } else if (effectiveness >= 2) { msg = `It's super effective!`; } else if (effectiveness == 0) { msg = `It doesn't affect ${target.name}`; } if (msg) { console.log("~ " + msg); this.showMessage(msg); } let stab = source.hasType(move.type) ? 1.5 : 1; let critical = 1; let random = Math.random() * 100; if (PE.Utils.chance(6.25)) { critical = 1.5; console.log("~ critical hit!"); this.showMessage("critical hit!"); } random = Math.random() * (1 - 0.81) + 0.81; let modifier = critical * random * stab * effectiveness; let damage = ((((2 * source.level) / 5 + 2) * basePower * (atk / def)) / 50 + 2) * modifier; return Math.max(Math.floor(damage), 1); } static showMessage(msg: string) { BattleEventQueue.push(() => { msg = PE.Utils.capitalize(msg); while (msg.length > CHARACTERS_PER_LINE) { let line = msg.substring(0, CHARACTERS_PER_LINE); let truncateIndex = Math.min(line.length, line.lastIndexOf(" ")); line = line.substring(0, truncateIndex); $gameMessage.add(line + "\\n"); msg = msg.substring(truncateIndex + 1); } $gameMessage.add(msg + "\\|\\^"); }); } static showPausedMessage(msg: string) { BattleEventQueue.push(() => { msg = PE.Utils.capitalize(msg); while (msg.length > CHARACTERS_PER_LINE) { let line = msg.substring(0, CHARACTERS_PER_LINE); let truncateIndex = Math.min(line.length, line.lastIndexOf(" ")); line = line.substring(0, truncateIndex + 1); $gameMessage.add(line + "\\n"); msg = msg.substring(truncateIndex + 1); } $gameMessage.add(msg); }); } static wait(mode: WaitModes) { BattleEventQueue.waitMode = mode; } /** * This is copy from showdown */ /** * sets the current move and pokemon */ static setActiveMove(move?: Battle_Move, source?: Battle_Battler, target?: Battle_Battler) { if (!move) move = null; if (!source) source = null; if (!target) target = source; this._activeMove = move; this._activeSource = source; this._activeTarget = target; } static tryMoveHit(target: Battle_Battler, pokemon: Battle_Battler, move: Battle_Move) { this.setActiveMove(move, pokemon, target); // move.zBrokeProtect = false; let hitResult = true; // hitResult = this.singleEvent('PrepareHit', move, {}, target, pokemon, move); // if (!hitResult) { // if (hitResult === false) this.add('-fail', target); // return false; // } // this.runEvent('PrepareHit', pokemon, target, move); // if (!this.singleEvent('Try', move, null, pokemon, target, move)) { // return false; // } // if (move.target === 'all' || move.target === 'foeSide' || move.target === 'allySide' || move.target === 'allyTeam') { // if (move.target === 'all') { // hitResult = this.runEvent('TryHitField', target, pokemon, move); // } else { // hitResult = this.runEvent('TryHitSide', target, pokemon, move); // } // if (!hitResult) { // if (hitResult === false) this.add('-fail', target); // return false; // } // return this.moveHit(target, pokemon, move); // } // hitResult = this.runEvent('TryImmunity', target, pokemon, move); // if (!hitResult) { // if (hitResult !== null) { // if (!move.spreadHit) this.attrLastMove('[miss]'); // this.add('-miss', pokemon, target); // } // return false; // } // if (move.ignoreImmunity === undefined) { // move.ignoreImmunity = (move.category === 'Status'); // } // if (this.gen < 7 && (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) && !target.runImmunity(move.type, true)) { // return false; // } // hitResult = this.runEvent('TryHit', target, pokemon, move); // if (!hitResult) { // if (hitResult === false) this.add('-fail', target); // return false; // } // if (this.gen >= 7 && (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) && !target.runImmunity(move.type, true)) { // return false; // } // if (move.flags['powder'] && target !== pokemon && !this.getImmunity('powder', target)) { // this.debug('natural powder immunity'); // this.add('-immune', target, '[msg]'); // return false; // } // if (this.gen >= 7 && move.pranksterBoosted && pokemon.hasAbility('prankster') && target.side !== pokemon.side && !this.getImmunity('prankster', target)) { // this.debug('natural prankster immunity'); // if (!target.illusion) this.add('-hint', "In gen 7, Dark is immune to Prankster moves."); // this.add('-immune', target, '[msg]'); // return false; // } // let boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3]; // // calculate true accuracy // let accuracy = move.accuracy; // let boosts, boost; // if (accuracy !== true) { // if (!move.ignoreAccuracy) { // boosts = this.runEvent('ModifyBoost', pokemon, null, null, Object.assign({}, pokemon.boosts)); // boost = this.clampIntRange(boosts['accuracy'], -6, 6); // if (boost > 0) { // accuracy *= boostTable[boost]; // } else { // accuracy /= boostTable[-boost]; // } // } // if (!move.ignoreEvasion) { // boosts = this.runEvent('ModifyBoost', target, null, null, Object.assign({}, target.boosts)); // boost = this.clampIntRange(boosts['evasion'], -6, 6); // if (boost > 0) { // accuracy /= boostTable[boost]; // } else if (boost < 0) { // accuracy *= boostTable[-boost]; // } // } // } // if (move.ohko) { // bypasses accuracy modifiers // if (!target.isSemiInvulnerable()) { // accuracy = 30; // if (move.ohko === 'Ice' && this.gen >= 7 && !pokemon.hasType('Ice')) { // accuracy = 20; // } // if (pokemon.level >= target.level && (move.ohko === true || !target.hasType(move.ohko))) { // accuracy += (pokemon.level - target.level); // } else { // this.add('-immune', target, '[ohko]'); // return false; // } // } // } else { // accuracy = this.runEvent('ModifyAccuracy', target, pokemon, move, accuracy); // } // if (move.alwaysHit || (move.id === 'toxic' && this.gen >= 6 && pokemon.hasType('Poison'))) { // accuracy = true; // bypasses ohko accuracy modifiers // } else { // accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy); // } // // @ts-ignore // if (accuracy !== true && !this.randomChance(accuracy, 100)) { // if (!move.spreadHit) this.attrLastMove('[miss]'); // this.add('-miss', pokemon, target); // return false; // } // if (move.breaksProtect) { // let broke = false; // for (const effectid of ['banefulbunker', 'kingsshield', 'protect', 'spikyshield']) { // if (target.removeVolatile(effectid)) broke = true; // } // if (this.gen >= 6 || target.side !== pokemon.side) { // for (const effectid of ['craftyshield', 'matblock', 'quickguard', 'wideguard']) { // if (target.side.removeSideCondition(effectid)) broke = true; // } // } // if (broke) { // if (move.id === 'feint') { // this.add('-activate', target, 'move: Feint'); // } else { // this.add('-activate', target, 'move: ' + move.name, '[broken]'); // } // } // } // if (move.stealsBoosts) { // let boosts = {}; // let stolen = false; // for (let statName in target.boosts) { // let stage = target.boosts[statName]; // if (stage > 0) { // boosts[statName] = stage; // stolen = true; // } // } // if (stolen) { // this.attrLastMove('[still]'); // this.add('-clearpositiveboost', target, pokemon, 'move: ' + move.name); // this.boost(boosts, pokemon, pokemon); // for (let statName in boosts) { // boosts[statName] = 0; // } // target.setBoost(boosts); // this.add('-anim', pokemon, "Spectral Thief", target); // } // } // move.totalDamage = 0; // /**@type {number | false} */ // let damage = 0; // pokemon.lastDamage = 0; // if (move.multihit) { // let hits = move.multihit; // if (Array.isArray(hits)) { // // yes, it's hardcoded... meh // if (hits[0] === 2 && hits[1] === 5) { // if (this.gen >= 5) { // hits = this.sample([2, 2, 3, 3, 4, 5]); // } else { // hits = this.sample([2, 2, 2, 3, 3, 3, 4, 5]); // } // } else { // hits = this.random(hits[0], hits[1] + 1); // } // } // hits = Math.floor(hits); // let nullDamage = true; // /**@type {number | false} */ // let moveDamage; // // There is no need to recursively check the ´sleepUsable´ flag as Sleep Talk can only be used while asleep. // let isSleepUsable = move.sleepUsable || this.getMove(move.sourceEffect).sleepUsable; // let i; // for (i = 0; i < hits && target.hp && pokemon.hp; i++) { // if (pokemon.status === 'slp' && !isSleepUsable) break; // if (move.multiaccuracy && i > 0) { // accuracy = move.accuracy; // if (accuracy !== true) { // if (!move.ignoreAccuracy) { // boosts = this.runEvent('ModifyBoost', pokemon, null, null, Object.assign({}, pokemon.boosts)); // boost = this.clampIntRange(boosts['accuracy'], -6, 6); // if (boost > 0) { // accuracy *= boostTable[boost]; // } else { // accuracy /= boostTable[-boost]; // } // } // if (!move.ignoreEvasion) { // boosts = this.runEvent('ModifyBoost', target, null, null, Object.assign({}, target.boosts)); // boost = this.clampIntRange(boosts['evasion'], -6, 6); // if (boost > 0) { // accuracy /= boostTable[boost]; // } else if (boost < 0) { // accuracy *= boostTable[-boost]; // } // } // } // accuracy = this.runEvent('ModifyAccuracy', target, pokemon, move, accuracy); // if (!move.alwaysHit) { // accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy); // // @ts-ignore // if (accuracy !== true && !this.randomChance(accuracy, 100)) break; // } // } // moveDamage = this.moveHit(target, pokemon, move); // if (moveDamage === false) break; // if (nullDamage && (moveDamage || moveDamage === 0 || moveDamage === undefined)) nullDamage = false; // // Damage from each hit is individually counted for the // // purposes of Counter, Metal Burst, and Mirror Coat. // damage = (moveDamage || 0); // // Total damage dealt is accumulated for the purposes of recoil (Parental Bond). // move.totalDamage += damage; // if (move.mindBlownRecoil && i === 0) { // this.damage(Math.round(pokemon.maxhp / 2), pokemon, pokemon, this.getEffect('Mind Blown'), true); // } // this.eachEvent('Update'); // } // if (i === 0) return false; // if (nullDamage) damage = false; // this.add('-hitcount', target, i); // } else { // damage = this.moveHit(target, pokemon, move); // move.totalDamage = damage; // } // if (move.recoil && move.totalDamage) { // this.damage(this.calcRecoilDamage(move.totalDamage, move), pokemon, pokemon, 'recoil'); // } // if (move.struggleRecoil) { // // @ts-ignore // this.directDamage(this.clampIntRange(Math.round(pokemon.maxhp / 4), 1), pokemon, pokemon, {id: 'strugglerecoil'}); // } // if (target && pokemon !== target) target.gotAttacked(move, damage, pokemon); // if (move.ohko) this.add('-ohko'); // if (!damage && damage !== 0) return damage; // this.eachEvent('Update'); // if (target && !move.negateSecondary && !(move.hasSheerForce && pokemon.hasAbility('sheerforce'))) { // this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move); // this.runEvent('AfterMoveSecondary', target, pokemon, move); // } // return damage; } static setWeather(weather: WEATHERS, duration) { EventManager.emit("SET_WEATHER", weather); let success = EventManager.run("SetWeather", undefined, undefined, { weather: weather }); if (success === false) return; this.weather = weather; } } } const $BattleManager = PE.Battle_Manager;
the_stack
declare namespace NodeJS { interface ProcessEnv { NODE_ENV: "development" | "staging" | "production" | "test", PUBLIC_URL: string } } declare module "*.bmp" { const src: string; export default src; } declare module "*.gif" { const src: string; export default src; } declare module "*.jpg" { const src: string; export default src; } declare module "*.jpeg" { const src: string; export default src; } declare module "*.png" { const src: string; export default src; } declare module "*.svg" { import * as React from "react"; export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>; const src: string; export default src; } declare module '*.css' { const classes: { [key: string]: string }; export default classes; } declare module '*.scss' { const classes: { [key: string]: string }; export default classes; } declare module '*.sass' { const classes: { [key: string]: string }; export default classes; } declare module "*.less" { const classes: { [key: string]: string }; export default classes; } //Treats Jest Global Function Declaration declare const shallow: Function; declare const render: Function; declare const mount: Function; declare const mountWithIntl: Function; declare const shallowWithIntl: Function; declare const renderWithIntl: Function; declare const shallowToJson: Function; declare const renderToJson: Function; declare const mountToJson: Function; //Treats Core Declaration declare module "@treats/intl" { import reactIntl = ReactIntl; export = reactIntl; } declare module "@treats/helmet" { import reactHelmet from "react-helmet"; export default reactHelmet; } declare module "@treats/router" { export { BrowserRouter, HashRouter, NavLink, Prompt, MemoryRouter, Route, Router, StaticRouter, Switch, withRouter, matchPath } from "react-router-dom"; export { default as Redirect } from "@treats/component/redirect"; export { default as Link } from "@treats/component/link"; } declare module "@treats/route" { type ModuleType = { [key: string]: string } type RouteType = { name: string, path: string, exact?: boolean, disabled?: boolean component: ModuleType } const routes: Array<RouteType> export default routes } declare module "@treats/client" { const initClient: Function; export default initClient; } declare module "@treats/server" { const initServer: Function; export default initServer; } declare module "@treats/redux" { export * from "redux"; export * from "react-redux"; } //Treats Util Declaration declare module "@treats/util/cookie" { export const getCookie: Function; } declare module "@treats/util/graphql" { export const mergeApolloConfig: Function; export const combineLinkStates: Function; } declare module "@treats/util/json" { export const injectParam: Function; export const bindParams: Function; } declare module "@treats/util/location" { export const findActiveRoute: Function; export const isPushEnabled: Function; export const getURLfromLocation: Function; } declare module "@treats/util/redux" { export const mergeReduxState: Function; export const typeGenerator: Function; export const reducerGenerator: Function; export const actionCreatorGenerator: Function; } declare module "@treats/util/security" { export const deserializeJSON: Function; export const serializeJSON: Function; export const escapeHtml: Function; export const escapeHtmlQueryObject: Function; } declare module "@treats/util/string" { export const camelToKebabCase: Function; } declare module "@treats/util/typecheck" { export const isArray: Function; export const isString: Function; export const isObject: Function; export const isNumber: Function; export const isFunction: Function; } //Treats Component declaration declare module "@treats/component/async-component" { const component: Function; export default component; } declare module "@treats/component/async-loader" { const component: Function; export default component; } declare module "@treats/component/error-boundary" { import * as React from "react"; export const withErrorBoundary: Function; const component: React.ReactNode; export default component; } declare module "@treats/component/http-status" { import * as React from "react"; const component: React.ReactNode; export default component; } declare module "@treats/component/link" { import * as React from "react"; const component: React.ReactNode; export default component; } declare module "@treats/component/provider" { import * as React from "react"; const component: React.ReactNode; export default component; } declare module "@treats/component/redirect" { const component: Route; export default component; } // These modules is an alias from react-intl/locale-data declare module "@treats/locale-data/af" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/agq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ak" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/am" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ar" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/as" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/asa" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ast" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/az" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bas" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/be" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bem" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bez" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bm" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/br" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/brx" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/bs" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ca" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ce" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/cgg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/chr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ckb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/cs" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/cu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/cy" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/da" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dav" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/de" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dje" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dsb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dua" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dv" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dyo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/dz" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ebu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ee" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/el" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/en" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/eo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/es" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/et" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/eu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ewo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fa" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ff" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fil" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fur" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/fy" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ga" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/gd" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/gl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/gsw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/gu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/guw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/guz" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/gv" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ha" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/haw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/he" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/hi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/hr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/hsb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/hu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/hy" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/id" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ig" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ii" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/in" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/is" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/it" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/iu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/iw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ja" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/jbo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/jgo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ji" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/jmc" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/jv" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/jw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ka" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kab" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kaj" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kam" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kcg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kde" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kea" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/khq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ki" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kkj" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kln" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/km" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ko" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kok" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ks" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ksb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ksf" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ksh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ku" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/kw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ky" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lag" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lkt" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ln" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lrc" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lt" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/luo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/luy" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/lv" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mas" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mer" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mfe" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mgh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mgo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ml" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ms" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mt" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mua" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/my" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/mzn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nah" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/naq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nb" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nd" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ne" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nmg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nnh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/no" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nqo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nso" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nus" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ny" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/nyn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/om" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/or" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/os" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/pa" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/pap" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/pl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/prg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ps" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/pt" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/qu" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/rm" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/rn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ro" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/rof" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ru" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/rw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/rwk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sah" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/saq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sbp" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sdh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/se" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/seh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ses" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sg" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/shi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/si" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sma" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/smi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/smj" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/smn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sms" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/so" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ss" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ssy" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/st" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sv" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/sw" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/syr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ta" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/te" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/teo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/th" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ti" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tig" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tl" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tn" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/to" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tr" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ts" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/twq" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/tzm" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ug" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/uk" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ur" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/uz" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/vai" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/ve" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/vi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/vo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/vun" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/wa" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/wae" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/wo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/xh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/xog" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/yav" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/yi" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/yo" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/zgh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/zh" { const data: ReactIntl.LocaleData; export = data; } declare module "@treats/locale-data/zu" { const data: ReactIntl.LocaleData; export = data; }
the_stack
"use strict"; declare var zip: any; import Package = require("./package"); import NativeAppInfo = require("./nativeAppInfo"); import FileUtil = require("./fileUtil"); import CodePushUtil = require("./codePushUtil"); import Sdk = require("./sdk"); /** * Defines a local package. * * !! THIS TYPE IS READ FROM NATIVE CODE AS WELL. ANY CHANGES TO THIS INTERFACE NEEDS TO BE UPDATED IN NATIVE CODE !! */ class LocalPackage extends Package implements ILocalPackage { public static RootDir: string = "codepush"; public static DownloadDir: string = LocalPackage.RootDir + "/download"; private static DownloadUnzipDir: string = LocalPackage.DownloadDir + "/unzipped"; private static DeployDir: string = LocalPackage.RootDir + "/deploy"; private static VersionsDir: string = LocalPackage.DeployDir + "/versions"; public static PackageUpdateFileName: string = "update.zip"; public static PackageInfoFile: string = "currentPackage.json"; private static OldPackageInfoFile: string = "oldPackage.json"; private static DiffManifestFile: string = "hotcodepush.json"; /** * The local storage path where this package is located. */ localPath: string; /** * Indicates if this is the current application run is the first one after the package was applied. */ isFirstRun: boolean; /** * Applies this package to the application. The application will be reloaded with this package and on every application launch this package will be loaded. * If the rollbackTimeout parameter is provided, the application will wait for a navigator.codePush.notifyApplicationReady() for the given number of milliseconds. * If navigator.codePush.notifyApplicationReady() is called before the time period specified by rollbackTimeout, the apply operation is considered a success. * Otherwise, the apply operation will be marked as failed, and the application is reverted to its previous version. * * @param applySuccess Callback invoked if the apply operation succeeded. * @param applyError Optional callback inovoked in case of an error. * @param rollbackTimeout The time interval, in milliseconds, to wait for a notifyApplicationReady() call before marking the apply as failed and reverting to the previous version. */ public apply(applySuccess: SuccessCallback<void>, errorCallbackOrRollbackTimeout?: ErrorCallback | number, rollbackTimeout?: number): void { try { CodePushUtil.logMessage("Applying update package ..."); var timeout = 0; var applyError: ErrorCallback; /* Handle parameters */ if (typeof rollbackTimeout === "number") { timeout = rollbackTimeout; } else if (!rollbackTimeout && typeof errorCallbackOrRollbackTimeout === "number") { timeout = <number>errorCallbackOrRollbackTimeout; } applyError = (error: Error): void => { var errorCallback: ErrorCallback; if (typeof errorCallbackOrRollbackTimeout === "function") { errorCallback = <ErrorCallback>errorCallbackOrRollbackTimeout; } CodePushUtil.invokeErrorCallback(error, errorCallback); Sdk.reportStatus(AcquisitionStatus.DeploymentFailed); }; var newPackageLocation = LocalPackage.VersionsDir + "/" + this.packageHash; var donePackageFileCopy = (deployDir: DirectoryEntry) => { this.localPath = deployDir.fullPath; this.finishApply(deployDir, timeout, applySuccess, applyError); }; var newPackageUnzipped = (unzipError: any) => { if (unzipError) { applyError && applyError(new Error("Could not unzip package. " + CodePushUtil.getErrorMessage(unzipError))); } else { LocalPackage.handleDeployment(newPackageLocation, CodePushUtil.getNodeStyleCallbackFor<DirectoryEntry>(donePackageFileCopy, applyError)); } }; FileUtil.getDataDirectory(LocalPackage.DownloadUnzipDir, false, (error: Error, directoryEntry: DirectoryEntry) => { var unzipPackage = () => { FileUtil.getDataDirectory(LocalPackage.DownloadUnzipDir, true, (innerError: Error, unzipDir: DirectoryEntry) => { if (innerError) { applyError && applyError(innerError); } else { zip.unzip(this.localPath, unzipDir.toInternalURL(), newPackageUnzipped); } }); }; if (!error && !!directoryEntry) { /* Unzip directory not clean */ directoryEntry.removeRecursively(() => { unzipPackage(); }, (cleanupError: FileError) => { applyError && applyError(FileUtil.fileErrorToError(cleanupError)); }); } else { unzipPackage(); } }); } catch (e) { applyError && applyError(new Error("An error ocurred while applying the package. " + CodePushUtil.getErrorMessage(e))); } } private cleanOldPackage(oldPackage: LocalPackage, cleanPackageCallback: Callback<void>): void { if (oldPackage && oldPackage.localPath) { FileUtil.deleteDirectory(oldPackage.localPath, cleanPackageCallback); } else { cleanPackageCallback(new Error("The package could not be found."), null); } }; private finishApply(deployDir: DirectoryEntry, timeout: number, applySuccess: SuccessCallback<void>, applyError: ErrorCallback): void { LocalPackage.getCurrentOrDefaultPackage((oldPackage: LocalPackage) => { LocalPackage.backupPackageInformationFile((backupError: Error) => { backupError && CodePushUtil.logMessage("First update: back up package information skipped. "); /* continue on error, current package information is missing if this is the fist update */ this.writeNewPackageMetadata(deployDir, (writeMetadataError: Error) => { if (writeMetadataError) { applyError && applyError(writeMetadataError); } else { var silentCleanup = (cleanCallback: Callback<void>) => { FileUtil.deleteDirectory(LocalPackage.DownloadDir, (e1: Error) => { this.cleanOldPackage(oldPackage, (e2: Error) => { cleanCallback(e1 || e2, null); }); }); }; var invokeSuccessAndApply = () => { CodePushUtil.logMessage("Apply succeeded."); applySuccess && applySuccess(); /* no neeed for callbacks, the javascript context will reload */ cordova.exec(() => { }, () => { }, "CodePush", "apply", [deployDir.fullPath, timeout.toString()]); }; var preApplySuccess = () => { Sdk.reportStatus(AcquisitionStatus.DeploymentSucceeded); if (timeout > 0) { /* package will be cleaned up after success, on the native side */ invokeSuccessAndApply(); } else { /* clean up the package, then invoke apply */ silentCleanup((cleanupError: Error) => { invokeSuccessAndApply(); }); } }; var preApplyFailure = (preApplyError?: any) => { CodePushUtil.logError("Preapply failure.", preApplyError); var error = new Error("An error has ocurred while applying the package. " + CodePushUtil.getErrorMessage(preApplyError)); applyError && applyError(error); }; cordova.exec(preApplySuccess, preApplyFailure, "CodePush", "preApply", [deployDir.fullPath]); } }); }); }, applyError); } private static handleDeployment(newPackageLocation: string, deployCallback: Callback<DirectoryEntry>): void { FileUtil.getDataDirectory(newPackageLocation, true, (deployDirError: Error, deployDir: DirectoryEntry) => { // check for diff manifest FileUtil.getDataFile(LocalPackage.DownloadUnzipDir, LocalPackage.DiffManifestFile, false, (manifestError: Error, diffManifest: FileEntry) => { if (!manifestError && !!diffManifest) { LocalPackage.handleDiffDeployment(newPackageLocation, diffManifest, deployCallback); } else { LocalPackage.handleCleanDeployment(newPackageLocation, (error: Error) => { deployCallback(error, deployDir); }); } }); }); } private writeNewPackageMetadata(deployDir: DirectoryEntry, writeMetadataCallback: Callback<void>): void { NativeAppInfo.getApplicationBuildTime((buildTimeError: Error, timestamp: string) => { NativeAppInfo.getApplicationVersion((appVersionError: Error, appVersion: string) => { buildTimeError && CodePushUtil.logError("Could not get application build time. " + buildTimeError); appVersionError && CodePushUtil.logError("Could not get application version." + appVersionError); var currentPackageMetadata: IPackageInfoMetadata = { nativeBuildTime: timestamp, localPath: this.localPath, appVersion: appVersion, deploymentKey: this.deploymentKey, description: this.description, isMandatory: this.isMandatory, packageSize: this.packageSize, label: this.label, packageHash: this.packageHash, isFirstRun: false, failedApply: false, apply: undefined }; LocalPackage.writeCurrentPackageInformation(currentPackageMetadata, writeMetadataCallback); }); }); } private static handleCleanDeployment(newPackageLocation: string, cleanDeployCallback: Callback<DirectoryEntry>): void { // no diff manifest FileUtil.getDataDirectory(newPackageLocation, true, (deployDirError: Error, deployDir: DirectoryEntry) => { FileUtil.getDataDirectory(LocalPackage.DownloadUnzipDir, false, (unzipDirErr: Error, unzipDir: DirectoryEntry) => { if (unzipDirErr || deployDirError) { cleanDeployCallback(new Error("Could not copy new package."), null); } else { FileUtil.copyDirectoryEntriesTo(unzipDir, deployDir, (copyError: Error) => { if (copyError) { cleanDeployCallback(copyError, null); } else { cleanDeployCallback(null, deployDir); } }); } }); }); } private static copyCurrentPackage(newPackageLocation: string, copyCallback: Callback<void>): void { var handleError = (e: Error) => { copyCallback && copyCallback(e, null); }; FileUtil.getDataDirectory(newPackageLocation, true, (deployDirError: Error, deployDir: DirectoryEntry) => { LocalPackage.getPackage(LocalPackage.PackageInfoFile, (currentPackage: LocalPackage) => { if (deployDirError) { handleError(new Error("Could not acquire the source/destination folders. ")); } else { var success = (currentPackageDirectory: DirectoryEntry) => { FileUtil.copyDirectoryEntriesTo(currentPackageDirectory, deployDir, copyCallback); }; var fail = (fileSystemError: FileError) => { copyCallback && copyCallback(FileUtil.fileErrorToError(fileSystemError), null); }; FileUtil.getDataDirectory(currentPackage.localPath, false, CodePushUtil.getNodeStyleCallbackFor(success, fail)); } }, handleError); }); } private static handleDiffDeployment(newPackageLocation: string, diffManifest: FileEntry, diffCallback: Callback<DirectoryEntry>): void { var handleError = (e: Error) => { diffCallback(e, null); }; /* copy old files */ LocalPackage.copyCurrentPackage(newPackageLocation, (currentPackageError: Error) => { /* copy new files */ LocalPackage.handleCleanDeployment(newPackageLocation, (cleanDeployError: Error) => { /* delete files mentioned in the manifest */ FileUtil.readFileEntry(diffManifest, (error: Error, content: string) => { if (error || currentPackageError || cleanDeployError) { handleError(new Error("Cannot perform diff-update.")); } else { var manifest: IDiffManifest = JSON.parse(content); FileUtil.deleteEntriesFromDataDirectory(newPackageLocation, manifest.deletedFiles, (deleteError: Error) => { FileUtil.getDataDirectory(newPackageLocation, true, (deployDirError: Error, deployDir: DirectoryEntry) => { if (deleteError || deployDirError) { handleError(new Error("Cannot clean up deleted manifest files.")); } else { diffCallback(null, deployDir); } }); }); } }); }); }); } /** * Writes the given local package information to the current package information file. * @param packageInfoMetadata The object to serialize. * @param callback In case of an error, this function will be called with the error as the fist parameter. */ public static writeCurrentPackageInformation(packageInfoMetadata: IPackageInfoMetadata, callback: Callback<void>): void { var content = JSON.stringify(packageInfoMetadata); FileUtil.writeStringToDataFile(content, LocalPackage.RootDir, LocalPackage.PackageInfoFile, true, callback); } /** * Backs up the current package information to the old package information file. * This file is used for recovery in case of an update going wrong. * @param callback In case of an error, this function will be called with the error as the fist parameter. */ public static backupPackageInformationFile(callback: Callback<void>): void { var reportFileError = (error: FileError) => { callback(FileUtil.fileErrorToError(error), null); }; var copyFile = (fileToCopy: FileEntry) => { fileToCopy.getParent((parent: DirectoryEntry) => { fileToCopy.copyTo(parent, LocalPackage.OldPackageInfoFile, () => { callback(null, null); }, reportFileError); }, reportFileError); }; var gotFile = (error: Error, currentPackageFile: FileEntry) => { if (error) { callback(error, null); } else { FileUtil.getDataFile(LocalPackage.RootDir, LocalPackage.OldPackageInfoFile, false, (error: Error, oldPackageFile: FileEntry) => { if (!error && !!oldPackageFile) { /* file already exists */ oldPackageFile.remove(() => { copyFile(currentPackageFile); }, reportFileError); } else { copyFile(currentPackageFile); } }); } }; FileUtil.getDataFile(LocalPackage.RootDir, LocalPackage.PackageInfoFile, false, gotFile); } /** * Get the previous package information. * * @param packageSuccess Callback invoked with the old package information. * @param packageError Optional callback invoked in case of an error. */ public static getOldPackage(packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { return LocalPackage.getPackage(LocalPackage.OldPackageInfoFile, packageSuccess, packageError); } /** * Reads package information from a given file. * * @param packageFile The package file name. * @param packageSuccess Callback invoked with the package information. * @param packageError Optional callback invoked in case of an error. */ public static getPackage(packageFile: string, packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { var handleError = (e: Error) => { packageError && packageError(new Error("Cannot read package information. " + CodePushUtil.getErrorMessage(e))); }; try { FileUtil.readDataFile(LocalPackage.RootDir, packageFile, (error: Error, content: string) => { if (error) { handleError(error); } else { try { var packageInfo: IPackageInfoMetadata = JSON.parse(content); LocalPackage.getLocalPackageFromMetadata(packageInfo, packageSuccess, packageError); } catch (e) { handleError(e); } } }); } catch (e) { handleError(e); } } private static getLocalPackageFromMetadata(metadata: IPackageInfoMetadata, packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { if (!metadata) { packageError && packageError(new Error("Invalid package metadata.")); } else { NativeAppInfo.isFailedUpdate(metadata.packageHash, (applyFailed: boolean) => { NativeAppInfo.isFirstRun(metadata.packageHash, (isFirstRun: boolean) => { var localPackage = new LocalPackage(); localPackage.appVersion = metadata.appVersion; localPackage.deploymentKey = metadata.deploymentKey; localPackage.description = metadata.description; localPackage.failedApply = applyFailed; localPackage.isFirstRun = isFirstRun; localPackage.label = metadata.label; localPackage.localPath = metadata.localPath; localPackage.packageHash = metadata.packageHash; localPackage.packageSize = metadata.packageSize; packageSuccess && packageSuccess(localPackage); }); }); } } public static getCurrentOrDefaultPackage(packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { LocalPackage.getPackageInfoOrDefault(LocalPackage.PackageInfoFile, packageSuccess, packageError); } public static getOldOrDefaultPackage(packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { LocalPackage.getPackageInfoOrDefault(LocalPackage.OldPackageInfoFile, packageSuccess, packageError); } public static getPackageInfoOrDefault(packageFile: string, packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { var packageFailure = (error: Error) => { NativeAppInfo.getApplicationVersion((appVersionError: Error, appVersion: string) => { if (appVersionError) { CodePushUtil.logError("Could not get application version." + appVersionError); packageError(appVersionError); } else { var defaultPackage: LocalPackage = new LocalPackage(); /* for the default package, we only need the app version */ defaultPackage.appVersion = appVersion; packageSuccess(defaultPackage); } }); }; LocalPackage.getPackage(packageFile, packageSuccess, packageFailure); } public static getPackageInfoOrNull(packageFile: string, packageSuccess: SuccessCallback<LocalPackage>, packageError?: ErrorCallback): void { LocalPackage.getPackage(packageFile, packageSuccess, packageSuccess.bind(null, null)); } } export = LocalPackage;
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import {STYLE, STYLE_CONST} from './Styles/styles'; import SocialShareIcons from './SocialShareIcons'; import RecordPlayButtonGroup from './RecordPlayButtonGroup'; import WaveformSelectGroup from './WaveformSelectGroup'; import RangeSliderGroup from './RangeSliderGroup'; import MultiTouchArea from './MultiTouchArea'; import DownloadModal from './DownloadModal'; import StartModal from './StartModal'; import {WaveformStringType} from '../Constants/AppTypings'; import { WAVEFORMS, DEFAULTS } from '../Constants/Defaults'; import {IGlobalState} from '../Constants/GlobalState'; import Audio from '../Audio'; import {downloadModalChange} from '../Actions/actions'; import Visibility from '../Utils/visibility'; import * as AudioUtils from '../Utils/AudioUtils'; import * as CanvasUtils from '../Utils/CanvasUtils'; import {IdentifierIndexMap, isCordovaIOS} from '../Utils/utils'; import Spectrum from './Spectrum'; import {RecordStateType} from '../Constants/AppTypings'; import {STATE} from '../Constants/AppTypings'; import {PlayerStateType} from '../Constants/AppTypings'; interface IState { delayVal?: number; feedbackVal?: number; playerState?: PlayerStateType; recordState?: RecordStateType; isDownloadOverlayActive?: boolean; scuzzVal?: number; startModalText?: string; waveform?: string; windowHeight?: number; windowWidth?: number; _touchAreaHeight?: number; _touchAreaWidth?: number; } function select(state: IGlobalState) { return { waveform: state.Waveform.wave, playerState: state.Player.playerState, recordState: state.Recorder.recordState, delayVal: state.Slider.delay, feedbackVal: state.Slider.feedback, scuzzVal: state.Slider.scuzz, isDownloadModalOpen: state.DownloadModal.isOpen, isStartModalOpen: state.StartModal.isOpen, }; } @connect(select) class App extends React.Component<any, IState> { public Audio: Audio; public canvas: HTMLCanvasElement; public spectrumLive: Spectrum; public spectrumRecording: Spectrum; private _isAnimating: boolean = false; private _pixelRatio: number = CanvasUtils.getPixelRatio(); private _touchAreaHeight: number; private _touchAreaWidth: number; private _DrawAnimationFrame: number; private touches: IdentifierIndexMap; private _IOSAudioContextUnlockFailCounter: number = 0; constructor(props) { super(props); this.state = { delayVal: DEFAULTS.Sliders.delay.value, feedbackVal: DEFAULTS.Sliders.feedback.value, playerState: STATE.STOPPED, recordState: STATE.STOPPED, isDownloadOverlayActive: false, scuzzVal: DEFAULTS.Sliders.scuzz.value, startModalText: DEFAULTS.Copy.en.startText, waveform: WAVEFORMS[DEFAULTS.Waveform], windowHeight: window.innerHeight, windowWidth: window.innerWidth, }; this.Audio = new Audio(); this.updateSize(); //Create canvas with the device resolution. this.canvas = CanvasUtils.createCanvas(this._touchAreaWidth, this._touchAreaHeight); this._pixelRatio = CanvasUtils.getPixelRatio(); this.touches = new IdentifierIndexMap(); this.initializeSpectrum(); this.Start = this.Start.bind(this); this.Stop = this.Stop.bind(this); this.Move = this.Move.bind(this); this.SliderChange = this.SliderChange.bind(this); this.SetWaveform = this.SetWaveform.bind(this); this.Record = this.Record.bind(this); this.Playback = this.Playback.bind(this); this.Download = this.Download.bind(this); this.handleResize = this.handleResize.bind(this); this.startPress = this.startPress.bind(this); } private initializeSpectrum() { this.spectrumLive = new Spectrum(this.canvas, this.Audio.analysers.live); this.spectrumRecording = new Spectrum(this.canvas, this.Audio.analysers.recording); } get mobileLandscapeSize(): boolean { return this.state.windowHeight < 450 && (this.state.windowWidth > this.state.windowHeight); } get smallScreen(): boolean { return this.state.windowHeight < 600; } private updateSize() { const topPanelHeight = this.mobileLandscapeSize ? STYLE_CONST.TOP_PANEL_HEIGHT_MOBILE_LANDSCAPE : STYLE_CONST.TOP_PANEL_HEIGHT; const bottomPanelHeight = this.smallScreen ? STYLE_CONST.BOTTOM_PANEL_HEIGHT_MOBILE : STYLE_CONST.BOTTOM_PANEL_HEIGHT; const statusBarHeight = this.getStatusBarHeight(); // const shareArea = topPanelHeight; const shareArea = 58; this._touchAreaHeight = this.state.windowHeight - (statusBarHeight + topPanelHeight + (STYLE_CONST.PADDING * 2) + bottomPanelHeight + shareArea); this._touchAreaWidth = this.state.windowWidth - (STYLE_CONST.PADDING * 2); } private getStatusBarHeight(): number { let h = 0; if (isCordovaIOS() && this.state.windowWidth < this.state.windowHeight) { h = 20; } return h; } public componentDidMount() { window.addEventListener('resize', this.handleResize); // Make sure all sounds stop when app is awoken. Visibility.onVisible = () => { this.Audio.StopAll(); }; // Stop when switch to another tab in browser Visibility.onInvisible = () => { this.Audio.StopAll(); }; if (isCordovaIOS()){ document.addEventListener("active", onActive, false); function onActive() { setTimeout(() => { AudioUtils.isIOSAudioUnlocked(this.Audio.context, (isUnlocked) => { console.log('is unlocked:', isUnlocked); if (!isUnlocked) { this.resetOnIOSLockedAudio(); } }); }, 100); } } } // private resetOnIOSLockedAudio() { // this.props.dispatch(startModalChange(true)); // this.setState({startModalText: DEFAULTS.Copy.en.resumeText}); // //Reset any record playback, download states // //FIXME: This depends on what state the recording was in // this.props.dispatch(RecorderStateChange(STATE.STOPPED)); // this.props.dispatch(PlayerStateChange(STATE.STOPPED)); // this.props.dispatch(PlayButtonDisabled(true)); // this.props.dispatch(downloadModalChange(false)); // } public componentWillUnmount() { window.removeEventListener('resize', this.handleResize); } public render(): React.ReactElement<{}> { const mobileSizeSmall = this.state.windowWidth < 512; const mobileSizeLarge = this.state.windowWidth < 600; const mobileLandscape = this.mobileLandscapeSize; let buttonSize = this.state.windowWidth > 600 ? 50 : (this.state.windowWidth / 9); buttonSize = buttonSize < 50 ? buttonSize : 50; const titleStyle = Object.assign({}, STYLE.title.h1, mobileSizeLarge && STYLE.title.h1_mobileSizeLarge, mobileSizeSmall && STYLE.title.h1_mobileSizeSmall, mobileLandscape && STYLE.title.h1_mobileLandscape, mobileLandscape && mobileSizeSmall && STYLE.title.h1_mobileSizeSmall ); const statusBarHeight = this.getStatusBarHeight(); const statusBarStyle = Object.assign({}, {marginTop: statusBarHeight}); const {iosAppStore, chromeAppStore, androidAppStore} = DEFAULTS.Links; return ( <div id='body-wrapper' onTouchMove={(e)=> e.preventDefault()}> <div style={ Object.assign({}, STYLE.topPanel, statusBarStyle, mobileLandscape && STYLE.topPanel_mobileLandscape )}> <div style={Object.assign({},STYLE.title.container, mobileSizeSmall && STYLE.title.container_mobile, mobileLandscape && STYLE.title.container_mobileLandscape)}> <span style={titleStyle}>{DEFAULTS.Title.toUpperCase()}</span> </div> <RecordPlayButtonGroup style={Object.assign({},STYLE.recordPlayButtonGroup.container, mobileSizeSmall && STYLE.recordPlayButtonGroup.container_mobile)} onRecordButtonChange={this.Record} onPlaybackButtonChange={this.Playback} onDownloadButtonChange={this.Download} buttonSize={buttonSize} maxLoopDuration={30} /> <WaveformSelectGroup style={Object.assign({},STYLE.waveformSelectGroup.container, mobileSizeSmall && STYLE.waveformSelectGroup.container_mobile)} waveformChange={this.SetWaveform} buttonSize={buttonSize} /> </div> <MultiTouchArea canvas={this.canvas} width={this._touchAreaWidth} height={this._touchAreaHeight} onMouseDown={this.Start} onTouchStart={this.Start} onMouseUp={this.Stop} onTouchEnd={this.Stop} onMouseMove={this.Move} onTouchMove={this.Move} fireMouseLeaveOnElementExit={true} style={STYLE.touchArea} /> <RangeSliderGroup sliderChange={this.SliderChange} smallScreen={this.smallScreen} windowWidth={this.state.windowWidth} /> <div style={Object.assign({}, STYLE.footer, mobileSizeSmall && STYLE.footerMobile)}> <div style={{display: 'flex'}}> <div onClick={(e) => { (e as any).currentTarget.classList.toggle('open'); }} className="appStoreButton" style={Object.assign({}, STYLE.appStoreButton, mobileSizeSmall && STYLE.appStoreButtonSmall)}> <span className="get-the-app-text">Get the app <span className="chevron chevron-up">&#8963;</span></span> <ul> <li><a href={iosAppStore}><span>iOS</span></a></li> <li><a href={androidAppStore}><span>Android</span></a></li> <li><a href={chromeAppStore}><span>Desktop</span></a></li> </ul> </div> </div> <a href={DEFAULTS.Links.femur} className="madeByFemur" style={Object.assign({}, STYLE.madeByFemurLink, mobileSizeSmall && STYLE.madeByFemurLinkMobile)}> By Femur </a> <SocialShareIcons/> </div> <DownloadModal Audio={this.Audio} isActive={this.props.isDownloadModalOpen} style={Object.assign({},STYLE.downloadModal)} windowWidth={this.state.windowWidth} windowHeight={this.state.windowHeight} /> <StartModal isActive={this.props.isStartModalOpen} onStartPress={this.startPress} buttonText={this.state.startModalText} style={Object.assign({}, STYLE.startModal)} mobileSizeSmall={mobileSizeSmall} /> </div> ); } /** * Start Press - only for ios * @param onStartPressed */ private startPress(onStartPressed) { this.handleResize(); this.setState({startModalText: 'Loading...'}); // if (this.Audio.context.state === 'suspended' ) { // this.Audio.context.resume(); // } else { // console.log('audio context not suspended') // // this.Audio.context.close(); // // this.Audio = new Audio(); // } AudioUtils.isIOSAudioUnlocked(this.Audio.context, (isUnlocked) => { if (isUnlocked){ this.onIOSAudioUnlocked(onStartPressed); } else { this.onIOSAudioNotUnlocked(onStartPressed); } }); } private onIOSAudioUnlocked(onUnlocked) { console.log('UNLOCKED'); this._IOSAudioContextUnlockFailCounter = 0; onUnlocked(); } private onIOSAudioNotUnlocked(onNotUnlocked){ console.log('NOT UNLOCKED'); this.Audio.context.close(); this.Audio = new Audio(); // Reinitialize the spectrums with the updated Audio this.initializeSpectrum(); if (window.cordova){ console.log(this.Audio.context); if (this._IOSAudioContextUnlockFailCounter < 100){ this._IOSAudioContextUnlockFailCounter++; console.log('try again',this._IOSAudioContextUnlockFailCounter); this.startPress(onNotUnlocked); } else { //TODO: iphone 4 test fix this & iphone 6 this.setState({startModalText: DEFAULTS.Copy.en.startText}); navigator.notification.alert("Couldn't unlock audio. Try restarting or contact support", () => { return; }, 'ERROR'); this._IOSAudioContextUnlockFailCounter = 0; } } else { console.error("Couldn't unlock audio. Try reloading web page"); } } private handleResize() { this.setState({ windowWidth: window.innerWidth, windowHeight: window.innerHeight, }); this.updateSize(); // Resize the canvas element CanvasUtils.canvasResize(this.canvas, this._touchAreaWidth, this._touchAreaHeight); this.forceUpdate(); } public Start(e: MouseEvent | Touch, identifier: number = 0): void { const index = this.touches.Add(identifier); const pos = CanvasUtils.getCoordinateFromEventAsPercentageWithinElement(e, this.canvas); //Only start animating when the touch is down if (this._isAnimating === false) { this.Draw(); } this.Audio.Start(pos, index); } public Stop(e: MouseEvent | Touch, identifier: number = 0): void { const index = this.touches.GetIndexFromIdentifier(identifier); const pos = CanvasUtils.getCoordinateFromEventAsPercentageWithinElement(e, this.canvas); this.Audio.Stop(pos, index); //Remove from list of touch ids this.touches.Remove(identifier); } public Move(e: MouseEvent | Touch, id: number = 0) { const index = this.touches.GetIndexFromIdentifier(id); const pos = CanvasUtils.getCoordinateFromEventAsPercentageWithinElement(e, this.canvas); this.Audio.Move(pos, index); } public SliderChange(slider, value) { switch (slider) { case 'delay': this.Audio.delay.delayTime.value = value; break; case 'feedback': this.Audio.feedback.gain.value = value; break; case 'scuzz': this.Audio.scuzzGain.gain.value = value; break; default: console.error(`Slider name ${slider} not found`); break; } } public SetWaveform(value: WaveformStringType) { this.Audio.SetWaveform(value); } public Record(){ this.Audio.onRecordPress(); } public Playback() { this.Audio.onPlaybackPress(); } public Download() { this.props.dispatch(downloadModalChange(true)); this.setState({isDownloadOverlayActive: true}); } private Draw() { this._isAnimating = true; this._DrawAnimationFrame = requestAnimationFrame(this.Draw.bind(this)); const ctx: CanvasRenderingContext2D = this.canvas.getContext('2d'); const width: number = this.canvas.width / this._pixelRatio; const height: number = this.canvas.height / this._pixelRatio; ctx.clearRect(0, 0, width, height); let liveColor = STYLE_CONST.BLACK; switch (this.props.recordState) { case 'recording': liveColor = STYLE_CONST.RED; break; case 'overdubbing': liveColor = STYLE_CONST.RED; break; case 'stopped': liveColor = STYLE_CONST.BLACK; break; } this.spectrumRecording.Draw({ isActive: this._isAnimating, color: STYLE_CONST.GREY, }); this.spectrumLive.Draw({ isActive: this._isAnimating, color: liveColor, }); } } export default App;
the_stack
import * as AlgebraicType from '../algebraic-type'; import * as AlgebraicTypeUtils from '../algebraic-type-utils'; import * as Code from '../code'; import * as Error from '../error'; import * as FileWriter from '../file-writer'; import * as List from '../list'; import * as Map from '../map'; import * as Maybe from '../maybe'; import * as ObjC from '../objc'; import * as ObjCCommentUtils from '../objc-comment-utils'; import * as ObjCImportUtils from '../objc-import-utils'; import * as ObjCNullabilityUtils from '../objc-nullability-utils'; import * as ObjectGeneration from '../object-generation'; import * as ObjectSpecCodeUtils from '../object-spec-code-utils'; import * as StringUtils from '../string-utils'; const PUBLIC_FOUNDATION_IMPORT: ObjC.Import = { library: 'Foundation', file: 'Foundation.h', isPublic: true, requiresCPlusPlus: false, }; function nameOfObjectWithinInitializer(): string { return 'object'; } function nameOfKeywordParameterForAttribute( attribute: AlgebraicType.SubtypeAttribute, ): string { return attribute.name; } function internalValueSettingCodeForAttribute( subtype: AlgebraicType.Subtype, attribute: AlgebraicType.SubtypeAttribute, ): string { return ( nameOfObjectWithinInitializer() + '->' + AlgebraicTypeUtils.valueAccessorForInstanceVariableForAttribute( subtype, attribute, ) + ' = ' + nameOfKeywordParameterForAttribute(attribute) + ';' ); } function keywordArgumentFromAttribute( attribute: AlgebraicType.SubtypeAttribute, ): ObjC.KeywordArgument | null { return { name: nameOfKeywordParameterForAttribute(attribute), modifiers: ObjCNullabilityUtils.keywordArgumentModifiersForNullability( attribute.nullability, ), type: { name: attribute.type.name, reference: attribute.type.reference, }, }; } function firstInitializerKeyword( subtype: AlgebraicType.NamedAttributeCollectionSubtype, attribute: AlgebraicType.SubtypeAttribute, ): ObjC.Keyword { return { argument: keywordArgumentFromAttribute(attribute), name: StringUtils.lowercased(subtype.name) + 'With' + StringUtils.capitalize(attribute.name), }; } function attributeToKeyword( attribute: AlgebraicType.SubtypeAttribute, ): ObjC.Keyword { return { argument: keywordArgumentFromAttribute(attribute), name: attribute.name, }; } function keywordsForNamedAttributeSubtype( subtype: AlgebraicType.NamedAttributeCollectionSubtype, ): ObjC.Keyword[] { if (subtype.attributes.length > 0) { return [firstInitializerKeyword(subtype, subtype.attributes[0])].concat( subtype.attributes.slice(1).map(attributeToKeyword), ); } else { return [ { name: StringUtils.lowercased(subtype.name), argument: null, }, ]; } } function commentsForSubtype(subtype: AlgebraicType.Subtype): string[] { return subtype.match( function ( namedAttributeCollectionSubtype: AlgebraicType.NamedAttributeCollectionSubtype, ) { return ObjCCommentUtils.prefixedParamCommentsFromAttributes( namedAttributeCollectionSubtype.comments, namedAttributeCollectionSubtype.attributes, ); }, function (attribute: AlgebraicType.SubtypeAttribute) { return attribute.comments; }, ); } export function keywordsForSubtype( subtype: AlgebraicType.Subtype, ): ObjC.Keyword[] { return subtype.match( function ( namedAttributeCollectionSubtype: AlgebraicType.NamedAttributeCollectionSubtype, ) { return keywordsForNamedAttributeSubtype(namedAttributeCollectionSubtype); }, function (attribute: AlgebraicType.SubtypeAttribute) { return [ { argument: keywordArgumentFromAttribute(attribute), name: StringUtils.lowercased(attribute.name), }, ]; }, ); } function swiftNameForSubtype(subtype: AlgebraicType.Subtype): string | null { return subtype.match( (collection) => { if (collection.attributes.length > 0) { const name = StringUtils.swiftCaseForString(collection.name); const keywords = collection.attributes .map( (attribute) => `${StringUtils.swiftCaseForString(attribute.name)}:`, ) .join(''); return `NS_SWIFT_NAME(${name}(${keywords}))`; } else { return null; } }, (attribute) => null, ); } function canAssertExistenceForTypeOfAttribute( attribute: AlgebraicType.SubtypeAttribute, ) { return ObjCNullabilityUtils.canAssertExistenceForType( AlgebraicTypeUtils.computeTypeOfAttribute(attribute), ); } function isRequiredAttribute( assumeNonnull: boolean, attribute: AlgebraicType.SubtypeAttribute, ): boolean { return ObjCNullabilityUtils.shouldProtectFromNilValuesForNullability( assumeNonnull, attribute.nullability, ); } function toRequiredAssertion( attribute: AlgebraicType.SubtypeAttribute, ): string { return 'RMParameterAssert(' + attribute.name + ' != nil);'; } function initializationClassMethodForSubtype( algebraicType: AlgebraicType.Type, subtype: AlgebraicType.Subtype, ): ObjC.Method { const openingCode: string[] = [ algebraicType.name + ' *' + nameOfObjectWithinInitializer() + ' = [(Class)self new];', nameOfObjectWithinInitializer() + '->' + AlgebraicTypeUtils.valueAccessorForInstanceVariableStoringSubtype() + ' = ' + AlgebraicTypeUtils.EnumerationValueNameForSubtype( algebraicType, subtype, ) + ';', ]; const assumeNonnull: boolean = algebraicType.includes.indexOf('RMAssumeNonnull') >= 0; const attributes: AlgebraicType.SubtypeAttribute[] = AlgebraicTypeUtils.attributesFromSubtype(subtype); const requiredParameterAssertions: string[] = attributes .filter(canAssertExistenceForTypeOfAttribute) .filter((attribute) => isRequiredAttribute(assumeNonnull, attribute)) .map(toRequiredAssertion); const setterStatements: string[] = attributes.map((attribute) => internalValueSettingCodeForAttribute(subtype, attribute), ); return { preprocessors: [], belongsToProtocol: null, code: requiredParameterAssertions .concat(openingCode) .concat(setterStatements) .concat('return object;'), comments: ObjCCommentUtils.commentsAsBlockFromStringArray( commentsForSubtype(subtype), ), compilerAttributes: Maybe.catMaybes([swiftNameForSubtype(subtype)]), keywords: keywordsForSubtype(subtype), returnType: { type: { name: 'instancetype', reference: 'instancetype', }, modifiers: [], }, }; } function internalImportForFileWithName(name: string): ObjC.Import { return { library: null, file: name + '.h', isPublic: false, requiresCPlusPlus: false, }; } function instanceVariableForEnumeration( algebraicType: AlgebraicType.Type, ): ObjC.InstanceVariable { const enumerationName: string = AlgebraicTypeUtils.EnumerationNameForAlgebraicType(algebraicType); return { name: AlgebraicTypeUtils.nameForInstanceVariableStoringSubtype(), comments: [], returnType: { name: enumerationName, reference: enumerationName, }, modifiers: [], access: ObjC.InstanceVariableAccess.Private(), }; } function instanceVariableFromAttribute( subtype: AlgebraicType.Subtype, attribute: AlgebraicType.SubtypeAttribute, ): ObjC.InstanceVariable { return { name: AlgebraicTypeUtils.nameOfInstanceVariableForAttribute( subtype, attribute, ), comments: [], returnType: { name: attribute.type.name, reference: attribute.type.reference, }, modifiers: [], access: ObjC.InstanceVariableAccess.Private(), }; } function instanceVariablesForImplementationOfAlgebraicType( algebraicType: AlgebraicType.Type, ): ObjC.InstanceVariable[] { const enumerationInstanceVariable: ObjC.InstanceVariable = instanceVariableForEnumeration(algebraicType); const attributeInstanceVariables: ObjC.InstanceVariable[] = AlgebraicTypeUtils.mapAttributesWithSubtypeFromSubtypes( algebraicType.subtypes, instanceVariableFromAttribute, ); return [enumerationInstanceVariable].concat(attributeInstanceVariables); } function makePublicImportsForAlgebraicType( algebraicType: AlgebraicType.Type, ): boolean { return algebraicType.includes.indexOf('UseForwardDeclarations') === -1; } function isImportRequiredForTypeLookup( algebraicType: AlgebraicType.Type, typeLookup: ObjectGeneration.TypeLookup, ): boolean { const needsImportsForAllTypeLookups = makePublicImportsForAlgebraicType(algebraicType); return ( typeLookup.name !== algebraicType.name && (!typeLookup.canForwardDeclare || needsImportsForAllTypeLookups) ); } function forwardDeclarationForTypeLookup( typeLookup: ObjectGeneration.TypeLookup, ): ObjC.ForwardDeclaration { return ObjC.ForwardDeclaration.ForwardClassDeclaration(typeLookup.name); } function enumerationForSubtypesOfAlgebraicType( algebraicType: AlgebraicType.Type, ): ObjC.Enumeration { return { name: AlgebraicTypeUtils.EnumerationNameForAlgebraicType(algebraicType), underlyingType: 'NSUInteger', values: algebraicType.subtypes.map((subtype) => AlgebraicTypeUtils.EnumerationValueNameForSubtype(algebraicType, subtype), ), isPublic: false, comments: [], }; } interface ValidationErrorReductionTracker { errors: List.List<Error.Error>; seenSubtypeNames: Map.Map<string, string>; } function buildAlgebraicTypeValidationErrors( soFar: ValidationErrorReductionTracker, subtype: AlgebraicType.Subtype, ): ValidationErrorReductionTracker { const subtypeName: string = AlgebraicTypeUtils.subtypeNameFromSubtype(subtype); if (Map.containsKey(subtypeName, soFar.seenSubtypeNames)) { const error: Error.Error = Error.Error( 'Algebraic types cannot have two subtypes with the same name, but found two or more subtypes with the name ' + subtypeName, ); return { errors: List.cons(error, soFar.errors), seenSubtypeNames: soFar.seenSubtypeNames, }; } else { return { errors: soFar.errors, seenSubtypeNames: Map.insert( subtypeName, subtypeName, soFar.seenSubtypeNames, ), }; } } export function createAlgebraicTypePlugin(): AlgebraicType.Plugin { return { additionalFiles: function (algebraicType: AlgebraicType.Type): Code.File[] { return []; }, transformBaseFile: function ( algebraicType: AlgebraicType.Type, baseFile: Code.File, ): Code.File { return baseFile; }, blockTypes: function (algebraicType: AlgebraicType.Type): ObjC.BlockType[] { return []; }, classMethods: function (algebraicType: AlgebraicType.Type): ObjC.Method[] { return algebraicType.subtypes.map((subtype) => initializationClassMethodForSubtype(algebraicType, subtype), ); }, enumerations: function ( algebraicType: AlgebraicType.Type, ): ObjC.Enumeration[] { return [enumerationForSubtypesOfAlgebraicType(algebraicType)]; }, transformFileRequest: function ( request: FileWriter.Request, ): FileWriter.Request { return request; }, fileType: function ( algebraicType: AlgebraicType.Type, ): Code.FileType | null { return null; }, forwardDeclarations: function ( algebraicType: AlgebraicType.Type, ): ObjC.ForwardDeclaration[] { if (makePublicImportsForAlgebraicType(algebraicType)) { return []; } const attributes = AlgebraicTypeUtils.allAttributesFromSubtypes( algebraicType.subtypes, ); return ([] as ObjC.ForwardDeclaration[]).concat( ...attributes.map((a) => ObjCImportUtils.forwardDeclarationsForAttributeType( a.type.name, a.type.underlyingType, a.type.conformingProtocol, a.type.referencedGenericTypes, algebraicType.typeLookups, ), ), ); }, functions: function (algebraicType: AlgebraicType.Type): ObjC.Function[] { return []; }, headerComments: function ( algebraicType: AlgebraicType.Type, ): ObjC.Comment[] { return []; }, implementedProtocols: function ( algebraicType: AlgebraicType.Type, ): ObjC.ImplementedProtocol[] { return []; }, imports: function imports( algebraicType: AlgebraicType.Type, ): ObjC.Import[] { const baseImports: ObjC.Import[] = [ PUBLIC_FOUNDATION_IMPORT, internalImportForFileWithName(algebraicType.name), ]; const makePublicImports = makePublicImportsForAlgebraicType(algebraicType); const typeLookupImports = algebraicType.typeLookups .filter((typeLookup) => isImportRequiredForTypeLookup(algebraicType, typeLookup), ) .map((typeLookup) => ObjCImportUtils.importForTypeLookup( algebraicType.libraryName, makePublicImports || !typeLookup.canForwardDeclare, typeLookup, ), ); const skipAttributeImports = !makePublicImports && algebraicType.includes.indexOf('SkipImportsInImplementation') !== -1; const attributeImports: ObjC.Import[] = skipAttributeImports ? [] : AlgebraicTypeUtils.allAttributesFromSubtypes(algebraicType.subtypes) .filter((attribute) => ObjCImportUtils.shouldIncludeImportForType( algebraicType.typeLookups, attribute.type.name, ), ) .map((attribute) => ObjCImportUtils.importForAttribute( attribute.type.name, attribute.type.underlyingType, attribute.type.libraryTypeIsDefinedIn, attribute.type.fileTypeIsDefinedIn, algebraicType.libraryName, makePublicImports, ), ); return baseImports.concat(typeLookupImports).concat(attributeImports); }, instanceMethods: function ( algebraicType: AlgebraicType.Type, ): ObjC.Method[] { return []; }, instanceVariables: function ( algebraicType: AlgebraicType.Type, ): ObjC.InstanceVariable[] { return instanceVariablesForImplementationOfAlgebraicType(algebraicType); }, macros: function (algebraicType: AlgebraicType.Type): ObjC.Macro[] { return []; }, requiredIncludesToRun: ['AlgebraicTypeInitialization'], staticConstants: function ( algebraicType: AlgebraicType.Type, ): ObjC.Constant[] { return []; }, validationErrors: function ( algebraicType: AlgebraicType.Type, ): Error.Error[] { const initialReductionTracker: ValidationErrorReductionTracker = { errors: List.of<Error.Error>(), seenSubtypeNames: Map.Empty<string, string>(), }; return List.toArray( algebraicType.subtypes.reduce( buildAlgebraicTypeValidationErrors, initialReductionTracker, ).errors, ); }, nullability: function ( algebraicType: AlgebraicType.Type, ): ObjC.ClassNullability | null { return null; }, subclassingRestricted: function ( algebraicType: AlgebraicType.Type, ): boolean { return false; }, }; }
the_stack
import Vue from 'vue'; import * as types from '../mutation-types'; import constants from '../../../renderer/mainBrowserWindow/constants'; import timeUtil from '../../../renderer/lib/time-util'; import urlUtil from '../../../renderer/lib/url-util'; const state: Lulumi.Store.State = { tabId: 0, tabs: [], tabsOrder: [], currentTabIndexes: [0], searchEngine: constants.searchEngine, currentSearchEngine: constants.currentSearchEngine, autoFetch: constants.autoFetch, homepage: constants.homepage, pdfViewer: constants.pdfViewer, tabConfig: constants.tabConfig, lang: 'en', proxyConfig: constants.proxyConfig, auth: { username: '', password: '' }, downloads: [], history: [], permissions: {}, lastOpenedTabs: [], certificates: {}, windows: [], extensionInfoDict: {}, }; // eslint-disable-next-line max-len function createTabObject(stateContext: Lulumi.Store.State, wid: number, openUrl: string | null = null): Lulumi.Store.TabObject { return { browserViewId: -1, webContentsId: -1, id: 0, index: 0, windowId: wid, highlighted: false, active: false, pinned: false, url: openUrl || stateContext.tabConfig.dummyTabObject.url, title: null, favIconUrl: null, status: null, incognito: false, statusText: false, isLoading: false, didNavigate: false, isSearching: false, canGoBack: false, canGoForward: false, canRefresh: false, error: false, hasMedia: false, isAudioMuted: false, pageActionMapping: {}, extensionsMetadata: {}, }; } const mutations = { // global counter [types.INCREMENT_TAB_ID](stateContext: Lulumi.Store.State): void { stateContext.tabId += 1; }, // tab handler [types.CREATE_TAB](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const url: string = payload.url; const isURL: boolean = payload.isURL; const follow: boolean = payload.follow; stateContext.tabs.forEach((tab, index) => { Vue.set(stateContext.tabs[index], 'highlighted', false); Vue.set(stateContext.tabs[index], 'active', false); }); let newUrl: string | null = null; if (isURL) { newUrl = url; stateContext.tabs.push(createTabObject(stateContext, windowId, newUrl)); } else if (url) { newUrl = constants.currentSearchEngine.search.replace('{queryString}', encodeURIComponent(url)); stateContext.tabs.push(createTabObject(stateContext, windowId, newUrl)); } else { stateContext.tabs.push(createTabObject(stateContext, windowId)); } Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'id', stateContext.tabId); const last = stateContext.tabs.filter(tab => tab.windowId === windowId).length - 1; if (url) { if (follow) { Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'highlighted', true); Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'active', true); Vue.set(stateContext.currentTabIndexes, windowId, last); } } else { Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'highlighted', true); Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'active', true); Vue.set(stateContext.currentTabIndexes, windowId, last); } }, [types.CLOSE_TAB](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const tabId: number = payload.tabId; const tabIndex: number = payload.tabIndex; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); const tabs = stateContext.tabs.filter(tab => tab.windowId === windowId); if (tabs.length > tabIndex) { stateContext.tabs.forEach((tab, index) => { Vue.set(stateContext.tabs[index], 'highlighted', false); Vue.set(stateContext.tabs[index], 'active', false); }); if (stateContext.tabs[tabsIndex].title !== 'error') { stateContext.lastOpenedTabs.unshift({ title: stateContext.tabs[tabsIndex].title, url: stateContext.tabs[tabsIndex].url, favIconUrl: stateContext.tabs[tabsIndex].favIconUrl, mtime: timeUtil.getMillisecondsTime(), }); } if (tabs.length === 1) { Vue.delete(stateContext.tabs, tabsIndex); stateContext.tabId += 1; stateContext.tabs.push(createTabObject(stateContext, windowId)); Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'id', stateContext.tabId); Object.keys(stateContext.extensionInfoDict).forEach((extensionId) => { Vue.set(stateContext.tabs[stateContext.tabs.length - 1].extensionsMetadata, extensionId, { browserActionIcon: '#', pageActionIcon: '#', badgeText: '', badgeBackgroundColor: '', }); }); Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'highlighted', true); Vue.set(stateContext.tabs[stateContext.tabs.length - 1], 'active', true); Vue.set(stateContext.currentTabIndexes, windowId, 0); } else { // find the nearest adjacent tab to make active // eslint-disable-next-line max-len const tabsMapping = (mappedTabs: Lulumi.Store.TabObject[], tabsOrder: number[]): number[] => { const newOrder: number[] = []; for (let index = 0; index < mappedTabs.length; index += 1) { if (tabsOrder) { newOrder[index] = !tabsOrder.includes(index) ? index : tabsOrder.indexOf(index); } else { newOrder[index] = index; } } return newOrder; }; const mapping = tabsMapping(tabs, stateContext.tabsOrder[windowId]); const currentTabIndex = stateContext.currentTabIndexes[windowId]; if (currentTabIndex === tabIndex) { Vue.delete(stateContext.tabs, tabsIndex); for (let i = mapping[tabIndex] + 1; i < tabs.length; i += 1) { if (tabs[mapping.indexOf(i)]) { if (mapping.indexOf(i) > tabIndex) { Vue.set(stateContext.currentTabIndexes, windowId, mapping.indexOf(i) - 1); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === stateContext.tabs[mapping.indexOf(i) - 1].id )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); } else { Vue.set(stateContext.currentTabIndexes, windowId, mapping.indexOf(i)); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === stateContext.tabs[mapping.indexOf(i)].id )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); } return; } } for (let i = mapping[tabIndex] - 1; i >= 0; i -= 1) { if (tabs[mapping.indexOf(i)]) { if (mapping.indexOf(i) > tabIndex) { Vue.set(stateContext.currentTabIndexes, windowId, mapping.indexOf(i) - 1); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === stateContext.tabs[mapping.indexOf(i) - 1].id )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); } else { Vue.set(stateContext.currentTabIndexes, windowId, mapping.indexOf(i)); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === stateContext.tabs[mapping.indexOf(i)].id )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); } return; } } } else if (currentTabIndex > tabIndex) { Vue.delete(stateContext.tabs, tabsIndex); Vue.set(stateContext.currentTabIndexes, windowId, currentTabIndex - 1); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === stateContext.tabs[currentTabIndex - 1].id )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); } else { Vue.delete(stateContext.tabs, tabsIndex); } } } }, [types.CLOSE_ALL_TABS](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const amount: number = payload.amount; if (amount === 1) { const index = stateContext.tabs.findIndex(tab => ( tab.windowId === windowId )); if (stateContext.tabs[index].title !== 'error') { stateContext.lastOpenedTabs.unshift({ title: stateContext.tabs[index].title, url: stateContext.tabs[index].url, favIconUrl: stateContext.tabs[index].favIconUrl, mtime: timeUtil.getMillisecondsTime(), }); } Vue.delete(stateContext.tabs, index); } else { stateContext.tabs.forEach((tab, index) => { if (tab.windowId === windowId) { Vue.delete(stateContext.tabs, index); } }); } }, [types.CLICK_TAB](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const tabId: number = payload.tabId; const tabIndex: number = payload.tabIndex; stateContext.tabs.forEach((tab, index) => { Vue.set(stateContext.tabs[index], 'highlighted', false); Vue.set(stateContext.tabs[index], 'active', false); }); Vue.set(stateContext.currentTabIndexes, windowId, tabIndex); const index: number = stateContext.tabs.findIndex(tab => ( tab.id === tabId )); Vue.set(stateContext.tabs[index], 'highlighted', true); Vue.set(stateContext.tabs[index], 'active', true); }, // tab handlers [types.SET_BROWSER_VIEW_ID](stateContext: Lulumi.Store.State, payload: any): void { const browserViewId: number = payload.browserViewId; const tabId: number = payload.tabId; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].browserViewId = browserViewId; } }, [types.DID_START_LOADING](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const webContentsId: number = payload.webContentsId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].webContentsId = webContentsId; stateContext.tabs[tabsIndex].url = url; stateContext.tabs[tabsIndex].isLoading = true; stateContext.tabs[tabsIndex].didNavigate = false; stateContext.tabs[tabsIndex].status = 'loading'; stateContext.tabs[tabsIndex].error = false; // extensionsMetadata initilized Object.keys(stateContext.extensionInfoDict).forEach((extensionId) => { Vue.set(stateContext.tabs[tabsIndex].extensionsMetadata, extensionId, { browserActionIcon: '#', pageActionIcon: '#', badgeText: '', badgeBackgroundColor: '', }); }); } }, [types.DID_NAVIGATE](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].didNavigate = true; stateContext.tabs[tabsIndex].title = url; stateContext.tabs[tabsIndex].hasMedia = false; } }, [types.PAGE_TITLE_UPDATED](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const title: string = payload.title; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].title = title; } }, [types.DOM_READY](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].canGoBack = payload.canGoBack; stateContext.tabs[tabsIndex].canGoForward = payload.canGoForward; stateContext.tabs[tabsIndex].canRefresh = true; } }, [types.DID_FRAME_FINISH_LOAD](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const regexp = new RegExp(/^lulumi(-extension)?:\/\/.+$/); const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex] && url) { if (stateContext.tabs[tabsIndex].title !== 'error') { stateContext.tabs[tabsIndex].url = url; stateContext.tabs[tabsIndex].error = false; if (url === 'chrome://gpu/') { stateContext.tabs[tabsIndex].title = urlUtil.getUrlIfPrivileged(url).title; stateContext.tabs[tabsIndex].favIconUrl = constants.tabConfig.lulumiDefault.tabFavicon; } else if (url.match(regexp)) { // lulumi:// if (url.match(regexp)![1] === undefined) { stateContext.tabs[tabsIndex].title = urlUtil.getUrlIfPrivileged(url).title; // lulumi-extension:// } else { stateContext.tabs[tabsIndex].statusText = false; stateContext.tabs[tabsIndex].canGoBack = payload.canGoBack; stateContext.tabs[tabsIndex].canGoForward = payload.canGoForward; } stateContext.tabs[tabsIndex].favIconUrl = constants.tabConfig.lulumiDefault.tabFavicon; } else { if (stateContext.tabs[tabsIndex].title === '') { stateContext.tabs[tabsIndex].title = stateContext.tabs[tabsIndex].url; } // history if (!((stateContext.tabs[tabsIndex].url.startsWith('file://') && stateContext.tabs[tabsIndex].url.includes('/error/index.html')) || stateContext.tabs[tabsIndex].url.startsWith('lulumi:blank'))) { const dates = timeUtil.getLocaleCurrentTime().split(' '); const mtime = timeUtil.getMillisecondsTime(); const index = stateContext.history.findIndex(entry => ( entry.url === stateContext.tabs[tabsIndex].url )); let entry: Lulumi.Store.TabHistory | null = null; if (index !== -1) { entry = stateContext.history.splice(index, 1)[0]; entry.label = dates[0]; entry.time = dates[1]; entry.mtime = mtime; } else { entry = { mtime, title: stateContext.tabs[tabsIndex].title, url: stateContext.tabs[tabsIndex].url, favIconUrl: constants.tabConfig.lulumiDefault.tabFavicon, label: dates[0], time: dates[1], }; } stateContext.history.unshift(entry); } } } } }, [types.PAGE_FAVICON_UPDATED](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { const index = stateContext.history.findIndex(entry => ( entry.url === stateContext.tabs[tabsIndex].url )); if (index !== -1) { stateContext.history[index].favIconUrl = url; stateContext.tabs[tabsIndex].favIconUrl = url; } } }, [types.DID_STOP_LOADING](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex] && url) { stateContext.tabs[tabsIndex].url = url; stateContext.tabs[tabsIndex].canGoBack = payload.canGoBack; stateContext.tabs[tabsIndex].canGoForward = payload.canGoForward; stateContext.tabs[tabsIndex].statusText = false; stateContext.tabs[tabsIndex].isLoading = false; stateContext.tabs[tabsIndex].status = 'complete'; } }, [types.DID_FAIL_LOAD](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const isMainFrame: boolean = payload.isMainFrame; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex] && isMainFrame) { stateContext.tabs[tabsIndex].title = stateContext.tabs[tabsIndex].title || 'error'; stateContext.tabs[tabsIndex].error = true; } }, [types.UPDATE_TARGET_URL](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const url: string = payload.url; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].statusText = url; } }, [types.MEDIA_STARTED_PLAYING](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const isAudioMuted: boolean = payload.isAudioMuted; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].hasMedia = true; stateContext.tabs[tabsIndex].isAudioMuted = isAudioMuted; } }, [types.MEDIA_PAUSED](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].hasMedia = false; } }, [types.TOGGLE_AUDIO](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const muted: boolean = payload.muted; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].isAudioMuted = muted; } }, [types.UPDATE_CERTIFICATE](stateContext: Lulumi.Store.State, payload: any): void { const hostname: string = payload.hostname; const certificate: Electron.Certificate = payload.certificate; const verificationResult: string = payload.verificationResult; const errorCode: string = payload.errorCode; if (stateContext.certificates[hostname] === undefined) { Vue.set(stateContext.certificates, hostname, {}); } Vue.set(stateContext.certificates[hostname]!, 'certificate', certificate); Vue.set(stateContext.certificates[hostname]!, 'verificationResult', verificationResult); Vue.set(stateContext.certificates[hostname]!, 'errorCode', errorCode); }, [types.UPDATE_EXTENSION_METADATA](stateContext: Lulumi.Store.State, payload: any): void { const tabId: number = payload.tabId; const extensionId: string = payload.extensionId; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { const orig = stateContext.tabs[tabsIndex].extensionsMetadata[extensionId]; if (payload.browserActionIcon) { orig.browserActionIcon = payload.browserActionIcon; } if (payload.pageActionIcon) { orig.pageActionIcon = payload.pageActionIcon; } if (payload.badgeText) { orig.badgeText = payload.badgeText; } if (payload.badgeBackgroundColor) { orig.badgeBackgroundColor = payload.badgeBackgroundColor; } Vue.set(stateContext.tabs[tabsIndex].extensionsMetadata, extensionId, orig); } }, // preferences handlers [types.SET_CURRENT_SEARCH_ENGINE_PROVIDER](stateContext: Lulumi.Store.State, { val }: { val: any }): void { if (val.currentSearchEngine !== null) { stateContext.currentSearchEngine = val.currentSearchEngine; } stateContext.autoFetch = val.autoFetch; }, [types.SET_HOMEPAGE](stateContext: Lulumi.Store.State, { val }: { val: any }): void { stateContext.homepage = val.homepage; }, [types.SET_PDF_VIEWER](stateContext: Lulumi.Store.State, { val }: { val: any }): void { stateContext.pdfViewer = val.pdfViewer; }, [types.SET_TAB_CONFIG](stateContext: Lulumi.Store.State, { val }: { val: any }): void { Vue.set(stateContext.tabConfig.lulumiDefault, 'tabFavicon', val.tabFavicon); Vue.set(stateContext.tabConfig.dummyTabObject, 'url', val.defaultUrl); }, [types.SET_LANG](stateContext: Lulumi.Store.State, { val }: { val: any }): void { stateContext.lang = val.lang; }, [types.SET_PROXY_CONFIG](stateContext: Lulumi.Store.State, { val }: { val: any }): void { Vue.set(stateContext.proxyConfig, 'pacScript', val.pacScript); Vue.set(stateContext.proxyConfig, 'proxyRules', val.proxyRules); Vue.set(stateContext.proxyConfig, 'proxyBypassRules', val.proxyBypassRules); }, [types.SET_AUTH](stateContext: Lulumi.Store.State, { val }: { val: any }): void { Vue.set(stateContext.auth, 'username', val.username); Vue.set(stateContext.auth, 'password', val.password); }, [types.SET_DOWNLOADS](stateContext: Lulumi.Store.State, { val }: { val: any }): void { stateContext.downloads = val; }, [types.SET_HISTORY](stateContext: Lulumi.Store.State, { val }: { val: any }): void { stateContext.history = val; }, [types.SET_TABS_ORDER](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const tabsOrder: string[] = payload.tabsOrder; if (tabsOrder.length !== 0) { Vue.set(stateContext.tabsOrder, windowId, tabsOrder.map(element => parseInt(element, 10))); // assigning new indexes to tabs const tabs = stateContext.tabs.filter(tab => tab.windowId === windowId); for (let index = 0; index < tabs.length; index += 1) { const tabsIndex: number = stateContext.tabs.findIndex(tab => ( tabs[tabsOrder[index]].id === tab.id )); Vue.set(stateContext.tabs[tabsIndex], 'index', index); } } }, [types.SET_PAGE_ACTION](stateContext: Lulumi.Store.State, payload: any): void { const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const extensionId: string = payload.extensionId; const enabled: boolean = payload.enabled; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { if (stateContext.tabs[tabsIndex].pageActionMapping[extensionId]) { Vue.set(stateContext.tabs[tabsIndex].pageActionMapping[extensionId], 'enabled', enabled); } else { Vue.set(stateContext.tabs[tabsIndex].pageActionMapping, extensionId, {}); Vue.set(stateContext.tabs[tabsIndex].pageActionMapping[extensionId], 'enabled', enabled); } } }, [types.CLEAR_PAGE_ACTION](stateContext: Lulumi.Store.State, payload: any): void { // const windowId: number = payload.windowId; const tabId: number = payload.tabId; // const tabIndex: number = payload.tabIndex; const tabsIndex = stateContext.tabs.findIndex(tab => tab.id === tabId); if (stateContext.tabs[tabsIndex]) { stateContext.tabs[tabsIndex].pageActionMapping = {}; } }, // downloads handlers [types.CREATE_DOWNLOAD_TASK](stateContext: Lulumi.Store.State, payload: any): void { stateContext.downloads.unshift(payload); }, [types.UPDATE_DOWNLOADS_PROGRESS](stateContext: Lulumi.Store.State, payload: any): void { const index = stateContext.downloads.findIndex(download => ( download.startTime === payload.startTime )); if (index !== -1) { const download = stateContext.downloads[index]; download.getReceivedBytes = payload.getReceivedBytes; download.savePath = payload.savePath; download.isPaused = payload.isPaused; download.canResume = payload.canResume; download.dataState = payload.dataState; } }, [types.COMPLETE_DOWNLOADS_PROGRESS](stateContext: Lulumi.Store.State, payload: any): void { const index = stateContext.downloads.findIndex(download => ( download.startTime === payload.startTime )); if (index !== -1) { const download = stateContext.downloads[index]; if (download.savePath) { download.name = payload.name; download.dataState = payload.dataState; } else { stateContext.downloads.splice(index, 1); } } }, [types.CLOSE_DOWNLOAD_BAR](stateContext: any): void { stateContext.downloads.forEach(download => (download.style = 'hidden')); }, // permissions [types.SET_PERMISSIONS](stateContext: Lulumi.Store.State, payload: any): void { const hostname: string = payload.hostname; const permission: string = payload.permission; const accept: boolean = payload.accept; if (stateContext.permissions[hostname] === undefined) { Vue.set(stateContext.permissions, hostname, {}); } Vue.set(stateContext.permissions[hostname], permission, accept); }, // set state [types.SET_LULUMI_STATE](stateContext: Lulumi.Store.State, { newState }: { newState: any }): void { stateContext.tabId = newState.pid; stateContext.tabs = newState.tabs; stateContext.currentTabIndexes = newState.currentTabIndexes; stateContext.searchEngine = constants.searchEngine; stateContext.currentSearchEngine = newState.currentSearchEngine; stateContext.autoFetch = newState.autoFetch; stateContext.homepage = newState.homepage; stateContext.pdfViewer = newState.pdfViewer; stateContext.tabConfig = newState.tabConfig; stateContext.lang = newState.lang; stateContext.proxyConfig = newState.proxyConfig; stateContext.downloads = newState.downloads; stateContext.history = newState.history; stateContext.lastOpenedTabs = newState.lastOpenedTabs; stateContext.windows = newState.windows; }, // window state [types.CREATE_WINDOW](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const width: number = payload.width; const height: number = payload.height; const left: number = payload.left; const top: number = payload.top; const windowState: string = payload.windowState; const type: string = payload.type; stateContext.windows.forEach( (_, index) => Vue.set(stateContext.windows[index], 'lastActive', false) ); const windowsIndex: number = stateContext.windows.findIndex(window => window.id === windowId); if (windowsIndex === -1) { stateContext.windows.push({ id: windowId, width, height, left, top, state: windowState, type, lastActive: true, }); } else { Vue.set(stateContext.windows, windowsIndex, { id: windowId, width, height, left, top, state: windowState, type, lastActive: true, }); } }, [types.CLOSE_WINDOW](stateContext: Lulumi.Store.State, { windowId }: { windowId: number }): void { const index: number = stateContext.windows.findIndex(window => (window.id === windowId)); if (index !== -1) { if (stateContext.windows[index].lastActive) { const keys = Object.keys(stateContext.windows); Vue.set(stateContext.windows[parseInt(keys[keys.length - 1], 10)], 'lastActive', true); } Vue.delete(stateContext.windows, index); } }, [types.UPDATE_WINDOW_PROPERTY](stateContext: Lulumi.Store.State, payload: any): void { const windowId: number = payload.windowId; const width: number = payload.width; const height: number = payload.height; const left: number = payload.left; const top: number = payload.top; const focused: boolean = payload.focused; const windowState: string = payload.windowState; const wid: number = stateContext.windows.findIndex(window => (window.id === windowId)); if (wid !== -1) { Vue.set(stateContext.windows[wid], 'width', width); Vue.set(stateContext.windows[wid], 'height', height); Vue.set(stateContext.windows[wid], 'left', left); Vue.set(stateContext.windows[wid], 'top', top); Vue.set(stateContext.windows[wid], 'focused', focused); Vue.set(stateContext.windows[wid], 'stateContext', windowState); if (focused) { stateContext.windows.forEach((window, index) => { Vue.set(stateContext.windows[index], 'lastActive', false); }); Vue.set(stateContext.windows[wid], 'lastActive', true); } } }, // extensions [types.ADD_EXTENSION](stateContext: Lulumi.Store.State, payload: any): void { const extensionInfo: chrome.management.ExtensionInfo = payload.extensionInfo; if (stateContext.extensionInfoDict[extensionInfo.id] === undefined) { Vue.set(stateContext.extensionInfoDict, extensionInfo.id, extensionInfo); stateContext.tabs.forEach((_, index) => { Vue.set(stateContext.tabs[index].extensionsMetadata, extensionInfo.id, { browserActionIcon: '#', pageActionIcon: '#', badgeText: '', badgeBackgroundColor: '', }); }); } }, [types.REMOVE_EXTENSION](stateContext: Lulumi.Store.State, payload: any): void { const extensionId: string = payload.extensionId; Vue.delete(stateContext.extensionInfoDict, extensionId); stateContext.tabs.forEach((_, index) => { Vue.delete(stateContext.tabs[index].extensionsMetadata, extensionId); }); }, [types.UPDATE_EXTENSION](stateContext: Lulumi.Store.State, payload: any): void { const enabled: boolean = payload.enabled; const extensionId: string = payload.extensionId; const extensionInfo = stateContext.extensionInfoDict[extensionId]; if (extensionInfo !== undefined) { extensionInfo.enabled = enabled; Vue.set(stateContext.extensionInfoDict, extensionId, extensionInfo); } }, }; export default { state, mutations, };
the_stack
import { NewExpression, Identifier, TemplateString, ArrayLiteral, CastExpression, BooleanLiteral, StringLiteral, NumericLiteral, CharacterLiteral, PropertyAccessExpression, Expression, ElementAccessExpression, BinaryExpression, UnresolvedCallExpression, ConditionalExpression, InstanceOfExpression, ParenthesizedExpression, RegexLiteral, UnaryExpression, UnaryType, MapLiteral, NullLiteral, AwaitExpression, UnresolvedNewExpression, UnresolvedMethodCallExpression, InstanceMethodCallExpression, NullCoalesceExpression, GlobalFunctionCallExpression, StaticMethodCallExpression, LambdaCallExpression, IMethodCallExpression } from "../One/Ast/Expressions"; import { Statement, ReturnStatement, UnsetStatement, ThrowStatement, ExpressionStatement, VariableDeclaration, BreakStatement, ForeachStatement, IfStatement, WhileStatement, ForStatement, DoStatement, ContinueStatement, TryStatement, Block } from "../One/Ast/Statements"; import { Class, SourceFile, IVariable, Lambda, Interface, IInterface, MethodParameter, IVariableWithInitializer, Visibility, Package, IHasAttributesAndTrivia, Enum } from "../One/Ast/Types"; import { VoidType, ClassType, InterfaceType, EnumType, AnyType, LambdaType, NullType, GenericsType } from "../One/Ast/AstTypes"; import { ThisReference, EnumReference, ClassReference, MethodParameterReference, VariableDeclarationReference, ForVariableReference, ForeachVariableReference, SuperReference, StaticFieldReference, StaticPropertyReference, InstanceFieldReference, InstancePropertyReference, EnumMemberReference, CatchVariableReference, GlobalFunctionReference, StaticThisReference, VariableReference } from "../One/Ast/References"; import { GeneratedFile } from "./GeneratedFile"; import { NameUtils } from "./NameUtils"; import { IGenerator } from "./IGenerator"; import { IExpression, IType } from "../One/Ast/Interfaces"; import { IGeneratorPlugin } from "./IGeneratorPlugin"; import { ITransformer } from "../One/ITransformer"; import { ExpressionValue, LambdaValue, TemplateFileGeneratorPlugin } from "./TemplateFileGeneratorPlugin"; import { IVMValue, StringValue } from "../VM/Values"; export class PhpGenerator implements IGenerator { usings: Set<string>; currentClass: IInterface; reservedWords: string[] = ["Generator", "Array", "List", "Interface", "Class"]; fieldToMethodHack = ["length"]; plugins: IGeneratorPlugin[] = []; getLangName(): string { return "PHP"; } getExtension(): string { return "php"; } getTransforms(): ITransformer[] { return []; } addInclude(include: string): void { this.usings.add(include); } addPlugin(plugin: IGeneratorPlugin) { this.plugins.push(plugin); // TODO: hack? if (plugin instanceof TemplateFileGeneratorPlugin) { plugin.modelGlobals["escape"] = new LambdaValue(args => new StringValue(this.escape(args[0]))); plugin.modelGlobals["escapeBackslash"] = new LambdaValue(args => new StringValue(this.escapeBackslash(args[0]))); } } escape(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof RegexLiteral) return JSON.stringify("/" + value.value.pattern.replace(/\//g, "\\/") + "/"); else if (value instanceof ExpressionValue && value.value instanceof StringLiteral) return JSON.stringify(value.value.stringValue); else if (value instanceof StringValue) return JSON.stringify(value.value); throw new Error(`Not supported VMValue for escape()`); } escapeBackslash(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof StringLiteral) return JSON.stringify(value.value.stringValue.replace(/\\/g, "\\\\")); throw new Error(`Not supported VMValue for escape()`); } name_(name: string) { if (this.reservedWords.includes(name)) name += "_"; if (this.fieldToMethodHack.includes(name)) name += "()"; const nameParts = name.split(/-/g); for (let i = 1; i < nameParts.length; i++) nameParts[i] = nameParts[i][0].toUpperCase() + nameParts[i].substr(1); name = nameParts.join(''); return name; } leading(item: Statement) { let result = ""; if (item.leadingTrivia !== null && item.leadingTrivia.length > 0) result += item.leadingTrivia; //if (item.attributes !== null) // result += Object.keys(item.attributes).map(x => `// @${x} ${item.attributes[x]}\n`).join(""); return result; } preArr(prefix: string, value: string[]) { return value.length > 0 ? `${prefix}${value.join(", ")}` : ""; } preIf(prefix: string, condition: boolean) { return condition ? prefix : ""; } pre(prefix: string, value: string) { return value !== null ? `${prefix}${value}` : ""; } typeArgs(args: string[]): string { return args !== null && args.length > 0 ? `<${args.join(", ")}>` : ""; } typeArgs2(args: IType[]): string { return this.typeArgs(args.map(x => this.type(x))); } type(t: IType, mutates = true): string { if (t instanceof ClassType) { //const typeArgs = this.typeArgs(t.typeArguments.map(x => this.type(x))); if (t.decl.name === "TsString") return "string"; else if (t.decl.name === "TsBoolean") return "bool"; else if (t.decl.name === "TsNumber") return "int"; else if (t.decl.name === "TsArray") { if (mutates) { return `List_`; } else return `${this.type(t.typeArguments[0])}[]`; } else if (t.decl.name === "Promise") { return this.type(t.typeArguments[0]); //return t.typeArguments[0] instanceof VoidType ? "Task" : `Task${typeArgs}`; } else if (t.decl.name === "Object") { //this.usings.add("System"); return `object`; } else if (t.decl.name === "TsMap") { return `Dictionary`; } if (t.decl.parentFile.exportScope === null) return `\\OneLang\\Core\\${this.name_(t.decl.name)}`; else return this.name_(t.decl.name); } else if (t instanceof InterfaceType) return `${this.name_(t.decl.name)}${this.typeArgs(t.typeArguments.map(x => this.type(x)))}`; else if (t instanceof VoidType) return "void"; else if (t instanceof EnumType) return `${this.name_(t.decl.name)}`; else if (t instanceof AnyType) return `object`; else if (t instanceof NullType) return `null`; else if (t instanceof GenericsType) return `${t.typeVarName}`; else if (t instanceof LambdaType) { const isFunc = !(t.returnType instanceof VoidType); const paramTypes = t.parameters.map(x => this.type(x.type)); if (isFunc) paramTypes.push(this.type(t.returnType)); return `${isFunc ? "Func" : "Action"}<${paramTypes.join(", ")}>`; } else if (t === null) { return "/* TODO */ object"; } else { debugger; return "/* MISSING */"; } } isTsArray(type: IType) { return type instanceof ClassType && type.decl.name == "TsArray"; } vis(v: Visibility, isProperty: boolean) { return v === Visibility.Private ? "private " : v === Visibility.Protected ? "protected " : v === Visibility.Public ? (isProperty ? "public " : "") : "/* TODO: not set */" + (isProperty ? "public " : ""); } varWoInit(v: IVariable, attr: IHasAttributesAndTrivia) { // let type: string; // if (attr !== null && attr.attributes !== null && "php-type" in attr.attributes) // type = attr.attributes["php-type"]; // else if (v.type instanceof ClassType && v.type.decl.name === "TsArray") { // if (v.mutability.mutated) { // type = `List<${this.type(v.type.typeArguments[0])}>`; // } else { // type = `${this.type(v.type.typeArguments[0])}[]`; // } // } else { // type = this.type(v.type); // } return `$${this.name_(v.name)}`; } var(v: IVariableWithInitializer, attrs: IHasAttributesAndTrivia) { return this.varWoInit(v, attrs) + (v.initializer !== null ? ` = ${this.expr(v.initializer)}` : ""); } exprCall(typeArgs: IType[], args: Expression[]) { return this.typeArgs2(typeArgs) + `(${args.map(x => this.expr(x)).join(", ")})`; } mutateArg(arg: Expression, shouldBeMutable: boolean) { // if (this.isTsArray(arg.actualType)) { // if (arg instanceof ArrayLiteral && !shouldBeMutable) { // return `Array(${arg.items.map(x => this.expr(x)).join(', ')})`; // } // let currentlyMutable = shouldBeMutable; // if (arg instanceof VariableReference) // currentlyMutable = arg.getVariable().mutability.mutated; // else if (arg instanceof InstanceMethodCallExpression || arg instanceof StaticMethodCallExpression) // currentlyMutable = false; // if (currentlyMutable && !shouldBeMutable) // return `${this.expr(arg)}.ToArray()`; // else if (!currentlyMutable && shouldBeMutable) { // return `${this.expr(arg)}.ToList()`; // } // } return this.expr(arg); } mutatedExpr(expr: Expression, toWhere: Expression) { if (toWhere instanceof VariableReference) { const v = toWhere.getVariable(); if (this.isTsArray(v.type)) return this.mutateArg(expr, v.mutability.mutated); } return this.expr(expr); } callParams(args: Expression[], params: MethodParameter[]) { const argReprs: string[] = []; for (let i = 0; i < args.length; i++) argReprs.push(this.isTsArray(params[i].type) ? this.mutateArg(args[i], params[i].mutability.mutated) : this.expr(args[i])); return `(${argReprs.join(", ")})`; } methodCall(expr: IMethodCallExpression) { return this.name_(expr.method.name) + this.typeArgs2(expr.typeArgs) + this.callParams(expr.args, expr.method.parameters); } inferExprNameForType(type: IType): string { if (type instanceof ClassType && type.typeArguments.every((x,_) => x instanceof ClassType)) { const fullName = type.typeArguments.map(x => (<ClassType>x).decl.name).join('') + type.decl.name; return NameUtils.shortName(fullName); } return null; } expr(expr: IExpression): string { for (const plugin of this.plugins) { const result = plugin.expr(expr); if (result !== null) return result; } let res = "UNKNOWN-EXPR"; if (expr instanceof NewExpression) { res = `new ${this.type(expr.cls)}${this.callParams(expr.args, expr.cls.decl.constructor_ !== null ? expr.cls.decl.constructor_.parameters : [])}`; } else if (expr instanceof UnresolvedNewExpression) { res = `/* TODO: UnresolvedNewExpression */ new ${this.type(expr.cls)}(${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof Identifier) { res = `/* TODO: Identifier */ ${expr.text}`; } else if (expr instanceof PropertyAccessExpression) { res = `/* TODO: PropertyAccessExpression */ ${this.expr(expr.object)}.${expr.propertyName}`; } else if (expr instanceof UnresolvedCallExpression) { res = `/* TODO: UnresolvedCallExpression */ ${this.expr(expr.func)}${this.exprCall(expr.typeArgs, expr.args)}`; } else if (expr instanceof UnresolvedMethodCallExpression) { res = `/* TODO: UnresolvedMethodCallExpression */ ${this.expr(expr.object)}->${expr.methodName}${this.exprCall(expr.typeArgs, expr.args)}`; } else if (expr instanceof InstanceMethodCallExpression) { if (expr.object instanceof SuperReference) res = `parent::${this.methodCall(expr)}`; else if (expr.object instanceof NewExpression) { res = `(${this.expr(expr.object)})->${this.methodCall(expr)}`; } else res = `${this.expr(expr.object)}->${this.methodCall(expr)}`; } else if (expr instanceof StaticMethodCallExpression) { res = `${this.name_(expr.method.parentInterface.name)}::${this.methodCall(expr)}`; if (expr.method.parentInterface.parentFile.exportScope === null) res = `\\OneLang\\Core\\${res}`; } else if (expr instanceof GlobalFunctionCallExpression) { res = `${this.name_(expr.func.name)}${this.exprCall([], expr.args)}`; } else if (expr instanceof LambdaCallExpression) { res = `call_user_func(${this.expr(expr.method)}, ${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof BooleanLiteral) { res = `${expr.boolValue ? "true" : "false"}`; } else if (expr instanceof StringLiteral) { res = JSON.stringify(expr.stringValue).replace(/\$/g, "\\$"); } else if (expr instanceof NumericLiteral) { res = expr.valueAsText; } else if (expr instanceof CharacterLiteral) { res = `'${expr.charValue}'`; } else if (expr instanceof ElementAccessExpression) { res = `${this.expr(expr.object)}[${this.expr(expr.elementExpr)}]`; } else if (expr instanceof TemplateString) { const parts: string[] = []; for (const part of expr.parts) { if (part.isLiteral) { let lit = ""; for (let i = 0; i < part.literalText.length; i++) { const chr = part.literalText[i]; if (chr === '\n') lit += "\\n"; else if (chr === '\r') lit += "\\r"; else if (chr === '\t') lit += "\\t"; else if (chr === '$') lit += "\\$"; else if (chr === '\\') lit += "\\\\"; else if (chr === '"') lit += '\\"'; else { const chrCode = chr.charCodeAt(0); if (32 <= chrCode && chrCode <= 126) lit += chr; else throw new Error(`invalid char in template string (code=${chrCode})`); } } parts.push(`"${lit}"`); } else { const repr = this.expr(part.expression); const isComplex = part.expression instanceof ConditionalExpression || part.expression instanceof BinaryExpression || part.expression instanceof NullCoalesceExpression; parts.push(isComplex ? `(${repr})` : repr); } } res = parts.join(' . '); } else if (expr instanceof BinaryExpression) { let op = expr.operator; if (op === "==") op = "==="; else if (op === "!=") op = "!=="; if (expr.left.actualType !== null && expr.left.actualType.repr() === "C:TsString") { if (op === "+") op = "."; else if (op === "+=") op = ".="; } // const useParen = expr.left instanceof BinaryExpression && expr.left.operator !== expr.operator; // const leftExpr = this.expr(expr.left); res = `${this.expr(expr.left)} ${op} ${this.mutatedExpr(expr.right, expr.operator === "=" ? expr.left : null)}`; } else if (expr instanceof ArrayLiteral) { res = `array(${expr.items.map(x => this.expr(x)).join(', ')})`; } else if (expr instanceof CastExpression) { res = `${this.expr(expr.expression)}`; } else if (expr instanceof ConditionalExpression) { let whenFalseExpr = this.expr(expr.whenFalse); if (expr.whenFalse instanceof ConditionalExpression) whenFalseExpr = `(${whenFalseExpr})`; res = `${this.expr(expr.condition)} ? ${this.expr(expr.whenTrue)} : ${whenFalseExpr}`; } else if (expr instanceof InstanceOfExpression) { res = `${this.expr(expr.expr)} instanceof ${this.type(expr.checkType)}`; } else if (expr instanceof ParenthesizedExpression) { res = `(${this.expr(expr.expression)})`; } else if (expr instanceof RegexLiteral) { res = `new \\OneLang\\Core\\RegExp(${JSON.stringify(expr.pattern)})`; } else if (expr instanceof Lambda) { const params = expr.parameters.map(x => `$${this.name_(x.name)}`); // TODO: captures should not be null const uses = expr.captures !== null && expr.captures.length > 0 ? ` use (${expr.captures.map(x => `$${x.name}`).join(", ")})` : ""; res = `function (${params.join(", ")})${uses} { ${this.rawBlock(expr.body)} }`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Prefix) { res = `${expr.operator}${this.expr(expr.operand)}`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Postfix) { res = `${this.expr(expr.operand)}${expr.operator}`; } else if (expr instanceof MapLiteral) { const repr = expr.items.map(item => `${JSON.stringify(item.key)} => ${this.expr(item.value)}`).join(",\n"); res = "Array(" + (repr === "" ? "" : repr.includes("\n") ? `\n${this.pad(repr)}\n` : repr) + ")"; } else if (expr instanceof NullLiteral) { res = `null`; } else if (expr instanceof AwaitExpression) { res = `${this.expr(expr.expr)}`; } else if (expr instanceof ThisReference) { res = `$this`; } else if (expr instanceof StaticThisReference) { res = `${this.currentClass.name}`; } else if (expr instanceof EnumReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ClassReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof MethodParameterReference) { res = `$${this.name_(expr.decl.name)}`; } else if (expr instanceof VariableDeclarationReference) { res = `$${this.name_(expr.decl.name)}`; } else if (expr instanceof ForVariableReference) { res = `$${this.name_(expr.decl.name)}`; } else if (expr instanceof ForeachVariableReference) { res = `$${this.name_(expr.decl.name)}`; } else if (expr instanceof CatchVariableReference) { res = `$${this.name_(expr.decl.name)}`; } else if (expr instanceof GlobalFunctionReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof SuperReference) { res = `parent`; } else if (expr instanceof StaticFieldReference) { res = `${this.name_(expr.decl.parentInterface.name)}::$${this.name_(expr.decl.name)}`; } else if (expr instanceof StaticPropertyReference) { res = `${this.name_(expr.decl.parentClass.name)}::get_${this.name_(expr.decl.name)}()`; } else if (expr instanceof InstanceFieldReference) { res = `${this.expr(expr.object)}->${this.name_(expr.field.name)}`; } else if (expr instanceof InstancePropertyReference) { res = `${this.expr(expr.object)}->get_${this.name_(expr.property.name)}()`; } else if (expr instanceof EnumMemberReference) { res = `${this.name_(expr.decl.parentEnum.name)}::${this.enumMemberName(expr.decl.name)}`; } else if (expr instanceof NullCoalesceExpression) { res = `${this.expr(expr.defaultExpr)} ?? ${this.mutatedExpr(expr.exprIfNull, expr.defaultExpr)}`; } else debugger; return res; } block(block: Block, allowOneLiner = true): string { const stmtLen = block.statements.length; return stmtLen === 0 ? " { }" : allowOneLiner && stmtLen === 1 && !(block.statements[0] instanceof IfStatement) ? `\n${this.pad(this.rawBlock(block))}` : ` {\n${this.pad(this.rawBlock(block))}\n}`; } stmtDefault(stmt: Statement): string { let res = "UNKNOWN-STATEMENT"; if (stmt.attributes !== null && "php" in stmt.attributes) { res = stmt.attributes["php"]; } else if (stmt instanceof BreakStatement) { res = "break;"; } else if (stmt instanceof ReturnStatement) { res = stmt.expression === null ? "return;" : `return ${this.mutateArg(stmt.expression, false)};`; } else if (stmt instanceof UnsetStatement) { res = `/* unset ${this.expr(stmt.expression)}; */`; } else if (stmt instanceof ThrowStatement) { res = `throw ${this.expr(stmt.expression)};`; } else if (stmt instanceof ExpressionStatement) { res = `${this.expr(stmt.expression)};`; } else if (stmt instanceof VariableDeclaration) { if (stmt.initializer instanceof NullLiteral) res = `$${this.name_(stmt.name)} = null;`; else if (stmt.initializer !== null) res = `$${this.name_(stmt.name)} = ${this.mutateArg(stmt.initializer, stmt.mutability.mutated)};`; else res = `/* @var $${this.name_(stmt.name)} */`; } else if (stmt instanceof ForeachStatement) { res = `foreach (${this.expr(stmt.items)} as $${this.name_(stmt.itemVar.name)})` + this.block(stmt.body); } else if (stmt instanceof IfStatement) { const elseIf = stmt.else_ !== null && stmt.else_.statements.length === 1 && stmt.else_.statements[0] instanceof IfStatement; res = `if (${this.expr(stmt.condition)})${this.block(stmt.then)}`; res += (elseIf ? `\nelse ${this.stmt(stmt.else_.statements[0])}` : "") + (!elseIf && stmt.else_ !== null ? `\nelse` + this.block(stmt.else_) : ""); } else if (stmt instanceof WhileStatement) { res = `while (${this.expr(stmt.condition)})` + this.block(stmt.body); } else if (stmt instanceof ForStatement) { res = `for (${stmt.itemVar !== null ? this.var(stmt.itemVar, null) : ""}; ${this.expr(stmt.condition)}; ${this.expr(stmt.incrementor)})` + this.block(stmt.body); } else if (stmt instanceof DoStatement) { res = `do${this.block(stmt.body)} while (${this.expr(stmt.condition)});`; } else if (stmt instanceof TryStatement) { res = "try" + this.block(stmt.tryBody, false); if (stmt.catchBody !== null) { // this.usings.add("System"); res += ` catch (Exception $${this.name_(stmt.catchVar.name)})${this.block(stmt.catchBody, false)}`; } if (stmt.finallyBody !== null) res += "finally" + this.block(stmt.finallyBody); } else if (stmt instanceof ContinueStatement) { res = `continue;`; } else debugger; return res; } stmt(stmt: Statement): string { let res: string = null; if (stmt.attributes !== null && "php" in stmt.attributes) { res = stmt.attributes["php"]; } else { for (const plugin of this.plugins) { res = plugin.stmt(stmt); if (res !== null) break; } if (res === null) res = this.stmtDefault(stmt); } return this.leading(stmt) + res; } stmts(stmts: Statement[]): string { return stmts.map(stmt => this.stmt(stmt)).join("\n"); } rawBlock(block: Block): string { return this.stmts(block.statements); } classLike(cls: IInterface) { this.currentClass = cls; const resList: string[] = []; const staticConstructorStmts: Statement[] = []; const complexFieldInits: Statement[] = []; if (cls instanceof Class) { const fieldReprs: string[] = []; for (const field of cls.fields) { const isInitializerComplex = field.initializer !== null && !(field.initializer instanceof StringLiteral) && !(field.initializer instanceof BooleanLiteral) && !(field.initializer instanceof NumericLiteral); const prefix = `${this.vis(field.visibility, true)}${this.preIf("static ", field.isStatic)}`; if (isInitializerComplex) { if (field.isStatic) staticConstructorStmts.push(new ExpressionStatement(new BinaryExpression(new StaticFieldReference(field), "=", field.initializer))); else complexFieldInits.push(new ExpressionStatement(new BinaryExpression(new InstanceFieldReference(new ThisReference(cls), field), "=", field.initializer))); fieldReprs.push(`${prefix}${this.varWoInit(field, field)};`); } else fieldReprs.push(`${prefix}${this.var(field, field)};`); } resList.push(fieldReprs.join("\n")); for (const prop of cls.properties) { if (prop.getter !== null) resList.push( this.vis(prop.visibility, false) + this.preIf("static ", prop.isStatic) + `function get_${this.name_(prop.name)}()${this.block(prop.getter, false)}`); if (prop.setter !== null) resList.push( this.vis(prop.visibility, false) + this.preIf("static ", prop.isStatic) + `function set_${this.name_(prop.name)}($value)${this.block(prop.setter, false)}`); } if (staticConstructorStmts.length > 0) resList.push(`static function StaticInit()\n{\n${this.pad(this.stmts(staticConstructorStmts))}\n}`); if (cls.constructor_ !== null) { const constrFieldInits: Statement[] = []; for (const field of cls.fields.filter(x => x.constructorParam !== null)) { const fieldRef = new InstanceFieldReference(new ThisReference(cls), field); const mpRef = new MethodParameterReference(field.constructorParam); // TODO: decide what to do with "after-TypeEngine" transformations mpRef.setActualType(field.type, false, false); constrFieldInits.push(new ExpressionStatement(new BinaryExpression(fieldRef, "=", mpRef))); } const parentCall = cls.constructor_.superCallArgs !== null ? `parent::__construct(${cls.constructor_.superCallArgs.map(x => this.expr(x)).join(", ")});\n` : ""; // @java var stmts = Stream.of(constrFieldInits, complexFieldInits, ((Class)cls).constructor_.getBody().statements).flatMap(Collection::stream).toArray(Statement[]::new); // @java-import java.util.Collection // @java-import java.util.stream.Stream const stmts = constrFieldInits.concat(complexFieldInits).concat(cls.constructor_.body.statements); resList.push( this.preIf("/* throws */ ", cls.constructor_.throws) + "function __construct" + `(${cls.constructor_.parameters.map(p => this.var(p, p)).join(", ")})` + ` {\n${this.pad( parentCall + this.stmts(stmts))}\n}`); } else if (complexFieldInits.length > 0) resList.push(`function __construct()\n{\n${this.pad(this.stmts(complexFieldInits))}\n}`); } else if (cls instanceof Interface) { //resList.push(cls.fields.map(field => `${this.varWoInit(field, field)} { get; set; }`).join("\n")); } const methods: string[] = []; for (const method of cls.methods) { if (cls instanceof Class && method.body === null) continue; // declaration only methods.push( (method.parentInterface instanceof Interface ? "" : this.vis(method.visibility, false)) + this.preIf("static ", method.isStatic) + //this.preIf("virtual ", method.overrides === null && method.overriddenBy.length > 0) + //this.preIf("override ", method.overrides !== null) + //this.preIf("async ", method.async) + this.preIf("/* throws */ ", method.throws) + `function ` + this.name_(method.name) + this.typeArgs(method.typeArguments) + `(${method.parameters.map(p => this.var(p, null)).join(", ")})` + (method.body !== null ? ` {\n${this.pad(this.stmts(method.body.statements))}\n}` : ";")); } resList.push(methods.join("\n\n")); const resListJoined = this.pad(resList.filter(x => x !== "").join("\n\n")); return ` {\n${resListJoined}\n}` + (staticConstructorStmts.length > 0 ? `\n${this.name_(cls.name)}::StaticInit();` : ""); } pad(str: string): string { return str.split(/\n/g).map(x => ` ${x}`).join('\n'); } pathToNs(path: string): string { // Generator/ExprLang/ExprLangAst -> Generator\ExprLang\ExprLangAst const parts = path.split(/\//g); //parts.pop(); return parts.join('\\'); } enumName(enum_: Enum, isDecl = false) { return enum_.name; } enumMemberName(name: string): string { return this.name_(name).toUpperCase(); } genFile(projName: string, sourceFile: SourceFile): string { this.usings = new Set<string>(); const enums: string[] = []; for (const enum_ of sourceFile.enums) { const values: string[] = []; for (let i = 0; i < enum_.values.length; i++) values.push(`const ${this.enumMemberName(enum_.values[i].name)} = ${i + 1};`); enums.push(`class ${this.enumName(enum_, true)} {\n` + this.pad(values.join("\n")) + `\n}`); } const intfs = sourceFile.interfaces.map(intf => `interface ${this.name_(intf.name)}${this.typeArgs(intf.typeArguments)}`+ `${this.preArr(" extends ", intf.baseInterfaces.map(x => this.type(x)))}${this.classLike(intf)}`); const classes: string[] = []; for (const cls of sourceFile.classes) { classes.push( `class ` + this.name_(cls.name) + (cls.baseClass !== null ? " extends " + this.type(cls.baseClass) : "") + this.preArr(" implements ", cls.baseInterfaces.map(x => this.type(x))) + `${this.classLike(cls)}`); } const main = this.rawBlock(sourceFile.mainBlock); const usingsSet = new Set<string>(); for (const imp of sourceFile.imports) { if ("php-use" in imp.attributes) for (const item of imp.attributes["php-use"].split(/\n/g)) usingsSet.add(item); else { const fileNs = this.pathToNs(imp.exportScope.scopeName); if (fileNs === "index") continue; for (const impItem of imp.imports) usingsSet.add(`${imp.exportScope.packageName}\\${fileNs}\\${this.name_(impItem.name)}`); } } for (const using of this.usings.values()) usingsSet.add(using); const usings: string[] = []; for (const using of usingsSet.values()) usings.push(`use ${using};`); let result = [usings.join("\n"), enums.join("\n"), intfs.join("\n\n"), classes.join("\n\n"), main].filter(x => x !== "").join("\n\n"); result = `<?php\n\nnamespace ${projName}\\${this.pathToNs(sourceFile.sourcePath.path)};\n\n${result}\n`; return result; } generate(pkg: Package): GeneratedFile[] { const result: GeneratedFile[] = []; for (const path of Object.keys(pkg.files)) result.push(new GeneratedFile(`${pkg.name}/${path}.php`, this.genFile(pkg.name, pkg.files[path]))); return result; } }
the_stack
import {Runtime} from 'vega-typings'; import { Binding, BuiltinParameter, ObjectOrAny, Operator, Parameter, Stream, Subflow, Update, ID, BaseOperator, } from 'vega-typings/types/runtime/runtime'; import {prettifyExpression} from './prettify'; import {Graph, Node} from './graph'; import {measureText} from './measureText'; export function runtimeToGraph(runtime: Runtime): Graph { const graph = {nodes: {}, edges: {}} as Graph; addRuntime(graph, runtime); return graph; } function addRuntime(graph: Graph, runtime: Runtime): void { runtime.bindings.forEach((b) => addBinding(graph, b)); addFlow(graph, runtime, undefined); } function addFlow(graph: Graph, {streams, operators, updates}: Subflow, parent: ID | undefined): void { streams.forEach((s) => addStream(graph, s, parent)); operators.forEach((o) => addOperator(graph, o, parent)); updates.forEach((u, i) => addUpdate(graph, u, i, parent)); } function addOperator(graph: Graph, {id, type, params, ...rest}: Operator, parent: ID | undefined): void { addNode(graph, { type: 'operator', id, parent, colorKey: `operator:${type}`, label: type, }); addParam(graph, id, 'ID', id.toString(), false); addOperatorParameters(graph, id, params); // Don't show metadata delete rest['metadata']; // Refs is always null delete rest['refs']; if ('update' in rest) { addParam(graph, id, 'update', rest.update.code); delete rest['update']; } if (rest.parent !== undefined) { const parentID = rest.parent.$ref; addEdge(graph, {source: parentID, target: id}); delete rest['parent']; } // Handle data separately to show in graph as nodes if (rest.data !== undefined) { addData(graph, id, rest.data, parent); delete rest['data']; } if (rest.signal !== undefined) { addSignal(graph, id, rest.signal, parent); delete rest['signal']; } for (const [k, v] of Object.entries(rest)) { if (v === undefined) { continue; } addParam(graph, id, k, JSON.stringify(v)); } } function addSignal(graph: Graph, id: ID, signal: string, parent: ID | undefined): void { // If we have a signal, add a node for that signal if we havent already, // and add an edge. // If we have already added a binding for that signal, we use that node instead // of making a new one const signalID = parent !== undefined ? `${parent}.${signal}` : signal; if (!hasNode(graph, signalID)) { addNode(graph, { type: 'signal', id: signalID, parent, label: signal, }); } associateNode(graph, signalID, id); addEdge(graph, {source: signalID, target: id, label: 'signal'}); } function addData(graph: Graph, id: ID, data: BaseOperator['data'], parent: ID | undefined): void { for (const [name, dataset] of Object.entries(data)) { const datasetNodeID = `data.${parent ?? 'root'}.${name}`; if (!hasNode(graph, datasetNodeID)) { addNode(graph, { type: 'data', id: datasetNodeID, parent, label: name, }); } associateNode(graph, datasetNodeID, id); for (const stage of new Set(dataset)) { const datasetStageNodeID = `${datasetNodeID}.${stage}`; addNode(graph, { type: 'data', id: datasetStageNodeID, parent: datasetNodeID, label: stage, }); associateNode(graph, datasetStageNodeID, id); addEdge(graph, {source: datasetStageNodeID, target: id}); } } } function addOperatorParameters(graph: Graph, id: ID, params: Operator['params']): void { for (const [k, v] of Object.entries(params ?? {})) { if (v === undefined) { continue; } // We have to check to see if the parameter values is a either a regular JSON value, // or a special case parameter, or a list of values/special case parameters. if (Array.isArray(v)) { const added = new Set<number>(); for (const [i, vI] of v.entries()) { if (addOperatorParameter(graph, id, `${k}[${i}]`, vI)) { added.add(i); } } // If we didn't add any operators, then add them all as one array if (added.size === 0) { addParam(graph, id, k, JSON.stringify(v)); continue; } // otherwise, add all that aren't added for (const [i, vI] of v.entries()) { if (!added.has(i)) { addParam(graph, id, `${k}[${i}]`, JSON.stringify(vI)); } } continue; } // Tries adding the operator parameter as a special case, if that fails, // then add as a regular parameter by stringifying if (!addOperatorParameter(graph, id, k, v)) { addParam(graph, id, k, JSON.stringify(v)); } } } /** * Adds a parameter, returning whether it was added or not. */ function addOperatorParameter(graph: Graph, id: ID, k: string, v: Parameter | ObjectOrAny<BuiltinParameter>): boolean { // Hide null parent params if (k === 'parent' && v === null) { return true; } if (typeof v !== 'object') { return false; } if (v === null) { return false; } if ('$ref' in v) { const vID = v.$ref; const primary = k === 'pulse'; const label = primary ? undefined : k; addEdge(graph, {source: vID, target: id, label, primary}); return true; } if ('$subflow' in v) { addFlow(graph, v.$subflow, id); // Add edge to first node, which is root node and is used to detach the subflow // TODO: Disable for now, until we understand its purpose // const rootID = v.$subflow.operators[0].id; // addEdge(graph, {source: id, target: rootID, label: 'root'}); return true; } if ('$expr' in v) { addParam(graph, id, k, v.$expr.code); for (const [label, {$ref}] of Object.entries(v.$params)) { addEdge(graph, {source: $ref, target: id, label: `${k}.${label}`}); } return true; } if ('$encode' in v) { for (const [stage, {$expr}] of Object.entries(v.$encode)) { // Assumes that the marktype is the same in all stages addParam(graph, id, 'encode marktype', $expr.marktype); // Add each stage as a param, mapping each channel to its value addParam( graph, id, `encode.${stage}`, '{' + Object.entries($expr.channels) .map(([channel, {code}]) => `${channel}: ${prettifyExpression(code)},`) .join('\n') + '}' ); } return true; } return false; } function addUpdate(graph: Graph, {source, target, update, options}: Update, index: number, parent: ID): void { // ID updates by index const id = `update-${parent || 'root'}.${index}`; addNode(graph, {type: 'update', id: id, parent, label: 'update'}); if (options?.force) { addParam(graph, id, 'force', 'true'); } if (update && typeof update === 'object' && '$expr' in update) { addParam(graph, id, 'value', update.$expr.code); for (const [k, v] of Object.entries(update.$params ?? {})) { const paramID = v.$ref; associateNode(graph, id, paramID); addEdge(graph, {source: paramID, target: id, label: k}); } } else { addParam(graph, id, 'value', JSON.stringify(update)); } const sourceID = typeof source === 'object' ? source.$ref : source; associateNode(graph, id, sourceID); associateNode(graph, id, target); addEdge(graph, {source: sourceID, target: id}); addEdge(graph, {source: id, target}); } function addBinding(graph: Graph, {signal, ...rest}: Binding) { addNode(graph, { type: 'binding', id: signal, label: signal, }); for (const [k, v] of Object.entries(rest)) { if (v === undefined) { continue; } addParam(graph, signal, k, JSON.stringify(v)); } } function addStream(graph: Graph, stream: Stream, parent: ID) { const {id} = stream; const label = 'stream' in stream ? 'stream' : 'merge' in stream ? 'merge' : `${stream.source}:${stream.type}`; addNode(graph, { type: 'stream', id, label, parent, }); addParam(graph, id, 'type', 'stream'); if ('stream' in stream) { addEdge(graph, {source: stream.stream, target: id}); } else if ('merge' in stream) { stream.merge.forEach((from) => { addEdge(graph, {source: from, target: id}); }); } if ('between' in stream) { const [before, after] = stream.between; addEdge(graph, {source: before, target: id, label: 'before'}); addEdge(graph, {source: id, target: after, label: 'after'}); } if (stream.consume) { addParam(graph, id, 'consume', 'true'); } if (stream.debounce) { addParam(graph, id, 'debounce', stream.debounce.toString()); } if (stream.throttle) { addParam(graph, id, 'throttle', stream.throttle.toString()); } if (stream.filter) { addParam(graph, id, 'filter', stream.filter.code); } } // Helper function to assist in adding to the graph, taking care of denormalization, converting node IDs // to string, and adding edge IDs. function addNode( graph: Graph, { id: runtimeID, parent: parentRuntimeID, colorKey, ...rest }: {id: ID; parent?: ID} & Required<Pick<Node, 'type' | 'label'>> & Pick<Node, 'colorKey'> ): void { const id = runtimeID.toString(); const node = getNode(graph, id); Object.assign(node, rest); node.colorKey = colorKey ?? rest.type; node.size = measureText(node.label); node.associated.push(id); node.partition = rest.type === 'binding' || rest.type === 'signal' ? 0 : rest.type === 'stream' || rest.type === 'data' ? 1 : 2; if (parentRuntimeID) { const parentID = parentRuntimeID.toString(); node.parent = parentID; getNode(graph, parentID).children.push(id); } } // TODO Namespace signal by parent? function addEdge( graph: Graph, { source: runtimeSource, target: runtimeTarget, primary, label, }: {source: ID; target: ID; label?: string; primary?: boolean} ): void { const source = runtimeSource.toString(); const target = runtimeTarget.toString(); // Increment edge ids to make each unique graph.edges[`edge:${Object.keys(graph.edges).length}`] = { source, target, label, primary: primary ?? false, size: measureText(label ?? ''), }; getNode(graph, source).outgoing.push(target); getNode(graph, target).incoming.push(source); } function addParam(graph: Graph, id: ID, key: string, value: string, prettify = true): void { getNode(graph, id.toString()).params[key] = prettify ? prettifyExpression(value, key.length) : value; } function hasNode(graph: Graph, id: ID): boolean { return graph.nodes[id] !== undefined; } function associateNode(graph: Graph, nodeID: ID, relatedID: ID): void { getNode(graph, nodeID.toString()).associated.push(relatedID.toString()); } function getNode({nodes}: Graph, id: string): Node { let node = nodes[id]; if (!node) { node = { children: [], incoming: [], outgoing: [], associated: [], params: {}, size: null, }; nodes[id] = node; } return node; }
the_stack
import { Browser, EventHandler, createElement, EmitType } from '@syncfusion/ej2-base'; import { ILoadedEventArgs, ILoadEventArgs } from '../../src/linear-gauge/model/interface'; import { LinearGauge } from '../../src/linear-gauge/linear-gauge'; import { Annotations } from '../../src/linear-gauge/annotations/annotations'; import {profile , inMB, getMemoryProfile} from '../common.spec'; import { Pointer } from '../../src'; LinearGauge.Inject(Annotations); describe('Linear gauge control', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('linear gauge direct properties', () => { let gauge: LinearGauge; let element: HTMLElement; let svg: HTMLElement; beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); gauge.destroy(); }); it('checking with guage instance', () => { gauge.loaded = (args: ILoadedEventArgs): void => { expect(gauge != null).toBe(true); }; }); it('checking wkith gauge element', () => { let ele: HTMLElement = document.getElementById("container"); expect(ele.childNodes.length).toBeGreaterThan(0); }); it('checking with module name', (): void => { expect(gauge.getModuleName()).toBe('lineargauge'); }); it('checking with empty width property', (): void => { svg = document.getElementById('container_svg'); expect(svg.getAttribute('width') != null).toBe(true); }); it('checking with empty height property', (): void => { svg = document.getElementById('container_svg'); expect(svg.getAttribute('height')).toEqual('450'); }); it('checking with background color', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg != null).toBe(true); }; gauge.background = 'red'; gauge.border.width = 2; gauge.refresh(); }); it('checking with background color', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeBorder'); expect(svg != null).toBe(true); }; gauge.background = 'green'; gauge.refresh(); }); it('checking with height property', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg.getAttribute('height')).toEqual('600'); }; gauge.height = '600'; gauge.refresh(); }); it('checking with height in percentage', (done: Function) => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg.getAttribute('height') == '450').toBe(true); done(); }; gauge.height = '50%'; gauge.refresh(); }); it('checking with width in percentage', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg !== null).toBe(true); }; gauge.width = '50%'; gauge.refresh(); }); it('checking with width property', () => { gauge.loaded = (arg: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg.getAttribute('width')).toBe('800'); }; gauge.width = '800'; gauge.refresh(); }); it('checking the load event', () => { gauge.width = '600'; gauge.height = '450'; gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById("container_svg"); expect(svg.getAttribute('width')).toEqual('900'); expect(svg.getAttribute('height')).toEqual('600'); }; gauge.load = (args: ILoadEventArgs): void => { gauge.width = '900'; gauge.height = '600'; }; gauge.refresh(); }); it('checking with empty gauge title', () => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg == null).toEqual(true); }); it('checking with gauge title', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg != null).toBe(true); }; gauge.title = 'linear gauge'; gauge.refresh(); }); it('checking with gauge title content', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg.textContent == 'linear gauge').toBe(true); }; gauge.title = 'linear gauge'; gauge.refresh(); }); it('checking with title font size', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg.style.fontSize).toEqual('20px'); }; gauge.titleStyle.size = '20px'; gauge.refresh(); }); it('checking with title font family', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg.style.fontFamily).toEqual('serif'); }; gauge.titleStyle.fontFamily = 'Serif'; gauge.refresh(); }); it('checking with title font style', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg.style.fontStyle).toEqual('oblique'); }; gauge.titleStyle.fontStyle = 'oblique'; gauge.refresh(); }); it('checking with title font weight', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeTitle'); expect(svg.style.fontWeight).toEqual('bold'); }; gauge.titleStyle.fontWeight = 'bold'; gauge.refresh(); }); it('checking with gauge border color', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeBorder'); expect(svg.getAttribute('stroke')).toEqual('green'); }; gauge.border.color = 'green'; gauge.border.width = 1; gauge.refresh(); }); it('checking with gauge border opacity', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeBorder'); expect(svg != null).toBe(true); }; gauge.border.width = 5; gauge.refresh(); }); it('checking with gauge border color', () => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeBorder'); expect(svg.getAttribute('stroke')).toEqual('red'); }; gauge.border.color = 'red'; gauge.refresh(); }); it('checking with gauge border width', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_LinearGaugeBorder'); expect(svg.getAttribute('stroke-width')).toEqual('5'); }; gauge.border.width = 5; gauge.refresh(); }); it('checking with container group', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Normal_Layout'); expect(svg != null).toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.refresh(); }); it('checking with container normal rectangle box', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Normal_Layout'); expect(svg != null).toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.type = 'Normal'; gauge.refresh(); }); it('checking with container rounded rectangle box', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_RoundedRectangle_Layout'); expect(svg != null).toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.type = 'RoundedRectangle'; gauge.refresh(); }); it('checking with container thermometer', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); expect(svg != null).toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.type = 'Thermometer'; gauge.refresh(); }); it('checking with container fill', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); expect(svg.getAttribute('stroke') == '#bfbfbf').toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.refresh(); }); it('checking with container fill', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); expect(svg.getAttribute('fill') == 'green').toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.backgroundColor = 'green'; gauge.refresh(); }); it('checking with container stroke', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); expect(svg.getAttribute('stroke') == 'red').toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.border.color = 'red'; gauge.refresh(); }); it('checking with container stroke width', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); expect(svg.getAttribute('stroke-width') == '5').toBe(true); }; gauge.container.height = 400; gauge.container.width = 30; gauge.container.border.width = 5; gauge.refresh(); }); it('checking with horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_svg'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.refresh(); }); it('checking with Normal Container', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Normal_Layout'); expect(svg != null).toBe(true); }; gauge.container.type = 'Normal' gauge.orientation = 'Horizontal'; gauge.refresh(); }); it('checking with Container height and width', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Normal_Layout'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.container.height = 400; gauge.container.width = 20; gauge.refresh(); }); it('checking with Rounded Rectangle Container', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_RoundedRectangle_Layout'); expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.container.type = 'RoundedRectangle'; gauge.refresh(); }); it('checking with Thermometer Container', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { svg = document.getElementById('container_Thermometer_Layout'); // expect(svg != null).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.container.type = 'Thermometer'; gauge.refresh(); }); it('checking with persist data method', (): void => { gauge.getPersistData(); }); }); describe('set pointer value', () => { let element: HTMLElement; let gauge: LinearGauge; beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); }); it('checking with setPointerValue Method in vertical orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.setPointerValue(0, 0, 30); }); it('checking with setPointerValue Method in horizontal orientation', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = document.getElementById('container_AxisIndex_0_MarkerPointer_0'); expect(svg != null).toBe(true); }; gauge.setPointerValue(0, 0, 30); }); it('checking with setPointerValue Method in horizontal orientation with value greater than axis maximum', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; gauge.setPointerValue(0, 0, 60); let pointer:Pointer = <Pointer>gauge.axes[0].pointers[0]; expect(pointer.currentValue == 50).toBe(true); }; gauge.orientation = 'Horizontal'; gauge.axes[0].minimum = 0; gauge.axes[0].maximum = 50; }); it('checking with setPointerValue Method in horizontal orientation with value less than axis minimum', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; gauge.setPointerValue(0, 0, -20); let pointer:Pointer = <Pointer>gauge.axes[0].pointers[0]; expect(pointer.currentValue == 0).toBe(true); }; gauge.axes[0].minimum = 0; gauge.axes[0].maximum = 50; }); it('checking with setPointerValue Method in vertical orientation with value greater than axis maximum', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; gauge.setPointerValue(0, 0, 60); let pointer:Pointer = <Pointer>gauge.axes[0].pointers[0]; expect(pointer.currentValue == 50).toBe(true); }; gauge.axes[0].minimum = 0; gauge.axes[0].maximum = 50; gauge.orientation = 'Vertical'; }); it('checking with setPointerValue Method in vertical orientation with value less than axis minimum', (): void => { gauge.loaded = (args: ILoadedEventArgs): void => { let svg: HTMLElement = <HTMLElement>document.getElementById('container_AxisIndex_0_MarkerPointer_0').children[0]; gauge.setPointerValue(0, 0, -20); let pointer:Pointer = <Pointer>gauge.axes[0].pointers[0]; expect(pointer.currentValue == 0).toBe(true); }; gauge.axes[0].minimum = 0; gauge.axes[0].maximum = 50; }); }); describe('Checking onproperty changed method ', () => { let element: HTMLElement; let gauge: LinearGauge; beforeAll((): void => { element = createElement('div', { id: 'container' }); document.body.appendChild(element); gauge = new LinearGauge(); gauge.appendTo('#container'); }); afterAll((): void => { element.remove(); gauge.destroy(); }); it('checking with height and width', (): void => { gauge.height = '600'; gauge.width = '900'; gauge.dataBind(); }); it('checking with title', (): void => { gauge.title = 'Linear gauge'; gauge.dataBind(); }); it('checking with title style', (): void => { gauge.titleStyle.size = '30px'; gauge.dataBind(); }); it('checking with border', (): void => { gauge.border.color = 'red'; gauge.border.width = 5; gauge.dataBind(); }); it('checking with background', (): void => { gauge.background = 'green'; gauge.dataBind(); }); it('checking with title font Weight', (): void => { gauge.titleStyle.fontWeight = 'Bold'; gauge.dataBind(); }); it('checking with container', (): void => { gauge.container.type = 'Thermometer'; gauge.dataBind(); }); it('Checking resize event', () => { gauge.gaugeResize(<Event>{}); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import * as React from 'react' import { Provider } from 'react-redux' import { act } from 'react-dom/test-utils' import UAParser from 'ua-parser-js' import { mount } from 'enzyme' import { when, resetAllWhenMocks } from 'jest-when' import configureMockStore from 'redux-mock-store' import thunk from 'redux-thunk' import { ConnectedStepItem, getMetaSelectedSteps } from '../ConnectedStepItem' import { StepItem } from '../../components/steplist' import { ConfirmDeleteModal, CLOSE_UNSAVED_STEP_FORM, CLOSE_STEP_FORM_WITH_CHANGES, CLOSE_BATCH_EDIT_FORM, } from '../../components/modals/ConfirmDeleteModal' import * as stepFormSelectors from '../../step-forms/selectors/index' import * as dismissSelectors from '../../dismiss/selectors' import * as uiStepSelectors from '../../ui/steps/selectors' import * as fileDataSelectors from '../../file-data/selectors/index' import * as timelineWarningSelectors from '../../top-selectors/timelineWarnings' jest.mock('ua-parser-js') jest.mock('../../step-forms/selectors/index') jest.mock('../../file-data/selectors/index') jest.mock('../../top-selectors/timelineWarnings') jest.mock('../../dismiss/selectors') jest.mock('../../ui/steps/selectors') jest.mock('../../labware-ingred/selectors') jest.mock('../../feature-flags/selectors') const mockUAParser = UAParser as jest.MockedFunction<typeof UAParser> const getSavedStepFormsMock = stepFormSelectors.getSavedStepForms as jest.MockedFunction< typeof stepFormSelectors.getSavedStepForms > const getOrderedStepIdsMock = stepFormSelectors.getOrderedStepIds as jest.MockedFunction< typeof stepFormSelectors.getOrderedStepIds > const getArgsAndErrorsByStepIdMock = stepFormSelectors.getArgsAndErrorsByStepId as jest.MockedFunction< typeof stepFormSelectors.getArgsAndErrorsByStepId > const getCurrentFormIsPresavedMock = stepFormSelectors.getCurrentFormIsPresaved as jest.MockedFunction< typeof stepFormSelectors.getCurrentFormIsPresaved > const getCurrentFormHasUnsavedChangesMock = stepFormSelectors.getCurrentFormHasUnsavedChanges as jest.MockedFunction< typeof stepFormSelectors.getCurrentFormHasUnsavedChanges > const getBatchEditFormHasUnsavedChangesMock = stepFormSelectors.getBatchEditFormHasUnsavedChanges as jest.MockedFunction< typeof stepFormSelectors.getBatchEditFormHasUnsavedChanges > const getHasTimelineWarningsPerStepMock = timelineWarningSelectors.getHasTimelineWarningsPerStep as jest.MockedFunction< typeof timelineWarningSelectors.getHasTimelineWarningsPerStep > const getHasFormLevelWarningsPerStepMock = dismissSelectors.getHasFormLevelWarningsPerStep as jest.MockedFunction< typeof dismissSelectors.getHasFormLevelWarningsPerStep > const getCollapsedStepsMock = uiStepSelectors.getCollapsedSteps as jest.MockedFunction< typeof uiStepSelectors.getCollapsedSteps > const getSelectedStepIdMock = uiStepSelectors.getSelectedStepId as jest.MockedFunction< typeof uiStepSelectors.getSelectedStepId > const getMultiSelectLastSelectedMock = uiStepSelectors.getMultiSelectLastSelected as jest.MockedFunction< typeof uiStepSelectors.getMultiSelectLastSelected > const getMultiSelectItemIdsMock = uiStepSelectors.getMultiSelectItemIds as jest.MockedFunction< typeof uiStepSelectors.getMultiSelectItemIds > const getSubstepsMock = fileDataSelectors.getSubsteps as jest.MockedFunction< typeof fileDataSelectors.getSubsteps > const getErrorStepId = fileDataSelectors.getErrorStepId as jest.MockedFunction< typeof fileDataSelectors.getErrorStepId > const getIsMultiSelectModeMock = uiStepSelectors.getIsMultiSelectMode as jest.MockedFunction< typeof uiStepSelectors.getIsMultiSelectMode > const middlewares = [thunk] const mockStore = configureMockStore(middlewares) const mockId = 'SOMEID' function createMockClickEvent({ shiftKey = false, metaKey = false, ctrlKey = false, persist = jest.fn(), }: { shiftKey?: boolean metaKey?: boolean ctrlKey?: boolean persist?: () => void } = {}): React.MouseEvent { return { shiftKey, metaKey, ctrlKey, persist, } as React.MouseEvent } const mockClickEvent = createMockClickEvent() describe('ConnectedStepItem', () => { let store: any beforeEach(() => { store = mockStore() // @ts-expect-error(sa, 2021-6-27): missing parameters from UA Parser constructor return type mockUAParser.mockImplementation(() => { return { getOS: () => ({ name: 'Mac OS', version: 'mockVersion' }), } }) when(getSavedStepFormsMock) .calledWith(expect.anything()) // @ts-expect-error(sa, 2021-6-21): 'some form' is not a valid FormData type .mockReturnValue({ [mockId]: 'some form' }) when(getCurrentFormIsPresavedMock) .calledWith(expect.anything()) .mockReturnValue(false) when(getCurrentFormHasUnsavedChangesMock) .calledWith(expect.anything()) .mockReturnValue(false) when(getIsMultiSelectModeMock) .calledWith(expect.anything()) .mockReturnValue(false) when(getErrorStepId) .calledWith(expect.anything()) .mockReturnValue('errorId') when(getArgsAndErrorsByStepIdMock) .calledWith(expect.anything()) // @ts-expect-error(sa, 2021-6-21): missing properties .mockReturnValue({ [mockId]: { errors: true } }) when(getHasTimelineWarningsPerStepMock) .calledWith(expect.anything()) .mockReturnValue({}) when(getHasFormLevelWarningsPerStepMock) .calledWith(expect.anything()) .mockReturnValue({}) when(getCollapsedStepsMock) .calledWith(expect.anything()) .mockReturnValue({ [mockId]: false }) when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(null) when(getSubstepsMock) .calledWith(expect.anything()) .mockReturnValue({ [mockId]: undefined }) }) afterEach(() => { jest.resetAllMocks() resetAllWhenMocks() }) const render = (props: any) => mount( <Provider store={store}> <ConnectedStepItem {...props} /> </Provider> ) describe('when clicked normally', () => { it('should select a single step when PD not in batch edit mode', () => { const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) const actions = store.getActions() const selectStepAction = { type: 'SELECT_STEP', payload: mockId } expect(actions[0]).toEqual(selectStepAction) }) it('should display the "close unsaved form" modal when form has not yet been saved', () => { when(getCurrentFormIsPresavedMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe(CLOSE_UNSAVED_STEP_FORM) expect(store.getActions().length).toBe(0) }) it('should display the "unsaved changes to multiple steps" modal when batch edit form has unsaved changes', () => { when(getBatchEditFormHasUnsavedChangesMock) .calledWith(expect.anything()) .mockReturnValue(true) when(getIsMultiSelectModeMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe(CLOSE_BATCH_EDIT_FORM) expect(store.getActions().length).toBe(0) }) it('should display the "unsaved changes to step" modal when single edit form has unsaved changes', () => { when(getCurrentFormHasUnsavedChangesMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe( CLOSE_STEP_FORM_WITH_CHANGES ) expect(store.getActions().length).toBe(0) }) describe('when PD in batch edit mode', () => { it('should select a multiple steps', () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID']) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', mockId]) const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) const actions = store.getActions() const selectStepAction = { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID', mockId], lastSelected: mockId, }, } expect(actions[0]).toEqual(selectStepAction) }) it('should deselect the step', () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', mockId]) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', mockId]) const props = { stepId: mockId, stepNumber: 1 } const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) const actions = store.getActions() const selectStepAction = { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID'], lastSelected: mockId, }, } expect(actions[0]).toEqual(selectStepAction) }) }) }) describe('when shift + clicked', () => { describe('modal prompts', () => { it('should display the "close unsaved form" modal when form has not yet been saved', () => { when(getCurrentFormIsPresavedMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const clickEvent = { ...mockClickEvent, shiftKey: true, } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe( CLOSE_UNSAVED_STEP_FORM ) expect(store.getActions().length).toBe(0) }) it('should display the "unsaved changes to step" modal when single edit form has unsaved changes', () => { when(getCurrentFormHasUnsavedChangesMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const clickEvent = { ...mockClickEvent, shiftKey: true, } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe( CLOSE_STEP_FORM_WITH_CHANGES ) expect(store.getActions().length).toBe(0) }) }) const testCases = [ { name: 'should select just one step (in batch edit mode)', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue([ 'ANOTHER_ID', 'NOT_SELECTED_ID', 'YET_ANOTHER_ID', mockId, ]) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId], lastSelected: mockId, }, }, }, { name: 'should select a range of steps when one step is already selected', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getSelectedStepIdMock) .calledWith(expect.anything()) .mockReturnValue('ANOTHER_ID') when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', 'YET_ANOTHER_ID', mockId]) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID', 'YET_ANOTHER_ID', mockId], lastSelected: mockId, }, }, }, { name: 'should select just one step when the clicked step is already selected', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getSelectedStepIdMock) .calledWith(expect.anything()) .mockReturnValue(mockId) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', 'YET_ANOTHER_ID', mockId]) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId], lastSelected: mockId, }, }, }, { name: 'should select a range when the selected step is earlier than the last selected step (single => multi)', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue([mockId, 'ANOTHER_ID', 'YET_ANOTHER_ID']) when(getSelectedStepIdMock) .calledWith(expect.anything()) .mockReturnValue('YET_ANOTHER_ID') }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId, 'ANOTHER_ID', 'YET_ANOTHER_ID'], lastSelected: mockId, }, }, }, { name: 'should select a range when the selected step is earlier than the last selected step (multi => multi)', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['FOURTH_ID']) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue([mockId, 'SECOND_ID', 'THIRD_ID', 'FOURTH_ID']) when(getMultiSelectLastSelectedMock) .calledWith(expect.anything()) .mockReturnValue('FOURTH_ID') }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['FOURTH_ID', mockId, 'SECOND_ID', 'THIRD_ID'], lastSelected: mockId, }, }, }, { name: 'should select a range when some of them are already selected', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['FIRST_ID', 'SECOND_ID', 'THIRD_ID']) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['FIRST_ID', 'SECOND_ID', 'THIRD_ID', mockId]) when(getMultiSelectLastSelectedMock) .calledWith(expect.anything()) .mockReturnValue('THIRD_ID') }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['FIRST_ID', 'SECOND_ID', 'THIRD_ID', mockId], lastSelected: mockId, }, }, }, { name: 'should deselect a range when all of them are already selected', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue([ 'FIRST_ID', 'ANOTHER_ID', 'YET_ANOTHER_ID', mockId, ]) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue([ 'FIRST_ID ', 'ANOTHER_ID', 'YET_ANOTHER_ID', mockId, ]) when(getMultiSelectLastSelectedMock) .calledWith(expect.anything()) .mockReturnValue('ANOTHER_ID') }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['FIRST_ID'], lastSelected: mockId, }, }, }, { name: 'should deselect a range when all of them are already selected (but preserve the first item and not exit batch edit mode)', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['YET_ANOTHER_ID', mockId]) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', 'YET_ANOTHER_ID', mockId]) when(getMultiSelectLastSelectedMock) .calledWith(expect.anything()) .mockReturnValue('ANOTHER_ID') }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID'], lastSelected: mockId, }, }, }, { name: 'should ignore modifier key when clicking step that is already lastSelected', props: { stepId: mockId, stepNumber: 1 }, mockClickEvent: createMockClickEvent({ shiftKey: true, metaKey: false, ctrlKey: false, }), setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['YET_ANOTHER_ID']) when(getOrderedStepIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID', 'YET_ANOTHER_ID', mockId]) when(getMultiSelectLastSelectedMock) .calledWith(expect.anything()) .mockReturnValue(mockId) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['YET_ANOTHER_ID', mockId], lastSelected: mockId, }, }, }, ] testCases.forEach( ({ name, props, mockClickEvent, setupMocks, expectedAction }) => { it(name, () => { if (setupMocks) { setupMocks() } const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(mockClickEvent) const actions = store.getActions() expect(actions[0]).toEqual(expectedAction) }) } ) }) describe('when command + clicked', () => { describe('modal prompts', () => { it('should display the "close unsaved form" modal when form has not yet been saved', () => { when(getCurrentFormIsPresavedMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const clickEvent = { ...mockClickEvent, shiftKey: true, } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe( CLOSE_UNSAVED_STEP_FORM ) expect(store.getActions().length).toBe(0) }) it('should display the "unsaved changes to step" modal when single edit form has unsaved changes', () => { when(getCurrentFormHasUnsavedChangesMock) .calledWith(expect.anything()) .mockReturnValue(true) const props = { stepId: mockId, stepNumber: 1 } const clickEvent = { ...mockClickEvent, shiftKey: true, } const wrapper = render(props) act(() => { // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) }) wrapper.update() const confirmDeleteModal = wrapper.find(ConfirmDeleteModal) expect(confirmDeleteModal).toHaveLength(1) expect(confirmDeleteModal.prop('modalType')).toBe( CLOSE_STEP_FORM_WITH_CHANGES ) expect(store.getActions().length).toBe(0) }) }) describe('on non mac OS', () => { it('should select a single step', () => { const props = { stepId: mockId, stepNumber: 1, } const clickEvent = { ...mockClickEvent, metaKey: true, } // @ts-expect-error(sa, 2021-6-27): missing parameters from UA Parser constructor return type mockUAParser.mockImplementation(() => { return { getOS: () => ({ name: 'NOT Mac OS', version: 'mockVersion' }), } }) const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) const actions = store.getActions() expect(actions[0]).toEqual({ payload: 'SOMEID', type: 'SELECT_STEP' }) }) }) describe('on mac OS', () => { const testCases = [ { name: 'should enter batch edit mode with just step', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, metaKey: true, }, setupMocks: null, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId], lastSelected: mockId, }, }, }, { name: 'should enter batch edit mode with just step (when clicking the same step that is already selected)', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, metaKey: true, }, setupMocks: () => { when(getSelectedStepIdMock) .calledWith(expect.anything()) .mockReturnValue(mockId) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId], lastSelected: mockId, }, }, }, { name: 'should enter batch edit mode with multiple steps', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, metaKey: true, }, setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID']) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID', mockId], lastSelected: mockId, }, }, }, { name: 'should do nothing if deselecting the step item results in 0 steps being selected', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, metaKey: true, }, setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue([mockId]) }, expectedAction: undefined, // no action should be dispatched }, ] testCases.forEach( ({ name, props, clickEvent, setupMocks, expectedAction }) => { it(name, () => { setupMocks && setupMocks() // @ts-expect-error(sa, 2021-6-27): missing parameters from UA Parser constructor return type mockUAParser.mockImplementation(() => { return { getOS: () => ({ name: 'Mac OS', version: 'mockVersion', }), } }) const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) const actions = store.getActions() expect(actions[0]).toEqual(expectedAction) }) } ) }) }) describe('when ctrl + clicked', () => { describe('on mac OS', () => { it('should select a single step', () => { const props = { stepId: mockId, stepNumber: 1, } const clickEvent = { ...mockClickEvent, ctrlKey: true, } // @ts-expect-error(sa, 2021-6-27): missing parameters from UA Parser constructor return type mockUAParser.mockImplementation(() => { return { getOS: () => ({ name: 'Mac OS', version: 'mockVersion' }), } }) const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) const actions = store.getActions() expect(actions[0]).toEqual({ payload: 'SOMEID', type: 'SELECT_STEP' }) }) }) describe('on non mac OS', () => { const testCases = [ { name: 'should enter batch edit mode with just step', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, ctrlKey: true, }, setupMocks: null, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: [mockId], lastSelected: mockId, }, }, }, { name: 'should enter batch edit mode with multiple steps', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, ctrlKey: true, }, setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue(['ANOTHER_ID']) }, expectedAction: { type: 'SELECT_MULTIPLE_STEPS', payload: { stepIds: ['ANOTHER_ID', mockId], lastSelected: mockId, }, }, }, { name: 'should do nothing if deselecting the step item results in 0 steps being selected', props: { stepId: mockId, stepNumber: 1 }, clickEvent: { ...mockClickEvent, ctrlKey: true, }, setupMocks: () => { when(getMultiSelectItemIdsMock) .calledWith(expect.anything()) .mockReturnValue([mockId]) }, expectedAction: undefined, // no action should be dispatched }, ] testCases.forEach( ({ name, props, clickEvent, setupMocks, expectedAction }) => { it(name, () => { setupMocks && setupMocks() // @ts-expect-error(sa, 2021-6-27): missing parameters from UA Parser constructor return type mockUAParser.mockImplementation(() => { return { getOS: () => ({ name: 'NOT Mac OS', version: 'mockVersion', }), } }) const wrapper = render(props) // @ts-expect-error(sa, 2021-6-21): handleClick handler might not exist wrapper.find(StepItem).prop('handleClick')(clickEvent) const actions = store.getActions() expect(actions[0]).toEqual(expectedAction) }) } ) }) }) }) describe('getMetaSelectedSteps', () => { describe('when already in multi select mode', () => { it('should return the new steps and the original selected step', () => { const multiSelectItemIds = ['1', '2'] const stepId = '3' const singleSelectedId = null expect( getMetaSelectedSteps(multiSelectItemIds, stepId, singleSelectedId) ).toEqual(['1', '2', '3']) }) it('should remove the step if its already been selected', () => { const multiSelectItemIds = ['1', '2'] const stepId = '2' const singleSelectedId = null expect( getMetaSelectedSteps(multiSelectItemIds, stepId, singleSelectedId) ).toEqual(['1']) }) }) describe('when one step is selected (in single edit mode)', () => { it('should return the original step and the new step', () => { const multiSelectItemIds = null const stepId = '2' const singleSelectedId = '1' expect( getMetaSelectedSteps(multiSelectItemIds, stepId, singleSelectedId) ).toEqual(['1', '2']) }) it('should only return the original step once when it is the same as the selected step id', () => { const multiSelectItemIds = null const stepId = '2' const singleSelectedId = '2' expect( getMetaSelectedSteps(multiSelectItemIds, stepId, singleSelectedId) ).toEqual(['2']) }) }) describe('when no steps are selected', () => { it('should return the given step id', () => { const multiSelectItemIds = null const stepId = '2' const singleSelectedId = null expect( getMetaSelectedSteps(multiSelectItemIds, stepId, singleSelectedId) ).toEqual(['2']) }) }) })
the_stack
import { ObjectDictionary } from "@opticss/util"; import * as async from "async"; import * as convertSourceMap from "convert-source-map"; import * as debugGenerator from "debug"; import * as fs from "fs"; import { adaptFromLegacySourceMap, adaptToLegacySourceMap, postcss } from "opticss"; import * as path from "path"; import { RawSourceMap } from "source-map"; import { Compiler as WebpackCompiler } from "webpack"; import { ConcatSource, RawSource, Source, SourceMapSource } from "webpack-sources"; import { WebpackAny } from "./Plugin"; // tslint:disable-next-line:prefer-unknown-to-any export type PostcssAny = any; const debug = debugGenerator("css-blocks:webpack:assets"); export type PostcssProcessor = Array<postcss.Plugin<PostcssAny>> | ((assetPath: string) => Array<postcss.Plugin<PostcssAny>> | Promise<Array<postcss.Plugin<PostcssAny>>>); export type GenericProcessor = (source: Source, assetPath: string) => Source | Promise<Source>; export interface PostcssProcessorOption { postcss: PostcssProcessor; } export interface GenericProcessorOption { processor: GenericProcessor; } export type PostProcessorOption = PostcssProcessorOption | GenericProcessorOption | (PostcssProcessorOption & GenericProcessorOption); function isPostcssProcessor(processor: PostProcessorOption): processor is PostcssProcessorOption { return !!(<PostcssProcessorOption>processor).postcss; } function isGenericProcessor(processor: PostProcessorOption): processor is GenericProcessorOption { return !!(<GenericProcessorOption>processor).processor; } export interface CssSourceOptions { /** * The name of the chunk to which the asset should belong. * If omitted, the asset won't belong to a any chunk. */ chunk: string | undefined; /** the source path to the css asset. */ source: string | string[]; /** * Post-process the concatenated file with the specified postcss plugins. */ // TODO: enable // postProcess?: PostProcessorOption; } export interface ConcatenationOptions { /** * A list of assets to be concatenated. */ sources: Array<string>; /** * When true, the files that are concatenated are left in the build. * Defaults to false. */ preserveSourceFiles?: boolean; /** * Post-process the concatenated file with the specified postcss plugins. * * If postcss plugins are provided in conjunction with a generic processor * the postcss plugins will be ran first. */ postProcess?: PostProcessorOption; } /** * Options for managing CSS assets without javascript imports. */ export interface CssAssetsOptions { /** Maps css files from a source location to a webpack asset location. */ cssFiles: ObjectDictionary<string | CssSourceOptions>; /** * Maps several webpack assets to a new concatenated asset and manages their * sourcemaps. The concatenated asset will belong to all the chunks to which * the assets belonged. */ concat: ObjectDictionary<string[] | ConcatenationOptions>; /** * When true, any source maps related to the assets are written out as * additional files or inline depending on the value of `inlineSourceMaps`. */ emitSourceMaps: boolean; // defaults to true /** * Whether source maps should be included in the css file itself. This * should only be used in development. */ inlineSourceMaps: boolean; // defaults to false } interface SourceAndMap { source: string; map?: RawSourceMap; } export class CssAssets { options: CssAssetsOptions; constructor(options: Partial<CssAssetsOptions>) { let defaultOpts: CssAssetsOptions = { cssFiles: {}, concat: {}, emitSourceMaps: true, inlineSourceMaps: false }; this.options = Object.assign(defaultOpts, options); } apply(compiler: WebpackCompiler) { // install assets // This puts assets into the compilation results but they won't be part of // any chunk. the cssFiles option is an object where the keys are // the asset to be added into the compilation results. The value // can be a path relative to the webpack project root or an absolute path. // TODO: get the watcher to watch these files on disk // TODO: Use loaders to get these files into the assets -- which may help with the watching. compiler.plugin("emit", (compilation, cb) => { debug("emitting assets"); let assetPaths = Object.keys(this.options.cssFiles); async.forEach(assetPaths, (assetPath, outputCallback) => { let asset = this.options.cssFiles[assetPath]; let sourcePath: string | string[], chunkName: string | undefined = undefined; if (typeof asset === "string" || Array.isArray(asset)) { sourcePath = asset; } else { sourcePath = asset.source; chunkName = asset.chunk; } let chunks: WebpackAny[] = compilation.chunks; let chunk: WebpackAny | undefined = chunkName && chunks.find(c => c.name === chunkName); if (chunkName && !chunk) { throw new Error(`No chunk named ${chunkName} found.`); } const handleSource = (err: Error | undefined, source?: Source) => { if (err) { outputCallback(err); } else { compilation.assets[assetPath] = source; if (chunk) { chunk.files.push(assetPath); } outputCallback(); } }; if (Array.isArray(sourcePath)) { const sourcePaths = sourcePath.map(sourcePath => path.resolve(compiler.options.context!, sourcePath)); assetFilesAsSource(sourcePaths, handleSource); } else { assetFileAsSource(path.resolve(compiler.options.context!, sourcePath), handleSource); } }, cb); }); // Concatenation // The concat option is an object where the keys are the // concatenated asset path and the value is an array of // strings of assets that should be in the asset. // TODO: maybe some glob or regex support compiler.plugin("emit", (compilation, cb) => { debug("concatenating assets"); if (!this.options.concat) return; let concatFiles = Object.keys(this.options.concat); let postProcessResults = new Array<Promise<void>>(); for (let concatFile of concatFiles) { let concatSource = new ConcatSource(); let concatenation = this.options.concat[concatFile]; let inputFiles = Array.isArray(concatenation) ? concatenation : concatenation.sources; let concatenationOptions = Array.isArray(concatenation) ? {sources: concatenation} : concatenation; let missingFiles = inputFiles.filter(f => (!compilation.assets[f])); let chunks = new Set<WebpackAny>(); if (missingFiles.length === 0) { for (let inputFile of inputFiles) { let asset = compilation.assets[inputFile]; concatSource.add(asset); let chunksWithInputAsset = compilation.chunks.filter((chunk: WebpackAny) => (<Array<string>>chunk.files).indexOf(inputFile) >= 0); chunksWithInputAsset.forEach((chunk: WebpackAny) => { chunks.add(chunk); let files: string[] = chunk.files; chunk.files = files.filter(file => file !== inputFile); }); if (!concatenationOptions.preserveSourceFiles) { delete compilation.assets[inputFile]; } } if (concatenationOptions.postProcess) { postProcessResults.push(postProcess(concatenationOptions.postProcess, concatSource, concatFile).then(source => { compilation.assets[concatFile] = source; })); } else { compilation.assets[concatFile] = concatSource; } } for (let chunk of chunks) { let files: Array<string> = chunk.files; if (files.indexOf(concatFile) >= 0) continue; files.push(concatFile); } } if (postProcessResults.length > 0) { Promise.all(postProcessResults).then(() => { cb(); }, error => { cb(error); }); } else { cb(); } }); // sourcemap output for css files // Emit all css files with sourcemaps when the `emitSourceMaps` option // is set to true (default). By default source maps are generated as a // separate file but they can be inline by setting `inlineSourceMaps` to // true (false by default) compiler.plugin("emit", (compilation, cb) => { if (!this.options.emitSourceMaps) { debug("not adding sourcemaps"); cb(); return; } debug("adding sourcemaps"); let assetPaths = Object.keys(compilation.assets).filter(p => /\.css$/.test(p)); assetPaths.forEach(assetPath => { let asset = compilation.assets[assetPath]; let {source, map} = sourceAndMap(asset); if (map) { let comment; if (this.options.inlineSourceMaps) { comment = convertSourceMap.fromObject(map).toComment({ multiline: true }); } else { let mapPath = assetPath + ".map"; comment = `/*# sourceMappingURL=${path.basename(mapPath)} */`; compilation.assets[mapPath] = new RawSource(JSON.stringify(map)); } compilation.assets[assetPath] = new RawSource(source + "\n" + comment); } }); cb(); }); } } function assetAsSource(contents: string, filename: string): Source { let sourcemap: convertSourceMap.SourceMapConverter | undefined; if (/sourceMappingURL/.test(contents)) { sourcemap = convertSourceMap.fromSource(contents) || convertSourceMap.fromMapFileComment(contents, path.dirname(filename)); } if (sourcemap) { let sm: RawSourceMap = sourcemap.toObject(); contents = convertSourceMap.removeComments(contents); contents = convertSourceMap.removeMapFileComments(contents); return new SourceMapSource(contents, filename, adaptToLegacySourceMap(sm)); } else { return new RawSource(contents); } } function assetFilesAsSource(filenames: string[], callback: (err: Error | undefined, source?: ConcatSource) => void) { let assetSource = new ConcatSource(); let assetFiles = filenames.slice(); let eachAssetFile = (err?: Error) => { if (err) { callback(err); } else { const nextAssetFile = assetFiles.shift(); if (nextAssetFile) { processAsset(nextAssetFile, eachAssetFile); } else { callback(undefined, assetSource); } } }; const firstAssetFile = assetFiles.shift(); if (firstAssetFile) { processAsset(firstAssetFile, eachAssetFile); } else { callback(new Error("No asset files provided.")); } function processAsset(assetPath: string, assetCallback: (err?: Error) => void) { fs.readFile(assetPath, "utf-8", (err, data) => { if (err) { assetCallback(err); } else { assetSource.add(assetAsSource(data, assetPath)); assetCallback(); } }); } } function assetFileAsSource(sourcePath: string, callback: (err: Error | undefined, source?: Source) => void) { fs.readFile(sourcePath, "utf-8", (err, contents) => { if (err) { callback(err); } else { try { callback(undefined, assetAsSource(contents, sourcePath)); } catch (e) { callback(e); } } }); } function sourceAndMap(asset: Source): SourceAndMap { // sourceAndMap is supposedly more efficient when implemented. if (asset.sourceAndMap) { let {source, map} = asset.sourceAndMap(); return {source, map: adaptFromLegacySourceMap(map)}; } else { let source = asset.source(); let map: RawSourceMap | undefined = undefined; if (asset.map) { map = asset.map(); } return { source, map }; } } function makePostcssProcessor ( plugins: PostcssProcessor, ): GenericProcessor { return (asset: Source, assetPath: string) => { let { source, map } = sourceAndMap(asset); let pluginsPromise: Promise<Array<postcss.Plugin<PostcssAny>>>; if (typeof plugins === "function") { pluginsPromise = Promise.resolve(plugins(assetPath)); } else { if (plugins.length > 0) { pluginsPromise = Promise.resolve(plugins); } else { return Promise.resolve(asset); } } return pluginsPromise.then(plugins => { let processor = postcss(plugins); let result = processor.process(source, { to: assetPath, map: { prev: map, inline: false, annotation: false }, }); return result.then((result) => { return new SourceMapSource(result.css, assetPath, result.map.toJSON(), source, map && adaptToLegacySourceMap(map)); }); }); }; } function process(processor: GenericProcessor, asset: Source, assetPath: string) { return Promise.resolve(processor(asset, assetPath)); } function postProcess(option: PostProcessorOption, asset: Source, assetPath: string): Promise<Source> { let promise: Promise<Source>; if (isPostcssProcessor(option)) { promise = process(makePostcssProcessor(option.postcss), asset, assetPath); } else { promise = Promise.resolve(asset); } if (isGenericProcessor(option)) { promise = promise.then(asset => { return process(option.processor, asset, assetPath); }); } return promise; }
the_stack
import { Api, CalendarItem, Classmate, CookieManager, EtjanstChild, Fetch, Fetcher, FetcherOptions, LoginStatusChecker, MenuItem, NewsItem, Notification, ScheduleItem, SchoolContact, Skola24Child, Teacher, TimetableEntry, toMarkdown, URLSearchParams, User, wrap, } from '@skolplattformen/api' import { EventEmitter } from 'events' import { decode } from 'he' import { DateTime, FixedOffsetZone } from 'luxon' import * as html from 'node-html-parser' import { fakeFetcher } from './fake/fakeFetcher' import { checkStatus, DummyStatusChecker } from './loginStatus' import { extractMvghostRequestBody, parseCalendarItem } from './parse/parsers' import { beginBankIdUrl, beginLoginUrl, calendarEventUrl, calendarsUrl, currentUserUrl, fullImageUrl, hjarntorgetEventsUrl, hjarntorgetUrl, infoSetReadUrl, infoUrl, initBankIdUrl, lessonsUrl, membersWithRoleUrl, mvghostUrl, myChildrenUrl, rolesInEventUrl, shibbolethLoginUrl, shibbolethLoginUrlBase, verifyUrlBase, wallMessagesUrl, } from './routes' import parse from '@skolplattformen/curriculum' function getDateOfISOWeek(week: number, year: number) { const simple = new Date(year, 0, 1 + (week - 1) * 7) const dow = simple.getDay() const isoWeekStart = simple if (dow <= 4) isoWeekStart.setDate(simple.getDate() - simple.getDay() + 1) else isoWeekStart.setDate(simple.getDate() + 8 - simple.getDay()) return isoWeekStart } export class ApiHjarntorget extends EventEmitter implements Api { private fetch: Fetcher private realFetcher: Fetcher private personalNumber?: string private cookieManager: CookieManager public isLoggedIn = false private _isFake = false public set isFake(fake: boolean) { this._isFake = fake if (this._isFake) { this.fetch = fakeFetcher } else { this.fetch = this.realFetcher } } public get isFake() { return this._isFake } constructor( fetch: Fetch, cookieManager: CookieManager, options?: FetcherOptions ) { super() this.fetch = wrap(fetch, options) this.realFetcher = this.fetch this.cookieManager = cookieManager } public replaceFetcher(fetcher: Fetcher) { this.fetch = fetcher } async getSchedule( child: EtjanstChild, from: DateTime, to: DateTime ): Promise<(CalendarItem & ScheduleItem)[]> { const lessonParams = { forUser: child.id, startDateIso: from.toISODate(), endDateIso: to.toISODate(), } const lessonsResponse = await this.fetch( `lessons-${lessonParams.forUser}`, lessonsUrl(lessonParams) ) const lessonsResponseJson: any[] = await lessonsResponse.json() return lessonsResponseJson.map((l) => { const start = DateTime.fromMillis(l.startDate.ts, { zone: FixedOffsetZone.instance(l.startDate.timezoneOffsetMinutes), }) const end = DateTime.fromMillis(l.endDate.ts, { zone: FixedOffsetZone.instance(l.endDate.timezoneOffsetMinutes), }) return { id: l.id, title: l.title, description: l.note, location: l.location, startDate: start.toISO(), endDate: end.toISO(), oneDayEvent: false, allDayEvent: false, } }) } getPersonalNumber(): string | undefined { return this.personalNumber } public async getSessionHeaders(url: string): Promise<{ [index: string]: string }> { const cookie = await this.cookieManager.getCookieString(url) return { cookie, } } async setSessionCookie(sessionCookie: string): Promise<void> { this.cookieManager.setCookieString(sessionCookie, hjarntorgetUrl) const user = await this.getUser() if (!user.isAuthenticated) { throw new Error('Session cookie is expired') } this.isLoggedIn = true this.emit('login') } async getUser(): Promise<User> { console.log('fetching user') const currentUserResponse = await this.fetch('current-user', currentUserUrl) if (currentUserResponse.status !== 200) { return { isAuthenticated: false } } const retrivedUser = await currentUserResponse.json() return { ...retrivedUser, isAuthenticated: true } } async getChildren(): Promise<(Skola24Child & EtjanstChild)[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } console.log('fetching children') const myChildrenResponse = await this.fetch('my-children', myChildrenUrl) const myChildrenResponseJson: any[] = await myChildrenResponse.json() return myChildrenResponseJson.map( (c) => ({ id: c.id, sdsId: c.id, personGuid: c.id, firstName: c.firstName, lastName: c.lastName, name: `${c.firstName} ${c.lastName}`, } as Skola24Child & EtjanstChild) ) } async getCalendar(child: EtjanstChild): Promise<CalendarItem[]> { const childEventsAndMembers = await this.getChildEventsWithAssociatedMembers(child) // This fetches the calendars search page on Hjärntorget. // It is used (at least at one school) for homework schedule // The Id for the "event" that the calendar belongs to is not the same as the ones // fetched using the API... So we match them by name :/ const calendarsResponse = await this.fetch('calendars', calendarsUrl) const calendarsResponseText = await calendarsResponse.text() const calendarsDoc = html.parse(decode(calendarsResponseText)) const calendarCheckboxes = Array.from( calendarsDoc.querySelectorAll('.calendarPageContainer input.checkbox') ) let calendarItems: CalendarItem[] = [] for (let i = 0; i < calendarCheckboxes.length; i++) { const calendarId = calendarCheckboxes[i].getAttribute('value') || '' const today = DateTime.fromJSDate(new Date()) const start = today.toISODate() const end = today.plus({ days: 30 }).toISODate() const calendarResponse = await this.fetch( `calendar-${calendarId}`, calendarEventUrl(calendarId, start, end) ) const calendarResponseText = await calendarResponse.text() const calendarDoc = html.parse(decode(calendarResponseText)) const calendarRows = Array.from( calendarDoc.querySelectorAll('.default-table tr') ) if (!calendarRows.length) { continue } calendarRows.shift() const eventName = calendarRows.shift()?.textContent if (childEventsAndMembers.some((e) => e.name === eventName)) { const items: CalendarItem[] = calendarRows.map(parseCalendarItem) calendarItems = calendarItems.concat(items) } } return calendarItems } // eslint-disable-next-line @typescript-eslint/no-unused-vars getClassmates(_child: EtjanstChild): Promise<Classmate[]> { // TODO: We could get this from the events a child is associated with... if (!this.isLoggedIn) { throw new Error('Not logged in...') } return Promise.resolve([]) } public async getTeachers(child: EtjanstChild): Promise<Teacher[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } return Promise.resolve([]) } public async getSchoolContacts(child: EtjanstChild): Promise<SchoolContact[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } return Promise.resolve([]) } // eslint-disable-next-line @typescript-eslint/no-unused-vars async getNews(_child: EtjanstChild): Promise<NewsItem[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } const children = await this.getChildren() const eventsAndMembersForChildren = await this.getEventsWithAssociatedMembersForChildren(children) const membersInChildensEvents = eventsAndMembersForChildren.reduce( (acc, e) => acc.concat(e.eventMembers), [] as any[] ) const wallMessagesResponse = await this.fetch( 'wall-events', wallMessagesUrl ) const wallMessagesResponseJson: any[] = await wallMessagesResponse.json() const nonChildSpecificMessages = wallMessagesResponseJson .filter((message) => // Ignore "Alarm" messages from the calendar message.creator.id !== '__system$virtual$calendar__' && // Only include messages that can not reliably be associated with one of the children !membersInChildensEvents.some((member) => member.id === message.creator.id) ) .map(message => { const createdDate = new Date(message.created.ts) const body = message.body as string const trimmedBody = body.trim() const firstNewline = trimmedBody.indexOf('\n') const title = trimmedBody.substring(0, firstNewline).trim() || message.title const intro = trimmedBody.substring(firstNewline).trim() return { id: message.id, author: message.creator && `${message.creator.firstName} ${message.creator.lastName}`, header: title, intro: intro, body: body, published: createdDate.toISOString(), modified: createdDate.toISOString(), fullImageUrl: message.creator && fullImageUrl(message.creator.imagePath), timestamp: message.created.ts, } }) const infoResponse = await this.fetch('info', infoUrl) const infoResponseJson: any[] = await infoResponse.json() // TODO: Filter out read messages? const officialInfoMessages = infoResponseJson.map((i) => { const body = html.parse(decode(i.body || '')) const bodyText = toMarkdown(i.body) const introText = body.innerText || '' const publishedDate = new Date(i.created.ts) return { id: i.id, author: i.creator && `${i.creator.firstName} ${i.creator.lastName}`, header: i.title, intro: introText, body: bodyText, published: publishedDate.toISOString(), modified: publishedDate.toISOString(), fullImageUrl: i.creator && fullImageUrl(i.creator.imagePath), timestamp: i.created.ts, } }) const newsMessages = officialInfoMessages.concat(nonChildSpecificMessages) newsMessages.sort((a,b) => b.timestamp - a.timestamp) return newsMessages } async getNewsDetails(_child: EtjanstChild, item: NewsItem): Promise<any> { return { ...item } } // eslint-disable-next-line @typescript-eslint/no-unused-vars getMenu(_child: EtjanstChild): Promise<MenuItem[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } // Have not found this available on hjärntorget. Perhaps do a mapping to https://www.skolmaten.se/ ? return Promise.resolve([]) } async getChildEventsWithAssociatedMembers(child: EtjanstChild) { return this.getEventsWithAssociatedMembersForChildren([child]) } async getEventsWithAssociatedMembersForChildren(children: EtjanstChild[]) { const hjarntorgetEventsResponse = await this.fetch( 'events', hjarntorgetEventsUrl ) const hjarntorgetEventsResponseJson: any[] = await hjarntorgetEventsResponse.json() const membersInEvents = await Promise.all( hjarntorgetEventsResponseJson .filter((e) => e.state === 'ONGOING') .map(async (e) => { const eventId = e.id as number const rolesInEvenResponse = await this.fetch( `roles-in-event-${eventId}`, rolesInEventUrl(eventId) ) const rolesInEvenResponseJson: any[] = await rolesInEvenResponse.json() const eventMembers = await Promise.all( rolesInEvenResponseJson.map(async (r) => { const roleId = r.id const membersWithRoleResponse = await this.fetch( `event-role-members-${eventId}-${roleId}`, membersWithRoleUrl(eventId, roleId) ) const membersWithRoleResponseJson: any[] = await membersWithRoleResponse.json() return membersWithRoleResponseJson }) ) return { eventId, name: e.name as string, eventMembers: ([] as any[]).concat(...eventMembers), } }) ) return membersInEvents.filter((e) => e.eventMembers.find((p) => children.some(c => c.id === p.id)) ) } async getNotifications(child: EtjanstChild): Promise<Notification[]> { const childEventsAndMembers = await this.getChildEventsWithAssociatedMembers(child) const membersInChildsEvents = childEventsAndMembers.reduce( (acc, e) => acc.concat(e.eventMembers), [] as any[] ) const wallMessagesResponse = await this.fetch( 'wall-events', wallMessagesUrl ) const wallMessagesResponseJson: any[] = await wallMessagesResponse.json() return wallMessagesResponseJson .filter((message) => membersInChildsEvents.find((member) => member.id === message.creator.id) ) .map((message) => { const createdDate = new Date(message.created.ts) return { id: message.id, sender: message.creator && `${message.creator.firstName} ${message.creator.lastName}`, dateCreated: createdDate.toISOString(), message: message.body, url: message.url, category: message.title, type: message.type, dateModified: createdDate.toISOString(), } }) } async getSkola24Children(): Promise<Skola24Child[]> { if (!this.isLoggedIn) { throw new Error('Not logged in...') } return [] } // eslint-disable-next-line @typescript-eslint/no-unused-vars async getTimetable( child: Skola24Child, week: number, year: number, _lang: string ): Promise<TimetableEntry[]> { const startDate = DateTime.fromJSDate(getDateOfISOWeek(week, year)) const endDate = startDate.plus({ days: 7 }) const lessonParams = { forUser: child.personGuid!, // This is a bit of a hack due to how we map things... startDateIso: startDate.toISODate(), endDateIso: endDate.toISODate(), } const lessonsResponse = await this.fetch( `lessons-${lessonParams.forUser}`, lessonsUrl(lessonParams) ) const lessonsResponseJson: any[] = await lessonsResponse.json() return lessonsResponseJson.map((l) => { const start = DateTime.fromMillis(l.startDate.ts, { zone: FixedOffsetZone.instance(l.startDate.timezoneOffsetMinutes), }) const end = DateTime.fromMillis(l.endDate.ts, { zone: FixedOffsetZone.instance(l.endDate.timezoneOffsetMinutes), }) return { ...parse(l.title, _lang), id: l.id, teacher: l.bookedTeacherNames && l.bookedTeacherNames[0], location: l.location, timeStart: start.toISOTime().substring(0, 5), timeEnd: end.toISOTime().substring(0, 5), dayOfWeek: start.toJSDate().getDay(), blockName: l.title, dateStart: start.toISODate(), dateEnd: end.toISODate(), } as TimetableEntry }) } async logout(): Promise<void> { this.isLoggedIn = false this.personalNumber = undefined this.cookieManager.clearAll() this.emit('logout') } public async login(personalNumber?: string): Promise<LoginStatusChecker> { // short circut the bank-id login if in fake mode if (personalNumber !== undefined && personalNumber.endsWith('1212121212')) return this.fakeMode() this.isFake = false console.log('initiating login to hjarntorget') const beginLoginRedirectResponse = await this.fetch( 'begin-login', beginLoginUrl, { redirect: 'follow', } ) if((beginLoginRedirectResponse as any).url.endsWith("startPage.do")) { // already logged in! const emitter = new DummyStatusChecker() setTimeout(() => { this.isLoggedIn = true emitter.emit('OK') this.emit('login') }, 50) return emitter as LoginStatusChecker; } console.log('prepping??? shibboleth') const shibbolethLoginResponse = await this.fetch( 'init-shibboleth-login', shibbolethLoginUrl( shibbolethLoginUrlBase((beginLoginRedirectResponse as any).url) ), { redirect: 'follow', } ) const shibbolethRedirectUrl = (shibbolethLoginResponse as any).url console.log('initiating bankid...') const initBankIdResponse = await this.fetch( 'init-bankId', initBankIdUrl(shibbolethRedirectUrl), { redirect: 'follow', } ) const initBankIdResponseText = await initBankIdResponse.text() const mvghostRequestBody = extractMvghostRequestBody(initBankIdResponseText) console.log('picking auth server???') const mvghostResponse = await this.fetch('pick-mvghost', mvghostUrl, { redirect: 'follow', method: 'POST', body: mvghostRequestBody, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) console.log('start bankid sign in') // We may get redirected to some other subdomain i.e. not 'm00-mg-local': // https://mNN-mg-local.idp.funktionstjanster.se/mg-local/auth/ccp11/grp/other const ssnBody = new URLSearchParams({ ssn: personalNumber }).toString() const beginBankIdResponse = await this.fetch( 'start-bankId', beginBankIdUrl((mvghostResponse as any).url), { redirect: 'follow', method: 'POST', body: ssnBody, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, } ) console.log('start polling') const statusChecker = checkStatus( this.fetch, verifyUrlBase((beginBankIdResponse as any).url) ) statusChecker.on('OK', async () => { // setting these similar to how the sthlm api does it // not sure if it is needed or if the cookies are enough for fetching all info... this.isLoggedIn = true this.personalNumber = personalNumber this.emit('login') }) statusChecker.on('ERROR', () => { this.personalNumber = undefined }) return statusChecker } private async fakeMode(): Promise<LoginStatusChecker> { this.isFake = true setTimeout(() => { this.isLoggedIn = true this.emit('login') }, 50) const emitter: any = new EventEmitter() emitter.token = 'fake' return emitter } }
the_stack
// 公共部分 declare namespace my { // #region 基本参数 interface DataResponse { /** 回调函数返回的内容 */ data: any; /** 开发者服务器返回的 HTTP 状态码 */ status: number; /** 开发者服务器返回的 HTTP Response Header */ headers: object; } interface ErrMsgResponse { /** 成功:ok,错误:详细信息 */ errMsg: "ok" | string; } interface TempFileResponse { /** 文件的临时路径 */ apFilePath: string; } interface BaseOptions<R = any, E = any> { /** 接口调用成功的回调函数 */ success?(res: R): void; /** 接口调用失败的回调函数 */ fail?(res: E): void; /** 接口调用结束的回调函数(调用成功、失败都会执行) */ complete?(res: any): void; } interface ErrCodeResponse { errCode: number; } // #endregion } // 界面 declare namespace my { //#region 导航栏 https://docs.alipay.com/mini/api/ui-navigate interface NavigateToOptions extends BaseOptions { /** 需要跳转的应用内页面的路径 */ url: string; } /** * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 * * 注意:为了不让用户在使用小程序时造成困扰, * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 */ function navigateTo(options: NavigateToOptions): void; interface RedirectToOptions extends BaseOptions { /** 需要跳转的应用内页面的路径 */ url: string; } /** * 关闭当前页面,跳转到应用内的某个页面。 */ function redirectTo(options: RedirectToOptions): void; interface NavigateBackOptions extends BaseOptions { /** 返回的页面数,如果 delta 大于现有打开的页面数,则返回到首页 */ delta: number; } /** * 关闭当前页面,返回上一级或多级页面。可通过 getCurrentPages 获取当前的页面栈信息,决定需要返回几层。 */ function navigateBack(options?: NavigateBackOptions): void; interface ReLaunchOptions extends BaseOptions { /** * 需要跳转的应用内页面路径 , 路径后可以带参数。 * 参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔 * 如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 */ url: string; } /** * 关闭所有页面,打开到应用内的某个页面。 */ function reLaunch(options?: ReLaunchOptions): void; interface SetNavigationBarOptions extends BaseOptions { /** 页面标题 */ title: string; /** 图片连接地址,必须是https,请使用3x高清图片。若设置了image则title参数失效 */ image: string; /** 导航栏背景色,支持十六进制颜色值 */ backgroundColor: string; /** 导航栏底部边框颜色,支持十六进制颜色值。若设置了 backgroundColor,则borderBottomColor 不会生效,默认会和 backgroundColor 颜色一样 */ borderBottomColor: string; /** 是否重置导航栏为支付宝默认配色,默认 false */ reset: boolean; } /** * 动态设置当前页面的标题。 */ function setNavigationBar(options: Partial<SetNavigationBarOptions>): void; /** * 显示导航栏 loading */ function showNavigationBarLoading(): void; /** 隐藏导航栏 loading。 */ function hideNavigationBarLoading(): void; //#endregion //#region TabBar https://docs.alipay.com/mini/api/ui-tabbar interface SwitchTabOptions extends BaseOptions { /** * 需要跳转的 tabBar 页面的路径 * (需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数 */ url: string; } /** * 跳转到指定 tabBar 页面,并关闭其他所有非 tabBar 页面 */ function switchTab(options: SwitchTabOptions): void; //#endregion //#region 交互反馈 https://docs.alipay.com/mini/api/ui-feedback interface AlertOptions extends BaseOptions { /** alert框的标题 */ title: string; /** alert框的内容 */ content: string; /** 按钮文字,默认确定 */ buttonText: string; } function alert(options: Partial<AlertOptions>): void; interface ConfirmOptions extends BaseOptions { /** confirm框的标题 */ title: string; /** confirm框的内容 */ content: string; /** 确认按钮文字,默认‘确定’ */ confirmButtonText: string; /** 确认按钮文字,默认‘取消’ */ cancelButtonText: string; success(result: { confirm: boolean; }): void; } function confirm(options: Partial<ConfirmOptions>): void; interface PromptOptions extends BaseOptions { /** prompt框标题 */ title?: string; /** prompt框文本,默认‘请输入内容’ */ message?: string; /** 输入框内的提示文案 */ placeholder?: string; /** message对齐方式,可用枚举left/center/right,iOS ‘center’, android ‘left’ */ align?: 'left' | 'center' | 'right' | string; /** 确认按钮文字,默认‘确定’ */ okButtonText: string; /** 确认按钮文字,默认‘取消’ */ cancelButtonText: string; success(result: { ok: boolean; inputValue: string; }): void; } function prompt(options: PromptOptions): void; interface ToastOptions extends BaseOptions { /** * 文字内容 */ content: string; /** toast 类型,展示相应图标,默认 none,支持 success / fail / exception / none’。其中 exception 类型必须传文字信息 */ type?: 'none' | 'success' | 'fail' | 'exception' | string; /** * 显示时长,单位为 ms,默认 2000 */ duration?: number; } /** * 显示消息提示框 */ function showToast(options: Partial<ToastOptions>): void; function hideToast(): void; interface LoadingOptions extends BaseOptions { /** * loading的文字内容 */ content?: string; /** * 延迟显示,单位 ms,默认 0。如果在此时间之前调用了 my.hideLoading 则不会显示 */ delay?: number; } /** * 显示加载提示 */ function showLoading(options?: LoadingOptions): void; interface HideLoadingOptions { /** * 体指当前page实例,某些场景下,需要指明在哪个page执行hideLoading。 */ page: any; } /** * 隐藏消息提示框 */ function hideLoading(options?: HideLoadingOptions): void; interface Badge { /** 需要飘红的选项的索引,从0开始 */ index: number; /** * 飘红类型,支持 none(无红点)/ point(纯红点) / num(数字红点)/ text(文案红点)/ more(...) * */ type: 'none' | 'point' | 'num' | 'text' | 'more' | string; /** * 自定义飘红文案: * * 1、type为none/point/more时本文案可不填 * 2、type为num时本文案为小数或<=0均不显示, >100 显示"..." */ text: string; } interface ActionSheetOptions extends BaseOptions { /** 菜单标题 */ title?: string; /** * 菜单按钮文字数组 */ items: string[]; /** * 取消按钮文案。默认为‘取消’。注:Android平台此字段无效,不会显示取消按钮。 */ cancelButtonText?: string; /** * (iOS特殊处理)指定按钮的索引号,从0开始,使用场景:需要删除或清除数据等类似场景,默认红色 */ destructiveBtnIndex?: number; /** * 需飘红选项的数组,数组内部对象字段见下表 */ badges?: Array<Partial<Badge>>; /** * 接口调用成功的回调函数 */ success?(res: { /** * 用户点击的按钮,从上到下的顺序,从0开始 */ index: number; }): void; } /** * 显示操作菜单 */ function showActionSheet(options: ActionSheetOptions): void; //#endregion //#region 下拉刷新 https://docs.alipay.com/mini/api/ui-pulldown /** * Page 实现的接口对象 */ interface PageOptions { /** * 下拉刷新 * 在 Page 中定义 onPullDownRefresh 处理函数,监听该页面用户下拉刷新事件。 * 需要在页面对应的 .json 配置文件中配置 "pullRefresh": true 选项,才能开启下拉刷新事件。 * 当处理完数据刷新后,调用 my.stopPullDownRefresh 可以停止当前页面的下拉刷新。 */ onPullDownRefresh?(this: Page): void; } /** * 停止当前页面的下拉刷新。 */ function stopPullDownRefresh(): void; //#endregion //#region 联系人 https://docs.alipay.com/mini/api/ui-contact interface ChoosePhoneContactOptions extends BaseOptions { success(result: { name: string; // 选中的联系人姓名 mobile: string; // 选中的联系人手机号 }): void; /** * 10 没有权限 * 11 用户取消操作(或设备未授权使用通讯录) */ fail?(error: 10 | 11): void; } /** * 选择本地系统通信录中某个联系人的电话。 */ function choosePhoneContact(options: ChoosePhoneContactOptions): void; interface ChooseAlipayContactOptions extends BaseOptions { /** 单次最多选择联系人个数,默认 1,最大 10 */ count: number; success(result: { realName: string; // 账号的真实姓名 mobile: string; // 账号对应的手机号码 email: string; // 账号的邮箱 avatar: string; // 账号的头像链接 userId: string; // 支付宝账号唯一 userId }): void; /** * 10 没有权限 * 11 用户取消操作(或设备未授权使用通讯录) */ fail?(error: 10 | 11): void; } /** * 唤起支付宝通讯录,选择一个或者多个支付宝联系人。 */ function chooseAlipayContact(options: ChooseAlipayContactOptions): void; interface ContactsDic { /** * 支付宝账号唯一 userId */ userId: string; /** * 账号的头像链接 */ avatar: string; /** * 账号对应的手机号码 */ mobile: string; /** * 账号的真实姓名 */ realName: string; /** * 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 */ displayName: string; // 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 } interface ChooseContactOptions extends BaseOptions { /** 选择类型,值为single(单选)或者 multi(多选) */ chooseType: 'single' | 'multi' | string; /** 包含手机通讯录联系人的模式:默认为不包含(none)、或者仅仅包含双向通讯录联系人(known)、或者包含手机通讯录联系人(all) */ includeMobileContactMode?: 'none' | 'known' | 'all' | string; /** 是否包含自己 */ includeMe?: boolean; /** 最大选择人数,仅 chooseType 为 multi 时才有效 */ multiChooseMax?: number; /** 多选达到上限的文案,仅 chooseType 为 multi 时才有效 */ multiChooseMaxTips?: string; success(result: { contactsDicArray: ContactsDic[]; }): void; } /** * 唤起选人组件,默认只包含支付宝联系人,可以通过修改参数包含手机通讯录联系人或者双向通讯录联系人。 */ function chooseContact(options: ChooseContactOptions): void; //#endregion //#region 选择城市 https://docs.alipay.com/mini/api/ui-city interface City { city: string; // 城市名 adCode: string; // 行政区划代码 spell?: string; // 城市名对应拼音拼写,方便用户搜索 } interface ChooseCityOptions extends BaseOptions { showLocatedCity: boolean; // 是否显示当前定位城市,默认 false showHotCities: boolean; // 是否显示热门城市,默认 true cities: City[]; // 自定义城市列表,列表内对象字段见下表 hotCities: City[]; // 自定义热门城市列表,列表内对象字段见下表 success(result: { city: string; adCode: string; }): void; } /** * 打开城市选择列表 * * 如果用户没有选择任何城市直接点击了返回,将不会触发回调函数。 */ function chooseCity(options: Partial<ChooseCityOptions>): void; //#endregion //#region 选择日期 https://docs.alipay.com/mini/api/ui-date interface DatePickerOptions extends BaseOptions { /** * 返回的日期格式, * 1. yyyy-MM-dd(默认) * 2. HH:mm * 3. yyyy-MM-dd HH:mm * 4. yyyy-MM (最低基础库:1.1.1, 可用 canIUse('datePicker.object.format.yyyy-MM') 判断) * 5. yyyy (最低基础库:1.1.1,可用 canIUse('datePicker.object.format.yyyy') 判断) */ format: 'yyyy-MM-dd' | 'HH:mm' | 'yyyy-MM-dd HH:mm' | 'yyyy-MM' | 'yyyy'; /** 初始选择的日期时间,默认当前时间 */ currentDate: string; /** 最小日期时间 */ startDate: string; /** 最大日期时间 */ endDate: string; success(result: { date: string; }): void; /** 11 用户取消操作 */ fail(error: 11): void; } /** * 打开日期选择列表 */ function datePicker(optiosn: Partial<DatePickerOptions>): void; //#endregion //#region 动画 https://docs.alipay.com/mini/api/ui-animation type TimingFunction = | "linear" | "ease" | "ease-in" | "ease-in-out" | "ease-out" | "step-start" | "step-end"; interface CreateAnimationOptions { /** 动画持续时间,单位ms,默认值 400 */ duration: number; /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ timeFunction: TimingFunction; /** 动画持续时间,单位 ms,默认值 0 */ delay: number; /** 设置transform-origin,默认为"50% 50% 0" */ transformOrigin: string; } interface Animator { actions: AnimationAction[]; } interface AnimationAction { animates: Animate[]; option: AnimationActionOption; } interface AnimationActionOption { transformOrigin: string; transition: AnimationTransition; } interface AnimationTransition { delay: number; duration: number; timingFunction: TimingFunction; } interface Animate { type: string; args: any[]; } /** * 创建动画实例 animation。调用实例的方法来描述动画,最后通过动画实例的export方法将动画数据导出并传递给组件的animation属性。 * * 注意: export 方法每次调用后会清掉之前的动画操作 */ function createAnimation(options: Partial<CreateAnimationOptions>): Animation; /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ interface Animation { /** * 调用动画操作方法后要调用 step() 来表示一组动画完成, * 可以在一组动画中调用任意多个动画方法, * 一组动画中的所有动画会同时开始, * 一组动画完成后才会进行下一组动画。 * @param options 指定当前组动画的配置 */ step(options?: CreateAnimationOptions): void; /** * 导出动画操作 * * 注意: export 方法每次调用后会清掉之前的动画操作 */ export(): Animator; /** 透明度,参数范围 0~1 */ opacity(value: number): Animation; /** 颜色值 */ backgroundColor(color: string): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ width(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ height(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ top(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ left(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ bottom(length: number): Animation; /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ right(length: number): Animation; /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ rotate(deg: number): Animation; /** deg的范围-180~180,在X轴旋转一个deg角度 */ rotateX(deg: number): Animation; /** deg的范围-180~180,在Y轴旋转一个deg角度 */ rotateY(deg: number): Animation; /** deg的范围-180~180,在Z轴旋转一个deg角度 */ rotateZ(deg: number): Animation; /** 同transform-function rotate3d */ rotate3d(x: number, y: number, z: number, deg: number): Animation; /** * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 */ scale(sx: number, sy?: number): Animation; /** 在X轴缩放sx倍数 */ scaleX(sx: number): Animation; /** 在Y轴缩放sy倍数 */ scaleY(sy: number): Animation; /** 在Z轴缩放sy倍数 */ scaleZ(sz: number): Animation; /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ scale3d(sx: number, sy: number, sz: number): Animation; /** * 一个参数时,表示在X轴偏移tx,单位px; * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 */ translate(tx: number, ty?: number): Animation; /** * 在X轴偏移tx,单位px */ translateX(tx: number): Animation; /** * 在Y轴偏移tx,单位px */ translateY(ty: number): Animation; /** * 在Z轴偏移tx,单位px */ translateZ(tz: number): Animation; /** * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px */ translate3d(tx: number, ty: number, tz: number): Animation; /** * 参数范围-180~180; * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 */ skew(ax: number, ay?: number): Animation; /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ skewX(ax: number): Animation; /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ skewY(ay: number): Animation; /** * 同transform-function matrix */ matrix( a: number, b: number, c: number, d: number, tx: number, ty: number ): Animation; /** 同transform-function matrix3d */ matrix3d( a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number ): Animation; } //#endregion //#region 画布 https://docs.alipay.com/mini/api/ui-canvas interface ToTempFilePathOptions extends BaseOptions { x: number; // 画布 x 轴起点,默认为 0 y: number; // 画布 y 轴起点,默认为 0 width: number; // 画布宽度,默认为 canvas 宽度 - x height: number; // 画布高度,默认为 canvas 高度 - y destWidth: number; // 输出的图片宽度,默认为 width destHeight: number; // 输出的图片高度,默认为 height } type Color = string | number[] | number | CanvasAction; interface CanvasAction { /** * 创建一个颜色的渐变点。 * 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 * * @param stop 渐变点位置,值必须在 [0,1] 范围内 * @param color 颜色值 */ addColorStop(stop: number, color: Color): void; } interface TextMetrics { width: number; } interface ConvasContext { font: string; /** * 把当前画布的内容导出生成图片,并返回文件路径。 */ toTempFilePath(options?: Partial<ToTempFilePathOptions>): void; /** * textAlign 是 Canvas 2D API 描述绘制文本时,文本的对齐方式的属性。注意,该对齐是基于 * CanvasRenderingContext2D.fillText 方法的x的值。所以如果 textAlign="center",那么该文本将画在 x-50%*width */ setTextAlign(textAlign: 'left' | 'right' | 'center' | 'start' | 'end'): void; /** * textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。 */ setTextBaseline(textBaseline: 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'): void; /** * 设置填充色。 * * 如果没有设置 fillStyle,则默认颜色为 black。 */ setFillStyle(color: Color): void; /** * 设置边框颜色。 * * 如果没有设置 strokeStyle,则默认颜色为 black。 */ setStrokeStyle(color: Color): void; /** * 设置阴影样式。 * 如果没有设置,offsetX 的默认值为 0, offsetY 的默认值为 0, blur 的默认值为 0,color 的默认值为 black。 * @param offsetX 阴影相对于形状水平方向的偏移 * @param offsetY 阴影相对于形状竖直方向的偏移 * @param blur 0~100 阴影的模糊级别,值越大越模糊 * @param color 阴影颜色 */ setShadow(offsetX: number, offsetY: number, blur: number, color: Color): void; /** * 创建一个线性的渐变色。 * * @param x0 起点 x 坐标 * @param y0 起点 y 坐标 * @param x1 终点 x 坐标 * @param y1 终点 y 坐标 */ createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasAction; /** * 创建一个圆形的渐变色。 * 起点在圆心,终点在圆环。 * 需要使用 addColorStop() 来指定渐变点,至少需要两个。 * @param x 圆心 x 坐标 * @param y 圆心 y 坐标 * @param r 圆半径 * @returns */ createCircularGradient(x: number, y: number, r: number): CanvasAction; /** * 设置线条的宽度。 * @param lineWidth 线条宽度,单位为 px */ setLineWidth(lineWidth: number): void; /** * 设置线条的端点样式。 * * @param lineCap 线条的结束端点样式 */ setLineCap(lineCap: 'round' | 'butt' | 'square'): void; /** * 设置线条的交点样式。 * * @param lineJoin 线条的结束交点样式 */ setLineJoin(lineJoin: 'round' | 'bevel' | 'miter'): void; /** * 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 当 setLineJoin() 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 * * @param miterLimit 最大斜接长度 */ setMiterLimit(miterLimit: number): void; /** * 创建一个矩形。 * * @param x 矩形左上角的 x 坐标 * @param y 矩形左上角的 y 坐标 * @param width 矩形路径宽度 * @param height 矩形路径高度 */ rect(x: number, y: number, width: number, height: number): void; /** * 填充矩形。 * 用 setFillStyle() 设置矩形的填充色,如果没设置则默认是 black。 * @param x 矩形左上角的 x 坐标 * @param y 矩形左上角的 y 坐标 * @param width 矩形路径宽度 * @param height 矩形路径高度 */ fillRect(x: number, y: number, width: number, height: number): void; /** * 画一个矩形(非填充)。 * 用 setFillStroke() 设置矩形线条的颜色,如果没设置默认是 black。 * @param x 矩形左上角的 x 坐标 * @param y 矩形左上角的 y 坐标 * @param width 矩形路径宽度 * @param height 矩形路径高度 */ strokeRect(x: number, y: number, width: number, height: number): void; /** * 清除画布上在该矩形区域内的内容。 * clearRect 并非画一个白色的矩形在地址区域,而是清空,为了有直观感受,可以对 canvas 加了一层背景色。 * @param x 矩形左上角的 x 坐标 * @param y 矩形左上角的 y 坐标 * @param width 矩形路径宽度 * @param height 矩形路径高度 */ clearRect(x: number, y: number, width: number, height: number): void; /** * 对当前路径中的内容进行填充。默认的填充色为黑色。 * */ fill(): void; /** * 画出当前路径的边框。默认 black。 * stroke() 描绘的的路径是从 beginPath() 开始计算,但是不会将 strokeRect() 包含进去 */ stroke(): void; /** * 关闭一个路径 * 关闭路径会连接起点和终点。 * 如果关闭路径后没有调用 fill() 或者 stroke() 并开启了新的路径,那之前的路径将不会被渲染。 */ beginPath(): void; /** * 关闭一个路径 * 关闭路径会连接起点和终点。 * */ closePath(): void; /** * 把路径移动到画布中的指定点,不创建线条。 * 用 stroke() 方法来画线条 * @param x 目标位置 x 坐标 * @param y 目标位置 y 坐标 */ moveTo(x: number, y: number): void; /** * lineTo 方法增加一个新点,然后创建一条从上次指定点到目标点的线。 * 用 stroke() 方法来画线条 * * @param x 目标位置 x 坐标 * @param y 目标位置 y 坐标 */ lineTo(x: number, y: number): void; /** * 画一条弧线。 * 创建一个圆可以用 arc() 方法指定其实弧度为0,终止弧度为 2 * Math.PI。 * * @param x * @param y * @param r * @param sAngle * @param eAngle */ arc(x: number, y: number, r: number, sAngle: number, eAngle: number): void; /** * 创建三次方贝塞尔曲线路径。 * 曲线的起始点为路径中前一个点。 * @param cp1x * @param cp1y * @param cp2x * @param cp2y * @param x * @param y */ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; /** * 将当前创建的路径设置为当前剪切路径。 * */ clip(): void; /** * 创建二次贝塞尔曲线路径。 * 曲线的起始点为路径中前一个点。 * @param cpx 贝塞尔控制点 x 坐标 * @param cpy 贝塞尔控制点 y 坐标 * @param x 结束点 x 坐标 * @param y 结束点 y 坐标 */ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; /** * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。多次调用scale,倍数会相乘。 * * @param scaleWidth 横坐标缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) * @param scaleHeight 纵坐标轴缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) */ scale(scaleWidth: number, scaleHeight: number): void; /** * 以原点为中心,原点可以用 translate方法修改。顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 * * @param rotate 旋转角度,以弧度计(degrees * Math.PI/180;degrees 范围为0~360) */ rotate(rotate: number): void; /** * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 * * @param x 水平坐标平移量 * @param y 竖直坐标平移量 */ translate(x: number, y: number): void; /** * 设置字体大小。 * * @param fontSize 字号 */ setFontSize(fontSize: number): void; /** * 在画布上绘制被填充的文本。 * * @param text 文本 * @param x 绘制文本的左上角 x 坐标 * @param y 绘制文本的左上角 y 坐标 */ fillText(text: string, x: number, y: number): void; /** * 绘制图像,图像保持原始尺寸。 * * @param imageResource 图片资源, 只支持线上 cdn 地址或离线包地址,线上 cdn 需返回头 Access-Control-Allow-Origin: * * @param x 图像左上角 x 坐标 * @param y 图像左上角 y 坐标 * @param width 图像宽度 * @param height 图像高度 */ drawImage(imageResource: string, x: number, y: number, width: number, height: number): void; /** * 设置全局画笔透明度。 * * @param alpha 透明度,0 表示完全透明,1 表示不透明 范围 [0, 1] */ setGlobalAlpha(alpha: number): void; /** * 设置虚线的样式 * * @param segments 一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。 */ setLineDash(segments: number[]): void; /** * 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。 * * @param scaleX 水平缩放 * @param skewX 水平倾斜 * @param skewY 垂直倾斜 * @param scaleY 垂直缩放 * @param translateX 水平移动 * @param translateY 垂直移动 */ transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; /** * 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。 * * @param scaleX 水平缩放 * @param skewX 水平倾斜 * @param skewY 垂直倾斜 * @param scaleY 垂直缩放 * @param translateX 水平移动 * @param translateY 垂直移动 */ setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; /** * 保存当前的绘图上下文。 * */ save(): void; /** * 恢复之前保存的绘图上下文。 */ restore(): void; /** * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 * 绘图上下文需要由 my.createCanvasContext(canvasId) 来创建。 * @param [reserve] 本次绘制是否接着上一次绘制,即 reserve 参数为 false 时则在本次调用 drawCanvas绘制之前 native 层应先清空画布再继续绘制;若 reserver 参数为true 时,则保留当前画布上的内容,本次调用drawCanvas绘制的内容覆盖在上面,默认 false */ draw(reserve?: boolean): void; measureText(text: string): TextMetrics; } /** * 创建 canvas 绘图上下文 * * 该绘图上下文只作用于对应 canvasId 的 <canvas/> */ function createCanvasContext(canvasId: string): ConvasContext; //#endregion //#region 地图 https://docs.alipay.com/mini/api/ui-map interface GetCenterLocationOptions extends BaseOptions { success?(res: { longitude: string; latitude: string; }): void; } interface MapContext extends BaseOptions { /** * 获取当前地图中心的经纬度,返回 gcj02 坐标系的值,可以用于 my.openLocation * * @param options */ getCenterLocation(options: GetCenterLocationOptions): void; /** * 将地图中心移动到当前定位点,需要配合 map 组件的 show-location 使用 */ moveToLocation(): void; } /** * 创建并返回一个 map 上下文对象 mapContext。 * * @param mapId * @returns */ function createMapContext(mapId: string): MapContext; //#endregion //#region 键盘 https://docs.alipay.com/mini/api/ui-hidekeyboard /** * 隐藏键盘 * */ function hideKeyboard(): void; //#endregion //#region 滚动 https://docs.alipay.com/mini/api/scroll interface PageScrollToOptions { scrollTop: number; // 滚动到页面的目标位置,单位 px } /** * 滚动到页面的目标位置 * * @param options */ function pageScrollTo(options: PageScrollToOptions): void; //#endregion //#region 节点查询 https://docs.alipay.com/mini/api/selector-query interface RectArea { /** 节点的左边界坐标 */ left: number; /** 节点的右边界坐标 */ right: number; /** 节点的上边界坐标 */ top: number; /** 节点的下边界坐标 */ bottom: number; /** 节点的宽度 */ width: number; /** 节点的高度 */ height: number; } interface NodesRefRect extends RectArea { /** 节点的ID */ id: string; /** 节点的dataset */ dataset: any; } interface NodeRefOffset { /** 节点的ID */ id: string; /** 节点的dataset */ dataset: any; /** 节点的水平滚动位置 */ scrollLeft: number; /** 节点的竖直滚动位置 */ scrollTop: number; } interface NodesRef { /** * 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位。 * 其功能类似于DOM的getBoundingClientRect。 * 返回值是nodesRef对应的selectorQuery。 * 返回的节点信息中,每个节点的位置用 * left、right、top、bottom、width、height字段描述。 * 如果提供了callback回调函数,在执行selectQuery的exec方法后 * 节点信息会在callback中返回。 */ boundingClientRect<T extends NodesRefRect | NodesRefRect[]>( callback?: (rect: T) => void ): SelectorQuery; /** * 添加节点的滚动位置查询请求,以像素为单位。 * 节点必须是scroll-view或者viewport。 * 返回值是nodesRef对应的selectorQuery。 * 返回的节点信息中,每个节点的滚动位置用scrollLeft、scrollHeight字段描述。 * 如果提供了callback回调函数,在执行selectQuery的exec方法后,节点信息会在callback中返回。 */ scrollOffset(callback?: (rect: NodeRefOffset) => void): SelectorQuery; // /** // * 获取节点的相关信息,需要获取的字段在fields中指定。 // * 返回值是nodesRef对应的selectorQuery。 // */ // fields( // fields: NodeRefFieldsOptions, // callback?: (result: any) => void // ): SelectorQuery; } /** * SelectorQuery对象实例 */ interface SelectorQuery { // /** // * 将选择器的选取范围更改为自定义组件component内 // * (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点 // * @version 1.6.0 // */ // in(component: Component<object, object>): SelectorQuery; /** * 在当前页面下选择第一个匹配选择器selector的节点,返回一个NodesRef对象实例,可以用于获取节点信息。 * selector类似于CSS的选择器,但仅支持下列语法。 * + ID选择器:#the-id * + class选择器(可以连续指定多个):.a-class.another-class * + 子元素选择器:.the-parent > .the-child * + 后代选择器:.the-ancestor .the-descendant * + 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant * + 多选择器的并集:#a-node, .some-other-nodes */ select(selector: string): NodesRef; /** * 在当前页面下选择匹配选择器selector的节点,返回一个NodesRef对象实例。 * 与selectorQuery.selectNode(selector)不同的是,它选择所有匹配选择器的节点。 */ selectAll(selector: string): NodesRef; /** * 选择显示区域,可用于获取显示区域的尺寸、滚动位置等信息 * 返回一个NodesRef对象实例。 */ selectViewport(): NodesRef; /** * 执行所有的请求 * 请求结果按请求次序构成数组,在callback的第一个参数中返回。 */ exec(callback?: (result: any[]) => void): void; } /** * 获取一个节点查询对象 SelectorQuery。 * * @param page 可以指定 page 属性,默认为当前页面 * @returns */ function createSelectorQuery(page?: any): SelectorQuery; //#endregion //#region 级联选择 https://docs.alipay.com/mini/api/ewdxl3 interface MultiLevelSelectItem { name: string; subList?: MultiLevelSelectItem[]; } interface MultiLevelSelectOptions extends BaseOptions { title?: string; // 标题 list?: MultiLevelSelectItem[]; // 选择数据列表 name?: string; // 条目名称 subList?: MultiLevelSelectItem[]; // 子条目列表 success?(res: { success: boolean; // 是否选择完成,取消返回false result: MultiLevelSelectItem[]; // 选择的结果,如[{“name”:”杭州市”},{“name”:”上城区”},{“name”:”古翠街道”}] }): void; } function multiLevelSelect(options?: MultiLevelSelectOptions): void; //#endregion } // 开放接口 declare namespace my { //#region 用户授权 https://docs.alipay.com/mini/api/openapi-authorize interface GetAuthCodeOptions extends BaseOptions { scopes?: string | string[]; // 授权类型,默认 auth_base。支持 auth_base(静默授权)/ auth_user(主动授权) / auth_zhima(芝麻信用) success?(res: { authCode: string; // 授权码 authErrorScope: { [scope: string]: number; }; // 失败的授权类型,key是授权失败的 scope,value 是对应的错误码 authSucessScope: string[]; // 成功的授权 scope }): void; } /** * 获取授权码。 * 详细用户授权接入参考 [指引](https://docs.alipay.com/mini/introduce/auth)。 */ function getAuthCode(options: GetAuthCodeOptions): void; //#endregion //#region 客户端获取会员信息 https://docs.alipay.com/mini/api/userinfo interface GetAuthUserInfoOptions extends BaseOptions { success?(res: { nickName: string; // 用户昵称 avatar: string; // 用户头像链接 }): void; } /** * 客户端获取会员信息 * 获取会员信息首先需要获取用户授权,详细会员信息获取参考[指引](https://docs.alipay.com/mini/introduce/auth),采用 jsapi 调用的方式。 */ function getAuthUserInfo(options: GetAuthUserInfoOptions): void; //#endregion //#region 小程序唤起支付 https://docs.alipay.com/mini/api/openapi-pay interface TradePayOptions extends BaseOptions { tradeNO?: string; // 接入小程序支付时传入此参数。此参数为支付宝交易号 success?(res: { // resultCode | 描述 // -----------|------ // 9000 | 订单支付成功 // 8000 | 正在处理中 // 4000 | 订单支付失败 // 6001 | 用户中途取消 // 6002 | 网络连接出错 // 6004 | 支付结果未知(有可能已经支付成功),请查询商户订单列表中订单的支付状态 // 99 | 用户点击忘记密码导致快捷界面退出(only iOS) resultCode: string; }): void; } /** * 发起支付。 * 详细接入支付方式参考[指引](https://docs.alipay.com/mini/introduce/pay)。 * @param options */ function tradePay(options: TradePayOptions): void; //#endregion //#region 支付代扣签约 https://docs.alipay.com/mini/api/pay-sign interface PaySignCenterOptions extends BaseOptions { signStr: string; // 签约字符串 } /** * 签约中心 * * 返回码 | 含义 * ------|------ * 7000 | 协议签约成功 * 7001 | 签约结果未知(有可能已经签约成功),请根据外部签约号查询签约状态 * 7002 | 协议签约失败 * 6001 | 用户中途取消 * 6002 | 网络连接错误 * @param options */ function paySignCenter(options: PaySignCenterOptions): void; //#endregion //#region 小程序二维码 https://docs.alipay.com/mini/api/openapi-qrcode // @see https://docs.alipay.com/mini/api/openapi-qrcode // @see https://docs.alipay.com/mini/introduce/qrcode //#endregion //#region 跳转支付宝卡包 https://docs.alipay.com/mini/api/card-voucher-ticket /** * 打开支付宝卡列表。 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openCardList(): void; interface OpenMerchantCardList extends BaseOptions { partnerId: string; // 商户编号 } /** * 打开支付宝卡列表。 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) * @param options */ function openMerchantCardList(options: OpenMerchantCardList): void; interface OpenCardDetailOptions extends BaseOptions { passId: string; // 卡实例Id } /** * 打开当前用户的某张卡的详情页 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) * * passId获取方式: * 1)通过alipass创建的卡 * 调用alipay.pass.instance.add(支付宝pass新建卡券实例接口)接口,在出参“result”中可获取 * 2)通过会员卡创建的卡 * 调用alipay.marketing.card.query(会员卡查询)接口,在schema_url中可获取,具体参数为“p=xxx”,xxx即为passId。 */ function openCardDetail(options: OpenCardDetailOptions): void; /** * 打开支付宝券列表 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) * * @param options */ function openVoucherList(): void; interface OpenMerchantVoucherListOptions extends BaseOptions { partnerId: string; // 商户编号 } /** * 打开当前用户的某个商户的券列表 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openMerchantVoucherList(options: OpenMerchantVoucherListOptions): void; interface OpenVoucherDetailOptions1 extends BaseOptions { passId: string; // 券实例Id,调用券发放接口可以获取该参数(如果传入了partnerId和serialNumber则不需传入) } interface OpenVoucherDetailOptions2 extends BaseOptions { partnerId: string; // 商户编号,以 2088 为开头(如果传入了passId则不需传入) serialNumber: string; // 序列号,调用新建卡券模板可以获取该参数(如果传入了passId则不需传入) } /** * 打开当前用户的某张券的详情页(非口碑) * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openVoucherDetail(options: OpenVoucherDetailOptions1 | OpenVoucherDetailOptions2): void; interface OpenKBVoucherDetailOptions1 extends BaseOptions { passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需传入) } interface OpenKBVoucherDetailOptions2 extends BaseOptions { partnerId: string; // 商户编号(如果传入了passId则不需传入) serialNumber: string; // 序列号(如果传入了passId则不需传入) } /** * 打开当前用户的某张券的详情页(口碑) * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openKBVoucherDetail(options: OpenKBVoucherDetailOptions1 | OpenKBVoucherDetailOptions2): void; /** * 打开支付宝票列表。 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openTicketList(): void; interface OpenMerchantTicketListOptions extends BaseOptions { partnerId: string; // 商户编号 } /** * 打开某个商户的票列表 * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openMerchantTicketList(options: OpenMerchantTicketListOptions): void; interface OpenTicketDetailOptions1 extends BaseOptions { passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需要传入passId) } interface OpenTicketDetailOptions2 extends BaseOptions { partnerId: string; // 商户编号(如果传入了passId则不需要传入partnerId) serialNumber: string; // 序列号(如果传入了passId则不需要传入serialNumber) } /** * 打开当前用户的某张票的详情页 * * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) */ function openTicketDetail(options: OpenTicketDetailOptions1 | OpenTicketDetailOptions2): void; //#endregion //#region 会员开卡授权 https://docs.alipay.com/mini/api/add-card-auth interface AddCardAuthResult { success: true | boolean; // true 表示领卡成功 resultStatus: string; // 9000 表示成功 result: { app_id: string; // 应用id auth_code: string; // 授权码,用于换取authtoken state: string; // 授权的state scope: string; // 授权scope template_id: string; // 会员卡模板Id request_id: string; // 会员卡表单信息请求Id out_string: string; // 会员卡领卡链接透传参数 }; } interface AddCardAuthResult { success: false | boolean; // false 表示领卡失败 /** * 失败的错误码 * 领卡失败 code 说明 * 名称 | 类型 | 说明 * -----|-----|----- * JSAPI_SERVICE_TERMINATED | String | 用户取消 * JSAPI_PARAM_INVALID | String | url 为空或非法参数 * JSAPI_SYSTEM_ERROR | String | 系统错误 */ code: string; } interface AddCardAuthOptions extends BaseOptions { /** * 开卡授权的页面地址,从alipay.marketing.card.activateurl.apply接口获取 */ url: string; success?(res: AddCardAuthResult): void; } /** * 小程序唤起会员开卡授权页面,小程序接入会员卡[点此查看](https://docs.alipay.com/mini/introduce/card) */ function addCardAuth(options: AddCardAuthOptions): void; //#endregion //#region 芝麻认证 https://docs.alipay.com/mini/api/zm-service interface StartZMVerifyOptions extends BaseOptions { bizNo: string; // 认证标识 success?(res: { token: string; // 认证标识 passed: string; // 认证是否通过 reason?: string; // 认证不通过原因 }): void; } /** * 芝麻认证接口,调用此接口可以唤起芝麻认证页面并进行人脸身份验证。 * 有关芝麻认证的产品和接入介绍,详见 [芝麻认证](https://docs.alipay.com/mini/introduce/zm-verify)。 * 需要通过蚂蚁开发平台,调用certification.initialize接口进行[认证初始化](https://docs.alipay.com/zmxy/271/105914)。获得biz_no 后,方能通过以下接口激活芝麻认证小程序。 */ function startZMVerify(options: StartZMVerifyOptions): void; //#endregion //#region 信用借还 https://docs.alipay.com/mini/api/zmcreditborrow interface ZMCreditBorrowOptions extends BaseOptions { /** * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+随机数 * */ out_order_no: string; /** * 信用借还的产品码,传入固定值:w1010100000000002858 */ product_code: string; /** * 物品名称,最长不能超过14个汉字 */ goods_name: string; /** * 租金单位,租金+租金单位组合才具备实际的租金意义。 * 取值定义如下: * DAY_YUAN: 元 / 天 * HOUR_YUAN: 元 / 小时 * YUAN: 元 * YUAN_ONCE: 元 / 次 */ rent_unit: string; /** * 租金,租金 + 租金单位组合才具备实际的租金意义。 * > 0.00元,代表有租金 * = 0.00元,代表无租金,免费借用 * 注:参数传值必须 >= 0,传入其他值会报错参数非法 */ rent_amount: string; /** * 押金,金额单位:元。 * 注:不允许免押金的用户按此金额支付押金;当物品丢失时,赔偿金额不得高于该金额。 */ deposit_amount: string; /** * 该字段目前默认传Y; * 是否支持当借用用户信用不够(不准入)时,可让用户支付押金借用: * Y: 支持 * N: 不支持 * 注:支付押金的金额等同于deposit_amount。 */ deposit_state?: string; // 该字段目前默认传Y; /** * 回调到商户的小程序schema地址。说明:商户的回调地址可以在商户后台里进行配置,服务端回调时,首先根据参数:invoke_type 查询是否有对应的配置地址,如果有,则使用已定义的地址,否则,使用该字段定义的地址执行回调; * 参考表格下方的说明一; * 小程序回调地址参考表格下方的说明三; * 说明一: * 支付宝商户账号登录我的商家服务打开入口链接; * 商家服务中选择“您可能需要->信用借还”或者点击链接; * 场景ID配置->配置新ID,选择对应的业务类型、服务类目和联盟,将生成的场景ID作为credit_biz的值传入即可; * 回调地址配置->设置小程序回调地址,注意:若设置了该回调地址,则接口my.zmCreditBorrow中的入参invoke_return_url将会失效,以该处设置为准; * 说明三: * 小程序回调地址示例一:alipays://platformapi/startapp?appId=1999; * 小程序回调地址示例二:alipays://platformapi/startapp?appId=1999&page=pages/map; */ invoke_return_url?: string; /** * 商户访问蚂蚁的对接模式,默认传TINYAPP: * TINYAPP:回跳至小程序地址; * WINDOWS:支付宝服务窗,默认值; */ invoke_type?: 'TINYAPP' | 'TINYAPP' | 'WINDOWS' | string; /** * 信用业务服务,注意:该字段不能为空,且必须根据说明的指引配置商户专属的场景ID,商户自助接入时,登录后台可配置场景ID,将后台配置的场景ID作为该字段的输入; * 参考说明一自助进行配置; */ credit_biz: string; /** * 商户订单创建的起始借用时间,格式:YYYY - MM - DD HH: MM: SS。如果不传入或者为空,则认为订单创建起始时间为调用此接口时的时间。 */ borrow_time?: string; /** * 到期时间,不允许为空,请根据实际业务合理设置该值,格式:YYYY - MM - DD HH: MM: SS,是指最晚归还时间,表示借用用户如果超过此时间还未完结订单(未归还物品或者未支付租金)将会进入逾期状态,芝麻会给借用用户发送催收提醒;需要晚于borrow_time。 */ expiry_time: string; /** * 借用用户的手机号码,可选字段。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 */ mobile_no?: string; /** * 物品借用地点的描述,便于用户知道物品是在哪里借的。可为空 * */ borrow_shop_name?: string; /** * 租金的结算方式,非必填字段,默认是支付宝租金结算支付 merchant:表示商户自行结算,信用借还不提供租金支付能力; alipay:表示使用支付宝支付功能,给用户提供租金代扣及赔偿金支付能力; * */ rent_settle_type?: 'merchant' | 'alipay' | string; /** * 商户请求状态上下文。商户发起借用服务时,需要在借用结束后返回给商户的参数,格式:json; * 如果json的某一项值包含中文,请使用encodeURIComponent对该值进行编码; * @example * var ext = { * name: encodeURIComponent('名字') * }; * var obj = { * invoke_state: JSON.stringify(ext) * } */ invoke_state?: string; /** * 租金信息描述, 长度不超过14个汉字,只用于页面展示给C端用户,除此之外无其他意义。 */ rent_info?: string; /** * 借用用户的真实姓名,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 */ name?: string; /** * 借用用户的真实身份证号,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 */ cert_no?: string; /** * 借用用户的收货地址,可选字段,最大长度128。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 */ address?: string; success?(res: { /** * 6001 用户取消了业务流程 * 6002 网络异常 * 9000 成功 * 4000 系统异常 */ resultStatus: '6001' | '6002' | '9000' | '4000' | string; result: { /** * 商户发起借用服务时传入的参数,需要在借用结束后返回给商户的参数 * @example * {"user_name":"john"} */ invoke_state: string; /** * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+4位随机数 * @example * 201610010000283627 */ out_order_no: string; /** * 芝麻信用借还订单号 * @example * 10020027631 */ order_no: string; /** * 是否准入:Y:准入;N:不准入(该字段目前无实际意义) */ admit_state: 'Y' | 'N' | string; /** * 物品借用/租赁者的用户id * @example * 2088202924240029 */ user_id: string; callbackData: any; // todo only in example } }): void; } function zmCreditBorrow(options: ZMCreditBorrowOptions): void; //#endregion //#region 文本风险识别 https://docs.alipay.com/mini/api/text-identification type TextRiskIdentificationType = 'keyword' | '0' | '1' | '2' | '3' | string; interface TextRiskIdentificationOptions extends BaseOptions { /** * 需要进行风险识别的文本内容 */ content: string; /** * 识别类型:keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 */ type: TextRiskIdentificationType[]; success?(res: { result: { /** * 目标内容文本识别到的类型,keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 */ type: TextRiskIdentificationType; /** * 仅当识别命中了 type 为 keyword 时,才会返回该字段 */ hitKeywords?: string[]; /** * 识别命中得分,最高分100分。仅当识别没有命中 keyword ,但入参中包含了广告或涉政或涉黄时,才会返回该字段 */ score?: string; }; fail?(res: { /** * 识别错误码 */ error: string; /** * 识别错误消息 */ errorMessage: string; }): void; }): void; } /** * 文本风险识别, **支付宝客户端10.1.10及以上版本支持。**详细接入参考[指引](https://docs.alipay.com/mini/introduce/text-identification) */ function textRiskIdentification(options: TextRiskIdentificationOptions): void; //#endregion //#region 小程序跳转 https://docs.alipay.com/mini/api/open-miniprogram interface NavigateToMiniProgramOptions extends BaseOptions { /** * 要跳转的目标小程序appId */ appId: string; /** * 打开的页面路径,如果为空则打开首页 */ path?: string; /** * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch() ,App.onShow() 中获取到这份数据 */ extraData?: any; /** * 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。默认值 release */ envVersion?: 'develop' | 'trial' | 'release' | string; } /** * 跳转到其他小程序。详细接入参考[指引](https://docs.alipay.com/mini/introduce/open-miniprogram) * @param options */ function navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; interface NavigateBackMiniProgramOptions extends BaseOptions { /** * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch(),App.onShow() 中获取到这份数据 */ extraData?: any; } /** * 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功 */ function navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; //#endregion //#region webview组件控制 https://docs.alipay.com/mini/api/webview-context interface WebViewContext { postMessage(param: any): void; } /** * 创建并返回 web-view 上下文 webViewContext 对象。 * * @param webviewId 要创建的web-view所对应的id属性 */ function createWebViewContext(webviewId: string): WebViewContext; //#endregion } // 多媒体 declare namespace my { //#region 图片 https://docs.alipay.com/mini/api/media-image type ImageSourceType = "album" | "camera"; interface ChooseImageOptions extends BaseOptions { /** 最大可选照片数,默认1张 */ count: number; /** 相册选取或者拍照,默认 [‘camera’,‘album’] */ sourceType: ImageSourceType[]; /** 成功则返回图片的本地文件路径列表 tempFilePaths */ success(res: { /** * 图片文件描述 */ apFilePaths: string[]; }): void; } /** * 从本地相册选择图片或使用相机拍照。 */ function chooseImage(options: Partial<ChooseImageOptions>): void; interface PreviewImageOptions extends BaseOptions { /** 当当前显示图片索引,默认 0 */ current?: number; /** 要预览的图片链接列表 */ urls: string[]; } /** * 预览图片。 */ function previewImage(options: PreviewImageOptions): void; interface SaveImageOptions extends BaseOptions { /** * 要保存的图片链接 */ url: string; success?(res: { errMsg: string }): void; } /** * 保存在线图片到手机相册。 */ function saveImage(options: SaveImageOptions): void; interface CompressImageOptions extends BaseOptions { /** * 要压缩的图片地址数组 */ apFilePaths: string[]; /** * 压缩级别,支持 0 ~ 4 的整数,默认 4。详见「compressLevel表 说明表」 * compressLevel表 * compressLevel | 说明 * --------------|----- * 0 | 低质量 * 1 | 中等质量 * 2 | 高质量 * 3 | 不压缩 * 4 | 根据网络适应 */ compressLevel?: 0 | 1 | 2 | 3 | 4; success?(res: { /** * 压缩后的路径数组 */ apFilePaths: string[]; }): void; } /** * 压缩图片。扫码体验: */ function compressImage(options: CompressImageOptions): void; interface GetImageInfoOptions extends BaseOptions { /** * 图片路径,目前支持: * - 网络图片路径 * - apFilePath路径 * - 相对路径 */ src: string; success?(res: { width: number; // 图片宽度(单位px) height: number; // 图片高度(单位px) path: string; // 图片本地路径 }): void; } /** * 获取图片信息 */ function getImageInfo(options: GetImageInfoOptions): void; //#endregion } // 缓存 declare namespace my { //#region 缓存 https://docs.alipay.com/mini/api/storage interface SetStorageOptions extends BaseOptions { /** 本地缓存中的指定的 key */ key: string; /** 需要存储的内容 */ data: any; } /** * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的数据。 * 这是异步接口。 */ function setStorage(options: SetStorageOptions): void; /** * 同步将数据存储在本地缓存中指定的 key 中。 * 这是同步接口。 * * @param key 本地缓存中的指定的 key * @param data 需要存储的内容 */ function setStorageSync(options: { key: string; data: any; }): void; interface GetStorageOptions extends BaseOptions { /** 本地缓存中的指定的 key */ key: string; /** 接口调用的回调函数,res = {data: key对应的内容} */ success(res: DataResponse): void; } /** * 获取缓存数据。 * 这是异步接口。 */ function getStorage(options: GetStorageOptions): void; /** * 同步获取缓存数据。 * 这是同步接口 */ function getStorageSync(options: { key: string; }): any; interface RemoveStorageOptions extends BaseOptions { key: string; } /** * 删除缓存数据。 * 这是异步接口。 */ function removeStorage(options: RemoveStorageOptions): void; /** * 同步删除缓存数据。 * 这是同步接口。 * @param key 缓存数据的key */ function removeStorageSync(options: { key: string; }): void; /** * 清除本地数据缓存。 * 这是异步接口。 */ function clearStorage(): void; /** * 同步清除本地数据缓存。 * 这是同步接口。 */ function clearStorageSync(): void; interface StorageInfo { /** * 当前storage中所有的key */ keys: string[]; /** * 当前占用的空间大小, 单位kb */ currentSize: number; /** * 限制的空间大小,单位kb */ limitSize: number; } interface GetStorageInfoOptions extends BaseOptions { success(res: StorageInfo): void; } /** * 异步获取当前storage的相关信息 */ function getStorageInfo(options: GetStorageInfoOptions): void; function getStorageInfoSync(): StorageInfo; //#endregion } // 文件 declare namespace my { //#region 文件 https://docs.alipay.com/mini/api/file interface SavedFileData { /** 文件保存路径 */ apFilePath: string; } interface SaveFileOptions extends BaseOptions { /** 文件路径 */ apFilePath: string; success?(res: SavedFileData): void; } /** * 保存文件到本地(本地文件大小总容量限制:10M) */ function saveFile(options: SaveFileOptions): void; interface GetFileInfoSuccess { /** 文件大小,单位:B */ size: number; /** 摘要结果 */ digest: string; } interface GetFileInfoOptions extends BaseOptions { /** 文件路径 */ apFilePath: string; /** 摘要算法,支持md5和sha1,默认为md5 */ digestAlgorithm?: 'md5' | 'sha1'; success?(options: GetFileInfoSuccess): void; } /** * 获取文件信息 * 基础库版本 1.4.0 开始支持,低版本需做兼容处理 */ function getFileInfo(options: GetFileInfoOptions): void; interface SavedFileInfoData { /** * 文件大小,单位B */ size: number; /** * 创建时间 */ createTime: number; } interface GetSavedFileInfoOptions extends BaseOptions { /** 文件路径 */ apFilePath: string; /** 接口调用成功的回调函数 */ success?(res: SavedFileInfoData): void; } /** * 获取保存的文件信息 */ function getSavedFileInfo(options: GetSavedFileInfoOptions): void; interface GetSavedFileListOptions extends BaseOptions { success?(res: { fileList: Array<{ /** 文件大小 */ size: number; /** 创建时间 */ createTime: number; /** 文件路径 */ apFilePath: string; }> }): void; } function getSavedFileList(options: GetSavedFileListOptions): void; type RemoveSavedFileOptions = GetSavedFileInfoOptions; /** * 删除某个保存的文件 */ function removeSavedFile(options: RemoveSavedFileOptions): void; //#endregion } // 位置 declare namespace my { //#region 位置 https://docs.alipay.com/mini/api/location interface LocationData { /** 经度 */ longitude: string; /** 纬度 */ latitude: string; /** 精确度,单位m */ accuracy: string; /** * 水平精确度,单位m */ horizontalAccuracy: string; /** * 国家(type>0生效) */ country?: string; /** * 国家编号 (type>0生效) */ countryCode?: string; /** * 省份(type>0生效) */ province?: string; /** * 城市(type>0生效) */ city?: string; /** * 城市级别的地区代码(type>0生效) */ cityAdcode?: string; /** * 区县(type>0生效) */ district?: string; /** * 区县级别的地区代码(type>0生效) */ districtAdcode?: string; /** * 需要街道级别逆地理的才会有的字段,街道门牌信息,结构是:{ street, number } (type > 1生效) */ streetNumber?: { street: string; number: string; }; /** * 需要POI级别逆地理的才会有的字段, 定位点附近的 POI 信息,结构是:{ name, address } (type > 2生效) */ pois?: Array<{ name: string; address: string; }>; } interface GetLocationOptions extends BaseOptions { /** * 支付宝客户端经纬度定位缓存过期时间,单位秒。默认 30s。使用缓存会加快定位速度,缓存过期会重新定位 */ cacheTimeout: number; /** * 0:默认,获取经纬度 * 1:获取经纬度和详细到区县级别的逆地理编码数据 * 2:获取经纬度和详细到街道级别的逆地理编码数据,不推荐使用 * 3:获取经纬度和详细到POI级别的逆地理编码数据,不推荐使用 */ type: 0 | 1 | 2 | 3; /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ success(res: LocationData): void; } /** * 获取用户当前的地理位置信息 */ function getLocation(options: Partial<GetLocationOptions>): void; interface OpenLocationOptions extends BaseOptions { /** 经度 */ longitude: number | string; /** 纬度 */ latitude: number | string; /** 位置名称 */ name: string; /** 地址的详细说明 */ address: string; /** 缩放比例,范围 3~19,默认为 15 */ scale?: number; } /** * 使用微信内置地图查看位置 */ function openLocation(options: OpenLocationOptions): void; interface ChooseLocationData { /** * 位置名称 */ name: string; /** * 详细地址 */ address: string; /** * 纬度,浮点数,范围为-90~90,负数表示南纬 */ latitude: number; /** * 经度,浮点数,范围为-180~180,负数表示西经 */ longitude: number; } interface ChooseLocationOptions extends BaseOptions { success(res: ChooseLocationData): void; } /** * 使用支付宝内置地图选择地理位置。 */ function chooseLocation(options: ChooseLocationOptions): void; //#endregion } // 网络 declare namespace my { //#region 网络 https://docs.alipay.com/mini/api/network interface RequestHeader { [key: string]: string; } interface RequestOptions extends BaseOptions<DataResponse> { /** 目标服务器url */ url: string; /** 设置请求的 HTTP 头,默认 {'Content-Type': 'application/x-www-form-urlencoded'} */ header?: RequestHeader; /** 默认GET,目前支持GET,POST */ method?: "GET" | "POST"; /** 请求的参数 */ data?: any; /** * 超时时间,单位ms,默认30000 */ timeout?: number; /** 期望返回的数据格式,默认json,支持json,text,base64 */ dataType?: 'json' | 'text' | 'base64'; /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ success?(res: DataResponse): void; } function httpRequest(options: RequestOptions): void; interface UploadFileOptions extends BaseOptions { /** 开发者服务器地址 */ url: string; /** 要上传文件资源的本地定位符 */ filePath: string; /** 文件名,即对应的 key, 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ fileName: string; /** * 文件类型 */ fileType: 'image' | 'video' | 'audio'; /** HTTP 请求 Header */ header?: RequestHeader; /** HTTP 请求中其他额外的 form 数据 */ formData?: any; success?(res: { /** 服务器返回的数据 */ data: string; /** HTTP 状态码 */ statusCode: string; header: any; }): void; } /** * 上传本地资源到开发者服务器。 */ function uploadFile(options: UploadFileOptions): void; interface DownloadFileOptions extends BaseOptions { /** 下载文件地址 */ url: string; /** HTTP 请求 Header */ header?: RequestHeader; /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ success?(res: TempFileResponse): void; } /** * 下载文件资源到本地。 */ function downloadFile(options: DownloadFileOptions): void; interface ConnectSocketOptions extends BaseOptions { /** 目标服务器url */ url: string; /** 请求的参数 */ data?: any; /** 设置请求的头部 */ header?: RequestHeader; method?: 'GET' | 'POST'; // todo missing in api } /** * 创建一个 WebSocket 的连接; * 一个支付宝小程序同时只能保留一个 WebSocket 连接,如果当前已存在 WebSocket 连接,会自动关闭该连接,并重新创建一个新的 WebSocket 连接。 */ function connectSocket(options: ConnectSocketOptions): void; /** * 监听WebSocket连接打开事件。 */ function onSocketOpen(callback: () => void): void; /** * 监听WebSocket关闭。 */ function onSocketClose(callback: () => void): void; /** * 取消监听WebSocket连接打开事件。 */ function offSocketOpen(callback: () => void): void; /** * 监听WebSocket错误。 */ function onSocketError(callback: (error: any) => void): void; /** * 取消监听WebSocket错误。 */ function offSocketError(callback: (error: any) => void): void; interface SendSocketMessageOptions extends BaseOptions { /** * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String */ data: string | ArrayBuffer; /** * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 */ isBuffer?: boolean; } /** * 通过 WebSocket 连接发送数据,需要先使用 my.connectSocket 发起建连,并在 my.onSocketOpen 回调之后再发送数据。 */ function sendSocketMessage(options: SendSocketMessageOptions): void; /** * 监听WebSocket接受到服务器的消息事件。 */ function onSocketMessage(callback: (res: { /** * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String */ data: string | ArrayBuffer; /** * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 */ isBuffer?: boolean; }) => void): void; function offSocketMessage(callback: (error: any) => void): void; interface CloseSocketOptions extends BaseOptions { success?(res: any): void; } /** * 监听WebSocket关闭。 */ function closeSocket(options?: CloseSocketOptions): void; /** * 取消监听WebSocket关闭。 */ function offSocketClose(callback: (error: any) => void): void; //#endregion } // 设备 declare namespace my { //#region canIUse https://docs.alipay.com/mini/api/can-i-use /** * 判断当前小程序的 API、入参或返回值、组件、属性等在当前版本是否支持。 * 参数使用 ${API}.${type}.${param}.${option} 或者 ${component}.${attribute}.${option} 方式来调用 * - API 表示 api 名字 * - type 取值 object/return/callback 表示 api 的判断类型 * - param 表示参数的某一个属性名 * - option 表示参数属性的具体属性值 * - component 表示组件名称 * - attribute 表示组件属性名 * - option 表示组件属性值 */ function canIUse(api: string): boolean; //#endregion //#region 获取基础库版本号 https://docs.alipay.com/mini/api/sdk-version const SDKVersion: string; //#endregion //#region 系统信息 https://docs.alipay.com/mini/api/system-info interface SystemInfo { /** * 手机型号 */ model: string; /** * 设备像素比 */ pixelRatio: number; /** * 窗口宽度 */ windowWidth: number; /** * 窗口高度 */ windowHeight: number; /** * 支付宝设置的语言 */ language: string; /** * 支付宝版本号 */ version: string; /** * 设备磁盘容量 */ storage: string; /** * 当前电量百分比 */ currentBattery: string; /** * 系统版本 */ system: string; /** * 系统名:Android,iOS */ platform: 'Android' | 'iOS' | string; /** * 屏幕宽度 */ screenWidth: number; /** * 屏幕高度 */ screenHeight: number; /** * 手机品牌 */ brand: string; /** * 用户设置字体大小 */ fontSizeSetting: number; /** * 当前运行的客户端,当前是支付宝则有效值是"alipay" */ app: 'alipay' | string; } interface GetSystemInfoOptions extends BaseOptions { success?(res: SystemInfo): void; } function getSystemInfo(options: GetSystemInfoOptions): void; function getSystemInfoSync(): SystemInfo; //#endregion //#region 网络状态 https://docs.alipay.com/mini/api/network-status interface GetNetworkTypeOptions extends BaseOptions { success?(res: { /** 网络是否可用 */ networkAvailable: boolean; /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ networkType: NetworkType; }): void; } type NetworkType = 'UNKNOWN' | 'NOTREACHABLE' | 'WIFI' | '3G' | '2G' | '4G' | 'WWAN'; function getNetworkType(options: GetNetworkTypeOptions): void; /** * 开始网络状态变化的监听 */ function onNetworkStatusChange(callback: (res: { /** 网络是否可用 */ isConnected: boolean; /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ networkType: NetworkType; }) => void): void; /** * 取消网络状态变化的监听 */ function offNetworkStatusChange(): void; //#endregion //#region 剪贴板 https://docs.alipay.com/mini/api/clipboard interface GetClipboardOptions extends BaseOptions { success?(res: { text: string; }): void; } function getClipboard(options: GetClipboardOptions): void; interface SetClipboardOptions extends BaseOptions { /** 剪贴板数据 */ text: string; } function setClipboard(options: SetClipboardOptions): void; //#endregion //#region 摇一摇 https://docs.alipay.com/mini/api/shake function watchShake(options: BaseOptions): void; //#endregion //#region 震动 https://docs.alipay.com/mini/api/vibrate /** * 调用震动功能。 */ function vibrate(options?: BaseOptions): void; /** * 调用震动功能。 */ function vibrateLong(options?: BaseOptions): void; /** * 调用震动功能。 */ function vibrateShort(options?: BaseOptions): void; //#endregion //#region 拨打电话 https://docs.alipay.com/mini/api/macke-call interface MakePhoneCallOptions extends BaseOptions { /** * 需要拨打的电话号码 */ number: string; } /** * 拨打电话 */ function makePhoneCall(options: MakePhoneCallOptions): void; //#endregion //#region 获取服务器时间 https://docs.alipay.com/mini/api/get-server-time interface GetServerTimeOptions extends BaseOptions { success?(res: { /** 服务器时间的毫秒数 */ time: number; }): void; } function getServerTime(options: GetServerTimeOptions): void; //#endregion //#region 用户截屏事件 https://docs.alipay.com/mini/api/user-capture-screen /** * 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件 */ function onUserCaptureScreen(callback?: (res: any) => void): void; /** * 取消监听截屏事件。一般需要与 my.onUserCaptureScreen 成对出现。 */ function offUserCaptureScreen(): void; //#endregion //#region 屏幕亮度 https://docs.alipay.com/mini/api/screen-brightness interface SetKeepScreenOnOptions extends BaseOptions { /** 是否保持屏幕常亮 */ keepScreenOn: boolean; success?(res: { errMsg: string }): void; } /** * 设置是否保持常亮状态。 * 仅在当前小程序生效,离开小程序后设置失效。 */ function setKeepScreenOn(options?: SetKeepScreenOnOptions): void; interface GetScreenBrightnessOptions extends BaseOptions { /** 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ success(value: number): void; } /** * 获取屏幕亮度 */ function getScreenBrightness(options?: GetScreenBrightnessOptions): void; interface SetScreenBrightnessOptions extends BaseOptions { /** 需要设置的屏幕亮度,取值范围0-1 */ brightness: number; } /** * 设置屏幕亮度 */ function setScreenBrightness(options: SetScreenBrightnessOptions): void; //#endregion //#region 权限引导 https://docs.alipay.com/mini/api/show-auth-guide interface showAuthGuideOptions extends BaseOptions { /** * 引导的权限标识,用于标识该权限类型(如 LBS) * 支持的 authType 如下: * * 权限名称 权限码 支持平台 * 后台保活权限 BACKGROUNDER Android * 桌面快捷权限 SHORTCUT Android * 麦克风权限 MICROPHONE iOS * 通讯录权限 ADDRESSBOOK iOS * 相机权限 CAMERA iOS * 照片权限 PHOTO iOS * push通知栏权限 NOTIFICATION iOS * 自启动权限 SELFSTARTING Android * lbs总开关 LBSSERVICE iOS * lbs开关(app) LBS iOS */ authType: 'BACKGROUNDER' | 'SHORTCUT' | 'MICROPHONE' | 'ADDRESSBOOK' | 'CAMERA' | 'PHOTO' | 'NOTIFICATION' | 'SELFSTARTING' | 'LBSSERVICE' | 'LBS'; } function showAuthGuide(options: showAuthGuideOptions): void; //#endregion } // 扫码 declare namespace my { //#region 扫码 https://docs.alipay.com/mini/api/scan type scanType = "qr" | "bar"; interface ScanCodeData { /** * 扫描二维码时返回二维码数据 */ code: string; /** * 所扫码的类型 */ qrCode: string; /** * 扫描条形码时返回条形码数据 */ barCode: string; } interface ScanOptions extends BaseOptions { /** * 扫码样式(默认 qr): * 1. qr,扫码框样式为二维码扫码框 * 1. bar,扫码样式为条形码扫码框 */ type?: scanType; /** * 是否隐藏相册(不允许从相册选择图片),只能从相机扫码 */ hideAlbum?: boolean; success?(res: ScanCodeData): void; } /** * 调起客户端扫码界面,扫码成功后返回对应的结果 */ function scan(options: ScanOptions): void; //#endregion } // 蓝牙 declare namespace my { //#region 快速接入 https://docs.alipay.com/mini/api/bluetooth-intro //#endregion //#region API https://docs.alipay.com/mini/api/bluetooth-api interface OpenBluetoothAdapterOptions extends BaseOptions { /** 不传的话默认是true,表示是否在离开当前页面时自动断开蓝牙(仅对android有效) */ autoClose: boolean; success(res: { /** * 是否支持 BLE */ isSupportBLE: boolean; }): void; } /** * 初始化小程序蓝牙模块,生效周期为调用 my.openBluetoothAdapter 至调用 my.closeBluetoothAdapter 或小程序被销毁为止。 在小程序蓝牙适配器模块生效期间,开发者可以正常调用下面的小程序API,并会收到蓝牙模块相关的 on 事件回调。 */ function openBluetoothAdapter(options: Partial<OpenBluetoothAdapterOptions>): void; interface CloseBluetoothAdapterOptions extends BaseOptions { success(res: any): void; } /** * 关闭本机蓝牙模块 */ function closeBluetoothAdapter(options: CloseBluetoothAdapterOptions): void; interface BluetoothAdapterStateData extends ErrMsgResponse { /** * 是否正在搜索设备 */ discovering: boolean; /** * 蓝牙模块是否可用(需支持 BLE 并且蓝牙是打开状态) */ available: boolean; } interface GetBluetoothAdapterStateOptions extends BaseOptions { success(res: BluetoothAdapterStateData): void; } /** * 获取本机蓝牙适配器状态 */ function getBluetoothAdapterState(options: GetBluetoothAdapterStateOptions): void; interface StartBluetoothDevicesDiscoveryOptions extends BaseOptions { /** * 蓝牙设备主 service 的 uuid 列表 * 某些蓝牙设备会广播自己的主 service 的 uuid。如果这里传入该数组,那么根据该 uuid 列表,只搜索有这个主服务的设备。 */ services?: string[]; /** * 否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 */ allowDuplicatesKey?: boolean; /** * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 */ interval?: number; } /** * 开始搜寻附近的蓝牙外围设备。搜索结果将在 my.onBluetoothDeviceFound 事件中返回。 */ function startBluetoothDevicesDiscovery(options: StartBluetoothDevicesDiscoveryOptions): void; interface StopBluetoothDevicesDiscoveryOptions extends BaseOptions { success(res: ErrMsgResponse): void; } /** * 停止搜寻附近的蓝牙外围设备。请在确保找到需要连接的设备后调用该方法停止搜索。 */ function stopBluetoothDevicesDiscovery(options: StopBluetoothDevicesDiscoveryOptions): void; /** * 蓝牙设备信息 */ interface BluetoothDevice { /** * 蓝牙设备名称,某些设备可能没有 */ name: string; /** * (兼容旧版本) 值与 name 一致 */ deviceName: string; /** * 广播设备名称 */ localName: string; /** * 设备的 id */ deviceId: string; /** * 设备信号强度 */ RSSI: number; /** * 设备的广播内容 */ advertisData: ArrayBuffer; /** * 设备的manufacturerData */ manufacturerData: ArrayBuffer; } interface GetBluetoothDevicesOptions extends BaseOptions { success( res: { devices: BluetoothDevice[]; } & ErrMsgResponse ): void; } /** * 获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。 */ function getBluetoothDevices(options: GetBluetoothDevicesOptions): void; interface GetConnectedBluetoothDevicesOptions extends BaseOptions { services?: string[]; success( res: { devices: BluetoothDevice[]; } & ErrMsgResponse ): void; } /** * 获取处于已连接状态的设备。 */ function getConnectedBluetoothDevices(options: GetConnectedBluetoothDevicesOptions): void; interface BLEDeviceOptions extends BaseOptions { /** * 蓝牙设备id */ deviceId: string; } /** * 连接低功耗蓝牙设备。 */ function connectBLEDevice(options: BLEDeviceOptions): void; /** * 断开与低功耗蓝牙设备的连接。 */ function disconnectBLEDevice(options: BLEDeviceOptions): void; interface WriteBLECharacteristicValueOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * 蓝牙设备特征值对应的值,16进制字符串,限制在20字节内 */ value: string; } /** * 向低功耗蓝牙设备特征值中写入数据。 */ function writeBLECharacteristicValue( options: WriteBLECharacteristicValueOptions ): void; interface ReadBLECharacteristicValueOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; success( res: { characteristic: { /** * 蓝牙设备特征值的 uuid */ characteristicId: string; /** * 蓝牙设备特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙设备特征值对应的二进制值 */ value: ArrayBuffer; }; } & ErrMsgResponse ): void; } /** * 读取低功耗蓝牙设备特征值中的数据。调用后在 my.onBLECharacteristicValueChange() 事件中接收数据返回。 */ function readBLECharacteristicValue(options: ReadBLECharacteristicValueOptions): void; interface NotifyBLECharacteristicValueChangeOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应 service 的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) */ descriptorId?: string; /** * 是否启用notify或indicate */ state?: boolean; } function notifyBLECharacteristicValueChange(optons: NotifyBLECharacteristicValueChangeOptions): void; interface NotifyBLECharacteristicValueChangedOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) */ descriptorId?: string; /** * true: 启用 notify; false: 停用 notify */ state: boolean; success(res: ErrMsgResponse): void; } /** * 启用低功耗蓝牙设备特征值变化时的 notify 功能。注意:设备的特征值必须支持 notify/indicate 才可以成功调用,具体参照 characteristic 的 properties 属性 另外,必须先启用 notify 才能监听到设备 characteristicValueChange 事件。 */ function notifyBLECharacteristicValueChanged(options: NotifyBLECharacteristicValueChangedOptions): void; interface GetBLEDeviceServicesOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success(res: { services: Array<{ /** * 蓝牙设备服务的 uuid */ serviceId: string; /** * 该服务是否为主服务 */ isPrimary: boolean; }>; } & ErrMsgResponse): void; } /** * 获取蓝牙设备所有 service(服务) */ function getBLEDeviceServices(options: GetBLEDeviceServicesOptions): void; interface GetBLEDeviceCharacteristicsOptions extends BaseOptions { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙服务 uuid */ serviceId: string; /** * 成功则返回本机蓝牙适配器状态 */ success(res: { characteristics: Array<{ /** * 蓝牙设备特征值的 uuid */ characteristicId: string; /** * 蓝牙设备特征值对应服务的 uuid */ serviceId: string; /** * 蓝牙设备特征值对应的16进制值 */ value: ArrayBuffer; /** * 该特征值支持的操作类型 */ properties: Array<{ /** * 该特征值是否支持 read 操作 */ read: boolean; /** * 该特征值是否支持 write 操作 */ write: boolean; /** * 该特征值是否支持 notify 操作 */ notify: boolean; /** * 该特征值是否支持 indicate 操作 */ indicate: boolean; }>; }>; } & ErrMsgResponse): void; } /** * 获取蓝牙设备所有 characteristic(特征值) */ function getBLEDeviceCharacteristics(options: GetBLEDeviceCharacteristicsOptions): void; interface OnBluetoothDeviceFoundOptions extends BaseOptions { success?(res: { devices: BluetoothDevice[]; }): void; } /** * 搜索到新的蓝牙设备时触发此事件。 */ function onBluetoothDeviceFound(options: OnBluetoothDeviceFoundOptions): void; /** * 移除寻找到新的蓝牙设备事件的监听。 */ function offBluetoothDeviceFound(callback?: any): void; interface OnBLECharacteristicValueChangeOptions extends BaseOptions { success?(res: { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 蓝牙特征值对应 service 的 uuid */ serviceId: string; /** * 蓝牙特征值的 uuid */ characteristicId: string; /** * 特征值最新的16进制值 */ value: ArrayBuffer; }): void; } /** * 监听低功耗蓝牙设备的特征值变化的事件。 */ function onBLECharacteristicValueChange(options: OnBLECharacteristicValueChangeOptions): void; interface OnBLEConnectionStateChangedOptions extends BaseOptions { success?(res: { /** * 蓝牙设备 id,参考 device 对象 */ deviceId: string; /** * 连接目前的状态 */ connected: boolean; }): void; } /** * 移除低功耗蓝牙设备的特征值变化事件的监听。 */ function offBLECharacteristicValueChange(callback?: any): void; /** * 监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等。 */ function onBLEConnectionStateChanged(options: OnBLEConnectionStateChangedOptions): void; /** * 移除低功耗蓝牙连接状态变化事件的监听。 */ function offBLEConnectionStateChanged(): void; interface BluetoothAdapterState { /** * 蓝牙适配器是否可用 */ available: boolean; /** * 蓝牙适配器是否处于搜索状态 */ discovering: boolean; } /** * 监听本机蓝牙状态变化的事件。 */ function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterState) => void): void; /** * 移除本机蓝牙状态变化的事件的监听。 */ function offBluetoothAdapterStateChange(): void; //#endregion } // iBeacon declare namespace my { //#region iBeacon https://docs.alipay.com/mini/api/yqleyc interface StartBeaconDiscoveryOptions extends BaseOptions { /** * iBeacon设备广播的 uuids */ uuids: string[]; success?(res: ErrMsgResponse): void; } /** * 开始搜索附近的iBeacon设备 */ function startBeaconDiscovery(options: StartBeaconDiscoveryOptions): void; interface StopBeaconDiscoveryOptions extends BaseOptions { success?(res: ErrMsgResponse): void; } /** * 停止搜索附近的iBeacon设备 */ function stopBeaconDiscovery(options: StopBeaconDiscoveryOptions): void; interface Beacon { /** iBeacon 设备广播的 uuid */ uuid: string; /** iBeacon 设备的主 id */ major: string; /** iBeacon 设备的次 id */ minor: string; /** 表示设备距离的枚举值(0-3分别代表:未知、极近、近、远) */ proximity: 0 | 1 | 2 | 3; /** iBeacon 设备的距离 */ accuracy: number; /** iBeacon 信号强度 */ rssi: number; } interface GetBeaconsSuccess { beacons: Beacon[]; /** * errorCode=0 ,接口调用成功 */ errCode: string; /** * ok */ errMsg: string; } interface GetBeaconsOptions extends BaseOptions { success?(options: GetBeaconsSuccess): void; } /** * 获取所有已搜索到的iBeacon设备 */ function getBeacons(options: GetBeaconsOptions): void; interface BeaconUpdateOptions extends BaseOptions { success?(res: { beacons: Beacon[]; }): void; } /** * 监听 iBeacon 设备的更新事件 */ function onBeaconUpdate(options: BeaconUpdateOptions): void; interface BeaconServiceChangeOptions extends BaseOptions { success?(res: { /** * 服务目前是否可用 */ available: boolean; /** * 目前是否处于搜索状态 */ discovering: boolean; }): void; } /** * 监听 iBeacon 服务的状态变化 */ function onBeaconServiceChange(options: BeaconServiceChangeOptions): void; //#endregion } // 数据安全 declare namespace my { //#region 数据安全 https://docs.alipay.com/mini/api/data-safe interface RsaOptions extends BaseOptions { /** * 使用rsa加密还是rsa解密,encrypt加密,decrypt解密 */ action: string; /** * 要处理的文本,加密为原始文本,解密为Base64编码格式文本 */ text: string; /** * rsa秘钥,加密使用公钥,解密使用私钥 */ key: string; success?(res: { /** * 经过处理过后得到的文本,加密为Base64编码文本,解密为原始文本 */ text: string; }): void; } /** * 非对称加密。 */ function rsa(options: RsaOptions): void; //#endregion } // 分享 declare namespace my { //#region 分享 https://docs.alipay.com/mini/api/share_app //#endregion } // 自定义分析 declare namespace my { //#region 自定义分析 https://docs.alipay.com/mini/api/report /** * 自定义分析数据的上报接口。使用前需要在小程序管理后台的事件管理中新建事件,并配置好事件名和字段。 * * @param eventName 自定义事件名,需申请 * @param data 上报的数据 */ function reportAnalytics(eventName: string, data: any): void; /** * 隐藏分享按钮。 */ function hideShareMenu(options?: BaseOptions): void; //#endregion } declare namespace my { interface LaunchOptions { /** * 打开小程序的路径 */ path: string; /** * 打开小程序的query */ query: object; /** * 打开小程序的[场景值] */ scene: number; /** * shareTicket,详见 获取更多[转发信息] */ shareTicket: string; /** * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ referrerInfo: object; /** * 来源小程序或公众号或App的 appId,详见下方说明 */ "referrerInfo.appId": string; /** * 来源小程序传过来的数据,scene=1037或1038时支持 */ "referrerInfo.extraData": object; // #endregion } interface AppOptions { /** * 监听小程序初始化。 * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) * 生命周期函数 */ onLaunch?: (this: App, option: LaunchOptions) => void; /** * 监听小程序显示。 * 当小程序启动,或从后台进入前台显示,会触发 onShow * 生命周期函数 */ onShow?: (this: App, option: LaunchOptions) => void; /** * 监听小程序隐藏。 * 当小程序从前台进入后台,会触发 onHide * 生命周期函数 */ onHide?: (this: App) => void; /** * 错误监听函数 * 当小程序发生脚本错误或者 api 调用失败时 * 会触发 onError 并带上错误信息 */ onError?: (this: App, msg: string) => void; /** * 小程序退出时触发 */ onUnlaunch?: (this: App) => void; /** * 全局Data */ globalData?: object; [key: string]: any; } interface CreateIntersectionObserverOption { thresholds?: [number, number]; initialRatio?: number; selectAll?: boolean; } interface Margins { left?: number; right?: number; top?: number; bottom?: number; } interface ObserveResponse { id: string; dataset: any; time: number; intersectionRatio: number; // 相交区域占目标节点的布局区域的比例 boundingClientRect: RectArea; intersectionRect: RectArea; relativeRect: RectArea; } interface IntersectionObserver { relativeTo(selector?: string, margins?: Margins): IntersectionObserver; relativeToViewport(margins?: Margins): IntersectionObserver; observe( selector?: string, callback?: (response: ObserveResponse) => void ): IntersectionObserver; disconnect(): void; } interface ComponentRelation { /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ type: "parent" | "child" | "ancestor" | "descendant"; /** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */ target?: string; /** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */ linked?: (target: Component) => void; /** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */ linkChanged?: (target: Component) => void; /** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */ unlinked?: (target: Component) => void; } interface Component { /** * 组件的文件路径 */ is: string; /** * 节点id */ id: string; /** * 节点dataset */ dataset: string; /** * 组件数据,包括内部数据和属性值 */ data: any; /** * 组件数据,包括内部数据和属性值(与 data 一致) */ properties: any; /** * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 * 3. 请不要把 data 中任何一项的 value 设为 undefined ,否则这一项将不被设置并可能遗留一些潜在问题 * @param data object 以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value * @param [callback] callback 是一个回调函数,在这次setData对界面渲染完毕后调用 */ setData( data: any, callback?: () => void ): void; hasBehavior(behavior: any): boolean; triggerEvent( name: string, details?: any, options?: Partial<{ bubbles: boolean; composed: boolean; capturePhase: boolean; }> ): void; createSelectorQuery(): SelectorQuery; createIntersectionObserver( options?: CreateIntersectionObserverOption ): IntersectionObserver; /** * 使用选择器选择组件实例节点 * 返回匹配到的第一个组件实例对象 */ selectComponent(selector: string): Component; /** * selector 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 */ selectAllComponents(selector: string): Component[]; getRelationNodes(relationKey: string): ComponentRelation[]; } interface Page extends Component { /** * data */ data: any; /** * 强制更新 */ forceUpdate(): void; /** * 字段可以获取到当前页面的路径。 */ route(): void; /** * 更新 */ update(): void; /** * 将页面滚动到目标位置。 * * scrollTop 滚动到页面的目标位置(单位px) * [duration] 滚动动画的时长,默认300ms,单位 ms */ pageScrollTo(option?: PageScrollToOptions): void; [key: string]: any; } interface App { data: any; /** * 获取当前页面 */ getCurrentPage(): Page; [key: string]: any; } interface EventTarget { id: string; tagName: string; dataset: { [name: string]: string }; } type TouchEventType = | "tap" | "touchstart" | "touchmove" | "touchcancel" | "touchend" | "touchforcechange"; type TransitionEventType = | "transitionend" | "animationstart" | "animationiteration" | "animationend"; type EventType = | "input" | "form" | "submit" | "scroll" | TouchEventType | TransitionEventType | "tap" | "longpress"; interface BaseEvent<T extends string, Detail> { type: T; timeStamp: number; currentTarget: EventTarget; target: EventTarget; detail: Detail; } interface Options { query: any; // 当前小程序的 query path: string; // 当前小程序的页面地址 } interface PageOptions { data: any; onLaunch(this: Page, options: Options): void; onShow(this: Page, options: Options): void; onHide(this: Page): void; onError(this: Page): void; [key: string]: any; } function postMessage(param: any): void; type onMessageFun = (p: any) => void; let onMessage: onMessageFun; } declare function App(app: Partial<my.AppOptions & my.App>): void; declare function getApp(): my.App; declare function Behavior(options?: any): my.Component; declare function Component(options?: any): my.Component; declare function Page(options: Partial<my.PageOptions & my.Page>): void; declare function getCurrentPages(): my.Page[];
the_stack
import type {FramebufferProps, ColorAttachment} from '@luma.gl/api'; import {Device, log, assert} from '@luma.gl/api'; import GL from '@luma.gl/constants'; import {getWebGL2Context, assertWebGL2Context} from '@luma.gl/webgl'; import {getKey} from '../webgl-utils/constants-to-keys'; import Renderbuffer from './renderbuffer'; import {clear, clearBuffer} from './clear'; import Texture from './texture'; // import {copyToDataUrl} from './copy-and-blit'; import {WebGLDevice, WEBGLFramebuffer} from '@luma.gl/webgl'; export type TextureAttachment = [Texture, number?, number?]; export type Attachment = WebGLTexture | Renderbuffer | TextureAttachment; const ERR_MULTIPLE_RENDERTARGETS = 'Multiple render targets not supported'; /** @deprecated backwards compatibility props */ export type ClassicFramebufferProps = FramebufferProps & { attachments?: Record<number, Attachment | Renderbuffer>; readBuffer?: number; drawBuffers?: number[]; check?: boolean; width?: number; height?: number; color?: boolean; depth?: boolean; stencil?: boolean; }; type ColorBufferFloatOptions = {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean}; /** Convert classic framebuffer attachments array to WebGPU style attachments */ function getDefaultProps(props: ClassicFramebufferProps): FramebufferProps { const newProps: FramebufferProps = {...props}; const {color = true, depth = true, stencil = false} = props; if (props.attachments) { newProps.depthStencilAttachment = undefined; newProps.colorAttachments = newProps.colorAttachments || []; for (const [attachmentPoint, attachment] of Object.entries(props.attachments)) { switch (Number(attachmentPoint) as GL) { case GL.DEPTH_ATTACHMENT: case GL.STENCIL_ATTACHMENT: case GL.DEPTH_STENCIL_ATTACHMENT: // @ts-expect-error newProps.depthStencilAttachment = attachment; break; default: // TODO, map attachmentPoint // @ts-expect-error newProps.colorAttachments.push(attachment); break; } } // @ts-expect-error delete newProps.attachments; return newProps; } if (color) { newProps.colorAttachments = newProps.colorAttachments || ['rgba8unorm-unsized']; } if (depth && stencil) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'depth24plus-stencil8'; } else if (depth) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'depth16unorm'; } else if (stencil) { newProps.depthStencilAttachment = newProps.depthStencilAttachment || 'stencil8'; } return newProps; } /** @deprecated Use device.createFramebuffer() */ export default class ClassicFramebuffer extends WEBGLFramebuffer { width = null; height = null; attachments = {}; readBuffer = GL.COLOR_ATTACHMENT0; drawBuffers = [GL.COLOR_ATTACHMENT0]; ownResources = []; static readonly FRAMEBUFFER_ATTACHMENT_PARAMETERS = [ GL.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, // WebGLRenderbuffer or WebGLTexture GL.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, // GL.RENDERBUFFER, GL.TEXTURE, GL.NONE // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, // GL.TEXTURE_CUBE_MAP_POSITIVE_X, etc. // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, // GLint // EXT_sRGB or WebGL2 GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, // GL.LINEAR, GL.SRBG // WebGL2 // GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER, // GLint GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, // GLint GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE // GLint // GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE // GL.FLOAT, GL.INT, GL.UNSIGNED_INT, GL.SIGNED_NORMALIZED, OR GL.UNSIGNED_NORMALIZED. ]; /** * Check color buffer float support * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ static isSupported(gl: WebGLRenderingContext, options: ColorBufferFloatOptions): boolean { return isFloatColorBufferSupported(gl, options); } /** * returns the default Classic * Creates a Framebuffer object wrapper for the default WebGL framebuffer (target === null) */ static getDefaultFramebuffer(gl: WebGLRenderingContext): ClassicFramebuffer { const webglDevice = WebGLDevice.attach(gl); // @ts-expect-error webglDevice.defaultFramebuffer = // @ts-expect-error webglDevice.defaultFramebuffer || new ClassicFramebuffer(gl, { id: 'default-framebuffer', handle: null, attachments: {}, check: false }); // TODO - can we query for and get a handle to the GL.FRONT renderbuffer? // @ts-expect-error return webglDevice.defaultFramebuffer; } get MAX_COLOR_ATTACHMENTS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_COLOR_ATTACHMENTS); } get MAX_DRAW_BUFFERS(): number { const gl2 = assertWebGL2Context(this.gl); return gl2.getParameter(gl2.MAX_DRAW_BUFFERS); } constructor(gl: Device | WebGLRenderingContext, props: ClassicFramebufferProps = {}) { super(WebGLDevice.attach(gl), getDefaultProps(props)); this.initialize(props); Object.seal(this); } get color() { return this.colorAttachments[0] || null; // return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get texture() { return this.colorAttachments[0] || null; // return this.attachments[GL.COLOR_ATTACHMENT0] || null; } get depth() { return ( this.depthStencilAttachment || null // this.attachments[GL.DEPTH_ATTACHMENT] || this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } get stencil() { return ( this.depthStencilAttachment || // this.attachments[GL.STENCIL_ATTACHMENT] || // this.attachments[GL.DEPTH_STENCIL_ATTACHMENT] || null ); } // initialize(props?: ClassicFramebufferProps): this; initialize(props: ClassicFramebufferProps) { let {attachments = null} = props || {}; const { width = 1, height = 1, check = true, readBuffer = undefined, drawBuffers = undefined } = props || {}; assert(width >= 0 && height >= 0, 'Width and height need to be integers'); // Store actual width and height for diffing this.width = width; this.height = height; // Resize any provided attachments - note that resize only resizes if needed // Note: A framebuffer has no separate size, it is defined by its attachments (which must agree) if (attachments) { for (const attachment in attachments) { const target = attachments[attachment]; const object = Array.isArray(target) ? target[0] : target; // @ts-expect-error object.resize({width, height}); } } else { // Create any requested default attachments // attachments = this._createDefaultAttachments(color, depth, stencil, width, height); } this.update({clearAttachments: true, attachments, readBuffer, drawBuffers}); // Checks that framebuffer was properly set up, if not, throws an explanatory error if (attachments && check) { this.checkStatus(); } } checkStatus(): this { super._checkStatus(); return this; } getStatus(): number { const {gl} = this; const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); const status = gl.checkFramebufferStatus(GL.FRAMEBUFFER); // @ts-expect-error gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return status; } // WEBGL INTERFACE bind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, this.handle); return this; } unbind({target = GL.FRAMEBUFFER} = {}) { this.gl.bindFramebuffer(target, null); return this; } /** @note Expects framebuffer to be bound */ _setReadBuffer(readBuffer: number): void { const gl2 = getWebGL2Context(this.gl); if (gl2) { gl2.readBuffer(readBuffer); } else { // Setting to color attachment 0 is a noop, so allow it in WebGL1 assert( readBuffer === GL.COLOR_ATTACHMENT0 || readBuffer === GL.BACK, ERR_MULTIPLE_RENDERTARGETS ); } } /** @note Expects framebuffer to be bound */ _setDrawBuffers(drawBuffers: number[]) { const {gl} = this; const gl2 = assertWebGL2Context(gl); if (gl2) { gl2.drawBuffers(drawBuffers); } else { // TODO - is this not handled by polyfills? const ext = gl.getExtension('WEBGL_draw_buffers'); if (ext) { ext.drawBuffersWEBGL(drawBuffers); } else { // Setting a single draw buffer to color attachment 0 is a noop, allow in WebGL1 assert( drawBuffers.length === 1 && (drawBuffers[0] === GL.COLOR_ATTACHMENT0 || drawBuffers[0] === GL.BACK), ERR_MULTIPLE_RENDERTARGETS ); } } } // RESOURCE METHODS _createHandle() { return this.gl.createFramebuffer(); } _deleteHandle() { this.gl.deleteFramebuffer(this.handle); } _bindHandle(handle) { return this.gl.bindFramebuffer(GL.FRAMEBUFFER, handle); } update(options: { attachments: Record<string, Attachment | Renderbuffer>, readBuffer?: number, drawBuffers?, clearAttachments?: boolean, resizeAttachments?: boolean }): this { const { attachments = {}, readBuffer, drawBuffers, clearAttachments = false, resizeAttachments = true } = options; this.attach(attachments, {clearAttachments, resizeAttachments}); const {gl} = this; // Multiple render target support, set read buffer and draw buffers const prevHandle = gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (readBuffer) { this._setReadBuffer(readBuffer); this.readBuffer = readBuffer; } if (drawBuffers) { this._setDrawBuffers(drawBuffers); this.drawBuffers = drawBuffers; } // @ts-expect-error gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } /** Attach from a map of attachments */ attach(attachments, {clearAttachments = false, resizeAttachments = true} = {}) { const newAttachments = {}; // Any current attachments need to be removed, add null values to map if (clearAttachments) { Object.keys(this.attachments).forEach((key) => { newAttachments[key] = null; }); } // Overlay the new attachments Object.assign(newAttachments, attachments); const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); // Walk the attachments for (const key in newAttachments) { // Ensure key is not undefined assert(key !== undefined, 'Misspelled framebuffer binding point?'); const attachment = Number(key); const descriptor = newAttachments[attachment]; let object = descriptor; if (!object) { this._unattach(attachment); } else { object = this._attachOne(attachment, object); this.attachments[attachment] = object; } // Resize objects if (resizeAttachments && object) { object.resize({width: this.width, height: this.height}); } } // @ts-expect-error this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); // Assign to attachments and remove any nulls to get a clean attachment map Object.assign(this.attachments, attachments); Object.keys(this.attachments) .filter((key) => !this.attachments[key]) .forEach((key) => { delete this.attachments[key]; }); } clear(options?: {color?: any; depth?: any; stencil?: any; drawBuffers?: any[]}): this { const {color, depth, stencil, drawBuffers = []} = options; // Bind framebuffer and delegate to global clear functions const prevHandle = this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); if (color || depth || stencil) { clear(this.gl, {color, depth, stencil}); } drawBuffers.forEach((value, drawBuffer) => { clearBuffer(this.gl, {drawBuffer, value}); }); // @ts-expect-error this.gl.bindFramebuffer(GL.FRAMEBUFFER, prevHandle || null); return this; } // WEBGL2 INTERFACE // Copies a rectangle of pixels between framebuffers // eslint-disable-next-line complexity blit(opts = {}) { log.error('Framebuffer.blit({...}) is no logner supported, use blit(source, target, opts)')(); return null; } // signals to the GL that it need not preserve all pixels of a specified region of the framebuffer invalidate(options: {attachments: []; x?: number; y?: number; width: number; height: number}) { const {attachments = [], x = 0, y = 0, width, height} = options; const gl2 = assertWebGL2Context(this.gl); const prevHandle = gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, this.handle); const invalidateAll = x === 0 && y === 0 && width === undefined && height === undefined; if (invalidateAll) { gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments); } else { // TODO - why does type checking fail on this line // @ts-expect-error gl2.invalidateFramebuffer(GL.READ_FRAMEBUFFER, attachments, x, y, width, height); } // @ts-expect-error gl2.bindFramebuffer(GL.READ_FRAMEBUFFER, prevHandle); return this; } // Return the value for `pname` of the specified attachment. // The type returned is the type of the requested pname getAttachmentParameter(attachment, pname, keys) { let value = this._getAttachmentParameterFallback(pname); if (value === null) { this.gl.bindFramebuffer(GL.FRAMEBUFFER, this.handle); value = this.gl.getFramebufferAttachmentParameter(GL.FRAMEBUFFER, attachment, pname); this.gl.bindFramebuffer(GL.FRAMEBUFFER, null); } if (keys && value > 1000) { // @ts-expect-error value = getKey(this.gl, value); } return value; } getAttachmentParameters( attachment = GL.COLOR_ATTACHMENT0, keys, // @ts-expect-error parameters = this.constructor.ATTACHMENT_PARAMETERS || [] ) { const values = {}; for (const pname of parameters) { const key = keys ? getKey(this.gl, pname) : pname; values[key] = this.getAttachmentParameter(attachment, pname, keys); } return values; } getParameters(keys = true) { const attachments = Object.keys(this.attachments); // if (this === this.gl.luma.defaultFramebuffer) { // attachments = [GL.COLOR_ATTACHMENT0, GL.DEPTH_STENCIL_ATTACHMENT]; // } const parameters = {}; for (const attachmentName of attachments) { const attachment = Number(attachmentName); const key = keys ? getKey(this.gl, attachment) : attachment; parameters[key] = this.getAttachmentParameters(attachment, keys); } return parameters; } // Note: Will only work when called in an event handler show() { if (typeof window !== 'undefined') { // window.open(copyToDataUrl(this), 'luma-debug-texture'); } return this; } log(logLevel = 0, message = '') { if (logLevel > log.level || typeof window === 'undefined') { return this; } message = message || `Framebuffer ${this.id}`; // const image = copyToDataUrl(this, {targetMaxHeight: 100}); // // @ts-expect-error probe.gl typings incorrectly require priority... // log.image({logLevel, message, image})(); return this; } // PRIVATE METHODS _unattach(attachment) { const oldAttachment = this.attachments[attachment]; if (!oldAttachment) { return; } if (oldAttachment instanceof Renderbuffer) { // render buffer this.gl.framebufferRenderbuffer(GL.FRAMEBUFFER, attachment, GL.RENDERBUFFER, null); } else { // Must be a texture attachment this.gl.framebufferTexture2D(GL.FRAMEBUFFER, attachment, GL.TEXTURE_2D, null, 0); } delete this.attachments[attachment]; } /** * Attempt to provide workable defaults for WebGL2 symbols under WebGL1 * null means OK to query * TODO - move to webgl1 polyfills * @param pname * @returns */ // eslint-disable-next-line complexity _getAttachmentParameterFallback(pname) { const webglDevice = WebGLDevice.attach(this.gl); const features = webglDevice.features; switch (pname) { case GL.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER: // GLint return !features.has('webgl2') ? 0 : null; case GL.FRAMEBUFFER_ATTACHMENT_RED_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE: // GLint case GL.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE: // GLint return !features.has('webgl2') ? 8 : null; case GL.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE: // GLenum return !features.has('webgl2') ? GL.UNSIGNED_INT : null; case GL.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING: return !features.has('webgl2') && !features.has('texture-formats-srgb-webgl1') ? GL.LINEAR : null; default: return null; } } } // PUBLIC METHODS /** * Support * @param gl * @param options.colorBufferFloat Whether floating point textures can be rendered and read * @param options.colorBufferHalfFloat Whether half float textures can be rendered and read */ function isFloatColorBufferSupported( gl: WebGLRenderingContext, options: {colorBufferFloat?: boolean; colorBufferHalfFloat?: boolean} ): boolean { const { colorBufferFloat, // Whether floating point textures can be rendered and read colorBufferHalfFloat // Whether half float textures can be rendered and read } = options; let supported = true; if (colorBufferFloat) { supported = Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1, not exposed on all platforms gl.getExtension('WEBGL_color_buffer_float') || // WebGL 1, implicitly enables float render targets https://www.khronos.org/registry/webgl/extensions/OES_texture_float/ gl.getExtension('OES_texture_float') ); } if (colorBufferHalfFloat) { supported = supported && Boolean( // WebGL 2 gl.getExtension('EXT_color_buffer_float') || // WebGL 1 gl.getExtension('EXT_color_buffer_half_float') ); } return supported; }
the_stack