import { ParseError, LoadingError, SchemaError, ResolutionError } from './chunk-DRL5U3PK.js';
import { __name } from './chunk-IBAHCH6O.js';
import { createHash } from 'crypto';

var NPM_PACKAGE_NAME_RE = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i;
var NPM_VERSION_RE = /^[\d]+(?:\.[\d]+)*(?:-[\w.-]+)?$/;
var TELEMETRY_IDENTIFIER_RE = /^[a-zA-Z][\w-]{0,63}$/;
var KNOWN_SOURCE_TYPES = /* @__PURE__ */ new Set(["schema", "example", "defaults", "values", "overrides"]);
var PLUGIN_ATTR_KEY_RE = /^[a-z][a-z0-9_]{0,39}$/;
var PLUGIN_ATTR_ENUM_RE = /^[a-zA-Z][\w-]{0,31}$/;
var MAX_PLUGIN_ATTR_KEYS = 24;
var sessionUsageContext = {
  plugins: [],
  features: null
};
var sessionGraph;
var sessionGraphLoaded = false;
var sessionLoadFailureErrorCode = null;
var cachedIntegrationFromEnv;
function hashTelemetryValue(value) {
  return createHash("sha256").update(value).digest("hex");
}
__name(hashTelemetryValue, "hashTelemetryValue");
function isOfficialVarlockPackageName(name) {
  return name.startsWith("@varlock/");
}
__name(isOfficialVarlockPackageName, "isOfficialVarlockPackageName");
function isBlockingError(err) {
  return !err.isWarning;
}
__name(isBlockingError, "isBlockingError");
function classifyGraphTelemetryErrorCode(graph) {
  if (graph.plugins.some((p) => p.loadingError && isBlockingError(p.loadingError))) {
    return "plugin_error";
  }
  for (const source of graph.sortedDataSources) {
    const loadingError = source.loadingError;
    if (loadingError instanceof ParseError && isBlockingError(loadingError)) {
      return "parse_error";
    }
    for (const err of source.errors) {
      if (!isBlockingError(err)) continue;
      if (err instanceof ParseError) return "parse_error";
      if (err instanceof LoadingError) return "load_error";
      if (err instanceof SchemaError) return "schema_error";
    }
    for (const err of source.resolutionErrors) {
      if (isBlockingError(err)) return "resolution_error";
    }
  }
  for (const itemKey of graph.sortedConfigKeys) {
    if (graph.configSchema[itemKey].validationState === "error") {
      return "validation_error";
    }
  }
  return null;
}
__name(classifyGraphTelemetryErrorCode, "classifyGraphTelemetryErrorCode");
function classifyThrownTelemetryErrorCode(err) {
  let current = err;
  while (current instanceof Error) {
    if (current instanceof ParseError) return "parse_error";
    if (current instanceof SchemaError) return "schema_error";
    if (current instanceof ResolutionError) return "resolution_error";
    if (current instanceof LoadingError) return "load_error";
    current = current.cause;
  }
  return "load_error";
}
__name(classifyThrownTelemetryErrorCode, "classifyThrownTelemetryErrorCode");
function sanitizeIntegrationIdentity(integration) {
  if (!integration) return null;
  const { name, version } = integration;
  if (name.length > 128 || version.length > 32 || !isOfficialVarlockPackageName(name) || !NPM_PACKAGE_NAME_RE.test(name)) {
    return null;
  }
  if (version !== "unknown" && !NPM_VERSION_RE.test(version)) return null;
  return { name, version };
}
__name(sanitizeIntegrationIdentity, "sanitizeIntegrationIdentity");
function sanitizeFeatureIdentifier(name) {
  if (name.startsWith("\0")) return null;
  if (!TELEMETRY_IDENTIFIER_RE.test(name)) return null;
  return name;
}
__name(sanitizeFeatureIdentifier, "sanitizeFeatureIdentifier");
var DROP_ATTR = /* @__PURE__ */ Symbol("drop-attr");
function sanitizePluginAttributeValue(value) {
  if (value === null) return null;
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return Number.isFinite(value) ? value : DROP_ATTR;
  if (typeof value === "string") return PLUGIN_ATTR_ENUM_RE.test(value) ? value : DROP_ATTR;
  return DROP_ATTR;
}
__name(sanitizePluginAttributeValue, "sanitizePluginAttributeValue");
function sanitizePluginAttributes(provider) {
  if (typeof provider !== "function") return null;
  let raw;
  try {
    raw = provider();
  } catch {
    return null;
  }
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const out = {};
  let count = 0;
  for (const [key, value] of Object.entries(raw)) {
    if (count >= MAX_PLUGIN_ATTR_KEYS) break;
    if (!PLUGIN_ATTR_KEY_RE.test(key)) continue;
    const sanitized = sanitizePluginAttributeValue(value);
    if (sanitized === DROP_ATTR) continue;
    out[key] = sanitized;
    count += 1;
  }
  return Object.keys(out).length ? out : null;
}
__name(sanitizePluginAttributes, "sanitizePluginAttributes");
function sanitizePluginForTelemetry(plugin) {
  const isOfficial = isOfficialVarlockPackageName(plugin.name);
  const nameIsHashed = !isOfficial && plugin.name !== "unnamed plugin";
  return {
    name: nameIsHashed ? hashTelemetryValue(plugin.name) : plugin.name,
    version: isOfficial ? plugin.version : null,
    type: plugin.type,
    is_official: isOfficial,
    name_is_hashed: nameIsHashed,
    has_loading_error: !!plugin.loadingError,
    warning_count: plugin.warnings.length,
    // only official plugins' attribute providers are run (we author/review those)
    attributes: isOfficial ? sanitizePluginAttributes(plugin._getTelemetryAttributes) : null
  };
}
__name(sanitizePluginForTelemetry, "sanitizePluginForTelemetry");
function parseIntegrationFromEnv(envValue = process.env.__VARLOCK_INTEGRATION) {
  if (!envValue?.trim()) return null;
  const trimmed = envValue.trim();
  if (trimmed.length > 160) return null;
  const at = trimmed.lastIndexOf("@");
  const parsed = at <= 0 ? { name: trimmed, version: "unknown" } : {
    name: trimmed.slice(0, at),
    version: trimmed.slice(at + 1) || "unknown"
  };
  return sanitizeIntegrationIdentity(parsed);
}
__name(parseIntegrationFromEnv, "parseIntegrationFromEnv");
function collectResolverNames(resolver, names) {
  if (!resolver) return;
  const sanitized = sanitizeFeatureIdentifier(resolver.fnName);
  if (sanitized) names.add(sanitized);
  for (const child of resolver.arrArgs ?? []) collectResolverNames(child, names);
  for (const child of Object.values(resolver.objArgs ?? {})) collectResolverNames(child, names);
}
__name(collectResolverNames, "collectResolverNames");
function countSourceTypes(sources) {
  const counts = {};
  for (const source of sources) {
    if (!KNOWN_SOURCE_TYPES.has(source.type)) continue;
    counts[source.type] = (counts[source.type] ?? 0) + 1;
  }
  return counts;
}
__name(countSourceTypes, "countSourceTypes");
function captureUsageContextFromEnvGraph(graph) {
  sessionGraph = graph;
  sessionGraphLoaded = true;
  sessionLoadFailureErrorCode = null;
  const serialized = graph.getSerializedGraph();
  const resolverNames = /* @__PURE__ */ new Set();
  for (const itemKey of graph.sortedConfigKeys) {
    collectResolverNames(graph.configSchema[itemKey].valueResolver, resolverNames);
  }
  const rootDecoratorNames = /* @__PURE__ */ new Set();
  for (const source of graph.sortedDataSources) {
    for (const dec of source.rootDecorators) {
      const sanitized = sanitizeFeatureIdentifier(dec.name);
      if (sanitized) rootDecoratorNames.add(sanitized);
    }
  }
  sessionUsageContext = {
    plugins: graph.plugins.map((p) => sanitizePluginForTelemetry(p)),
    features: {
      settings: serialized.settings,
      cache_mode: graph._cacheMode,
      resolver_names: [...resolverNames].sort(),
      root_decorator_names: [...rootDecoratorNames].sort(),
      source_type_counts: countSourceTypes(serialized.sources),
      config_item_count: graph.sortedConfigKeys.length
    }
  };
}
__name(captureUsageContextFromEnvGraph, "captureUsageContextFromEnvGraph");
function captureTelemetryGraphLoadFailure(err) {
  sessionGraph = void 0;
  sessionGraphLoaded = false;
  sessionLoadFailureErrorCode = classifyThrownTelemetryErrorCode(err);
  sessionUsageContext = { plugins: [], features: null };
}
__name(captureTelemetryGraphLoadFailure, "captureTelemetryGraphLoadFailure");
function resolveTelemetryErrorCode() {
  if (sessionGraphLoaded && sessionGraph) {
    return classifyGraphTelemetryErrorCode(sessionGraph);
  }
  return sessionLoadFailureErrorCode;
}
__name(resolveTelemetryErrorCode, "resolveTelemetryErrorCode");
function getTelemetryUsageContext() {
  if (cachedIntegrationFromEnv === void 0) {
    cachedIntegrationFromEnv = parseIntegrationFromEnv();
  }
  return {
    integration: cachedIntegrationFromEnv,
    plugins: sessionUsageContext.plugins,
    features: sessionUsageContext.features,
    graph_loaded: sessionGraphLoaded,
    error_code: resolveTelemetryErrorCode()
  };
}
__name(getTelemetryUsageContext, "getTelemetryUsageContext");
function getTelemetryUsageContextPayload() {
  const ctx = getTelemetryUsageContext();
  return {
    integration_name: ctx.integration?.name ?? null,
    integration_version: ctx.integration?.version ?? null,
    // Flat, directly-breakdownable list of official plugin names in use (an
    // array of strings can be sliced in PostHog's UI; the nested `plugins`
    // detail below needs HogQL/SQL to query). Third-party (hashed) plugins are
    // excluded here — see `plugins` for those.
    official_plugins: ctx.plugins.filter((p) => p.is_official).map((p) => p.name).sort(),
    plugins: ctx.plugins,
    features: ctx.features,
    graph_loaded: ctx.graph_loaded,
    error_code: ctx.error_code
  };
}
__name(getTelemetryUsageContextPayload, "getTelemetryUsageContextPayload");

export { captureTelemetryGraphLoadFailure, captureUsageContextFromEnvGraph, getTelemetryUsageContextPayload };
//# sourceMappingURL=chunk-XEN5SRUR.js.map
//# sourceMappingURL=chunk-XEN5SRUR.js.map