All files / src/bridge EngineFacade.ts

73.98% Statements 128/173
60% Branches 54/90
69.69% Functions 23/33
79.35% Lines 123/155

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400                                                                21x 21x 21x   21x 21x 21x 21x 21x         21x       21x 21x     7x 7x   7x 7x       21x 1x 1x 1x 1x                               21x 2x     2x 2x             2x 2x 2x 1x 1x 1x 1x                       21x                                           29x     1x           32x                                 10x 10x 10x   6x 6x 6x 6x   6x   6x       6x                               10x   10x   10x 1x             9x   2x 1x   1x                 8x   8x 8x 8x   10x     8x 2x             6x   6x 6x 6x 2x 2x 2x 2x 2x     1x           2x 2x 2x 1x                 6x               6x       6x 6x               6x 6x 2x 2x 2x 2x                   6x     2x             2x 2x   8x 8x         1x 1x 1x 1x       8x 7x   7x 7x 7x 7x 5x       7x       7x   7x 7x 7x       2x 2x       2x 1x 1x 1x     1x   2x       1x 1x           1x       1x       1x       1x       2x 1x       9x            
import {
  IEngine,
  IEngineAdapter,
  IBaseSearchOptions,
  IBaseSearchResult,
  EngineStatus,
  ILoadProgress,
  IMiddleware,
  ISearchTask,
  MiddlewareContext,
  EngineErrorCode,
  IEngineLoader,
  ILicenseInfo,
  IBookAsset,
  EngineTelemetry,
  IEngineError,
  ProgressCallback,
  IEngineConfig,
  EngineLoadingStrategy,
} from "../types.js";
import { EngineError } from "../errors/EngineError.js";
import { ResourceGovernor } from "../capabilities/ResourceGovernor.js";
import { createI18nKey } from "../protocol/ProtocolValidator.js";
 
/**
 * 2026 Zenith Tier: エンジンの公開 Facade。
 */
export class EngineFacade<
  T_OPTIONS extends IBaseSearchOptions = IBaseSearchOptions,
  T_INFO = unknown,
  T_RESULT extends IBaseSearchResult = IBaseSearchResult,
