summaryrefslogtreecommitdiff
path: root/ext/js/general/object-property-accessor.js
blob: d50948d9d3113a0bf2c0d0fc1ab5ad83b540e212 (plain)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
 * Copyright (C) 2023-2024  Yomitan Authors
 * Copyright (C) 2016-2022  Yomichan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * Class used to get and mutate generic properties of an object by using path strings.
 */
export class ObjectPropertyAccessor {
    /**
     * Create a new accessor for a specific object.
     * @param {unknown} target The object which the getter and mutation methods are applied to.
     */
    constructor(target) {
        /** @type {unknown} */
        this._target = target;
    }

    /**
     * Gets the value at the specified path.
     * @param {(string|number)[]} pathArray The path to the property on the target object.
     * @param {number} [pathLength] How many parts of the pathArray to use.
     *   This parameter is optional and defaults to the length of pathArray.
     * @returns {unknown} The value found at the path.
     * @throws {Error} An error is thrown if pathArray is not valid for the target object.
     */
    get(pathArray, pathLength) {
        let target = this._target;
        const ii = typeof pathLength === 'number' ? Math.min(pathArray.length, pathLength) : pathArray.length;
        for (let i = 0; i < ii; ++i) {
            const key = pathArray[i];
            if (!ObjectPropertyAccessor.hasProperty(target, key)) {
                throw new Error(`Invalid path: ${ObjectPropertyAccessor.getPathString(pathArray.slice(0, i + 1))}`);
            }
            target = /** @type {import('core').SerializableObject} */ (target)[key];
        }
        return target;
    }

    /**
     * Sets the value at the specified path.
     * @param {(string|number)[]} pathArray The path to the property on the target object.
     * @param {unknown} value The value to assign to the property.
     * @throws {Error} An error is thrown if pathArray is not valid for the target object.
     */
    set(pathArray, value) {
        const ii = pathArray.length - 1;
        if (ii < 0) { throw new Error('Invalid path'); }

        const target = this.get(pathArray, ii);
        const key = pathArray[ii];
        if (!ObjectPropertyAccessor.isValidPropertyType(target, key)) {
            throw new Error(`Invalid path: ${ObjectPropertyAccessor.getPathString(pathArray)}`);
        }

        /** @type {import('core').SerializableObject} */ (target)[key] = value;
    }

    /**
     * Deletes the property of the target object at the specified path.
     * @param {(string|number)[]}pathArray The path to the property on the target object.
     * @throws {Error} An error is thrown if pathArray is not valid for the target object.
     */
    delete(pathArray) {
        const ii = pathArray.length - 1;
        if (ii < 0) { throw new Error('Invalid path'); }

        const target = this.get(pathArray, ii);
        const key = pathArray[ii];
        if (!ObjectPropertyAccessor.isValidPropertyType(target, key)) {
            throw new Error(`Invalid path: ${ObjectPropertyAccessor.getPathString(pathArray)}`);
        }

        if (Array.isArray(target)) {
            throw new Error('Invalid type');
        }

        delete /** @type {import('core').SerializableObject} */ (target)[key];
    }

    /**
     * Swaps two properties of an object or array.
     * @param {(string|number)[]} pathArray1 The path to the first property on the target object.
     * @param {(string|number)[]} pathArray2 The path to the second property on the target object.
     * @throws An error is thrown if pathArray1 or pathArray2 is not valid for the target object,
     *   or if the swap cannot be performed.
     */
    swap(pathArray1, pathArray2) {
        const ii1 = pathArray1.length - 1;
        if (ii1 < 0) { throw new Error('Invalid path 1'); }
        const target1 = this.get(pathArray1, ii1);
        const key1 = pathArray1[ii1];
        if (!ObjectPropertyAccessor.isValidPropertyType(target1, key1)) { throw new Error(`Invalid path 1: ${ObjectPropertyAccessor.getPathString(pathArray1)}`); }

        const ii2 = pathArray2.length - 1;
        if (ii2 < 0) { throw new Error('Invalid path 2'); }
        const target2 = this.get(pathArray2, ii2);
        const key2 = pathArray2[ii2];
        if (!ObjectPropertyAccessor.isValidPropertyType(target2, key2)) { throw new Error(`Invalid path 2: ${ObjectPropertyAccessor.getPathString(pathArray2)}`); }

        const value1 = /** @type {import('core').SerializableObject} */ (target1)[key1];
        const value2 = /** @type {import('core').SerializableObject} */ (target2)[key2];

        /** @type {import('core').SerializableObject} */ (target1)[key1] = value2;
        try {
            /** @type {import('core').SerializableObject} */ (target2)[key2] = value1;
        } catch (e) {
            // Revert
            try {
                /** @type {import('core').SerializableObject} */ (target1)[key1] = value1;
            } catch (e2) {
                // NOP
            }
            throw e;
        }
    }

