@traqula/core 0.0.23 → 0.0.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +2 -0
  2. package/dist/cjs/lib/AstCoreFactory.js +181 -149
  3. package/dist/cjs/lib/AstCoreFactory.js.map +1 -0
  4. package/dist/cjs/lib/generator-builder/builderTypes.js +2 -15
  5. package/dist/cjs/lib/generator-builder/builderTypes.js.map +1 -0
  6. package/dist/cjs/lib/generator-builder/dynamicGenerator.js +209 -200
  7. package/dist/cjs/lib/generator-builder/dynamicGenerator.js.map +1 -0
  8. package/dist/cjs/lib/generator-builder/generatorBuilder.js +103 -117
  9. package/dist/cjs/lib/generator-builder/generatorBuilder.js.map +1 -0
  10. package/dist/cjs/lib/generator-builder/generatorTypes.js +2 -15
  11. package/dist/cjs/lib/generator-builder/generatorTypes.js.map +1 -0
  12. package/dist/cjs/lib/index.js +39 -57
  13. package/dist/cjs/lib/index.js.map +1 -0
  14. package/dist/cjs/lib/indirection-builder/IndirBuilder.js +63 -85
  15. package/dist/cjs/lib/indirection-builder/IndirBuilder.js.map +1 -0
  16. package/dist/cjs/lib/indirection-builder/dynamicIndirected.js +28 -50
  17. package/dist/cjs/lib/indirection-builder/dynamicIndirected.js.map +1 -0
  18. package/dist/cjs/lib/indirection-builder/helpers.js +11 -31
  19. package/dist/cjs/lib/indirection-builder/helpers.js.map +1 -0
  20. package/dist/cjs/lib/lexer-builder/LexerBuilder.js +92 -114
  21. package/dist/cjs/lib/lexer-builder/LexerBuilder.js.map +1 -0
  22. package/dist/cjs/lib/parser-builder/builderTypes.js +2 -15
  23. package/dist/cjs/lib/parser-builder/builderTypes.js.map +1 -0
  24. package/dist/cjs/lib/parser-builder/dynamicParser.js +116 -136
  25. package/dist/cjs/lib/parser-builder/dynamicParser.js.map +1 -0
  26. package/dist/cjs/lib/parser-builder/parserBuilder.js +167 -169
  27. package/dist/cjs/lib/parser-builder/parserBuilder.js.map +1 -0
  28. package/dist/cjs/lib/parser-builder/ruleDefTypes.js +2 -15
  29. package/dist/cjs/lib/parser-builder/ruleDefTypes.js.map +1 -0
  30. package/dist/cjs/lib/transformers/TransformerObject.js +196 -198
  31. package/dist/cjs/lib/transformers/TransformerObject.js.map +1 -0
  32. package/dist/cjs/lib/transformers/TransformerSubTyped.js +110 -141
  33. package/dist/cjs/lib/transformers/TransformerSubTyped.js.map +1 -0
  34. package/dist/cjs/lib/transformers/TransformerTyped.js +87 -120
  35. package/dist/cjs/lib/transformers/TransformerTyped.js.map +1 -0
  36. package/dist/cjs/lib/types.js +2 -15
  37. package/dist/cjs/lib/types.js.map +1 -0
  38. package/dist/cjs/lib/utils.js +20 -34
  39. package/dist/cjs/lib/utils.js.map +1 -0
  40. package/dist/esm/lib/AstCoreFactory.d.ts +19 -7
  41. package/dist/esm/lib/AstCoreFactory.js +50 -5
  42. package/dist/esm/lib/AstCoreFactory.js.map +1 -1
  43. package/dist/esm/lib/generator-builder/dynamicGenerator.d.ts +5 -0
  44. package/dist/esm/lib/generator-builder/dynamicGenerator.js +20 -0
  45. package/dist/esm/lib/generator-builder/dynamicGenerator.js.map +1 -1
  46. package/dist/esm/lib/parser-builder/dynamicParser.js +1 -0
  47. package/dist/esm/lib/parser-builder/dynamicParser.js.map +1 -1
  48. package/dist/esm/lib/parser-builder/parserBuilder.js +2 -2
  49. package/dist/esm/lib/parser-builder/parserBuilder.js.map +1 -1
  50. package/dist/esm/lib/transformers/TransformerObject.d.ts +1 -1
  51. package/dist/esm/lib/transformers/TransformerObject.js.map +1 -1
  52. package/dist/esm/lib/transformers/TransformerSubTyped.d.ts +31 -22
  53. package/dist/esm/lib/transformers/TransformerSubTyped.js +30 -40
  54. package/dist/esm/lib/transformers/TransformerSubTyped.js.map +1 -1
  55. package/dist/esm/lib/transformers/TransformerTyped.d.ts +24 -20
  56. package/dist/esm/lib/transformers/TransformerTyped.js +23 -35
  57. package/dist/esm/lib/transformers/TransformerTyped.js.map +1 -1
  58. package/dist/esm/lib/types.d.ts +67 -5
  59. package/dist/esm/lib/types.js.map +1 -1
  60. package/dist/esm/lib/utils.d.ts +10 -0
  61. package/dist/esm/lib/utils.js +7 -0
  62. package/dist/esm/lib/utils.js.map +1 -1
  63. package/package.json +9 -9
  64. package/dist/cjs/test/generatorBuilder/generatorBuilder.types.test.js +0 -30
  65. package/dist/cjs/test/grammar-builder/parserBuilder.types.test.js +0 -27
  66. package/dist/cjs/test/transformer.test.js +0 -82
  67. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.d.ts +0 -1
  68. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.js +0 -38
  69. package/dist/esm/test/generatorBuilder/generatorBuilder.types.test.js.map +0 -1
  70. package/dist/esm/test/grammar-builder/parserBuilder.types.test.d.ts +0 -1
  71. package/dist/esm/test/grammar-builder/parserBuilder.types.test.js +0 -38
  72. package/dist/esm/test/grammar-builder/parserBuilder.types.test.js.map +0 -1
  73. package/dist/esm/test/transformer.test.d.ts +0 -1
  74. package/dist/esm/test/transformer.test.js +0 -82
  75. package/dist/esm/test/transformer.test.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parserBuilder.js","sourceRoot":"","sources":["../../../../lib/parser-builder/parserBuilder.ts"],"names":[],"mappings":";;;AAQA,sEAAgE;AAShE,yDAAmD;AAGnD;;GAEG;AACH,SAAS,gBAAgB,CAAkC,KAAQ;IACjE,MAAM,QAAQ,GAA+B,EAAE,CAAC;IAChD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC7B,CAAC;IACD,OAA8B,QAAQ,CAAC;AACzC,CAAC;AAUD;;;;;GAKG;AACH,iDAAiD;AACjD,MAAa,aAAa;IACxB;;;OAGG;IACI,MAAM,CAAC,MAAM,CAMlB,KAAsD;QAEtD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EA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;QACD,OAAmD,oBAAoB,CAAC;IAC1E,CAAC;IAEO,OAAO,CAAC,EAAE,eAAe,EAAE,MAAM,GAAG,EAAE,EAG7C;QAEC,OACuD,IAAI,gCAAa,CAAC,IAAI,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,CAAC;IAChH,CAAC;CACF;AAhQD,sCAgQC","sourcesContent":["import type {\n ILexerConfig,\n IParserConfig,\n IRecognitionException,\n TokenType,\n TokenVocabulary,\n EmbeddedActionsParser,\n} from '@traqula/chevrotain';\nimport { LexerBuilder } from '../lexer-builder/LexerBuilder.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type {\n ParseMethodsFromRules,\n ParserFromRules,\n ParseRuleMap,\n ParseRulesToObject,\n ParseNamesFromList,\n} from './builderTypes.js';\nimport { DynamicParser } from './dynamicParser.js';\nimport type { ParserRule } from './ruleDefTypes.js';\n\n/**\n * Converts a list of ruledefs to a record mapping a name to the corresponding ruledef.\n */\nfunction listToRuleDefMap<T extends readonly ParserRule[]>(rules: T): ParseRulesToObject<T> {\n const newRules: Record<string, ParserRule> = {};\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <ParseRulesToObject<T>>newRules;\n}\n\nexport interface ParserBuildArgs {\n tokenVocabulary: readonly TokenType[];\n parserConfig?: IParserConfig;\n lexerConfig?: ILexerConfig;\n queryPreProcessor?: (input: string) => string;\n errorHandler?: (errors: IRecognitionException[]) => void;\n}\n\n/**\n * The grammar builder. This is the core of traqula (besides using the amazing chevrotain framework).\n * Using the builder you can create a grammar + AST creator.\n * At any point in time, a parser can be constructed from the added rules.\n * Constructing a parser will cause a validation which will validate the correctness of the grammar.\n */\n// This code is wild so other code can be simple.\nexport class ParserBuilder<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>> {\n /**\n * Create a builder from some initial grammar rules or an existing builder.\n * If a builder is provided, a new copy will be created.\n */\n public static create<\n Rules extends readonly ParserRule[] = readonly ParserRule[],\n Context = Rules[0] extends ParserRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends ParseRuleMap<Names> = ParseRulesToObject<Rules>,\n >(\n start: Rules | ParserBuilder<Context, Names, RuleDefs>,\n ): ParserBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <ParserBuilder<Context, Names, RuleDefs>> <unknown> new ParserBuilder(listToRuleDefMap(start));\n }\n return new ParserBuilder({ ...(<ParserBuilder<any, any, any>>start).rules });\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n public widenContext<NewContext extends Context>(): ParserBuilder<\n NewContext,\nNames,\n{[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends ParserRule<any, any, infer RT, infer PT> ? ParserRule<NewContext, Key, RT, PT> : never)\n : never }\n> {\n return <any> this;\n }\n\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n ParserBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? ParserRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer yourself\n Patch[Key] extends [any] ? (\n RuleDefs[Key] extends ParserRule<any, any, any, infer Par> ?\n ParserRule<Context, Key, Patch[Key][0], Par> : never\n ) : never\n )\n ) : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing grammar rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }>>\n <unknown> this;\n self.rules[patch.name] = <any> patch;\n return self;\n }\n\n /**\n * Add a rule to the grammar. If the rule already exists, but the implementation differs, an error will be thrown.\n */\n public addRuleRedundant<U extends string, RET, ARGS extends any[]>(rule: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never)\n }> {\n const self = <ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }>>\n <unknown> this;\n const rules = <Record<string, ParserRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the builder`);\n }\n rules[rule.name] = rule;\n return self;\n }\n\n /**\n * Add a rule to the grammar. Will raise a typescript error if the rule already exists in the grammar.\n */\n public addRule<U extends string, RET, ARGS extends any[]>(\n rule: CheckOverlap<U, Names, ParserRule<Context, U, RET, ARGS>>,\n ): ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }> {\n return this.addRuleRedundant(rule);\n }\n\n public addMany<U extends readonly ParserRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): ParserBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof ParseRulesToObject<typeof rules> ? (\n ParseRulesToObject<typeof rules>[K] extends ParserRule<Context, K> ? ParseRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never\n )\n }\n > {\n this.rules = { ...this.rules, ...listToRuleDefMap(rules) };\n return <any> <unknown> this;\n }\n\n /**\n * Delete a grammar rule by its name.\n */\n public deleteRule<U extends Names>(ruleName: U):\n ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends ParserRule<any, U, infer RT, infer PT> ?\n ParserRule<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this grammar builder with another.\n * It is best to merge the bigger grammar with the smaller one.\n * If the two builders both have a grammar rule with the same name,\n * no error will be thrown case they map to the same ruledef object.\n * If they map to a different object, an error will be thrown.\n * To fix this problem, the overridingRules array should contain a rule with the same conflicting name,\n * this rule implementation will be used.\n */\n public merge<\n OtherNames extends string,\n OtherRules extends ParseRuleMap<OtherNames>,\n OW extends readonly ParserRule<Context>[],\n >(\n builder: ParserBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n ParserBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof ParseRulesToObject<OW> ? (\n ParseRulesToObject<OW>[K] extends ParserRule<Context, K> ? ParseRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends ParserRule<Context, K> ? OtherRules[K] : never) : never\n ) }\n > {\n // Assume the other grammar is bigger than yours. So start from that one and add this one\n const otherRules: Record<string, ParserRule<Context>> = { ...builder.rules };\n const myRules: Record<string, ParserRule<Context>> = this.rules;\n\n for (const rule of Object.values(myRules)) {\n if (otherRules[rule.name] === undefined) {\n otherRules[rule.name] = rule;\n } else {\n const existingRule = otherRules[rule.name];\n // If same rule, no issue, move on. Else\n if (existingRule !== rule) {\n const override = overridingRules.find(x => x.name === rule.name);\n // If override specified, take override, else, inform user that there is a conflict\n if (override) {\n otherRules[rule.name] = override;\n } else {\n throw new Error(`Rule with name \"${rule.name}\" already exists in the builder, specify an override to resolve conflict`);\n }\n }\n }\n }\n\n this.rules = <any> <unknown> otherRules;\n return <any> <unknown> this;\n }\n\n private defaultErrorHandler(input: string, errors: IRecognitionException[]): void {\n const firstError = errors[0];\n const messageBuilder: string[] = [ 'Parse error' ];\n const lineIdx = firstError.token.startLine;\n if (lineIdx !== undefined && !Number.isNaN(lineIdx)) {\n const errorLine = input.split('\\n')[lineIdx - 1];\n messageBuilder.push(` on line ${lineIdx}\n${errorLine}`);\n const columnIdx = firstError.token.startColumn;\n if (columnIdx !== undefined) {\n messageBuilder.push(`\\n${'-'.repeat(columnIdx - 1)}^`);\n }\n }\n messageBuilder.push(`\\n${firstError.message}`);\n throw new Error(messageBuilder.join(''));\n }\n\n public build({\n tokenVocabulary,\n parserConfig = {},\n lexerConfig = {},\n queryPreProcessor = s => s,\n errorHandler,\n }: ParserBuildArgs): ParserFromRules<Context, Names, RuleDefs> {\n const lexer = LexerBuilder.create().add(...tokenVocabulary).build({\n positionTracking: 'onlyOffset',\n recoveryEnabled: false,\n ensureOptimizations: true,\n safeMode: false,\n skipValidations: true,\n ...lexerConfig,\n });\n // Get the chevrotain parser\n const parser = this.consume({\n tokenVocabulary: <TokenType[]> tokenVocabulary,\n config: parserConfig,\n });\n // Start building a parser that does not pass input using a state, but instead gets it as a function argument.\n const selfSufficientParser: Partial<ParserFromRules<Context, Names, RuleDefs>> = {};\n\n // To do that, we need to create a wrapper for each parser rule.\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <ParserRule<Context, Names>[]> Object.values(this.rules)) {\n selfSufficientParser[rule.name] = <any> ((input: string, context: Context, ...args: unknown[]) => {\n const processedInput = queryPreProcessor(input);\n const lexResult = lexer.tokenize(processedInput);\n\n // This also resets the parser\n parser.input = lexResult.tokens;\n parser.setContext(context);\n const result = parser[rule.name](context, ...args);\n if (parser.errors.length > 0) {\n // Console.log(JSON.stringify(lexResult, null, 2));\n if (errorHandler) {\n errorHandler(parser.errors);\n } else {\n this.defaultErrorHandler(processedInput, parser.errors);\n }\n }\n return result;\n });\n }\n return <ParserFromRules<Context, Names, RuleDefs>> selfSufficientParser;\n }\n\n private consume({ tokenVocabulary, config = {}}: {\n tokenVocabulary: TokenVocabulary;\n config?: IParserConfig;\n }): EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void } {\n return <EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void }><unknown> new DynamicParser(this.rules, tokenVocabulary, config);\n }\n}\n"]}
