import { NumberWithUnitSymbol, isLanguageError, ProcessorError, isObject, isNumber, isString, renameReferences, DictionarySymbol, serializeInterpreterResult, stringifyInterpreterResult, TokenSymbol, ListSymbol, parseExpression, StringSymbol, NumberSymbol, isBoolean, BooleanSymbol, isNull, NullSymbol, isArray, isTokenscriptSymbol, Interpreter, jsValueToSymbolType, getKeyAlt } from '../chunk-QYTZHMUN.js';
import { UNINTERPRETED_KEYWORDS } from '../chunk-BNLQ6GCU.js';
import { type } from 'arktype';

// src/processor/resolver/DependencyTracker.ts
var DependencyTracker = class {
  constructor() {
    this.tokenDeps = /* @__PURE__ */ new Map();
    this.reverseDeps = /* @__PURE__ */ new Map();
    this.prefixDeps = /* @__PURE__ */ new Map();
    this.prefixReverseDeps = /* @__PURE__ */ new Map();
  }
  addTokenDependency(dependent, dependency) {
    this.addToSetMap(this.tokenDeps, dependent, dependency);
    this.addToSetMap(this.reverseDeps, dependency, dependent);
  }
  removeTokenDependency(dependent, dependency) {
    this.removeFromSetMap(this.tokenDeps, dependent, dependency);
    this.removeFromSetMap(this.reverseDeps, dependency, dependent);
  }
  addPrefixDependency(dependent, prefix) {
    this.addToSetMap(this.prefixDeps, dependent, prefix);
    this.addToSetMap(this.prefixReverseDeps, prefix, dependent);
  }
  removePrefixDependency(dependent, prefix) {
    this.removeFromSetMap(this.prefixDeps, dependent, prefix);
    this.removeFromSetMap(this.prefixReverseDeps, prefix, dependent);
  }
  getTokenDependents(token) {
    return this.cloneSet(this.reverseDeps.get(token));
  }
  getTokenDependentsIterable(token) {
    return this.reverseDeps.get(token) ?? [];
  }
  getTokensWaitingForPrefix(prefix) {
    return this.cloneSet(this.prefixReverseDeps.get(prefix));
  }
  getTokensWaitingForPrefixIterable(prefix) {
    return this.prefixReverseDeps.get(prefix) ?? [];
  }
  getTokenDependencies(token) {
    return this.cloneSet(this.tokenDeps.get(token));
  }
  getPrefixDependencies(token) {
    return this.cloneSet(this.prefixDeps.get(token));
  }
  isTokenReady(token) {
    const tokenDeps = this.tokenDeps.get(token);
    const prefixDeps = this.prefixDeps.get(token);
    return (!tokenDeps || tokenDeps.size === 0) && (!prefixDeps || prefixDeps.size === 0);
  }
  hasAnyDependencies() {
    return this.tokenDeps.size > 0 || this.prefixDeps.size > 0;
  }
  getUnresolvedTokens() {
    const unresolved = /* @__PURE__ */ new Set();
    for (const [token] of this.tokenDeps) unresolved.add(token);
    for (const [token] of this.prefixDeps) unresolved.add(token);
    return Array.from(unresolved);
  }
  addToSetMap(map, key, value) {
    let set = map.get(key);
    if (!set) {
      set = /* @__PURE__ */ new Set();
      map.set(key, set);
    }
    set.add(value);
  }
  removeFromSetMap(map, key, value) {
    const set = map.get(key);
    if (!set) return;
    set.delete(value);
    if (set.size === 0) {
      map.delete(key);
    }
  }
  cloneSet(values) {
    return values ? new Set(values) : /* @__PURE__ */ new Set();
  }
};

