diff --git a/src/mscz.ts b/src/mscz.ts index 0ef500c..cec07c2 100644 --- a/src/mscz.ts +++ b/src/mscz.ts @@ -1,10 +1,10 @@ -import { saveAs, assertRes } from './utils' +import { saveAs, assertRes, getFetch } from './utils' import { ScoreInfo } from './scoreinfo' const MSCZ_BUF_SYM = Symbol('msczBufferP') -export const fetchMscz = async (scoreinfo: ScoreInfo, _fetch = fetch): Promise => { +export const fetchMscz = async (scoreinfo: ScoreInfo, _fetch = getFetch()): Promise => { let msczBufferP = scoreinfo.store.get(MSCZ_BUF_SYM) as Promise | undefined if (!msczBufferP) { diff --git a/src/utils.ts b/src/utils.ts index 86cd3ce..d1e71f5 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,6 @@ import FileSaver from 'file-saver/dist/FileSaver.js' +import isNodeJs from 'detect-node' export const saveAs: typeof import('file-saver').saveAs = FileSaver.saveAs @@ -13,6 +14,15 @@ export const getIndexPath = (id: number): string => { return indexN.join('/') } +export const getFetch = (): typeof fetch => { + if (!isNodeJs) { + return fetch + } else { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return require('node-fetch') + } +} + export const fetchData = async (url: string, init?: RequestInit): Promise => { const r = await fetch(url, init) const data = await r.arrayBuffer() @@ -37,6 +47,7 @@ export const useTimeout = async (promise: T | Promise, ms: number): Promi } export const getSandboxWindow = (): Window => { + if (typeof document === 'undefined') return {} as any as Window const iframe = document.createElement('iframe') iframe.style.display = 'none' document.body.append(iframe)