@@ -1,16 +1,3 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
- var ruleDefTypes_exports = {};
16
- module.exports = __toCommonJS(ruleDefTypes_exports);
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=ruleDefTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ruleDefTypes.js","sourceRoot":"","sources":["../../../../lib/parser-builder/ruleDefTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AtLeastOneSepMethodOpts,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n ManySepMethodOpts,\n OrMethodOpts,\n ConsumeMethodOpts,\n IToken,\n TokenType,\n} from '@traqula/chevrotain';\n\n/**\n * Get the return-type of a RuleDef\n */\nexport type RuleDefReturn<T extends ParserRule> = T extends ParserRule<any, string, infer Ret> ? Ret : never;\n\n/**\n * Type used to declare grammar rules.\n */\nexport type ParserRule<\n /**\n * Context object available in rule implementation.\n */\n Context = any,\n /**\n * Name of grammar rule, should be a strict subtype of string like 'myGrammarRule'.\n */\n NameType extends string = string,\n /**\n * Type that will be returned after a correct parse of this rule.\n * This type will be the return type of calling SUBRULE with this grammar rule.\n */\n ReturnType = unknown,\n /**\n * Function arguments that can be given to convey the state of the current parse operation.\n */\n ParamType extends any[] = any[],\n> = {\n name: NameType;\n impl: (def: ImplArgs) => (context: Context, ...params: ParamType) => ReturnType;\n};\n\n/**\n * Type expected by grammar rules in the main `impl` function.\n */\nexport interface ImplArgs extends CstDef {\n cache: WeakMap<ParserRule, unknown>;\n}\n\n/**\n * Type definition used by {@link CstDef.SUBRULE} and family.\n */\ntype SubRuleFunc = <T extends string, U = unknown, ARGS extends any[] = any>(\n cstDef: ParserRule<any, T, U, ARGS>,\n ...argument: ARGS\n) => U;\n/**\n * Type definition used by {@link CstDef.BACKTRACK}.\n */\ntype BacktrackFunc = <T extends string, U = unknown, ARGS extends any[] = any>(\n cstDef: ParserRule<any, T, U, ARGS>,\n ...argument: ARGS\n) => () => boolean;\n\n/**\n * Mainly a repetition of the functions exposed by the {@link EmbeddedActionsParser},\n * with some small adjustments that allow for the API changes made by traqula.\n * Specifically changes are made to the {@link CstDef.SUBRULE} (and family) interface,\n * and to the {@link CstDef.BACKTRACK} interface.\n */\nexport interface CstDef {\n /**\n *\n * A Parsing DSL method use to consume a single Token.\n * In EBNF terms this is equivalent to a Terminal.\n *\n * A Token will be consumed, IFF the next token in the token vector matches `tokType`.\n * otherwise the parser may attempt to perform error recovery (if enabled).\n *\n * The index in the method name indicates the unique occurrence of a terminal consumption\n * inside a the top level rule. What this means is that if a terminal appears\n * more than once in a single rule, each appearance must have a **different** index.\n *\n * For example:\n * ```\n * this.RULE(\"qualifiedName\", () => {\n * this.CONSUME1(Identifier);\n * this.MANY(() => {\n * this.CONSUME1(Dot);\n * // here we use CONSUME2 because the terminal\n * // 'Identifier' has already appeared previously in the\n * // the rule 'parseQualifiedName'\n * this.CONSUME2(Identifier);\n * });\n * })\n * ```\n *\n * - See more details on the [unique suffixes requirement](http://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES).\n *\n * @param tokType - The Type of the token to be consumed.\n * @param options - optional properties to modify the behavior of CONSUME.\n */\n CONSUME: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME1: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME2: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME3: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME4: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME5: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME6: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME7: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME8: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n CONSUME9: (tokType: TokenType, options?: ConsumeMethodOpts) => IToken;\n /**\n * Parsing DSL Method that Indicates an Optional production.\n * in EBNF notation this is equivalent to: \"[...]\".\n *\n * Note that there are two syntax forms:\n * - Passing the grammar action directly:\n * ```\n * this.OPTION(() => {\n * this.CONSUME(Digit)}\n * );\n * ```\n *\n * - using an \"options\" object:\n * ```\n * this.OPTION({\n * GATE:predicateFunc,\n * DEF: () => {\n * this.CONSUME(Digit)\n * }});\n * ```\n *\n * The optional 'GATE' property in \"options\" object form can be used to add constraints\n * to invoking the grammar action.\n *\n * As in CONSUME the index in the method name indicates the occurrence\n * of the optional production in it's top rule.\n *\n * @param actionORMethodDef - The grammar action to optionally invoke once\n * or an \"OPTIONS\" object describing the grammar action and optional properties.\n *\n * @returns The `GrammarAction` return value (OUT) if the optional syntax is encountered\n * or `undefined` if not.\n */\n OPTION: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION1: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION2: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION3: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION4: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION5: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION6: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION7: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION8: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n OPTION9: <OUT>(\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ) => OUT | undefined;\n /**\n * Parsing DSL method that indicates a choice between a set of alternatives must be made.\n * This is equivalent to an EBNF alternation (A | B | C | D ...), except\n * that the alternatives are ordered like in a PEG grammar.\n * This means that the **first** matching alternative is always chosen.\n *\n * There are several forms for the inner alternatives array:\n *\n * - Passing alternatives array directly:\n * ```\n * this.OR([\n * { ALT:() => { this.CONSUME(One) }},\n * { ALT:() => { this.CONSUME(Two) }},\n * { ALT:() => { this.CONSUME(Three) }}\n * ])\n * ```\n *\n * - Passing alternative array directly with predicates (GATE):\n * ```\n * this.OR([\n * { GATE: predicateFunc1, ALT:() => { this.CONSUME(One) }},\n * { GATE: predicateFuncX, ALT:() => { this.CONSUME(Two) }},\n * { GATE: predicateFuncX, ALT:() => { this.CONSUME(Three) }}\n * ])\n * ```\n *\n * - These syntax forms can also be mixed:\n * ```\n * this.OR([\n * {\n * GATE: predicateFunc1,\n * ALT:() => { this.CONSUME(One) }\n * },\n * { ALT:() => { this.CONSUME(Two) }},\n * { ALT:() => { this.CONSUME(Three) }}\n * ])\n * ```\n *\n * - Additionally an \"options\" object may be used:\n * ```\n * this.OR({\n * DEF:[\n * { ALT:() => { this.CONSUME(One) }},\n * { ALT:() => { this.CONSUME(Two) }},\n * { ALT:() => { this.CONSUME(Three) }}\n * ],\n * // OPTIONAL property\n * ERR_MSG: \"A Number\"\n * })\n * ```\n *\n * The 'predicateFuncX' in the long form can be used to add constraints to choosing the alternative.\n *\n * As in CONSUME the index in the method name indicates the occurrence\n * of the alternation production in it's top rule.\n *\n * @param altsOrOpts - A set of alternatives or an \"OPTIONS\" object describing the alternatives\n * and optional properties.\n *\n * @returns The result of invoking the chosen alternative.\n */\n OR: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR1: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR2: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR3: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR4: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR5: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR6: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR7: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR8: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n OR9: <T>(altsOrOpts: IOrAlt<T>[] | OrMethodOpts<T>) => T;\n /**\n * Parsing DSL method, that indicates a repetition of zero or more.\n * This is equivalent to EBNF repetition \\{...\\}.\n *\n * Note that there are two syntax forms:\n * - Passing the grammar action directly:\n * ```\n * this.MANY(() => {\n * this.CONSUME(Comma)\n * this.CONSUME(Digit)\n * })\n * ```\n *\n * - using an \"options\" object:\n * ```\n * this.MANY({\n * GATE: predicateFunc,\n * DEF: () => {\n * this.CONSUME(Comma)\n * this.CONSUME(Digit)\n * }\n * });\n * ```\n *\n * The optional 'GATE' property in \"options\" object form can be used to add constraints\n * to invoking the grammar action.\n *\n * As in CONSUME the index in the method name indicates the occurrence\n * of the repetition production in it's top rule.\n *\n * @param actionORMethodDef - The grammar action to optionally invoke multiple times\n * or an \"OPTIONS\" object describing the grammar action and optional properties.\n *\n */\n MANY: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY1: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY2: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY3: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY4: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY5: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY6: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY7: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY8: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n MANY9: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ) => void;\n /**\n * Parsing DSL method, that indicates a repetition of zero or more with a separator\n * Token between the repetitions.\n *\n * Example:\n *\n * ```\n * this.MANY_SEP({\n * SEP:Comma,\n * DEF: () => {\n * this.CONSUME(Number};\n * // ...\n * })\n * ```\n *\n * Note that because this DSL method always requires more than one argument the options object is always required\n * and it is not possible to use a shorter form like in the MANY DSL method.\n *\n * Note that for the purposes of deciding on whether or not another iteration exists\n * Only a single Token is examined (The separator). Therefore if the grammar being implemented is\n * so \"crazy\" to require multiple tokens to identify an item separator please use the more basic DSL methods\n * to implement it.\n *\n * As in CONSUME the index in the method name indicates the occurrence\n * of the repetition production in it's top rule.\n *\n * @param options - An object defining the grammar of each iteration and the separator between iterations\n *\n */\n MANY_SEP: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP1: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP2: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP3: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP4: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP5: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP6: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP7: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP8: (options: ManySepMethodOpts<any>) => void;\n MANY_SEP9: (options: ManySepMethodOpts<any>) => void;\n /**\n * Convenience method, same as MANY but the repetition is of one or more.\n * failing to match at least one repetition will result in a parsing error and\n * cause a parsing error.\n *\n * @see MANY\n *\n * @param actionORMethodDef - The grammar action to optionally invoke multiple times\n * or an \"OPTIONS\" object describing the grammar action and optional properties.\n *\n */\n AT_LEAST_ONE: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE1: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE2: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE3: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE4: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE5: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE6: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE7: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE8: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n AT_LEAST_ONE9: (\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ) => void;\n /**\n * Convenience method, same as MANY_SEP but the repetition is of one or more.\n * failing to match at least one repetition will result in a parsing error and\n * cause the parser to attempt error recovery.\n *\n * Note that an additional optional property ERR_MSG can be used to provide custom error messages.\n *\n * @see MANY_SEP\n *\n * @param options - An object defining the grammar of each iteration and the separator between iterations\n *\n * @return ISeparatedIterationResult<OUT>\n */\n AT_LEAST_ONE_SEP: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP1: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP2: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP3: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP4: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP5: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP6: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP7: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP8: (options: AtLeastOneSepMethodOpts<any>) => void;\n AT_LEAST_ONE_SEP9: (options: AtLeastOneSepMethodOpts<any>) => void;\n /**\n * Perform an action that is only executed during actual parsing and not during parser initialization.\n * (When a lot of this secretly return null)\n * @param impl\n * @constructor\n */\n ACTION: <T>(impl: () => T) => T;\n BACKTRACK: BacktrackFunc;\n SUBRULE: SubRuleFunc;\n SUBRULE1: SubRuleFunc;\n SUBRULE2: SubRuleFunc;\n SUBRULE3: SubRuleFunc;\n SUBRULE4: SubRuleFunc;\n SUBRULE5: SubRuleFunc;\n SUBRULE6: SubRuleFunc;\n SUBRULE7: SubRuleFunc;\n SUBRULE8: SubRuleFunc;\n SUBRULE9: SubRuleFunc;\n}\n"]}
@@ -1,213 +1,211 @@
1
1
  "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var TransformerObject_exports = {};