// src/processor/resolver/helpers.ts
function getAffectedTokens(result) {
  if (!result.dependants?.graph) {
    return /* @__PURE__ */ new Set();
  }
  return new Set(result.dependants.graph.getNodes().keys());
}
function getBrokenReferences(result) {
  if (!result.issues) {
    return /* @__PURE__ */ new Set();
  }
  const brokenRefs = /* @__PURE__ */ new Set();
  for (const [tokenPath, issues] of result.issues) {
    for (const issue of issues) {
      if (isLanguageError(issue) && (issue.code === "PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */ || issue.code === "PROC_DEPENDENCY_ERROR" /* DEPENDENCY_ERROR */)) {
        brokenRefs.add(tokenPath);
        break;
      }
    }
  }
  return brokenRefs;
}
function getRenamedReferences(_result, modifiedTokens) {
  return modifiedTokens;
}
function getModifiedDependants(oldTokens, result) {
  const modified = /* @__PURE__ */ new Set();
  const affectedTokens = getAffectedTokens(result);
  for (const tokenPath of affectedTokens) {
    const oldValue = oldTokens.get(tokenPath);
    const newValue = result.tokens.get(tokenPath);
    if (oldValue !== newValue) {
      modified.add(tokenPath);
    }
  }
  return modified;
}

// src/processor/resolver/issue-helpers.ts
function hasIssueWithCode(issues, code) {
  if (!issues) return false;
  return Array.from(issues.entries()).some(
    ([_tokenName, issueList]) => issueList.some((issue) => "code" in issue && issue.code === code)
  );
}
function tokenHasIssueWithCode(issues, tokenName, code) {
  if (!issues) return false;
  const tokenIssues = issues.get(tokenName);
  if (!tokenIssues) return false;
  return tokenIssues.some((issue) => "code" in issue && issue.code === code);
}
function getTokensWithIssues(issues) {
  if (!issues) return /* @__PURE__ */ new Set();
  return new Set(issues.keys());
}
function hasAnyIssues(issues) {
  return issues !== void 0 && issues.size > 0;
}
function getTokenError(issues, tokenName) {
  if (!issues) return void 0;
  const tokenIssues = issues.get(tokenName);
  if (!tokenIssues) return void 0;
  return tokenIssues.find((issue) => "code" in issue);
}

// src/processor/resolver/PrefixExtractor.ts
var PrefixExtractor = class {
  constructor() {
    this.prefixCache = /* @__PURE__ */ new Map();
  }
  /**
   * Extract all prefix paths for a token reference.
   *
   * Example: "a.b.c" returns ["a", "a.b"]
   * Cached after first call for the same token.
   */
  extractPrefixes(tokenName) {
    const cached = this.prefixCache.get(tokenName);
    if (cached) {
      return cached;
    }
    const prefixes = [];
    let dotIndex = tokenName.indexOf(".");
    while (dotIndex !== -1) {
      prefixes.push(tokenName.slice(0, dotIndex));
      dotIndex = tokenName.indexOf(".", dotIndex + 1);
    }
    this.prefixCache.set(tokenName, prefixes);
    return prefixes;
  }
  clearCache() {
    this.prefixCache.clear();
  }
};

// src/processor/resolver/PrefixManager.ts
var PrefixManager = class {
  constructor(config) {
    this.config = config;
    this.prefixes = /* @__PURE__ */ new Map();
    this.tokenPrefixes = /* @__PURE__ */ new Map();
    this.activePrefixes = /* @__PURE__ */ new Map();
    this.virtualChildren = /* @__PURE__ */ new Map();
    this.prefixExtractor = new PrefixExtractor();
    // Optimization caches
    this.directChildrenCache = /* @__PURE__ */ new Map();
    this.parentLookupCache = /* @__PURE__ */ new Map();
  }
  addTokenToPrefix(tokenName) {
    const prefixes = this.prefixExtractor.extractPrefixes(tokenName);
    if (prefixes.length === 0) return;
    for (const prefix of prefixes) {
      this.addToSetMap(this.prefixes, prefix, tokenName);
      this.addToSetMap(this.tokenPrefixes, tokenName, prefix);
      const prefixLen = prefix.length + 1;
      const shortName = tokenName.slice(prefixLen);
      if (!shortName.includes(".")) {
        this.addToSetMap(this.directChildrenCache, prefix, shortName);
      }
    }
  }
  hasPrefix(prefix) {
    return this.prefixes.has(prefix);
  }
  activatePrefix(prefix) {
    if (this.activePrefixes.has(prefix)) return;
    const members = this.prefixes.get(prefix);
    if (!members || members.size === 0) return;
    this.activePrefixes.set(prefix, new Set(members));
  }
  markTokenResolved(tokenName) {
    const prefixes = this.tokenPrefixes.get(tokenName);
    if (!prefixes || prefixes.size === 0) return [];
    const ready = [];
    for (const prefix of prefixes) {
      const pending = this.activePrefixes.get(prefix);
      if (!pending) continue;
      pending.delete(tokenName);
      if (pending.size === 0) {
        this.activePrefixes.delete(prefix);
        ready.push(prefix);
      }
    }
    this.tokenPrefixes.delete(tokenName);
    return ready;
  }
  buildPrefixDictionary(prefix, referenceCache) {
    const directChildren = this.directChildrenCache.get(prefix);
    if (!directChildren || directChildren.size === 0) return void 0;
    const dictionaryEntries = /* @__PURE__ */ new Map();
    for (const shortName of directChildren) {
      const tokenName = `${prefix}.${shortName}`;
      const referenceValue = referenceCache.get(tokenName);
      const symbol = this.toSymbol(referenceValue);
      if (symbol) {
        dictionaryEntries.set(shortName, symbol.cloneIfMutable());
      }
    }
    if (dictionaryEntries.size === 0) return void 0;
    return new DictionarySymbol(dictionaryEntries, this.config);
  }
  findParentToken(reference, tokens) {
    const cached = this.parentLookupCache.get(reference);
    if (cached !== void 0) {
      return cached === null ? void 0 : cached;
    }
    let lastDotIndex = reference.lastIndexOf(".");
    while (lastDotIndex > 0) {
      const candidate = reference.slice(0, lastDotIndex);
      if (tokens.has(candidate)) {
        this.parentLookupCache.set(reference, candidate);
        return candidate;
      }
      lastDotIndex = reference.lastIndexOf(".", lastDotIndex - 1);
    }
    this.parentLookupCache.set(reference, null);
    return void 0;
  }
  addVirtualChild(parent, child) {
    this.addToSetMap(this.virtualChildren, parent, child);
  }
  getVirtualChildren(parent) {
    const children = this.virtualChildren.get(parent);
    return children ? new Set(children) : /* @__PURE__ */ new Set();
  }
  getAndRemoveVirtualChildren(parent) {
    const children = this.virtualChildren.get(parent);
    if (!children) return /* @__PURE__ */ new Set();
    this.virtualChildren.delete(parent);
    return children;
  }
  removeVirtualChildren(parent) {
    this.virtualChildren.delete(parent);
  }
  getReadyPrefixes() {
    return Array.from(this.activePrefixes.keys()).filter((prefix) => {
      const pending = this.activePrefixes.get(prefix);
      return pending && pending.size === 0;
    });
  }
  clearCaches() {
    this.directChildrenCache.clear();
    this.parentLookupCache.clear();
  }
  addToSetMap(map, key, value) {
    let set = map.get(key);
    if (!set) {
      set = /* @__PURE__ */ new Set();
      map.set(key, set);
    }
    set.add(value);
  }
  toSymbol(value) {
    if (value === void 0) return void 0;
    if (value === null) return new NullSymbol(this.config);
    if (isTokenscriptSymbol(value)) return value;
    return new StringSymbol(String(value), this.config);
  }
};

// src/processor/resolver/ReadinessTracker.ts
var ReadinessTracker = class {
  constructor() {
    this.readyCache = /* @__PURE__ */ new Map();
  }
  /**
   * Check if a token is ready to be resolved.
   * Results are cached until marked dirty.
   */
  isReady(tokenName, dependencyTracker) {
    if (!this.readyCache.has(tokenName)) {
      const ready = dependencyTracker.isTokenReady(tokenName);
      this.readyCache.set(tokenName, ready);
      return ready;
    }
    const cached = this.readyCache.get(tokenName);
    return cached ?? false;
  }
  /**
   * Mark a token's readiness state as dirty after a dependency change
   */
  markDirty(tokenName) {
    this.readyCache.delete(tokenName);
  }
  /**
   * Clear all cached state (e.g., for testing)
   */
  clearCache() {
    this.readyCache.clear();
  }
};

// src/processor/resolver/ResolutionNotifier.ts
var ResolutionNotifier = class {
  constructor(dependencyTracker, prefixManager, readinessTracker, pendingResolution, readyQueue, resolveCallback, buildDictionaryCallback) {
    this.dependencyTracker = dependencyTracker;
    this.prefixManager = prefixManager;
    this.readinessTracker = readinessTracker;
    this.pendingResolution = pendingResolution;
    this.readyQueue = readyQueue;
    this.resolveCallback = resolveCallback;
    this.buildDictionaryCallback = buildDictionaryCallback;
  }
  /**
   * Release all dependencies and prefixes for a token and its flattened children.
   * This is called after a token has been successfully resolved.
   * Triggers cascade resolution of any newly-ready dependents.
   */
  releaseDependencies(tokenName, flattened, referenceCache) {
    this.releaseDependentsFor(tokenName);
    this.releasePrefixesFor(tokenName, referenceCache);
    if (flattened) {
      for (const flatName of flattened) {
        this.releaseDependentsFor(flatName);
        this.releasePrefixesFor(flatName, referenceCache);
      }
    }
  }
  /**
   * Release dependents waiting for a specific token and add to ready queue
   */
  releaseDependentsFor(name) {
    for (const dependent of this.dependencyTracker.getTokenDependentsIterable(name)) {
      if (this.pendingResolution.has(dependent)) continue;
      this.dependencyTracker.removeTokenDependency(dependent, name);
      this.readinessTracker.markDirty(dependent);
      if (this.readinessTracker.isReady(dependent, this.dependencyTracker)) {
        this.readyQueue.add(dependent);
      }
    }
  }
  /**
   * Release prefixes that may now be complete after a token resolution
   */
  releasePrefixesFor(name, referenceCache) {
    const readyPrefixes = this.prefixManager.markTokenResolved(name);
    if (readyPrefixes.length === 0) return;
    for (const prefix of readyPrefixes) {
      this.releasePrefixDependents(prefix, referenceCache);
    }
  }
  /**
   * Release tokens waiting for a specific prefix and add to ready queue
   */
  releasePrefixDependents(prefix, referenceCache) {
    this.buildDictionaryCallback(prefix, referenceCache);
    for (const tokenName of this.dependencyTracker.getTokensWaitingForPrefixIterable(prefix)) {
      if (this.pendingResolution.has(tokenName)) continue;
      this.dependencyTracker.removePrefixDependency(tokenName, prefix);
      this.readinessTracker.markDirty(tokenName);
      if (this.readinessTracker.isReady(tokenName, this.dependencyTracker)) {
        this.readyQueue.add(tokenName);
      }
    }
  }
};
var SelectedTokenSetsObjectSchema = type("Record<string, 'enabled' | 'source'>");
var SelectedTokenSetsArraySchema = type({
  id: "string",
  status: "'enabled' | 'source'"
}).array();
var SelectedTokenSetsSchema = type([
  SelectedTokenSetsObjectSchema,
  "|",
  SelectedTokenSetsArraySchema
]);
var ThemeSchema = type({
  name: "string",
  selectedTokenSets: SelectedTokenSetsSchema,
  "figmaCollectionId?": "string",
  "figmaModeId?": "string",
  "group?": "string"
});
var ThemesArraySchema = ThemeSchema.array();
var selectTheme = (themes, themeName) => {
  return themes.find((theme) => theme.name === themeName);
};
var resolveThemes = (jsonFiles) => {
  const themesFile = jsonFiles.$themes;
  if (themesFile) {
    if (isObject(themesFile) && "$themes" in themesFile) {
      const themesValue = themesFile.$themes;
      const validatedThemes = ThemesArraySchema(themesValue);
      if (!(validatedThemes instanceof type.errors)) {
        return ["$themes", validatedThemes];
      }
    }
    const validatedAsArray = ThemesArraySchema(themesFile);
    if (!(validatedAsArray instanceof type.errors)) {
      return ["$themes", validatedAsArray];
    }
  }
  return void 0;
};
var extractSetNames = (selectedTokenSets) => {
  if (Array.isArray(selectedTokenSets)) {
    return selectedTokenSets.map((set) => set.id);
  }
  return Object.keys(selectedTokenSets);
};

// src/processor/utils/tokens.ts
function getTokenValue(data) {
  return isString(data) ? data : data.$value;
}
function setTokenValue(value) {
  return isString(value) ? { $value: value } : value;
}
function flattenTokensObject(obj, prefixAccumulator = "") {
  const result = /* @__PURE__ */ new Map();
  for (const [prefix, value] of Object.entries(obj)) {
    if (prefix.startsWith("$")) {
      continue;
    }
    const path = prefixAccumulator ? `${prefixAccumulator}.${prefix}` : prefix;
    if (isObject(value)) {
      const objValue = value;
      const tokenValue = getKeyAlt(["$value", "value"], objValue);
      if (tokenValue !== void 0) {
        const tokenType = objValue.$type;
        const tokenMetadata = objValue.$metadata;
        const tokenData = {
          $value: tokenValue,
          ...tokenType !== void 0 && { $type: String(tokenType) },
          ...tokenMetadata !== void 0 && { $metadata: tokenMetadata }
        };
        result.set(path, tokenData);
      } else {
        const nested = flattenTokensObject(objValue, path);
        for (const [nestedKey, nestedValue] of nested) {
          result.set(nestedKey, nestedValue);
        }
      }
    } else {
      result.set(path, { $value: value });
    }
  }
  return result;
}
function normalizeToTokenData(value) {
  if (typeof value === "string") {
    return { $value: value };
  }
  if (isObject(value) && "$value" in value) {
    const obj = value;
    const metadata = obj.$metadata;
    return {
      $value: obj.$value,
      ...isString(obj.$type) && { $type: obj.$type },
      ...metadata !== void 0 && { $metadata: metadata }
    };
  }
  return { $value: value };
}
function recordToMap(record) {
  const map = /* @__PURE__ */ new Map();
  for (const [key, value] of Object.entries(record)) {
    map.set(key, normalizeToTokenData(value));
  }
  return map;
}
function isNested(obj) {
  return Object.keys(obj).some((key) => {
    const value = obj[key];
    return isObject(value) && !key.startsWith("$");
  });
}

// src/processor/utils/set-processor.ts
function determineSets(jsonFiles, activeSets, activeTheme) {
  if (activeSets) return activeSets;
  if (activeTheme) {
    const resolved = resolveThemes(jsonFiles);
    if (!resolved) {
      throw new ProcessorError("PROC_NO_THEMES_FOUND" /* NO_THEMES_FOUND */, {
        data: { themeName: activeTheme }
      });
    }
    const [, themes] = resolved;
    const theme = selectTheme(themes, activeTheme);
    if (!theme) {
      throw new ProcessorError("PROC_THEME_NOT_FOUND" /* THEME_NOT_FOUND */, {
        data: {
          themeName: activeTheme,
          availableThemes: themes.map((t) => t.name)
        }
      });
    }
    return extractSetNames(theme.selectedTokenSets);
  }
  const keys = Object.keys(jsonFiles);
  if (keys.length === 1) {
    return keys;
  }
  if (keys.length > 1) {
    throw new ProcessorError("PROC_MULTIPLE_SETS_NO_SELECTION" /* MULTIPLE_SETS_NO_SELECTION */, {
      data: { setNames: keys }
    });
  }
  throw new ProcessorError("PROC_NO_SETS_TO_PROCESS" /* NO_SETS_TO_PROCESS */);
}
function getSetTokens(setData) {
  if (setData instanceof Map) {
    return setData;
  }
  if (!isObject(setData)) {
    return /* @__PURE__ */ new Map();
  }
  if (isNested(setData)) {
    return flattenTokensObject(setData, "");
  }
  return recordToMap(setData);
}
function flattenToTokens(sets, setNames) {
  const tokens = /* @__PURE__ */ new Map();
  const entries = sets instanceof Map ? sets.entries() : setNames.map((name) => [name, sets[name]]);
  for (const [key, setData] of entries) {
    if (sets instanceof Map) {
      tokens.set(key, normalizeToTokenData(setData));
    } else {
      if (!setData) {
        throw new ProcessorError("PROC_TOKEN_SET_NOT_FOUND" /* TOKEN_SET_NOT_FOUND */, {
          data: { setName: key }
        });
      }
      if (!isObject(setData) && !(setData instanceof Map)) {
        throw new ProcessorError("PROC_TOKEN_SET_INVALID" /* TOKEN_SET_INVALID */, {
          data: { setName: key }
        });
      }
      const setTokens = getSetTokens(setData);
      for (const [tokenKey, value] of setTokens) {
        tokens.set(tokenKey, normalizeToTokenData(value));
      }
    }
  }
  return tokens;
}

// src/processor/process.ts
function processTokens(tokens, options) {
  const tokenDataMap = tokens instanceof Map ? flattenToTokens(tokens, []) : flattenToTokens({ tokens }, ["tokens"]);
  return buildTokens(tokenDataMap, options);
}
function processTokenSets(normalizedFiles, options) {
  const { activeSets, activeTheme } = options ?? {};
  const setNames = determineSets(normalizedFiles, activeSets, activeTheme);
  const tokens = flattenToTokens(normalizedFiles, setNames);
  return buildTokens(tokens, options);
}

// src/processor/errors.ts
function createDependencyError(tokenName, dependencyName, originalError) {
  const { chain, rootError } = extractDependencyInfo(tokenName, dependencyName, originalError);
  const chainStr = chain.join(" \u2192 ");
  return new ProcessorError("PROC_DEPENDENCY_ERROR" /* DEPENDENCY_ERROR */, {
    data: {
      tokenName,
      chain: chainStr,
      rootCause: rootError.message
    }
  });
}
function extractDependencyInfo(tokenName, dependencyName, error) {
  if (error instanceof ProcessorError && error.code === "PROC_DEPENDENCY_ERROR" /* DEPENDENCY_ERROR */ && error.data.chain) {
    const existingChain = String(error.data.chain).split(" \u2192 ");
    return {
      chain: [tokenName, ...existingChain],
      rootError: new Error(String(error.data.rootCause))
    };
  }
  return {
    chain: [tokenName, dependencyName],
    rootError: error
  };
}

// src/processor/resolver/TokenInterpreter.ts
var TokenInterpreter = class {
  constructor(referenceCache, config, options) {
    this.referenceCache = referenceCache;
    this.config = config;
    this.astNodes = /* @__PURE__ */ new Map();
    this.parsedConstants = /* @__PURE__ */ new Map();
    this.inlineConstantsEnabled = options?.inlineConstants ?? true;
    this.interpreter = new Interpreter(null, {
      references: this.referenceCache,
      config: this.config
    });
    if (this.inlineConstantsEnabled) {
      this.parseConstants();
    }
  }
  parseConstants() {
    if (!this.config) return;
    for (const [name, rawValue] of this.config.inlineConstants) {
      if (typeof rawValue === "string") {
        try {
          const { ast } = parseExpression(rawValue);
          if (ast) {
            const tempInterpreter = new Interpreter(ast, { config: this.config });
            const result = tempInterpreter.interpret();
            if (result !== null && typeof result !== "string") {
              this.parsedConstants.set(name, result);
            } else if (typeof result === "string") {
              this.parsedConstants.set(name, jsValueToSymbolType(result, this.config));
            }
          }
        } catch {
          this.parsedConstants.set(name, jsValueToSymbolType(rawValue, this.config));
        }
      } else {
        this.parsedConstants.set(name, jsValueToSymbolType(rawValue, this.config));
      }
    }
  }
  injectConstants() {
    for (const [name, value] of this.parsedConstants) {
      this.interpreter.setSymbol(name, value.cloneIfMutable());
    }
  }
  setTokenAST(tokenName, ast) {
    this.astNodes.set(tokenName, ast);
  }
  getTokenAST(tokenName) {
    return this.astNodes.get(tokenName);
  }
  interpretToken(tokenName, originalValue) {
    const ast = this.astNodes.get(tokenName);
    if (!ast) {
      return originalValue;
    }
    return this.interpretTokenWithAST(tokenName, ast);
  }
  interpretTokenWithAST(_tokenName, ast) {
    try {
      this.interpreter.resetSymbolTable();
      if (this.inlineConstantsEnabled) {
        this.injectConstants();
      }
      this.interpreter.setAst(ast);
      return this.interpreter.interpret();
    } catch (error) {
      if (isLanguageError(error)) {
        return error;
      }
      return new Error("Unknown error during token interpretation", { cause: error });
    }
  }
  buildDependencyError(tokenName, dependencies, resolved, missingDependencies) {
    for (const dep of dependencies) {
      const depValue = resolved.get(dep);
      if (depValue instanceof Error) {
        return createDependencyError(tokenName, dep, depValue);
      }
      if (missingDependencies?.has(dep)) {
        const error = new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
          data: { tokenName: dep }
        });
        return createDependencyError(tokenName, dep, error);
      }
    }
    return void 0;
  }
  flattenDictionaryToCache(tokenName, value) {
    if (!(value instanceof DictionarySymbol) || !value.value) {
      return [];
    }
    const flattenedNames = [];
    const entries = value.value;
    for (const [childKey, childValue] of entries) {
      const flattenedKey = `${tokenName}.${childKey}`;
      const clone = this.isSymbolType(childValue) ? childValue.cloneIfMutable() : childValue;
      this.referenceCache.set(flattenedKey, clone);
      flattenedNames.push(flattenedKey);
    }
    return flattenedNames;
  }
  updateReferenceCache(tokenName, value) {
    if (value instanceof Error) return;
    this.referenceCache.set(tokenName, value);
  }
  isSymbolType(value) {
    return Boolean(
      value && typeof value === "object" && typeof value.cloneIfMutable === "function"
    );
  }
};

