import b from "@arcgis/core/layers/FeatureLayer.js";
import X from "@arcgis/core/request.js";
import { p as Y, i as Z } from "./monaco-importer.js";
import ee from "@arcgis/core/portal/PortalItem.js";
import te from "@arcgis/core/WebMap.js";
import ie from "@arcgis/core/WebScene.js";
import { isNotNull as w, isNotUndefined as U, addLTRMark as re, setValuesInString as V, normalizeLocale as se } from "@arcgis/components-utils";
import { s as W, f as ne, a as _, b as oe } from "./fields.js";
import { CompletionItemKind as T, InsertTextFormat as I, InsertTextMode as M } from "vscode-languageserver-types";
import { g as ae } from "./runtime.js";
import { filterApiLibraryForContext as le } from "@arcgis/languages-api-utils";
import { Emitter as x, Uri as $ } from "monaco-editor";
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
v4.34.0-next.59 */
function B(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && typeof t.declaredClass == "string" && t.declaredClass.startsWith("esri.layers.") && g(t) && "queryFeatures" in t && typeof t.queryFeatures == "function";
}
function ue(t) {
  return !!t && typeof t == "object" && "allLayers" in t && "allTables" in t && typeof t.allLayers == "object" && typeof t.allTables == "object";
}
function N(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && typeof t.declaredClass == "string" && (t.declaredClass === "esri.Map" || t.declaredClass === "esri.WebMap" || t.declaredClass === "esri.WebScene");
}
function ce(t) {
  return !!t && typeof t == "object" && "loadAll" in t && typeof t.loadAll == "function";
}
function O(t) {
  return !!t && typeof t == "object" && "portalItem" in t && t.portalItem != null;
}
function R(t) {
  return !!t && typeof t == "object" && "portalItem" in t && t.portalItem != null;
}
function g(t) {
  return !!t && typeof t == "object" && "fields" in t && Array.isArray(t.fields);
}
function D(t) {
  return !!t && typeof t == "object" && "url" in t && typeof t.url == "string";
}
function pe(t) {
  return D(t) && /\/(?:featureserver|mapserver)(?:\/|$)/iu.test(t.url ?? "");
}
function Ue(t) {
  return D(t) || g(t) || R(t);
}
function We(t) {
  return D(t) || g(t) || R(t);
}
function Be(t) {
  return O(t) || N(t) || pe(t);
}
function A(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.Subtype";
}
function C(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.CodedValueDomain";
}
function he(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.InheritedDomain";
}
function Ne(t) {
  return !!t && typeof t == "object" && "id" in t && typeof t.id == "string" && "definitions" in t && typeof t.definitions == "object" && !Array.isArray(t.definitions);
}
function m(t) {
  return !!t && typeof t == "object" && "title" in t && typeof t.title == "string";
}
function fe(t) {
  return !!t && typeof t == "object" && "url" in t && typeof t.url == "string";
}
function k(t) {
  return !!t && typeof t == "object" && "layerId" in t && typeof t.layerId == "number";
}
function S(t) {
  return !!t && typeof t == "object" && "typeIdField" in t && "types" in t;
}
function L(t) {
  return !!t && typeof t == "object" && "getFieldDomain" in t && typeof t.getFieldDomain == "function";
}
function f(t) {
  return !!t && typeof t == "object" && "subtypeField" in t;
}
function de(t) {
  return f(t) && "subtypes" in t;
}
function ye(t) {
  return !!t && typeof t == "object" && "portalItem" in t;
}
function _e(t) {
  return k(t) && "relationships" in t && "url" in t && Array.isArray(t.relationships) && typeof t.url == "string";
}
function be(t) {
  return !!t && typeof t == "object" && "isTable" in t && typeof t.isTable == "boolean";
}
function me(t) {
  return !!t && typeof t == "object" && "load" in t && typeof t.load == "function";
}
async function q(t) {
  if (!t)
    return null;
  let e;
  return g(t) ? e = t : e = new b(t), me(e) && await e.load(), e;
}
async function ge(t) {
  t += "/layers";
  const e = await X(t, { responseType: "json", query: { f: "json" } }), i = t.endsWith("MapServer/layers") ? "data" : "query", r = G(e.data?.layers, i), s = G(e.data?.tables, i);
  return { layers: r, tables: s };
}
function G(t, e) {
  return t ? t.filter((i) => {
    switch (i.type) {
      case "Feature Layer":
      case "Oriented Imagery Layer":
      case "Catalog Layer":
      case "Table":
        return (i.capabilities ? i.capabilities.toLowerCase().split(",").map((s) => s.trim()) : []).includes(e);
      default:
        return !1;
    }
  }) : [];
}
async function De(t, e) {
  const i = new b({ url: `${t.url}/${e.relatedTableId}` });
  return await i.load(), i;
}
function K(t) {
  return (e, i) => {
    if (e.type === "oid")
      return -1;
    if (i.type === "oid")
      return 1;
    if (f(t)) {
      if (e.name === t.subtypeField)
        return -1;
      if (i.name === t.subtypeField)
        return 1;
    }
    if (S(t)) {
      if (e.name === t.typeIdField)
        return -1;
      if (i.name === t.typeIdField)
        return 1;
    }
    return e.name.localeCompare(i.name, "en", { sensitivity: "base" });
  };
}
function j(t, e) {
  return t?.every((i) => i.domains?.[e.name]?.type === "inherited") ?? !1;
}
const Ce = /^[a-z_$][a-z0-9_$]*$/giu;
function z(t, e = !0) {
  return t.match(Ce) ? `${e ? "." : ""}${t}` : `["${t}"]`;
}
function H(t, e) {
  return t ? `${t}${z(e)}` : e;
}
function E(t) {
  return ye(t) ? t.portalItem : null;
}
function Oe(t, e, i = !1) {
  let r = e;
  const s = [], n = [];
  return W(t).forEach((o) => {
    r && (r += `  
  
`), r += `**${o.name}** (${o.alias})  
${o.type}`, o.description && (r += `  
'${o.description}`);
    const p = oe(o), c = z(o.name, !1), y = _(o);
    if (s.push({
      name: o.name,
      description: y,
      type: p,
      completion: {
        label: o.name,
        detail: y,
        insertText: c,
        insertTextMode: M.asIs,
        insertTextFormat: I.PlainText,
        kind: T.Field
      }
    }), i) {
      if (!o.alias || o.alias.toLowerCase() === o.name.toLowerCase())
        return;
      let h = `**${o.alias}**  
${o.type}`;
      o.description && (h += `  
'${o.description}`), n.push({
        name: o.alias,
        description: o.name,
        type: p,
        completion: {
          label: o.alias,
          detail: o.name,
          insertText: c,
          insertTextMode: M.asIs,
          insertTextFormat: I.PlainText,
          kind: T.Field,
          documentation: { kind: "markdown", value: h }
        }
      });
    }
  }), [[...s, ...n], r];
}
class J {
  constructor(e, i, r) {
    this._profile = e, this._label = i, this.description = r, this.filterDescription = !1;
  }
  /**
   * Returns the label string.
   */
  getLabel() {
    return this._label == null ? "" : typeof this._label == "string" ? re(this._label) : V(this._profile?.intlStrings[this._label.code], this._label.formatValues);
  }
  /**
   * Returns the description string.
   */
  getDescription() {
    return this.description == null ? "" : typeof this.description == "string" ? this.description : V(this._profile?.intlStrings[this.description.code], this.description.formatValues);
  }
  /**
   * Returns true if the item pass the filter test
   */
  passFilter(e) {
    return !e || e.test(this.getLabel()) ? !0 : this.filterDescription && e.test(this.getDescription());
  }
}
class F extends J {
  constructor(e) {
    super(e.profile, e.label, e.description ?? e.declaration?.description), this.declaration = e.declaration ?? {}, this.name = e.declaration?.name ?? "", this.snippet = e.snippet ?? "", this.nonInteractive = e.nonInteractive ?? !1, this.filterDescription = e.filterDescription ?? !1, this.icon = e.icon;
  }
}
class a extends F {
  constructor(e) {
    super(e), this.type = "text", this.isCollection = !1, this.type = e.declaration?.type ?? "text";
  }
  getDescription() {
    return this.description == null ? this._profile?.intlStrings[this.type.toLowerCase()] ?? "" : super.getDescription();
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration };
  }
}
class we extends F {
  constructor(e) {
    super(e), this.type = "array", this.isCollection = !1, this.elementType = e.declaration?.elementType ?? { type: "number", name: "number" };
  }
  getDescription() {
    return this.description == null ? this._profile?.intlStrings[this.type.toLowerCase()] ?? "" : super.getDescription();
  }
  toProfileVariableDefinition() {
    return { type: this.type, elementType: this.elementType, name: "", ...this.declaration };
  }
}
class v extends F {
  constructor(e, i) {
    super(i), this.owner = e, this.isCollection = !0, this._loaded = !0, this.variables = [];
  }
  get breadcrumb() {
    if (this.owner) {
      const e = this.owner.breadcrumb;
      return e ? `${e} / ${this.name}` : this.name;
    }
    return this.name;
  }
  /**
   * Returns true if the collection has been loaded
   */
  get loaded() {
    return this._loaded;
  }
  /**
   * Returns an url to the associated information
   */
  get informationUrl() {
    return null;
  }
  get informationType() {
    return "";
  }
}
class l extends J {
  constructor(e, i, r = [], s = !1) {
    super(e, i), this.variables = r, this.isHeader = s, this.type = "group", this.isCollection = !0;
  }
  passFilter() {
    return !0;
  }
}
class d extends v {
  constructor(e, i) {
    super(e, i), this.type = "dictionary", this.dictionaryVariables = [], this.loadPropertyDeclarations(i.declaration?.properties), this.snippet && this.dictionaryVariables.length && (this.variables = [new l(this._profile, this.snippet, this.dictionaryVariables)]);
  }
  async loadSource() {
  }
  loadPropertyDeclarations(e) {
    this.dictionaryVariables = this.createVariableInstances(e), this.variables = this.dictionaryVariables;
  }
  createVariableInstances(e) {
    if (!Array.isArray(e))
      return [];
    const i = [];
    return e.forEach((r) => {
      const s = this.createVariableInstance(r);
      s && i.push(s);
    }), i;
  }
  createVariableInstance(e) {
    const i = H(this.snippet, e.name);
    switch (e.type) {
      case "number":
      case "text":
      case "boolean":
      case "date":
      case "dateOnly":
      case "time":
      case "geometry":
      case "knowledgeGraph":
        return new a({ profile: this._profile, declaration: e, label: i, snippet: i });
      case "feature":
        return new Se(this, { profile: this._profile, declaration: e, label: i, snippet: i });
      case "featureSet":
        return new P(this, { profile: this._profile, declaration: e, label: i, snippet: i }, [
          new a({ profile: this._profile, label: i, description: "", snippet: i })
        ]);
      case "featureSetCollection":
        return new Fe(this, {
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      case "dictionary":
        return new d(this, {
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      case "array":
        return new we({
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      default:
        return console.error("Editor profile: Invalid profile variable", e), null;
    }
  }
  toProfileVariableDefinition() {
    return {
      type: this.type,
      name: "",
      ...this.declaration,
      properties: this.dictionaryVariables.map((e) => e.toProfileVariableDefinition())
    };
  }
}
class Q extends v {
  constructor(e, i, r) {
    super(e, i), this.relationshipsProperties = r, this._source = null, this._loaded = !1, this._definition = i.declaration?.definition;
  }
  get title() {
    return m(this._source) ? this._source.title ?? "" : "";
  }
  get url() {
    return fe(this._source) ? this._source.url ?? "" : "";
  }
  get informationUrl() {
    return !this.loaded || !this.url ? null : k(this._source) ? `${this.url}/${this._source.layerId}` : this.url;
  }
  get informationType() {
    return this._profile?.intlStrings.layer ?? "layer";
  }
  async loadSource() {
    return w(this._loadPromise) && U(this._loadPromise) ? await this._loadPromise : (this._loadPromise = this._loadSource(), await this._loadPromise);
  }
  _getValueSnippet(e) {
    return this.type === "feature" ? H(this.snippet, e.name) : e.name;
  }
  _getSubtypeOrDomainNameSnippet(e) {
    return this.type !== "feature" ? null : f(this._source) && e.name === this._source.subtypeField ? `SubtypeName(${this.snippet})` : `DomainName(${this.snippet}, "${e.name}")`;
  }
  _getFieldProperty(e) {
    const i = this._getDomainDictionary(e);
    if (i)
      return i;
    const r = this._getValueSnippet(e);
    return new a({
      profile: this._profile,
      label: r,
      description: _(e),
      snippet: r,
      icon: ne(e),
      filterDescription: !0
    });
  }
  _getDomainDictionary(e) {
    return L(this._source) ? f(this._source) && this._source.subtypeField ? this._getSubtypeDomainDictionary(e) : S(this._source) && this._source.typeIdField ? this._getFeatureTypeDomainDictionary(e) : this._getFieldDomainDictionary(e) : null;
  }
  _getSubtypeDomainDictionary(e) {
    if (!f(this._source))
      return null;
    if (!de(this._source))
      return e.name === this._source.subtypeField ? null : this._getFieldDomainDictionary(e);
    if (e.name === this._source.subtypeField) {
      const s = this._createDomainDictionary(e);
      return s.icon = "subtype", s.variables.push(this._getTypeOrSubtypeDomainGroup(this._source.subtypes, e)), s;
    }
    if (j(this._source.subtypes, e))
      return this._getFieldDomainDictionary(e);
    const i = this._getDomainValuesGroup(this._source.subtypes, e);
    if (!i)
      return null;
    const r = this._createDomainDictionary(e);
    return r.variables.push(i), r;
  }
  _getFeatureTypeDomainDictionary(e) {
    if (!S(this._source))
      return null;
    if (e.name === this._source.typeIdField) {
      const s = this._createDomainDictionary(e);
      return s.variables.push(this._getTypeOrSubtypeDomainGroup(this._source.types, e)), s;
    }
    if (j(this._source.types, e))
      return this._getFieldDomainDictionary(e);
    const i = this._getDomainValuesGroup(this._source.types, e);
    if (!i)
      return null;
    const r = this._createDomainDictionary(e);
    return r.variables.push(i), r;
  }
  _getFieldDomainDictionary(e) {
    if (!L(this._source))
      return null;
    const i = this._source.getFieldDomain(e.name);
    if (!C(i))
      return null;
    const r = this._getCodedValueDomainGroup(i, {
      code: "domainvalues"
    }), s = this._createDomainDictionary(e);
    return s.variables.push(r), s;
  }
  _getTypeOrSubtypeDomainGroup(e, i) {
    if (C(i.domain))
      return this._getCodedValueDomainGroup(i.domain, { code: "subtypes" });
    const r = e?.map((s) => {
      const n = A(s) ? s.code : s.id;
      return new a({
        profile: this._profile,
        label: `${n}`,
        description: s.name,
        snippet: `"${n}"`
      });
    }) ?? [];
    return new l(this._profile, { code: "subtypes" }, r);
  }
  _getCodedValueDomainGroup(e, i) {
    const r = e.codedValues.map(
      (s) => new a({
        profile: this._profile,
        label: `${s.code}`,
        description: s.name,
        snippet: `"${s.code}"`,
        filterDescription: !0
      })
    );
    return new l(this._profile, i, r);
  }
  _getDomainValuesGroup(e, i) {
    const r = [];
    return !e || e.length === 0 || (e.forEach((s) => {
      const n = s.domains?.[i.name];
      if (!n || he(n) || !C(n))
        return;
      const u = _(i), o = this._getCodedValueDomainGroup(n, {
        code: "domainvaluesfortypeformat",
        formatValues: {
          fieldName: u,
          typeName: s.name
        }
      }), p = A(s) ? s.code : s.id, c = `${p}`, y = `"${p}""`, h = new d(this, {
        profile: this._profile,
        label: c,
        snippet: y,
        description: s.name,
        declaration: { name: u }
      });
      h.variables = [o], r.push(h);
    }), !r.length) ? null : new l(this._profile, { code: "domainvaluesbysubtypes" }, r);
  }
  _createDomainDictionary(e) {
    const i = this._getValueSnippet(e), r = _(e), s = new d(this, {
      profile: this._profile,
      label: i,
      description: r,
      snippet: i,
      icon: "form-dropdown",
      declaration: { name: e.name }
    }), n = new l(this._profile, r, [
      new a({
        profile: this._profile,
        label: i,
        description: "",
        snippet: i
      })
    ]);
    s.variables = [n];
    const u = this._getSubtypeOrDomainNameSnippet(e);
    return u && n.variables.push(
      new a({
        profile: this._profile,
        label: u,
        description: "",
        snippet: u
      })
    ), s;
  }
  async _getRelationshipsProperty() {
    if (!this.relationshipsProperties?.exposeRelationships || !this._profile?.supportFeatureSetFunctions)
      return null;
    const e = this._source;
    if (!_e(e))
      return null;
    const i = new l(this._profile, { code: "relationships" }), r = await Promise.all(
      e.relationships?.map(async (s) => {
        const n = await De(e, s);
        if (!B(n) || s.relatedTableId === this.relationshipsProperties?.sourceTableId)
          return null;
        const u = `FeatureSetByRelationshipName(${this.snippet}, "${s.name}")`;
        return new P(
          this,
          {
            profile: this._profile,
            declaration: { definition: n },
            label: n.title,
            description: "",
            nonInteractive: !0
          },
          [new a({ profile: this._profile, label: u, description: "", snippet: u })],
          { exposeRelationships: !0, sourceTableId: e.layerId }
        );
      }) ?? []
    );
    return i.variables = r.filter(w), i.variables.length ? i : null;
  }
}
class Se extends Q {
  constructor(e, i) {
    super(e, i, { exposeRelationships: !0 }), this.type = "feature";
  }
  get title() {
    return m(this._source) ? this._source.title ?? "" : { code: "feature" };
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (this._source = await q(this._definition), !this._source)
        throw new Error("Invalid definition");
      const e = m(this._source) ? this._source.title ?? "" : "";
      this.variables.push(
        new l(this._profile, e, [
          new a({
            profile: this._profile,
            label: this.snippet,
            description: "",
            snippet: this.snippet
          })
        ])
      );
      const i = new l(this._profile, { code: "values" });
      if (this.variables.push(i), be(this._source) && !this._source.isTable) {
        const s = `Geometry(${this.snippet})`, n = new a({
          profile: this._profile,
          declaration: { name: s },
          label: s,
          description: "Geometry",
          snippet: s,
          icon: "shapes",
          filterDescription: !0
        });
        i.variables.push(n);
      }
      W(this._source.fields).sort(K(this._source)).forEach((s) => {
        i.variables.push(this._getFieldProperty(s));
      });
      const r = await this._getRelationshipsProperty();
      r && this.variables.push(r);
    } catch (e) {
      console.error("Error with definition", e, this._definition), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration, definition: this._definition };
  }
}
class P extends Q {
  constructor(e, i, r = [], s) {
    super(e, i, s), this.featureSetSnippets = r, this.type = "featureSet";
  }
  get title() {
    return m(this._source) ? this._source.title ?? "" : { code: "featureset" };
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (this._source = await q(this._definition), !this._source)
        throw new Error("Invalid definition");
      this.variables.push(new l(this._profile, this.title, this.featureSetSnippets, !0));
      const e = new l(this._profile, { code: "fields" });
      this.variables.push(e), e.variables = this._source.fields.sort(K(this._source)).map((r) => this._getFieldProperty(r));
      const i = await this._getRelationshipsProperty();
      i && this.variables.push(i);
    } catch (e) {
      console.error("Error with definition", e, this._definition), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration, definition: this._definition };
  }
}
class Fe extends v {
  constructor(e, i) {
    super(e, i), this.type = "featureSetCollection", this._featureSetCollections = null, this._loaded = !1, this._definition = i.declaration?.definition;
  }
  get informationUrl() {
    return !this.loaded || !this._featureSetCollections ? null : typeof this._featureSetCollections.source != "string" ? Y(E(this._featureSetCollections.source)) : null;
  }
  get informationType() {
    if (!this.loaded || !this._featureSetCollections)
      return "";
    if (typeof this._featureSetCollections.source == "string")
      return this._profile?.intlStrings.featureservice ?? "featureservice";
    switch (this._featureSetCollections.source.declaredClass) {
      case "esri.WebMap":
        return this._profile?.intlStrings.webmap ?? "webmap";
      case "esri.WebScene":
        return this._profile?.intlStrings.webscene ?? "webscene";
      default:
        return this._profile?.intlStrings.map ?? "map";
    }
  }
  async loadSource() {
    return w(this._loadPromise) && U(this._loadPromise) ? await this._loadPromise : (this._loadPromise = this._loadSource(), await this._loadPromise);
  }
  async _loadSource() {
    if (this.loaded)
      return this._featureSetCollections;
    try {
      if (this._featureSetCollections = await this._featureSetCollectionsFromDefinition(), !this._featureSetCollections)
        throw new Error("Invalid definition");
      const e = typeof this._featureSetCollections.source == "string" ? { code: this._featureSetCollections.source.endsWith("FeatureServer") ? "featureservice" : "mapservice" } : {
        code: "webmapformat",
        formatValues: {
          webMapTitle: E(this._featureSetCollections.source)?.title || "Untitled map"
        }
      }, i = new l(this._profile, e, [
        new a({
          profile: this._profile,
          label: this.snippet,
          description: "",
          snippet: this.snippet
        })
      ]), r = new l(this._profile, { code: "layers" }, this._featureSetCollections.layers), s = new l(this._profile, { code: "tables" }, this._featureSetCollections.tables);
      this.variables.push(i, r, s);
    } catch (e) {
      console.error("Error with definition", e, this._definition), this._featureSetCollections = null;
    } finally {
      this._loaded = !0;
    }
    return this._featureSetCollections;
  }
  async _featureSetCollectionsFromDefinition() {
    return this._definition ? N(this._definition) ? await this._featureSetCollectionFromMap(this._definition) : D(this._definition) ? await this._featureSetCollectionFromUrl(this._definition.url) : O(this._definition) ? await this._featureSetCollectionFromPortalItem(this._definition.portalItem) : null : null;
  }
  async _featureSetCollectionFromMap(e) {
    return ce(e) && await e.loadAll(), await Promise.all(e.tables.map(async (i) => await i.load())), {
      layers: this._convertWebMapLayersToVariables(e.layers),
      tables: this._convertWebMapLayersToVariables(e.tables, !0),
      source: e
    };
  }
  async _featureSetCollectionFromPortalItem(e) {
    const i = new ee(e);
    switch (await i.load(), i.type) {
      case "Web Map": {
        const r = new te({ portalItem: i });
        return await this._featureSetCollectionFromMap(r);
      }
      case "Web Scene": {
        const r = new ie({ portalItem: i });
        return await this._featureSetCollectionFromMap(r);
      }
      case "Feature Service":
        return await this._featureSetCollectionFromUrl(i.url);
      default:
        return console.error("Unsupported portal item", e), null;
    }
  }
  async _featureSetCollectionFromUrl(e) {
    let i = e?.replace(/\/featureserver\/[0-9]*/iu, "/FeatureServer");
    if (i = i?.replace(/\/mapserver\/[0-9]*/iu, "/MapServer"), i = i?.split("?")[0], !i)
      return null;
    const r = await ge(i), s = Promise.all(
      r.layers.map(async (p) => {
        const c = new b({ url: `${i}/${p.id}` });
        return await c.load(), this._createFeatureSetVariable(c);
      })
    ), n = Promise.all(
      r.tables.map(async (p) => {
        const c = new b({ url: `${i}/${p.id}` });
        return await c.load(), this._createFeatureSetVariable(c);
      })
    ), [u, o] = await Promise.all([s, n]);
    return { layers: u, tables: o, source: i };
  }
  _convertWebMapLayersToVariables(e, i = !1) {
    const r = [];
    return e.toArray().reverse().forEach((s) => {
      if (B(s)) {
        r.push(this._createFeatureSetVariable(s, !0));
        return;
      }
      if (ue(s)) {
        const n = i ? this._convertWebMapLayersToVariables(s.allTables, !0) : this._convertWebMapLayersToVariables(s.allLayers);
        r.push(...n);
      }
    }), r;
  }
  _createFeatureSetVariable(e, i = !1) {
    return new P(
      this,
      {
        profile: this._profile,
        declaration: { name: e.title ?? "", definition: e },
        label: i ? e.title : e.sourceJSON.name ?? e.title,
        description: "",
        nonInteractive: !0
      },
      this._makeFeatureSetSnippets(e, i)
    );
  }
  _makeFeatureSetSnippets(e, i = !1) {
    if (!this._profile?.supportFeatureSetFunctions)
      return [];
    if (i) {
      const r = `FeatureSetById(${this.snippet}, "${e.id}")`, s = `FeatureSetByName(${this.snippet}, "${e.title}")`;
      return [
        new a({ profile: this._profile, label: r, description: "", snippet: r }),
        new a({ profile: this._profile, label: s, description: "", snippet: s })
      ];
    } else {
      const r = `FeatureSetById(${this.snippet}, "${e.layerId}")`;
      return [new a({ profile: this._profile, label: r, description: "", snippet: r })];
    }
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration, definition: this._definition };
  }
}
class Re extends d {
  constructor(e, i, r = "en") {
    super(void 0, {
      profile: null,
      declaration: { properties: [] }
    }), this.definition = e, this.intlStrings = i, this.locale = r, this.variables = [], this._profile = this, this.loadPropertyDeclarations(e?.variables);
  }
  /**
   * Returns true if the profile supports feature set functions for snippets.
   */
  get supportFeatureSetFunctions() {
    return this.definition?.bundles?.includes("data-access") ?? !1;
  }
  /**
   * Returns the EditorProfile as a json. The EditorProfile may have been updated. This function allows to
   * get the new json representing mutations.
   */
  toEditorProfileDefinition() {
    return {
      ...this.definition,
      variables: this.dictionaryVariables.map((e) => e.toProfileVariableDefinition())
    };
  }
}
const ve = {
  locale: "en"
};
class ke {
  // #endregion
  constructor(e, i) {
    this.languageId = e, this._apiConfig = i, this._onDidChange = new x(), this._modelToProfileMap = /* @__PURE__ */ new Map(), this._modelToApiContextMap = /* @__PURE__ */ new Map(), this._localeToApiLibraryPromiseMap = /* @__PURE__ */ new Map(), this._onModelContextDidChange = new x(), this._onDidModelContextChangeTimeout = -1, this.workerHost = {
      getApiLibrary: async (r) => await this.getApiLibrary(r)
    }, Z().then((r) => {
      r.onWillDisposeModel((s) => {
        this.disposeForModel(s.uri);
      });
    });
  }
  // #region Protected methods
  _fireModelContextDidChange(e) {
    this._onDidModelContextChangeTimeout === -1 && (this._onDidModelContextChangeTimeout = window.setTimeout(() => {
      this._onDidModelContextChangeTimeout = -1, this._onModelContextDidChange.fire(e);
    }, 0));
  }
  _getApiKey(e) {
    return $.isUri(e) || (e = $.parse(e)), e.toString();
  }
  // #endregion
  // #region Public methods
  get onDidChange() {
    return this._onDidChange.event;
  }
  /**
   * Dispose any cached resources for the model
   */
  disposeForModel(e) {
    const i = this._getApiKey(e);
    this._modelToProfileMap.delete(i), this._modelToApiContextMap.delete(i) && this._fireModelContextDidChange(i);
  }
  /**
   * Returns the editor profile for the given model id.
   * @param modelId The model id for which to get the editor profile.
   * @returns The editor profile for the model.
   */
  getEditorProfileForModel(e) {
    return this._modelToProfileMap.get(this._getApiKey(e));
  }
  /**
   * Returns the API context for the given model id.
   * Returns the default context if the model has no context.
   * @param modelId The model id for which to get the API context.
   * @returns The API context for the model.
   */
  getApiContextForModel(e) {
    return this._modelToApiContextMap.get(this._getApiKey(e)) ?? ve;
  }
  /**
   * Set or update api context for the given model id.
   * @param modelId The model id for which to set the context.
   * @param apiContext The api context to set.
   */
  updateApiContextForModel(e, i) {
    const r = this._getApiKey(e), s = this._modelToApiContextMap.get(r) ?? {};
    this._modelToApiContextMap.set(r, { ...s, ...i }), this._fireModelContextDidChange(r);
  }
  get onModelContextDidChange() {
    return this._onModelContextDidChange.event;
  }
  /**
   * Gets the API library for the given model id.
   * @param modelId The model id for which to get the API library.
   * @returns The API library for the model.
   */
  async getApiLibraryForModel(e) {
    const i = this.getApiContextForModel(e), r = this.getApiLibrary(i.locale ?? "en");
    return (await le(r, i)).categories;
  }
  // #endregion
  //#region Private methods
  async fetchApiLibrary(e) {
    try {
      const { apiPath: i, apiPrefix: r } = this._apiConfig, s = ae(`${i}/${r}${e}.json`), n = await fetch(s);
      return n.ok ? await n.json() : [];
    } catch {
      return [];
    }
  }
  async getApiLibrary(e) {
    const i = se(e);
    return this._localeToApiLibraryPromiseMap.has(i) || this._localeToApiLibraryPromiseMap.set(i, this.fetchApiLibrary(i)), await this._localeToApiLibraryPromiseMap.get(i) ?? [];
  }
  // #endregion
}
export {
  Re as E,
  ke as L,
  We as a,
  B as b,
  Be as c,
  Ue as d,
  Oe as f,
  Ne as i
};
