| 44 | * @throws {ChartGPUWorkerError} If container is invalid, canvas creation fails, or worker initialization fails |
| 45 | */ |
| 46 | export async function createChartInWorker( |
| 47 | container: HTMLElement, |
| 48 | options: ChartGPUOptions, |
| 49 | workerOrUrl?: Worker | string | URL |
| 50 | ): Promise<ChartGPUInstance> { |
| 51 | // Validate container |
| 52 | if (!container || !(container instanceof HTMLElement)) { |
| 53 | throw new ChartGPUWorkerError( |
| 54 | 'Invalid container: must be an HTMLElement', |
| 55 | 'INVALID_ARGUMENT', |
| 56 | 'createChartInWorker', |
| 57 | 'unknown' |
| 58 | ); |
| 59 | } |
| 60 | |
| 61 | let worker: Worker | null = null; |
| 62 | let workerCreated = false; |
| 63 | const chartId = `chart_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`; |
| 64 | |
| 65 | try { |
| 66 | // Initialize worker based on input type |
| 67 | if (workerOrUrl instanceof Worker) { |
| 68 | // Use provided worker instance |
| 69 | worker = workerOrUrl; |
| 70 | workerCreated = false; |
| 71 | } else if (typeof workerOrUrl === 'string' || workerOrUrl instanceof URL) { |
| 72 | // Create worker from URL string or URL object |
| 73 | try { |
| 74 | worker = new Worker(workerOrUrl, { type: 'module' }); |
| 75 | workerCreated = true; |
| 76 | } catch (error) { |
| 77 | throw new ChartGPUWorkerError( |
| 78 | `Failed to create worker from URL: ${error instanceof Error ? error.message : String(error)}`, |
| 79 | 'WEBGPU_INIT_FAILED', |
| 80 | 'createChartInWorker', |
| 81 | chartId |
| 82 | ); |
| 83 | } |
| 84 | } else { |
| 85 | // Use built-in worker (bundler will resolve this) |
| 86 | try { |
| 87 | worker = new Worker(new URL('./worker-entry.ts', import.meta.url), { type: 'module' }); |
| 88 | workerCreated = true; |
| 89 | } catch (error) { |
| 90 | throw new ChartGPUWorkerError( |
| 91 | `Failed to create built-in worker: ${error instanceof Error ? error.message : String(error)}`, |
| 92 | 'WEBGPU_INIT_FAILED', |
| 93 | 'createChartInWorker', |
| 94 | chartId |
| 95 | ); |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // Create proxy instance |
| 100 | const proxy = new ChartGPUWorkerProxy( |
| 101 | { |
| 102 | worker, |
| 103 | chartId, |