// src/processor/object-parsers/default-object-parsers.ts
var defaultObjectParsers = [];

// src/processor/object-parsers/parsers/number-with-unit.ts
var numberWithUnitParser = {
  predicate: (value) => {
    if (!isObject(value)) {
      return false;
    }
    const obj = value;
    return "value" in obj && "unit" in obj && isNumber(obj.value) && isString(obj.unit) && Object.keys(obj).length === 2;
  },
  toSymbol: (value, config) => new NumberWithUnitSymbol(value.value, value.unit, config)
};

// src/processor/object-parsers/symbol-conversion.ts
function parseValueToSymbol(value, config, parsers = defaultObjectParsers) {
  if (value && typeof value === "object" && "getTypeName" in value) {
    return value;
  }
  for (const parser of parsers) {
    if (parser.predicate(value)) {
      return parser.toSymbol(value, config);
    }
  }
  return jsValueToSymbolType(value, config);
}
function createTokenSymbol(value, tokenType = "unknown", config, parsers = defaultObjectParsers, metadata) {
  if (isObject(value)) {
    const symbolMap = {};
    for (const [key, val] of Object.entries(value)) {
      symbolMap[key] = parseValueToSymbol(val, config, parsers);
    }
    return new TokenSymbol(tokenType, symbolMap, config, metadata);
  }
  if (isArray(value)) {
    const symbolArray = value.map((val) => parseValueToSymbol(val, config, parsers));
    return new TokenSymbol(tokenType, symbolArray, config, metadata);
  }
  return new TokenSymbol(tokenType, value, config, metadata);
}
function buildValueFromResolvedFields(currentPath, originalValue, resolvedFields, config, parsers = defaultObjectParsers) {
  if (resolvedFields.has(currentPath)) {
    return resolvedFields.get(currentPath);
  }
  if (isObject(originalValue)) {
    for (const parser of parsers) {
      if (parser.predicate(originalValue)) {
        return parser.toSymbol(originalValue, config);
      }
    }
    const symbolMap = {};
    for (const [key, val] of Object.entries(originalValue)) {
      const fieldPath = `${currentPath}.${key}`;
      symbolMap[key] = buildValueFromResolvedFields(
        fieldPath,
        val,
        resolvedFields,
        config,
        parsers
      );
    }
    return new DictionarySymbol(symbolMap, config);
  }
  if (isArray(originalValue)) {
    const symbolArray = [];
    for (let i = 0; i < originalValue.length; i++) {
      const fieldPath = `${currentPath}[${i}]`;
      symbolArray.push(
        buildValueFromResolvedFields(fieldPath, originalValue[i], resolvedFields, config, parsers)
      );
    }
    return new ListSymbol(symbolArray, false, config);
  }
  return parseValueToSymbol(originalValue, config, parsers);
}
function createTokenSymbolFromResolvedFields(tokenName, resolvedFields, originalValue, tokenType = "unknown", config, parsers = defaultObjectParsers, metadata) {
  if (isObject(originalValue)) {
    const symbolMap = {};
    for (const [key, val] of Object.entries(originalValue)) {
      const fieldPath = `${tokenName}.${key}`;
      symbolMap[key] = buildValueFromResolvedFields(
        fieldPath,
        val,
        resolvedFields,
        config,
        parsers
      );
    }
    return new TokenSymbol(tokenType, symbolMap, config, metadata);
  }
  if (isArray(originalValue)) {
    const symbolArray = [];
    for (let i = 0; i < originalValue.length; i++) {
      const fieldPath = `${tokenName}[${i}]`;
      symbolArray.push(
        buildValueFromResolvedFields(fieldPath, originalValue[i], resolvedFields, config, parsers)
      );
    }
    return new TokenSymbol(tokenType, symbolArray, config, metadata);
  }
  return new TokenSymbol(tokenType, originalValue, config, metadata);
}

