All files / linter mutationNotation.ts

85.79% Statements 145/169
77.07% Branches 121/157
100% Functions 8/8
93.1% Lines 135/145

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443    3x         3x                       3x 1258x 1258x               3x 307x 307x   302x 302x 302x   302x             302x 302x                     1887x 1885x 152x   1733x             1096x                   3x         294x 294x   292x 426x 425x 389x 386x 386x 386x 386x 9x 2x 2x 2x   377x 377x   413x 59x 58x 58x 58x 58x     280x                         279x 12x 12x       267x 267x 267x 267x 267x 147x 147x 132x 132x 132x 132x 132x 1x         131x   146x 30x 30x 30x 30x   146x   266x 266x 266x 27x 27x 9x 9x 9x 9x 9x 1x     8x   8x     26x     26x             239x   239x     239x                                 3x         284x 284x 1x                 283x 283x 1x                 282x 282x 2x                 280x 280x                                 280x 1x                   279x 279x   279x     34x 1x                 33x 33x 2x                 31x                     31x     31x                     29x 2x                 27x 27x 22x                   22x 13x 13x 1x                   12x     12x   9x   5x                   5x 5x         3x                 2x     216x 5x                 211x 1x                 210x                                             3x 7x 7x 5x    
import type { Schema } from "@featurevisor/types";
 
import { parseNotation, type MutationOperation, type PathPart } from "../builder/mutator";
 
export type { MutationOperation, PathPart };
export type PathSegment = PathPart;
 
const OPERATION_SUFFIX = /:((?:append|prepend|after|before|remove))$/;
 
export interface ParsedMutationKey {
  rootKey: string;
  pathSegments: PathSegment[];
  allSegments: PathSegment[];
  operation: MutationOperation;
}
 
/**
 * Returns true if the key looks like mutation notation (contains path or operation).
 */
export function isMutationKey(key: string): boolean {
  const k = key.trim();
  return k.includes(".") || k.includes("[") || OPERATION_SUFFIX.test(k);
}
 
/**
 * Parse a full variable key (e.g. "config.width", "items[1].name", "tags:append")
 * into root variable name, path segments within the variable, and operation.
 * Uses the shared parseNotation from the mutator.
 */
export function parseMutationKey(key: string): ParsedMutationKey | null {
  const rest = key.trim();
  if (!rest) return null;
 
  const { segments, operation } = parseNotation(rest);
  const rootKey = segments.length > 0 && "key" in segments[0] ? segments[0].key : "";
  const first = segments[0];
  const firstPathPart: PathSegment[] =
    first && ("index" in first || "selector" in first)
      ? [
          "index" in first
            ? { key: "", index: first.index }
            : { key: "", selector: first.selector! },
        ]
      : [];
  const pathWithinVariable = firstPathPart.concat(segments.slice(1));
  return { rootKey, pathSegments: pathWithinVariable, allSegments: segments, operation };
}
 
/**
 * Resolve a schema reference (schema.schema -> schemasByKey[name]).
 * Follows one level of reference; the resolved schema may itself have oneOf or another ref.
 */
function resolveSchemaRef(
  schema: Schema | null,
  schemasByKey: Record<string, Schema> | undefined,
): Schema | null {
  if (!schema || typeof schema !== "object") return null;
  if (schema.schema && schemasByKey?.[schema.schema]) {
    return resolveSchemaRef(schemasByKey[schema.schema], schemasByKey);
  }
  return schema;
}
 
/**
 * Return true if the schema is a oneOf (multiple possible shapes); path resolution cannot descend through oneOf.
 */
function isOneOfSchema(schema: Schema): boolean {
  return Array.isArray(schema.oneOf) && schema.oneOf.length > 0;
}
 
/**
 * Resolve the schema at a path within a variable schema.
 * pathSegments are the path *within* the variable (e.g. for variable "config", path [ {key:"width"} ];
 * for variable "items", path [ {index:0}, {key:"name"} ]).
 * Returns the schema at that path, or null if the path is invalid.
 * Does not descend through oneOf (path through oneOf is considered invalid for mutation targets).
 */
export function resolveSchemaAtPath(
  variableSchema: Schema | null,
  pathSegments: PathSegment[],
  schemasByKey?: Record<string, Schema>,
): Schema | null {
  let current: Schema | null = resolveSchemaRef(variableSchema, schemasByKey);
  if (!current) return null;
 
  for (const seg of pathSegments) {
    if (isOneOfSchema(current)) return null;
    if (seg.key) {
      if (current.type !== "object") return null;
      const props = current.properties;
      const additional = current.additionalProperties;
      const next = props && typeof props === "object" ? props[seg.key] : undefined;
      if (next === undefined) {
        if (!additional || typeof additional !== "object") return null;
        current = resolveSchemaRef(additional, schemasByKey);
        Iif (!current) return null;
        continue;
      }
      current = resolveSchemaRef(next, schemasByKey);
      Iif (!current) return null;
    }
    if ("index" in seg || "selector" in seg) {
      if (current.type !== "array") return null;
      const itemSchema = current.items;
      Iif (!itemSchema || typeof itemSchema !== "object") return null;
      current = resolveSchemaRef(itemSchema, schemasByKey);
      Iif (!current) return null;
    }
  }
  return current;
}
 
