(function() {
  "use strict";
  const registry = /* @__PURE__ */ new Map();
  function getTransformer(id) {
    return registry.get(id);
  }
  const ALIASES = {
    // filterFieldsByName is first-class; filterByName is internal alias
    filterByName: "filterFieldsByName",
    filterFramesByRefId: "filterByRefId",
    seriesToColumns: "joinByField"
  };
  const DEFAULT_OPTIONS$1 = {
    limit: { limitField: 10 },
    sortBy: { sort: [] },
    reduce: { reducers: ["sum"] },
    histogram: { bucketCount: 10 },
    smoothing: { windowSize: 3 },
    filterByValue: { type: "include", filters: [] },
    prepareTimeSeries: { format: "multi" }
  };
  function resolveTransformerId(id) {
    return ALIASES[id] ?? id;
  }
  function deepCloneFrames(frames) {
    return frames.map((frame) => {
      const fields = frame.fields.map((f) => ({
        name: f.name,
        type: f.type,
        config: f.config ? { ...f.config } : {},
        values: f.values.slice(),
        labels: f.labels ? { ...f.labels } : void 0,
        state: f.state ? { ...f.state } : void 0
      }));
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta ? { ...frame.meta } : void 0,
        fields,
        length: frame.length ?? fields[0]?.values.length ?? 0
      };
    });
  }
  function interpolateOptions(value, interpolate) {
    return value;
  }
  function patternFromFilterOptions(options) {
    if (options == null) return "";
    if (typeof options === "string" || typeof options === "number")
      return String(options);
    if (typeof options === "object") {
      const o = options;
      if (o.pattern != null) return String(o.pattern);
      if (o.refId != null) return String(o.refId);
      if (o.value != null) return String(o.value);
      if (Array.isArray(o.names))
        return o.names.map(String).join("|");
    }
    return String(options);
  }
  function compileMatcher(raw) {
    const s = raw.trim();
    if (!s) return () => true;
    const m = s.match(/^\/(.+)\/([gimsuy]*)$/);
    if (m) {
      try {
        const re = new RegExp(m[1], m[2]);
        return (v) => re.test(v);
      } catch {
        return (v) => v === s;
      }
    }
    try {
      const re = new RegExp(`^(?:${s})$`);
      return (v) => re.test(v);
    } catch {
      return (v) => v === s;
    }
  }
  function matchFrameFilter(frame, filter) {
    if (filter == null || filter === "") return true;
    if (typeof filter === "string") {
      const hit2 = compileMatcher(filter);
      return hit2(String(frame.refId ?? "")) || hit2(String(frame.name ?? ""));
    }
    const id = String(filter.id || "byRefId");
    const pattern = patternFromFilterOptions(filter.options);
    const hit = compileMatcher(pattern);
    if (id === "byName" || id === "byFrameName") {
      return hit(String(frame.name ?? ""));
    }
    if (id === "byRefId" || id === "byFrameRefID" || id === "byFrameRefId") {
      return hit(String(frame.refId ?? ""));
    }
    return hit(String(frame.refId ?? "")) || hit(String(frame.name ?? ""));
  }
  function applyWithFrameFilter(frames, filter, fn, options) {
    if (filter == null || filter === "") {
      return fn(frames, options);
    }
    const matched = [];
    const passthrough = /* @__PURE__ */ new Map();
    frames.forEach((f, i) => {
      if (matchFrameFilter(f, filter)) {
        matched.push(f);
      } else {
        passthrough.set(i, f);
      }
    });
    if (!matched.length) return frames;
    const transformed = fn(matched, options);
    const out = [];
    let inserted = false;
    for (let i = 0; i < frames.length; i++) {
      if (passthrough.has(i)) {
        out.push(passthrough.get(i));
      } else if (!inserted) {
        out.push(...transformed);
        inserted = true;
        transformed.length;
      }
    }
    if (!inserted) out.push(...transformed);
    return out;
  }
  function readLimitOption$1(options) {
    if (!options) return void 0;
    const raw = options.limit ?? options.limitField ?? options.limitValue;
    if (raw == null) return void 0;
    const n = Math.floor(Number(raw));
    return Number.isFinite(n) && n >= 0 ? n : void 0;
  }
  function tryFuseSortLimit$1(transformations, index) {
    const cur = transformations[index];
    const next = transformations[index + 1];
    if (!cur || !next) return null;
    if (cur.disabled || next.disabled) return null;
    const curId = resolveTransformerId(cur.id);
    const nextId = resolveTransformerId(next.id);
    if (curId !== "sortBy" || nextId !== "limit") return null;
    const f1 = cur.filter ?? null;
    const f2 = next.filter ?? null;
    if (JSON.stringify(f1) !== JSON.stringify(f2)) return null;
    const lim = readLimitOption$1(next.options);
    if (lim == null) return null;
    return {
      fusedOptions: { ...cur.options || {}, limit: lim, limitField: lim, limitValue: lim },
      skipNext: true
    };
  }
  function applyTransformations(frames, transformations = [], diagnostics, context) {
    let acc = deepCloneFrames(frames);
    if (!transformations.length) return acc;
    const localDiag = [];
    for (let i = 0; i < transformations.length; i++) {
      const t = transformations[i];
      if (t.disabled) continue;
      const resolvedId = resolveTransformerId(t.id);
      const fn = getTransformer(resolvedId) ?? getTransformer(t.id);
      if (!fn) {
        localDiag.push({
          id: t.id,
          level: "warn",
          message: `Unknown transformation: ${t.id}`
        });
        continue;
      }
      const defaults = DEFAULT_OPTIONS$1[resolvedId] ?? DEFAULT_OPTIONS$1[t.id] ?? {};
      const fuse = tryFuseSortLimit$1(transformations, i);
      const stepOptions = fuse ? { ...defaults, ...fuse.fusedOptions } : { ...defaults, ...t.options || {} };
      const merged = interpolateOptions(stepOptions);
      try {
        acc = applyWithFrameFilter(
          acc,
          t.filter,
          fn,
          merged
        );
        if (fuse?.skipNext) i += 1;
      } catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        localDiag.push({ id: t.id, level: "error", message: msg });
        throw e;
      }
    }
    return acc;
  }
  function asNames(options) {
    if (Array.isArray(options)) return options.map(String);
    if (options && typeof options === "object" && Array.isArray(options.names)) {
      return options.names.map(String);
    }
    return String(options?.names ?? options ?? "").split(",").map((s) => s.trim()).filter(Boolean);
  }
  function safeRegExp(pattern) {
    try {
      return new RegExp(String(pattern ?? ""));
    } catch {
      return null;
    }
  }
  const MATCHERS = [
    {
      id: "byName",
      name: "字段名称为",
      pickerDefault: true,
      get: (options) => (field) => field.name === options
    },
    {
      id: "byNames",
      name: "字段名称为（列表）",
      pickerDefault: true,
      get: (options) => (field) => {
        const names = asNames(options);
        const hit = names.includes(field.name);
        const mode = typeof options === "object" && options && !Array.isArray(options) ? options.mode || "include" : "include";
        return mode === "exclude" ? !hit : hit;
      }
    },
    {
      id: "byRegexp",
      name: "字段名匹配正则",
      pickerDefault: true,
      get: (options) => {
        const re = safeRegExp(options);
        return (field) => re ? re.test(field.name) : false;
      }
    },
    {
      id: "byRegexpOrNames",
      name: "字段名匹配正则或列表",
      pickerDefault: false,
      get: (options) => {
        const opts = options;
        const pattern = typeof opts === "string" ? opts : opts?.pattern ?? "";
        const names = typeof opts === "object" && opts ? asNames(opts) : [];
        const re = safeRegExp(pattern);
        return (field) => names.includes(field.name) || !!re && re.test(field.name);
      }
    },
    {
      id: "byType",
      name: "字段类型为",
      pickerDefault: true,
      get: (options) => (field) => field.type === options
    },
    {
      id: "byTypes",
      name: "字段类型为（列表）",
      pickerDefault: false,
      get: (options) => {
        const types = Array.isArray(options) ? options.map(String) : String(options ?? "").split(",").map((s) => s.trim()).filter(Boolean);
        return (field) => types.includes(String(field.type));
      }
    },
    {
      id: "byFrameRefID",
      name: "查询返回的字段",
      pickerDefault: true,
      get: (options) => (_field, frame) => (frame?.refId ?? "") === String(options ?? "")
    },
    {
      id: "byValue",
      name: "值为",
      pickerDefault: true,
      get: (options) => (field) => {
        if (options && typeof options === "object" && "op" in options) {
          const n2 = Number(options.value);
          return field.values.some((v) => Number(v) === n2);
        }
        const n = Number(options);
        if (!Number.isNaN(n) && String(options).trim() !== "") {
          return field.values.some((v) => Number(v) === n);
        }
        return field.values.some((v) => String(v) === String(options ?? ""));
      }
    },
    {
      id: "numeric",
      name: "数值字段",
      pickerDefault: false,
      get: () => (field) => field.type === "number"
    },
    {
      id: "time",
      name: "时间字段",
      pickerDefault: false,
      get: () => (field) => field.type === "time"
    },
    {
      id: "first",
      name: "第一个字段",
      pickerDefault: false,
      get: () => (field, frame) => !!frame && frame.fields[0] === field
    },
    {
      id: "firstTimeField",
      name: "第一个时间字段",
      pickerDefault: false,
      get: () => (field, frame) => {
        if (!frame) return field.type === "time";
        const first = frame.fields.find((f) => f.type === "time");
        return first === field;
      }
    }
  ];
  const byId = new Map(MATCHERS.map((m) => [m.id, m]));
  function getFieldMatcher(config) {
    const info = byId.get(config.id);
    if (!info) {
      return () => false;
    }
    return info.get(config.options);
  }
  function identity(v) {
    return v;
  }
  function numberOrUndefined(v) {
    if (v === "" || v === null || v === void 0) return void 0;
    const n = Number(v);
    return Number.isFinite(n) ? n : void 0;
  }
  const STANDARD_OVERRIDE_PROCESSORS = [
    {
      id: "unit",
      name: "单位",
      path: "unit",
      process: (v) => v == null || v === "" ? void 0 : String(v)
    },
    {
      id: "decimals",
      name: "小数位",
      path: "decimals",
      process: numberOrUndefined
    },
    { id: "min", name: "最小值", path: "min", process: numberOrUndefined },
    { id: "max", name: "最大值", path: "max", process: numberOrUndefined },
    {
      id: "fieldMinMax",
      name: "字段最小/最大",
      path: "fieldMinMax",
      process: (v) => v == null ? void 0 : Boolean(v)
    },
    {
      id: "displayName",
      name: "显示名称",
      path: "displayName",
      process: (v) => v == null || v === "" ? void 0 : String(v)
    },
    {
      id: "noValue",
      name: "空值显示",
      path: "noValue",
      process: (v) => v == null ? void 0 : String(v)
    },
    { id: "color", name: "颜色", path: "color", process: identity },
    { id: "thresholds", name: "阈值", path: "thresholds", process: identity },
    { id: "mappings", name: "值映射", path: "mappings", process: identity },
    { id: "links", name: "数据链接", path: "links", process: identity },
    { id: "actions", name: "动作", path: "actions", process: identity },
    {
      id: "filterable",
      name: "可过滤",
      path: "filterable",
      process: (v) => v == null ? void 0 : Boolean(v)
    }
  ];
  const processorById = new Map(
    STANDARD_OVERRIDE_PROCESSORS.map((p) => [p.id, p])
  );
  function getOverrideProcessor(id) {
    if (processorById.has(id)) return processorById.get(id);
    if (id.startsWith("custom.")) {
      return {
        id,
        name: id.slice(7),
        path: id,
        process: identity
      };
    }
    return {
      id,
      name: id,
      path: id,
      process: identity,
      shouldApply: () => false
    };
  }
  function processOverrideValue(id, value) {
    return getOverrideProcessor(id).process(value);
  }
  function isKnownOverrideProperty(id) {
    return processorById.has(id) || id.startsWith("custom.");
  }
  function applyProcessedProperty(config, id, raw) {
    const processor = getOverrideProcessor(id);
    if (processor.shouldApply === void 0 && !isKnownOverrideProperty(id) && !id.startsWith("custom.")) {
      return config;
    }
    const value = processor.process(raw);
    if (value === void 0) {
      const next = { ...config };
      if (id.startsWith("custom.")) {
        const custom = { ...config.custom ?? {} };
        delete custom[id.slice(7)];
        return { ...config, custom };
      }
      delete next[id];
      return next;
    }
    if (id.startsWith("custom.")) {
      const key = id.slice(7);
      return { ...config, custom: { ...config.custom ?? {}, [key]: value } };
    }
    return { ...config, [id]: value };
  }
  const compiledRulesCache = /* @__PURE__ */ new WeakMap();
  const compiledRulesLru = [];
  const COMPILED_RULES_LRU_MAX = 32;
  function defaultsCacheKey(defaults) {
    const unit = defaults.unit ?? "";
    const decimals = defaults.decimals ?? "";
    const displayName = defaults.displayName ?? "";
    const customKeys = defaults.custom ? Object.keys(defaults.custom).join(",") : "";
    return `${unit}|${decimals}|${displayName}|${customKeys}`;
  }
  function rulesSignature(overrides) {
    let s = String(overrides.length);
    for (let i = 0; i < overrides.length; i++) {
      const r = overrides[i];
      s += `|${r.matcher?.id}:${JSON.stringify(r.matcher?.options)}:${r.properties?.length ?? 0}`;
      for (const p of r.properties || []) s += `:${p.id}`;
    }
    return s;
  }
  function compileOverrideRules(overrides = []) {
    return overrides.map((rule) => ({
      matcher: rule.matcher,
      properties: rule.properties || [],
      match: getFieldMatcher(rule.matcher || { id: "" })
    }));
  }
  function getCompiledRules(overrides, defaults) {
    const dKey = defaultsCacheKey(defaults);
    const weakHit = compiledRulesCache.get(overrides);
    if (weakHit && weakHit.defaultsKey === dKey) return weakHit.rules;
    const sig = rulesSignature(overrides) + "::" + dKey;
    const lruHit = compiledRulesLru.find((e) => e.key === sig);
    if (lruHit) {
      compiledRulesCache.set(overrides, { rules: lruHit.rules, defaultsKey: dKey });
      return lruHit.rules;
    }
    const rules = compileOverrideRules(overrides);
    compiledRulesCache.set(overrides, { rules, defaultsKey: dKey });
    compiledRulesLru.unshift({ key: sig, rules });
    if (compiledRulesLru.length > COMPILED_RULES_LRU_MAX) compiledRulesLru.pop();
    return rules;
  }
  function normalizePropId(id) {
    if (id === "unit" || id === "decimals" || id === "displayName" || id === "min" || id === "max" || id === "noValue" || id === "fieldMinMax" || id === "filterable" || id === "color" || id === "thresholds" || id === "mappings" || id === "links" || id === "actions") {
      return id;
    }
    if (id.startsWith("standardOptions."))
      return id.slice("standardOptions.".length);
    if (id.startsWith("custom.")) return id;
    const customKeys = [
      "drawStyle",
      "lineInterpolation",
      "lineWidth",
      "fillOpacity",
      "gradientMode",
      "spanNulls",
      "showPoints",
      "pointSize",
      "stacking",
      "axisPlacement",
      "axisLabel",
      "axisSoftMin",
      "axisSoftMax",
      "axisCenteredZero",
      "hideFrom",
      "scaleDistribution",
      "thresholdsStyle",
      "barAlignment",
      "lineStyle",
      "insertNulls",
      "barWidthFactor"
    ];
    if (customKeys.includes(id)) return `custom.${id}`;
    return id;
  }
  function setNested(config, path, value) {
    if (path.startsWith("custom.")) {
      const rest = path.slice(7);
      const custom = { ...config.custom ?? {} };
      const parts = rest.split(".");
      let cur = custom;
      for (let i = 0; i < parts.length - 1; i++) {
        cur[parts[i]] = cur[parts[i]] && typeof cur[parts[i]] === "object" ? { ...cur[parts[i]] } : {};
        cur = cur[parts[i]];
      }
      cur[parts[parts.length - 1]] = value;
      return { ...config, custom };
    }
    if (path.includes(".")) {
      const parts = path.split(".");
      const root = { ...config };
      let cur = root;
      for (let i = 0; i < parts.length - 1; i++) {
        cur[parts[i]] = cur[parts[i]] && typeof cur[parts[i]] === "object" ? { ...cur[parts[i]] } : {};
        cur = cur[parts[i]];
      }
      cur[parts[parts.length - 1]] = value;
      return root;
    }
    return { ...config, [path]: value };
  }
  function applyFieldOverrides(frames, defaults = {}, overrides = []) {
    const compiled = getCompiledRules(overrides, defaults);
    return frames.map((frame) => ({
      ...frame,
      fields: frame.fields.map((field) => {
        let config = { ...defaults, ...field.config };
        for (const rule of compiled) {
          if (!rule.match(field, frame, frames)) continue;
          for (const prop of rule.properties) {
            const id = normalizePropId(prop.id);
            if (!isKnownOverrideProperty(id) && !id.includes(".")) {
              continue;
            }
            const processed = processOverrideValue(id, prop.value);
            if (id.startsWith("custom.") || !isKnownOverrideProperty(id)) {
              config = setNested(config, id, processed);
            } else {
              config = applyProcessedProperty(config, id, prop.value);
            }
            if (id === "color" && prop.value && typeof prop.value === "object" && prop.value.fixedColor) {
              config = {
                ...config,
                color: {
                  ...config.color,
                  ...prop.value,
                  mode: prop.value.mode ?? "fixed"
                }
              };
            }
          }
        }
        return { ...field, config };
      })
    }));
  }
  const DEFAULT_MAX_ENTRIES = 64;
  const DEFAULT_MAX_BYTES = 512 * 1024;
  const cache = /* @__PURE__ */ new Map();
  let cacheBytes = 0;
  let maxEntries = DEFAULT_MAX_ENTRIES;
  let maxBytes = DEFAULT_MAX_BYTES;
  const DEFAULT_OPTIONS = {
    limit: { limitField: 10 },
    sortBy: { sort: [] },
    reduce: { reducers: ["sum"] },
    histogram: { bucketCount: 10 },
    smoothing: { windowSize: 3 },
    filterByValue: { type: "include", filters: [] },
    prepareTimeSeries: { format: "multi" }
  };
  function readLimitOption(options) {
    if (!options) return void 0;
    const raw = options.limit ?? options.limitField ?? options.limitValue;
    if (raw == null) return void 0;
    const n = Math.floor(Number(raw));
    return Number.isFinite(n) && n >= 0 ? n : void 0;
  }
  function tryFuseSortLimit(steps, index) {
    const cur = steps[index];
    const next = steps[index + 1];
    if (!cur || !next) return null;
    if (cur.disabled || next.disabled) return null;
    const curId = resolveTransformerId(cur.id);
    const nextId = resolveTransformerId(next.id);
    if (curId !== "sortBy" || nextId !== "limit") return null;
    if (JSON.stringify(cur.filter ?? null) !== JSON.stringify(next.filter ?? null)) {
      return null;
    }
    const lim = readLimitOption(next.options);
    if (lim == null) return null;
    const defaults = DEFAULT_OPTIONS.sortBy ?? {};
    return {
      fused: {
        id: "sortBy",
        filter: cur.filter,
        options: {
          ...defaults,
          ...cur.options || {},
          limit: lim,
          limitField: lim,
          limitValue: lim
        }
      },
      skipNext: true
    };
  }
  function compileTransformSteps(transformations = []) {
    const out = [];
    const src = transformations ?? [];
    for (let i = 0; i < src.length; i++) {
      const t = src[i];
      if (t.disabled) continue;
      const fuse = tryFuseSortLimit(src, i);
      if (fuse) {
        out.push(fuse.fused);
        if (fuse.skipNext) i += 1;
        continue;
      }
      const resolvedId = resolveTransformerId(t.id);
      const defaults = DEFAULT_OPTIONS[resolvedId] ?? DEFAULT_OPTIONS[t.id] ?? {};
      out.push({
        id: resolvedId,
        filter: t.filter,
        options: { ...defaults, ...t.options || {} }
      });
    }
    return out;
  }
  function estimateConfigBytes(config) {
    let n = 128;
    const transforms = config.transformations ?? [];
    n += transforms.length * 64;
    for (const t of transforms) {
      n += String(t.id).length + 16;
      if (t.options) n += Object.keys(t.options).length * 24;
    }
    const overrides = config.fieldConfigOverrides ?? [];
    n += overrides.length * 96;
    for (const r of overrides) {
      n += String(r.matcher?.id ?? "").length;
      n += (r.properties?.length ?? 0) * 32;
    }
    const defaults = config.fieldConfigDefaults;
    if (defaults) n += Object.keys(defaults).length * 24 + 32;
    return n;
  }
  function pipelineConfigRevision(config) {
    const transforms = config.transformations ?? [];
    const overrides = config.fieldConfigOverrides ?? [];
    const defaults = config.fieldConfigDefaults ?? {};
    const parts = [`t${transforms.length}`, `o${overrides.length}`];
    for (let i = 0; i < transforms.length; i++) {
      const t = transforms[i];
      parts.push(
        `${t.disabled ? "D" : ""}${t.id}:${stableSmallJson(t.options)}:${stableSmallJson(t.filter)}`
      );
    }
    for (let i = 0; i < overrides.length; i++) {
      const r = overrides[i];
      const props = (r.properties || []).map((p) => `${p.id}=${stableSmallJson(p.value)}`).join(",");
      parts.push(
        `m${r.matcher?.id}:${stableSmallJson(r.matcher?.options)}:${props}`
      );
    }
    parts.push(`d:${stableSmallJson(defaults)}`);
    return parts.join("|");
  }
  function stableSmallJson(value) {
    if (value == null) return "";
    if (typeof value === "string") return value.length > 64 ? value.slice(0, 64) : value;
    if (typeof value === "number" || typeof value === "boolean") return String(value);
    try {
      const s = JSON.stringify(value);
      return s.length > 256 ? s.slice(0, 256) : s;
    } catch {
      return "?";
    }
  }
  function touch(revision, entry) {
    cache.delete(revision);
    cache.set(revision, entry);
  }
  function evictIfNeeded() {
    while ((cache.size > maxEntries || cacheBytes > maxBytes) && cache.size > 0) {
      const oldest = cache.keys().next().value;
      if (oldest == null) break;
      const e = cache.get(oldest);
      cache.delete(oldest);
      if (e) cacheBytes -= e.bytes;
    }
    if (cacheBytes < 0) cacheBytes = 0;
  }
  function getCompiledPipeline(config) {
    const revision = pipelineConfigRevision(config);
    const hit = cache.get(revision);
    if (hit) {
      touch(revision, hit);
      return hit.compiled;
    }
    const transformations = (config.transformations ?? []).map((t) => ({
      id: t.id,
      options: t.options ? { ...t.options } : void 0,
      disabled: t.disabled,
      filter: t.filter
    }));
    const defaults = { ...config.fieldConfigDefaults ?? {} };
    const overrides = (config.fieldConfigOverrides ?? []).map((r) => ({
      matcher: { ...r.matcher || { id: "" } },
      properties: (r.properties || []).map((p) => ({ ...p }))
    }));
    const fastSteps = compileTransformSteps(transformations);
    const compiledOverrides = compileOverrideRules(overrides);
    const estimatedBytes = estimateConfigBytes(config);
    const compiled = {
      revision,
      transformations,
      fastSteps,
      defaults,
      overrides,
      compiledOverrides,
      estimatedBytes
    };
    const bytes = Math.max(estimatedBytes, revision.length + 64);
    cacheBytes += bytes;
    cache.set(revision, { revision, compiled, bytes });
    evictIfNeeded();
    return compiled;
  }
  function runCompiledPipeline(frames, compiled, opts) {
    const transformed = applyTransformations(
      frames,
      compiled.fastSteps
    );
    const series = applyFieldOverrides(
      transformed,
      compiled.defaults,
      compiled.overrides
    );
    return { frames: series, steps: [], diagnostics: [] };
  }
  function canEncodeF64(values) {
    for (let i = 0; i < values.length; i++) {
      const v = values[i];
      if (v == null) continue;
      if (typeof v !== "number") return false;
    }
    return true;
  }
  function packFramesForTransfer(frames) {
    const transfer = [];
    const wire = (frames ?? []).map((frame) => {
      const fields = (frame.fields ?? []).map((f) => {
        const values = f.values ?? [];
        const type = f.type;
        const numericLike = (type === "number" || type === "time") && canEncodeF64(values);
        if (numericLike) {
          const f64 = new Float64Array(values.length);
          const nulls = new Uint8Array(values.length);
          for (let i = 0; i < values.length; i++) {
            const v = values[i];
            if (v == null) {
              nulls[i] = 1;
              f64[i] = 0;
            } else {
              nulls[i] = 0;
              f64[i] = v;
            }
          }
          transfer.push(f64.buffer, nulls.buffer);
          return {
            name: f.name,
            type,
            config: f.config ? { ...f.config } : {},
            labels: f.labels ? { ...f.labels } : void 0,
            encoding: "f64",
            f64,
            nulls
          };
        }
        return {
          name: f.name,
          type,
          config: f.config ? { ...f.config } : {},
          labels: f.labels ? { ...f.labels } : void 0,
          encoding: "clone",
          values: values.slice()
        };
      });
      const len = frame.length ?? fields[0]?.f64?.length ?? fields[0]?.values?.length ?? 0;
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta ? { ...frame.meta } : void 0,
        length: len,
        fields
      };
    });
    return { frames: wire, transfer };
  }
  function unpackWireFrames(frames) {
    return (frames ?? []).map((frame) => {
      const fields = (frame.fields ?? []).map((f) => {
        if (f.encoding === "f64" && f.f64) {
          const n = f.f64.length;
          const values = new Array(n);
          const nulls = f.nulls;
          for (let i = 0; i < n; i++) {
            values[i] = nulls && nulls[i] ? null : f.f64[i];
          }
          return {
            name: f.name,
            type: f.type,
            config: f.config ?? {},
            values,
            labels: f.labels
          };
        }
        return {
          name: f.name,
          type: f.type,
          config: f.config ?? {},
          values: f.values ?? [],
          labels: f.labels
        };
      });
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta,
        fields,
        length: frame.length ?? fields.reduce((m, field) => Math.max(m, field.values.length), 0)
      };
    });
  }
  const cancelled = /* @__PURE__ */ new Set();
  function handlePanelPipelineMessage(msg, post) {
    if (msg == null || msg.id == null) return;
    if (msg.type === "cancel") {
      cancelled.add(msg.id);
      return;
    }
    if (cancelled.has(msg.id)) {
      cancelled.delete(msg.id);
      post({
        id: msg.id,
        generation: msg.generation,
        ok: false,
        error: "aborted",
        aborted: true
      });
      return;
    }
    try {
      const series = unpackWireFrames(msg.frames ?? []);
      const compiled = getCompiledPipeline({
        transformations: msg.transformations ?? [],
        fieldConfigDefaults: msg.fieldConfigDefaults ?? {},
        fieldConfigOverrides: msg.fieldConfigOverrides ?? []
      });
      if (cancelled.has(msg.id)) {
        cancelled.delete(msg.id);
        post({
          id: msg.id,
          generation: msg.generation,
          ok: false,
          error: "aborted",
          aborted: true
        });
        return;
      }
      const out = runCompiledPipeline(series, compiled, { withTrace: false });
      if (cancelled.has(msg.id)) {
        cancelled.delete(msg.id);
        post({
          id: msg.id,
          generation: msg.generation,
          ok: false,
          error: "aborted",
          aborted: true
        });
        return;
      }
      const packed = packFramesForTransfer(out.frames);
      post(
        {
          id: msg.id,
          generation: msg.generation,
          ok: true,
          frames: packed.frames
        },
        packed.transfer
      );
    } catch (e) {
      post({
        id: msg.id,
        generation: msg.generation,
        ok: false,
        error: e instanceof Error ? e.message : String(e)
      });
    }
  }
  function onMessage(ev) {
    handlePanelPipelineMessage(ev.data, (res, transfer) => {
      const scope = self;
      if (transfer?.length) scope.postMessage(res, transfer);
      else scope.postMessage(res);
    });
  }
  const isDedicatedWorker = typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && // eslint-disable-next-line no-undef
  self instanceof WorkerGlobalScope;
  if (isDedicatedWorker) {
    self.onmessage = onMessage;
  }
})();
//# sourceMappingURL=panelPipelineWorker-5BqW8fRn.js.map
