* 加载模块 * * @param isOnTargetFrame 当前脚本是否运行在目标 frame 上 * - `unknown`: 不知道(至少要等到`document-body`后才能确定) * - `yes`: 是的
(isOnTargetFrame: IsOnTargetFrameTypes)
| 196 | * - `yes`: 是的 |
| 197 | */ |
| 198 | function loadModules(isOnTargetFrame: IsOnTargetFrameTypes): void { |
| 199 | const cacheStore = useCacheStore() |
| 200 | |
| 201 | if (isOnTargetFrame === 'unknown') { |
| 202 | for (const [name, module] of Object.entries(otherModules)) { |
| 203 | if (module.onFrame === 'all' || (module.onFrame === 'top' && isSelfTopFrame())) { |
| 204 | if (module.runOnMultiplePages || cacheStore.currentScriptType !== 'Other') { |
| 205 | if (!module.runAfterDefault) { |
| 206 | // 如果不需要等默认模块运行完了再运行,现在就加载并记录 |
| 207 | // 否则不做记录,等之后(isOnTargetFrame 为 yes 时)再加载 |
| 208 | waitForMoment(module.runAt).then(() => _runModule(module, name)) |
| 209 | // 记录被加载的 onFrame 为 all 或 top 的模块名称 |
| 210 | allAndTopFrameModuleNames.push(name) |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | } else { |
| 216 | // 在默认模块之后运行的模块(key为模块名称,value为模块class) |
| 217 | const moduleAfterDefault: Record<string, typeof BaseModule> = {} |
| 218 | // 加载默认模块 |
| 219 | const defaultModulesLoadingResult: Promise<PromiseSettledResult<void>[]> = |
| 220 | _loadDefaultModules() |
| 221 | // 加载其它模块 |
| 222 | for (const [name, module] of Object.entries(otherModules)) { |
| 223 | // 对 onFrame 为 all 或 top 的模块来说,如果之前运行过,现在就不运行了 |
| 224 | if ( |
| 225 | module.onFrame === 'target' || |
| 226 | (module.onFrame === 'top' && |
| 227 | isSelfTopFrame() && |
| 228 | !allAndTopFrameModuleNames.includes(name)) || |
| 229 | (module.onFrame === 'all' && !allAndTopFrameModuleNames.includes(name)) |
| 230 | ) { |
| 231 | if (module.runOnMultiplePages || cacheStore.currentScriptType !== 'Other') { |
| 232 | if (module.runAfterDefault) { |
| 233 | // 记录需要等默认模块运行完后再运行的模块,暂时不运行 |
| 234 | moduleAfterDefault[name] = module |
| 235 | } else { |
| 236 | waitForMoment(module.runAt).then(() => _runModule(module, name)) |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | // 等待默认模块运行完毕 |
| 243 | defaultModulesLoadingResult.then((results) => { |
| 244 | // 解析默认模块返回的 Promises |
| 245 | for (const result of results) { |
| 246 | if (result.status === 'rejected') { |
| 247 | const error: Error = result.reason |
| 248 | |
| 249 | if (error instanceof ModuleCriticalError) { |
| 250 | // 致命错误,停止运行 |
| 251 | new Logger(error.moduleName).error(error.message) |
| 252 | return |
| 253 | } else if (error instanceof ModuleError) { |
| 254 | // 一般错误,继续运行 |
| 255 | new Logger(error.moduleName).error(error.message) |
nothing calls this directly
no test coverage detected