Skip to content

Commit

Permalink
feat(upgrade): add node.js support
Browse files Browse the repository at this point in the history
  • Loading branch information
gfortaine committed Jan 2, 2023
1 parent 31dcc2b commit 956ed99
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# CHANGELOG

## 3.0.0
- Add node.js support
- Upgrade to TypeScript 4.9
- Add exports in package.json
- This package is now pure ESM. Please [read this](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"tsconfig.esm.json"
],
"engines": {
"node": ">=14.16"
"node": ">=18.12"
},
"scripts": {
"clean": "rimraf ./lib ./coverage",
Expand Down
18 changes: 10 additions & 8 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export interface FetchEventSourceInit extends RequestInit {
*/
openWhenHidden?: boolean;

/** The Fetch function to use. Defaults to window.fetch */
/** The Fetch function to use. Defaults to fetch */
fetch?: typeof fetch;
}

Expand Down Expand Up @@ -79,15 +79,17 @@ export function fetchEventSource(input: RequestInfo, {
}
}

if (!openWhenHidden) {
if (typeof window !== 'undefined' && !openWhenHidden) {
document.addEventListener('visibilitychange', onVisibilityChange);
}

let retryInterval = DefaultRetryInterval;
let retryTimer = 0;
function dispose() {
document.removeEventListener('visibilitychange', onVisibilityChange);
window.clearTimeout(retryTimer);
if (typeof window !== 'undefined' && !openWhenHidden) {
document.removeEventListener('visibilitychange', onVisibilityChange);
}
clearTimeout(retryTimer);
curRequestController.abort();
}

Expand All @@ -97,12 +99,12 @@ export function fetchEventSource(input: RequestInfo, {
resolve(); // don't waste time constructing/logging errors
});

const fetch = inputFetch ?? window.fetch;
const fetchFn = inputFetch ?? fetch;
const onopen = inputOnOpen ?? defaultOnOpen;
async function create() {
curRequestController = new AbortController();
try {
const response = await fetch(input, {
const response = await fetchFn(input, {
...rest,
headers,
signal: curRequestController.signal,
Expand Down Expand Up @@ -131,8 +133,8 @@ export function fetchEventSource(input: RequestInfo, {
try {
// check if we need to retry:
const interval: any = onerror?.(err) ?? retryInterval;
window.clearTimeout(retryTimer);
retryTimer = window.setTimeout(create, interval);
clearTimeout(retryTimer);
retryTimer = setTimeout(create, interval);
} catch (innerErr) {
// we should not retry anymore:
dispose();
Expand Down

0 comments on commit 956ed99

Please sign in to comment.