// src/processor/utils/DependencyGraph.ts
var DependencyGraph = class {
  constructor() {
    this.nodes = /* @__PURE__ */ new Map();
  }
  addNode(node, dependencies = []) {
    if (!this.nodes.has(node)) {
      this.nodes.set(node, new Set(dependencies));
    }
  }
  removeNode(node) {
    this.nodes.delete(node);
    for (const deps of this.nodes.values()) {
      deps.delete(node);
    }
  }
  getNodes() {
    return this.nodes;
  }
  // Find nodes with no dependencies
  entryNodes() {
    const entries = [];
    for (const [node, deps] of this.nodes) {
      if (deps.size === 0) {
        entries.push(node);
      }
    }
    return entries;
  }
  // Find a cycle in the graph starting from the given nodes
  findCycle(candidateNodes) {
    const visited = /* @__PURE__ */ new Set();
    const recursionStack = /* @__PURE__ */ new Set();
    const path = [];
    const dfs = (node) => {
      visited.add(node);
      recursionStack.add(node);
      path.push(node);
      const deps = this.nodes.get(node);
      if (deps) {
        for (const dep of deps) {
          if (!visited.has(dep)) {
            if (dfs(dep)) {
              return true;
            }
          } else if (recursionStack.has(dep)) {
            return true;
          }
        }
      }
      path.pop();
      recursionStack.delete(node);
      return false;
    };
    for (const node of candidateNodes) {
      if (!visited.has(node)) {
        if (dfs(node)) {
          return path;
        }
      }
    }
    return candidateNodes;
  }
  // Topological sort using Kahn's algorithm
  topologicalSort() {
    const inDegree = /* @__PURE__ */ new Map();
    const result = [];
    for (const node of this.nodes.keys()) {
      inDegree.set(node, 0);
    }
    for (const deps of this.nodes.values()) {
      for (const dep of deps) {
        inDegree.set(dep, (inDegree.get(dep) || 0) + 1);
      }
    }
    const queue = [];
    for (const [node, degree] of inDegree) {
      if (degree === 0) {
        queue.push(node);
      }
    }
    while (queue.length > 0) {
      const node = queue.shift();
      if (node === void 0) break;
      result.push(node);
      const deps = this.nodes.get(node) || /* @__PURE__ */ new Set();
      for (const dep of deps) {
        const newDegree = (inDegree.get(dep) || 0) - 1;
        inDegree.set(dep, newDegree);
        if (newDegree === 0) {
          queue.push(dep);
        }
      }
    }
    if (result.length !== this.nodes.size) {
      const resultSet = new Set(result);
      const remainingNodes = [];
      for (const node of this.nodes.keys()) {
        if (!resultSet.has(node)) {
          remainingNodes.push(node);
        }
      }
      const cycle = this.findCycle(remainingNodes);
      const tokens = `${cycle.map((n) => String(n)).join(" \u2192 ")} \u2192 ${String(cycle[0])}`;
      throw new ProcessorError("PROC_CIRCULAR_DEPENDENCY" /* CIRCULAR_DEPENDENCY */, {
        data: { tokens }
      });
    }
    return result;
  }
};

// src/processor/utils/structured-tokens.ts
function matchesObjectParser(value, parsers) {
  if (!isObject(value)) return false;
  return parsers.some((parser) => parser.predicate(value));
}
function extractStringFields(value, parentPath, objectParsers = defaultObjectParsers) {
  const result = /* @__PURE__ */ new Map();
  const processValue = (val, path) => {
    if (isString(val)) {
      result.set(path, val);
    } else if (isObject(val)) {
      if (matchesObjectParser(val, objectParsers)) {
        return;
      }
      const nested = extractStringFields(val, path, objectParsers);
      for (const [nestedPath, nestedVal] of nested) {
        result.set(nestedPath, nestedVal);
      }
    } else if (isArray(val)) {
      const nested = extractStringFields(val, path, objectParsers);
      for (const [nestedPath, nestedVal] of nested) {
        result.set(nestedPath, nestedVal);
      }
    }
  };
  if (isObject(value)) {
    for (const [key, val] of Object.entries(value)) {
      processValue(val, `${parentPath}.${key}`);
    }
  } else if (isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      processValue(value[i], `${parentPath}[${i}]`);
    }
  }
  return result;
}

// src/processor/validator/types.ts
var ValidationSeverity = /* @__PURE__ */ ((ValidationSeverity2) => {
  ValidationSeverity2["ERROR"] = "error";
  ValidationSeverity2["WARNING"] = "warning";
  ValidationSeverity2["INFO"] = "info";
  return ValidationSeverity2;
})(ValidationSeverity || {});

