UNPKG

@neo4j/cypher-builder

Version:

A programmatic API for building Cypher queries for Neo4j

74 lines (73 loc) 2.36 kB
"use strict"; /* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.escapeLabel = escapeLabel; exports.escapeType = escapeType; exports.escapeProperty = escapeProperty; exports.escapeVariable = escapeVariable; exports.escapeLiteralString = escapeLiteralString; const ESCAPE_SYMBOL_REGEX = /`/g; /** These names must be escaped for variables */ const RESERVED_VAR_NAMES = ["contains", "in", "where", "is"]; /** Escapes a Node label string */ function escapeLabel(label) { return escapeIfNeeded(label); } /** Escapes a Relationship type string */ function escapeType(type) { // Use same logic as escape label return escapeLabel(type); } /** Escapes a property name string */ function escapeProperty(propName) { return escapeIfNeeded(propName); } /** Escapes a variable name if needed */ function escapeVariable(varName) { if (RESERVED_VAR_NAMES.includes(varName.toLowerCase())) { return escapeString(varName); } return escapeIfNeeded(varName); } /** Escapes a literal string */ function escapeLiteralString(str) { return str.replaceAll(`"`, `\\"`); } function escapeIfNeeded(str) { const normalizedStr = normalizeString(str); if (needsEscape(normalizedStr)) { return escapeString(normalizedStr); } return normalizedStr; } function escapeString(str) { const normalizedStr = normalizeString(str); const escapedStr = normalizedStr.replace(ESCAPE_SYMBOL_REGEX, "``"); return `\`${escapedStr}\``; } function normalizeString(str) { return str.replace(/\\u0060/g, "`"); } function needsEscape(str) { if (!str) return false; const validStr = /^[a-z_][0-9a-z_]*$/i; return !validStr.test(str); }