|
| 1 | +/** |
| 2 | + * Fetch wrapper for CJS builds - uses dynamic imports for node-fetch compatibility |
| 3 | + */ |
| 4 | + |
| 5 | +// Types for the dynamic import result |
| 6 | +interface NodeFetchModule { |
| 7 | + default: any; // fetch function |
| 8 | + Request: any; // Request constructor |
| 9 | + Response: any; // Response constructor |
| 10 | +} |
| 11 | + |
| 12 | +// Cache for the dynamically imported module |
| 13 | +let nodeFetchModule: NodeFetchModule | null = null; |
| 14 | + |
| 15 | +/** |
| 16 | + * Get fetch function - uses dynamic import for CJS |
| 17 | + */ |
| 18 | +export async function getFetch(): Promise<any> { |
| 19 | + // In test environment, use global fetch (mocked by jest-fetch-mock) |
| 20 | + if (typeof global !== 'undefined' && global.fetch) { |
| 21 | + return global.fetch; |
| 22 | + } |
| 23 | + |
| 24 | + if (!nodeFetchModule) { |
| 25 | + // Use Function constructor to prevent TypeScript from converting to require() |
| 26 | + const dynamicImport = new Function('specifier', 'return import(specifier)'); |
| 27 | + nodeFetchModule = (await dynamicImport('node-fetch')) as NodeFetchModule; |
| 28 | + } |
| 29 | + |
| 30 | + return nodeFetchModule.default; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Get Request constructor - uses dynamic import for CJS |
| 35 | + */ |
| 36 | +export async function getRequest(): Promise<any> { |
| 37 | + // In test environment, use global Request or a mock |
| 38 | + if (typeof global !== 'undefined' && global.Request) { |
| 39 | + return global.Request; |
| 40 | + } |
| 41 | + |
| 42 | + if (!nodeFetchModule) { |
| 43 | + // Use Function constructor to prevent TypeScript from converting to require() |
| 44 | + const dynamicImport = new Function('specifier', 'return import(specifier)'); |
| 45 | + nodeFetchModule = (await dynamicImport('node-fetch')) as NodeFetchModule; |
| 46 | + } |
| 47 | + |
| 48 | + return nodeFetchModule.Request; |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Get Response constructor - uses dynamic import for CJS |
| 53 | + */ |
| 54 | +export async function getResponse(): Promise<any> { |
| 55 | + // In test environment, use global Response or a mock |
| 56 | + if (typeof global !== 'undefined' && global.Response) { |
| 57 | + return global.Response; |
| 58 | + } |
| 59 | + |
| 60 | + if (!nodeFetchModule) { |
| 61 | + // Use Function constructor to prevent TypeScript from converting to require() |
| 62 | + const dynamicImport = new Function('specifier', 'return import(specifier)'); |
| 63 | + nodeFetchModule = (await dynamicImport('node-fetch')) as NodeFetchModule; |
| 64 | + } |
| 65 | + |
| 66 | + return nodeFetchModule.Response; |
| 67 | +} |
| 68 | + |
| 69 | +// Export types as any for CJS compatibility |
| 70 | +export type RequestInit = any; |
| 71 | +export type HeadersInit = any; |
| 72 | +export type Request = any; |
| 73 | +export type Response = any; |
0 commit comments