20
- __export(TransformerObject_exports, {
21
- TransformerObject: () => TransformerObject
22
- });
23
- module.exports = __toCommonJS(TransformerObject_exports);
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TransformerObject = void 0;
24
4
  class TransformerObject {
25
- defaultContext;
26
- maxStackSize = 1e6;
27
- /**
28
- * Creates stateless transformer.
29
- * @param defaultContext
30
- */
31
- constructor(defaultContext = {}) {
32
- this.defaultContext = defaultContext;
33
- }
34
- clone(newDefaultContext = {}) {
35
- return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });
36
- }
37
- /**
38
- * Function to shallow clone any type.
39
- * @param obj
40
- * @protected
41
- */
42
- cloneObj(obj) {
43
- if (obj === null || typeof obj !== "object") {
44
- return obj;
5
+ defaultContext;
6
+ maxStackSize = 1_000_000;
7
+ /**
8
+ * Creates stateless transformer.
9
+ * @param defaultContext
10
+ */
11
+ constructor(defaultContext = {}) {
12
+ this.defaultContext = defaultContext;
45
13
  }
46
- const proto = Object.getPrototypeOf(obj);
47
- if (proto === Object.prototype || proto === null) {
48
- return { ...obj };
14
+ clone(newDefaultContext = {}) {
15
+ return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });
49
16
  }
50
- return Object.assign(Object.create(proto), obj);
51
- }
52
- /**
53
- * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.
54
- * @param startObject object to start iterating from
55
- * @param mapper mapper to transform the various objects - argument is a copy of the original
56
- * @param preVisitor callback that is evaluated before iterating deeper.
57
- * If continues is false, we do not iterate deeper, current object is still mapped. - default: true
58
- * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.
59
- * - Default false
60
- */
61
- transformObject(startObject, mapper, preVisitor = () => ({})) {
62
- const defaults = this.defaultContext;
63
- const defaultCopyFlag = defaults.copy ?? true;
64
- const defaultContinues = defaults.continue ?? true;
65
- const defaultIgnoreKeys = defaults.ignoreKeys;
66
- const defaultShallowKeys = defaults.shallowKeys;
67
- const defaultDidShortCut = defaults.shortcut ?? false;
68
- let didShortCut = false;
69
- const resultWrap = { res: startObject };
70
- const stack = [startObject];
71
- const stackParent = [resultWrap];
72
- const stackParentKey = ["res"];
73
- const handleMapperOnLen = [];
74
- const mapperCopyStack = [];
75
- const mapperOrigStack = [];
76
- const mapperParent = [];
77
- const mapperParentKey = [];
78
- function handleMapper() {
79
- while (stack.length === handleMapperOnLen.at(-1)) {
80
- handleMapperOnLen.pop();
81
- const copyToMap = mapperCopyStack.pop();
82
- const origToMap = mapperOrigStack.pop();
83
- const parent = mapperParent.pop();
84
- const parentKey = mapperParentKey.pop();
85
- parent[parentKey] = mapper(copyToMap, origToMap);
86
- }
17
+ /**
18
+ * Function to shallow clone any type.
19
+ * @param obj
20
+ * @protected
21
+ */
22
+ cloneObj(obj) {
23
+ if (obj === null || typeof obj !== 'object') {
24
+ return obj;
25
+ }
26
+ const proto = Object.getPrototypeOf(obj);
27
+ // Fast path: plain object
28
+ if (proto === Object.prototype || proto === null) {
29
+ // Spread or assign preserves fast properties
30
+ return { ...obj };
31
+ }
32
+ // Otherwise, preserve prototype for custom objects
33
+ return Object.assign(Object.create(proto), obj);
87
34
  }
88
- while (stack.length > 0 && stack.length < this.maxStackSize) {
89
- const curObject = stack.pop();
90
- const curParent = stackParent.pop();
91
- const curKey = stackParentKey.pop();
92
- if (!didShortCut) {
93
- if (Array.isArray(curObject)) {
94
- const newArr = [...curObject];
95
- handleMapperOnLen.push(stack.length);
96
- mapperCopyStack.push(newArr);
97
- mapperOrigStack.push(curObject);
98
- mapperParent.push(curParent);
99
- mapperParentKey.push(curKey);
100
- for (let index = curObject.length - 1; index >= 0; index--) {
101
- const val = curObject[index];
102
- if (val !== null && typeof val === "object") {
103
- stack.push(val);
104
- stackParent.push(newArr);
105
- stackParentKey.push(index.toString());
35
+ /**
36
+ * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.
37
+ * @param startObject object to start iterating from
38
+ * @param mapper mapper to transform the various objects - argument is a copy of the original
39
+ * @param preVisitor callback that is evaluated before iterating deeper.
40
+ * If continues is false, we do not iterate deeper, current object is still mapped. - default: true
41
+ * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.
42
+ * - Default false
43
+ */
44
+ transformObject(startObject, mapper, preVisitor = () => ({})) {
45
+ const defaults = this.defaultContext;
46
+ const defaultCopyFlag = defaults.copy ?? true;
47
+ const defaultContinues = defaults.continue ?? true;
48
+ const defaultIgnoreKeys = defaults.ignoreKeys;
49
+ const defaultShallowKeys = defaults.shallowKeys;
50
+ const defaultDidShortCut = defaults.shortcut ?? false;
51
+ // Code handles own stack instead of using recursion - this optimizes it for deep operations.
52
+ let didShortCut = false;
53
+ const resultWrap = { res: startObject };
54
+ // Grows with stack
55
+ const stack = [startObject];
56
+ const stackParent = [resultWrap];
57
+ const stackParentKey = ['res'];
58
+ // Grows with reverse stack - when popping down the stack, you realise you still want to map something.
59
+ // Counter of stack size when we started adding the children of this object, going beyond this means a new parent
60
+ const handleMapperOnLen = [];
61
+ const mapperCopyStack = [];
62
+ const mapperOrigStack = [];
63
+ const mapperParent = [];
64
+ const mapperParentKey = [];
65
+ function handleMapper() {
66
+ while (stack.length === handleMapperOnLen.at(-1)) {
67
+ handleMapperOnLen.pop();
68
+ const copyToMap = mapperCopyStack.pop();
69
+ const origToMap = mapperOrigStack.pop();
70
+ const parent = mapperParent.pop();
71
+ const parentKey = mapperParentKey.pop();
72
+ parent[parentKey] = mapper(copyToMap, origToMap);
106
73
  }
107
- }
108
- handleMapper();
109
- continue;
110
74
  }
111
- const context = preVisitor(curObject);
112
- const copyFlag = context.copy ?? defaultCopyFlag;
113
- const continues = context.continue ?? defaultContinues;
114
- const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;
115
- const shallowKeys = context.shallowKeys ?? defaultShallowKeys;
116
- didShortCut = context.shortcut ?? defaultDidShortCut;
117
- const copy = copyFlag ? this.cloneObj(curObject) : curObject;
118
- handleMapperOnLen.push(stack.length);
119
- mapperCopyStack.push(copy);
120
- mapperOrigStack.push(curObject);
121
- mapperParent.push(curParent);
122
- mapperParentKey.push(curKey);
123
- if (continues && !didShortCut) {
124
- for (const key in copy) {
125
- if (!Object.hasOwn(copy, key)) {
126
- continue;
127
- }
128
- const val = copy[key];
129
- const onlyShallow = shallowKeys && shallowKeys?.has(key);
130
- if (onlyShallow) {
131
- copy[key] = this.cloneObj(val);
132
- }
133
- if (ignoreKeys && ignoreKeys.has(key)) {
134
- continue;
75
+ while (stack.length > 0 && stack.length < this.maxStackSize) {
76
+ const curObject = stack.pop();
77
+ const curParent = stackParent.pop();
78
+ const curKey = stackParentKey.pop();
79
+ // Only add to the stack when you did not shortcut
80
+ if (!didShortCut) {
81
+ if (Array.isArray(curObject)) {
82
+ const newArr = [...curObject];
83
+ handleMapperOnLen.push(stack.length);
84
+ mapperCopyStack.push(newArr);
85
+ mapperOrigStack.push(curObject);
86
+ mapperParent.push(curParent);
87
+ mapperParentKey.push(curKey);
88
+ for (let index = curObject.length - 1; index >= 0; index--) {
89
+ const val = curObject[index];
90
+ if (val !== null && typeof val === 'object') {
91
+ stack.push(val);
92
+ stackParent.push(newArr);
93
+ stackParentKey.push(index.toString());
94
+ }
95
+ }
96
+ handleMapper();
97
+ continue;
98
+ }
99
+ // Perform pre visit before expanding the stack
100
+ const context = preVisitor(curObject);
101
+ const copyFlag = context.copy ?? defaultCopyFlag;
102
+ const continues = context.continue ?? defaultContinues;
103
+ const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;
104
+ const shallowKeys = context.shallowKeys ?? defaultShallowKeys;
105
+ didShortCut = context.shortcut ?? defaultDidShortCut;
106
+ const copy = copyFlag ? this.cloneObj(curObject) : curObject;
107
+ // Register that you want to be visited
108
+ handleMapperOnLen.push(stack.length);
109
+ mapperCopyStack.push(copy);
110
+ mapperOrigStack.push(curObject);
111
+ mapperParent.push(curParent);
112
+ mapperParentKey.push(curKey);
113
+ // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.
114
+ if (continues && !didShortCut) {
115
+ for (const key in copy) {
116
+ if (!Object.hasOwn(copy, key)) {
117
+ continue;
118
+ }
119
+ const val = copy[key];
120
+ // If shallow copy required, do
121
+ const onlyShallow = shallowKeys && shallowKeys?.has(key);
122
+ if (onlyShallow) {
123
+ // Do not add stack entry - assign straight away
124
+ copy[key] = this.cloneObj(val);
125
+ }
126
+ if (ignoreKeys && ignoreKeys.has(key)) {
127
+ // Do not add stack entry
128
+ continue;
129
+ }
130
+ if (!onlyShallow && val !== null && typeof val === 'object') {
131
+ // Do add stack entry.
132
+ stack.push(val);
133
+ stackParentKey.push(key);
134
+ stackParent.push(copy);
135
+ }
136
+ }
137
+ }
135
138
  }
136
- if (!onlyShallow && val !== null && typeof val === "object") {
137
- stack.push(val);
138
- stackParentKey.push(key);
139
- stackParent.push(copy);
140
- }
141
- }
139
+ handleMapper();
142
140
  }
143
- }
144
- handleMapper();
145
- }
146
- if (stack.length >= this.maxStackSize) {
147
- throw new Error("Transform object stack overflowed");
148
- }
149
- handleMapper();
150
- return resultWrap.res;
151
- }
152
- /**
153
- * Visitor that visits all objects. Visits deeper objects first.
154
- */
155
- visitObject(startObject, visitor, preVisitor = () => ({})) {
156
- const defaults = this.defaultContext;
157
- const defaultContinues = defaults.continue ?? true;
158
- const defaultIgnoreKeys = defaults.ignoreKeys;
159
- const defaultShortcut = defaults.shortcut ?? false;
160
- let didShortCut = false;
161
- const stack = [startObject];
162
- const handleVisitorOnLen = [];
163
- const visitorStack = [];
164
- function handleVisitor() {
165
- while (stack.length === handleVisitorOnLen.at(-1)) {
166
- handleVisitorOnLen.pop();
167
- const toVisit = visitorStack.pop();
168
- visitor(toVisit);
169
- }
170
- }
171
- while (stack.length > 0 && stack.length < this.maxStackSize) {
172
- const curObject = stack.pop();
173
- if (!didShortCut) {
174
- if (Array.isArray(curObject)) {
175
- for (let i = curObject.length - 1; i >= 0; i--) {
176
- stack.push(curObject[i]);
177
- }
178
- handleVisitor();
179
- continue;
141
+ if (stack.length >= this.maxStackSize) {
142
+ throw new Error('Transform object stack overflowed');
180
143
  }
181
- const context = preVisitor(curObject);
182
- didShortCut = context.shortcut ?? defaultShortcut;
183
- const continues = context.continue ?? defaultContinues;
184
- const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;
185
- handleVisitorOnLen.push(stack.length);
186
- visitorStack.push(curObject);
187
- if (continues && !didShortCut) {
188
- for (const key in curObject) {
189
- if (!Object.hasOwn(curObject, key)) {
190
- continue;
191
- }
192
- if (ignoreKeys && ignoreKeys.has(key)) {
193
- continue;
144
+ handleMapper();
145
+ return resultWrap.res;
146
+ }
147
+ /**
148
+ * Visitor that visits all objects. Visits deeper objects first.
149
+ */
150
+ visitObject(startObject, visitor, preVisitor = () => ({})) {
151
+ const defaults = this.defaultContext;
152
+ const defaultContinues = defaults.continue ?? true;
153
+ const defaultIgnoreKeys = defaults.ignoreKeys;
154
+ const defaultShortcut = defaults.shortcut ?? false;
155
+ let didShortCut = false;
156
+ // Stack of things to preVisit
157
+ const stack = [startObject];
158
+ // When the stack is done preVisiting things above this lengths, visit the bellow
159
+ const handleVisitorOnLen = [];
160
+ const visitorStack = [];
161
+ function handleVisitor() {
162
+ while (stack.length === handleVisitorOnLen.at(-1)) {
163
+ handleVisitorOnLen.pop();
164
+ const toVisit = visitorStack.pop();
165
+ visitor(toVisit);
194
166
  }
195
- const val = curObject[key];
196
- if (val && typeof val === "object") {
197
- stack.push(val);
167
+ }
168
+ while (stack.length > 0 && stack.length < this.maxStackSize) {
169
+ const curObject = stack.pop();
170
+ if (!didShortCut) {
171
+ if (Array.isArray(curObject)) {
172
+ for (let i = curObject.length - 1; i >= 0; i--) {
173
+ stack.push(curObject[i]);
174
+ }
175
+ handleVisitor();
176
+ continue;
177
+ }
178
+ // Perform pre visit before expanding the stack
179
+ const context = preVisitor(curObject);
180
+ didShortCut = context.shortcut ?? defaultShortcut;
181
+ const continues = context.continue ?? defaultContinues;
182
+ const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;
183
+ // Register that you want to be visited
184
+ handleVisitorOnLen.push(stack.length);
185
+ visitorStack.push(curObject);
186
+ // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.
187
+ if (continues && !didShortCut) {
188
+ for (const key in curObject) {
189
+ if (!Object.hasOwn(curObject, key)) {
190
+ continue;
191
+ }
192
+ if (ignoreKeys && ignoreKeys.has(key)) {
193
+ continue;
194
+ }
195
+ const val = curObject[key];
196
+ if (val && typeof val === 'object') {
197
+ stack.push(val);
198
+ }
199
+ }
200
+ }
198
201
  }
199
- }
202
+ handleVisitor();
200
203
  }
201
- }
202
- handleVisitor();
203
- }
204
- if (stack.length >= this.maxStackSize) {
205
- throw new Error("Transform object stack overflowed");
204
+ if (stack.length >= this.maxStackSize) {
205
+ throw new Error('Transform object stack overflowed');
206
+ }
207
+ handleVisitor();
206
208
  }
207
- handleVisitor();
208
- }
209
209
  }
210
- // Annotate the CommonJS export names for ESM import in node:
211
- 0 && (module.exports = {
212
- TransformerObject
213
- });
210
+ exports.TransformerObject = TransformerObject;
211
+ //# sourceMappingURL=TransformerObject.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TransformerObject.js","sourceRoot":"","sources":["../../../../lib/transformers/TransformerObject.ts"],"names":[],"mappings":";;;AAsCA,MAAa,iBAAiB;IAMU;IAL5B,YAAY,GAAG,SAAS,CAAC;IACnC;;;OAGG;IACH,YAAsC,iBAAmC,EAAE;QAArC,mBAAc,GAAd,cAAc,CAAuB;IAAG,CAAC;IAExE,KAAK,CAAC,oBAAsC,EAAE;QACnD,OAAO,IAAI,iBAAiB,CAAC,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE,GAAG,iBAAiB,EAAE,CAAC,CAAC;IACjF,CAAC;IAED;;;;OAIG;IACI,QAAQ,CAAI,GAAM;QACvB,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;YAC5C,OAAO,GAAG,CAAC;QACb,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QAEzC,0BAA0B;QAC1B,IAAI,KAAK,KAAK,MAAM,CAAC,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;YACjD,6CAA6C;YAC7C,OAAO,EAAE,GAAG,GAAG,EAAE,CAAC;QACpB,CAAC;QAED,mDAAmD;QACnD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACI,eAAe,CACpB,WAAmB,EACnB,MAA+C,EAC/C,aAAiD,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;QAE3D,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC;QACrC,MAAM,eAAe,GAAG,QAAQ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AE,CAAC;wBAC5B,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,CAAC;4BACnC,SAAS;wBACX,CAAC;wBACD,IAAI,UAAU,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;4BACtC,SAAS;wBACX,CAAC;wBACD,MAAM,GAAG,GAA8B,SAAU,CAAC,GAAG,CAAC,CAAC;wBACvD,IAAI,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;4BACnC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;wBAClB,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YACD,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACvD,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC;CACF;AA9OD,8CA8OC","sourcesContent":["export interface VisitContext {\n /**\n * Whether you should stop iterating after this object. Default false.\n */\n shortcut?: boolean;\n /**\n * Whether you should continue iterating deeper with this object. Default true.\n */\n continue?: boolean;\n /**\n * Object keys that can be ignored, meaning they do not get visited.\n */\n ignoreKeys?: Set<string>;\n}\n\nexport interface TransformContext extends VisitContext {\n /**\n * Object keys that will be shallowly copied but not traversed.\n * When the same key is included here and in ignoreKeys, the copy will still be made.\n */\n shallowKeys?: Set<string>;\n /**\n * Whether the visited object should be shallowly copied or not. Defaults to true.\n */\n copy?: boolean;\n}\n\nexport interface SelectiveTraversalContext<Nodes> {\n /**\n * Nodes you should visit next. Defaults to empty list\n */\n next?: Nodes[];\n /**\n * Whether you should stop visiting after visiting this object. Default false.\n */\n shortcut?: boolean;\n}\n\nexport class TransformerObject {\n protected maxStackSize = 1_000_000;\n /**\n * Creates stateless transformer.\n * @param defaultContext\n */\n public constructor(protected readonly defaultContext: TransformContext = {}) {}\n\n public clone(newDefaultContext: TransformContext = {}): TransformerObject {\n return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });\n }\n\n /**\n * Function to shallow clone any type.\n * @param obj\n * @protected\n */\n public cloneObj<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n const proto = Object.getPrototypeOf(obj);\n\n // Fast path: plain object\n if (proto === Object.prototype || proto === null) {\n // Spread or assign preserves fast properties\n return { ...obj };\n }\n\n // Otherwise, preserve prototype for custom objects\n return Object.assign(Object.create(proto), obj);\n }\n\n /**\n * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.\n * @param startObject object to start iterating from\n * @param mapper mapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n * If continues is false, we do not iterate deeper, current object is still mapped. - default: true\n * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.\n * - Default false\n */\n public transformObject(\n startObject: object,\n mapper: (copy: object, orig: object) => unknown,\n preVisitor: (orig: object) => TransformContext = () => ({}),\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n let didShortCut = false;\n const resultWrap = { res: startObject };\n\n // Grows with stack\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n\n // Grows with reverse stack - when popping down the stack, you realise you still want to map something.\n // Counter of stack size when we started adding the children of this object, going beyond this means a new parent\n const handleMapperOnLen: number[] = [];\n const mapperCopyStack: object[] = [];\n const mapperOrigStack: object[] = [];\n const mapperParent: object[] = [];\n const mapperParentKey: string[] = [];\n\n function handleMapper(): void {\n while (stack.length === handleMapperOnLen.at(-1)) {\n handleMapperOnLen.pop();\n const copyToMap = mapperCopyStack.pop()!;\n const origToMap = mapperOrigStack.pop()!;\n const parent = <Record<string, unknown>> mapperParent.pop()!;\n const parentKey = mapperParentKey.pop()!;\n parent[parentKey] = mapper(copyToMap, origToMap);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n const curParent = stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n\n // Only add to the stack when you did not shortcut\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(newArr);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n for (let index = curObject.length - 1; index >= 0; index--) {\n const val = curObject[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(newArr);\n stackParentKey.push(index.toString());\n }\n }\n handleMapper();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(<any>curObject);\n const copyFlag = context.copy ?? defaultCopyFlag;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = context.shallowKeys ?? defaultShallowKeys;\n didShortCut = context.shortcut ?? defaultDidShortCut;\n\n const copy = copyFlag ? this.cloneObj(curObject) : curObject;\n\n // Register that you want to be visited\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(copy);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in copy) {\n if (!Object.hasOwn(copy, key)) {\n continue;\n }\n const val = (<Record<string, unknown>> copy)[key];\n\n // If shallow copy required, do\n const onlyShallow = shallowKeys && shallowKeys?.has(key);\n if (onlyShallow) {\n // Do not add stack entry - assign straight away\n (<Record<string, unknown>> copy)[key] = this.cloneObj(val);\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n // Do not add stack entry\n continue;\n }\n if (!onlyShallow && val !== null && typeof val === 'object') {\n // Do add stack entry.\n stack.push(val);\n stackParentKey.push(key);\n stackParent.push(copy);\n }\n }\n }\n }\n handleMapper();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleMapper();\n\n return <any> resultWrap.res;\n }\n\n /**\n * Visitor that visits all objects. Visits deeper objects first.\n */\n public visitObject(\n startObject: object,\n visitor: (orig: object) => void,\n preVisitor: (orig: object) => VisitContext = () => ({}),\n ): void {\n const defaults = this.defaultContext;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShortcut = defaults.shortcut ?? false;\n\n let didShortCut = false;\n\n // Stack of things to preVisit\n const stack = [ startObject ];\n // When the stack is done preVisiting things above this lengths, visit the bellow\n const handleVisitorOnLen: number[] = [];\n const visitorStack: object[] = [];\n\n function handleVisitor(): void {\n while (stack.length === handleVisitorOnLen.at(-1)) {\n handleVisitorOnLen.pop();\n const toVisit = visitorStack.pop()!;\n visitor(toVisit);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n for (let i = curObject.length - 1; i >= 0; i--) {\n stack.push(curObject[i]);\n }\n handleVisitor();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(curObject);\n didShortCut = context.shortcut ?? defaultShortcut;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n\n // Register that you want to be visited\n handleVisitorOnLen.push(stack.length);\n visitorStack.push(curObject);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in curObject) {\n if (!Object.hasOwn(curObject, key)) {\n continue;\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n continue;\n }\n const val = (<Record<string, unknown>> curObject)[key];\n if (val && typeof val === 'object') {\n stack.push(val);\n }\n }\n }\n }\n handleVisitor();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleVisitor();\n }\n}\n"]}