/**
 * Return the schema of the container at the end of path (object or array) and the last segment.
 * Used to check if we can do append/prepend (must be array) or remove (object key or array element).
 * Does not descend through oneOf.
 */
function getContainerSchemaAtPath(
  variableSchema: Schema | null,
  pathSegments: PathSegment[],
  schemasByKey?: Record<string, Schema>,
): { containerSchema: Schema; lastSegment: PathSegment; parentSchema: Schema } | null {
  if (pathSegments.length === 0) {
    const resolved = variableSchema ? resolveSchemaRef(variableSchema, schemasByKey) : null;
    return resolved
      ? { containerSchema: resolved, lastSegment: { key: "" }, parentSchema: resolved }
      : null;
  }
  let current: Schema | null = resolveSchemaRef(variableSchema, schemasByKey);
  Iif (!current) return null;
  const pathWithoutLast = pathSegments.slice(0, -1);
  const lastSegment = pathSegments[pathSegments.length - 1];
  for (const seg of pathWithoutLast) {
    Iif (isOneOfSchema(current)) return null;
    if (seg.key) {
      Iif (current.type !== "object") return null;
      const props = current.properties;
      const additional = current.additionalProperties;
      const next = props && typeof props === "object" ? props[seg.key] : undefined;
      if (next === undefined) {
        if (!additional || typeof additional !== "object") return null;
        current = resolveSchemaRef(additional, schemasByKey);
        Iif (!current) return null;
        continue;
      }
      current = resolveSchemaRef(next, schemasByKey);
    }
    if ("index" in seg || "selector" in seg) {
      Iif (current?.type !== "array") return null;
      const itemSchema = current.items;
      Iif (!itemSchema || typeof itemSchema !== "object") return null;
      current = resolveSchemaRef(itemSchema, schemasByKey);
    }
    Iif (!current) return null;
  }
  Iif (!current) return null;
  const parentSchema = current;
  if ("index" in lastSegment || "selector" in lastSegment) {
    let arraySchema: Schema | null = parentSchema;
    if (lastSegment.key) {
      Iif (arraySchema.type !== "object") return null;
      const props = arraySchema.properties;
      const additional = arraySchema.additionalProperties;
      const next = props && typeof props === "object" ? props[lastSegment.key] : undefined;
      if (next === undefined) {
        if (!additional || typeof additional !== "object") return null;
        arraySchema = resolveSchemaRef(additional, schemasByKey);
      } else {
        arraySchema = resolveSchemaRef(next, schemasByKey);
      }
      Iif (!arraySchema) return null;
    }
    const normalizedLastSegment =
      "index" in lastSegment
        ? ({ key: "", index: lastSegment.index } as PathSegment)
        : ({ key: "", selector: lastSegment.selector } as PathSegment);
    return {
      containerSchema: arraySchema,
      lastSegment: normalizedLastSegment,
      parentSchema: arraySchema,
    };
  }
  const propSchema =
    parentSchema.properties?.[lastSegment.key] ?? parentSchema.additionalProperties;
  const resolvedProp =
    propSchema && typeof propSchema === "object"
      ? resolveSchemaRef(propSchema, schemasByKey)
      : null;
  return resolvedProp ? { containerSchema: resolvedProp, lastSegment, parentSchema } : null;
}
 
export interface MutationValidationResult {
  valid: boolean;
  rootKey: string;
  pathSegments: PathSegment[];
  operation: MutationOperation;
  valueSchema: Schema | null;
  error?: string;
}
 
/**
 * Validate mutation key against variable schema: root exists, path valid, operation allowed.
 * Returns valueSchema to validate the value against (for set: schema at path; for append/prepend/after/before: item schema).
 * Uses Schema from @featurevisor/types; validates required (no :remove on required props) and does not allow path through oneOf.
 */
