|
1 | | -//https://github.com/babel/babel/pull/14583#discussion_r882828856 |
2 | | -function deepClone(value: any, cache: Map<any, any>): any { |
| 1 | +const circleSet = new Set(); |
| 2 | +let depth = 0; |
| 3 | +// https://github.com/babel/babel/pull/14583#discussion_r882828856 |
| 4 | +function deepClone( |
| 5 | + value: any, |
| 6 | + cache: Map<any, any>, |
| 7 | + allowCircle: boolean, |
| 8 | +): any { |
3 | 9 | if (value !== null) { |
4 | | - if (cache.has(value)) return cache.get(value); |
| 10 | + if (allowCircle) { |
| 11 | + if (cache.has(value)) return cache.get(value); |
| 12 | + } else if (++depth > 250) { |
| 13 | + if (circleSet.has(value)) { |
| 14 | + depth = 0; |
| 15 | + circleSet.clear(); |
| 16 | + throw new Error("Babel-deepClone: Cycles are not allowed in AST"); |
| 17 | + } |
| 18 | + circleSet.add(value); |
| 19 | + } |
5 | 20 | let cloned: any; |
6 | 21 | if (Array.isArray(value)) { |
7 | 22 | cloned = new Array(value.length); |
8 | | - cache.set(value, cloned); |
| 23 | + if (allowCircle) cache.set(value, cloned); |
9 | 24 | for (let i = 0; i < value.length; i++) { |
10 | 25 | cloned[i] = |
11 | | - typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache); |
| 26 | + typeof value[i] !== "object" |
| 27 | + ? value[i] |
| 28 | + : deepClone(value[i], cache, allowCircle); |
12 | 29 | } |
13 | 30 | } else { |
14 | 31 | cloned = {}; |
15 | | - cache.set(value, cloned); |
| 32 | + if (allowCircle) cache.set(value, cloned); |
16 | 33 | const keys = Object.keys(value); |
17 | 34 | for (let i = 0; i < keys.length; i++) { |
18 | 35 | const key = keys[i]; |
19 | 36 | cloned[key] = |
20 | 37 | typeof value[key] !== "object" |
21 | 38 | ? value[key] |
22 | | - : deepClone(value[key], cache); |
| 39 | + : deepClone( |
| 40 | + value[key], |
| 41 | + cache, |
| 42 | + allowCircle || |
| 43 | + key === "leadingComments" || |
| 44 | + key === "innerComments" || |
| 45 | + key === "trailingComments" || |
| 46 | + key === "extra", |
| 47 | + ); |
23 | 48 | } |
24 | 49 | } |
| 50 | + if (!allowCircle) { |
| 51 | + if (depth-- > 250) circleSet.delete(value); |
| 52 | + } |
25 | 53 | return cloned; |
26 | 54 | } |
27 | 55 | return value; |
28 | 56 | } |
29 | 57 |
|
30 | 58 | export default function <T>(value: T): T { |
31 | 59 | if (typeof value !== "object") return value; |
32 | | - return deepClone(value, new Map()); |
| 60 | + |
| 61 | + if (process.env.BABEL_8_BREAKING) { |
| 62 | + if (!process.env.IS_PUBLISH && depth > 0) { |
| 63 | + throw new Error("depth > 0"); |
| 64 | + } |
| 65 | + return deepClone(value, new Map(), false); |
| 66 | + } else { |
| 67 | + try { |
| 68 | + return deepClone(value, new Map(), true); |
| 69 | + } catch (_) { |
| 70 | + return structuredClone(value); |
| 71 | + } |
| 72 | + } |
33 | 73 | } |
0 commit comments