// src/processor/resolver/TokenResolver.ts
function parseFieldPath(fieldPath) {
  const result = [];
  let remaining = fieldPath;
  while (remaining.length > 0) {
    const arrayMatch = remaining.match(/^\[(\d+)\]/);
    if (arrayMatch) {
      result.push(parseInt(arrayMatch[1], 10));
      remaining = remaining.substring(arrayMatch[0].length);
      continue;
    }
    const propMatch = remaining.match(/^\.?([^.[\]]+)/);
    if (propMatch) {
      result.push(propMatch[1]);
      remaining = remaining.substring(propMatch[0].length);
      continue;
    }
    if (remaining.startsWith(".")) {
      remaining = remaining.substring(1);
      continue;
    }
    break;
  }
  return result;
}
function errorToValidationIssue(error, parentToken, path) {
  return {
    code: error.code,
    severity: "error" /* ERROR */,
    message: path.length > 0 ? `Error at ${path.join(".")}: ${error.message}` : error.message,
    tokenName: parentToken,
    path,
    line: error.line,
    data: error.data
  };
}
function getTokenDependencyGraph(tokenName, graph) {
  const reverseDeps = /* @__PURE__ */ new Map();
  const graphNodes = graph.getNodes();
  for (const [node, dependencies] of graphNodes) {
    for (const dep of dependencies) {
      if (!reverseDeps.has(dep)) {
        reverseDeps.set(dep, /* @__PURE__ */ new Set());
      }
      reverseDeps.get(dep)?.add(node);
    }
  }
  const affectedTokens = /* @__PURE__ */ new Set();
  const queue = [tokenName];
  const visited = /* @__PURE__ */ new Set();
  while (queue.length > 0) {
    const current = queue.shift();
    if (current === void 0 || visited.has(current)) continue;
    visited.add(current);
    affectedTokens.add(current);
    const dependents = reverseDeps.get(current);
    if (dependents) {
      for (const dependent of dependents) {
        if (!visited.has(dependent)) {
          queue.push(dependent);
        }
      }
    }
  }
  const subgraph = new DependencyGraph();
  for (const token of affectedTokens) {
    const dependencies = graphNodes.get(token);
    if (dependencies) {
      const affectedDeps = /* @__PURE__ */ new Set();
      for (const dep of dependencies) {
        if (affectedTokens.has(dep)) {
          affectedDeps.add(dep);
        }
      }
      subgraph.addNode(token, affectedDeps);
    } else {
      subgraph.addNode(token, []);
    }
  }
  return {
    tokens: affectedTokens,
    subgraph
  };
}
var PrefixResolver = class _PrefixResolver {
  constructor(params) {
    this.params = params;
    this.graph = new DependencyGraph();
    this.resolved = /* @__PURE__ */ new Map();
    this.unresolved = /* @__PURE__ */ new Map();
    this.referenceCache = /* @__PURE__ */ new Map();
    this.pendingResolution = /* @__PURE__ */ new Set();
    this.readyQueue = /* @__PURE__ */ new Set();
    // Structured tokens tracking
    this.subFieldPaths = /* @__PURE__ */ new Set();
    this.structuredTokens = /* @__PURE__ */ new Map();
    // Issues collection (errors and lint issues)
    this.issues = /* @__PURE__ */ new Map();
    // Phase state
    this.earlyResolved = [];
    // Track missing dependencies that were referenced but don't exist
    this.missingDependencies = /* @__PURE__ */ new Set();
    const { tokens, callbacks, config, objectParsers } = params;
    this.tokens = tokens;
    this.callbacks = callbacks;
    this.config = config;
    this.objectParsers = objectParsers;
    this.dependencyTracker = new DependencyTracker();
    this.prefixManager = new PrefixManager(config);
    this.tokenInterpreter = new TokenInterpreter(this.referenceCache, config);
    this.readinessTracker = new ReadinessTracker();
    this.notifier = new ResolutionNotifier(
      this.dependencyTracker,
      this.prefixManager,
      this.readinessTracker,
      this.pendingResolution,
      this.readyQueue,
      (tokenName) => this.resolveSingleToken(tokenName),
      (prefix, cache) => this.buildPrefixDictionary(prefix, cache)
    );
  }
  addIssue(tokenName, issue) {
    const existing = this.issues.get(tokenName) || [];
    this.issues.set(tokenName, [...existing, issue]);
  }
  /**
   * Add an issue for a sub-field, converting the error to a ValidationIssue.
   * This ensures all issues have a uniform interface (same as validation issues).
   */
  addSubFieldIssue(parentToken, fieldPath, error) {
    const path = parseFieldPath(fieldPath);
    const issue = errorToValidationIssue(error, parentToken, path);
    this.addIssue(parentToken, issue);
  }
  ensureLanguageError(error) {
    if (isLanguageError(error)) {
      return error;
    }
    return new ProcessorError("PROC_UNKNOWN_PARSING_ERROR" /* UNKNOWN_PARSING_ERROR */, {
      data: { error: error.message }
    });
  }
  resolveError(refPath, error, value) {
    const isActualToken = this.tokens.has(refPath) || this.subFieldPaths.has(refPath);
    if (isActualToken) {
      this.resolved.set(refPath, error);
      this.callbacks?.onError?.(refPath, error, value);
      if (this.subFieldPaths.has(refPath)) {
        const { parentToken, fieldPath } = this.extractSubFieldMetadata(refPath);
        if (parentToken) {
          this.addSubFieldIssue(parentToken, fieldPath, error);
        } else {
          this.addIssue(refPath, error);
        }
      } else {
        this.addIssue(refPath, error);
      }
      this.earlyResolved.push(refPath);
      this.graph.addNode(refPath, []);
    }
    return error;
  }
  lintTokenResult(tokenName, value) {
    if (this.subFieldPaths.has(tokenName)) return;
    const tokenData = this.tokens.get(tokenName);
    const tokenType = tokenData && typeof tokenData === "object" && "$type" in tokenData ? tokenData.$type : void 0;
    this.validateTokenType(tokenName, tokenType, value);
  }
  /**
   * Validate token value against its registered type validation function.
   * Handles both top-level and nested validation errors.
   */
  validateTokenType(tokenName, tokenType, value) {
    if (!tokenType || !this.config?.tokenManager) return;
    if (!this.config.tokenManager.getSpecByType(tokenType)) return;
    if (value === null || typeof value === "string") return;
    let valueToValidate;
    if (value instanceof TokenSymbol) {
      const innerValue = value.value;
      if (Array.isArray(innerValue)) {
        valueToValidate = new ListSymbol(innerValue, false, this.config);
      } else if (innerValue instanceof Map) {
        valueToValidate = new DictionarySymbol(innerValue, this.config);
      } else {
        valueToValidate = value;
      }
    } else if (typeof value === "object" && value !== null && "type" in value) {
      valueToValidate = value;
    } else {
      return;
    }
    const validationResults = this.config.tokenManager.validate(tokenType, valueToValidate);
    for (const result of validationResults) {
      if (!result.valid && result.error) {
        const isNested2 = result.path && result.path.length > 0;
        const issue = {
          code: result.error,
          severity: "warning" /* WARNING */,
          message: isNested2 ? `Validation failed at ${result.path?.join(".")}: ${result.error}` : `Token validation failed: ${result.error}`,
          tokenName,
          path: result.path,
          data: isNested2 ? { tokenType: result.tokenType, parentTokenType: tokenType } : { tokenType }
        };
        this.addIssue(tokenName, issue);
      }
    }
  }
  earlyResolvePrimitiveToken(tokenName, value) {
    this.resolved.set(tokenName, value);
    this.referenceCache.set(tokenName, value);
    this.callbacks?.onResolve?.(tokenName, value);
    this.lintTokenResult(tokenName, value);
    this.graph.addNode(tokenName, []);
    this.earlyResolved.push(tokenName);
  }
  tryParseExpression(refPath, value) {
    try {
      return parseExpression(value);
    } catch (error) {
      if (isLanguageError(error)) {
        return this.resolveError(refPath, error, value);
      }
      return this.resolveError(
        refPath,
        new ProcessorError("PROC_UNKNOWN_PARSING_ERROR" /* UNKNOWN_PARSING_ERROR */, {
          data: { error: error instanceof Error ? error.message : String(error) }
        }),
        value
      );
    }
  }
  processParsedToken(tokenName, ast, dependencies) {
    this.tokenInterpreter.setTokenAST(tokenName, ast);
    if (dependencies.size > 0) {
      this.unresolved.set(tokenName, { ast, dependencies });
    }
    this.graph.addNode(tokenName, dependencies);
    for (const dep of dependencies) {
      if (this.prefixManager.hasPrefix(dep) && !this.tokens.has(dep)) {
        continue;
      }
      if (this.resolved.has(dep)) continue;
      this.dependencyTracker.addTokenDependency(tokenName, dep);
      if (this.tokens.has(dep)) continue;
      const parentToken = this.prefixManager.findParentToken(dep, this.tokens);
      if (parentToken) {
        this.prefixManager.addVirtualChild(parentToken, dep);
        continue;
      }
      if (!this.referenceCache.has(dep) && !this.resolved.has(dep) && !this.tokens.has(dep)) {
        this.missingDependencies.add(dep);
      }
    }
  }
  resolve() {
    this.parseAndBuildGraph();
    this.mapPrefixDependencies();
    this.releaseEarlyResolved();
    this.resolveDependencyFreeTokens();
    this.finalizeResolution();
    return {
      graph: this.graph,
      resolved: this.resolved,
      issues: this.issues.size > 0 ? this.issues : void 0
    };
  }
  // Expose internal state for incremental updates
  getGraph() {
    return this.graph;
  }
  getReferenceCache() {
    return this.referenceCache;
  }
  getTokenInterpreter() {
    return this.tokenInterpreter;
  }
  getSubFieldPaths() {
    return this.subFieldPaths;
  }
  clone(overrides) {
    const { tokens, callbacks } = {
      ...this.params,
      ...overrides
    };
    const resolver = new _PrefixResolver({
      tokens,
      callbacks,
      config: this.config,
      objectParsers: this.objectParsers
    });
    if (overrides.initialCache && overrides.tokens) {
      for (const [tokenName, value] of overrides.initialCache) {
        if (!overrides.tokens.has(tokenName)) {
          resolver.referenceCache.set(tokenName, value);
        }
      }
    }
    return resolver;
  }
  /**
   * Phase 1: Parse and build graph (ResolutionPhase.PARSE_AND_BUILD_GRAPH)
   * - Parse all token values into ASTs
   * - Build dependency graph
   * - Identify and mark early-resolved tokens
   * - Detect missing token dependencies
   * - Handle primitive and structured tokens
   */
  parseAndBuildGraph() {
    this.earlyResolved = [];
    for (const [tokenName, tokenData] of this.tokens.entries()) {
      const tokenValue = getTokenValue(tokenData);
      if (isString(tokenValue) && UNINTERPRETED_KEYWORDS.includes(tokenValue)) {
        const symbol = new StringSymbol(tokenValue, this.config);
        this.earlyResolvePrimitiveToken(tokenName, symbol);
        continue;
      }
      if (isNumber(tokenValue)) {
        this.earlyResolvePrimitiveToken(tokenName, new NumberSymbol(tokenValue, this.config));
        continue;
      }
      if (isBoolean(tokenValue)) {
        this.earlyResolvePrimitiveToken(tokenName, new BooleanSymbol(tokenValue, this.config));
        continue;
      }
      if (isNull(tokenValue)) {
        this.earlyResolvePrimitiveToken(tokenName, new NullSymbol(this.config));
        continue;
      }
      if (isObject(tokenValue) || isArray(tokenValue)) {
        this.handleStructuredToken(tokenName, setTokenValue(tokenData));
        continue;
      }
      const tokenValueStr = String(tokenValue);
      const parseResult = this.tryParseExpression(tokenName, tokenValueStr);
      if (parseResult instanceof Error) {
        continue;
      }
      const { ast, parser } = parseResult;
      if (!ast) {
        this.earlyResolvePrimitiveToken(tokenName, "");
        continue;
      }
      this.prefixManager.addTokenToPrefix(tokenName);
      this.processParsedToken(tokenName, ast, parser.requiredReferences);
    }
  }
  handleStructuredToken(tokenName, tokenData) {
    const tokenValue = tokenData.$value;
    this.structuredTokens.set(tokenName, tokenData);
    const stringFields = extractStringFields(
      tokenValue,
      tokenName,
      this.objectParsers || void 0
    );
    if (stringFields.size === 0) {
      const tokenType = tokenData.$type || "unknown";
      const tokenSymbol = createTokenSymbol(
        tokenValue,
        tokenType,
        this.config,
        this.objectParsers,
        tokenData.$metadata
      );
      this.resolved.set(tokenName, tokenSymbol);
      this.referenceCache.set(tokenName, tokenSymbol);
      this.callbacks?.onResolve?.(tokenName, tokenSymbol);
      this.lintTokenResult(tokenName, tokenSymbol);
      this.graph.addNode(tokenName, []);
      this.earlyResolved.push(tokenName);
      return;
    }
    for (const [fieldPath, fieldValue] of stringFields) {
      this.subFieldPaths.add(fieldPath);
      const parseResult = this.tryParseExpression(fieldPath, fieldValue);
      if (parseResult instanceof Error) {
        continue;
      }
      const { ast, parser } = parseResult;
      if (!ast) {
        this.earlyResolvePrimitiveToken(fieldPath, "");
        continue;
      }
      this.processParsedToken(fieldPath, ast, parser.requiredReferences);
    }
    const subFieldDeps = Array.from(stringFields.keys());
    this.graph.addNode(tokenName, subFieldDeps);
    for (const dep of subFieldDeps) {
      this.dependencyTracker.addTokenDependency(tokenName, dep);
    }
    this.unresolved.set(tokenName, {
      ast: null,
      dependencies: new Set(subFieldDeps)
    });
  }
  /**
   * Phase 2: Map prefix dependencies (ResolutionPhase.MAP_PREFIX_DEPENDENCIES)
   * - Identify which tokens depend on prefixes
   * - Activate prefix resolution tracking
   * - Mark prefix dependencies for later resolution
   */
  mapPrefixDependencies() {
    for (const [tokenName, unresolved] of this.unresolved.entries()) {
      for (const dep of unresolved.dependencies) {
        if (this.prefixManager.hasPrefix(dep) && !this.tokens.has(dep)) {
          this.prefixManager.activatePrefix(dep);
          this.dependencyTracker.addPrefixDependency(tokenName, dep);
        }
      }
    }
  }
  /**
   * Phase 3: Release early resolved (ResolutionPhase.RELEASE_EARLY_RESOLVED)
   * - Notify dependents of early-resolved tokens
   * - Release prefix dependencies waiting for these tokens
   * - Trigger cascade resolution of dependent tokens
   */
  releaseEarlyResolved() {
    for (const tokenName of this.earlyResolved) {
      this.notifyResolution(tokenName);
    }
  }
  /**
   * Phase 4: Resolve dependency-free tokens (ResolutionPhase.RESOLVE_DEPENDENCY_FREE)
   * - Seed ready queue with initially dependency-free tokens
   * - Process queue in event-driven manner (cascade resolution)
   * - Queue is populated by ResolutionNotifier when dependencies are released
   */
  resolveDependencyFreeTokens() {
    const allTokens = /* @__PURE__ */ new Set([...this.tokens.keys(), ...this.subFieldPaths]);
    for (const tokenName of allTokens) {
      if (this.resolved.has(tokenName)) continue;
      if (this.readinessTracker.isReady(tokenName, this.dependencyTracker)) {
        this.readyQueue.add(tokenName);
      }
    }
    while (this.readyQueue.size > 0) {
      const tokenName = this.readyQueue.values().next().value;
      this.readyQueue.delete(tokenName);
      this.resolveSingleToken(tokenName);
    }
  }
  /**
   * Extract parent token and field path from a sub-field token name.
   * Example: "shadow.card.offsetY" -> { parentToken: "shadow.card", fieldPath: "offsetY" }
   * Example: "shadow[0].blur" -> { parentToken: "shadow", fieldPath: "[0].blur" }
   */
  extractSubFieldMetadata(subFieldPath) {
    for (const [parentToken] of this.structuredTokens) {
      if (subFieldPath.startsWith(`${parentToken}.`) || subFieldPath.startsWith(`${parentToken}[`)) {
        const fieldPath = subFieldPath.substring(parentToken.length);
        const normalizedFieldPath = fieldPath.startsWith(".") ? fieldPath.substring(1) : fieldPath;
        return { parentToken, fieldPath: normalizedFieldPath };
      }
    }
    const lastDotIndex = subFieldPath.lastIndexOf(".");
    if (lastDotIndex !== -1) {
      return {
        parentToken: subFieldPath.substring(0, lastDotIndex),
        fieldPath: subFieldPath.substring(lastDotIndex + 1)
      };
    }
    return { parentToken: "", fieldPath: subFieldPath };
  }
  resolveSingleToken(tokenName) {
    if (this.resolved.has(tokenName)) return;
    this.pendingResolution.add(tokenName);
    if (this.structuredTokens.has(tokenName)) {
      this.resolveStructuredToken(tokenName);
      this.pendingResolution.delete(tokenName);
      return;
    }
    if (this.subFieldPaths.has(tokenName)) {
      const ast = this.tokenInterpreter.getTokenAST(tokenName);
      if (ast) {
        const unresolved2 = this.unresolved.get(tokenName);
        const dependencyError2 = unresolved2 ? this.tokenInterpreter.buildDependencyError(
          tokenName,
          unresolved2.dependencies,
          this.resolved
        ) : void 0;
        if (dependencyError2) {
          this.resolved.set(tokenName, dependencyError2);
          const { parentToken, fieldPath } = this.extractSubFieldMetadata(tokenName);
          this.callbacks?.onError?.(tokenName, dependencyError2, "", {
            isSubField: true,
            parentToken,
            fieldPath
          });
          if (parentToken) {
            this.addSubFieldIssue(parentToken, fieldPath, dependencyError2);
          } else {
            this.addIssue(tokenName, dependencyError2);
          }
        } else {
          const tokenValue2 = this.tokenInterpreter.interpretTokenWithAST(tokenName, ast);
          this.resolved.set(tokenName, tokenValue2);
          if (tokenValue2 instanceof Error) {
            const { parentToken, fieldPath } = this.extractSubFieldMetadata(tokenName);
            this.callbacks?.onError?.(tokenName, tokenValue2, "", {
              isSubField: true,
              parentToken,
              fieldPath
            });
            const langError = this.ensureLanguageError(tokenValue2);
            if (parentToken) {
              this.addSubFieldIssue(parentToken, fieldPath, langError);
            } else {
              this.addIssue(tokenName, langError);
            }
          } else {
            this.tokenInterpreter.updateReferenceCache(tokenName, tokenValue2);
          }
        }
      }
      this.unresolved.delete(tokenName);
      this.notifyResolution(tokenName);
      this.pendingResolution.delete(tokenName);
      return;
    }
    const originalValue = this.tokens.get(tokenName);
    if (originalValue === void 0) return;
    const tokenValueStr = String(getTokenValue(originalValue));
    const unresolved = this.unresolved.get(tokenName);
    const dependencyError = unresolved ? this.tokenInterpreter.buildDependencyError(
      tokenName,
      unresolved.dependencies,
      this.resolved
    ) : void 0;
    let tokenValue;
    if (dependencyError) {
      tokenValue = dependencyError;
      this.resolved.set(tokenName, dependencyError);
      this.callbacks?.onError?.(tokenName, dependencyError, tokenValueStr);
      this.addIssue(tokenName, dependencyError);
    } else {
      tokenValue = this.tokenInterpreter.interpretToken(tokenName, tokenValueStr);
      this.resolved.set(tokenName, tokenValue);
      if (tokenValue instanceof Error) {
        this.callbacks?.onError?.(tokenName, tokenValue, tokenValueStr);
        this.addIssue(tokenName, this.ensureLanguageError(tokenValue));
      } else {
        this.callbacks?.onResolve?.(tokenName, tokenValue);
        this.lintTokenResult(tokenName, tokenValue);
        this.tokenInterpreter.updateReferenceCache(tokenName, tokenValue);
      }
    }
    const flattened = this.tokenInterpreter.flattenDictionaryToCache(tokenName, tokenValue);
    this.resolveVirtualChildren(tokenName, flattened);
    this.notifyResolution(tokenName, flattened);
    this.unresolved.delete(tokenName);
    this.pendingResolution.delete(tokenName);
  }
  /**
   * Resolve a structured token by assembling resolved sub-fields
   */
  resolveStructuredToken(tokenName) {
    const tokenData = this.structuredTokens.get(tokenName);
    if (!tokenData) return;
    const originalValue = tokenData.$value;
    const stringFields = extractStringFields(
      originalValue,
      tokenName,
      this.objectParsers || void 0
    );
    const resolvedFields = /* @__PURE__ */ new Map();
    let hasError = false;
    for (const [fieldPath] of stringFields) {
      const fieldValue = this.resolved.get(fieldPath);
      if (fieldValue === void 0) {
        const error = new ProcessorError("PROC_SUB_FIELD_NOT_RESOLVED" /* SUB_FIELD_NOT_RESOLVED */, {
          data: { fieldPath }
        });
        this.resolved.set(tokenName, error);
        this.callbacks?.onError?.(tokenName, error, originalValue);
        this.addIssue(tokenName, error);
        hasError = true;
        break;
      }
      if (fieldValue instanceof Error) {
        this.resolved.set(tokenName, fieldValue);
        this.callbacks?.onError?.(tokenName, fieldValue, originalValue);
        this.addIssue(tokenName, this.ensureLanguageError(fieldValue));
        hasError = true;
        break;
      }
      resolvedFields.set(fieldPath, fieldValue);
    }
    if (!hasError) {
      const tokenType = tokenData.$type || "unknown";
      const tokenSymbol = createTokenSymbolFromResolvedFields(
        tokenName,
        resolvedFields,
        originalValue,
        tokenType,
        this.config,
        this.objectParsers,
        tokenData.$metadata
      );
      this.resolved.set(tokenName, tokenSymbol);
      this.referenceCache.set(tokenName, tokenSymbol);
      this.callbacks?.onResolve?.(tokenName, tokenSymbol);
      this.lintTokenResult(tokenName, tokenSymbol);
    }
    this.unresolved.delete(tokenName);
    this.notifyResolution(tokenName);
  }
  resolveVirtualChildren(parent, flattened) {
    const children = this.prefixManager.getAndRemoveVirtualChildren(parent);
    if (children.size === 0) return;
    const satisfied = flattened.length > 0 ? new Set(flattened) : null;
    const parentValue = this.resolved.get(parent);
    for (const child of children) {
      if (satisfied?.has(child) || this.referenceCache.has(child) || this.resolved.has(child)) {
        continue;
      }
      const error = parentValue instanceof Error ? createDependencyError(child, parent, parentValue) : new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
        data: { tokenName: child }
      });
      this.resolved.set(child, error);
      this.callbacks?.onError?.(child, error, "");
    }
  }
  notifyResolution(name, flattened) {
    this.notifier.releaseDependencies(name, flattened, this.referenceCache);
  }
  /**
   * Helper for ResolutionNotifier to build prefix dictionaries
   */
  buildPrefixDictionary(prefix, cache) {
    const dictionary = this.prefixManager.buildPrefixDictionary(prefix, cache);
    if (dictionary) {
      cache.set(prefix, dictionary);
    }
  }
  /**
   * Phase 5: Finalize resolution (ResolutionPhase.FINALIZE)
   * - Handle any true stragglers not caught by event-driven phase
   * - Generate errors for unresolved tokens with dependency issues
   * - Check for circular dependencies
   */
  finalizeResolution() {
    const unresolvedTokens = [];
    const allTokens = /* @__PURE__ */ new Set([...this.tokens.keys(), ...this.subFieldPaths]);
    for (const tokenName of allTokens) {
      if (this.resolved.has(tokenName)) continue;
      const isSubField = this.subFieldPaths.has(tokenName);
      let tokenValueStr = "";
      if (!isSubField) {
        const originalValue = this.tokens.get(tokenName);
        if (originalValue === void 0) continue;
        tokenValueStr = String(getTokenValue(originalValue));
      }
      const unresolved = this.unresolved.get(tokenName);
      if (unresolved) {
        const dependencyError = this.tokenInterpreter.buildDependencyError(
          tokenName,
          unresolved.dependencies,
          this.resolved,
          this.missingDependencies
        );
        if (dependencyError) {
          this.resolved.set(tokenName, dependencyError);
          if (isSubField) {
            const { parentToken, fieldPath } = this.extractSubFieldMetadata(tokenName);
            this.callbacks?.onError?.(tokenName, dependencyError, tokenValueStr, {
              isSubField: true,
              parentToken,
              fieldPath
            });
            if (parentToken) {
              this.addSubFieldIssue(parentToken, fieldPath, dependencyError);
            } else {
              this.addIssue(tokenName, dependencyError);
            }
          } else {
            this.callbacks?.onError?.(tokenName, dependencyError, tokenValueStr);
            this.addIssue(tokenName, dependencyError);
          }
          this.resolveVirtualChildren(tokenName, []);
          this.notifyResolution(tokenName);
          this.unresolved.delete(tokenName);
          continue;
        }
      }
      unresolvedTokens.push(tokenName);
    }
    while (this.readyQueue.size > 0) {
      const tokenName = this.readyQueue.values().next().value;
      this.readyQueue.delete(tokenName);
      this.resolveSingleToken(tokenName);
    }
    const stillUnresolved = unresolvedTokens.filter((tokenName) => !this.resolved.has(tokenName));
    if (stillUnresolved.length > 0) {
      const tokensWithMissingDeps = /* @__PURE__ */ new Set();
      for (const tokenName of stillUnresolved) {
        const unresolvedData = this.unresolved.get(tokenName);
        if (unresolvedData) {
          for (const dep of unresolvedData.dependencies) {
            if (this.missingDependencies.has(dep)) {
              tokensWithMissingDeps.add(tokenName);
              break;
            }
          }
        }
      }
      for (const tokenName of stillUnresolved) {
        const isSubField = this.subFieldPaths.has(tokenName);
        let tokenValueStr = "";
        if (!isSubField) {
          const originalValue = this.tokens.get(tokenName);
          if (originalValue === void 0) continue;
          tokenValueStr = String(getTokenValue(originalValue));
        }
        const dependsOnMissing = tokensWithMissingDeps.has(tokenName);
        const error = dependsOnMissing ? new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
          data: { tokenName }
        }) : new ProcessorError("PROC_CIRCULAR_DEPENDENCY" /* CIRCULAR_DEPENDENCY */, {
          data: { tokens: tokenName }
        });
        this.resolved.set(tokenName, error);
        if (isSubField) {
          const { parentToken, fieldPath } = this.extractSubFieldMetadata(tokenName);
          this.callbacks?.onError?.(tokenName, error, tokenValueStr, {
            isSubField: true,
            parentToken,
            fieldPath
          });
          if (parentToken) {
            this.addSubFieldIssue(parentToken, fieldPath, error);
          } else {
            this.addIssue(tokenName, error);
          }
        } else {
          this.callbacks?.onError?.(tokenName, error, tokenValueStr);
          this.addIssue(tokenName, error);
        }
        this.resolveVirtualChildren(tokenName, []);
        this.notifyResolution(tokenName);
        this.unresolved.delete(tokenName);
      }
    }
  }
};
var TokenResolver = class {
  processTokens(tokens, callbacks, config, objectParsers) {
    const resolver = new PrefixResolver({
      tokens,
      callbacks,
      config,
      objectParsers
    });
    return resolver.resolve();
  }
  /**
   * Find all tokens affected by a change to the given token.
   *
   * Uses BFS traversal on the reverse dependency graph to identify
   * the changed token plus all tokens that transitively depend on it.
   *
   * @param tokenName - The token that changed
   * @returns Object containing affected tokens and a subgraph showing their relationships
   *
   * @example
   * const { resolver } = new TokenResolver().build(tokens);
   * const { tokens, subgraph } = resolver.getTokenDependencyGraph("color.primary");
   * console.log(tokens); // Set(['color.primary', 'button.background', ...])
   */
  getTokenDependencyGraph(tokenName) {
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const graph = this.prefixResolver.getGraph();
    const reverseDeps = /* @__PURE__ */ new Map();
    const graphNodes = graph.getNodes();
    for (const [node, dependencies] of graphNodes) {
      for (const dep of dependencies) {
        if (!reverseDeps.has(dep)) {
          reverseDeps.set(dep, /* @__PURE__ */ new Set());
        }
        reverseDeps.get(dep)?.add(node);
      }
    }
    const affectedTokens = /* @__PURE__ */ new Set();
    const queue = [tokenName];
    const visited = /* @__PURE__ */ new Set();
    while (queue.length > 0) {
      const current = queue.shift();
      if (current === void 0 || visited.has(current)) continue;
      visited.add(current);
      affectedTokens.add(current);
      const dependents = reverseDeps.get(current);
      if (dependents) {
        for (const dependent of dependents) {
          if (!visited.has(dependent)) {
            queue.push(dependent);
          }
        }
      }
    }
    const subgraph = new DependencyGraph();
    for (const token of affectedTokens) {
      const dependencies = graphNodes.get(token);
      if (dependencies) {
        const affectedDeps = /* @__PURE__ */ new Set();
        for (const dep of dependencies) {
          if (affectedTokens.has(dep)) {
            affectedDeps.add(dep);
          }
        }
        subgraph.addNode(token, affectedDeps);
      } else {
        subgraph.addNode(token, []);
      }
    }
    return {
      tokens: affectedTokens,
      subgraph
    };
  }
  build(tokens, config, objectParsers) {
    const output = /* @__PURE__ */ new Map();
    const callbacks = {
      onResolve: (tokenName, value) => {
        output.set(tokenName, value);
      },
      onError: (tokenName, _error, originalValue) => {
        output.set(tokenName, originalValue);
      }
    };
    this.prefixResolver = new PrefixResolver({
      tokens,
      callbacks,
      config,
      objectParsers
    });
    this.tokens = tokens;
    this.config = config;
    this.objectParsers = objectParsers;
    const result = this.prefixResolver.resolve();
    const subFieldPaths = this.prefixResolver.getSubFieldPaths();
    if (subFieldPaths.size > 0) {
      for (const subFieldPath of subFieldPaths) {
        output.delete(subFieldPath);
        result.issues?.delete(subFieldPath);
      }
    }
    return {
      ...result,
      tokens: output,
      resolver: this,
      issues: result.issues
    };
  }
  ensureInitialized() {
    if (!this.prefixResolver || !this.tokens) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
  }
  normalizeTokenPath(tokenPath) {
    return tokenPath?.trim() || "";
  }
  createOutputCallbacks() {
    const output = /* @__PURE__ */ new Map();
    const callbacks = {
      onResolve: (name, value) => {
        output.set(name, value);
      },
      onError: (_name, _error) => {
      }
    };
    return { output, callbacks };
  }
  rebuildResolver(updatedTokens, callbacks) {
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const newResolver = this.prefixResolver.clone({
      tokens: updatedTokens,
      callbacks
    });
    const result = newResolver.resolve();
    this.prefixResolver = newResolver;
    return result;
  }
  updateToken(params) {
    this.ensureInitialized();
    const { tokenPath, tokenData, tokenPathRenamed, updateReferences = false } = params;
    const prevPath = this.normalizeTokenPath(tokenPath);
    const newPath = tokenPathRenamed?.trim();
    if (!this.tokens || !this.tokens.has(prevPath)) {
      if (tokenData) {
        const createResult = this.createToken({
          tokenPath: prevPath,
          tokenData
        });
        return {
          ...createResult,
          updated: false
        };
      }
      throw new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
        data: { tokenName: prevPath }
      });
    }
    const oldTokenData = this.tokens.get(prevPath);
    if (!oldTokenData) {
      throw new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
        data: { tokenName: prevPath }
      });
    }
    const isRename = newPath && newPath !== prevPath;
    if (isRename && this.tokens.has(newPath)) {
      throw new ProcessorError("PROC_TOKEN_ALREADY_EXISTS" /* TOKEN_ALREADY_EXISTS */, {
        data: { tokenName: newPath }
      });
    }
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const currentGraph = this.prefixResolver.getGraph();
    const { tokens: affectedTokens } = getTokenDependencyGraph(prevPath, currentGraph);
    affectedTokens.delete(prevPath);
    const updatedTokens = new Map(this.tokens);
    if (isRename && updateReferences && affectedTokens.size > 0) {
      const renameMap = { [prevPath]: newPath };
      const tokenInterpreter = this.prefixResolver.getTokenInterpreter();
      for (const dependentToken of affectedTokens) {
        const dependentTokenData = updatedTokens.get(dependentToken);
        if (!dependentTokenData) continue;
        const dependentValue = getTokenValue(dependentTokenData);
        if (!isString(dependentValue)) continue;
        const ast = tokenInterpreter.getTokenAST(dependentToken);
        if (!ast) continue;
        const updatedValue = renameReferences(dependentValue, ast, renameMap);
        if (updatedValue !== dependentValue) {
          const updatedTokenData = { ...dependentTokenData, $value: updatedValue };
          updatedTokens.set(dependentToken, updatedTokenData);
        }
      }
    }
    updatedTokens.delete(prevPath);
    const finalPath = isRename ? newPath : prevPath;
    updatedTokens.set(finalPath, tokenData || oldTokenData);
    this.tokens = updatedTokens;
    const { output, callbacks } = this.createOutputCallbacks();
    const resolverResult = this.rebuildResolver(updatedTokens, callbacks);
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const { subgraph } = getTokenDependencyGraph(finalPath, this.prefixResolver.getGraph());
    const resolvedValue = output.get(finalPath);
    return {
      tokens: output,
      resolved: resolvedValue,
      issues: resolverResult.issues,
      dependants: { graph: subgraph },
      updated: true
    };
  }
  createToken(params) {
    this.ensureInitialized();
    const { tokenPath, tokenData } = params;
    const normalizedTokenPath = this.normalizeTokenPath(tokenPath);
    if (this.tokens?.has(normalizedTokenPath)) {
      throw new ProcessorError("PROC_TOKEN_ALREADY_EXISTS" /* TOKEN_ALREADY_EXISTS */, {
        data: { tokenName: normalizedTokenPath }
      });
    }
    const updatedTokens = new Map(this.tokens);
    updatedTokens.set(normalizedTokenPath, tokenData);
    this.tokens = updatedTokens;
    const { output, callbacks } = this.createOutputCallbacks();
    const resolverResult = this.rebuildResolver(updatedTokens, callbacks);
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const { subgraph } = getTokenDependencyGraph(
      normalizedTokenPath,
      this.prefixResolver.getGraph()
    );
    const resolvedValue = output.get(normalizedTokenPath);
    return {
      tokens: output,
      resolved: resolvedValue,
      issues: resolverResult.issues,
      dependants: { graph: subgraph },
      created: true
    };
  }
  deleteToken(params) {
    this.ensureInitialized();
    const { tokenPath } = params;
    const normalizedTokenPath = this.normalizeTokenPath(tokenPath);
    if (!this.tokens?.has(normalizedTokenPath)) {
      throw new ProcessorError("PROC_TOKEN_NOT_FOUND" /* TOKEN_NOT_FOUND */, {
        data: { tokenName: normalizedTokenPath }
      });
    }
    if (!this.prefixResolver) {
      throw new ProcessorError("PROC_RESOLVER_NOT_INITIALIZED" /* RESOLVER_NOT_INITIALIZED */);
    }
    const currentGraph = this.prefixResolver.getGraph();
    const { subgraph } = getTokenDependencyGraph(normalizedTokenPath, currentGraph);
    subgraph.removeNode(normalizedTokenPath);
    const updatedTokens = new Map(this.tokens);
    updatedTokens.delete(normalizedTokenPath);
    this.tokens = updatedTokens;
    const { output, callbacks } = this.createOutputCallbacks();
    const resolverResult = this.rebuildResolver(updatedTokens, callbacks);
    return {
      tokens: output,
      issues: resolverResult.issues,
      dependants: { graph: subgraph }
    };
  }
};

