UNPKG

1.63 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.proxyWrap = exports.makeCallable = void 0;
4function makeCallable(func, object) {
5 Object.assign(func, object);
6 return func;
7}
8exports.makeCallable = makeCallable;
9function intercept(wrapper) {
10 return (target, property) => {
11 if (target[property]) {
12 if (wrapper[property]) {
13 const propertyType = typeof wrapper[property];
14 if (propertyType === 'function') {
15 wrapper[property](...arguments);
16 }
17 }
18 return target[property];
19 }
20 else {
21 if (wrapper[property]) {
22 return wrapper[property];
23 }
24 throw new Error('Tried to access an unititialized property.');
25 }
26 };
27}
28/**
29 * Wrap an object in a proxy
30 *
31 * If a wrapper is supplied, each of its properties will be added to the proxy.
32 * If a property is a function on the wrapper and target, the wrapper's function
33 * will be invoked and then the target's will be.
34 * If the proxy encounters a property that does not exist on the target or the
35 * wrapper, it will throw an error.
36 *
37 * @param target The object what will be wrapped in a proxy
38 * @param wrapper An optional object whose properties will be added to the proxy
39 */
40function proxyWrap(target, wrapper) {
41 const proxy = new Proxy(target, {
42 get: intercept(wrapper || {}),
43 set() {
44 throw new Error('Tried to update a readonly object.');
45 },
46 });
47 return [target, proxy];
48}
49exports.proxyWrap = proxyWrap;