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 401 402 403 404 405 406 407 408 409 410 411 412 | 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 2x 44x 44x 43x 2x 2x 2x 2x 2x 1x 1x 4x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 2x 2x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 1x 1x 7x 7x 23x 23x 21x 21x 3x 3x 21x 21x 2x 3x 9x 9x 9x 9x 4x 4x 4x 4x 5x 5x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 63x 63x 9x 9x 9x 63x 1x 1x 1x 1x 1x 1x 3x | import { createI18nKey } from "../protocol/ProtocolValidator.js";
import {
IEngineAdapter,
EngineStatus,
ILoadProgress,
ITelemetryEvent,
IEngineConfig,
IEngineSourceConfig,
IEngineLoader,
IBaseSearchOptions,
IBaseSearchInfo,
IBaseSearchResult,
EngineErrorCode,
IBookAsset,
ILicenseInfo,
ISearchTask,
MiddlewareCommand,
IProtocolParser,
} from "../types.js";
import { EngineError } from "../errors/EngineError.js";
import { WorkerCommunicator } from "../workers/WorkerCommunicator.js";
/**
* 2026 Zenith Tier: 全てのアダプターの基底クラス。
* 識別子 (id, name) はオブジェクト生成時に物理的に確定させ、ライフサイクル全体の安全性を保証します。
*/
export abstract class BaseAdapter<
T_OPTIONS extends IBaseSearchOptions = IBaseSearchOptions,
T_INFO extends IBaseSearchInfo = IBaseSearchInfo,
T_RESULT extends IBaseSearchResult = IBaseSearchResult,
> implements IEngineAdapter<T_OPTIONS, T_INFO, T_RESULT> {
protected _status: EngineStatus = "uninitialized";
protected communicator: WorkerCommunicator | null = null;
protected activeLoader: {
loadResource: (
engineId: string,
config: IEngineSourceConfig,
) => Promise<string>;
} | null = null;
protected readonly statusListeners = new Set<
(status: EngineStatus) => void
>();
protected readonly infoListeners = new Set<(info: T_INFO) => void>();
protected readonly resultListeners = new Set<(result: T_RESULT) => void>();
protected readonly progressListeners = new Set<
(progress: ILoadProgress) => void
>();
protected readonly telemetryListeners = new Set<
(event: ITelemetryEvent) => void
>();
protected pendingResolve: ((value: T_RESULT) => void) | null = null;
protected pendingReject: ((reason?: unknown) => void) | null = null;
protected messageUnsubscriber: (() => void) | null = null;
protected infoController: ReadableStreamDefaultController<T_INFO> | null =
null;
// 物理的な識別子。public readonly プロパティとして保持し、サブクラスでのプロパティ上書きを避ける。
public readonly id: string;
public readonly name: string;
protected readonly config: IEngineConfig;
constructor(
idOrConfig: string | IEngineConfig,
nameOrUndefined?: string,
configOrUndefined?: IEngineConfig,
) {
if (typeof idOrConfig === "string") {
this.id = idOrConfig;
this.name = nameOrUndefined ?? idOrConfig;
this.config = configOrUndefined || {};
} else E{
this.config = idOrConfig;
this.id = idOrConfig.id ?? "unknown";
this.name = idOrConfig.name ?? "Unknown Engine";
}
if (this.config.sources) {
this.validateSources();
}
}
abstract readonly version: string;
public readonly engineLicense: ILicenseInfo = { name: "Unknown", url: "" };
public readonly adapterLicense: ILicenseInfo = { name: "MIT", url: "" };
abstract readonly parser: IProtocolParser<T_OPTIONS, T_INFO, T_RESULT>;
get status(): EngineStatus {
return this._status;
}
get progress(): ILoadProgress {
return { status: this._status, loadedBytes: 0 };
}
/**
* 2026 Zenith Tier: 進捗通知付きのリソースロード。
*/
protected async loadWithProgress(
loader: IEngineLoader,
sources: Record<string, IEngineSourceConfig>,
signal?: AbortSignal,
): Promise<Record<string, string>> {
return loader.loadResources(this.id, sources, {
...(signal ? { signal } : {}),
onProgress: (p: ILoadProgress) => this.emitProgress(p),
});
}
/**
* 2026 Zenith Tier: Worker へのリソース注入。
*/
protected async injectResources(
resourceMap: Record<string, string>,
): Promise<void> {
if (this.communicator) {
await this.communicator.postMessage({
type: "inject-resources",
resourceMap,
});
}
}
protected validateSources(): void {
const sources = this.config.sources;
Iif (!sources || !sources.main) {
throw new EngineError({
code: EngineErrorCode.VALIDATION_ERROR,
message: `Engine "${this.id}" requires a "main" source.`,
engineId: this.id,
i18nKey: createI18nKey("factory.requiresMainSource"),
});
}
for (const [key, source] of Object.entries(sources)) {
const sri = (source as IEngineSourceConfig).sri;
if (sri && !/^(sha256|sha384|sha512)-[A-Za-z0-9+/=]+$/.test(sri)) {
throw new EngineError({
code: EngineErrorCode.VALIDATION_ERROR,
message: `Invalid SRI hash format for source "${key}".`,
engineId: this.id,
i18nKey: createI18nKey("engine.errors.validationError"),
});
}
Iif (sri && sri.includes("Placeholder")) {
throw new EngineError({
code: EngineErrorCode.SECURITY_ERROR,
message: `Placeholder SRI hash detected for source "${key}".`,
engineId: this.id,
i18nKey: createI18nKey("engine.errors.sriMismatch"),
});
}
}
}
async setBook(asset: IBookAsset): Promise<void> {
if (!this.activeLoader) throw new Error("No loader");
const config: IEngineSourceConfig = {
url: asset.url,
type: "asset",
sri: asset.sri,
__unsafeNoSRI: asset.sri ? undefined : true,
} as IEngineSourceConfig;
const blobUrl = await this.activeLoader.loadResource(this.id, config);
await this.onBookLoaded(blobUrl);
}
abstract load(loader?: unknown): Promise<void>;
async search(options: T_OPTIONS): Promise<T_RESULT> {
const task = this.searchRaw(this.parser.createSearchCommand(options));
return task.result;
}
searchRaw(command: MiddlewareCommand): ISearchTask<T_INFO, T_RESULT> {
if (this._status !== "ready" && this._status !== "busy") {
throw new EngineError({
code: EngineErrorCode.NOT_READY,
message: "Engine not ready",
engineId: this.id,
i18nKey: createI18nKey("engine.errors.notLoaded"),
});
}
Iif (this._status === "busy") this.cleanupPendingTask("Restart", true);
Iif (!this.communicator) throw new Error("No communicator");
this.emitStatusChange("busy");
const readableStream = new ReadableStream<T_INFO>({
start: (controller) => {
this.infoController = controller;
},
cancel: () => {
void this.handleStreamCancel();
},
});
const infoStream: AsyncIterable<T_INFO> = {
[Symbol.asyncIterator]: async function* () {
const reader = readableStream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
yield value;
}
} finally {
reader.releaseLock();
}
},
};
const resultPromise = new Promise<T_RESULT>((resolve, reject) => {
this.pendingResolve = resolve;
this.pendingReject = reject;
});
try {
this.sendSearchCommand(command);
} catch (err) {
this.pendingResolve = null;
this.pendingReject = null;
this.emitStatusChange("ready");
throw err;
}
return {
info: infoStream,
result: resultPromise,
stop: () => {
void this.stop();
},
};
}
async stop(): Promise<void> {
if (this._status !== "busy") return;
Iif (this.communicator) {
await this.communicator.postMessage(this.parser.createStopCommand());
}
this.cleanupPendingTask("Stop requested");
}
async setOption(
name: string,
value: string | number | boolean,
): Promise<void> {
if (this.communicator)
await this.communicator.postMessage(
this.parser.createOptionCommand(name, value),
);
}
async dispose(): Promise<void> {
this.cleanupPendingTask("Dispose", true);
if (this.communicator) await this.communicator.terminate();
this.communicator = null;
this.activeLoader = null;
this.emitStatusChange("terminated");
this.clearListeners();
}
onStatusChange(callback: (status: EngineStatus) => void): () => void {
this.statusListeners.add(callback);
return () => this.statusListeners.delete(callback);
}
onInfo(callback: (info: T_INFO) => void): () => void {
this.infoListeners.add(callback);
return () => this.infoListeners.delete(callback);
}
onSearchResult(callback: (result: T_RESULT) => void): () => void {
this.resultListeners.add(callback);
return () => this.resultListeners.delete(callback);
}
onProgress(callback: (progress: ILoadProgress) => void): () => void {
this.progressListeners.add(callback);
return () => this.progressListeners.delete(callback);
}
onTelemetry(callback: (event: ITelemetryEvent) => void): () => void {
this.telemetryListeners.add(callback);
return () => this.telemetryListeners.delete(callback);
}
public updateStatus(status: EngineStatus): void {
this.emitStatusChange(status);
}
public emitTelemetry(event: ITelemetryEvent): void {
this.telemetryListeners.forEach((l) => l(event));
}
protected async handleStreamCancel() {
await this.stop();
}
protected handleIncomingMessage(data: unknown): void {
Iif (this._status === "error" || this._status === "terminated") return;
// 物理的安全なキャスト
const rawData = data as string | Record<string, unknown>;
const info = this.parser.parseInfo(rawData);
if (info) {
try {
this.infoController?.enqueue(info);
} catch {
/* ignore */
}
this.infoListeners.forEach((l) => l(info));
return;
}
const result = this.parser.parseResult(rawData);
if (result) {
Iif (this.pendingResolve) {
this.pendingResolve(result);
this.pendingResolve = null;
this.pendingReject = null;
}
this.resultListeners.forEach((l) => l(result));
this.emitStatusChange("ready");
return;
}
if (
typeof data === "string" &&
data.startsWith("error") &&
this.parser.translateError
) {
const message = this.parser.translateError(data);
Eif (message) {
this.emitStatusChange("error");
this.cleanupPendingTask(message, true);
const reject = this.pendingReject;
Iif (reject) {
this.pendingReject = null;
this.pendingResolve = null;
reject(
new EngineError({
code: EngineErrorCode.PROTOCOL_ERROR,
message,
engineId: this.id,
}),
);
}
}
}
}
protected cleanupPendingTask(
reason?: string,
skipReadyTransition = false,
): void {
if (this.pendingReject) {
const reject = this.pendingReject;
this.pendingReject = null;
this.pendingResolve = null;
void Promise.resolve().then(() => {
reject(
new EngineError({
code: EngineErrorCode.SEARCH_ABORTED,
message: reason ?? "Aborted",
engineId: this.id,
}),
);
});
}
try {
this.infoController?.close();
} catch {
/* ignore */
}
this.infoController = null;
if (this._status === "busy" && !skipReadyTransition)
this.emitStatusChange("ready");
}
protected emitStatusChange(status: EngineStatus): void {
this._status = status;
if (status === "error" || status === "terminated") {
try {
this.infoController?.close();
} catch {
/* ignore */
}
this.infoController = null;
}
this.statusListeners.forEach((l) => l(status));
}
protected emitProgress(progress: ILoadProgress): void {
this.progressListeners.forEach((l) => l(progress));
}
protected clearListeners(): void {
this.statusListeners.clear();
this.progressListeners.clear();
this.telemetryListeners.clear();
this.infoListeners.clear();
this.resultListeners.clear();
}
protected sendSearchCommand(command: MiddlewareCommand): void {
this.communicator?.postMessage(command);
}
protected async onInitialize(): Promise<void> {}
protected async onSearchRaw(_command: unknown): Promise<void> {}
protected async onStop(): Promise<void> {}
protected async onDispose(): Promise<void> {}
protected async onBookLoaded(_url: string): Promise<void> {}
}
|