// src/processor/builders/MapBuilder.ts
var MapBuilder = class {
  constructor() {
    this.name = "map";
    this.result = /* @__PURE__ */ new Map();
    this.successfullyResolved = /* @__PURE__ */ new Map();
  }
  onResolve(tokenName, value) {
    this.successfullyResolved.set(tokenName, value);
    this.result.set(tokenName, value);
  }
  onError(tokenName, _error, originalValue) {
    this.result.set(tokenName, originalValue);
  }
  getResult() {
    return this.result;
  }
  getResolvedTokens() {
    return this.successfullyResolved;
  }
};

// src/processor/builders/base.ts
function buildTokens(tokens, options) {
  const { config, builder = new MapBuilder(), objectParsers } = options ?? {};
  const tokensMapBuilder = builder.constructor === MapBuilder ? builder : new MapBuilder();
  const result = new TokenResolver().build(tokens, config, objectParsers);
  for (const [tokenName, value] of result.tokens) {
    const error = getTokenError(result.issues, tokenName);
    if (error) {
      const originalValue = tokens.get(tokenName);
      const originalValueData = typeof originalValue === "string" ? originalValue : originalValue?.$value;
      builder.onError(tokenName, error, originalValueData);
      if (builder.constructor !== MapBuilder)
        tokensMapBuilder.onError(tokenName, error, originalValueData);
    } else {
      builder.onResolve(tokenName, value);
      if (builder.constructor !== MapBuilder) tokensMapBuilder.onResolve(tokenName, value);
    }
  }
  const tokensMap = tokensMapBuilder.getResult();
  const builderOutput = builder.getResult();
  const issues = result.issues;
  return {
    ...result,
    tokens: tokensMap,
    output: builderOutput,
    issues,
    resolver: result.resolver
  };
}

