-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (74 loc) · 2.43 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const mergeUserOptionsIn = require('./mergeUserOptionsIn');
const warnUser = require('./warnUser');
function freezeTag(userOptions) {
const handler = {};
const options = mergeUserOptionsIn(userOptions);
const handlerFunctions = {
get(target, property) {
// where the recursion happens
if (typeof target[property] === 'object' && target[property] !== null) {
return freezeTag(options)(target[property]);
}
return target[property];
},
set(target, property, value) {
const { freeze, tag } = options.set;
if (tag) {
warnUser(target, `Property "${property}"`, `changing its value to "${value}"`, freeze);
}
if (!freeze) {
target[property] = value;
}
return true;
},
// Note the difference between 'deleteProperty' and 'delete'.
// I have no idea why the JavaScript proxy handler needs the
// function to be called "deleteProperty".
// It's not "setProperty" or "getProperty".
// Maybe they wanted it to match "defineProperty"?
// But we actually DO call "Object.defineProperty". We don't call
// deleteProperty.
// I'm glad we had this talk.
deleteProperty(target, property) {
const { freeze, tag } = options.delete;
if (tag) {
warnUser(target, `Property "${property}"`, 'delete', freeze);
}
if (!freeze) {
delete target[property];
}
return true;
},
setPrototypeOf(target, prototype) {
const { freeze, tag } = options.setPrototypeOf;
if (tag) {
warnUser(target, 'The prototype', 'Object.setPrototypeOf', freeze);
}
if (!freeze) {
Object.setPrototypeOf(target, prototype);
}
return true;
},
defineProperty(target, property, descriptor) {
const { freeze, tag } = options.defineProperty;
if (tag) {
warnUser(target, `Property "${property}"`, 'Object.defineProperty', freeze);
}
if (!freeze) {
Object.defineProperty(target, property, descriptor);
}
return true;
}
};
// If it's approved on the options object, set the matching
// custom handler function onto our handler object.
Object.keys(options).forEach(key => {
if (options[key]) {
handler[key] = handlerFunctions[key];
}
});
return obj => new Proxy(obj, handler);
}
// Make a default version of the freeze function.
const freeze = freezeTag();
module.exports = {freezeTag, freeze};