1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.polyfill;
16
17 import java.io.IOException;
18 import java.nio.charset.StandardCharsets;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import org.apache.commons.io.IOUtils;
23 import org.htmlunit.corejs.javascript.Context;
24 import org.htmlunit.corejs.javascript.Script;
25 import org.htmlunit.corejs.javascript.Scriptable;
26 import org.htmlunit.corejs.javascript.VarScope;
27
28
29
30
31
32
33
34 public class Polyfill {
35
36 private static final Map<String, Polyfill> CACHE = new HashMap<>();
37
38 private String url_;
39 private String source_;
40 private Script script_;
41
42
43
44
45
46 public static Polyfill getFetchPolyfill() throws IOException {
47 return getPolyfill("fetch/fetch.umd.js");
48 }
49
50 private static Polyfill getPolyfill(final String resouceName) throws IOException {
51 Polyfill poly = CACHE.get(resouceName);
52 if (poly != null) {
53 return poly;
54 }
55
56 poly = new Polyfill();
57 poly.source_ = IOUtils.toString(poly.getClass().getResourceAsStream(resouceName), StandardCharsets.UTF_8);
58 poly.url_ = poly.getClass().getResource(resouceName).toExternalForm();
59
60 CACHE.put(resouceName, poly);
61 return poly;
62 }
63
64
65
66
67
68
69
70
71 public void apply(final Context context, final VarScope scope, final Scriptable thisObject) {
72 if (script_ == null) {
73 script_ = context.compileString(source_, url_, 0, null);
74 }
75
76 if (script_ != null) {
77 script_.exec(context, scope, thisObject);
78 }
79 }
80 }