    /**
     * Converts a path string to a path array.
     * @param {(string|number)[]} pathArray The path array to convert.
     * @returns {string} A string representation of `pathArray`.
     * @throws {Error} An error is thrown if any item of `pathArray` is not a string or an integer.
     */
    static getPathString(pathArray) {
        const regexShort = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
        let pathString = '';
        let first = true;
        for (let part of pathArray) {
            switch (typeof part) {
                case 'number':
                    if (Math.floor(part) !== part || part < 0) {
                        throw new Error('Invalid index');
                    }
                    part = `[${part}]`;
                    break;
                case 'string':
                    if (!regexShort.test(part)) {
                        const escapedPart = part.replace(/["\\]/g, '\\$&');
                        part = `["${escapedPart}"]`;
                    } else {
                        if (!first) {
                            part = `.${part}`;
                        }
                    }
                    break;
                default:
                    throw new Error(`Invalid type: ${typeof part}`);
            }
            pathString += part;
            first = false;
        }
        return pathString;
    }

    /**
     * Converts a path array to a path string. For the most part, the format of this string
     * matches Javascript's notation for property access.
     * @param {string} pathString The path string to convert.
     * @returns {(string | number)[]} An array representation of `pathString`.
     * @throws {Error} An error is thrown if `pathString` is malformed.
     */
    static getPathArray(pathString) {
        const pathArray = [];
        /** @type {import('object-property-accessor').ParsePathStringState} */
        let state = 'empty';
        let quote = 0;
        let value = '';
        let escaped = false;
        for (const c of pathString) {
            const v = /** @type {number} */ (c.codePointAt(0));
            switch (state) {
                case 'empty': // Empty
                case 'id-start': // Expecting identifier start
                    if (v === 0x5b) { // '['
                        if (state === 'id-start') {
                            throw new Error(`Unexpected character: ${c}`);
                        }
                        state = 'open-bracket';
                    } else if (
                        (v >= 0x41 && v <= 0x5a) || // ['A', 'Z']
                        (v >= 0x61 && v <= 0x7a) || // ['a', 'z']
                        v === 0x5f // '_'
                    ) {
                        state = 'id';
                        value += c;
                    } else {
                        throw new Error(`Unexpected character: ${c}`);
                    }
                    break;
                case 'id': // Identifier
                    if (
                        (v >= 0x41 && v <= 0x5a) || // ['A', 'Z']
                        (v >= 0x61 && v <= 0x7a) || // ['a', 'z']
                        (v >= 0x30 && v <= 0x39) || // ['0', '9']
                        v === 0x5f // '_'
                    ) {
                        value += c;
                    } else {
                        switch (v) {
                            case 0x5b: // '['
                                pathArray.push(value);
                                value = '';
                                state = 'open-bracket';
                                break;
                            case 0x2e: // '.'
                                pathArray.push(value);
                                value = '';
                                state = 'id-start';
                                break;
                            default:
                                throw new Error(`Unexpected character: ${c}`);
                        }
                    }
                    break;
                case 'open-bracket': // Open bracket
                    if (v === 0x22 || v === 0x27) { // '"' or '\''
                        quote = v;
                        state = 'string';
                    } else if (v >= 0x30 && v <= 0x39) { // ['0', '9']
                        state = 'number';
                        value += c;
                    } else {
                        throw new Error(`Unexpected character: ${c}`);
                    }
                    break;
                case 'string': // Quoted string
                    if (escaped) {
                        value += c;
                        escaped = false;
                    } else if (v === 0x5c) { // '\\'
                        escaped = true;
                    } else if (v !== quote) {
                        value += c;
                    } else {
                        state = 'close-bracket';
                    }
                    break;
                case 'number': // Number
                    if (v >= 0x30 && v <= 0x39) { // ['0', '9']
                        value += c;
                    } else if (v === 0x5d) { // ']'
                        pathArray.push(Number.parseInt(value, 10));
                        value = '';
                        state = 'next';
                    } else {
                        throw new Error(`Unexpected character: ${c}`);
                    }
                    break;
                case 'close-bracket': // Expecting closing bracket after quoted string
                    if (v === 0x5d) { // ']'
                        pathArray.push(value);
                        value = '';
                        state = 'next';
                    } else {
                        throw new Error(`Unexpected character: ${c}`);
                    }
                    break;
                case 'next': { // Expecting . or [
                    switch (v) {
                        case 0x5b: // '['
                            state = 'open-bracket';
                            break;
                        case 0x2e: // '.'
                            state = 'id-start';
                            break;
                        default:
                            throw new Error(`Unexpected character: ${c}`);
                    }
                    break;
                }
            }
        }
        switch (state) {
            case 'empty':
            case 'next':
                break;
            case 'id':
                pathArray.push(value);
                value = '';
                break;
            default:
                throw new Error('Path not terminated correctly');
        }
        return pathArray;
    }

    /**
     * Checks whether an object or array has the specified property.
     * @param {unknown} object The object to test.
     * @param {string|number} property The property to check for existence.
     *   This value should be a string if the object is a non-array object.
     *   For arrays, it should be an integer.
     * @returns {boolean} `true` if the property exists, otherwise `false`.
     */
    static hasProperty(object, property) {
        switch (typeof property) {
            case 'string':
                return (
                    typeof object === 'object' &&
                    object !== null &&
                    !Array.isArray(object) &&
                    Object.prototype.hasOwnProperty.call(object, property)
                );
            case 'number':
                return (
                    Array.isArray(object) &&
                    property >= 0 &&
                    property < object.length &&
                    property === Math.floor(property)
                );
            default:
                return false;
        }
    }

    /**
     * Checks whether a property is valid for the given object
     * @param {unknown} object The object to test.
     * @param {string|number} property The property to check for existence.
     * @returns {boolean} `true` if the property is correct for the given object type, otherwise `false`.
     *   For arrays, this means that the property should be a positive integer.
     *   For non-array objects, the property should be a string.
     */
    static isValidPropertyType(object, property) {
        switch (typeof property) {
            case 'string':
                return (
                    typeof object === 'object' &&
                    object !== null &&
                    !Array.isArray(object)
                );
            case 'number':
                return (
                    Array.isArray(object) &&
                    property >= 0 &&
                    property === Math.floor(property)
                );
            default:
                return false;
        }
    }
}