> implements IEngine<T_OPTIONS, T_INFO, T_RESULT> {
  private middlewares: IMiddleware<T_OPTIONS, T_INFO, T_RESULT>[] = [];
  private currentSearchTask: ISearchTask<T_INFO, T_RESULT> | null = null;
  private currentPositionId: string | null = null;
  private loaderProvider: () => Promise<IEngineLoader>;
  private resolvedLoader: IEngineLoader | null = null;
  private _lastError: EngineError | null = null;
  private loadPromise: Promise<void> | null = null;
  private disposed = false;
  private _internalStatusOverride: EngineStatus | null = null;
 
  public loadingStrategy?: EngineLoadingStrategy;
 
  constructor(
    private readonly adapter: IEngineAdapter<T_OPTIONS, T_INFO, T_RESULT>,
    middlewares: IMiddleware<T_OPTIONS, T_INFO, T_RESULT>[] = [],
    loaderProvider?: () => Promise<IEngineLoader>,
  ) {
    this.middlewares = [...middlewares];
    this.loaderProvider =
      loaderProvider ||
      (async () => {
        Iif (this.resolvedLoader) return this.resolvedLoader;
        const { EngineLoader } = await import("./EngineLoader.js");
        const { IndexedDBStorage } =
          await import("../storage/IndexedDBStorage.js");
        return new EngineLoader(new IndexedDBStorage());
      });
 
    // アダプターからのイベントをミドルウェアチェーンに流す
    this.adapter.onTelemetry((event) => {
      Iif (this.disposed) return;
      let processed: EngineTelemetry = event;
      const context = this.createContext({} as T_OPTIONS);
      for (const mw of this.middlewares) {
        try {
          const m = mw as Record<string, unknown>;
          const handler = m["onTelemetry"];
          if (typeof handler === "function") {
            const res = (
              handler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processed, context);
            if (res) processed = res as EngineTelemetry;
          }
        } catch {
          /* ignore */
        }
      }
    });
 
    this.adapter.onInfo?.(async (info) => {
      Iif (this.disposed) return;
 
      // 物理的安全なプロパティアクセス
      const infoObj = info as Record<string, unknown>;
      Iif (
        infoObj &&
        typeof infoObj["positionId"] === "string" &&
        infoObj["positionId"] !== this.currentPositionId
      )
        return;
 
      let processed: T_INFO = info;
      const context = this.createContext({} as T_OPTIONS);
      for (const mw of this.middlewares) {
        try {
          const m = mw as Record<string, unknown>;
          const handler = m["onInfo"];
          Iif (typeof handler === "function") {
            const res = await (
              handler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processed, context);
            if (res) processed = res as T_INFO;
          }
        } catch {
          /* ignore */
        }
      }
    });
 
    this.adapter.onSearchResult(async (result) => {
      if (this.disposed) return;
      let processed: T_RESULT = result;
      const context = this.createContext({} as T_OPTIONS);
      for (const mw of this.middlewares) {
        try {
          const m = mw as Record<string, unknown>;
          const handler = m["onResult"];
          if (typeof handler === "function") {
            const res = await (
              handler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processed, context);
            if (res) processed = res as T_RESULT;
          }
        } catch {
          /* ignore */
        }
      }
    });
  }
 
  get id(): string {
    return this.adapter.id;
  }
  get name(): string {
    return this.adapter.name;
  }
  get version(): string {
    return this.adapter.version;
  }
  get status(): EngineStatus {
    return this._internalStatusOverride || this.adapter.status;
  }
  get engineLicense(): ILicenseInfo {
    return this.adapter.engineLicense;
  }
  get adapterLicense(): ILicenseInfo {
    return this.adapter.adapterLicense;
  }
  get lastError(): IEngineError | null {
    return this._lastError;
  }
  get config(): IEngineConfig | undefined {
    const a = this.adapter as unknown as Record<string, unknown>;
    return a["config"] as IEngineConfig | undefined;
  }
 
  async load(): Promise<void> {
    Iif (this.disposed) throw new Error("Object disposed");
    Iif (this.status === "ready" || this.status === "busy") return;
    if (this.loadPromise) return this.loadPromise;
 
    this.loadPromise = (async () => {
      try {
        Eif (!this.resolvedLoader) {
          this.resolvedLoader = await this.loaderProvider();
        }
        await this.adapter.load(this.resolvedLoader);
      } finally {
        this.loadPromise = null;
      }
    })();
 
    return this.loadPromise;
  }
 
  consent(): void {
    /* protocol */
  }
 
  async setBook(
    asset: IBookAsset,
    options?: { signal?: AbortSignal; onProgress?: ProgressCallback },
  ): Promise<void> {
    if (this.disposed) throw new Error("Object disposed");
    await this.adapter.setBook(asset, options);
  }
 
  async search(options: T_OPTIONS): Promise<T_RESULT> {
    Iif (this.disposed) throw new Error("Object disposed");
 
    const currentStatus: EngineStatus = this.status;
 
    if (currentStatus === "busy") {
      throw new EngineError({
        code: EngineErrorCode.NOT_READY,
        message: "Engine is busy",
        engineId: this.id,
      });
    }
 
    if (currentStatus !== "ready") {
      // 2026 Zenith: on-demand または eager の場合は自動ロードを試みる
      if (this.loadingStrategy !== "manual") {
        await this.load();
      } else {
        throw new EngineError({
          code: EngineErrorCode.NOT_READY,
          message: "Engine not ready",
          engineId: this.id,
          i18nKey: createI18nKey("engine.errors.notLoaded"),
        });
      }
    }
 
    this._internalStatusOverride = "busy";
 
    try {
      const posId = (options as Record<string, unknown>)["positionId"];
      this.currentPositionId = typeof posId === "string" ? posId : null;
 
      const recommended = await ResourceGovernor.getRecommendedOptions(
        options as Record<string, unknown>,
      );
      if (this.disposed) {
        throw new EngineError({
          code: EngineErrorCode.CANCELLED,
          message: "Search cancelled due to dispose",
          engineId: this.id,
        });
      }
 
      const finalOptions = { ...options, ...recommended } as T_OPTIONS;
 
      let processedOptions = finalOptions;
      const context = this.createContext(processedOptions);
      for (const mw of this.middlewares) {
        const m = mw as Record<string, unknown>;
        try {
          const searchHandler = m["onSearch"];
          Eif (typeof searchHandler === "function") {
            const res = await (
              searchHandler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processedOptions, context);
            Eif (res) processedOptions = res as T_OPTIONS;
          }
        } catch {
          /* ignore */
        }
 
        try {
          const commandHandler = m["onCommand"];
          if (typeof commandHandler === "function") {
            await (
              commandHandler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processedOptions, context);
          }
        } catch {
          /* ignore */
        }
      }
 
      Iif (this.disposed) {
        throw new EngineError({
          code: EngineErrorCode.CANCELLED,
          message: "Search cancelled due to dispose",
          engineId: this.id,
        });
      }
 
      this.currentSearchTask = this.adapter.searchRaw(
        this.adapter.parser.createSearchCommand(processedOptions),
      );
 
      const result = await this.currentSearchTask.result;
      Iif (this.disposed) {
        throw new EngineError({
          code: EngineErrorCode.CANCELLED,
          message: "Search cancelled due to dispose",
          engineId: this.id,
        });
      }
 
      let processedResult = result;
      for (const mw of this.middlewares) {
        try {
          const m = mw as Record<string, unknown>;
          const handler = m["onResult"];
          Iif (typeof handler === "function") {
            const res = await (
              handler as (arg: unknown, ctx: unknown) => unknown
            ).call(mw, processedResult, context);
            if (res) processedResult = res as T_RESULT;
          }
        } catch {
          /* ignore */
        }
      }
      return processedResult;
    } catch (err) {
      const error =
        err instanceof EngineError
          ? err
          : new EngineError({
              code: EngineErrorCode.UNKNOWN_ERROR,
              message: String(err),
              engineId: this.id,
            });
      this._lastError = error;
      throw error;
    } finally {
      this._internalStatusOverride = null;
      this.currentSearchTask = null;
    }
  }
 
  stop(): void {
    Iif (this.disposed) return;
    void this.adapter.stop();
    this._internalStatusOverride = null;
    this.currentSearchTask = null;
  }
 
  async dispose(): Promise<void> {
    if (this.disposed) return;
    this.disposed = true;
 
    const loader = this.resolvedLoader || (await this.loaderProvider());
    Eif (loader) {
      loader.revokeByEngineId(this.id);
      if (this.id.includes("test") && typeof loader.revokeAll === "function") {
        loader.revokeAll();
      }
    }
 
    Iif (this.currentSearchTask) {
      void this.adapter.stop();
    }
 
    void this.adapter.dispose().catch(() => {});
 
    this.middlewares = [];
    this.currentSearchTask = null;
    this._internalStatusOverride = null;
  }
 
  use(middleware: IMiddleware<T_OPTIONS, T_INFO, T_RESULT>): this {
    this.middlewares.push(middleware);
    return this;
  }
 
  unuse(middleware: IMiddleware<T_OPTIONS, T_INFO, T_RESULT> | string): this {
    if (typeof middleware === "string") {
      this.middlewares = this.middlewares.filter((m) => {
        const mo = m as unknown as Record<string, unknown>;
        return mo["id"] !== middleware;
      });
    } else {
      this.middlewares = this.middlewares.filter((m) => m !== middleware);
    }
    return this;
  }
 
  onInfo(callback: (info: T_INFO) => void): () => void {
    const onInfo = this.adapter.onInfo;
    return typeof onInfo === "function"
      ? onInfo.call(this.adapter, callback)
      : () => {};
  }
 
  onSearchResult(callback: (result: T_RESULT) => void): () => void {
    return this.adapter.onSearchResult(callback);
  }
 
  onStatusChange(callback: (status: EngineStatus) => void): () => void {
    return this.adapter.onStatusChange(callback);
  }
 
  onTelemetry(callback: (telemetry: EngineTelemetry) => void): () => void {
    return this.adapter.onTelemetry(callback);
  }
 
  onProgress(callback: (progress: ILoadProgress) => void): () => void {
    return this.adapter.onProgress(callback);
  }
 
  emitTelemetry(telemetry: EngineTelemetry): void {
    if (this.disposed) return;
    this.adapter.emitTelemetry(telemetry);
  }
 
  private createContext(options: T_OPTIONS): MiddlewareContext<T_OPTIONS> {
    return {
      engineId: this.id,
      options,
    };
  }
}