Skip to content

Commit

Permalink
Merge branch 'main' into v7
Browse files Browse the repository at this point in the history
  • Loading branch information
juliusmarminge committed Sep 2, 2024
2 parents 4a5a10d + 5ff7648 commit 7eb09cc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changeset/perfect-squids-relate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@uploadthing/shared": patch
"uploadthing": patch
---

fix: number serialization - passing non-serializable numbers in the router config should no longer cause unexpected failures.
30 changes: 29 additions & 1 deletion packages/shared/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function getDefaultSizeForType(fileType: FileRouterInputKey): FileSize {

/**
* This function takes in the user's input and "upscales" it to a full config
* Additionally, it replaces numbers with "safe" equivalents
*
* Example:
* ```ts
Expand Down Expand Up @@ -82,7 +83,13 @@ export const fillInputRouteConfig = (
newConfig[key] = { ...defaultValues, ...value };
}

return Micro.succeed(newConfig);
// we know that the config is valid, so we can stringify it and parse it back
// this allows us to replace numbers with "safe" equivalents
return Micro.succeed(
JSON.parse(
JSON.stringify(newConfig, safeNumberReplacer),
) as ExpandedRouteConfig,
);
};

export const getTypeFromFileName = (
Expand Down Expand Up @@ -307,3 +314,24 @@ export function parseTimeToSeconds(time: Time) {

return num * multiplier;
}

/**
* Replacer for JSON.stringify that will replace numbers that cannot be
* serialized to JSON with "reasonable equivalents".
*
* Infinity and -Infinity are replaced by MAX_SAFE_INTEGER and MIN_SAFE_INTEGER
* NaN is replaced by 0
*
*/
export const safeNumberReplacer = (_: string, value: unknown) => {
if (typeof value !== "number") return value;
if (
Number.isSafeInteger(value) ||
(value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER)
) {
return value;
}
if (value === Infinity) return Number.MAX_SAFE_INTEGER;
if (value === -Infinity) return Number.MIN_SAFE_INTEGER;
if (Number.isNaN(value)) return 0;
};

0 comments on commit 7eb09cc

Please sign in to comment.