export function validateMutationKey(
  key: string,
  variableSchemaByKey: Record<string, Schema>,
  schemasByKey?: Record<string, Schema>,
): MutationValidationResult {
  const parsed = parseMutationKey(key);
  if (!parsed) {
    return {
      valid: false,
      rootKey: "",
      pathSegments: [],
      operation: "set",
      valueSchema: null,
      error: `Invalid mutation notation: "${key}"`,
    };
  }
  const { rootKey, pathSegments, operation } = parsed;
  if (!rootKey) {
    return {
      valid: false,
      rootKey: "",
      pathSegments: [],
      operation,
      valueSchema: null,
      error: `Mutation key must start with a variable name: "${key}"`,
    };
  }
  const variableSchema = variableSchemaByKey[rootKey];
  if (!variableSchema) {
    return {
      valid: false,
      rootKey,
      pathSegments,
      operation,
      valueSchema: null,
      error: `Variable "${rootKey}" is not defined in \`variablesSchema\`.`,
    };
  }
  const resolvedRoot = resolveSchemaRef(variableSchema, schemasByKey);
  Iif (!resolvedRoot) {
    const refName =
      variableSchema && typeof variableSchema === "object" && "schema" in variableSchema
        ? (variableSchema as { schema?: string }).schema
        : undefined;
    return {
      valid: false,
      rootKey,
      pathSegments,
      operation,
      valueSchema: null,
      error:
        refName != null
          ? `Schema "${refName}" could not be loaded for variable "${rootKey}".`
          : `Could not resolve schema for variable "${rootKey}".`,
    };
  }
  if (pathSegments.length > 0 && isOneOfSchema(resolvedRoot)) {
    return {
      valid: false,
      rootKey,
      pathSegments,
      operation,
      valueSchema: null,
      error: `Cannot mutate path into variable "${rootKey}" (root schema is \`oneOf\`; path resolution not defined).`,
    };
  }
 
  const container = getContainerSchemaAtPath(variableSchema, pathSegments, schemasByKey);
  const valueSchemaAtPath = resolveSchemaAtPath(variableSchema, pathSegments, schemasByKey);
 
  switch (operation) {
    case "append":
    case "prepend": {
      if (!container) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Path "${key}" is invalid for variable "${rootKey}" (path does not exist in schema).`,
        };
      }
      const arrResolved = container.containerSchema;
      if (!arrResolved || arrResolved.type !== "array") {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Operation ":${operation}" is only allowed on array variables or object properties of type array; path "${key}" does not point to an array.`,
        };
      }
      Iif (isOneOfSchema(arrResolved)) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Operation ":${operation}" is not allowed when array \`items\` is \`oneOf\` (path "${key}").`,
        };
      }
      const itemSchema =
        arrResolved.items && typeof arrResolved.items === "object"
          ? resolveSchemaRef(arrResolved.items, schemasByKey)
          : null;
      return {
        valid: true,
        rootKey,
        pathSegments,
        operation,
        valueSchema: itemSchema,
      };
    }
    case "after":
    case "before":
    case "remove": {
      if (!container) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Path "${key}" is invalid for variable "${rootKey}" (path does not exist in schema).`,
        };
      }
      const last = container.lastSegment;
      if ("index" in last || "selector" in last) {
        Iif (container.parentSchema.type !== "array") {
          return {
            valid: false,
            rootKey,
            pathSegments,
            operation,
            valueSchema: null,
            error: `Operation ":${operation}" with array index/selector is only allowed on arrays; path "${key}" does not point to an array element.`,
          };
        }
        if (operation === "after" || operation === "before") {
          const parentItems = container.parentSchema.items;
          if (parentItems && typeof parentItems === "object" && isOneOfSchema(parentItems)) {
            return {
              valid: false,
              rootKey,
              pathSegments,
              operation,
              valueSchema: null,
              error: `Operation ":${operation}" is not allowed when array \`items\` is \`oneOf\` (path "${key}").`,
            };
          }
          const itemSchema =
            parentItems && typeof parentItems === "object"
              ? resolveSchemaRef(parentItems, schemasByKey)
              : null;
          return { valid: true, rootKey, pathSegments, operation, valueSchema: itemSchema };
        }
        return { valid: true, rootKey, pathSegments, operation, valueSchema: null };
      }
      Iif (container.parentSchema.type !== "object") {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Operation ":${operation}" on a property is only allowed on objects; path "${key}" does not point to an object property.`,
        };
      }
      const requiredKeys = container.parentSchema.required;
      if (
        operation === "remove" &&
        Array.isArray(requiredKeys) &&
        requiredKeys.includes(last.key)
      ) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Cannot remove required property "${last.key}" from variable "${rootKey}" (listed in schema \`required\`).`,
        };
      }
      return { valid: true, rootKey, pathSegments, operation, valueSchema: null };
    }
    case "set": {
      if (valueSchemaAtPath === null && pathSegments.length > 0) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Path "${key}" is invalid for variable "${rootKey}" (path does not exist in schema).`,
        };
      }
      if (valueSchemaAtPath && isOneOfSchema(valueSchemaAtPath)) {
        return {
          valid: false,
          rootKey,
          pathSegments,
          operation,
          valueSchema: null,
          error: `Cannot set value at path "${key}" (target schema is \`oneOf\`; mutation target must be a single schema).`,
        };
      }
      return {
        valid: true,
        rootKey,
        pathSegments,
        operation,
        valueSchema: valueSchemaAtPath,
      };
    }
    default:
      return {
        valid: true,
        rootKey,
        pathSegments,
        operation,
        valueSchema: valueSchemaAtPath,
      };
  }
}
 
/**
 * Parse a path-map key (relative to a variable) into path segments for resolveSchemaAtPath.
 * e.g. "display.fontSize" -> [{key:"display"},{key:"fontSize"}], "[0].name" -> [{key:"",index:0},{key:"name"}].
 */
export function parsePathMapKey(relativePath: string): PathSegment[] | null {
  const parsed = parseMutationKey(relativePath);
  if (!parsed) return null;
  return parsed.allSegments.length > 0 ? parsed.allSegments : null;
}