// src/processor/builders/flatten.ts
function flattenChildrenObject(result, prefix, callback) {
  if (result instanceof DictionarySymbol) {
    flattenChildrenMap(result.value, prefix, callback);
  }
}
function flattenChildrenMap(map, prefix, callback) {
  for (const [key, value] of map.entries()) {
    const newKey = `${prefix}.${key}`;
    if (typeof value === "undefined") {
      continue;
    }
    if (value instanceof DictionarySymbol) {
      flattenChildrenMap(value.value, newKey, callback);
    } else {
      callback(newKey, value);
    }
  }
}

// src/processor/builders/ObjectBuilder.ts
function setNestedValue(target, path, value) {
  if (path.length === 0) {
    return;
  }
  const segments = path.split(".");
  let cursor = target;
  for (let i = 0; i < segments.length; i++) {
    const key = segments[i];
    const isLast = i === segments.length - 1;
    if (isLast) {
      cursor[key] = value;
      return;
    }
    if (!isObject(cursor[key])) {
      cursor[key] = {};
    }
    cursor = cursor[key];
  }
}
var NestedObjectBuilder = class {
  constructor() {
    this.name = "nested";
    this.result = {};
  }
  onResolve(tokenName, value) {
    const serialized = serializeInterpreterResult(value, { stringify: true });
    if (typeof serialized !== "undefined") {
      setNestedValue(this.result, tokenName, serialized);
    }
  }
  onError(tokenName, _error, originalValue) {
    setNestedValue(this.result, tokenName, originalValue);
  }
  getResult() {
    return this.result;
  }
};
var FlatObjectBuilder = class {
  constructor() {
    this.name = "flat";
    this.result = {};
  }
  onResolve(tokenName, value) {
    let didFlatten = false;
    flattenChildrenObject(value, tokenName, (key, val) => {
      didFlatten = true;
      this.result[key] = serializeInterpreterResult(val, { stringify: true });
    });
    if (!didFlatten) {
      const serialized = serializeInterpreterResult(value, { stringify: true });
      if (typeof serialized !== "undefined") {
        this.result[tokenName] = serialized;
      }
    }
  }
  onError(tokenName, _error, originalValue) {
    this.result[tokenName] = originalValue;
  }
  getResult() {
    return this.result;
  }
};

// src/processor/builders/StringMapBuilder.ts
var StringMapBuilder = class extends MapBuilder {
  onResolve(tokenName, value) {
    super.onResolve(tokenName, value);
    this.result.set(tokenName, stringifyInterpreterResult(value));
  }
  getResult() {
    const stringMap = /* @__PURE__ */ new Map();
    for (const [key, value] of this.result.entries()) {
      stringMap.set(key, typeof value === "string" ? value : stringifyInterpreterResult(value));
    }
    return stringMap;
  }
};

export { FlatObjectBuilder, MapBuilder, NestedObjectBuilder, StringMapBuilder, TokenResolver, ValidationSeverity, buildTokens, createDependencyError, defaultObjectParsers, flattenChildrenMap, flattenChildrenObject, getAffectedTokens, getBrokenReferences, getModifiedDependants, getRenamedReferences, getTokensWithIssues, hasAnyIssues, hasIssueWithCode, numberWithUnitParser, processTokenSets, processTokens, tokenHasIssueWithCode };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map