import type { IPlugin, JsepInstance, Expression, HookEnv } from 'nc-jsep/types'; const OCURLY_CODE = 123; // { const CCURLY_CODE = 125; // } const OBJECT_EXP = 'ObjectExpression'; const PROPERTY = 'Property'; interface Property { type: string; computed: boolean; key: Expression; value: Expression; shorthand: boolean; } const plugin: IPlugin = { name: 'object', init(jsep: JsepInstance) { // Object literal support function gobbleObjectExpression(this: JsepInstance, env: HookEnv) { if (this.code === OCURLY_CODE) { this.index++; const properties: (Property | Expression)[] = []; while (!isNaN(this.code)) { this.gobbleSpaces(); if (this.code === CCURLY_CODE) { this.index++; env.node = this.gobbleTokenProperty({ type: OBJECT_EXP, properties, }); return; } // Note: using gobbleExpression instead of gobbleToken to support object destructuring const key = this.gobbleExpression(); if (!key) { break; // missing } } this.gobbleSpaces(); if (key.type === jsep.IDENTIFIER && (this.code === jsep.COMMA_CODE || this.code === CCURLY_CODE)) { // property value shorthand properties.push({ type: PROPERTY, computed: false, key, value: key, shorthand: true, }); } else if (this.code === jsep.COLON_CODE) { this.index++; const value = this.gobbleExpression(); if (!value) { this.throwError('unexpected object property'); } const computed = key.type === jsep.ARRAY_EXP; const keyExpr = key as Expression & { elements?: Expression[] }; properties.push({ type: PROPERTY, computed, key: computed ? keyExpr.elements![0] : key, value: value, shorthand: false, }); this.gobbleSpaces(); } else if (key) { // spread, assignment (object destructuring with defaults), etc. properties.push(key); } if (this.code === jsep.COMMA_CODE) { this.index++; } } this.throwError('missing }'); } } jsep.hooks.add('gobble-token', gobbleObjectExpression); } }; export default plugin;