import {
  capitalize
} from "./chunk-MEZEAS7S.js";
import {
  DuplicateTracker,
  useStateMap,
  useStateSet
} from "./chunk-7O6JY2LB.js";
import {
  createTypekit,
  defineKit
} from "./chunk-Y6LX2MYA.js";
import {
  IdentifierKind,
  ListenerFlow,
  NoTarget,
  ResolutionResultFlags,
  SyntaxKind,
  compilerAssert,
  createDiagnostic,
  createDiagnosticCollector,
  defineCodeFix,
  exprIsBareIdentifier,
  getFirstAncestor,
  getIdentifierContext,
  getSourceLocation,
  hasParseError,
  ignoreDiagnostics,
  printIdentifier,
  reportDiagnostic,
  typeReferenceToString,
  visitChildren
} from "./chunk-HK7BTPGC.js";
import {
  MultiKeyMap,
  createRekeyableMap,
  isArray,
  isDefined,
  mutate
} from "./chunk-3K4NAOXV.js";

// src/typespec/core/packages/compiler/dist/src/experimental/realm.js
var _a;
var StateMapRealmView = class {
  #realm;
  #parentState;
  #realmState;
  constructor(realm, realmState, parentState) {
    this.#realm = realm;
    this.#parentState = parentState;
    this.#realmState = realmState;
  }
  has(t2) {
    return this.#select(t2).has(t2) ?? false;
  }
  set(t2, v2) {
    this.#select(t2).set(t2, v2);
    return this;
  }
  get(t2) {
    return this.#select(t2).get(t2);
  }
  delete(t2) {
    return this.#select(t2).delete(t2);
  }
  forEach(cb, thisArg) {
    for (const item of this.entries()) {
      cb.call(thisArg, item[1], item[0], this);
    }
    return this;
  }
  get size() {
    return this.#realmState.size + this.#parentState.size;
  }
  clear() {
    this.#realmState.clear();
  }
  *entries() {
    for (const item of this.#realmState) {
      yield item;
    }
    for (const item of this.#parentState) {
      yield item;
    }
    return void 0;
  }
  *values() {
    for (const item of this.entries()) {
      yield item[1];
    }
    return void 0;
  }
  *keys() {
    for (const item of this.entries()) {
      yield item[0];
    }
    return void 0;
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  [Symbol.toStringTag] = "StateMap";
  #select(keyType) {
    if (this.#realm.hasType(keyType)) {
      return this.#realmState;
    }
    return this.#parentState;
  }
};
var Realm = class {
  #program;
  /**
   * Stores all types owned by this realm.
   */
  #types = /* @__PURE__ */ new Set();
  /**
   * Stores types that are deleted in this realm. When a realm is active and doing a traversal, you will
   * not find this type in e.g. collections. Deleted types are mapped to `null` if you ask for it.
   */
  #deletedTypes = /* @__PURE__ */ new WeakSet();
  #stateMaps = /* @__PURE__ */ new Map();
  key;
  /**
   * Create a new realm in the given program.
   *
   * @param program - The program to create the realm in.
   * @param description - A short description of the realm's purpose.
   */
  constructor(program, description) {
    this.key = Symbol(description);
    this.#program = program;
  }
  #_typekit;
  /**
   * The typekit instance bound to this realm.
   *
   * If the realm does not already have a typekit associated with it, one will be created and bound to this realm.
   */
  get typekit() {
    return this.#_typekit ??= createTypekit(this);
  }
  /**
   * The program that this realm is associated with.
   */
  get program() {
    return this.#program;
  }
  /**
   * Gets a state map for the given state key symbol.
   *
   * This state map is a view of the program's state map for the given state key, with modifications made to the realm's
   * own state.
   *
   * @param stateKey - The symbol to use as the state key.
   * @returns The realm's state map for the given state key.
   */
  stateMap(stateKey) {
    let m2 = this.#stateMaps.get(stateKey);
    if (!m2) {
      m2 = /* @__PURE__ */ new Map();
      this.#stateMaps.set(stateKey, m2);
    }
    return new StateMapRealmView(this, m2, this.#program.stateMap(stateKey));
  }
  /**
   * Clones a type and adds it to the realm. This operation will use the realm's typekit to clone the type.
   *
   * @param type - The type to clone.
   * @returns A clone of the input type that exists within this realm.
   */
  clone(type) {
    compilerAssert(type, "Undefined type passed to clone");
    const clone = this.#cloneIntoRealm(type);
    this.typekit.type.finishType(clone);
    return clone;
  }
  /**
   * Removes a type from this realm. This operation will not affect the type in the program, only this realm's view
   * of the type.
   *
   * @param type - The TypeSpec type to remove from this realm.
   */
  remove(type) {
    this.#deletedTypes.add(type);
  }
  /**
   * Determines whether or not this realm contains a given type.
   *
   * @param type - The type to check.
   * @returns true if the type was created within this realm or added to this realm, false otherwise.
   */
  hasType(type) {
    return this.#types.has(type);
  }
  /**
   * Adds a type to this realm. Once a type is added to the realm, the realm considers it part of itself.
   *
   * A type can be present in multiple realms, but `Realm.realmForType` will only return the last realm that the type
   * was added to.
   *
   * @param type - The type to add to this realm.
   */
  addType(type) {
    this.#types.add(type);
    _a.realmForType.set(type, this);
  }
  #cloneIntoRealm(type) {
    const clone = this.typekit.type.clone(type);
    this.#types.add(clone);
    _a.realmForType.set(clone, this);
    return clone;
  }
  // TODO better way?
  /** @internal */
  get types() {
    return this.#types;
  }
  static realmForType = singleton("Realm.realmForType", () => /* @__PURE__ */ new WeakMap());
};
_a = Realm;
function singleton(key, init) {
  const sym = Symbol.for(key);
  if (!globalThis[sym]) {
    globalThis[sym] = init();
  }
  return globalThis[sym];
}

// src/typespec/core/packages/compiler/dist/src/typekit/create-diagnosable.js
function createDiagnosable(fn2) {
  function wrapper(...args) {
    return ignoreDiagnostics(fn2.apply(this, args));
  }
  wrapper.withDiagnostics = fn2;
  return wrapper;
}

// src/typespec/core/packages/compiler/dist/src/core/type-utils.js
function isErrorType(type) {
  return "kind" in type && type.kind === "Intrinsic" && type.name === "ErrorType";
}
function isVoidType(type) {
  return "kind" in type && type.kind === "Intrinsic" && type.name === "void";
}
function isNeverType(type) {
  return "kind" in type && type.kind === "Intrinsic" && type.name === "never";
}
function isUnknownType(type) {
  return "kind" in type && type.kind === "Intrinsic" && type.name === "unknown";
}
function isNullType(type) {
  return "kind" in type && type.kind === "Intrinsic" && type.name === "null";
}
function isType(entity) {
  return entity.entityKind === "Type";
}
function isValue(entity) {
  return entity.entityKind === "Value";
}
function isArrayModelType(program, type) {
  return Boolean(type.indexer && type.indexer.key.name === "integer");
}
function isRecordModelType(program, type) {
  return Boolean(type.indexer && type.indexer.key.name === "string");
}
function getParentTemplateNode(node) {
  switch (node.kind) {
    case SyntaxKind.ModelStatement:
    case SyntaxKind.ScalarStatement:
    case SyntaxKind.UnionStatement:
    case SyntaxKind.InterfaceStatement:
      return node.templateParameters.length > 0 ? node : void 0;
    case SyntaxKind.OperationStatement:
      return node.templateParameters.length > 0 ? node : node.parent?.kind === SyntaxKind.InterfaceStatement ? node.parent.templateParameters.length > 0 ? node.parent : void 0 : void 0;
    case SyntaxKind.OperationSignatureDeclaration:
    case SyntaxKind.ModelProperty:
    case SyntaxKind.UnionVariant:
    case SyntaxKind.ModelExpression:
    case SyntaxKind.UnionExpression:
      return node.parent ? getParentTemplateNode(node.parent) : void 0;
    default:
      return void 0;
  }
}
function isTemplateInstance(type) {
  const maybeTemplateType = type;
  return maybeTemplateType.templateMapper !== void 0 && !maybeTemplateType.templateMapper.partial && maybeTemplateType.isFinished;
}
function isDeclaredType(type) {
  if (type.node === void 0) {
    return false;
  }
  const node = type.node;
  return node.templateParameters === void 0 || type.templateMapper === void 0;
}
function isTemplateDeclaration(type) {
  if (type.node === void 0) {
    return false;
  }
  const node = type.node;
  return node.templateParameters && node.templateParameters.length > 0 && type.templateMapper === void 0;
}
function isTemplateDeclarationOrInstance(type) {
  if (type.node === void 0) {
    return false;
  }
  const node = type.node;
  return node.templateParameters && node.templateParameters.length > 0;
}
function isGlobalNamespace(program, namespace) {
  return program.getGlobalNamespaceType() === namespace;
}
function isDeclaredInNamespace(type, namespace, options = { recursive: true }) {
  let candidateNs = type.namespace;
  while (candidateNs) {
    if (candidateNs === namespace) {
      return true;
    }
    if (type.kind === "Operation" && type.interface && type.interface.namespace === namespace) {
      return true;
    }
    candidateNs = options.recursive ? candidateNs.namespace : void 0;
  }
  return false;
}
function getFullyQualifiedSymbolName(sym, options) {
  if (!sym)
    return "";
  if (sym.symbolSource)
    sym = sym.symbolSource;
  const parent = sym.parent && !(sym.parent.flags & 32768) ? sym.parent : void 0;
  const name = sym.flags & 512 ? sym.name.slice(1) : sym.name;
  if (parent?.name) {
    return `${getFullyQualifiedSymbolName(parent)}.${name}`;
  } else if (options?.useGlobalPrefixAtTopLevel) {
    return `global.${name}`;
  } else {
    return name;
  }
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/array.js
defineKit({
  array: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "Model" && isArrayModelType(this.program, type) && type.properties.size === 0;
    },
    getElementType(type) {
      if (!this.array.is(type)) {
        throw new Error("Type is not an array.");
      }
      return type.indexer.value;
    },
    create(elementType) {
      return this.model.create({
        name: "Array",
        properties: {},
        indexer: {
          key: this.builtin.integer,
          value: elementType
        }
      });
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/builtin.js
defineKit({
  builtin: {
    get string() {
      return this.program.checker.getStdType("string");
    },
    get boolean() {
      return this.program.checker.getStdType("boolean");
    },
    get bytes() {
      return this.program.checker.getStdType("bytes");
    },
    get decimal() {
      return this.program.checker.getStdType("decimal");
    },
    get decimal128() {
      return this.program.checker.getStdType("decimal128");
    },
    get duration() {
      return this.program.checker.getStdType("duration");
    },
    get float() {
      return this.program.checker.getStdType("float");
    },
    get float32() {
      return this.program.checker.getStdType("float32");
    },
    get float64() {
      return this.program.checker.getStdType("float64");
    },
    get int8() {
      return this.program.checker.getStdType("int8");
    },
    get int16() {
      return this.program.checker.getStdType("int16");
    },
    get int32() {
      return this.program.checker.getStdType("int32");
    },
    get int64() {
      return this.program.checker.getStdType("int64");
    },
    get integer() {
      return this.program.checker.getStdType("integer");
    },
    get offsetDateTime() {
      return this.program.checker.getStdType("offsetDateTime");
    },
    get plainDate() {
      return this.program.checker.getStdType("plainDate");
    },
    get plainTime() {
      return this.program.checker.getStdType("plainTime");
    },
    get safeInt() {
      return this.program.checker.getStdType("safeint");
    },
    get uint8() {
      return this.program.checker.getStdType("uint8");
    },
    get uint16() {
      return this.program.checker.getStdType("uint16");
    },
    get uint32() {
      return this.program.checker.getStdType("uint32");
    },
    get uint64() {
      return this.program.checker.getStdType("uint64");
    },
    get url() {
      return this.program.checker.getStdType("url");
    },
    get utcDateTime() {
      return this.program.checker.getStdType("utcDateTime");
    },
    get numeric() {
      return this.program.checker.getStdType("numeric");
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/entity.js
defineKit({
  entity: {
    isAssignableTo: createDiagnosable(function(source, target, diagnosticTarget) {
      return this.program.checker.isTypeAssignableTo(source, target, diagnosticTarget ?? source);
    }),
    resolve: createDiagnosable(function(reference) {
      return this.program.resolveTypeOrValueReference(reference);
    })
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/utils.js
function copyMap(map) {
  return createRekeyableMap(map.entries());
}
function decoratorApplication(typekit, decorators) {
  return decorators?.map((arg) => {
    const [decorator, args] = Array.isArray(arg) ? [arg[0], arg.slice(1)] : [arg, []];
    return {
      decorator,
      args: args.map((rawValue) => ({
        value: typeof rawValue === "object" && rawValue !== null ? rawValue : typekit.literal.create(rawValue),
        jsValue: rawValue
      }))
    };
  }) ?? [];
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/enum-member.js
defineKit({
  enumMember: {
    create(desc) {
      const member = this.program.checker.createType({
        kind: "EnumMember",
        name: desc.name,
        value: desc.value,
        decorators: decoratorApplication(this, desc.decorators),
        enum: desc.enum
        // initialized in enum.build if not provided here
      });
      this.program.checker.finishType(member);
      return member;
    },
    is(type) {
      return type.entityKind === "Type" && type.kind === "EnumMember";
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/core/decorator-utils.js
function validateDecoratorTarget(context, target, decoratorName, expectedType) {
  const isCorrectType = isTypeSpecValueTypeOf(target, expectedType);
  if (!isCorrectType) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      format: {
        decorator: decoratorName,
        to: target.kind
      },
      target: context.decoratorTarget
    });
    return false;
  }
  return true;
}
function isIntrinsicType(program, type, kind) {
  return ignoreDiagnostics(program.checker.isTypeAssignableTo(type, program.checker.getStdType(kind), type));
}
function isTypeSpecValueTypeOf(target, expectedType) {
  const kind = getTypeKind(target);
  if (kind === void 0) {
    return false;
  }
  return typeof expectedType === "string" ? expectedType === "Any" || kind === expectedType : expectedType.includes("Any") || expectedType.includes(kind);
}
function getTypeKind(target) {
  switch (typeof target) {
    case "object":
      return target.kind;
    case "string":
      return "String";
    case "number":
      return "Number";
    case "boolean":
      return "Boolean";
    default:
      return void 0;
  }
}
function typespecTypeToJson(typespecType, target) {
  if (typeof typespecType !== "object") {
    return [typespecType, []];
  }
  return typespecTypeToJsonInternal(typespecType, target, []);
}
function typespecTypeToJsonInternal(typespecType, target, path) {
  switch (typespecType.kind) {
    case "String":
    case "Boolean":
    case "Number":
      return [typespecType.value, []];
    case "EnumMember":
      return [typespecType.value ?? typespecType.name, []];
    case "Tuple": {
      const result = [];
      for (const [index, type] of typespecType.values.entries()) {
        const [item, diagnostics] = typespecTypeToJsonInternal(type, target, [
          ...path,
          index.toString()
        ]);
        if (diagnostics.length > 0) {
          return [void 0, diagnostics];
        }
        result.push(item);
      }
      return [result, []];
    }
    case "Model": {
      const result = {};
      for (const [name, type] of typespecType.properties.entries()) {
        const [item, diagnostics] = typespecTypeToJsonInternal(type.type, target, [
          ...path,
          name.toString()
        ]);
        if (diagnostics.length > 0) {
          return [void 0, diagnostics];
        }
        result[name] = item;
      }
      return [result, []];
    }
    case "StringTemplate":
      if (typespecType.stringValue) {
        return [typespecType.stringValue, []];
      }
    // By design
    // eslint-disable-next-line no-fallthrough
    default:
      const diagnostic = path.length === 0 ? createDiagnostic({
        code: "invalid-value",
        format: {
          kind: typespecType.kind
        },
        target
      }) : createDiagnostic({
        code: "invalid-value",
        messageId: "atPath",
        format: {
          kind: typespecType.kind,
          path: path.join(".")
        },
        target
      });
      return [void 0, [diagnostic]];
  }
}
function validateDecoratorUniqueOnNode(context, type, decorator) {
  compilerAssert("decorators" in type, "Type should have decorators");
  const sameDecorators = type.decorators.filter((x2) => x2.decorator === decorator && x2.node?.kind === SyntaxKind.DecoratorExpression && x2.node?.parent === type.node);
  if (sameDecorators.length > 1) {
    reportDiagnostic(context.program, {
      code: "duplicate-decorator",
      format: { decoratorName: "@" + decorator.name.slice(1) },
      target: context.decoratorTarget
    });
    return false;
  }
  return true;
}
function validateDecoratorNotOnType(context, type, badDecorator, givenDecorator) {
  compilerAssert("decorators" in type, "Type should have decorators");
  const decAppsToCheck = [];
  let base = type;
  while (base) {
    decAppsToCheck.push(...base.decorators);
    base = getHeritage(base);
  }
  for (const decapp of decAppsToCheck) {
    if (decapp.decorator === badDecorator) {
      reportDiagnostic(context.program, {
        code: "decorator-conflict",
        format: {
          decoratorName: "@" + badDecorator.name.slice(1),
          otherDecoratorName: "@" + givenDecorator.name.slice(1)
        },
        target: context.decoratorTarget
      });
      return false;
    }
  }
  return true;
  function getHeritage(type2) {
    if (type2.kind === "Model") {
      return type2.baseModel;
    } else if (type2.kind === "Scalar") {
      return type2.baseScalar;
    } else {
      return void 0;
    }
  }
}
function getPropertyType(target) {
  if (target.kind === "ModelProperty") {
    return target.type;
  } else {
    return target;
  }
}

// src/typespec/core/packages/compiler/dist/src/lib/utils.js
function filterModelPropertiesInPlace(model, filter) {
  for (const [key, prop] of model.properties) {
    if (!filter(prop)) {
      model.properties.delete(key);
    }
  }
}
function createStateSymbol(name) {
  return Symbol.for(`TypeSpec.${name}`);
}
function replaceTemplatedStringFromProperties(formatString, sourceObject) {
  if (sourceObject.kind === "TemplateParameter") {
    return formatString;
  }
  return formatString.replace(/{(\w+)}/g, (_2, propName) => {
    return sourceObject[propName];
  });
}

// src/typespec/core/packages/compiler/dist/src/core/deprecation.js
var deprecatedKey = createStateSymbol("deprecated");
function isDeprecated(program, type) {
  return program.stateMap(deprecatedKey).has(type);
}
function getDeprecationDetails(program, typeOrNode) {
  function isType2(maybeType) {
    return typeof maybeType.kind === "string";
  }
  if (isType2(typeOrNode)) {
    return program.stateMap(deprecatedKey).get(typeOrNode);
  } else {
    const deprecatedDirective = (typeOrNode.directives ?? []).find((directive) => directive.target.sv === "deprecated");
    if (deprecatedDirective?.arguments[0].kind === SyntaxKind.StringLiteral) {
      return {
        message: deprecatedDirective.arguments[0].value
      };
    }
  }
  return void 0;
}
function markDeprecated(program, type, details) {
  program.stateMap(deprecatedKey).set(type, details);
}

// src/typespec/core/packages/compiler/dist/src/core/intrinsic-type-state.js
var stateKeys = {
  minValues: createStateSymbol("minValues"),
  maxValues: createStateSymbol("maxValues"),
  minValueExclusive: createStateSymbol("minValueExclusive"),
  maxValueExclusive: createStateSymbol("maxValueExclusive"),
  minLength: createStateSymbol("minLengthValues"),
  maxLength: createStateSymbol("maxLengthValues"),
  minItems: createStateSymbol("minItems"),
  maxItems: createStateSymbol("maxItems"),
  docs: createStateSymbol("docs"),
  returnDocs: createStateSymbol("returnsDocs"),
  errorsDocs: createStateSymbol("errorDocs"),
  discriminator: createStateSymbol("discriminator")
};
function setMinValue(program, target, value) {
  program.stateMap(stateKeys.minValues).set(target, value);
}
function getMinValueAsNumeric(program, target) {
  return program.stateMap(stateKeys.minValues).get(target);
}
function getMinValue(program, target) {
  return getMinValueAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMaxValue(program, target, value) {
  program.stateMap(stateKeys.maxValues).set(target, value);
}
function getMaxValueAsNumeric(program, target) {
  return program.stateMap(stateKeys.maxValues).get(target);
}
function getMaxValue(program, target) {
  return getMaxValueAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMinValueExclusive(program, target, value) {
  program.stateMap(stateKeys.minValueExclusive).set(target, value);
}
function getMinValueExclusiveAsNumeric(program, target) {
  return program.stateMap(stateKeys.minValueExclusive).get(target);
}
function getMinValueExclusive(program, target) {
  return getMinValueExclusiveAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMaxValueExclusive(program, target, value) {
  program.stateMap(stateKeys.maxValueExclusive).set(target, value);
}
function getMaxValueExclusiveAsNumeric(program, target) {
  return program.stateMap(stateKeys.maxValueExclusive).get(target);
}
function getMaxValueExclusive(program, target) {
  return getMaxValueExclusiveAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMinLength(program, target, value) {
  program.stateMap(stateKeys.minLength).set(target, value);
}
function getMinLengthAsNumeric(program, target) {
  return program.stateMap(stateKeys.minLength).get(target);
}
function getMinLength(program, target) {
  return getMinLengthAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMaxLength(program, target, value) {
  program.stateMap(stateKeys.maxLength).set(target, value);
}
function getMaxLengthAsNumeric(program, target) {
  return program.stateMap(stateKeys.maxLength).get(target);
}
function getMaxLength(program, target) {
  return getMaxLengthAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMinItems(program, target, value) {
  program.stateMap(stateKeys.minItems).set(target, value);
}
function getMinItemsAsNumeric(program, target) {
  return program.stateMap(stateKeys.minItems).get(target);
}
function getMinItems(program, target) {
  return getMinItemsAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setMaxItems(program, target, value) {
  program.stateMap(stateKeys.maxItems).set(target, value);
}
function getMaxItemsAsNumeric(program, target) {
  return program.stateMap(stateKeys.maxItems).get(target);
}
function getMaxItems(program, target) {
  return getMaxItemsAsNumeric(program, target)?.asNumber() ?? void 0;
}
function setDocData(program, target, key, data) {
  program.stateMap(getDocKey(key)).set(target, data);
}
function getDocKey(target) {
  switch (target) {
    case "self":
      return stateKeys.docs;
    case "returns":
      return stateKeys.returnDocs;
    case "errors":
      return stateKeys.errorsDocs;
  }
}
function getDocDataInternal(program, target, key) {
  return program.stateMap(getDocKey(key)).get(target);
}
function getDocData(program, target) {
  return getDocDataInternal(program, target, "self");
}
function setDiscriminator(program, entity, discriminator) {
  program.stateMap(stateKeys.discriminator).set(entity, discriminator);
}
function getDiscriminator(program, entity) {
  return program.stateMap(stateKeys.discriminator).get(entity);
}
function getDiscriminatedTypes(program) {
  return [...program.stateMap(stateKeys.discriminator).entries()];
}
var [getDiscriminatedOptions, setDiscriminatedOptions] = useStateMap(createStateSymbol("discriminated"));

// src/typespec/core/packages/compiler/dist/src/core/helpers/discriminator-utils.js
function getDiscriminatedUnion(typeOrProgram, typeOrDiscriminator) {
  return getDiscriminatedUnionForUnion(typeOrProgram, typeOrDiscriminator);
}
function validateInheritanceDiscriminatedUnions(program) {
  for (const [type, discriminator] of getDiscriminatedTypes(program)) {
    if (type.kind === "Model") {
      const [_2, diagnostics] = getDiscriminatedUnionFromInheritance(type, discriminator);
      program.reportDiagnostics(diagnostics);
    }
  }
}
function getDiscriminatedUnionForUnion(program, type) {
  const options = getDiscriminatedOptions(program, type);
  const diagnostics = [];
  if (options === void 0) {
    return [void 0, []];
  }
  const variants = /* @__PURE__ */ new Map();
  let defaultVariant;
  for (const variant of type.variants.values()) {
    if (typeof variant.name !== "string") {
      if (defaultVariant) {
        diagnostics.push(createDiagnostic({
          code: "invalid-discriminated-union-variant",
          messageId: "duplicateDefaultVariant",
          target: variant
        }));
      } else {
        defaultVariant = variant.type;
      }
      continue;
    }
    variants.set(variant.name, variant.type);
    if (options.envelope === "none") {
      if (variant.type.kind !== "Model") {
        diagnostics.push(createDiagnostic({
          code: "invalid-discriminated-union-variant",
          messageId: "noEnvelopeModel",
          format: { name: variant.name.toString() },
          target: variant
        }));
        continue;
      }
      const prop = variant.type.properties.get(options.discriminatorPropertyName);
      if (prop !== void 0) {
        const key = getStringValue(prop.type);
        if (key !== variant.name) {
          diagnostics.push(createDiagnostic({
            code: "invalid-discriminated-union-variant",
            messageId: "discriminantMismatch",
            format: {
              name: variant.name.toString(),
              discriminant: options.discriminatorPropertyName,
              propertyValue: key,
              variantName: String(variant.name)
            },
            target: variant.type
          }));
        }
      }
    }
  }
  return [
    {
      type,
      options,
      variants
    },
    diagnostics
  ];
}
function getDiscriminatedUnionFromInheritance(type, discriminator) {
  const variants = /* @__PURE__ */ new Map();
  const diagnostics = [];
  const duplicates = new DuplicateTracker();
  function checkForVariantsIn(current) {
    for (const derivedModel of current.derivedModels) {
      if (isTemplateDeclarationOrInstance(derivedModel)) {
        continue;
      }
      const keys = getDiscriminatorValues(derivedModel, discriminator, diagnostics);
      if (keys === void 0) {
        if (derivedModel.derivedModels.length === 0) {
          diagnostics.push(createDiagnostic({
            code: "missing-discriminator-property",
            format: { discriminator: discriminator.propertyName },
            target: derivedModel
          }));
        } else {
          checkForVariantsIn(derivedModel);
        }
      } else {
        for (const key of keys) {
          duplicates.track(key, derivedModel);
          variants.set(key, derivedModel);
        }
      }
    }
  }
  checkForVariantsIn(type);
  reportDuplicateDiscriminatorValues(duplicates, diagnostics);
  const discriminatedUnion = {
    kind: "legacy",
    propertyName: discriminator.propertyName,
    variants
  };
  return [discriminatedUnion, diagnostics];
}
function reportDuplicateDiscriminatorValues(duplicates, diagnostics) {
  for (const [duplicateKey, models] of duplicates.entries()) {
    for (const model of models) {
      diagnostics.push(createDiagnostic({
        code: "invalid-discriminator-value",
        messageId: "duplicate",
        format: { discriminator: duplicateKey },
        target: model
      }));
    }
  }
}
function getDiscriminatorProperty(model, discriminator, diagnostics) {
  const prop = model.properties.get(discriminator.propertyName);
  if (prop && prop.optional) {
    diagnostics.push(createDiagnostic({
      code: "invalid-discriminator-value",
      messageId: "required",
      target: prop
    }));
  }
  return prop;
}
function getDiscriminatorValues(model, discriminator, diagnostics) {
  const prop = getDiscriminatorProperty(model, discriminator, diagnostics);
  if (!prop)
    return void 0;
  const keys = getStringValues(prop.type);
  if (keys.length === 0) {
    diagnostics.push(createDiagnostic({
      code: "invalid-discriminator-value",
      format: { kind: prop.type.kind },
      target: prop
    }));
  }
  return keys;
}
function getStringValues(type) {
  switch (type.kind) {
    case "String":
      return [type.value];
    case "Union":
      return [...type.variants.values()].flatMap((x2) => getStringValues(x2.type)).filter(isDefined);
    case "EnumMember":
      return typeof type.value !== "number" ? [type.value ?? type.name] : [];
    case "UnionVariant":
      return getStringValues(type.type);
    default:
      return [];
  }
}
function getStringValue(type) {
  switch (type.kind) {
    case "String":
      return type.value;
    case "EnumMember":
      return typeof type.value !== "number" ? type.value ?? type.name : void 0;
    default:
      return void 0;
  }
}

// src/typespec/core/packages/compiler/dist/src/core/helpers/type-name-utils.js
function getTypeName(type, options) {
  switch (type.kind) {
    case "Namespace":
      return getNamespaceFullName(type, options);
    case "TemplateParameter":
      return getIdentifierName(type.node.id.sv, options);
    case "Scalar":
      return getScalarName(type, options);
    case "Model":
      return getModelName(type, options);
    case "ModelProperty":
      return getModelPropertyName(type, options);
    case "Interface":
      return getInterfaceName(type, options);
    case "Operation":
      return getOperationName(type, options);
    case "Enum":
      return getEnumName(type, options);
    case "EnumMember":
      return `${getEnumName(type.enum, options)}.${getIdentifierName(type.name, options)}`;
    case "Union":
      return getUnionName(type, options);
    case "UnionVariant":
      return getTypeName(type.type, options);
    case "Tuple":
      return "[" + type.values.map((x2) => getTypeName(x2, options)).join(", ") + "]";
    case "StringTemplate":
      return getStringTemplateName(type);
    case "String":
      return `"${type.value}"`;
    case "Number":
      return type.valueAsString;
    case "Boolean":
      return type.value.toString();
    case "Intrinsic":
      return type.name;
    default:
      return `(unnamed type)`;
  }
}
function getValuePreview(value, options) {
  switch (value.valueKind) {
    case "ObjectValue":
      return `#{${[...value.properties.entries()].map(([name, value2]) => `${name}: ${getValuePreview(value2.value, options)}`).join(", ")}}`;
    case "ArrayValue":
      return `#[${value.values.map((x2) => getValuePreview(x2, options)).join(", ")}]`;
    case "StringValue":
      return `"${value.value}"`;
    case "BooleanValue":
      return `${value.value}`;
    case "NumericValue":
      return `${value.value.toString()}`;
    case "EnumValue":
      return getTypeName(value.value);
    case "NullValue":
      return "null";
    case "ScalarValue":
      return `${getTypeName(value.type, options)}.${value.value.name}(${value.value.args.map((x2) => getValuePreview(x2, options)).join(", ")}})`;
  }
}
function getEntityName(entity, options) {
  if (isValue(entity)) {
    return getValuePreview(entity, options);
  } else if (isType(entity)) {
    return getTypeName(entity, options);
  } else {
    switch (entity.entityKind) {
      case "MixedParameterConstraint":
        return [
          entity.type && getEntityName(entity.type),
          entity.valueType && `valueof ${getEntityName(entity.valueType)}`
        ].filter(isDefined).join(" | ");
      case "Indeterminate":
        return getTypeName(entity.type, options);
    }
  }
}
function isStdNamespace(namespace) {
  return namespace.name === "TypeSpec" && namespace.namespace?.name === "" || namespace.name === "Reflection" && namespace.namespace?.name === "TypeSpec" && namespace.namespace?.namespace?.name === "";
}
function getNamespaceFullName(type, options) {
  const filter = options?.namespaceFilter;
  const segments = [];
  let current = type;
  while (current && current.name !== "") {
    if (filter && !filter(current)) {
      break;
    }
    segments.unshift(getIdentifierName(current.name, options));
    current = current.namespace;
  }
  return segments.join(".");
}
function getNamespacePrefix(type, options) {
  if (type === void 0 || isStdNamespace(type) || options?.nameOnly === true) {
    return "";
  }
  const namespaceFullName = getNamespaceFullName(type, options);
  return namespaceFullName !== "" ? namespaceFullName + "." : "";
}
function getEnumName(e2, options) {
  return `${getNamespacePrefix(e2.namespace, options)}${getIdentifierName(e2.name, options)}`;
}
function getScalarName(scalar, options) {
  return `${getNamespacePrefix(scalar.namespace, options)}${getIdentifierName(scalar.name, options)}`;
}
function getModelName(model, options) {
  const nsPrefix = getNamespacePrefix(model.namespace, options);
  if (model.name === "" && model.properties.size === 0) {
    return "{}";
  }
  if (model.indexer && model.indexer.key.kind === "Scalar") {
    if (model.name === "Array" && isInTypeSpecNamespace(model)) {
      return `${getTypeName(model.indexer.value, options)}[]`;
    }
  }
  if (model.name === "") {
    return nsPrefix + `{ ${[...model.properties.values()].map((prop) => `${prop.name}: ${getTypeName(prop.type, options)}`).join(", ")} }`;
  }
  const modelName = nsPrefix + getIdentifierName(model.name, options);
  if (isTemplateInstance(model)) {
    const args = model.templateMapper.args.map((x2) => getEntityName(x2, options));
    return `${modelName}<${args.join(", ")}>`;
  } else if (model.node?.templateParameters?.length > 0) {
    const params = model.node.templateParameters.map((t2) => getIdentifierName(t2.id.sv, options));
    return `${modelName}<${params.join(", ")}>`;
  } else {
    return modelName;
  }
}
function getUnionName(type, options) {
  const nsPrefix = type.expression ? "" : getNamespacePrefix(type.namespace, options);
  const typeName = type.name ? getIdentifierName(type.name, options) : [...type.variants.values()].map((x2) => getTypeName(x2.type, options)).join(" | ");
  return nsPrefix + typeName;
}
function isTypeSpecNamespace(namespace) {
  return namespace.name === "TypeSpec" && namespace.namespace?.name === "";
}
function isInTypeSpecNamespace(type) {
  return Boolean(type.namespace && isTypeSpecNamespace(type.namespace));
}
function getModelPropertyName(prop, options) {
  if (options?.nameOnly === true) {
    return prop.name;
  }
  const modelName = prop.model ? getModelName(prop.model, options) : void 0;
  return `${modelName ?? "(anonymous model)"}.${prop.name}`;
}
function getInterfaceName(iface, options) {
  let interfaceName = getIdentifierName(iface.name, options);
  if (isTemplateInstance(iface)) {
    interfaceName += `<${iface.templateMapper.args.map((x2) => getEntityName(x2, options)).join(", ")}>`;
  }
  return `${getNamespacePrefix(iface.namespace, options)}${interfaceName}`;
}
function getOperationName(op, options) {
  let opName = getIdentifierName(op.name, options);
  if (op.node && op.node.templateParameters.length > 0) {
    const params = op.node.templateParameters.map((t2) => getIdentifierName(t2.id.sv, options));
    opName += `<${params.join(", ")}>`;
  }
  if (options?.nameOnly === true) {
    return opName;
  } else {
    const prefix = op.interface ? getInterfaceName(op.interface, options) + "." : getNamespacePrefix(op.namespace, options);
    return `${prefix}${opName}`;
  }
}
function getIdentifierName(name, options) {
  return options?.printable ? printIdentifier(name) : name;
}
function getStringTemplateName(type) {
  if (type.stringValue) {
    return `"${type.stringValue}"`;
  }
  return "string";
}

// src/typespec/core/packages/compiler/dist/src/core/mime-type.js
var regex = /^(application|audio|font|example|image|message|model|multipart|text|video|x-(?:[0-9A-Za-z!#$%&'*+.^_`|~-]+))\/([0-9A-Za-z!#$%&'*+.^_`|~-]+)$/;
function parseMimeType(mimeType) {
  const match = mimeType.match(regex);
  if (match == null) {
    return void 0;
  }
  const type = {
    type: match[1],
    ...parseSubType(match[2])
  };
  return type;
}
function parseSubType(value) {
  if (!value.includes("+"))
    return { subtype: value };
  const [subtype, suffix] = value.split("+", 2);
  return { subtype, suffix };
}

// src/typespec/core/packages/compiler/dist/src/lib/key.js
var [getKey, setKey] = useStateMap(createStateSymbol("key"));
function isKey(program, property) {
  return getKey(program, property) !== void 0;
}

// src/typespec/core/packages/compiler/dist/src/lib/encoded-names.js
var [getEncodedNamesMap, setEncodedNamesMap, getEncodedNamesStateMap] = useStateMap(createStateSymbol("encodedName"));
function $encodedName(context, target, mimeType, name) {
  let existing = getEncodedNamesMap(context.program, target);
  if (existing === void 0) {
    existing = /* @__PURE__ */ new Map();
    setEncodedNamesMap(context.program, target, existing);
  }
  const mimeTypeObj = parseMimeType(mimeType);
  if (mimeTypeObj === void 0) {
    reportDiagnostic(context.program, {
      code: "invalid-mime-type",
      format: { mimeType },
      target: context.getArgumentTarget(0)
    });
  } else if (mimeTypeObj.suffix) {
    reportDiagnostic(context.program, {
      code: "no-mime-type-suffix",
      format: { mimeType, suffix: mimeTypeObj.suffix },
      target: context.getArgumentTarget(0)
    });
  }
  existing.set(mimeType, name);
}
function getEncodedName(program, target, mimeType) {
  const mimeTypeObj = parseMimeType(mimeType);
  if (mimeTypeObj === void 0) {
    return void 0;
  }
  const resolvedMimeType = mimeTypeObj?.suffix ? `${mimeTypeObj.type}/${mimeTypeObj.suffix}` : mimeType;
  return getEncodedNamesMap(program, target)?.get(resolvedMimeType);
}
function resolveEncodedName(program, target, mimeType) {
  return getEncodedName(program, target, mimeType) ?? target.name;
}
function validateEncodedNamesConflicts(program) {
  const duplicateTrackers = /* @__PURE__ */ new Map();
  function getOrCreateDuplicateTracker(type, mimeType) {
    let perMimeTypes = duplicateTrackers.get(type);
    if (perMimeTypes === void 0) {
      perMimeTypes = /* @__PURE__ */ new Map();
      duplicateTrackers.set(type, perMimeTypes);
    }
    let tracker = perMimeTypes.get(mimeType);
    if (tracker === void 0) {
      tracker = new DuplicateTracker();
      perMimeTypes.set(mimeType, tracker);
    }
    return tracker;
  }
  for (const [target, map] of getEncodedNamesStateMap(program).entries()) {
    const scope = getScope(target);
    if (scope === void 0) {
      return;
    }
    for (const [mimeType, name] of map.entries()) {
      const duplicateTracker = getOrCreateDuplicateTracker(scope.parent, mimeType);
      duplicateTracker.track(name, target);
      if (scope.members.has(name)) {
        reportDiagnostic(program, {
          code: "encoded-name-conflict",
          format: { name, mimeType },
          target
        });
      }
    }
  }
  for (const perMimeTypes of duplicateTrackers.values()) {
    for (const [mimeType, tracker] of perMimeTypes.entries()) {
      for (const [duplicateName, items] of tracker.entries()) {
        for (const item of items) {
          reportDiagnostic(program, {
            code: "encoded-name-conflict",
            messageId: "duplicate",
            format: { name: duplicateName, mimeType },
            target: item
          });
        }
      }
    }
  }
}
function getScope(type) {
  switch (type.kind) {
    case "ModelProperty":
      return type.model && { parent: type.model, members: type.model.properties };
    case "EnumMember":
      return { parent: type.enum, members: type.enum.members };
    case "UnionVariant":
      return { parent: type.union, members: type.union.variants };
    default:
      return void 0;
  }
}

// src/typespec/node_modules/.pnpm/temporal-polyfill@0.3.0/node_modules/temporal-polyfill/chunks/internal.js
function clampProp(e2, n2, t2, o2, r2) {
  return clampEntity(n2, ((e3, n3) => {
    const t3 = e3[n3];
    if (void 0 === t3) {
      throw new TypeError(missingField(n3));
    }
    return t3;
  })(e2, n2), t2, o2, r2);
}
function clampEntity(e2, n2, t2, o2, r2, i2) {
  const a2 = clampNumber(n2, t2, o2);
  if (r2 && n2 !== a2) {
    throw new RangeError(numberOutOfRange(e2, n2, t2, o2, i2));
  }
  return a2;
}
function s(e2) {
  return null !== e2 && /object|function/.test(typeof e2);
}
function on(e2, n2 = Map) {
  const t2 = new n2();
  return (n3, ...o2) => {
    if (t2.has(n3)) {
      return t2.get(n3);
    }
    const r2 = e2(n3, ...o2);
    return t2.set(n3, r2), r2;
  };
}
function r(e2) {
  return n({
    name: e2
  }, 1);
}
function n(n2, t2) {
  return e(((e2) => ({
    value: e2,
    configurable: 1,
    writable: !t2
  })), n2);
}
function t(n2) {
  return e(((e2) => ({
    get: e2,
    configurable: 1
  })), n2);
}
function o(e2) {
  return {
    [Symbol.toStringTag]: {
      value: e2,
      configurable: 1
    }
  };
}
function zipProps(e2, n2) {
  const t2 = {};
  let o2 = e2.length;
  for (const r2 of n2) {
    t2[e2[--o2]] = r2;
  }
  return t2;
}
function e(e2, n2, t2) {
  const o2 = {};
  for (const r2 in n2) {
    o2[r2] = e2(n2[r2], r2, t2);
  }
  return o2;
}
function g(e2, n2, t2) {
  const o2 = {};
  for (let r2 = 0; r2 < n2.length; r2++) {
    const i2 = n2[r2];
    o2[i2] = e2(i2, r2, t2);
  }
  return o2;
}
function remapProps(e2, n2, t2) {
  const o2 = {};
  for (let r2 = 0; r2 < e2.length; r2++) {
    o2[n2[r2]] = t2[e2[r2]];
  }
  return o2;
}
function nn(e2, n2) {
  const t2 = /* @__PURE__ */ Object.create(null);
  for (const o2 of e2) {
    t2[o2] = n2[o2];
  }
  return t2;
}
function hasAnyPropsByName(e2, n2) {
  for (const t2 of n2) {
    if (t2 in e2) {
      return 1;
    }
  }
  return 0;
}
function allPropsEqual(e2, n2, t2) {
  for (const o2 of e2) {
    if (n2[o2] !== t2[o2]) {
      return 0;
    }
  }
  return 1;
}
function zeroOutProps(e2, n2, t2) {
  const o2 = {
    ...t2
  };
  for (let t3 = 0; t3 < n2; t3++) {
    o2[e2[t3]] = 0;
  }
  return o2;
}
function Pt(e2, ...n2) {
  return (...t2) => e2(...n2, ...t2);
}
function capitalize2(e2) {
  return e2[0].toUpperCase() + e2.substring(1);
}
function sortStrings(e2) {
  return e2.slice().sort();
}
function padNumber(e2, n2) {
  return String(n2).padStart(e2, "0");
}
function compareNumbers(e2, n2) {
  return Math.sign(e2 - n2);
}
function clampNumber(e2, n2, t2) {
  return Math.min(Math.max(e2, n2), t2);
}
function divModFloor(e2, n2) {
  return [Math.floor(e2 / n2), modFloor(e2, n2)];
}
function modFloor(e2, n2) {
  return (e2 % n2 + n2) % n2;
}
function divModTrunc(e2, n2) {
  return [divTrunc(e2, n2), modTrunc(e2, n2)];
}
function divTrunc(e2, n2) {
  return Math.trunc(e2 / n2) || 0;
}
function modTrunc(e2, n2) {
  return e2 % n2 || 0;
}
function hasHalf(e2) {
  return 0.5 === Math.abs(e2 % 1);
}
function givenFieldsToBigNano(e2, n2, t2) {
  let o2 = 0, r2 = 0;
  for (let i3 = 0; i3 <= n2; i3++) {
    const n3 = e2[t2[i3]], a3 = Ao[i3], s2 = Uo / a3, [c2, u2] = divModTrunc(n3, s2);
    o2 += u2 * a3, r2 += c2;
  }
  const [i2, a2] = divModTrunc(o2, Uo);
  return [r2 + i2, a2];
}
function nanoToGivenFields(e2, n2, t2) {
  const o2 = {};
  for (let r2 = n2; r2 >= 0; r2--) {
    const n3 = Ao[r2];
    o2[t2[r2]] = divTrunc(e2, n3), e2 = modTrunc(e2, n3);
  }
  return o2;
}
function d(e2) {
  if (void 0 !== e2) {
    return m(e2);
  }
}
function P(e2) {
  if (void 0 !== e2) {
    return h(e2);
  }
}
function S(e2) {
  if (void 0 !== e2) {
    return T(e2);
  }
}
function h(e2) {
  return requireNumberIsPositive(T(e2));
}
function T(e2) {
  return ze(cr(e2));
}
function requirePropDefined(e2, n2) {
  if (null == n2) {
    throw new RangeError(missingField(e2));
  }
  return n2;
}
function requireObjectLike(e2) {
  if (!s(e2)) {
    throw new TypeError(oo);
  }
  return e2;
}
function requireType(e2, n2, t2 = e2) {
  if (typeof n2 !== e2) {
    throw new TypeError(invalidEntity(t2, n2));
  }
  return n2;
}
function ze(e2, n2 = "number") {
  if (!Number.isInteger(e2)) {
    throw new RangeError(expectedInteger(n2, e2));
  }
  return e2 || 0;
}
function requireNumberIsPositive(e2, n2 = "number") {
  if (e2 <= 0) {
    throw new RangeError(expectedPositive(n2, e2));
  }
  return e2;
}
function toString(e2) {
  if ("symbol" == typeof e2) {
    throw new TypeError(no);
  }
  return String(e2);
}
function toStringViaPrimitive(e2, n2) {
  return s(e2) ? String(e2) : m(e2, n2);
}
function toBigInt(e2) {
  if ("string" == typeof e2) {
    return BigInt(e2);
  }
  if ("bigint" != typeof e2) {
    throw new TypeError(invalidBigInt(e2));
  }
  return e2;
}
function toNumber(e2, n2 = "number") {
  if ("bigint" == typeof e2) {
    throw new TypeError(forbiddenBigIntToNumber(n2));
  }
  if (e2 = Number(e2), !Number.isFinite(e2)) {
    throw new RangeError(expectedFinite(n2, e2));
  }
  return e2;
}
function toInteger(e2, n2) {
  return Math.trunc(toNumber(e2, n2)) || 0;
}
function toStrictInteger(e2, n2) {
  return ze(toNumber(e2, n2), n2);
}
function toPositiveInteger(e2, n2) {
  return requireNumberIsPositive(toInteger(e2, n2), n2);
}
function createBigNano(e2, n2) {
  let [t2, o2] = divModTrunc(n2, Uo), r2 = e2 + t2;
  const i2 = Math.sign(r2);
  return i2 && i2 === -Math.sign(o2) && (r2 -= i2, o2 += i2 * Uo), [r2, o2];
}
function addBigNanos(e2, n2, t2 = 1) {
  return createBigNano(e2[0] + n2[0] * t2, e2[1] + n2[1] * t2);
}
function moveBigNano(e2, n2) {
  return createBigNano(e2[0], e2[1] + n2);
}
function diffBigNanos(e2, n2) {
  return addBigNanos(n2, e2, -1);
}
function compareBigNanos(e2, n2) {
  return compareNumbers(e2[0], n2[0]) || compareNumbers(e2[1], n2[1]);
}
function bigNanoOutside(e2, n2, t2) {
  return -1 === compareBigNanos(e2, n2) || 1 === compareBigNanos(e2, t2);
}
function bigIntToBigNano(e2, n2 = 1) {
  const t2 = BigInt(Uo / n2);
  return [Number(e2 / t2), Number(e2 % t2) * n2];
}
function Ge(e2, n2 = 1) {
  const t2 = Uo / n2, [o2, r2] = divModTrunc(e2, t2);
  return [o2, r2 * n2];
}
function bigNanoToNumber(e2, n2 = 1, t2) {
  const [o2, r2] = e2, [i2, a2] = divModTrunc(r2, n2);
  return o2 * (Uo / n2) + (i2 + (t2 ? a2 / n2 : 0));
}
function divModBigNano(e2, n2, t2 = divModFloor) {
  const [o2, r2] = e2, [i2, a2] = t2(r2, n2);
  return [o2 * (Uo / n2) + i2, a2];
}
function checkIsoYearMonthInBounds(e2) {
  return clampProp(e2, "isoYear", wr, Fr, 1), e2.isoYear === wr ? clampProp(e2, "isoMonth", 4, 12, 1) : e2.isoYear === Fr && clampProp(e2, "isoMonth", 1, 9, 1), e2;
}
function checkIsoDateInBounds(e2) {
  return checkIsoDateTimeInBounds({
    ...e2,
    ...Nt,
    isoHour: 12
  }), e2;
}
function checkIsoDateTimeInBounds(e2) {
  const n2 = clampProp(e2, "isoYear", wr, Fr, 1), t2 = n2 === wr ? 1 : n2 === Fr ? -1 : 0;
  return t2 && checkEpochNanoInBounds(isoToEpochNano({
    ...e2,
    isoDay: e2.isoDay + t2,
    isoNanosecond: e2.isoNanosecond - t2
  })), e2;
}
function checkEpochNanoInBounds(e2) {
  if (!e2 || bigNanoOutside(e2, Sr, Er)) {
    throw new RangeError(Io);
  }
  return e2;
}
function isoTimeFieldsToNano(e2) {
  return givenFieldsToBigNano(e2, 5, w)[1];
}
function nanoToIsoTimeAndDay(e2) {
  const [n2, t2] = divModFloor(e2, Uo);
  return [nanoToGivenFields(t2, 5, w), n2];
}
function epochNanoToSecMod(e2) {
  return divModBigNano(e2, Ro);
}
function isoToEpochMilli(e2) {
  return isoArgsToEpochMilli(e2.isoYear, e2.isoMonth, e2.isoDay, e2.isoHour, e2.isoMinute, e2.isoSecond, e2.isoMillisecond);
}
function isoToEpochNano(e2) {
  const n2 = isoToEpochMilli(e2);
  if (void 0 !== n2) {
    const [t2, o2] = divModTrunc(n2, ko);
    return [t2, o2 * Qe + (e2.isoMicrosecond || 0) * Yo + (e2.isoNanosecond || 0)];
  }
}
function isoToEpochNanoWithOffset(e2, n2) {
  const [t2, o2] = nanoToIsoTimeAndDay(isoTimeFieldsToNano(e2) - n2);
  return checkEpochNanoInBounds(isoToEpochNano({
    ...e2,
    isoDay: e2.isoDay + o2,
    ...t2
  }));
}
function isoArgsToEpochSec(...e2) {
  return isoArgsToEpochMilli(...e2) / Co;
}
function isoArgsToEpochMilli(...e2) {
  const [n2, t2] = isoToLegacyDate(...e2), o2 = n2.valueOf();
  if (!isNaN(o2)) {
    return o2 - t2 * ko;
  }
}
function isoToLegacyDate(e2, n2 = 1, t2 = 1, o2 = 0, r2 = 0, i2 = 0, a2 = 0) {
  const s2 = e2 === wr ? 1 : e2 === Fr ? -1 : 0, c2 = /* @__PURE__ */ new Date();
  return c2.setUTCHours(o2, r2, i2, a2), c2.setUTCFullYear(e2, n2 - 1, t2 + s2), [c2, s2];
}
function epochNanoToIso(e2, n2) {
  let [t2, o2] = moveBigNano(e2, n2);
  o2 < 0 && (o2 += Uo, t2 -= 1);
  const [r2, i2] = divModFloor(o2, Qe), [a2, s2] = divModFloor(i2, Yo);
  return epochMilliToIso(t2 * ko + r2, a2, s2);
}
function epochMilliToIso(e2, n2 = 0, t2 = 0) {
  const o2 = Math.ceil(Math.max(0, Math.abs(e2) - Pr) / ko) * Math.sign(e2), r2 = new Date(e2 - o2 * ko);
  return zipProps(Tr, [r2.getUTCFullYear(), r2.getUTCMonth() + 1, r2.getUTCDate() + o2, r2.getUTCHours(), r2.getUTCMinutes(), r2.getUTCSeconds(), r2.getUTCMilliseconds(), n2, t2]);
}
function hashIntlFormatParts(e2, n2) {
  if (n2 < -Pr) {
    throw new RangeError(Io);
  }
  const t2 = e2.formatToParts(n2), o2 = {};
  for (const e3 of t2) {
    o2[e3.type] = e3.value;
  }
  return o2;
}
function computeIsoDateParts(e2) {
  return [e2.isoYear, e2.isoMonth, e2.isoDay];
}
function computeIsoMonthCodeParts(e2, n2) {
  return [n2, 0];
}
function computeIsoMonthsInYear() {
  return kr;
}
function computeIsoDaysInMonth(e2, n2) {
  switch (n2) {
    case 2:
      return computeIsoInLeapYear(e2) ? 29 : 28;
    case 4:
    case 6:
    case 9:
    case 11:
      return 30;
  }
  return 31;
}
function computeIsoDaysInYear(e2) {
  return computeIsoInLeapYear(e2) ? 366 : 365;
}
function computeIsoInLeapYear(e2) {
  return e2 % 4 == 0 && (e2 % 100 != 0 || e2 % 400 == 0);
}
function computeIsoDayOfWeek(e2) {
  const [n2, t2] = isoToLegacyDate(e2.isoYear, e2.isoMonth, e2.isoDay);
  return modFloor(n2.getUTCDay() - t2, 7) || 7;
}
function computeIsoEraParts(e2) {
  return this.id === or ? (({ isoYear: e3 }) => e3 < 1 ? ["gregory-inverse", 1 - e3] : ["gregory", e3])(e2) : this.id === rr ? Yr(e2) : [];
}
function computeJapaneseEraParts(e2) {
  const n2 = isoToEpochMilli(e2);
  if (n2 < Cr) {
    const { isoYear: n3 } = e2;
    return n3 < 1 ? ["japanese-inverse", 1 - n3] : ["japanese", n3];
  }
  const t2 = hashIntlFormatParts(Ci(rr), n2), { era: o2, eraYear: r2 } = parseIntlYear(t2, rr);
  return [o2, r2];
}
function checkIsoDateTimeFields(e2) {
  return checkIsoDateFields(e2), constrainIsoTimeFields(e2, 1), e2;
}
function checkIsoDateFields(e2) {
  return constrainIsoDateFields(e2, 1), e2;
}
function isIsoDateFieldsValid(e2) {
  return allPropsEqual(Dr, e2, constrainIsoDateFields(e2));
}
function constrainIsoDateFields(e2, n2) {
  const { isoYear: t2 } = e2, o2 = clampProp(e2, "isoMonth", 1, computeIsoMonthsInYear(), n2);
  return {
    isoYear: t2,
    isoMonth: o2,
    isoDay: clampProp(e2, "isoDay", 1, computeIsoDaysInMonth(t2, o2), n2)
  };
}
function constrainIsoTimeFields(e2, n2) {
  return zipProps(w, [clampProp(e2, "isoHour", 0, 23, n2), clampProp(e2, "isoMinute", 0, 59, n2), clampProp(e2, "isoSecond", 0, 59, n2), clampProp(e2, "isoMillisecond", 0, 999, n2), clampProp(e2, "isoMicrosecond", 0, 999, n2), clampProp(e2, "isoNanosecond", 0, 999, n2)]);
}
function mt(e2) {
  return void 0 === e2 ? 0 : Xr(requireObjectLike(e2));
}
function je(e2, n2 = 0) {
  e2 = normalizeOptions(e2);
  const t2 = ei(e2), o2 = ni(e2, n2);
  return [Xr(e2), o2, t2];
}
function refineDiffOptions(e2, n2, t2, o2 = 9, r2 = 0, i2 = 4) {
  n2 = normalizeOptions(n2);
  let a2 = Kr(n2, o2, r2), s2 = parseRoundingIncInteger(n2), c2 = ii(n2, i2);
  const u2 = Jr(n2, o2, r2, 1);
  return null == a2 ? a2 = Math.max(t2, u2) : checkLargestSmallestUnit(a2, u2), s2 = refineRoundingInc(s2, u2, 1), e2 && (c2 = ((e3) => e3 < 4 ? (e3 + 2) % 4 : e3)(c2)), [a2, u2, s2, c2];
}
function refineRoundingOptions(e2, n2 = 6, t2) {
  let o2 = parseRoundingIncInteger(e2 = normalizeOptionsOrString(e2, Rr));
  const r2 = ii(e2, 7);
  let i2 = Jr(e2, n2);
  return i2 = requirePropDefined(Rr, i2), o2 = refineRoundingInc(o2, i2, void 0, t2), [i2, o2, r2];
}
function refineDateDisplayOptions(e2) {
  return ti(normalizeOptions(e2));
}
function refineTimeDisplayOptions(e2, n2) {
  return refineTimeDisplayTuple(normalizeOptions(e2), n2);
}
function Me(e2) {
  const n2 = normalizeOptionsOrString(e2, qr), t2 = refineChoiceOption(qr, _r, n2, 0);
  if (!t2) {
    throw new RangeError(invalidEntity(qr, t2));
  }
  return t2;
}
function refineTimeDisplayTuple(e2, n2 = 4) {
  const t2 = refineSubsecDigits(e2);
  return [ii(e2, 4), ...refineSmallestUnitAndSubsecDigits(Jr(e2, n2), t2)];
}
function refineSmallestUnitAndSubsecDigits(e2, n2) {
  return null != e2 ? [Ao[e2], e2 < 4 ? 9 - 3 * e2 : -1] : [void 0 === n2 ? 1 : 10 ** (9 - n2), n2];
}
function parseRoundingIncInteger(e2) {
  const n2 = e2[zr];
  return void 0 === n2 ? 1 : toInteger(n2, zr);
}
function refineRoundingInc(e2, n2, t2, o2) {
  const r2 = o2 ? Uo : Ao[n2 + 1];
  if (r2) {
    const t3 = Ao[n2];
    if (r2 % ((e2 = clampEntity(zr, e2, 1, r2 / t3 - (o2 ? 0 : 1), 1)) * t3)) {
      throw new RangeError(invalidEntity(zr, e2));
    }
  } else {
    e2 = clampEntity(zr, e2, 1, t2 ? 10 ** 9 : 1, 1);
  }
  return e2;
}
function refineSubsecDigits(e2) {
  let n2 = e2[Ur];
  if (void 0 !== n2) {
    if ("number" != typeof n2) {
      if ("auto" === toString(n2)) {
        return;
      }
      throw new RangeError(invalidEntity(Ur, n2));
    }
    n2 = clampEntity(Ur, Math.floor(n2), 0, 9, 1);
  }
  return n2;
}
function normalizeOptions(e2) {
  return void 0 === e2 ? {} : requireObjectLike(e2);
}
function normalizeOptionsOrString(e2, n2) {
  return "string" == typeof e2 ? {
    [n2]: e2
  } : requireObjectLike(e2);
}
function fabricateOverflowOptions(e2) {
  return {
    overflow: jr[e2]
  };
}
function refineUnitOption(e2, n2, t2 = 9, o2 = 0, r2) {
  let i2 = n2[e2];
  if (void 0 === i2) {
    return r2 ? o2 : void 0;
  }
  if (i2 = toString(i2), "auto" === i2) {
    return r2 ? o2 : null;
  }
  let a2 = Oo[i2];
  if (void 0 === a2 && (a2 = mr[i2]), void 0 === a2) {
    throw new RangeError(invalidChoice(e2, i2, Oo));
  }
  return clampEntity(e2, a2, o2, t2, 1, Bo), a2;
}
function refineChoiceOption(e2, n2, t2, o2 = 0) {
  const r2 = t2[e2];
  if (void 0 === r2) {
    return o2;
  }
  const i2 = toString(r2), a2 = n2[i2];
  if (void 0 === a2) {
    throw new RangeError(invalidChoice(e2, i2, n2));
  }
  return a2;
}
function checkLargestSmallestUnit(e2, n2) {
  if (n2 > e2) {
    throw new RangeError(Eo);
  }
}
function xe(e2) {
  return {
    branding: Re,
    epochNanoseconds: e2
  };
}
function _e(e2, n2, t2) {
  return {
    branding: z,
    calendar: t2,
    timeZone: n2,
    epochNanoseconds: e2
  };
}
function jt(e2, n2 = e2.calendar) {
  return {
    branding: x,
    calendar: n2,
    ...nn(Nr, e2)
  };
}
function W(e2, n2 = e2.calendar) {
  return {
    branding: G,
    calendar: n2,
    ...nn(Ir, e2)
  };
}
function createPlainYearMonthSlots(e2, n2 = e2.calendar) {
  return {
    branding: Ut,
    calendar: n2,
    ...nn(Ir, e2)
  };
}
function createPlainMonthDaySlots(e2, n2 = e2.calendar) {
  return {
    branding: qt,
    calendar: n2,
    ...nn(Ir, e2)
  };
}
function St(e2) {
  return {
    branding: ft,
    ...nn(Mr, e2)
  };
}
function Oe(e2) {
  return {
    branding: N,
    sign: computeDurationSign(e2),
    ...nn(ur, e2)
  };
}
function I(e2) {
  return divModBigNano(e2.epochNanoseconds, Qe)[0];
}
function v(e2) {
  return ((e3, n2 = 1) => {
    const [t2, o2] = e3, r2 = Math.floor(o2 / n2), i2 = Uo / n2;
    return BigInt(t2) * BigInt(i2) + BigInt(r2);
  })(e2.epochNanoseconds);
}
function extractEpochNano(e2) {
  return e2.epochNanoseconds;
}
function J(e2, n2, t2, o2, r2) {
  const i2 = getMaxDurationUnit(o2), [a2, s2] = ((e3, n3) => {
    const t3 = n3((e3 = normalizeOptionsOrString(e3, Zr))[Ar]);
    let o3 = Qr(e3);
    return o3 = requirePropDefined(Zr, o3), [o3, t3];
  })(r2, e2), c2 = Math.max(a2, i2);
  if (!s2 && isUniformUnit(c2, s2)) {
    return totalDayTimeDuration(o2, a2);
  }
  if (!s2) {
    throw new RangeError(yo);
  }
  if (!o2.sign) {
    return 0;
  }
  const [u2, f2, l2] = createMarkerSystem(n2, t2, s2), d2 = createMarkerToEpochNano(l2), m2 = createMoveMarker(l2), h2 = createDiffMarkers(l2), g2 = m2(f2, u2, o2);
  isZonedEpochSlots(s2) || (checkIsoDateTimeInBounds(u2), checkIsoDateTimeInBounds(g2));
  const D2 = h2(f2, u2, g2, a2);
  return isUniformUnit(a2, s2) ? totalDayTimeDuration(D2, a2) : ((e3, n3, t3, o3, r3, i3, a3) => {
    const s3 = computeDurationSign(e3), [c3, u3] = clampRelativeDuration(o3, gr(t3, e3), t3, s3, r3, i3, a3), f3 = computeEpochNanoFrac(n3, c3, u3);
    return e3[p[t3]] + f3 * s3;
  })(D2, d2(g2), a2, f2, u2, d2, m2);
}
function totalDayTimeDuration(e2, n2) {
  return bigNanoToNumber(durationFieldsToBigNano(e2), Ao[n2], 1);
}
function clampRelativeDuration(e2, n2, t2, o2, r2, i2, a2) {
  const s2 = p[t2], c2 = {
    ...n2,
    [s2]: n2[s2] + o2
  }, u2 = a2(e2, r2, n2), f2 = a2(e2, r2, c2);
  return [i2(u2), i2(f2)];
}
function computeEpochNanoFrac(e2, n2, t2) {
  const o2 = bigNanoToNumber(diffBigNanos(n2, t2));
  if (!o2) {
    throw new RangeError(fo);
  }
  return bigNanoToNumber(diffBigNanos(n2, e2)) / o2;
}
function Le(e2, n2) {
  const [t2, o2, r2] = refineRoundingOptions(n2, 5, 1);
  return xe(roundBigNano(e2.epochNanoseconds, t2, o2, r2, 1));
}
function Ie(e2, n2, t2) {
  let { epochNanoseconds: o2, timeZone: r2, calendar: i2 } = n2;
  const [a2, s2, c2] = refineRoundingOptions(t2);
  if (0 === a2 && 1 === s2) {
    return n2;
  }
  const u2 = e2(r2);
  if (6 === a2) {
    o2 = ((e3, n3, t3, o3) => {
      const r3 = he(t3, n3), [i3, a3] = e3(r3), s3 = t3.epochNanoseconds, c3 = getStartOfDayInstantFor(n3, i3), u3 = getStartOfDayInstantFor(n3, a3);
      if (bigNanoOutside(s3, c3, u3)) {
        throw new RangeError(fo);
      }
      return roundWithMode(computeEpochNanoFrac(s3, c3, u3), o3) ? u3 : c3;
    })(computeDayInterval, u2, n2, c2);
  } else {
    const e3 = u2.R(o2);
    o2 = getMatchingInstantFor(u2, roundDateTime(epochNanoToIso(o2, e3), a2, s2, c2), e3, 2, 0, 1);
  }
  return _e(o2, r2, i2);
}
function vt(e2, n2) {
  return jt(roundDateTime(e2, ...refineRoundingOptions(n2)), e2.calendar);
}
function lt(e2, n2) {
  const [t2, o2, r2] = refineRoundingOptions(n2, 5);
  var i2;
  return St((i2 = r2, roundTimeToNano(e2, computeNanoInc(t2, o2), i2)[0]));
}
function Te(e2, n2) {
  const t2 = e2(n2.timeZone), o2 = he(n2, t2), [r2, i2] = computeDayInterval(o2), a2 = bigNanoToNumber(diffBigNanos(getStartOfDayInstantFor(t2, r2), getStartOfDayInstantFor(t2, i2)), zo, 1);
  if (a2 <= 0) {
    throw new RangeError(fo);
  }
  return a2;
}
function ve(e2, n2) {
  const { timeZone: t2, calendar: o2 } = n2, r2 = ((e3, n3, t3) => getStartOfDayInstantFor(n3, e3(he(t3, n3))))(computeDayFloor, e2(t2), n2);
  return _e(r2, t2, o2);
}
function roundDateTime(e2, n2, t2, o2) {
  return roundDateTimeToNano(e2, computeNanoInc(n2, t2), o2);
}
function roundDateTimeToNano(e2, n2, t2) {
  const [o2, r2] = roundTimeToNano(e2, n2, t2);
  return checkIsoDateTimeInBounds({
    ...moveByDays(e2, r2),
    ...o2
  });
}
function roundTimeToNano(e2, n2, t2) {
  return nanoToIsoTimeAndDay(roundByInc(isoTimeFieldsToNano(e2), n2, t2));
}
function roundToMinute(e2) {
  return roundByInc(e2, Zo, 7);
}
function computeNanoInc(e2, n2) {
  return Ao[e2] * n2;
}
function computeDayInterval(e2) {
  const n2 = computeDayFloor(e2);
  return [n2, moveByDays(n2, 1)];
}
function computeDayFloor(e2) {
  return yr(6, e2);
}
function roundDayTimeDurationByInc(e2, n2, t2) {
  const o2 = Math.min(getMaxDurationUnit(e2), 6);
  return nanoToDurationDayTimeFields(roundBigNanoByInc(durationFieldsToBigNano(e2, o2), n2, t2), o2);
}
function roundRelativeDuration(e2, n2, t2, o2, r2, i2, a2, s2, c2, u2) {
  if (0 === o2 && 1 === r2) {
    return e2;
  }
  const f2 = isUniformUnit(o2, s2) ? isZonedEpochSlots(s2) && o2 < 6 && t2 >= 6 ? nudgeZonedTimeDuration : nudgeDayTimeDuration : nudgeRelativeDuration;
  let [l2, d2, m2] = f2(e2, n2, t2, o2, r2, i2, a2, s2, c2, u2);
  return m2 && 7 !== o2 && (l2 = ((e3, n3, t3, o3, r3, i3, a3, s3) => {
    const c3 = computeDurationSign(e3);
    for (let u3 = o3 + 1; u3 <= t3; u3++) {
      if (7 === u3 && 7 !== t3) {
        continue;
      }
      const o4 = gr(u3, e3);
      o4[p[u3]] += c3;
      const f3 = bigNanoToNumber(diffBigNanos(a3(s3(r3, i3, o4)), n3));
      if (f3 && Math.sign(f3) !== c3) {
        break;
      }
      e3 = o4;
    }
    return e3;
  })(l2, d2, t2, Math.max(6, o2), a2, s2, c2, u2)), l2;
}
function roundBigNano(e2, n2, t2, o2, r2) {
  if (6 === n2) {
    const n3 = ((e3) => e3[0] + e3[1] / Uo)(e2);
    return [roundByInc(n3, t2, o2), 0];
  }
  return roundBigNanoByInc(e2, computeNanoInc(n2, t2), o2, r2);
}
function roundBigNanoByInc(e2, n2, t2, o2) {
  let [r2, i2] = e2;
  o2 && i2 < 0 && (i2 += Uo, r2 -= 1);
  const [a2, s2] = divModFloor(roundByInc(i2, n2, t2), Uo);
  return createBigNano(r2 + a2, s2);
}
function roundByInc(e2, n2, t2) {
  return roundWithMode(e2 / n2, t2) * n2;
}
function roundWithMode(e2, n2) {
  return ai[n2](e2);
}
function nudgeDayTimeDuration(e2, n2, t2, o2, r2, i2) {
  const a2 = computeDurationSign(e2), s2 = durationFieldsToBigNano(e2), c2 = roundBigNano(s2, o2, r2, i2), u2 = diffBigNanos(s2, c2), f2 = Math.sign(c2[0] - s2[0]) === a2, l2 = nanoToDurationDayTimeFields(c2, Math.min(t2, 6));
  return [{
    ...e2,
    ...l2
  }, addBigNanos(n2, u2), f2];
}
function nudgeZonedTimeDuration(e2, n2, t2, o2, r2, i2, a2, s2, c2, u2) {
  const f2 = computeDurationSign(e2) || 1, l2 = bigNanoToNumber(durationFieldsToBigNano(e2, 5)), d2 = computeNanoInc(o2, r2);
  let m2 = roundByInc(l2, d2, i2);
  const [p2, h2] = clampRelativeDuration(a2, {
    ...e2,
    ...hr
  }, 6, f2, s2, c2, u2), g2 = m2 - bigNanoToNumber(diffBigNanos(p2, h2));
  let D2 = 0;
  g2 && Math.sign(g2) !== f2 ? n2 = moveBigNano(p2, m2) : (D2 += f2, m2 = roundByInc(g2, d2, i2), n2 = moveBigNano(h2, m2));
  const T2 = nanoToDurationTimeFields(m2);
  return [{
    ...e2,
    ...T2,
    days: e2.days + D2
  }, n2, Boolean(D2)];
}
function nudgeRelativeDuration(e2, n2, t2, o2, r2, i2, a2, s2, c2, u2) {
  const f2 = computeDurationSign(e2), l2 = p[o2], d2 = gr(o2, e2);
  7 === o2 && (e2 = {
    ...e2,
    weeks: e2.weeks + Math.trunc(e2.days / 7)
  });
  const m2 = divTrunc(e2[l2], r2) * r2;
  d2[l2] = m2;
  const [h2, g2] = clampRelativeDuration(a2, d2, o2, r2 * f2, s2, c2, u2), D2 = m2 + computeEpochNanoFrac(n2, h2, g2) * f2 * r2, T2 = roundByInc(D2, r2, i2), I2 = Math.sign(T2 - D2) === f2;
  return d2[l2] = T2, [d2, I2 ? g2 : h2, I2];
}
function ke(e2, n2, t2, o2) {
  const [r2, i2, a2, s2] = ((e3) => {
    const n3 = refineTimeDisplayTuple(e3 = normalizeOptions(e3));
    return [e3.timeZone, ...n3];
  })(o2), c2 = void 0 !== r2;
  return ((e3, n3, t3, o3, r3, i3) => {
    t3 = roundBigNanoByInc(t3, r3, o3, 1);
    const a3 = n3.R(t3);
    return formatIsoDateTimeFields(epochNanoToIso(t3, a3), i3) + (e3 ? Se(roundToMinute(a3)) : "Z");
  })(c2, n2(c2 ? e2(r2) : si), t2.epochNanoseconds, i2, a2, s2);
}
function Fe(e2, n2, t2) {
  const [o2, r2, i2, a2, s2, c2] = ((e3) => {
    e3 = normalizeOptions(e3);
    const n3 = ti(e3), t3 = refineSubsecDigits(e3), o3 = ri(e3), r3 = ii(e3, 4), i3 = Jr(e3, 4);
    return [n3, oi(e3), o3, r3, ...refineSmallestUnitAndSubsecDigits(i3, t3)];
  })(t2);
  return ((e3, n3, t3, o3, r3, i3, a3, s3, c3, u2) => {
    o3 = roundBigNanoByInc(o3, c3, s3, 1);
    const f2 = e3(t3).R(o3);
    return formatIsoDateTimeFields(epochNanoToIso(o3, f2), u2) + Se(roundToMinute(f2), a3) + ((e4, n4) => 1 !== n4 ? "[" + (2 === n4 ? "!" : "") + e4 + "]" : "")(t3, i3) + formatCalendar(n3, r3);
  })(e2, n2.calendar, n2.timeZone, n2.epochNanoseconds, o2, r2, i2, a2, s2, c2);
}
function Ft(e2, n2) {
  const [t2, o2, r2, i2] = ((e3) => (e3 = normalizeOptions(e3), [ti(e3), ...refineTimeDisplayTuple(e3)]))(n2);
  return a2 = e2.calendar, s2 = t2, c2 = i2, formatIsoDateTimeFields(roundDateTimeToNano(e2, r2, o2), c2) + formatCalendar(a2, s2);
  var a2, s2, c2;
}
function ce(e2, n2) {
  return t2 = e2.calendar, o2 = e2, r2 = refineDateDisplayOptions(n2), formatIsoDateFields(o2) + formatCalendar(t2, r2);
  var t2, o2, r2;
}
function Kt(e2, n2) {
  return formatDateLikeIso(e2.calendar, formatIsoYearMonthFields, e2, refineDateDisplayOptions(n2));
}
function Jt(e2, n2) {
  return formatDateLikeIso(e2.calendar, formatIsoMonthDayFields, e2, refineDateDisplayOptions(n2));
}
function ct(e2, n2) {
  const [t2, o2, r2] = refineTimeDisplayOptions(n2);
  return i2 = r2, formatIsoTimeFields(roundTimeToNano(e2, o2, t2)[0], i2);
  var i2;
}
function k(e2, n2) {
  const [t2, o2, r2] = refineTimeDisplayOptions(n2, 3);
  return o2 > 1 && checkDurationUnits(e2 = {
    ...e2,
    ...roundDayTimeDurationByInc(e2, o2, t2)
  }), ((e3, n3) => {
    const { sign: t3 } = e3, o3 = -1 === t3 ? negateDurationFields(e3) : e3, { hours: r3, minutes: i2 } = o3, [a2, s2] = divModBigNano(durationFieldsToBigNano(o3, 3), Ro, divModTrunc);
    checkDurationTimeUnit(a2);
    const c2 = formatSubsecNano(s2, n3), u2 = n3 >= 0 || !t3 || c2;
    return (t3 < 0 ? "-" : "") + "P" + formatDurationFragments({
      Y: formatDurationNumber(o3.years),
      M: formatDurationNumber(o3.months),
      W: formatDurationNumber(o3.weeks),
      D: formatDurationNumber(o3.days)
    }) + (r3 || i2 || a2 || u2 ? "T" + formatDurationFragments({
      H: formatDurationNumber(r3),
      M: formatDurationNumber(i2),
      S: formatDurationNumber(a2, u2) + c2
    }) : "");
  })(e2, r2);
}
function formatDateLikeIso(e2, n2, t2, o2) {
  const r2 = o2 > 1 || 0 === o2 && e2 !== l;
  return 1 === o2 ? e2 === l ? n2(t2) : formatIsoDateFields(t2) : r2 ? formatIsoDateFields(t2) + formatCalendarId(e2, 2 === o2) : n2(t2);
}
function formatDurationFragments(e2) {
  const n2 = [];
  for (const t2 in e2) {
    const o2 = e2[t2];
    o2 && n2.push(o2, t2);
  }
  return n2.join("");
}
function formatIsoDateTimeFields(e2, n2) {
  return formatIsoDateFields(e2) + "T" + formatIsoTimeFields(e2, n2);
}
function formatIsoDateFields(e2) {
  return formatIsoYearMonthFields(e2) + "-" + bo(e2.isoDay);
}
function formatIsoYearMonthFields(e2) {
  const { isoYear: n2 } = e2;
  return (n2 < 0 || n2 > 9999 ? getSignStr(n2) + padNumber(6, Math.abs(n2)) : padNumber(4, n2)) + "-" + bo(e2.isoMonth);
}
function formatIsoMonthDayFields(e2) {
  return bo(e2.isoMonth) + "-" + bo(e2.isoDay);
}
function formatIsoTimeFields(e2, n2) {
  const t2 = [bo(e2.isoHour), bo(e2.isoMinute)];
  return -1 !== n2 && t2.push(bo(e2.isoSecond) + ((e3, n3, t3, o2) => formatSubsecNano(e3 * Qe + n3 * Yo + t3, o2))(e2.isoMillisecond, e2.isoMicrosecond, e2.isoNanosecond, n2)), t2.join(":");
}
function Se(e2, n2 = 0) {
  if (1 === n2) {
    return "";
  }
  const [t2, o2] = divModFloor(Math.abs(e2), zo), [r2, i2] = divModFloor(o2, Zo), [a2, s2] = divModFloor(i2, Ro);
  return getSignStr(e2) + bo(t2) + ":" + bo(r2) + (a2 || s2 ? ":" + bo(a2) + formatSubsecNano(s2) : "");
}
function formatCalendar(e2, n2) {
  return 1 !== n2 && (n2 > 1 || 0 === n2 && e2 !== l) ? formatCalendarId(e2, 2 === n2) : "";
}
function formatCalendarId(e2, n2) {
  return "[" + (n2 ? "!" : "") + "u-ca=" + e2 + "]";
}
function formatSubsecNano(e2, n2) {
  let t2 = padNumber(9, e2);
  return t2 = void 0 === n2 ? t2.replace(li, "") : t2.slice(0, n2), t2 ? "." + t2 : "";
}
function getSignStr(e2) {
  return e2 < 0 ? "-" : "+";
}
function formatDurationNumber(e2, n2) {
  return e2 || n2 ? e2.toLocaleString("fullwide", {
    useGrouping: 0
  }) : "";
}
function _zonedEpochSlotsToIso(e2, n2) {
  const { epochNanoseconds: t2 } = e2, o2 = (n2.R ? n2 : n2(e2.timeZone)).R(t2), r2 = epochNanoToIso(t2, o2);
  return {
    calendar: e2.calendar,
    ...r2,
    offsetNanoseconds: o2
  };
}
function getMatchingInstantFor(e2, n2, t2, o2 = 0, r2 = 0, i2, a2) {
  if (void 0 !== t2 && 1 === o2 && (1 === o2 || a2)) {
    return isoToEpochNanoWithOffset(n2, t2);
  }
  const s2 = e2.I(n2);
  if (void 0 !== t2 && 3 !== o2) {
    const e3 = ((e4, n3, t3, o3) => {
      const r3 = isoToEpochNano(n3);
      o3 && (t3 = roundToMinute(t3));
      for (const n4 of e4) {
        let e5 = bigNanoToNumber(diffBigNanos(n4, r3));
        if (o3 && (e5 = roundToMinute(e5)), e5 === t3) {
          return n4;
        }
      }
    })(s2, n2, t2, i2);
    if (void 0 !== e3) {
      return e3;
    }
    if (0 === o2) {
      throw new RangeError(Do);
    }
  }
  return a2 ? isoToEpochNano(n2) : getSingleInstantFor(e2, n2, r2, s2);
}
function getSingleInstantFor(e2, n2, t2 = 0, o2 = e2.I(n2)) {
  if (1 === o2.length) {
    return o2[0];
  }
  if (1 === t2) {
    throw new RangeError(To);
  }
  if (o2.length) {
    return o2[3 === t2 ? 1 : 0];
  }
  const r2 = isoToEpochNano(n2), i2 = ((e3, n3) => {
    const t3 = e3.R(moveBigNano(n3, -Uo));
    return ((e4) => {
      if (e4 > Uo) {
        throw new RangeError(go);
      }
      return e4;
    })(e3.R(moveBigNano(n3, Uo)) - t3);
  })(e2, r2), a2 = i2 * (2 === t2 ? -1 : 1);
  return (o2 = e2.I(epochNanoToIso(r2, a2)))[2 === t2 ? 0 : o2.length - 1];
}
function getStartOfDayInstantFor(e2, n2) {
  const t2 = e2.I(n2);
  if (t2.length) {
    return t2[0];
  }
  const o2 = moveBigNano(isoToEpochNano(n2), -Uo);
  return e2.O(o2, 1);
}
function Ye(e2, n2, t2) {
  return xe(checkEpochNanoInBounds(addBigNanos(n2.epochNanoseconds, ((e3) => {
    if (durationHasDateParts(e3)) {
      throw new RangeError(vo);
    }
    return durationFieldsToBigNano(e3, 5);
  })(e2 ? negateDurationFields(t2) : t2))));
}
function pe(e2, n2, t2, o2, r2, i2 = /* @__PURE__ */ Object.create(null)) {
  const a2 = n2(o2.timeZone), s2 = e2(o2.calendar);
  return {
    ...o2,
    ...moveZonedEpochs(a2, s2, o2, t2 ? negateDurationFields(r2) : r2, i2)
  };
}
function wt(e2, n2, t2, o2, r2 = /* @__PURE__ */ Object.create(null)) {
  const { calendar: i2 } = t2;
  return jt(moveDateTime(e2(i2), t2, n2 ? negateDurationFields(o2) : o2, r2), i2);
}
function ne(e2, n2, t2, o2, r2) {
  const { calendar: i2 } = t2;
  return W(moveDate(e2(i2), t2, n2 ? negateDurationFields(o2) : o2, r2), i2);
}
function Gt(e2, n2, t2, o2, r2) {
  const i2 = t2.calendar, a2 = e2(i2);
  let s2 = checkIsoDateInBounds(moveToDayOfMonthUnsafe(a2, t2));
  n2 && (o2 = B(o2)), o2.sign < 0 && (s2 = a2.P(s2, {
    ...pr,
    months: 1
  }), s2 = moveByDays(s2, -1));
  const c2 = a2.P(s2, o2, r2);
  return createPlainYearMonthSlots(moveToDayOfMonthUnsafe(a2, c2), i2);
}
function at(e2, n2, t2) {
  return St(moveTime(n2, e2 ? negateDurationFields(t2) : t2)[0]);
}
function moveZonedEpochs(e2, n2, t2, o2, r2) {
  const i2 = durationFieldsToBigNano(o2, 5);
  let a2 = t2.epochNanoseconds;
  if (durationHasDateParts(o2)) {
    const s2 = he(t2, e2);
    a2 = addBigNanos(getSingleInstantFor(e2, {
      ...moveDate(n2, s2, {
        ...o2,
        ...hr
      }, r2),
      ...nn(w, s2)
    }), i2);
  } else {
    a2 = addBigNanos(a2, i2), mt(r2);
  }
  return {
    epochNanoseconds: checkEpochNanoInBounds(a2)
  };
}
function moveDateTime(e2, n2, t2, o2) {
  const [r2, i2] = moveTime(n2, t2);
  return checkIsoDateTimeInBounds({
    ...moveDate(e2, n2, {
      ...t2,
      ...hr,
      days: t2.days + i2
    }, o2),
    ...r2
  });
}
function moveDate(e2, n2, t2, o2) {
  if (t2.years || t2.months || t2.weeks) {
    return e2.P(n2, t2, o2);
  }
  mt(o2);
  const r2 = t2.days + durationFieldsToBigNano(t2, 5)[0];
  return r2 ? checkIsoDateInBounds(moveByDays(n2, r2)) : n2;
}
function moveToDayOfMonthUnsafe(e2, n2, t2 = 1) {
  return moveByDays(n2, t2 - e2.day(n2));
}
function moveTime(e2, n2) {
  const [t2, o2] = durationFieldsToBigNano(n2, 5), [r2, i2] = nanoToIsoTimeAndDay(isoTimeFieldsToNano(e2) + o2);
  return [r2, t2 + i2];
}
function moveByDays(e2, n2) {
  return n2 ? {
    ...e2,
    ...epochMilliToIso(isoToEpochMilli(e2) + n2 * ko)
  } : e2;
}
function createMarkerSystem(e2, n2, t2) {
  const o2 = e2(t2.calendar);
  return isZonedEpochSlots(t2) ? [t2, o2, n2(t2.timeZone)] : [{
    ...t2,
    ...Nt
  }, o2];
}
function createMarkerToEpochNano(e2) {
  return e2 ? extractEpochNano : isoToEpochNano;
}
function createMoveMarker(e2) {
  return e2 ? Pt(moveZonedEpochs, e2) : moveDateTime;
}
function createDiffMarkers(e2) {
  return e2 ? Pt(diffZonedEpochsExact, e2) : diffDateTimesExact;
}
function isZonedEpochSlots(e2) {
  return e2 && e2.epochNanoseconds;
}
function isUniformUnit(e2, n2) {
  return e2 <= 6 - (isZonedEpochSlots(n2) ? 1 : 0);
}
function E(e2, n2, t2, o2, r2, i2, a2) {
  const s2 = e2(normalizeOptions(a2).relativeTo), c2 = Math.max(getMaxDurationUnit(r2), getMaxDurationUnit(i2));
  if (isUniformUnit(c2, s2)) {
    return Oe(checkDurationUnits(((e3, n3, t3, o3) => {
      const r3 = addBigNanos(durationFieldsToBigNano(e3), durationFieldsToBigNano(n3), o3 ? -1 : 1);
      if (!Number.isFinite(r3[0])) {
        throw new RangeError(Io);
      }
      return {
        ...pr,
        ...nanoToDurationDayTimeFields(r3, t3)
      };
    })(r2, i2, c2, o2)));
  }
  if (!s2) {
    throw new RangeError(yo);
  }
  o2 && (i2 = negateDurationFields(i2));
  const [u2, f2, l2] = createMarkerSystem(n2, t2, s2), d2 = createMoveMarker(l2), m2 = createDiffMarkers(l2), p2 = d2(f2, u2, r2);
  return Oe(m2(f2, u2, d2(f2, p2, i2), c2));
}
function V(e2, n2, t2, o2, r2) {
  const i2 = getMaxDurationUnit(o2), [a2, s2, c2, u2, f2] = ((e3, n3, t3) => {
    e3 = normalizeOptionsOrString(e3, Rr);
    let o3 = Kr(e3);
    const r3 = t3(e3[Ar]);
    let i3 = parseRoundingIncInteger(e3);
    const a3 = ii(e3, 7);
    let s3 = Jr(e3);
    if (void 0 === o3 && void 0 === s3) {
      throw new RangeError(Po);
    }
    if (null == s3 && (s3 = 0), null == o3 && (o3 = Math.max(s3, n3)), checkLargestSmallestUnit(o3, s3), i3 = refineRoundingInc(i3, s3, 1), i3 > 1 && s3 > 5 && o3 !== s3) {
      throw new RangeError("For calendar units with roundingIncrement > 1, use largestUnit = smallestUnit");
    }
    return [o3, s3, i3, a3, r3];
  })(r2, i2, e2), l2 = Math.max(i2, a2);
  if (!f2 && l2 <= 6) {
    return Oe(checkDurationUnits(((e3, n3, t3, o3, r3) => {
      const i3 = roundBigNano(durationFieldsToBigNano(e3), t3, o3, r3);
      return {
        ...pr,
        ...nanoToDurationDayTimeFields(i3, n3)
      };
    })(o2, a2, s2, c2, u2)));
  }
  if (!isZonedEpochSlots(f2) && !o2.sign) {
    return o2;
  }
  if (!f2) {
    throw new RangeError(yo);
  }
  const [d2, m2, p2] = createMarkerSystem(n2, t2, f2), h2 = createMarkerToEpochNano(p2), g2 = createMoveMarker(p2), D2 = createDiffMarkers(p2), T2 = g2(m2, d2, o2);
  isZonedEpochSlots(f2) || (checkIsoDateTimeInBounds(d2), checkIsoDateTimeInBounds(T2));
  let I2 = D2(m2, d2, T2, a2);
  const M2 = o2.sign, N2 = computeDurationSign(I2);
  if (M2 && N2 && M2 !== N2) {
    throw new RangeError(fo);
  }
  return I2 = roundRelativeDuration(I2, h2(T2), a2, s2, c2, u2, m2, d2, h2, g2), Oe(I2);
}
function Y(e2) {
  return -1 === e2.sign ? B(e2) : e2;
}
function B(e2) {
  return Oe(negateDurationFields(e2));
}
function negateDurationFields(e2) {
  const n2 = {};
  for (const t2 of p) {
    n2[t2] = -1 * e2[t2] || 0;
  }
  return n2;
}
function y(e2) {
  return !e2.sign;
}
function computeDurationSign(e2, n2 = p) {
  let t2 = 0;
  for (const o2 of n2) {
    const n3 = Math.sign(e2[o2]);
    if (n3) {
      if (t2 && t2 !== n3) {
        throw new RangeError(No);
      }
      t2 = n3;
    }
  }
  return t2;
}
function checkDurationUnits(e2) {
  for (const n2 of dr) {
    clampEntity(n2, e2[n2], -di, di, 1);
  }
  return checkDurationTimeUnit(bigNanoToNumber(durationFieldsToBigNano(e2), Ro)), e2;
}
function checkDurationTimeUnit(e2) {
  if (!Number.isSafeInteger(e2)) {
    throw new RangeError(Mo);
  }
}
function durationFieldsToBigNano(e2, n2 = 6) {
  return givenFieldsToBigNano(e2, n2, p);
}
function nanoToDurationDayTimeFields(e2, n2 = 6) {
  const [t2, o2] = e2, r2 = nanoToGivenFields(o2, n2, p);
  if (r2[p[n2]] += t2 * (Uo / Ao[n2]), !Number.isFinite(r2[p[n2]])) {
    throw new RangeError(Io);
  }
  return r2;
}
function nanoToDurationTimeFields(e2, n2 = 5) {
  return nanoToGivenFields(e2, n2, p);
}
function durationHasDateParts(e2) {
  return Boolean(computeDurationSign(e2, lr));
}
function getMaxDurationUnit(e2) {
  let n2 = 9;
  for (; n2 > 0 && !e2[p[n2]]; n2--) {
  }
  return n2;
}
function createSplitTuple(e2, n2) {
  return [e2, n2];
}
function computePeriod(e2) {
  const n2 = Math.floor(e2 / ci) * ci;
  return [n2, n2 + ci];
}
function We(e2) {
  const n2 = parseDateTimeLike(e2 = toStringViaPrimitive(e2));
  if (!n2) {
    throw new RangeError(failedParse(e2));
  }
  let t2;
  if (n2.j) {
    t2 = 0;
  } else {
    if (!n2.offset) {
      throw new RangeError(failedParse(e2));
    }
    t2 = parseOffsetNano(n2.offset);
  }
  return n2.timeZone && parseOffsetNanoMaybe(n2.timeZone, 1), xe(isoToEpochNanoWithOffset(checkIsoDateTimeFields(n2), t2));
}
function H(e2) {
  const n2 = parseDateTimeLike(m(e2));
  if (!n2) {
    throw new RangeError(failedParse(e2));
  }
  if (n2.timeZone) {
    return finalizeZonedDateTime(n2, n2.offset ? parseOffsetNano(n2.offset) : void 0);
  }
  if (n2.j) {
    throw new RangeError(failedParse(e2));
  }
  return finalizeDate(n2);
}
function Ae(e2, n2) {
  const t2 = parseDateTimeLike(m(e2));
  if (!t2 || !t2.timeZone) {
    throw new RangeError(failedParse(e2));
  }
  const { offset: o2 } = t2, r2 = o2 ? parseOffsetNano(o2) : void 0, [, i2, a2] = je(n2);
  return finalizeZonedDateTime(t2, r2, i2, a2);
}
function parseOffsetNano(e2) {
  const n2 = parseOffsetNanoMaybe(e2);
  if (void 0 === n2) {
    throw new RangeError(failedParse(e2));
  }
  return n2;
}
function Bt(e2) {
  const n2 = parseDateTimeLike(m(e2));
  if (!n2 || n2.j) {
    throw new RangeError(failedParse(e2));
  }
  return jt(finalizeDateTime(n2));
}
function de(e2, n2, t2) {
  let o2 = parseDateTimeLike(m(e2));
  if (!o2 || o2.j) {
    throw new RangeError(failedParse(e2));
  }
  return n2 ? o2.calendar === l && (o2 = -271821 === o2.isoYear && 4 === o2.isoMonth ? {
    ...o2,
    isoDay: 20,
    ...Nt
  } : {
    ...o2,
    isoDay: 1,
    ...Nt
  }) : t2 && o2.calendar === l && (o2 = {
    ...o2,
    isoYear: Br
  }), W(o2.C ? finalizeDateTime(o2) : finalizeDate(o2));
}
function _t(e2, n2) {
  const t2 = parseYearMonthOnly(m(n2));
  if (t2) {
    return requireIsoCalendar(t2), createPlainYearMonthSlots(checkIsoYearMonthInBounds(checkIsoDateFields(t2)));
  }
  const o2 = de(n2, 1);
  return createPlainYearMonthSlots(moveToDayOfMonthUnsafe(e2(o2.calendar), o2));
}
function requireIsoCalendar(e2) {
  if (e2.calendar !== l) {
    throw new RangeError(invalidSubstring(e2.calendar));
  }
}
function xt(e2, n2) {
  const t2 = parseMonthDayOnly(m(n2));
  if (t2) {
    return requireIsoCalendar(t2), createPlainMonthDaySlots(checkIsoDateFields(t2));
  }
  const o2 = de(n2, 0, 1), { calendar: r2 } = o2, i2 = e2(r2), [a2, s2, c2] = i2.v(o2), [u2, f2] = i2.q(a2, s2), [l2, d2] = i2.G(u2, f2, c2);
  return createPlainMonthDaySlots(checkIsoDateInBounds(i2.V(l2, d2, c2)), r2);
}
function ht(e2) {
  let n2, t2 = ((e3) => {
    const n3 = Pi.exec(e3);
    return n3 ? (organizeAnnotationParts(n3[10]), organizeTimeParts(n3)) : void 0;
  })(m(e2));
  if (!t2) {
    if (t2 = parseDateTimeLike(e2), !t2) {
      throw new RangeError(failedParse(e2));
    }
    if (!t2.C) {
      throw new RangeError(failedParse(e2));
    }
    if (t2.j) {
      throw new RangeError(invalidSubstring("Z"));
    }
    requireIsoCalendar(t2);
  }
  if ((n2 = parseYearMonthOnly(e2)) && isIsoDateFieldsValid(n2)) {
    throw new RangeError(failedParse(e2));
  }
  if ((n2 = parseMonthDayOnly(e2)) && isIsoDateFieldsValid(n2)) {
    throw new RangeError(failedParse(e2));
  }
  return St(constrainIsoTimeFields(t2, 1));
}
function R(e2) {
  const n2 = ((e3) => {
    const n3 = Fi.exec(e3);
    return n3 ? ((e4) => {
      function parseUnit(e5, r3, i2) {
        let a2 = 0, s2 = 0;
        if (i2 && ([a2, o2] = divModFloor(o2, Ao[i2])), void 0 !== e5) {
          if (t2) {
            throw new RangeError(invalidSubstring(e5));
          }
          s2 = ((e6) => {
            const n5 = parseInt(e6);
            if (!Number.isFinite(n5)) {
              throw new RangeError(invalidSubstring(e6));
            }
            return n5;
          })(e5), n4 = 1, r3 && (o2 = parseSubsecNano(r3) * (Ao[i2] / Ro), t2 = 1);
        }
        return a2 + s2;
      }
      let n4 = 0, t2 = 0, o2 = 0, r2 = {
        ...zipProps(p, [parseUnit(e4[2]), parseUnit(e4[3]), parseUnit(e4[4]), parseUnit(e4[5]), parseUnit(e4[6], e4[7], 5), parseUnit(e4[8], e4[9], 4), parseUnit(e4[10], e4[11], 3)]),
        ...nanoToGivenFields(o2, 2, p)
      };
      if (!n4) {
        throw new RangeError(noValidFields(p));
      }
      return parseSign(e4[1]) < 0 && (r2 = negateDurationFields(r2)), r2;
    })(n3) : void 0;
  })(m(e2));
  if (!n2) {
    throw new RangeError(failedParse(e2));
  }
  return Oe(checkDurationUnits(n2));
}
function f(e2) {
  const n2 = parseDateTimeLike(e2) || parseYearMonthOnly(e2) || parseMonthDayOnly(e2);
  return n2 ? n2.calendar : e2;
}
function Z(e2) {
  const n2 = parseDateTimeLike(e2);
  return n2 && (n2.timeZone || n2.j && si || n2.offset) || e2;
}
function finalizeZonedDateTime(e2, n2, t2 = 0, o2 = 0) {
  const r2 = M(e2.timeZone), i2 = L(r2);
  let a2;
  return checkIsoDateTimeFields(e2), a2 = e2.C ? getMatchingInstantFor(i2, e2, n2, t2, o2, !i2.$, e2.j) : getStartOfDayInstantFor(i2, e2), _e(a2, r2, u(e2.calendar));
}
function finalizeDateTime(e2) {
  return resolveSlotsCalendar(checkIsoDateTimeInBounds(checkIsoDateTimeFields(e2)));
}
function finalizeDate(e2) {
  return resolveSlotsCalendar(checkIsoDateInBounds(checkIsoDateFields(e2)));
}
function resolveSlotsCalendar(e2) {
  return {
    ...e2,
    calendar: u(e2.calendar)
  };
}
function parseDateTimeLike(e2) {
  const n2 = vi.exec(e2);
  return n2 ? ((e3) => {
    const n3 = e3[10], t2 = "Z" === (n3 || "").toUpperCase();
    return {
      isoYear: organizeIsoYearParts(e3),
      isoMonth: parseInt(e3[4]),
      isoDay: parseInt(e3[5]),
      ...organizeTimeParts(e3.slice(5)),
      ...organizeAnnotationParts(e3[16]),
      C: Boolean(e3[6]),
      j: t2,
      offset: t2 ? void 0 : n3
    };
  })(n2) : void 0;
}
function parseYearMonthOnly(e2) {
  const n2 = Ni.exec(e2);
  return n2 ? ((e3) => ({
    isoYear: organizeIsoYearParts(e3),
    isoMonth: parseInt(e3[4]),
    isoDay: 1,
    ...organizeAnnotationParts(e3[5])
  }))(n2) : void 0;
}
function parseMonthDayOnly(e2) {
  const n2 = yi.exec(e2);
  return n2 ? ((e3) => ({
    isoYear: Br,
    isoMonth: parseInt(e3[1]),
    isoDay: parseInt(e3[2]),
    ...organizeAnnotationParts(e3[3])
  }))(n2) : void 0;
}
function parseOffsetNanoMaybe(e2, n2) {
  const t2 = Ei.exec(e2);
  return t2 ? ((e3, n3) => {
    const t3 = e3[4] || e3[5];
    if (n3 && t3) {
      throw new RangeError(invalidSubstring(t3));
    }
    return ((e4) => {
      if (Math.abs(e4) >= Uo) {
        throw new RangeError(ho);
      }
      return e4;
    })((parseInt0(e3[2]) * zo + parseInt0(e3[3]) * Zo + parseInt0(e3[4]) * Ro + parseSubsecNano(e3[5] || "")) * parseSign(e3[1]));
  })(t2, n2) : void 0;
}
function organizeIsoYearParts(e2) {
  const n2 = parseSign(e2[1]), t2 = parseInt(e2[2] || e2[3]);
  if (n2 < 0 && !t2) {
    throw new RangeError(invalidSubstring(-0));
  }
  return n2 * t2;
}
function organizeTimeParts(e2) {
  const n2 = parseInt0(e2[3]);
  return {
    ...nanoToIsoTimeAndDay(parseSubsecNano(e2[4] || ""))[0],
    isoHour: parseInt0(e2[1]),
    isoMinute: parseInt0(e2[2]),
    isoSecond: 60 === n2 ? 59 : n2
  };
}
function organizeAnnotationParts(e2) {
  let n2, t2;
  const o2 = [];
  if (e2.replace(Si, ((e3, r2, i2) => {
    const a2 = Boolean(r2), [s2, c2] = i2.split("=").reverse();
    if (c2) {
      if ("u-ca" === c2) {
        o2.push(s2), n2 || (n2 = a2);
      } else if (a2 || /[A-Z]/.test(c2)) {
        throw new RangeError(invalidSubstring(e3));
      }
    } else {
      if (t2) {
        throw new RangeError(invalidSubstring(e3));
      }
      t2 = s2;
    }
    return "";
  })), o2.length > 1 && n2) {
    throw new RangeError(invalidSubstring(e2));
  }
  return {
    timeZone: t2,
    calendar: o2[0] || l
  };
}
function parseSubsecNano(e2) {
  return parseInt(e2.padEnd(9, "0"));
}
function createRegExp(e2) {
  return new RegExp(`^${e2}$`, "i");
}
function parseSign(e2) {
  return e2 && "+" !== e2 ? -1 : 1;
}
function parseInt0(e2) {
  return void 0 === e2 ? 0 : parseInt(e2);
}
function Ze(e2) {
  return M(m(e2));
}
function M(e2) {
  const n2 = getTimeZoneEssence(e2);
  return "number" == typeof n2 ? Se(n2) : n2 ? ((e3) => {
    if (Oi.test(e3)) {
      throw new RangeError(F(e3));
    }
    if (bi.test(e3)) {
      throw new RangeError(po);
    }
    return e3.toLowerCase().split("/").map(((e4, n3) => (e4.length <= 3 || /\d/.test(e4)) && !/etc|yap/.test(e4) ? e4.toUpperCase() : e4.replace(/baja|dumont|[a-z]+/g, ((e5, t2) => e5.length <= 2 && !n3 || "in" === e5 || "chat" === e5 ? e5.toUpperCase() : e5.length > 2 || !t2 ? capitalize2(e5).replace(/island|noronha|murdo|rivadavia|urville/, capitalize2) : e5)))).join("/");
  })(e2) : si;
}
function getTimeZoneAtomic(e2) {
  const n2 = getTimeZoneEssence(e2);
  return "number" == typeof n2 ? n2 : n2 ? n2.resolvedOptions().timeZone : si;
}
function getTimeZoneEssence(e2) {
  const n2 = parseOffsetNanoMaybe(e2 = e2.toUpperCase(), 1);
  return void 0 !== n2 ? n2 : e2 !== si ? wi(e2) : void 0;
}
function Ke(e2, n2) {
  return compareBigNanos(e2.epochNanoseconds, n2.epochNanoseconds);
}
function Be(e2, n2) {
  return compareBigNanos(e2.epochNanoseconds, n2.epochNanoseconds);
}
function K(e2, n2, t2, o2, r2, i2) {
  const a2 = e2(normalizeOptions(i2).relativeTo), s2 = Math.max(getMaxDurationUnit(o2), getMaxDurationUnit(r2));
  if (allPropsEqual(p, o2, r2)) {
    return 0;
  }
  if (isUniformUnit(s2, a2)) {
    return compareBigNanos(durationFieldsToBigNano(o2), durationFieldsToBigNano(r2));
  }
  if (!a2) {
    throw new RangeError(yo);
  }
  const [c2, u2, f2] = createMarkerSystem(n2, t2, a2), l2 = createMarkerToEpochNano(f2), d2 = createMoveMarker(f2);
  return compareBigNanos(l2(d2(u2, c2, o2)), l2(d2(u2, c2, r2)));
}
function Yt(e2, n2) {
  return te(e2, n2) || Dt(e2, n2);
}
function te(e2, n2) {
  return compareNumbers(isoToEpochMilli(e2), isoToEpochMilli(n2));
}
function Dt(e2, n2) {
  return compareNumbers(isoTimeFieldsToNano(e2), isoTimeFieldsToNano(n2));
}
function Ve(e2, n2) {
  return !Ke(e2, n2);
}
function Ce(e2, n2) {
  return !Be(e2, n2) && !!isTimeZoneIdsEqual(e2.timeZone, n2.timeZone) && e2.calendar === n2.calendar;
}
function Ct(e2, n2) {
  return !Yt(e2, n2) && e2.calendar === n2.calendar;
}
function re(e2, n2) {
  return !te(e2, n2) && e2.calendar === n2.calendar;
}
function $t(e2, n2) {
  return !te(e2, n2) && e2.calendar === n2.calendar;
}
function Lt(e2, n2) {
  return !te(e2, n2) && e2.calendar === n2.calendar;
}
function st(e2, n2) {
  return !Dt(e2, n2);
}
function isTimeZoneIdsEqual(e2, n2) {
  if (e2 === n2) {
    return 1;
  }
  try {
    return getTimeZoneAtomic(e2) === getTimeZoneAtomic(n2);
  } catch (e3) {
  }
}
function Ee(e2, n2, t2, o2) {
  const r2 = refineDiffOptions(e2, o2, 3, 5), i2 = diffEpochNanos(n2.epochNanoseconds, t2.epochNanoseconds, ...r2);
  return Oe(e2 ? negateDurationFields(i2) : i2);
}
function we(e2, n2, t2, o2, r2, i2) {
  const a2 = getCommonCalendarId(o2.calendar, r2.calendar), [s2, c2, u2, f2] = refineDiffOptions(t2, i2, 5), l2 = o2.epochNanoseconds, d2 = r2.epochNanoseconds, m2 = compareBigNanos(d2, l2);
  let p2;
  if (m2) {
    if (s2 < 6) {
      p2 = diffEpochNanos(l2, d2, s2, c2, u2, f2);
    } else {
      const t3 = n2(((e3, n3) => {
        if (!isTimeZoneIdsEqual(e3, n3)) {
          throw new RangeError(mo);
        }
        return e3;
      })(o2.timeZone, r2.timeZone)), l3 = e2(a2);
      p2 = diffZonedEpochsBig(l3, t3, o2, r2, m2, s2, i2), p2 = roundRelativeDuration(p2, d2, s2, c2, u2, f2, l3, o2, extractEpochNano, Pt(moveZonedEpochs, t3));
    }
  } else {
    p2 = pr;
  }
  return Oe(t2 ? negateDurationFields(p2) : p2);
}
function It(e2, n2, t2, o2, r2) {
  const i2 = getCommonCalendarId(t2.calendar, o2.calendar), [a2, s2, c2, u2] = refineDiffOptions(n2, r2, 6), f2 = isoToEpochNano(t2), l2 = isoToEpochNano(o2), d2 = compareBigNanos(l2, f2);
  let m2;
  if (d2) {
    if (a2 <= 6) {
      m2 = diffEpochNanos(f2, l2, a2, s2, c2, u2);
    } else {
      const n3 = e2(i2);
      m2 = diffDateTimesBig(n3, t2, o2, d2, a2, r2), m2 = roundRelativeDuration(m2, l2, a2, s2, c2, u2, n3, t2, isoToEpochNano, moveDateTime);
    }
  } else {
    m2 = pr;
  }
  return Oe(n2 ? negateDurationFields(m2) : m2);
}
function oe(e2, n2, t2, o2, r2) {
  const i2 = getCommonCalendarId(t2.calendar, o2.calendar);
  return diffDateLike(n2, (() => e2(i2)), t2, o2, ...refineDiffOptions(n2, r2, 6, 9, 6));
}
function zt(e2, n2, t2, o2, r2) {
  const i2 = getCommonCalendarId(t2.calendar, o2.calendar), a2 = refineDiffOptions(n2, r2, 9, 9, 8), s2 = e2(i2), c2 = moveToDayOfMonthUnsafe(s2, t2), u2 = moveToDayOfMonthUnsafe(s2, o2);
  return c2.isoYear === u2.isoYear && c2.isoMonth === u2.isoMonth && c2.isoDay === u2.isoDay ? Oe(pr) : diffDateLike(n2, (() => s2), checkIsoDateInBounds(c2), checkIsoDateInBounds(u2), ...a2, 8);
}
function diffDateLike(e2, n2, t2, o2, r2, i2, a2, s2, c2 = 6) {
  const u2 = isoToEpochNano(t2), f2 = isoToEpochNano(o2);
  if (void 0 === u2 || void 0 === f2) {
    throw new RangeError(Io);
  }
  let l2;
  if (compareBigNanos(f2, u2)) {
    if (6 === r2) {
      l2 = diffEpochNanos(u2, f2, r2, i2, a2, s2);
    } else {
      const e3 = n2();
      l2 = e3.N(t2, o2, r2), i2 === c2 && 1 === a2 || (l2 = roundRelativeDuration(l2, f2, r2, i2, a2, s2, e3, t2, isoToEpochNano, moveDate));
    }
  } else {
    l2 = pr;
  }
  return Oe(e2 ? negateDurationFields(l2) : l2);
}
function it(e2, n2, t2, o2) {
  const [r2, i2, a2, s2] = refineDiffOptions(e2, o2, 5, 5), c2 = roundByInc(diffTimes(n2, t2), computeNanoInc(i2, a2), s2), u2 = {
    ...pr,
    ...nanoToDurationTimeFields(c2, r2)
  };
  return Oe(e2 ? negateDurationFields(u2) : u2);
}
function diffZonedEpochsExact(e2, n2, t2, o2, r2, i2) {
  const a2 = compareBigNanos(o2.epochNanoseconds, t2.epochNanoseconds);
  return a2 ? r2 < 6 ? diffEpochNanosExact(t2.epochNanoseconds, o2.epochNanoseconds, r2) : diffZonedEpochsBig(n2, e2, t2, o2, a2, r2, i2) : pr;
}
function diffDateTimesExact(e2, n2, t2, o2, r2) {
  const i2 = isoToEpochNano(n2), a2 = isoToEpochNano(t2), s2 = compareBigNanos(a2, i2);
  return s2 ? o2 <= 6 ? diffEpochNanosExact(i2, a2, o2) : diffDateTimesBig(e2, n2, t2, s2, o2, r2) : pr;
}
function diffZonedEpochsBig(e2, n2, t2, o2, r2, i2, a2) {
  const [s2, c2, u2] = ((e3, n3, t3, o3) => {
    function updateMid() {
      return f3 = {
        ...moveByDays(a3, c3++ * -o3),
        ...i3
      }, l3 = getSingleInstantFor(e3, f3), compareBigNanos(s3, l3) === -o3;
    }
    const r3 = he(n3, e3), i3 = nn(w, r3), a3 = he(t3, e3), s3 = t3.epochNanoseconds;
    let c3 = 0;
    const u3 = diffTimes(r3, a3);
    let f3, l3;
    if (Math.sign(u3) === -o3 && c3++, updateMid() && (-1 === o3 || updateMid())) {
      throw new RangeError(fo);
    }
    const d2 = bigNanoToNumber(diffBigNanos(l3, s3));
    return [r3, f3, d2];
  })(n2, t2, o2, r2);
  var f2, l2;
  return {
    ...6 === i2 ? (f2 = s2, l2 = c2, {
      ...pr,
      days: diffDays(f2, l2)
    }) : e2.N(s2, c2, i2, a2),
    ...nanoToDurationTimeFields(u2)
  };
}
function diffDateTimesBig(e2, n2, t2, o2, r2, i2) {
  const [a2, s2, c2] = ((e3, n3, t3) => {
    let o3 = n3, r3 = diffTimes(e3, n3);
    return Math.sign(r3) === -t3 && (o3 = moveByDays(n3, -t3), r3 += Uo * t3), [e3, o3, r3];
  })(n2, t2, o2);
  return {
    ...e2.N(a2, s2, r2, i2),
    ...nanoToDurationTimeFields(c2)
  };
}
function diffEpochNanos(e2, n2, t2, o2, r2, i2) {
  return {
    ...pr,
    ...nanoToDurationDayTimeFields(roundBigNano(diffBigNanos(e2, n2), o2, r2, i2), t2)
  };
}
function diffEpochNanosExact(e2, n2, t2) {
  return {
    ...pr,
    ...nanoToDurationDayTimeFields(diffBigNanos(e2, n2), t2)
  };
}
function diffDays(e2, n2) {
  return diffEpochMilliByDay(isoToEpochMilli(e2), isoToEpochMilli(n2));
}
function diffEpochMilliByDay(e2, n2) {
  return Math.trunc((n2 - e2) / ko);
}
function diffTimes(e2, n2) {
  return isoTimeFieldsToNano(n2) - isoTimeFieldsToNano(e2);
}
function getCommonCalendarId(e2, n2) {
  if (e2 !== n2) {
    throw new RangeError(lo);
  }
  return e2;
}
function computeNativeWeekOfYear(e2) {
  return this.m(e2)[0];
}
function computeNativeYearOfWeek(e2) {
  return this.m(e2)[1];
}
function computeNativeDayOfYear(e2) {
  const [n2] = this.v(e2);
  return diffEpochMilliByDay(this.p(n2), isoToEpochMilli(e2)) + 1;
}
function parseMonthCode(e2) {
  const n2 = Bi.exec(e2);
  if (!n2) {
    throw new RangeError(invalidMonthCode(e2));
  }
  return [parseInt(n2[1]), Boolean(n2[2])];
}
function formatMonthCode(e2, n2) {
  return "M" + bo(e2) + (n2 ? "L" : "");
}
function monthCodeNumberToMonth(e2, n2, t2) {
  return e2 + (n2 || t2 && e2 >= t2 ? 1 : 0);
}
function monthToMonthCodeNumber(e2, n2) {
  return e2 - (n2 && e2 >= n2 ? 1 : 0);
}
function eraYearToYear(e2, n2) {
  return (n2 + e2) * (Math.sign(n2) || 1) || 0;
}
function getCalendarEraOrigins(e2) {
  return ir[getCalendarIdBase(e2)];
}
function getCalendarLeapMonthMeta(e2) {
  return sr[getCalendarIdBase(e2)];
}
function getCalendarIdBase(e2) {
  return computeCalendarIdBase(e2.id || l);
}
function createIntlCalendar(e2) {
  function epochMilliToIntlFields(e3) {
    return ((e4, n3) => ({
      ...parseIntlYear(e4, n3),
      o: e4.month,
      day: parseInt(e4.day)
    }))(hashIntlFormatParts(n2, e3), t2);
  }
  const n2 = Ci(e2), t2 = computeCalendarIdBase(e2);
  return {
    id: e2,
    h: createIntlFieldCache(epochMilliToIntlFields),
    l: createIntlYearDataCache(epochMilliToIntlFields)
  };
}
function createIntlFieldCache(e2) {
  return on(((n2) => {
    const t2 = isoToEpochMilli(n2);
    return e2(t2);
  }), WeakMap);
}
function createIntlYearDataCache(e2) {
  const n2 = e2(0).year - Or;
  return on(((t2) => {
    let o2, r2 = isoArgsToEpochMilli(t2 - n2), i2 = 0;
    const a2 = [], s2 = [];
    do {
      r2 += 400 * ko;
    } while ((o2 = e2(r2)).year <= t2);
    do {
      if (r2 += (1 - o2.day) * ko, o2.year === t2 && (a2.push(r2), s2.push(o2.o)), r2 -= ko, ++i2 > 100 || r2 < -Pr) {
        throw new RangeError(fo);
      }
    } while ((o2 = e2(r2)).year >= t2);
    return {
      i: a2.reverse(),
      u: Fo(s2.reverse())
    };
  }));
}
function parseIntlYear(e2, n2) {
  let t2, o2, r2 = parseIntlPartsYear(e2);
  if (e2.era) {
    const i2 = ir[n2], a2 = ar[n2] || {};
    void 0 !== i2 && (t2 = "islamic" === n2 ? "ah" : e2.era.normalize("NFD").toLowerCase().replace(/[^a-z0-9]/g, ""), "bc" === t2 || "b" === t2 ? t2 = "bce" : "ad" === t2 || "a" === t2 ? t2 = "ce" : "beforeroc" === t2 && (t2 = "broc"), t2 = a2[t2] || t2, o2 = r2, r2 = eraYearToYear(o2, i2[t2] || 0));
  }
  return {
    era: t2,
    eraYear: o2,
    year: r2
  };
}
function parseIntlPartsYear(e2) {
  return parseInt(e2.relatedYear || e2.year);
}
function computeIntlDateParts(e2) {
  const { year: n2, o: t2, day: o2 } = this.h(e2), { u: r2 } = this.l(n2);
  return [n2, r2[t2] + 1, o2];
}
function computeIntlEpochMilli(e2, n2 = 1, t2 = 1) {
  return this.l(e2).i[n2 - 1] + (t2 - 1) * ko;
}
function computeIntlMonthCodeParts(e2, n2) {
  const t2 = computeIntlLeapMonth.call(this, e2);
  return [monthToMonthCodeNumber(n2, t2), t2 === n2];
}
function computeIntlLeapMonth(e2) {
  const n2 = queryMonthStrings(this, e2), t2 = queryMonthStrings(this, e2 - 1), o2 = n2.length;
  if (o2 > t2.length) {
    const e3 = getCalendarLeapMonthMeta(this);
    if (e3 < 0) {
      return -e3;
    }
    for (let e4 = 0; e4 < o2; e4++) {
      if (n2[e4] !== t2[e4]) {
        return e4 + 1;
      }
    }
  }
}
function computeIntlDaysInYear(e2) {
  return diffEpochMilliByDay(computeIntlEpochMilli.call(this, e2), computeIntlEpochMilli.call(this, e2 + 1));
}
function computeIntlDaysInMonth(e2, n2) {
  const { i: t2 } = this.l(e2);
  let o2 = n2 + 1, r2 = t2;
  return o2 > t2.length && (o2 = 1, r2 = this.l(e2 + 1).i), diffEpochMilliByDay(t2[n2 - 1], r2[o2 - 1]);
}
function computeIntlMonthsInYear(e2) {
  return this.l(e2).i.length;
}
function computeIntlEraParts(e2) {
  const n2 = this.h(e2);
  return [n2.era, n2.eraYear];
}
function queryMonthStrings(e2, n2) {
  return Object.keys(e2.l(n2).u);
}
function Mt(e2) {
  return u(m(e2));
}
function u(e2) {
  if ((e2 = e2.toLowerCase()) !== l && e2 !== or) {
    const n2 = Ci(e2).resolvedOptions().calendar;
    if (computeCalendarIdBase(e2) !== computeCalendarIdBase(n2)) {
      throw new RangeError(c(e2));
    }
    return n2;
  }
  return e2;
}
function computeCalendarIdBase(e2) {
  return "islamicc" === e2 && (e2 = "islamic"), e2.split("-")[0];
}
function createNativeOpsCreator(e2, n2) {
  return (t2) => t2 === l ? e2 : t2 === or || t2 === rr ? Object.assign(Object.create(e2), {
    id: t2
  }) : Object.assign(Object.create(n2), ki(t2));
}
function $(e2, n2, t2, o2) {
  const r2 = refineCalendarFields(t2, o2, Xo, [], xo);
  if (void 0 !== r2.timeZone) {
    const o3 = t2.F(r2), i2 = refineTimeBag(r2), a2 = e2(r2.timeZone);
    return {
      epochNanoseconds: getMatchingInstantFor(n2(a2), {
        ...o3,
        ...i2
      }, void 0 !== r2.offset ? parseOffsetNano(r2.offset) : void 0),
      timeZone: a2
    };
  }
  return {
    ...t2.F(r2),
    ...Nt
  };
}
function Ne(e2, n2, t2, o2, r2, i2) {
  const a2 = refineCalendarFields(t2, r2, Xo, jo, xo), s2 = e2(a2.timeZone), [c2, u2, f2] = je(i2), l2 = t2.F(a2, fabricateOverflowOptions(c2)), d2 = refineTimeBag(a2, c2);
  return _e(getMatchingInstantFor(n2(s2), {
    ...l2,
    ...d2
  }, void 0 !== a2.offset ? parseOffsetNano(a2.offset) : void 0, u2, f2), s2, o2);
}
function At(e2, n2, t2) {
  const o2 = refineCalendarFields(e2, n2, Xo, [], O), r2 = mt(t2);
  return jt(checkIsoDateTimeInBounds({
    ...e2.F(o2, fabricateOverflowOptions(r2)),
    ...refineTimeBag(o2, r2)
  }));
}
function me(e2, n2, t2, o2 = []) {
  const r2 = refineCalendarFields(e2, n2, Xo, o2);
  return e2.F(r2, t2);
}
function Xt(e2, n2, t2, o2) {
  const r2 = refineCalendarFields(e2, n2, Ko, o2);
  return e2.K(r2, t2);
}
function Rt(e2, n2, t2, o2) {
  const r2 = refineCalendarFields(e2, t2, Xo, Jo);
  return n2 && void 0 !== r2.month && void 0 === r2.monthCode && void 0 === r2.year && (r2.year = Br), e2._(r2, o2);
}
function Tt(e2, n2) {
  return St(refineTimeBag(refineFields(e2, qo, [], 1), mt(n2)));
}
function q(e2) {
  const n2 = refineFields(e2, ur);
  return Oe(checkDurationUnits({
    ...pr,
    ...n2
  }));
}
function refineCalendarFields(e2, n2, t2, o2 = [], r2 = []) {
  return refineFields(n2, [...e2.fields(t2), ...r2].sort(), o2);
}
function refineFields(e2, n2, t2, o2 = !t2) {
  const r2 = {};
  let i2, a2 = 0;
  for (const o3 of n2) {
    if (o3 === i2) {
      throw new RangeError(duplicateFields(o3));
    }
    if ("constructor" === o3 || "__proto__" === o3) {
      throw new RangeError(forbiddenField(o3));
    }
    let n3 = e2[o3];
    if (void 0 !== n3) {
      a2 = 1, Li[o3] && (n3 = Li[o3](n3, o3)), r2[o3] = n3;
    } else if (t2) {
      if (t2.includes(o3)) {
        throw new TypeError(missingField(o3));
      }
      r2[o3] = tr[o3];
    }
    i2 = o3;
  }
  if (o2 && !a2) {
    throw new TypeError(noValidFields(n2));
  }
  return r2;
}
function refineTimeBag(e2, n2) {
  return constrainIsoTimeFields(xi({
    ...tr,
    ...e2
  }), n2);
}
function De(e2, n2, t2, o2, r2) {
  const { calendar: i2, timeZone: a2 } = t2, s2 = e2(i2), c2 = n2(a2), u2 = [...s2.fields(Xo), ...Lo].sort(), f2 = ((e3) => {
    const n3 = he(e3, L), t3 = Se(n3.offsetNanoseconds), o3 = ji(e3.calendar), [r3, i3, a3] = o3.v(n3), [s3, c3] = o3.q(r3, i3), u3 = formatMonthCode(s3, c3);
    return {
      ...$i(n3),
      year: r3,
      monthCode: u3,
      day: a3,
      offset: t3
    };
  })(t2), l2 = refineFields(o2, u2), d2 = s2.k(f2, l2), m2 = {
    ...f2,
    ...l2
  }, [p2, h2, g2] = je(r2, 2);
  return _e(getMatchingInstantFor(c2, {
    ...s2.F(d2, fabricateOverflowOptions(p2)),
    ...constrainIsoTimeFields(xi(m2), p2)
  }, parseOffsetNano(m2.offset), h2, g2), a2, i2);
}
function gt(e2, n2, t2, o2) {
  const r2 = e2(n2.calendar), i2 = [...r2.fields(Xo), ...O].sort(), a2 = {
    ...computeDateEssentials(s2 = n2),
    hour: s2.isoHour,
    minute: s2.isoMinute,
    second: s2.isoSecond,
    millisecond: s2.isoMillisecond,
    microsecond: s2.isoMicrosecond,
    nanosecond: s2.isoNanosecond
  };
  var s2;
  const c2 = refineFields(t2, i2), u2 = mt(o2), f2 = r2.k(a2, c2), l2 = {
    ...a2,
    ...c2
  };
  return jt(checkIsoDateTimeInBounds({
    ...r2.F(f2, fabricateOverflowOptions(u2)),
    ...constrainIsoTimeFields(xi(l2), u2)
  }));
}
function ee(e2, n2, t2, o2) {
  const r2 = e2(n2.calendar), i2 = r2.fields(Xo).sort(), a2 = computeDateEssentials(n2), s2 = refineFields(t2, i2), c2 = r2.k(a2, s2);
  return r2.F(c2, o2);
}
function Wt(e2, n2, t2, o2) {
  const r2 = e2(n2.calendar), i2 = r2.fields(Ko).sort(), a2 = ((e3) => {
    const n3 = ji(e3.calendar), [t3, o3] = n3.v(e3), [r3, i3] = n3.q(t3, o3);
    return {
      year: t3,
      monthCode: formatMonthCode(r3, i3)
    };
  })(n2), s2 = refineFields(t2, i2), c2 = r2.k(a2, s2);
  return r2.K(c2, o2);
}
function Et(e2, n2, t2, o2) {
  const r2 = e2(n2.calendar), i2 = r2.fields(Xo).sort(), a2 = ((e3) => {
    const n3 = ji(e3.calendar), [t3, o3, r3] = n3.v(e3), [i3, a3] = n3.q(t3, o3);
    return {
      monthCode: formatMonthCode(i3, a3),
      day: r3
    };
  })(n2), s2 = refineFields(t2, i2), c2 = r2.k(a2, s2);
  return r2._(c2, o2);
}
function rt(e2, n2, t2) {
  return St(((e3, n3, t3) => refineTimeBag({
    ...nn(qo, e3),
    ...refineFields(n3, qo)
  }, mt(t3)))(e2, n2, t2));
}
function A(e2, n2) {
  return Oe((t2 = e2, o2 = n2, checkDurationUnits({
    ...t2,
    ...refineFields(o2, ur)
  })));
  var t2, o2;
}
function convertToIso(e2, n2, t2, o2, r2) {
  n2 = nn(t2 = e2.fields(t2), n2), o2 = refineFields(o2, r2 = e2.fields(r2), []);
  let i2 = e2.k(n2, o2);
  return i2 = refineFields(i2, [...t2, ...r2].sort(), []), e2.F(i2);
}
function refineYear(e2, n2) {
  const t2 = getCalendarEraOrigins(e2), o2 = ar[e2.id || ""] || {};
  let { era: r2, eraYear: i2, year: a2 } = n2;
  if (void 0 !== r2 || void 0 !== i2) {
    if (void 0 === r2 || void 0 === i2) {
      throw new TypeError(io);
    }
    if (!t2) {
      throw new RangeError(ro);
    }
    const e3 = t2[o2[r2] || r2];
    if (void 0 === e3) {
      throw new RangeError(invalidEra(r2));
    }
    const n3 = eraYearToYear(i2, e3);
    if (void 0 !== a2 && a2 !== n3) {
      throw new RangeError(ao);
    }
    a2 = n3;
  } else if (void 0 === a2) {
    throw new TypeError(missingYear(t2));
  }
  return a2;
}
function refineMonth(e2, n2, t2, o2) {
  let { month: r2, monthCode: i2 } = n2;
  if (void 0 !== i2) {
    const n3 = ((e3, n4, t3, o3) => {
      const r3 = e3.L(t3), [i3, a2] = parseMonthCode(n4);
      let s2 = monthCodeNumberToMonth(i3, a2, r3);
      if (a2) {
        const n5 = getCalendarLeapMonthMeta(e3);
        if (void 0 === n5) {
          throw new RangeError(uo);
        }
        if (n5 > 0) {
          if (s2 > n5) {
            throw new RangeError(uo);
          }
          if (void 0 === r3) {
            if (1 === o3) {
              throw new RangeError(uo);
            }
            s2--;
          }
        } else {
          if (s2 !== -n5) {
            throw new RangeError(uo);
          }
          if (void 0 === r3 && 1 === o3) {
            throw new RangeError(uo);
          }
        }
      }
      return s2;
    })(e2, i2, t2, o2);
    if (void 0 !== r2 && r2 !== n3) {
      throw new RangeError(so);
    }
    r2 = n3, o2 = 1;
  } else if (void 0 === r2) {
    throw new TypeError(co);
  }
  return clampEntity("month", r2, 1, e2.B(t2), o2);
}
function refineDay(e2, n2, t2, o2, r2) {
  return clampProp(n2, "day", 1, e2.U(o2, t2), r2);
}
function spliceFields(e2, n2, t2, o2) {
  let r2 = 0;
  const i2 = [];
  for (const e3 of t2) {
    void 0 !== n2[e3] ? r2 = 1 : i2.push(e3);
  }
  if (Object.assign(e2, n2), r2) {
    for (const n3 of o2 || i2) {
      delete e2[n3];
    }
  }
}
function computeDateEssentials(e2) {
  const n2 = ji(e2.calendar), [t2, o2, r2] = n2.v(e2), [i2, a2] = n2.q(t2, o2);
  return {
    year: t2,
    monthCode: formatMonthCode(i2, a2),
    day: r2
  };
}
function qe(e2) {
  return xe(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(e2))));
}
function ye(e2, n2, t2, o2, r2 = l) {
  return _e(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(t2))), n2(o2), e2(r2));
}
function Zt(n2, t2, o2, r2, i2 = 0, a2 = 0, s2 = 0, c2 = 0, u2 = 0, f2 = 0, d2 = l) {
  return jt(checkIsoDateTimeInBounds(checkIsoDateTimeFields(e(toInteger, zipProps(Tr, [t2, o2, r2, i2, a2, s2, c2, u2, f2])))), n2(d2));
}
function ue(n2, t2, o2, r2, i2 = l) {
  return W(checkIsoDateInBounds(checkIsoDateFields(e(toInteger, {
    isoYear: t2,
    isoMonth: o2,
    isoDay: r2
  }))), n2(i2));
}
function Qt(e2, n2, t2, o2 = l, r2 = 1) {
  const i2 = toInteger(n2), a2 = toInteger(t2), s2 = e2(o2);
  return createPlainYearMonthSlots(checkIsoYearMonthInBounds(checkIsoDateFields({
    isoYear: i2,
    isoMonth: a2,
    isoDay: toInteger(r2)
  })), s2);
}
function kt(e2, n2, t2, o2 = l, r2 = Br) {
  const i2 = toInteger(n2), a2 = toInteger(t2), s2 = e2(o2);
  return createPlainMonthDaySlots(checkIsoDateInBounds(checkIsoDateFields({
    isoYear: toInteger(r2),
    isoMonth: i2,
    isoDay: a2
  })), s2);
}
function ut(n2 = 0, t2 = 0, o2 = 0, r2 = 0, i2 = 0, a2 = 0) {
  return St(constrainIsoTimeFields(e(toInteger, zipProps(w, [n2, t2, o2, r2, i2, a2])), 1));
}
function j(n2 = 0, t2 = 0, o2 = 0, r2 = 0, i2 = 0, a2 = 0, s2 = 0, c2 = 0, u2 = 0, f2 = 0) {
  return Oe(checkDurationUnits(e(toStrictInteger, zipProps(p, [n2, t2, o2, r2, i2, a2, s2, c2, u2, f2]))));
}
function Je(e2, n2, t2 = l) {
  return _e(e2.epochNanoseconds, n2, t2);
}
function be(e2) {
  return xe(e2.epochNanoseconds);
}
function yt(e2, n2) {
  return jt(he(n2, e2));
}
function fe(e2, n2) {
  return W(he(n2, e2));
}
function dt(e2, n2) {
  return St(he(n2, e2));
}
function bt(e2, n2, t2, o2) {
  const r2 = ((e3, n3, t3, o3) => {
    const r3 = ((e4) => ei(normalizeOptions(e4)))(o3);
    return getSingleInstantFor(e3(n3), t3, r3);
  })(e2, t2, n2, o2);
  return _e(checkEpochNanoInBounds(r2), t2, n2.calendar);
}
function ae(e2, n2, t2, o2, r2) {
  const i2 = e2(r2.timeZone), a2 = r2.plainTime, s2 = void 0 !== a2 ? n2(a2) : void 0, c2 = t2(i2);
  let u2;
  return u2 = s2 ? getSingleInstantFor(c2, {
    ...o2,
    ...s2
  }) : getStartOfDayInstantFor(c2, {
    ...o2,
    ...Nt
  }), _e(u2, i2, o2.calendar);
}
function ie(e2, n2 = Nt) {
  return jt(checkIsoDateTimeInBounds({
    ...e2,
    ...n2
  }));
}
function le(e2, n2, t2) {
  return ((e3, n3) => {
    const t3 = refineCalendarFields(e3, n3, Qo);
    return e3.K(t3, void 0);
  })(e2(n2.calendar), t2);
}
function se(e2, n2, t2) {
  return ((e3, n3) => {
    const t3 = refineCalendarFields(e3, n3, nr);
    return e3._(t3);
  })(e2(n2.calendar), t2);
}
function Ht(e2, n2, t2, o2) {
  return ((e3, n3, t3) => convertToIso(e3, n3, Qo, requireObjectLike(t3), Jo))(e2(n2.calendar), t2, o2);
}
function Vt(e2, n2, t2, o2) {
  return ((e3, n3, t3) => convertToIso(e3, n3, nr, requireObjectLike(t3), Go))(e2(n2.calendar), t2, o2);
}
function $e(e2) {
  return xe(checkEpochNanoInBounds(Ge(toStrictInteger(e2), Qe)));
}
function He(e2) {
  return xe(checkEpochNanoInBounds(bigIntToBigNano(toBigInt(e2))));
}
function createOptionsTransformer(e2, n2, t2) {
  const o2 = new Set(t2);
  return (r2, i2) => {
    const a2 = t2 && hasAnyPropsByName(r2, t2);
    if (!hasAnyPropsByName(r2 = ((e3, n3) => {
      const t3 = {};
      for (const o3 in n3) {
        e3.has(o3) || (t3[o3] = n3[o3]);
      }
      return t3;
    })(o2, r2), e2)) {
      if (i2 && a2) {
        throw new TypeError("Invalid formatting options");
      }
      r2 = {
        ...n2,
        ...r2
      };
    }
    return t2 && (r2.timeZone = si, ["full", "long"].includes(r2.J) && (r2.J = "medium")), r2;
  };
}
function Q(e2, n2 = an, t2 = 0) {
  const [o2, , , r2] = e2;
  return (i2, a2 = Na, ...s2) => {
    const c2 = n2(r2 && r2(...s2), i2, a2, o2, t2), u2 = c2.resolvedOptions();
    return [c2, ...toEpochMillis(e2, u2, s2)];
  };
}
function an(e2, n2, t2, o2, r2) {
  if (t2 = o2(t2, r2), e2) {
    if (void 0 !== t2.timeZone) {
      throw new TypeError(So);
    }
    t2.timeZone = e2;
  }
  return new en(n2, t2);
}
function toEpochMillis(e2, n2, t2) {
  const [, o2, r2] = e2;
  return t2.map(((e3) => (e3.calendar && ((e4, n3, t3) => {
    if ((t3 || e4 !== l) && e4 !== n3) {
      throw new RangeError(lo);
    }
  })(e3.calendar, n2.calendar, r2), o2(e3, n2))));
}
function ge(e2, n2, t2) {
  const o2 = n2.timeZone, r2 = e2(o2), i2 = {
    ...he(n2, r2),
    ...t2 || Nt
  };
  let a2;
  return a2 = t2 ? getMatchingInstantFor(r2, i2, i2.offsetNanoseconds, 2) : getStartOfDayInstantFor(r2, i2), _e(a2, o2, n2.calendar);
}
function Ot(e2, n2 = Nt) {
  return jt(checkIsoDateTimeInBounds({
    ...e2,
    ...n2
  }));
}
function pt(e2, n2) {
  return {
    ...e2,
    calendar: n2
  };
}
function Pe(e2, n2) {
  return {
    ...e2,
    timeZone: n2
  };
}
function tn(e2) {
  const n2 = Xe();
  return epochNanoToIso(n2, e2.R(n2));
}
function Xe() {
  return Ge(Date.now(), Qe);
}
function Ue() {
  return va || (va = new en().resolvedOptions().timeZone);
}
var expectedInteger = (e2, n2) => `Non-integer ${e2}: ${n2}`;
var expectedPositive = (e2, n2) => `Non-positive ${e2}: ${n2}`;
var expectedFinite = (e2, n2) => `Non-finite ${e2}: ${n2}`;
var forbiddenBigIntToNumber = (e2) => `Cannot convert bigint to ${e2}`;
var invalidBigInt = (e2) => `Invalid bigint: ${e2}`;
var no = "Cannot convert Symbol to string";
var oo = "Invalid object";
var numberOutOfRange = (e2, n2, t2, o2, r2) => r2 ? numberOutOfRange(e2, r2[n2], r2[t2], r2[o2]) : invalidEntity(e2, n2) + `; must be between ${t2}-${o2}`;
var invalidEntity = (e2, n2) => `Invalid ${e2}: ${n2}`;
var missingField = (e2) => `Missing ${e2}`;
var forbiddenField = (e2) => `Invalid field ${e2}`;
var duplicateFields = (e2) => `Duplicate field ${e2}`;
var noValidFields = (e2) => "No valid fields: " + e2.join();
var i = "Invalid bag";
var invalidChoice = (e2, n2, t2) => invalidEntity(e2, n2) + "; must be " + Object.keys(t2).join();
var b = "Cannot use valueOf";
var a = "Invalid calling context";
var ro = "Forbidden era/eraYear";
var io = "Mismatching era/eraYear";
var ao = "Mismatching year/eraYear";
var invalidEra = (e2) => `Invalid era: ${e2}`;
var missingYear = (e2) => "Missing year" + (e2 ? "/era/eraYear" : "");
var invalidMonthCode = (e2) => `Invalid monthCode: ${e2}`;
var so = "Mismatching month/monthCode";
var co = "Missing month/monthCode";
var uo = "Invalid leap month";
var fo = "Invalid protocol results";
var c = (e2) => invalidEntity("Calendar", e2);
var lo = "Mismatching Calendars";
var F = (e2) => invalidEntity("TimeZone", e2);
var mo = "Mismatching TimeZones";
var po = "Forbidden ICU TimeZone";
var ho = "Out-of-bounds offset";
var go = "Out-of-bounds TimeZone gap";
var Do = "Invalid TimeZone offset";
var To = "Ambiguous offset";
var Io = "Out-of-bounds date";
var Mo = "Out-of-bounds duration";
var No = "Cannot mix duration signs";
var yo = "Missing relativeTo";
var vo = "Cannot use large units";
var Po = "Required smallestUnit or largestUnit";
var Eo = "smallestUnit > largestUnit";
var failedParse = (e2) => `Cannot parse: ${e2}`;
var invalidSubstring = (e2) => `Invalid substring: ${e2}`;
var rn = (e2) => `Cannot format ${e2}`;
var ln = "Mismatching types for formatting";
var So = "Cannot specify TimeZone";
var Fo = /* @__PURE__ */ Pt(g, ((e2, n2) => n2));
var wo = /* @__PURE__ */ Pt(g, ((e2, n2, t2) => t2));
var bo = /* @__PURE__ */ Pt(padNumber, 2);
var Oo = {
  nanosecond: 0,
  microsecond: 1,
  millisecond: 2,
  second: 3,
  minute: 4,
  hour: 5,
  day: 6,
  week: 7,
  month: 8,
  year: 9
};
var Bo = /* @__PURE__ */ Object.keys(Oo);
var ko = 864e5;
var Co = 1e3;
var Yo = 1e3;
var Qe = 1e6;
var Ro = 1e9;
var Zo = 6e10;
var zo = 36e11;
var Uo = 864e11;
var Ao = [1, Yo, Qe, Ro, Zo, zo, Uo];
var O = /* @__PURE__ */ Bo.slice(0, 6);
var qo = /* @__PURE__ */ sortStrings(O);
var Wo = ["offset"];
var jo = ["timeZone"];
var Lo = /* @__PURE__ */ O.concat(Wo);
var xo = /* @__PURE__ */ Lo.concat(jo);
var $o = ["era", "eraYear"];
var Ho = /* @__PURE__ */ $o.concat(["year"]);
var Go = ["year"];
var Vo = ["monthCode"];
var _o = /* @__PURE__ */ ["month"].concat(Vo);
var Jo = ["day"];
var Ko = /* @__PURE__ */ _o.concat(Go);
var Qo = /* @__PURE__ */ Vo.concat(Go);
var Xo = /* @__PURE__ */ Jo.concat(Ko);
var er = /* @__PURE__ */ Jo.concat(_o);
var nr = /* @__PURE__ */ Jo.concat(Vo);
var tr = /* @__PURE__ */ wo(O, 0);
var l = "iso8601";
var or = "gregory";
var rr = "japanese";
var ir = {
  [or]: {
    "gregory-inverse": -1,
    gregory: 0
  },
  [rr]: {
    "japanese-inverse": -1,
    japanese: 0,
    meiji: 1867,
    taisho: 1911,
    showa: 1925,
    heisei: 1988,
    reiwa: 2018
  },
  ethiopic: {
    ethioaa: 0,
    ethiopic: 5500
  },
  coptic: {
    "coptic-inverse": -1,
    coptic: 0
  },
  roc: {
    "roc-inverse": -1,
    roc: 0
  },
  buddhist: {
    be: 0
  },
  islamic: {
    ah: 0
  },
  indian: {
    saka: 0
  },
  persian: {
    ap: 0
  }
};
var ar = {
  [or]: {
    bce: "gregory-inverse",
    ce: "gregory"
  },
  [rr]: {
    bce: "japanese-inverse",
    ce: "japanese"
  },
  ethiopic: {
    era0: "ethioaa",
    era1: "ethiopic"
  },
  coptic: {
    era0: "coptic-inverse",
    era1: "coptic"
  },
  roc: {
    broc: "roc-inverse",
    minguo: "roc"
  }
};
var sr = {
  chinese: 13,
  dangi: 13,
  hebrew: -6
};
var m = /* @__PURE__ */ Pt(requireType, "string");
var D = /* @__PURE__ */ Pt(requireType, "boolean");
var cr = /* @__PURE__ */ Pt(requireType, "number");
var p = /* @__PURE__ */ Bo.map(((e2) => e2 + "s"));
var ur = /* @__PURE__ */ sortStrings(p);
var fr = /* @__PURE__ */ p.slice(0, 6);
var lr = /* @__PURE__ */ p.slice(6);
var dr = /* @__PURE__ */ lr.slice(1);
var mr = /* @__PURE__ */ Fo(p);
var pr = /* @__PURE__ */ wo(p, 0);
var hr = /* @__PURE__ */ wo(fr, 0);
var gr = /* @__PURE__ */ Pt(zeroOutProps, p);
var w = ["isoNanosecond", "isoMicrosecond", "isoMillisecond", "isoSecond", "isoMinute", "isoHour"];
var Dr = ["isoDay", "isoMonth", "isoYear"];
var Tr = /* @__PURE__ */ w.concat(Dr);
var Ir = /* @__PURE__ */ sortStrings(Dr);
var Mr = /* @__PURE__ */ sortStrings(w);
var Nr = /* @__PURE__ */ sortStrings(Tr);
var Nt = /* @__PURE__ */ wo(Mr, 0);
var yr = /* @__PURE__ */ Pt(zeroOutProps, Tr);
var vr = 1e8;
var Pr = vr * ko;
var Er = [vr, 0];
var Sr = [-vr, 0];
var Fr = 275760;
var wr = -271821;
var en = Intl.DateTimeFormat;
var br = "en-GB";
var Or = 1970;
var Br = 1972;
var kr = 12;
var Cr = /* @__PURE__ */ isoArgsToEpochMilli(1868, 9, 8);
var Yr = /* @__PURE__ */ on(computeJapaneseEraParts, WeakMap);
var Rr = "smallestUnit";
var Zr = "unit";
var zr = "roundingIncrement";
var Ur = "fractionalSecondDigits";
var Ar = "relativeTo";
var qr = "direction";
var Wr = {
  constrain: 0,
  reject: 1
};
var jr = /* @__PURE__ */ Object.keys(Wr);
var Lr = {
  compatible: 0,
  reject: 1,
  earlier: 2,
  later: 3
};
var xr = {
  reject: 0,
  use: 1,
  prefer: 2,
  ignore: 3
};
var $r = {
  auto: 0,
  never: 1,
  critical: 2,
  always: 3
};
var Hr = {
  auto: 0,
  never: 1,
  critical: 2
};
var Gr = {
  auto: 0,
  never: 1
};
var Vr = {
  floor: 0,
  halfFloor: 1,
  ceil: 2,
  halfCeil: 3,
  trunc: 4,
  halfTrunc: 5,
  expand: 6,
  halfExpand: 7,
  halfEven: 8
};
var _r = {
  previous: -1,
  next: 1
};
var Jr = /* @__PURE__ */ Pt(refineUnitOption, Rr);
var Kr = /* @__PURE__ */ Pt(refineUnitOption, "largestUnit");
var Qr = /* @__PURE__ */ Pt(refineUnitOption, Zr);
var Xr = /* @__PURE__ */ Pt(refineChoiceOption, "overflow", Wr);
var ei = /* @__PURE__ */ Pt(refineChoiceOption, "disambiguation", Lr);
var ni = /* @__PURE__ */ Pt(refineChoiceOption, "offset", xr);
var ti = /* @__PURE__ */ Pt(refineChoiceOption, "calendarName", $r);
var oi = /* @__PURE__ */ Pt(refineChoiceOption, "timeZoneName", Hr);
var ri = /* @__PURE__ */ Pt(refineChoiceOption, "offset", Gr);
var ii = /* @__PURE__ */ Pt(refineChoiceOption, "roundingMode", Vr);
var Ut = "PlainYearMonth";
var qt = "PlainMonthDay";
var G = "PlainDate";
var x = "PlainDateTime";
var ft = "PlainTime";
var z = "ZonedDateTime";
var Re = "Instant";
var N = "Duration";
var ai = [Math.floor, (e2) => hasHalf(e2) ? Math.floor(e2) : Math.round(e2), Math.ceil, (e2) => hasHalf(e2) ? Math.ceil(e2) : Math.round(e2), Math.trunc, (e2) => hasHalf(e2) ? Math.trunc(e2) || 0 : Math.round(e2), (e2) => e2 < 0 ? Math.floor(e2) : Math.ceil(e2), (e2) => Math.sign(e2) * Math.round(Math.abs(e2)) || 0, (e2) => hasHalf(e2) ? (e2 = Math.trunc(e2) || 0) + e2 % 2 : Math.round(e2)];
var si = "UTC";
var ci = 5184e3;
var ui = /* @__PURE__ */ isoArgsToEpochSec(1847);
var fi = /* @__PURE__ */ isoArgsToEpochSec(/* @__PURE__ */ (/* @__PURE__ */ new Date()).getUTCFullYear() + 10);
var li = /0+$/;
var he = /* @__PURE__ */ on(_zonedEpochSlotsToIso, WeakMap);
var di = 2 ** 32 - 1;
var L = /* @__PURE__ */ on(((e2) => {
  const n2 = getTimeZoneEssence(e2);
  return "object" == typeof n2 ? new IntlTimeZone(n2) : new FixedTimeZone(n2 || 0);
}));
var FixedTimeZone = class {
  constructor(e2) {
    this.$ = e2;
  }
  R() {
    return this.$;
  }
  I(e2) {
    return ((e3) => {
      const n2 = isoToEpochNano({
        ...e3,
        ...Nt
      });
      if (!n2 || Math.abs(n2[0]) > 1e8) {
        throw new RangeError(Io);
      }
    })(e2), [isoToEpochNanoWithOffset(e2, this.$)];
  }
  O() {
  }
};
var IntlTimeZone = class {
  constructor(e2) {
    this.nn = ((e3) => {
      function getOffsetSec(e4) {
        const i2 = clampNumber(e4, o2, r2), [a2, s2] = computePeriod(i2), c2 = n2(a2), u2 = n2(s2);
        return c2 === u2 ? c2 : pinch(t2(a2, s2), c2, u2, e4);
      }
      function pinch(n3, t3, o3, r3) {
        let i2, a2;
        for (; (void 0 === r3 || void 0 === (i2 = r3 < n3[0] ? t3 : r3 >= n3[1] ? o3 : void 0)) && (a2 = n3[1] - n3[0]); ) {
          const t4 = n3[0] + Math.floor(a2 / 2);
          e3(t4) === o3 ? n3[1] = t4 : n3[0] = t4 + 1;
        }
        return i2;
      }
      const n2 = on(e3), t2 = on(createSplitTuple);
      let o2 = ui, r2 = fi;
      return {
        tn(e4) {
          const n3 = getOffsetSec(e4 - 86400), t3 = getOffsetSec(e4 + 86400), o3 = e4 - n3, r3 = e4 - t3;
          if (n3 === t3) {
            return [o3];
          }
          const i2 = getOffsetSec(o3);
          return i2 === getOffsetSec(r3) ? [e4 - i2] : n3 > t3 ? [o3, r3] : [];
        },
        rn: getOffsetSec,
        O(e4, i2) {
          const a2 = clampNumber(e4, o2, r2);
          let [s2, c2] = computePeriod(a2);
          const u2 = ci * i2, f2 = i2 < 0 ? () => c2 > o2 || (o2 = a2, 0) : () => s2 < r2 || (r2 = a2, 0);
          for (; f2(); ) {
            const o3 = n2(s2), r3 = n2(c2);
            if (o3 !== r3) {
              const n3 = t2(s2, c2);
              pinch(n3, o3, r3);
              const a3 = n3[0];
              if ((compareNumbers(a3, e4) || 1) === i2) {
                return a3;
              }
            }
            s2 += u2, c2 += u2;
          }
        }
      };
    })(/* @__PURE__ */ ((e3) => (n2) => {
      const t2 = hashIntlFormatParts(e3, n2 * Co);
      return isoArgsToEpochSec(parseIntlPartsYear(t2), parseInt(t2.month), parseInt(t2.day), parseInt(t2.hour), parseInt(t2.minute), parseInt(t2.second)) - n2;
    })(e2));
  }
  R(e2) {
    return this.nn.rn(((e3) => epochNanoToSecMod(e3)[0])(e2)) * Ro;
  }
  I(e2) {
    const [n2, t2] = [isoArgsToEpochSec((o2 = e2).isoYear, o2.isoMonth, o2.isoDay, o2.isoHour, o2.isoMinute, o2.isoSecond), o2.isoMillisecond * Qe + o2.isoMicrosecond * Yo + o2.isoNanosecond];
    var o2;
    return this.nn.tn(n2).map(((e3) => checkEpochNanoInBounds(moveBigNano(Ge(e3, Ro), t2))));
  }
  O(e2, n2) {
    const [t2, o2] = epochNanoToSecMod(e2), r2 = this.nn.O(t2 + (n2 > 0 || o2 ? 1 : 0), n2);
    if (void 0 !== r2) {
      return Ge(r2, Ro);
    }
  }
};
var mi = "([+-])";
var pi = "(?:[.,](\\d{1,9}))?";
var hi = `(?:(?:${mi}(\\d{6}))|(\\d{4}))-?(\\d{2})`;
var gi = "(\\d{2})(?::?(\\d{2})(?::?(\\d{2})" + pi + ")?)?";
var Di = mi + gi;
var Ti = hi + "-?(\\d{2})(?:[T ]" + gi + "(Z|" + Di + ")?)?";
var Ii = "\\[(!?)([^\\]]*)\\]";
var Mi = `((?:${Ii}){0,9})`;
var Ni = /* @__PURE__ */ createRegExp(hi + Mi);
var yi = /* @__PURE__ */ createRegExp("(?:--)?(\\d{2})-?(\\d{2})" + Mi);
var vi = /* @__PURE__ */ createRegExp(Ti + Mi);
var Pi = /* @__PURE__ */ createRegExp("T?" + gi + "(?:" + Di + ")?" + Mi);
var Ei = /* @__PURE__ */ createRegExp(Di);
var Si = /* @__PURE__ */ new RegExp(Ii, "g");
var Fi = /* @__PURE__ */ createRegExp(`${mi}?P(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?(?:T(?:(\\d+)${pi}H)?(?:(\\d+)${pi}M)?(?:(\\d+)${pi}S)?)?`);
var wi = /* @__PURE__ */ on(((e2) => new en(br, {
  timeZone: e2,
  era: "short",
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric"
})));
var bi = /^(AC|AE|AG|AR|AS|BE|BS|CA|CN|CS|CT|EA|EC|IE|IS|JS|MI|NE|NS|PL|PN|PR|PS|SS|VS)T$/;
var Oi = /[^\w\/:+-]+/;
var Bi = /^M(\d{2})(L?)$/;
var ki = /* @__PURE__ */ on(createIntlCalendar);
var Ci = /* @__PURE__ */ on(((e2) => new en(br, {
  calendar: e2,
  timeZone: si,
  era: "short",
  year: "numeric",
  month: "short",
  day: "numeric"
})));
var Yi = {
  P(e2, n2, t2) {
    const o2 = mt(t2);
    let r2, { years: i2, months: a2, weeks: s2, days: c2 } = n2;
    if (c2 += durationFieldsToBigNano(n2, 5)[0], i2 || a2) {
      r2 = ((e3, n3, t3, o3, r3) => {
        let [i3, a3, s3] = e3.v(n3);
        if (t3) {
          const [n4, o4] = e3.q(i3, a3);
          i3 += t3, a3 = monthCodeNumberToMonth(n4, o4, e3.L(i3)), a3 = clampEntity("month", a3, 1, e3.B(i3), r3);
        }
        return o3 && ([i3, a3] = e3.un(i3, a3, o3)), s3 = clampEntity("day", s3, 1, e3.U(i3, a3), r3), e3.p(i3, a3, s3);
      })(this, e2, i2, a2, o2);
    } else {
      if (!s2 && !c2) {
        return e2;
      }
      r2 = isoToEpochMilli(e2);
    }
    if (void 0 === r2) {
      throw new RangeError(Io);
    }
    return r2 += (7 * s2 + c2) * ko, checkIsoDateInBounds(epochMilliToIso(r2));
  },
  N(e2, n2, t2) {
    if (t2 <= 7) {
      let o3 = 0, r3 = diffDays({
        ...e2,
        ...Nt
      }, {
        ...n2,
        ...Nt
      });
      return 7 === t2 && ([o3, r3] = divModTrunc(r3, 7)), {
        ...pr,
        weeks: o3,
        days: r3
      };
    }
    const o2 = this.v(e2), r2 = this.v(n2);
    let [i2, a2, s2] = ((e3, n3, t3, o3, r3, i3, a3) => {
      let s3 = r3 - n3, c2 = i3 - t3, u2 = a3 - o3;
      if (s3 || c2) {
        const f2 = Math.sign(s3 || c2);
        let l2 = e3.U(r3, i3), d2 = 0;
        if (Math.sign(u2) === -f2) {
          const o4 = l2;
          [r3, i3] = e3.un(r3, i3, -f2), s3 = r3 - n3, c2 = i3 - t3, l2 = e3.U(r3, i3), d2 = f2 < 0 ? -o4 : l2;
        }
        if (u2 = a3 - Math.min(o3, l2) + d2, s3) {
          const [o4, a4] = e3.q(n3, t3), [u3, l3] = e3.q(r3, i3);
          if (c2 = u3 - o4 || Number(l3) - Number(a4), Math.sign(c2) === -f2) {
            const t4 = f2 < 0 && -e3.B(r3);
            s3 = (r3 -= f2) - n3, c2 = i3 - monthCodeNumberToMonth(o4, a4, e3.L(r3)) + (t4 || e3.B(r3));
          }
        }
      }
      return [s3, c2, u2];
    })(this, ...o2, ...r2);
    return 8 === t2 && (a2 += this.cn(i2, o2[0]), i2 = 0), {
      ...pr,
      years: i2,
      months: a2,
      days: s2
    };
  },
  F(e2, n2) {
    const t2 = mt(n2), o2 = refineYear(this, e2), r2 = refineMonth(this, e2, o2, t2), i2 = refineDay(this, e2, r2, o2, t2);
    return W(checkIsoDateInBounds(this.V(o2, r2, i2)), this.id || l);
  },
  K(e2, n2) {
    const t2 = mt(n2), o2 = refineYear(this, e2), r2 = refineMonth(this, e2, o2, t2);
    return createPlainYearMonthSlots(checkIsoYearMonthInBounds(this.V(o2, r2, 1)), this.id || l);
  },
  _(e2, n2) {
    const t2 = mt(n2);
    let o2, r2, i2, a2 = void 0 !== e2.eraYear || void 0 !== e2.year ? refineYear(this, e2) : void 0;
    const s2 = !this.id;
    if (void 0 === a2 && s2 && (a2 = Br), void 0 !== a2) {
      const n3 = refineMonth(this, e2, a2, t2);
      o2 = refineDay(this, e2, n3, a2, t2);
      const s3 = this.L(a2);
      r2 = monthToMonthCodeNumber(n3, s3), i2 = n3 === s3;
    } else {
      if (void 0 === e2.monthCode) {
        throw new TypeError(co);
      }
      if ([r2, i2] = parseMonthCode(e2.monthCode), this.id && this.id !== or && this.id !== rr) {
        if (this.id && "coptic" === computeCalendarIdBase(this.id) && 0 === t2) {
          const n3 = i2 || 13 !== r2 ? 30 : 6;
          o2 = e2.day, o2 = clampNumber(o2, 1, n3);
        } else if (this.id && "chinese" === computeCalendarIdBase(this.id) && 0 === t2) {
          const n3 = !i2 || 1 !== r2 && 9 !== r2 && 10 !== r2 && 11 !== r2 && 12 !== r2 ? 30 : 29;
          o2 = e2.day, o2 = clampNumber(o2, 1, n3);
        } else {
          o2 = e2.day;
        }
      } else {
        o2 = refineDay(this, e2, refineMonth(this, e2, Br, t2), Br, t2);
      }
    }
    const c2 = this.G(r2, i2, o2);
    if (!c2) {
      throw new RangeError("Cannot guess year");
    }
    const [u2, f2] = c2;
    return createPlainMonthDaySlots(checkIsoDateInBounds(this.V(u2, f2, o2)), this.id || l);
  },
  fields(e2) {
    return getCalendarEraOrigins(this) && e2.includes("year") ? [...e2, ...$o] : e2;
  },
  k(e2, n2) {
    const t2 = Object.assign(/* @__PURE__ */ Object.create(null), e2);
    return spliceFields(t2, n2, _o), getCalendarEraOrigins(this) && (spliceFields(t2, n2, Ho), this.id === rr && spliceFields(t2, n2, er, $o)), t2;
  },
  inLeapYear(e2) {
    const [n2] = this.v(e2);
    return this.sn(n2);
  },
  monthsInYear(e2) {
    const [n2] = this.v(e2);
    return this.B(n2);
  },
  daysInMonth(e2) {
    const [n2, t2] = this.v(e2);
    return this.U(n2, t2);
  },
  daysInYear(e2) {
    const [n2] = this.v(e2);
    return this.fn(n2);
  },
  dayOfYear: computeNativeDayOfYear,
  era(e2) {
    return this.hn(e2)[0];
  },
  eraYear(e2) {
    return this.hn(e2)[1];
  },
  monthCode(e2) {
    const [n2, t2] = this.v(e2), [o2, r2] = this.q(n2, t2);
    return formatMonthCode(o2, r2);
  },
  dayOfWeek: computeIsoDayOfWeek,
  daysInWeek() {
    return 7;
  }
};
var Ri = {
  v: computeIsoDateParts,
  hn: computeIsoEraParts,
  q: computeIsoMonthCodeParts
};
var Zi = {
  dayOfYear: computeNativeDayOfYear,
  v: computeIsoDateParts,
  p: isoArgsToEpochMilli
};
var zi = /* @__PURE__ */ Object.assign({}, Zi, {
  weekOfYear: computeNativeWeekOfYear,
  yearOfWeek: computeNativeYearOfWeek,
  m(e2) {
    function computeWeekShift(e3) {
      return (7 - e3 < n2 ? 7 : 0) - e3;
    }
    function computeWeeksInYear(e3) {
      const n3 = computeIsoDaysInYear(f2 + e3), t3 = e3 || 1, o3 = computeWeekShift(modFloor(a2 + n3 * t3, 7));
      return c2 = (n3 + (o3 - s2) * t3) / 7;
    }
    const n2 = this.id ? 1 : 4, t2 = computeIsoDayOfWeek(e2), o2 = this.dayOfYear(e2), r2 = modFloor(t2 - 1, 7), i2 = o2 - 1, a2 = modFloor(r2 - i2, 7), s2 = computeWeekShift(a2);
    let c2, u2 = Math.floor((i2 - s2) / 7) + 1, f2 = e2.isoYear;
    return u2 ? u2 > computeWeeksInYear(0) && (u2 = 1, f2++) : (u2 = computeWeeksInYear(-1), f2--), [u2, f2, c2];
  }
});
var Ui = /* @__PURE__ */ Object.assign({}, Yi, zi, {
  v: computeIsoDateParts,
  hn: computeIsoEraParts,
  q: computeIsoMonthCodeParts,
  G(e2, n2) {
    if (!n2) {
      return [Br, e2];
    }
  },
  sn: computeIsoInLeapYear,
  L() {
  },
  B: computeIsoMonthsInYear,
  cn: (e2) => e2 * kr,
  U: computeIsoDaysInMonth,
  fn: computeIsoDaysInYear,
  V: (e2, n2, t2) => ({
    isoYear: e2,
    isoMonth: n2,
    isoDay: t2
  }),
  p: isoArgsToEpochMilli,
  un: (e2, n2, t2) => (e2 += divTrunc(t2, kr), (n2 += modTrunc(t2, kr)) < 1 ? (e2--, n2 += kr) : n2 > kr && (e2++, n2 -= kr), [e2, n2]),
  year(e2) {
    return e2.isoYear;
  },
  month(e2) {
    return e2.isoMonth;
  },
  day: (e2) => e2.isoDay
});
var Ai = {
  v: computeIntlDateParts,
  hn: computeIntlEraParts,
  q: computeIntlMonthCodeParts
};
var qi = {
  dayOfYear: computeNativeDayOfYear,
  v: computeIntlDateParts,
  p: computeIntlEpochMilli,
  weekOfYear: computeNativeWeekOfYear,
  yearOfWeek: computeNativeYearOfWeek,
  m() {
    return [];
  }
};
var Wi = /* @__PURE__ */ Object.assign({}, Yi, qi, {
  v: computeIntlDateParts,
  hn: computeIntlEraParts,
  q: computeIntlMonthCodeParts,
  G(e2, n2, t2) {
    const o2 = this.id && "chinese" === computeCalendarIdBase(this.id) ? ((e3, n3, t3) => {
      if (n3) {
        switch (e3) {
          case 1:
            return 1651;
          case 2:
            return t3 < 30 ? 1947 : 1765;
          case 3:
            return t3 < 30 ? 1966 : 1955;
          case 4:
            return t3 < 30 ? 1963 : 1944;
          case 5:
            return t3 < 30 ? 1971 : 1952;
          case 6:
            return t3 < 30 ? 1960 : 1941;
          case 7:
            return t3 < 30 ? 1968 : 1938;
          case 8:
            return t3 < 30 ? 1957 : 1718;
          case 9:
            return 1832;
          case 10:
            return 1870;
          case 11:
            return 1814;
          case 12:
            return 1890;
        }
      }
      return 1972;
    })(e2, n2, t2) : Br;
    let [r2, i2, a2] = computeIntlDateParts.call(this, {
      isoYear: o2,
      isoMonth: kr,
      isoDay: 31
    });
    const s2 = computeIntlLeapMonth.call(this, r2), c2 = i2 === s2;
    1 === (compareNumbers(e2, monthToMonthCodeNumber(i2, s2)) || compareNumbers(Number(n2), Number(c2)) || compareNumbers(t2, a2)) && r2--;
    for (let o3 = 0; o3 < 100; o3++) {
      const i3 = r2 - o3, a3 = computeIntlLeapMonth.call(this, i3), s3 = monthCodeNumberToMonth(e2, n2, a3);
      if (n2 === (s3 === a3) && t2 <= computeIntlDaysInMonth.call(this, i3, s3)) {
        return [i3, s3];
      }
    }
  },
  sn(e2) {
    const n2 = computeIntlDaysInYear.call(this, e2);
    return n2 > computeIntlDaysInYear.call(this, e2 - 1) && n2 > computeIntlDaysInYear.call(this, e2 + 1);
  },
  L: computeIntlLeapMonth,
  B: computeIntlMonthsInYear,
  cn(e2, n2) {
    const t2 = n2 + e2, o2 = Math.sign(e2), r2 = o2 < 0 ? -1 : 0;
    let i2 = 0;
    for (let e3 = n2; e3 !== t2; e3 += o2) {
      i2 += computeIntlMonthsInYear.call(this, e3 + r2);
    }
    return i2;
  },
  U: computeIntlDaysInMonth,
  fn: computeIntlDaysInYear,
  V(e2, n2, t2) {
    return epochMilliToIso(computeIntlEpochMilli.call(this, e2, n2, t2));
  },
  p: computeIntlEpochMilli,
  un(e2, n2, t2) {
    if (t2) {
      if (n2 += t2, !Number.isSafeInteger(n2)) {
        throw new RangeError(Io);
      }
      if (t2 < 0) {
        for (; n2 < 1; ) {
          n2 += computeIntlMonthsInYear.call(this, --e2);
        }
      } else {
        let t3;
        for (; n2 > (t3 = computeIntlMonthsInYear.call(this, e2)); ) {
          n2 -= t3, e2++;
        }
      }
    }
    return [e2, n2];
  },
  year(e2) {
    return this.h(e2).year;
  },
  month(e2) {
    const { year: n2, o: t2 } = this.h(e2), { u: o2 } = this.l(n2);
    return o2[t2] + 1;
  },
  day(e2) {
    return this.h(e2).day;
  }
});
var ji = /* @__PURE__ */ createNativeOpsCreator(Ri, Ai);
var C = /* @__PURE__ */ createNativeOpsCreator(Ui, Wi);
var Li = {
  ...{
    era: toStringViaPrimitive,
    eraYear: toInteger,
    year: toInteger,
    month: toPositiveInteger,
    monthCode(e2) {
      const n2 = toStringViaPrimitive(e2);
      return parseMonthCode(n2), n2;
    },
    day: toPositiveInteger
  },
  .../* @__PURE__ */ wo(O, toInteger),
  .../* @__PURE__ */ wo(p, toStrictInteger),
  offset(e2) {
    const n2 = toStringViaPrimitive(e2);
    return parseOffsetNano(n2), n2;
  }
};
var xi = /* @__PURE__ */ Pt(remapProps, O, w);
var $i = /* @__PURE__ */ Pt(remapProps, w, O);
var Hi = "numeric";
var Gi = ["timeZoneName"];
var Vi = {
  month: Hi,
  day: Hi
};
var _i = {
  year: Hi,
  month: Hi
};
var Ji = /* @__PURE__ */ Object.assign({}, _i, {
  day: Hi
});
var Ki = {
  hour: Hi,
  minute: Hi,
  second: Hi
};
var Qi = /* @__PURE__ */ Object.assign({}, Ji, Ki);
var Xi = /* @__PURE__ */ Object.assign({}, Qi, {
  timeZoneName: "short"
});
var ea = /* @__PURE__ */ Object.keys(_i);
var na = /* @__PURE__ */ Object.keys(Vi);
var ta = /* @__PURE__ */ Object.keys(Ji);
var oa = /* @__PURE__ */ Object.keys(Ki);
var ra = ["dateStyle"];
var ia = /* @__PURE__ */ ea.concat(ra);
var aa = /* @__PURE__ */ na.concat(ra);
var sa = /* @__PURE__ */ ta.concat(ra, ["weekday"]);
var ca = /* @__PURE__ */ oa.concat(["dayPeriod", "timeStyle", "fractionalSecondDigits"]);
var ua = /* @__PURE__ */ sa.concat(ca);
var fa = /* @__PURE__ */ Gi.concat(ca);
var la = /* @__PURE__ */ Gi.concat(sa);
var da = /* @__PURE__ */ Gi.concat(["day", "weekday"], ca);
var ma = /* @__PURE__ */ Gi.concat(["year", "weekday"], ca);
var pa = /* @__PURE__ */ createOptionsTransformer(ua, Qi);
var ha = /* @__PURE__ */ createOptionsTransformer(ua, Xi);
var ga = /* @__PURE__ */ createOptionsTransformer(ua, Qi, Gi);
var Da = /* @__PURE__ */ createOptionsTransformer(sa, Ji, fa);
var Ta = /* @__PURE__ */ createOptionsTransformer(ca, Ki, la);
var Ia = /* @__PURE__ */ createOptionsTransformer(ia, _i, da);
var Ma = /* @__PURE__ */ createOptionsTransformer(aa, Vi, ma);
var Na = {};
var ya = new en(void 0, {
  calendar: l
}).resolvedOptions().calendar === l;
var U = [pa, I];
var ot = [ha, I, 0, (e2, n2) => {
  const t2 = e2.timeZone;
  if (n2 && n2.timeZone !== t2) {
    throw new RangeError(mo);
  }
  return t2;
}];
var X = [ga, isoToEpochMilli];
var _ = [Da, isoToEpochMilli];
var tt = [Ta, (e2) => isoTimeFieldsToNano(e2) / Qe];
var et = [Ia, isoToEpochMilli, ya];
var nt = [Ma, isoToEpochMilli, ya];
var va;

// src/typespec/node_modules/.pnpm/temporal-polyfill@0.3.0/node_modules/temporal-polyfill/chunks/classApi.js
function createSlotClass(i2, l2, s2, c2, u2) {
  function Class(...t2) {
    if (!(this instanceof Class)) {
      throw new TypeError(a);
    }
    un(this, l2(...t2));
  }
  function bindMethod(t2, e2) {
    return Object.defineProperties((function(...e3) {
      return t2.call(this, getSpecificSlots(this), ...e3);
    }), r(e2));
  }
  function getSpecificSlots(t2) {
    const e2 = cn(t2);
    if (!e2 || e2.branding !== i2) {
      throw new TypeError(a);
    }
    return e2;
  }
  return Object.defineProperties(Class.prototype, {
    ...t(e(bindMethod, s2)),
    ...n(e(bindMethod, c2)),
    ...o("Temporal." + i2)
  }), Object.defineProperties(Class, {
    ...n(u2),
    ...r(i2)
  }), [Class, (t2) => {
    const e2 = Object.create(Class.prototype);
    return un(e2, t2), e2;
  }, getSpecificSlots];
}
function rejectInvalidBag(t2) {
  if (cn(t2) || void 0 !== t2.calendar || void 0 !== t2.timeZone) {
    throw new TypeError(i);
  }
  return t2;
}
function getCalendarIdFromBag(t2) {
  return extractCalendarIdFromBag(t2) || l;
}
function extractCalendarIdFromBag(t2) {
  const { calendar: e2 } = t2;
  if (void 0 !== e2) {
    return refineCalendarArg(e2);
  }
}
function refineCalendarArg(t2) {
  if (s(t2)) {
    const { calendar: e2 } = cn(t2) || {};
    if (!e2) {
      throw new TypeError(c(t2));
    }
    return e2;
  }
  return ((t3) => u(f(m(t3))))(t2);
}
function createCalendarGetters(t2) {
  const e2 = {};
  for (const n2 in t2) {
    e2[n2] = (t3) => {
      const { calendar: e3 } = t3;
      return C(e3)[n2](t3);
    };
  }
  return e2;
}
function neverValueOf() {
  throw new TypeError(b);
}
function refineTimeZoneArg(t2) {
  if (s(t2)) {
    const { timeZone: e2 } = cn(t2) || {};
    if (!e2) {
      throw new TypeError(F(t2));
    }
    return e2;
  }
  return ((t3) => M(Z(m(t3))))(t2);
}
function toDurationSlots(t2) {
  if (s(t2)) {
    const e2 = cn(t2);
    return e2 && e2.branding === N ? e2 : q(t2);
  }
  return R(t2);
}
function refinePublicRelativeTo(t2) {
  if (void 0 !== t2) {
    if (s(t2)) {
      const e2 = cn(t2) || {};
      switch (e2.branding) {
        case z:
        case G:
          return e2;
        case x:
          return W(e2);
      }
      const n2 = getCalendarIdFromBag(t2);
      return {
        ...$(refineTimeZoneArg, L, C(n2), t2),
        calendar: n2
      };
    }
    return H(t2);
  }
}
function toPlainTimeSlots(t2, e2) {
  if (s(t2)) {
    const n3 = cn(t2) || {};
    switch (n3.branding) {
      case ft:
        return mt(e2), n3;
      case x:
        return mt(e2), St(n3);
      case z:
        return mt(e2), dt(L, n3);
    }
    return Tt(t2, e2);
  }
  const n2 = ht(t2);
  return mt(e2), n2;
}
function optionalToPlainTimeFields(t2) {
  return void 0 === t2 ? void 0 : toPlainTimeSlots(t2);
}
function toPlainDateTimeSlots(t2, e2) {
  if (s(t2)) {
    const n3 = cn(t2) || {};
    switch (n3.branding) {
      case x:
        return mt(e2), n3;
      case G:
        return mt(e2), jt({
          ...n3,
          ...Nt
        });
      case z:
        return mt(e2), yt(L, n3);
    }
    return At(C(getCalendarIdFromBag(t2)), t2, e2);
  }
  const n2 = Bt(t2);
  return mt(e2), n2;
}
function toPlainMonthDaySlots(t2, e2) {
  if (s(t2)) {
    const n3 = cn(t2);
    if (n3 && n3.branding === qt) {
      return mt(e2), n3;
    }
    const o2 = extractCalendarIdFromBag(t2);
    return Rt(C(o2 || l), !o2, t2, e2);
  }
  const n2 = xt(C, t2);
  return mt(e2), n2;
}
function toPlainYearMonthSlots(t2, e2) {
  if (s(t2)) {
    const n3 = cn(t2);
    return n3 && n3.branding === Ut ? (mt(e2), n3) : Xt(C(getCalendarIdFromBag(t2)), t2, e2);
  }
  const n2 = _t(C, t2);
  return mt(e2), n2;
}
function toPlainDateSlots(t2, e2) {
  if (s(t2)) {
    const n3 = cn(t2) || {};
    switch (n3.branding) {
      case G:
        return mt(e2), n3;
      case x:
        return mt(e2), W(n3);
      case z:
        return mt(e2), fe(L, n3);
    }
    return me(C(getCalendarIdFromBag(t2)), t2, e2);
  }
  const n2 = de(t2);
  return mt(e2), n2;
}
function toZonedDateTimeSlots(t2, e2) {
  if (s(t2)) {
    const n2 = cn(t2);
    if (n2 && n2.branding === z) {
      return je(e2), n2;
    }
    const o2 = getCalendarIdFromBag(t2);
    return Ne(refineTimeZoneArg, L, C(o2), o2, t2, e2);
  }
  return Ae(t2, e2);
}
function adaptDateMethods(t2) {
  return e(((t3) => (e2) => t3(slotsToIso(e2))), t2);
}
function slotsToIso(t2) {
  return he(t2, L);
}
function toInstantSlots(t2) {
  if (s(t2)) {
    const e2 = cn(t2);
    if (e2) {
      switch (e2.branding) {
        case Re:
          return e2;
        case z:
          return xe(e2.epochNanoseconds);
      }
    }
  }
  return We(t2);
}
function createDateTimeFormatClass() {
  function DateTimeFormatFunc(t3, e3) {
    return new DateTimeFormatNew(t3, e3);
  }
  function DateTimeFormatNew(t3, e3 = /* @__PURE__ */ Object.create(null)) {
    to.set(this, ((t4, e4) => {
      const n3 = new en(t4, e4), o2 = n3.resolvedOptions(), r2 = o2.locale, a2 = nn(Object.keys(e4), o2), i2 = on(createFormatPrepperForBranding), prepFormat = (t5, ...e5) => {
        if (t5) {
          if (2 !== e5.length) {
            throw new TypeError(ln);
          }
          for (const t6 of e5) {
            if (void 0 === t6) {
              throw new TypeError(ln);
            }
          }
        }
        t5 || void 0 !== e5[0] || (e5 = []);
        const o3 = e5.map(((t6) => cn(t6) || Number(t6)));
        let l2, s2 = 0;
        for (const t6 of o3) {
          const e6 = "object" == typeof t6 ? t6.branding : void 0;
          if (s2++ && e6 !== l2) {
            throw new TypeError(ln);
          }
          l2 = e6;
        }
        return l2 ? i2(l2)(r2, a2, ...o3) : [n3, ...o3];
      };
      return prepFormat.X = n3, prepFormat;
    })(t3, e3));
  }
  const t2 = en.prototype, e2 = Object.getOwnPropertyDescriptors(t2), n2 = Object.getOwnPropertyDescriptors(en);
  for (const t3 in e2) {
    const n3 = e2[t3], o2 = t3.startsWith("format") && createFormatMethod(t3);
    "function" == typeof n3.value ? n3.value = "constructor" === t3 ? DateTimeFormatFunc : o2 || createProxiedMethod(t3) : o2 && (n3.get = function() {
      if (!to.has(this)) {
        throw new TypeError(a);
      }
      return (...t4) => o2.apply(this, t4);
    }, Object.defineProperties(n3.get, r(`get ${t3}`)));
  }
  return n2.prototype.value = DateTimeFormatNew.prototype = Object.create({}, e2), Object.defineProperties(DateTimeFormatFunc, n2), DateTimeFormatFunc;
}
function createFormatMethod(t2) {
  return Object.defineProperties((function(...e2) {
    const n2 = to.get(this), [o2, ...r2] = n2(t2.includes("Range"), ...e2);
    return o2[t2](...r2);
  }), r(t2));
}
function createProxiedMethod(t2) {
  return Object.defineProperties((function(...e2) {
    return to.get(this).X[t2](...e2);
  }), r(t2));
}
function createFormatPrepperForBranding(t2) {
  const e2 = Cn[t2];
  if (!e2) {
    throw new TypeError(rn(t2));
  }
  return Q(e2, on(an), 1);
}
var sn = /* @__PURE__ */ new WeakMap();
var cn = /* @__PURE__ */ sn.get.bind(sn);
var un = /* @__PURE__ */ sn.set.bind(sn);
var fn = {
  era: d,
  eraYear: S,
  year: T,
  month: h,
  daysInMonth: h,
  daysInYear: h,
  inLeapYear: D,
  monthsInYear: h
};
var mn = {
  monthCode: m
};
var dn = {
  day: h
};
var Sn = {
  dayOfWeek: h,
  dayOfYear: h,
  weekOfYear: P,
  yearOfWeek: S,
  daysInWeek: h
};
var Tn = /* @__PURE__ */ createCalendarGetters(/* @__PURE__ */ Object.assign({}, fn, mn, dn, Sn));
var hn = /* @__PURE__ */ createCalendarGetters({
  ...fn,
  ...mn
});
var Dn = /* @__PURE__ */ createCalendarGetters({
  ...mn,
  ...dn
});
var Pn = {
  calendarId: (t2) => t2.calendar
};
var gn = /* @__PURE__ */ g(((t2) => (e2) => e2[t2]), p.concat("sign"));
var pn = /* @__PURE__ */ g(((t2, e2) => (t3) => t3[w[e2]]), O);
var On = {
  epochMilliseconds: I,
  epochNanoseconds: v
};
var [wn, In, vn] = createSlotClass(N, j, {
  ...gn,
  blank: y
}, {
  with: (t2, e2) => In(A(t2, e2)),
  negated: (t2) => In(B(t2)),
  abs: (t2) => In(Y(t2)),
  add: (t2, e2, n2) => In(E(refinePublicRelativeTo, C, L, 0, t2, toDurationSlots(e2), n2)),
  subtract: (t2, e2, n2) => In(E(refinePublicRelativeTo, C, L, 1, t2, toDurationSlots(e2), n2)),
  round: (t2, e2) => In(V(refinePublicRelativeTo, C, L, t2, e2)),
  total: (t2, e2) => J(refinePublicRelativeTo, C, L, t2, e2),
  toLocaleString(t2, e2, n2) {
    return Intl.DurationFormat ? new Intl.DurationFormat(e2, n2).format(this) : k(t2);
  },
  toString: k,
  toJSON: (t2) => k(t2),
  valueOf: neverValueOf
}, {
  from: (t2) => In(toDurationSlots(t2)),
  compare: (t2, e2, n2) => K(refinePublicRelativeTo, C, L, toDurationSlots(t2), toDurationSlots(e2), n2)
});
var Cn = {
  Instant: U,
  PlainDateTime: X,
  PlainDate: _,
  PlainTime: tt,
  PlainYearMonth: et,
  PlainMonthDay: nt
};
var bn = /* @__PURE__ */ Q(U);
var Fn = /* @__PURE__ */ Q(ot);
var Mn = /* @__PURE__ */ Q(X);
var Zn = /* @__PURE__ */ Q(_);
var yn = /* @__PURE__ */ Q(tt);
var jn = /* @__PURE__ */ Q(et);
var Nn = /* @__PURE__ */ Q(nt);
var [An, Bn] = createSlotClass(ft, ut, pn, {
  with(t2, e2, n2) {
    return Bn(rt(this, rejectInvalidBag(e2), n2));
  },
  add: (t2, e2) => Bn(at(0, t2, toDurationSlots(e2))),
  subtract: (t2, e2) => Bn(at(1, t2, toDurationSlots(e2))),
  until: (t2, e2, n2) => In(it(0, t2, toPlainTimeSlots(e2), n2)),
  since: (t2, e2, n2) => In(it(1, t2, toPlainTimeSlots(e2), n2)),
  round: (t2, e2) => Bn(lt(t2, e2)),
  equals: (t2, e2) => st(t2, toPlainTimeSlots(e2)),
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = yn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: ct,
  toJSON: (t2) => ct(t2),
  valueOf: neverValueOf
}, {
  from: (t2, e2) => Bn(toPlainTimeSlots(t2, e2)),
  compare: (t2, e2) => Dt(toPlainTimeSlots(t2), toPlainTimeSlots(e2))
});
var [Yn, En] = createSlotClass(x, Pt(Zt, Mt), {
  ...Pn,
  ...Tn,
  ...pn
}, {
  with: (t2, e2, n2) => En(gt(C, t2, rejectInvalidBag(e2), n2)),
  withCalendar: (t2, e2) => En(pt(t2, refineCalendarArg(e2))),
  withPlainTime: (t2, e2) => En(Ot(t2, optionalToPlainTimeFields(e2))),
  add: (t2, e2, n2) => En(wt(C, 0, t2, toDurationSlots(e2), n2)),
  subtract: (t2, e2, n2) => En(wt(C, 1, t2, toDurationSlots(e2), n2)),
  until: (t2, e2, n2) => In(It(C, 0, t2, toPlainDateTimeSlots(e2), n2)),
  since: (t2, e2, n2) => In(It(C, 1, t2, toPlainDateTimeSlots(e2), n2)),
  round: (t2, e2) => En(vt(t2, e2)),
  equals: (t2, e2) => Ct(t2, toPlainDateTimeSlots(e2)),
  toZonedDateTime: (t2, e2, n2) => $n(bt(L, t2, refineTimeZoneArg(e2), n2)),
  toPlainDate: (t2) => Wn(W(t2)),
  toPlainTime: (t2) => Bn(St(t2)),
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = Mn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: Ft,
  toJSON: (t2) => Ft(t2),
  valueOf: neverValueOf
}, {
  from: (t2, e2) => En(toPlainDateTimeSlots(t2, e2)),
  compare: (t2, e2) => Yt(toPlainDateTimeSlots(t2), toPlainDateTimeSlots(e2))
});
var [Ln, Vn, Jn] = createSlotClass(qt, Pt(kt, Mt), {
  ...Pn,
  ...Dn
}, {
  with: (t2, e2, n2) => Vn(Et(C, t2, rejectInvalidBag(e2), n2)),
  equals: (t2, e2) => Lt(t2, toPlainMonthDaySlots(e2)),
  toPlainDate(t2, e2) {
    return Wn(Vt(C, t2, this, e2));
  },
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = Nn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: Jt,
  toJSON: (t2) => Jt(t2),
  valueOf: neverValueOf
}, {
  from: (t2, e2) => Vn(toPlainMonthDaySlots(t2, e2))
});
var [kn, qn, Rn] = createSlotClass(Ut, Pt(Qt, Mt), {
  ...Pn,
  ...hn
}, {
  with: (t2, e2, n2) => qn(Wt(C, t2, rejectInvalidBag(e2), n2)),
  add: (t2, e2, n2) => qn(Gt(C, 0, t2, toDurationSlots(e2), n2)),
  subtract: (t2, e2, n2) => qn(Gt(C, 1, t2, toDurationSlots(e2), n2)),
  until: (t2, e2, n2) => In(zt(C, 0, t2, toPlainYearMonthSlots(e2), n2)),
  since: (t2, e2, n2) => In(zt(C, 1, t2, toPlainYearMonthSlots(e2), n2)),
  equals: (t2, e2) => $t(t2, toPlainYearMonthSlots(e2)),
  toPlainDate(t2, e2) {
    return Wn(Ht(C, t2, this, e2));
  },
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = jn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: Kt,
  toJSON: (t2) => Kt(t2),
  valueOf: neverValueOf
}, {
  from: (t2, e2) => qn(toPlainYearMonthSlots(t2, e2)),
  compare: (t2, e2) => te(toPlainYearMonthSlots(t2), toPlainYearMonthSlots(e2))
});
var [xn, Wn, Gn] = createSlotClass(G, Pt(ue, Mt), {
  ...Pn,
  ...Tn
}, {
  with: (t2, e2, n2) => Wn(ee(C, t2, rejectInvalidBag(e2), n2)),
  withCalendar: (t2, e2) => Wn(pt(t2, refineCalendarArg(e2))),
  add: (t2, e2, n2) => Wn(ne(C, 0, t2, toDurationSlots(e2), n2)),
  subtract: (t2, e2, n2) => Wn(ne(C, 1, t2, toDurationSlots(e2), n2)),
  until: (t2, e2, n2) => In(oe(C, 0, t2, toPlainDateSlots(e2), n2)),
  since: (t2, e2, n2) => In(oe(C, 1, t2, toPlainDateSlots(e2), n2)),
  equals: (t2, e2) => re(t2, toPlainDateSlots(e2)),
  toZonedDateTime(t2, e2) {
    const n2 = s(e2) ? e2 : {
      timeZone: e2
    };
    return $n(ae(refineTimeZoneArg, toPlainTimeSlots, L, t2, n2));
  },
  toPlainDateTime: (t2, e2) => En(ie(t2, optionalToPlainTimeFields(e2))),
  toPlainYearMonth(t2) {
    return qn(le(C, t2, this));
  },
  toPlainMonthDay(t2) {
    return Vn(se(C, t2, this));
  },
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = Zn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: ce,
  toJSON: (t2) => ce(t2),
  valueOf: neverValueOf
}, {
  from: (t2, e2) => Wn(toPlainDateSlots(t2, e2)),
  compare: (t2, e2) => te(toPlainDateSlots(t2), toPlainDateSlots(e2))
});
var [zn, $n] = createSlotClass(z, Pt(ye, Mt, Ze), {
  ...On,
  ...Pn,
  ...adaptDateMethods(Tn),
  ...adaptDateMethods(pn),
  offset: (t2) => Se(slotsToIso(t2).offsetNanoseconds),
  offsetNanoseconds: (t2) => slotsToIso(t2).offsetNanoseconds,
  timeZoneId: (t2) => t2.timeZone,
  hoursInDay: (t2) => Te(L, t2)
}, {
  with: (t2, e2, n2) => $n(De(C, L, t2, rejectInvalidBag(e2), n2)),
  withCalendar: (t2, e2) => $n(pt(t2, refineCalendarArg(e2))),
  withTimeZone: (t2, e2) => $n(Pe(t2, refineTimeZoneArg(e2))),
  withPlainTime: (t2, e2) => $n(ge(L, t2, optionalToPlainTimeFields(e2))),
  add: (t2, e2, n2) => $n(pe(C, L, 0, t2, toDurationSlots(e2), n2)),
  subtract: (t2, e2, n2) => $n(pe(C, L, 1, t2, toDurationSlots(e2), n2)),
  until: (t2, e2, n2) => In(Oe(we(C, L, 0, t2, toZonedDateTimeSlots(e2), n2))),
  since: (t2, e2, n2) => In(Oe(we(C, L, 1, t2, toZonedDateTimeSlots(e2), n2))),
  round: (t2, e2) => $n(Ie(L, t2, e2)),
  startOfDay: (t2) => $n(ve(L, t2)),
  equals: (t2, e2) => Ce(t2, toZonedDateTimeSlots(e2)),
  toInstant: (t2) => Kn(be(t2)),
  toPlainDateTime: (t2) => En(yt(L, t2)),
  toPlainDate: (t2) => Wn(fe(L, t2)),
  toPlainTime: (t2) => Bn(dt(L, t2)),
  toLocaleString(t2, e2, n2 = {}) {
    const [o2, r2] = Fn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: (t2, e2) => Fe(L, t2, e2),
  toJSON: (t2) => Fe(L, t2),
  valueOf: neverValueOf,
  getTimeZoneTransition(t2, e2) {
    const { timeZone: n2, epochNanoseconds: o2 } = t2, r2 = Me(e2), a2 = L(n2).O(o2, r2);
    return a2 ? $n({
      ...t2,
      epochNanoseconds: a2
    }) : null;
  }
}, {
  from: (t2, e2) => $n(toZonedDateTimeSlots(t2, e2)),
  compare: (t2, e2) => Be(toZonedDateTimeSlots(t2), toZonedDateTimeSlots(e2))
});
var [Hn, Kn, Qn] = createSlotClass(Re, qe, On, {
  add: (t2, e2) => Kn(Ye(0, t2, toDurationSlots(e2))),
  subtract: (t2, e2) => Kn(Ye(1, t2, toDurationSlots(e2))),
  until: (t2, e2, n2) => In(Ee(0, t2, toInstantSlots(e2), n2)),
  since: (t2, e2, n2) => In(Ee(1, t2, toInstantSlots(e2), n2)),
  round: (t2, e2) => Kn(Le(t2, e2)),
  equals: (t2, e2) => Ve(t2, toInstantSlots(e2)),
  toZonedDateTimeISO: (t2, e2) => $n(Je(t2, refineTimeZoneArg(e2))),
  toLocaleString(t2, e2, n2) {
    const [o2, r2] = bn(e2, n2, t2);
    return o2.format(r2);
  },
  toString: (t2, e2) => ke(refineTimeZoneArg, L, t2, e2),
  toJSON: (t2) => ke(refineTimeZoneArg, L, t2),
  valueOf: neverValueOf
}, {
  from: (t2) => Kn(toInstantSlots(t2)),
  fromEpochMilliseconds: (t2) => Kn($e(t2)),
  fromEpochNanoseconds: (t2) => Kn(He(t2)),
  compare: (t2, e2) => Ke(toInstantSlots(t2), toInstantSlots(e2))
});
var Un = /* @__PURE__ */ Object.defineProperties({}, {
  ...o("Temporal.Now"),
  ...n({
    timeZoneId: () => Ue(),
    instant: () => Kn(xe(Xe())),
    zonedDateTimeISO: (t2 = Ue()) => $n(_e(Xe(), refineTimeZoneArg(t2), l)),
    plainDateTimeISO: (t2 = Ue()) => En(jt(tn(L(refineTimeZoneArg(t2))), l)),
    plainDateISO: (t2 = Ue()) => Wn(W(tn(L(refineTimeZoneArg(t2))), l)),
    plainTimeISO: (t2 = Ue()) => Bn(St(tn(L(refineTimeZoneArg(t2)))))
  })
});
var Xn = /* @__PURE__ */ Object.defineProperties({}, {
  ...o("Temporal"),
  ...n({
    PlainYearMonth: kn,
    PlainMonthDay: Ln,
    PlainDate: xn,
    PlainTime: An,
    PlainDateTime: Yn,
    ZonedDateTime: zn,
    Instant: Hn,
    Duration: wn,
    Now: Un
  })
});
var _n = /* @__PURE__ */ createDateTimeFormatClass();
var to = /* @__PURE__ */ new WeakMap();
var eo = /* @__PURE__ */ Object.defineProperties(Object.create(Intl), n({
  DateTimeFormat: _n
}));

// src/typespec/core/packages/compiler/dist/src/core/semantic-walker.js
var defaultOptions = {
  includeTemplateDeclaration: false
};
function navigateProgram(program, listeners, options = {}) {
  const context = createNavigationContext(listeners, options);
  context.emit("root", program);
  navigateNamespaceType(program.getGlobalNamespaceType(), context);
}
function navigateType(type, listeners, options) {
  const context = createNavigationContext(listeners, options);
  navigateTypeInternal(type, context);
}
function scopeNavigationToNamespace(namespace, listeners, options = {}) {
  const wrappedListeners = {};
  for (const [name, callback] of Object.entries(listeners)) {
    wrappedListeners[name] = (x2) => {
      if (x2 !== namespace && "namespace" in x2) {
        if (options.skipSubNamespaces && x2.namespace !== namespace) {
          return ListenerFlow.NoRecursion;
        }
        if (x2.namespace && !isSubNamespace(x2.namespace, namespace)) {
          return ListenerFlow.NoRecursion;
        }
      }
      return callback(x2);
    };
  }
  return wrappedListeners;
}
function navigateTypesInNamespace(namespace, listeners, options = {}) {
  navigateType(namespace, scopeNavigationToNamespace(namespace, listeners, options), options);
}
function mapEventEmitterToNodeListener(eventEmitter) {
  const listener = {};
  for (const eventName of eventNames) {
    listener[eventName] = (...args) => {
      eventEmitter.emit(eventName, ...args);
    };
  }
  return listener;
}
function isSubNamespace(subNamespace, namespace) {
  let current = subNamespace;
  while (current !== void 0) {
    if (current === namespace) {
      return true;
    }
    current = current.namespace;
  }
  return false;
}
function createNavigationContext(listeners, options = {}) {
  return {
    visited: /* @__PURE__ */ new Set(),
    emit: (key, ...args) => listeners[key]?.(...args),
    options: computeOptions(options)
  };
}
function computeOptions(options) {
  return { ...defaultOptions, ...options };
}
function navigateNamespaceType(namespace, context) {
  if (context.emit("namespace", namespace) === ListenerFlow.NoRecursion)
    return;
  for (const model of namespace.models.values()) {
    navigateModelType(model, context);
  }
  for (const scalar of namespace.scalars.values()) {
    navigateScalarType(scalar, context);
  }
  for (const operation of namespace.operations.values()) {
    navigateOperationType(operation, context);
  }
  for (const subNamespace of namespace.namespaces.values()) {
    if (!(namespace.name === "TypeSpec" && subNamespace.name === "Prototypes")) {
      navigateNamespaceType(subNamespace, context);
    }
  }
  for (const union of namespace.unions.values()) {
    navigateUnionType(union, context);
  }
  for (const iface of namespace.interfaces.values()) {
    navigateInterfaceType(iface, context);
  }
  for (const enumType of namespace.enums.values()) {
    navigateEnumType(enumType, context);
  }
  for (const decorator of namespace.decoratorDeclarations.values()) {
    navigateDecoratorDeclaration(decorator, context);
  }
  context.emit("exitNamespace", namespace);
}
function checkVisited(visited, item) {
  if (visited.has(item)) {
    return true;
  }
  visited.add(item);
  return false;
}
function shouldNavigateTemplatableType(context, type) {
  if (context.options.includeTemplateDeclaration) {
    return type.isFinished || isTemplateDeclaration(type);
  } else {
    return type.isFinished;
  }
}
function navigateOperationType(operation, context) {
  if (checkVisited(context.visited, operation)) {
    return;
  }
  if (!shouldNavigateTemplatableType(context, operation)) {
    return;
  }
  if (context.emit("operation", operation) === ListenerFlow.NoRecursion)
    return;
  for (const parameter of operation.parameters.properties.values()) {
    navigateTypeInternal(parameter, context);
  }
  navigateTypeInternal(operation.returnType, context);
  if (operation.sourceOperation) {
    navigateTypeInternal(operation.sourceOperation, context);
  }
  context.emit("exitOperation", operation);
}
function navigateModelType(model, context) {
  if (checkVisited(context.visited, model)) {
    return;
  }
  if (!shouldNavigateTemplatableType(context, model)) {
    return;
  }
  if (context.emit("model", model) === ListenerFlow.NoRecursion)
    return;
  for (const property of model.properties.values()) {
    navigateModelTypeProperty(property, context);
  }
  if (model.baseModel) {
    navigateModelType(model.baseModel, context);
  }
  if (model.indexer && model.indexer.value) {
    navigateTypeInternal(model.indexer.value, context);
  }
  if (context.options.visitDerivedTypes) {
    for (const derived of model.derivedModels) {
      navigateModelType(derived, context);
    }
  }
  context.emit("exitModel", model);
}
function navigateModelTypeProperty(property, context) {
  if (checkVisited(context.visited, property)) {
    return;
  }
  if (context.emit("modelProperty", property) === ListenerFlow.NoRecursion)
    return;
  navigateTypeInternal(property.type, context);
  context.emit("exitModelProperty", property);
}
function navigateScalarType(scalar, context) {
  if (checkVisited(context.visited, scalar)) {
    return;
  }
  if (context.emit("scalar", scalar) === ListenerFlow.NoRecursion)
    return;
  if (scalar.baseScalar) {
    navigateScalarType(scalar.baseScalar, context);
  }
  for (const constructor of scalar.constructors.values()) {
    navigateScalarConstructor(constructor, context);
  }
  context.emit("exitScalar", scalar);
}
function navigateInterfaceType(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (!shouldNavigateTemplatableType(context, type)) {
    return;
  }
  context.emit("interface", type);
  for (const op of type.operations.values()) {
    navigateOperationType(op, context);
  }
  context.emit("exitInterface", type);
}
function navigateEnumType(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  context.emit("enum", type);
  for (const member of type.members.values()) {
    navigateTypeInternal(member, context);
  }
  context.emit("exitEnum", type);
}
function navigateUnionType(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (!shouldNavigateTemplatableType(context, type)) {
    return;
  }
  if (context.emit("union", type) === ListenerFlow.NoRecursion)
    return;
  for (const variant of type.variants.values()) {
    navigateUnionTypeVariant(variant, context);
  }
  context.emit("exitUnion", type);
}
function navigateUnionTypeVariant(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("unionVariant", type) === ListenerFlow.NoRecursion)
    return;
  navigateTypeInternal(type.type, context);
  context.emit("exitUnionVariant", type);
}
function navigateTupleType(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("tuple", type) === ListenerFlow.NoRecursion)
    return;
  for (const value of type.values) {
    navigateTypeInternal(value, context);
  }
  context.emit("exitTuple", type);
}
function navigateStringTemplate(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("stringTemplate", type) === ListenerFlow.NoRecursion)
    return;
  for (const value of type.spans) {
    navigateTypeInternal(value, context);
  }
}
function navigateStringTemplateSpan(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("stringTemplateSpan", type) === ListenerFlow.NoRecursion)
    return;
  navigateTypeInternal(type.type, context);
}
function navigateTemplateParameter(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("templateParameter", type) === ListenerFlow.NoRecursion)
    return;
}
function navigateDecoratorDeclaration(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("decorator", type) === ListenerFlow.NoRecursion)
    return;
}
function navigateScalarConstructor(type, context) {
  if (checkVisited(context.visited, type)) {
    return;
  }
  if (context.emit("scalarConstructor", type) === ListenerFlow.NoRecursion)
    return;
}
function navigateTypeInternal(type, context) {
  switch (type.kind) {
    case "Model":
      return navigateModelType(type, context);
    case "Scalar":
      return navigateScalarType(type, context);
    case "ModelProperty":
      return navigateModelTypeProperty(type, context);
    case "Namespace":
      return navigateNamespaceType(type, context);
    case "Interface":
      return navigateInterfaceType(type, context);
    case "Enum":
      return navigateEnumType(type, context);
    case "Operation":
      return navigateOperationType(type, context);
    case "Union":
      return navigateUnionType(type, context);
    case "UnionVariant":
      return navigateUnionTypeVariant(type, context);
    case "Tuple":
      return navigateTupleType(type, context);
    case "StringTemplate":
      return navigateStringTemplate(type, context);
    case "StringTemplateSpan":
      return navigateStringTemplateSpan(type, context);
    case "TemplateParameter":
      return navigateTemplateParameter(type, context);
    case "Decorator":
      return navigateDecoratorDeclaration(type, context);
    case "ScalarConstructor":
      return navigateScalarConstructor(type, context);
    case "FunctionParameter":
    case "Boolean":
    case "EnumMember":
    case "Intrinsic":
    case "Number":
    case "String":
      return;
    default:
      const _assertNever = type;
      return;
  }
}
function getProperty(type, propertyName) {
  while (type.baseModel) {
    if (type.properties.has(propertyName)) {
      return type.properties.get(propertyName);
    }
    type = type.baseModel;
  }
  return type.properties.get(propertyName);
}
var EventEmitter = class {
  listeners = /* @__PURE__ */ new Map();
  on(name, listener) {
    const array = this.listeners.get(name);
    if (array) {
      array.push(listener);
    } else {
      this.listeners.set(name, [listener]);
    }
  }
  emit(name, ...args) {
    const listeners = this.listeners.get(name);
    if (listeners) {
      for (const listener of listeners) {
        listener(...args);
      }
    }
  }
};
var eventNames = [
  "root",
  "templateParameter",
  "exitTemplateParameter",
  "scalar",
  "exitScalar",
  "model",
  "exitModel",
  "modelProperty",
  "exitModelProperty",
  "interface",
  "exitInterface",
  "enum",
  "exitEnum",
  "enumMember",
  "exitEnumMember",
  "namespace",
  "exitNamespace",
  "operation",
  "exitOperation",
  "string",
  "exitString",
  "number",
  "exitNumber",
  "boolean",
  "exitBoolean",
  "tuple",
  "exitTuple",
  "union",
  "exitUnion",
  "unionVariant",
  "exitUnionVariant",
  "intrinsic",
  "exitIntrinsic"
];

// src/typespec/core/packages/compiler/dist/src/lib/examples.js
function serializeValueAsJson(program, value, type, encodeAs) {
  if (type.kind === "ModelProperty") {
    return serializeValueAsJson(program, value, type.type, encodeAs ?? getEncode(program, type));
  }
  switch (value.valueKind) {
    case "NullValue":
      return null;
    case "BooleanValue":
    case "StringValue":
      return value.value;
    case "NumericValue":
      return value.value.asNumber();
    case "EnumValue":
      return value.value.value ?? value.value.name;
    case "ArrayValue":
      return value.values.map((v2) => serializeValueAsJson(program, v2, type.kind === "Model" && isArrayModelType(program, type) ? type.indexer.value : program.checker.anyType));
    case "ObjectValue":
      return serializeObjectValueAsJson(program, value, type);
    case "ScalarValue":
      return serializeScalarValueAsJson(program, value, type, encodeAs);
  }
}
function getPropertyOfType(type, name) {
  switch (type.kind) {
    case "Model":
      return getProperty(type, name) ?? type.indexer?.value;
    case "Intrinsic":
      if (isUnknownType(type)) {
        return type;
      } else {
        return;
      }
    default:
      return void 0;
  }
}
function resolveUnions(program, value, type) {
  if (type.kind !== "Union") {
    return type;
  }
  const exactValueType = program.checker.getValueExactType(value);
  for (const variant of type.variants.values()) {
    if (ignoreDiagnostics(program.checker.isTypeAssignableTo(exactValueType ?? value.type, variant.type, value))) {
      return variant.type;
    }
  }
  return type;
}
function serializeObjectValueAsJson(program, value, type) {
  type = resolveUnions(program, value, type) ?? type;
  const obj = {};
  for (const propValue of value.properties.values()) {
    const definition = getPropertyOfType(type, propValue.name);
    if (definition) {
      const name = definition.kind === "ModelProperty" ? resolveEncodedName(program, definition, "application/json") : propValue.name;
      obj[name] = serializeValueAsJson(program, propValue.value, definition);
    }
  }
  return obj;
}
function resolveKnownScalar(program, scalar) {
  const encode = getEncode(program, scalar);
  if (program.checker.isStdType(scalar)) {
    switch (scalar.name) {
      case "utcDateTime":
      case "offsetDateTime":
      case "plainDate":
      case "plainTime":
      case "duration":
        return { scalar, encodeAs: encode };
      case "unixTimestamp32":
        break;
      default:
        return void 0;
    }
  }
  if (scalar.baseScalar) {
    const result = resolveKnownScalar(program, scalar.baseScalar);
    return result && { scalar: result.scalar, encodeAs: encode };
  }
  return void 0;
}
function serializeScalarValueAsJson(program, value, type, encodeAs) {
  const result = resolveKnownScalar(program, value.scalar);
  if (result === void 0) {
    return serializeValueAsJson(program, value.value.args[0], value.value.args[0].type);
  }
  encodeAs = encodeAs ?? result.encodeAs;
  switch (result.scalar.name) {
    case "utcDateTime":
      return ScalarSerializers.utcDateTime(value.value.args[0].value, encodeAs);
    case "offsetDateTime":
      return ScalarSerializers.offsetDateTime(value.value.args[0].value, encodeAs);
    case "plainDate":
      return ScalarSerializers.plainDate(value.value.args[0].value);
    case "plainTime":
      return ScalarSerializers.plainTime(value.value.args[0].value);
    case "duration":
      return ScalarSerializers.duration(value.value.args[0].value, encodeAs);
  }
}
var ScalarSerializers = {
  utcDateTime: (value, encodeAs) => {
    if (encodeAs === void 0 || encodeAs.encoding === "rfc3339") {
      return value;
    }
    const date = new Date(value);
    switch (encodeAs.encoding) {
      case "unixTimestamp":
        return Math.floor(date.getTime() / 1e3);
      case "rfc7231":
        return date.toUTCString();
      default:
        return date.toISOString();
    }
  },
  offsetDateTime: (value, encodeAs) => {
    if (encodeAs === void 0 || encodeAs.encoding === "rfc3339") {
      return value;
    }
    const date = new Date(value);
    switch (encodeAs.encoding) {
      case "rfc7231":
        return date.toUTCString();
      default:
        return date.toISOString();
    }
  },
  plainDate: (value) => {
    return value;
  },
  plainTime: (value) => {
    return value;
  },
  duration: (value, encodeAs) => {
    const duration = Xn.Duration.from(value);
    switch (encodeAs?.encoding) {
      case "seconds":
        if (isInteger(encodeAs.type)) {
          return Math.floor(duration.total({ unit: "seconds" }));
        } else {
          return duration.total({ unit: "seconds" });
        }
      default:
        return duration.toString();
    }
  }
};
function isInteger(scalar) {
  while (scalar.baseScalar) {
    scalar = scalar.baseScalar;
    if (scalar.name === "integer") {
      return true;
    }
  }
  return false;
}

// src/typespec/core/packages/compiler/dist/src/lib/paging.js
var [
  /**
   * Check if the given operation is used to page through a list.
   * @param program Program
   * @param target Operation
   */
  isList,
  markList,
  /** {@inheritdoc ListDecorator} */
  listDecorator
] = createMarkerDecorator("list");
var [
  /**
   * Check if the given property is the `@offset` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isOffsetProperty,
  markOffset,
  /** {@inheritdoc OffsetDecorator} */
  offsetDecorator
] = createMarkerDecorator("offset", createNumericValidation("offset"));
var [
  /**
   * Check if the given property is the `@pageIndex` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isPageIndexProperty,
  markPageIndexProperty,
  /** {@inheritdoc PageIndexDecorator} */
  pageIndexDecorator
] = createMarkerDecorator("pageIndex", createNumericValidation("pageIndex"));
var [
  /**
   * Check if the given property is the `@pageIndex` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isPageSizeProperty,
  markPageSizeProperty,
  /** {@inheritdoc PageSizeDecorator} */
  pageSizeDecorator
] = createMarkerDecorator("pageSize", createNumericValidation("pageSize"));
var [
  /**
   * Check if the given property is the `@pageIndex` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isPageItemsProperty,
  markPageItemsProperty,
  /** {@inheritdoc PageItemsDecorator} */
  pageItemsDecorator
] = createMarkerDecorator("pageItems", (context, target) => {
  if (target.type.kind !== "Model" || !isArrayModelType(context.program, target.type)) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      messageId: "withExpected",
      format: { decorator: "continuationToken", expected: "Array", to: getTypeName(target.type) },
      target: context.decoratorTarget
    });
    return false;
  }
  return true;
});
var [
  /**
   * Check if the given property is the `@pageIndex` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isContinuationTokenProperty,
  markContinuationTokenProperty,
  /** {@inheritdoc ContinuationTokenDecorator} */
  continuationTokenDecorator
] = createMarkerDecorator("continuationToken", (context, target) => {
  if (!isStringType(context.program, target.type)) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      messageId: "withExpected",
      format: { decorator: "continuationToken", expected: "string", to: getTypeName(target.type) },
      target: context.decoratorTarget
    });
    return false;
  }
  return true;
});
var [
  /**
   * Check if the given property is the `@nextLink` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isNextLink,
  markNextLink,
  /** {@inheritdoc NextLinkDecorator} */
  nextLinkDecorator
] = createMarkerDecorator("nextLink");
var [
  /**
   * Check if the given property is the `@prevLink` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isPrevLink,
  markPrevLink,
  /** {@inheritdoc PrevLinkDecorator} */
  prevLinkDecorator
] = createMarkerDecorator("prevLink");
var [
  /**
   * Check if the given property is the `@firstLink` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isFirstLink,
  markFirstLink,
  /** {@inheritdoc FirstLinkDecorator} */
  firstLinkDecorator
] = createMarkerDecorator("firstLink");
var [
  /**
   * Check if the given property is the `@lastLink` property for a paging operation.
   * @param program Program
   * @param target Model Property
   */
  isLastLink,
  markLastLink,
  /** {@inheritdoc LastLinkDecorator} */
  lastLinkDecorator
] = createMarkerDecorator("lastLink");
function validatePagingOperations(program) {
  navigateProgram(program, {
    operation: (op) => {
      if (isList(program, op)) {
        validatePagingOperation(program, op);
      }
    }
  });
}
var inputProps = /* @__PURE__ */ new Set(["offset", "pageIndex", "pageSize", "continuationToken"]);
var outputProps = /* @__PURE__ */ new Set([
  "pageItems",
  "nextLink",
  "prevLink",
  "firstLink",
  "lastLink",
  "continuationToken"
]);
function findPagingProperties(program, op, base, source) {
  const diags = createDiagnosticCollector();
  const acceptableProps = source === "input" ? inputProps : outputProps;
  const duplicateTracker = new DuplicateTracker();
  const data = {};
  navigateProperties(base, (property, path) => {
    const kind = diags.pipe(getPagingProperty(program, property));
    if (kind === void 0) {
      return;
    }
    duplicateTracker.track(kind, property);
    if (acceptableProps.has(kind)) {
      data[kind] = { property, path };
    } else {
      diags.add(createDiagnostic({
        code: "invalid-paging-prop",
        messageId: source === "input" ? "input" : "output",
        format: { kind },
        target: property
      }));
    }
  });
  for (const [key, duplicates] of duplicateTracker.entries()) {
    for (const prop of duplicates) {
      diags.add(createDiagnostic({
        code: "duplicate-paging-prop",
        format: { kind: key, operationName: op.name },
        target: prop
      }));
    }
  }
  return diags.wrap(data);
}
function getPagingOperation(program, op) {
  const diags = createDiagnosticCollector();
  const result = {
    input: diags.pipe(findPagingProperties(program, op, op.parameters, "input")),
    output: diags.pipe(findPagingProperties(program, op, op.returnType, "output"))
  };
  if (result.output.pageItems === void 0) {
    diags.add(createDiagnostic({
      code: "missing-paging-items",
      format: { operationName: op.name },
      target: op
    }));
    return diags.wrap(void 0);
  }
  return diags.wrap(result);
}
function navigateProperties(type, callback, path = [], visited = /* @__PURE__ */ new Set()) {
  if (visited.has(type))
    return;
  visited.add(type);
  switch (type.kind) {
    case "Model":
      for (const prop of type.properties.values()) {
        callback(prop, [...path, prop]);
        navigateProperties(prop.type, callback, [...path, prop], visited);
      }
      if (type.baseModel) {
        navigateProperties(type.baseModel, callback, path, visited);
      }
      break;
    case "Union":
      for (const member of type.variants.values()) {
        navigateProperties(member, callback, path, visited);
      }
      break;
    case "UnionVariant":
      navigateProperties(type.type, callback, path, visited);
      break;
  }
}
function getPagingProperty(program, prop) {
  const diagnostics = [];
  const props = {
    offset: isOffsetProperty(program, prop),
    pageIndex: isPageIndexProperty(program, prop),
    pageItems: isPageItemsProperty(program, prop),
    pageSize: isPageSizeProperty(program, prop),
    continuationToken: isContinuationTokenProperty(program, prop),
    nextLink: isNextLink(program, prop),
    prevLink: isPrevLink(program, prop),
    lastLink: isLastLink(program, prop),
    firstLink: isFirstLink(program, prop)
  };
  const defined = Object.entries(props).filter((x2) => !!x2[1]);
  if (defined.length > 1) {
    diagnostics.push(createDiagnostic({
      code: "incompatible-paging-props",
      format: { kinds: defined.map((x2) => x2[0]).join(", ") },
      target: prop
    }));
  }
  if (defined.length === 0) {
    return [void 0, diagnostics];
  }
  return [defined[0][0], diagnostics];
}
function validatePagingOperation(program, op) {
  const [_2, diagnostics] = getPagingOperation(program, op);
  program.reportDiagnostics(diagnostics);
}
function createMarkerDecorator(key, validate) {
  const [isLink, markLink] = useStateSet(createStateSymbol(key));
  const decorator = (...args) => {
    if (validate && !validate(...args)) {
      return;
    }
    const [context, target] = args;
    markLink(context.program, target);
  };
  return [isLink, markLink, decorator];
}
function createNumericValidation(decoratorName) {
  return (context, target) => {
    if (!isNumericType(context.program, target.type)) {
      reportDiagnostic(context.program, {
        code: "decorator-wrong-target",
        messageId: "withExpected",
        format: {
          decorator: decoratorName,
          expected: "numeric",
          to: getTypeName(target.type)
        },
        target: context.decoratorTarget
      });
      return false;
    }
    return true;
  };
}

// src/typespec/core/packages/compiler/dist/src/lib/service.js
var [getService, setService, getServiceMap] = useStateMap(Symbol.for("@typespec/compiler.services"));
function listServices(program) {
  return [...getServiceMap(program).values()].filter((x2) => !Realm.realmForType.has(x2.type));
}
function isService(program, namespace) {
  return getServiceMap(program).has(namespace);
}
function addService(program, namespace, details = {}) {
  const serviceMap = getServiceMap(program);
  const existing = serviceMap.get(namespace) ?? {};
  setService(program, namespace, { ...existing, ...details, type: namespace });
}
var $service = (context, target, options) => {
  validateDecoratorUniqueOnNode(context, target, $service);
  addService(context.program, target, options);
};

// src/typespec/core/packages/compiler/dist/src/core/visibility/core.js
var [getVisibilityStore, setVisibilityStore] = useStateMap(createStateSymbol("visibilityStore"));
function getRawVisibilityStore(...params) {
  return getVisibilityStore(...params);
}
function getOrInitializeVisibilityModifiers(program, property) {
  let visibilityModifiers = getVisibilityStore(program, property);
  if (!visibilityModifiers) {
    visibilityModifiers = /* @__PURE__ */ new Map();
    setVisibilityStore(program, property, visibilityModifiers);
  }
  return visibilityModifiers;
}
function getOrInitializeActiveModifierSetForClass(program, property, visibilityClass, defaultSet) {
  const visibilityModifiers = getOrInitializeVisibilityModifiers(program, property);
  let visibilityModifierSet = visibilityModifiers.get(visibilityClass);
  if (!visibilityModifierSet) {
    visibilityModifierSet = defaultSet;
    visibilityModifiers.set(visibilityClass, visibilityModifierSet);
  }
  return visibilityModifierSet;
}
var VISIBILITY_PROGRAM_SEALS = /* @__PURE__ */ new WeakSet();
var [isVisibilitySealedForProperty, sealVisibilityForProperty] = useStateSet(createStateSymbol("propertyVisibilitySealed"));
var [getSealedVisibilityClasses, setSealedVisibilityClasses] = useStateMap(createStateSymbol("sealedVisibilityClasses"));
function sealVisibilityModifiersForClass(program, property, visibilityClass) {
  let sealedClasses = getSealedVisibilityClasses(program, property);
  if (!sealedClasses) {
    sealedClasses = /* @__PURE__ */ new Set();
    setSealedVisibilityClasses(program, property, sealedClasses);
  }
  sealedClasses.add(visibilityClass);
}
var [getDefaultModifiers, setDefaultModifiers] = useStateMap(createStateSymbol("defaultVisibilityModifiers"));
function getDefaultModifierSetForClass(program, visibilityClass) {
  const cached = getDefaultModifiers(program, visibilityClass);
  if (cached)
    return new Set(cached);
  const defaultModifierSet = new Set(visibilityClass.members.values());
  setDefaultModifiers(program, visibilityClass, defaultModifierSet);
  return new Set(defaultModifierSet);
}
function setDefaultModifierSetForVisibilityClass(program, visibilityClass, defaultSet) {
  compilerAssert(!getDefaultModifiers(program, visibilityClass), "The default modifier set for a visibility class may only be set once.");
  setDefaultModifiers(program, visibilityClass, defaultSet);
}
function groupModifiersByVisibilityClass(modifiers) {
  const enumMap = /* @__PURE__ */ new Map();
  for (const modifier of modifiers) {
    const visibilityClass = modifier.enum;
    let modifierSet = enumMap.get(visibilityClass);
    if (!modifierSet) {
      modifierSet = /* @__PURE__ */ new Set();
      enumMap.set(visibilityClass, modifierSet);
    }
    modifierSet.add(modifier);
  }
  return enumMap;
}
function isSealed(program, property, visibilityClass) {
  if (VISIBILITY_PROGRAM_SEALS.has(program))
    return true;
  const classSealed = visibilityClass ? getSealedVisibilityClasses(program, property)?.has(visibilityClass) : false;
  return classSealed || isVisibilitySealedForProperty(program, property);
}
function sealVisibilityModifiers(program, property, visibilityClass) {
  if (visibilityClass) {
    sealVisibilityModifiersForClass(program, property, visibilityClass);
  } else {
    sealVisibilityForProperty(program, property);
  }
}
function sealVisibilityModifiersForProgram(program) {
  VISIBILITY_PROGRAM_SEALS.add(program);
}
function addVisibilityModifiers(program, property, modifiers, context) {
  const modifiersByClass = groupModifiersByVisibilityClass(modifiers);
  for (const [visibilityClass, newModifiers] of modifiersByClass.entries()) {
    const target = context?.decoratorTarget ?? property;
    if (isSealed(program, property, visibilityClass)) {
      reportDiagnostic(program, {
        code: "visibility-sealed",
        format: {
          propName: property.name
        },
        target
      });
      continue;
    }
    const modifierSet = getOrInitializeActiveModifierSetForClass(
      program,
      property,
      visibilityClass,
      /* defaultSet: */
      /* @__PURE__ */ new Set()
    );
    for (const modifier of newModifiers) {
      modifierSet.add(modifier);
    }
  }
}
function removeVisibilityModifiers(program, property, modifiers, context) {
  const modifiersByClass = groupModifiersByVisibilityClass(modifiers);
  for (const [visibilityClass, newModifiers] of modifiersByClass.entries()) {
    const target = context?.decoratorTarget ?? property;
    if (isSealed(program, property, visibilityClass)) {
      reportDiagnostic(program, {
        code: "visibility-sealed",
        format: {
          propName: property.name
        },
        target
      });
      continue;
    }
    const modifierSet = getOrInitializeActiveModifierSetForClass(
      program,
      property,
      visibilityClass,
      /* defaultSet: */
      getDefaultModifierSetForClass(program, visibilityClass)
    );
    for (const modifier of newModifiers) {
      modifierSet.delete(modifier);
    }
  }
}
function clearVisibilityModifiersForClass(program, property, visibilityClass, context) {
  const target = context?.decoratorTarget ?? property;
  if (isSealed(program, property, visibilityClass)) {
    reportDiagnostic(program, {
      code: "visibility-sealed",
      format: {
        propName: property.name
      },
      target
    });
    return;
  }
  const modifierSet = getOrInitializeActiveModifierSetForClass(
    program,
    property,
    visibilityClass,
    /* defaultSet: */
    /* @__PURE__ */ new Set()
  );
  modifierSet.clear();
}
function resetVisibilityModifiersForClass(program, property, visibilityClass, context) {
  const target = context?.decoratorTarget ?? property;
  if (isSealed(program, property, visibilityClass)) {
    reportDiagnostic(program, {
      code: "visibility-sealed",
      format: {
        propName: property.name
      },
      target
    });
    return;
  }
  getOrInitializeVisibilityModifiers(program, property).delete(visibilityClass);
}
function getVisibilityForClass(program, property, visibilityClass) {
  const store = getVisibilityStore(program, property);
  return store?.get(visibilityClass) ?? getDefaultModifierSetForClass(program, visibilityClass);
}
function hasVisibility(program, property, modifier) {
  const visibilityClass = modifier.enum;
  return getVisibilityForClass(program, property, visibilityClass).has(modifier) ?? false;
}
var VISIBILITY_FILTER = Symbol.for("TypeSpec.Core.VisibilityFilter");
var VisibilityFilter = {
  /**
   * Convert a TypeSpec `GeneratedVisibilityFilter` value to a `VisibilityFilter`.
   *
   * @param filter - the decorator argument filter to convert
   * @returns a `VisibilityFilter` object that can be consumed by the visibility APIs
   */
  fromDecoratorArgument(filter) {
    return filter[VISIBILITY_FILTER] ??= {
      all: filter.all && new Set(filter.all.map((v2) => v2.value)),
      any: filter.any && new Set(filter.any.map((v2) => v2.value)),
      none: filter.none && new Set(filter.none.map((v2) => v2.value))
    };
  },
  /**
   * Extracts the unique visibility classes referred to by the modifiers in a
   * visibility filter.
   *
   * @param filter - the visibility filter to extract visibility classes from
   * @returns a set of visibility classes referred to by the filter
   */
  getVisibilityClasses(filter) {
    const classes = /* @__PURE__ */ new Set();
    if (filter.all)
      filter.all.forEach((v2) => classes.add(v2.enum));
    if (filter.any)
      filter.any.forEach((v2) => classes.add(v2.enum));
    if (filter.none)
      filter.none.forEach((v2) => classes.add(v2.enum));
    return classes;
  },
  /**
   * Converts a visibility filter into a stable string representation.
   *
   * This can be used as a cache key for the filter that will be stable for filters that are not object-identical but
   * are semantically identical.
   */
  toCacheKey(program, filter) {
    return visibilityFilterToCacheKey(program, filter);
  }
};
var ENUM_INTERN_TABLE = Symbol.for("TypeSpec.Core.enumInternTable");
function internEnum(program, enumType) {
  const enumInternTable = program[ENUM_INTERN_TABLE] ??= {
    idx: 0,
    map: /* @__PURE__ */ new WeakMap()
  };
  let idx = enumInternTable.map.get(enumType);
  if (idx === void 0) {
    idx = enumInternTable.idx++;
    enumInternTable.map.set(enumType, idx);
  }
  return idx;
}
var VISIBILITY_FILTER_TO_STRING_CACHE = Symbol.for("TypeSpec.Core.visibilityFilterToStringCache");
function visibilityFilterToCacheKey(program, filter) {
  const visibilityFilterToStringCache = program[VISIBILITY_FILTER_TO_STRING_CACHE] ??= /* @__PURE__ */ new WeakMap();
  let str = visibilityFilterToStringCache.get(filter);
  if (str) {
    return str;
  }
  str = "{";
  for (const [key, modifierSet] of Object.entries(filter).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))) {
    if (!modifierSet)
      continue;
    str += `${key}:[`;
    const values = [];
    for (const modifier of modifierSet) {
      const enumType = internEnum(program, modifier.enum);
      values.push({ _enum: enumType, modifier: modifier.name });
    }
    str += values.sort(function sortByEnumThenModifier(a2, b2) {
      if (a2._enum !== b2._enum) {
        return a2._enum - b2._enum;
      }
      return a2.modifier.localeCompare(b2.modifier);
    }).join(",") + "]";
  }
  str += "}";
  visibilityFilterToStringCache.set(filter, str);
  return str;
}
function isVisible(program, property, filter) {
  if (filter.all) {
    for (const modifier of filter.all) {
      if (!hasVisibility(program, property, modifier))
        return false;
    }
  }
  if (filter.none) {
    for (const modifier of filter.none) {
      if (hasVisibility(program, property, modifier))
        return false;
    }
  }
  if (filter.any) {
    for (const modifier of filter.any) {
      if (hasVisibility(program, property, modifier))
        return true;
    }
    return false;
  }
  return true;
}

// src/typespec/core/packages/compiler/dist/src/core/visibility/lifecycle.js
var LIFECYCLE_ENUM_CACHE = /* @__PURE__ */ new WeakMap();
function getLifecycleVisibilityEnum(program) {
  const cached = LIFECYCLE_ENUM_CACHE.get(program);
  if (cached)
    return cached;
  const [type, diagnostics] = program.resolveTypeReference("TypeSpec.Lifecycle");
  compilerAssert(diagnostics.length === 0, "Encountered diagnostics when resolving the `TypeSpec.Lifecycle` visibility class enum");
  compilerAssert(type.kind === "Enum", "Expected `TypeSpec.Visibility.Lifecycle` to be an enum");
  LIFECYCLE_ENUM_CACHE.set(program, type);
  return type;
}

// src/typespec/core/packages/compiler/dist/src/core/helpers/location-context.js
function getLocationContext(program, type) {
  const sourceLocation = getSourceLocation(type);
  if (sourceLocation.isSynthetic) {
    return { type: "synthetic" };
  }
  return program.getSourceFileLocationContext(sourceLocation.file);
}

// src/typespec/core/packages/compiler/dist/src/utils/custom-key-map.js
var CustomKeyMap = class {
  #items = /* @__PURE__ */ new Map();
  #keyer;
  constructor(keyer) {
    this.#keyer = keyer;
  }
  get(items) {
    return this.#items.get(this.#keyer(items));
  }
  set(items, value) {
    const key = this.#keyer(items);
    this.#items.set(key, value);
  }
  static objectKeyer() {
    const knownKeys = /* @__PURE__ */ new WeakMap();
    let count = 0;
    return {
      getKey(o2) {
        if (knownKeys.has(o2)) {
          return knownKeys.get(o2);
        }
        const key = count;
        count++;
        knownKeys.set(o2, key);
        return key;
      }
    };
  }
};

// src/typespec/core/packages/compiler/dist/src/experimental/mutators.js
var MutatorFlow;
(function(MutatorFlow2) {
  MutatorFlow2[MutatorFlow2["MutateAndRecur"] = 0] = "MutateAndRecur";
  MutatorFlow2[MutatorFlow2["DoNotMutate"] = 1] = "DoNotMutate";
  MutatorFlow2[MutatorFlow2["DoNotRecur"] = 2] = "DoNotRecur";
})(MutatorFlow || (MutatorFlow = {}));
function isMutableTypeWithNamespace(type) {
  switch (type.kind) {
    case "TemplateParameter":
    case "Intrinsic":
    case "Decorator":
    case "FunctionParameter":
      return false;
    default:
      void type;
      return true;
  }
}
function isMutableType(type) {
  switch (type.kind) {
    case "TemplateParameter":
    case "Intrinsic":
    case "Decorator":
    case "FunctionParameter":
    case "Namespace":
      return false;
    default:
      void type;
      return true;
  }
}
var typeId = CustomKeyMap.objectKeyer();
var mutatorId = CustomKeyMap.objectKeyer();
var seen = new CustomKeyMap(([type, mutators]) => {
  const key = `${typeId.getKey(type)}-${[...mutators.values()].map((v2) => mutatorId.getKey(v2)).join("-")}`;
  return key;
});
function mutateSubgraphWithNamespace(program, mutators, type) {
  const engine = createMutatorEngine(program, mutators, {
    mutateNamespaces: true
  });
  const mutated = engine.mutate(type);
  if (mutated === type) {
    return { realm: null, type };
  }
  return { realm: engine.realm, type: mutated };
}
function mutateSubgraph(program, mutators, type) {
  const engine = createMutatorEngine(program, mutators, {
    mutateNamespaces: false
  });
  const mutated = engine.mutate(type);
  if (mutated === type) {
    return { realm: null, type };
  }
  return { realm: engine.realm, type: mutated };
}
var [getAlwaysMutate, _setAlwaysMutate] = useStateMap(Symbol.for("TypeSpec.Mutators.alwaysMutate"));
function setAlwaysMutate(program, type, alwaysMutate = true) {
  _setAlwaysMutate(program, type, alwaysMutate);
}
function createMutatorEngine(program, mutators, options) {
  const realm = new Realm(program, `Mutator realm ${mutators.map((m2) => m2.name).join(", ")}`);
  const interstitialFunctions = [];
  let preparingNamespace = false;
  const muts = new Set(mutators);
  const postVisits = [];
  const namespacesVisitedContent = /* @__PURE__ */ new Set();
  if (options.mutateNamespaces) {
    preparingNamespace = true;
    mutateSubgraphWorker(program.getGlobalNamespaceType(), muts);
    preparingNamespace = false;
    postVisits.forEach((visit) => visit());
  }
  return {
    realm,
    mutate: (type) => {
      return mutateSubgraphWorker(type, muts);
    }
  };
  function resolveMutators(activeMutators, type) {
    const mutatorsWithOptions = [];
    const newMutators = new Set(activeMutators.values());
    for (const mutator of activeMutators) {
      const record = mutator[type.kind];
      if (!record) {
        continue;
      }
      let mutationFn = null;
      let replaceFn = null;
      let mutate2 = false;
      let recurse = false;
      if (typeof record === "function") {
        mutationFn = record;
        mutate2 = true;
        recurse = true;
      } else {
        mutationFn = "mutate" in record ? record.mutate : null;
        replaceFn = "replace" in record ? record.replace : null;
        if (record.filter) {
          const filterResult = record.filter(type, program, realm);
          if (filterResult === true) {
            mutate2 = true;
            recurse = true;
          } else if (filterResult === false) {
            mutate2 = false;
            recurse = true;
          } else {
            mutate2 = (filterResult & MutatorFlow.DoNotMutate) === 0;
            recurse = (filterResult & MutatorFlow.DoNotRecur) === 0;
          }
        } else {
          mutate2 = true;
          recurse = true;
        }
      }
      if (!recurse) {
        newMutators.delete(mutator);
      }
      if (mutate2) {
        mutatorsWithOptions.push({ mutator, mutationFn, replaceFn });
      }
    }
    return { mutatorsWithOptions, newMutators };
  }
  function applyMutations(type, clone, mutatorsWithOptions) {
    let resolved = clone;
    for (const { mutationFn, replaceFn } of mutatorsWithOptions) {
      const result = (mutationFn ?? replaceFn)(type, resolved, program, realm);
      if (replaceFn && result !== void 0) {
        resolved = result;
      }
    }
    return resolved;
  }
  function mutateSubgraphWorker(type, activeMutators, mutateSubNamespace = true) {
    let existing = seen.get([type, activeMutators]);
    if (existing) {
      if (mutateSubNamespace && existing.kind === "Namespace" && !namespacesVisitedContent.has(existing)) {
        namespacesVisitedContent.add(existing);
        mutateSubMap(existing, "namespaces", true, activeMutators);
      }
      clearInterstitialFunctions();
      return existing;
    }
    const alwaysMutate = getAlwaysMutate(program, type);
    if (!alwaysMutate && getLocationContext(program, type).type === "compiler" && !isTemplateInstance(type)) {
      return type;
    }
    let clone = null;
    const { mutatorsWithOptions, newMutators } = resolveMutators(activeMutators, type);
    const mutatorsToApply = mutatorsWithOptions.map((v2) => v2.mutator);
    let mutating = false;
    if (mutatorsWithOptions.length === 0) {
      if (newMutators.size > 0) {
        interstitialFunctions.push(initializeClone);
        seen.set([type, activeMutators], type);
        visitSubgraph();
        visitParents();
        interstitialFunctions.pop();
        return clone ?? type;
      } else {
        return type;
      }
    }
    clearInterstitialFunctions();
    existing = seen.get([type, mutatorsToApply]);
    if (existing) {
      return existing;
    }
    initializeClone();
    const result = applyMutations(type, clone, mutatorsWithOptions);
    if (result !== clone) {
      clone = result;
      seen.set([type, activeMutators], clone);
      seen.set([type, mutatorsToApply], clone);
    }
    if (newMutators.size > 0) {
      if (preparingNamespace && type.kind === "Namespace") {
        compilerAssert(mutating, "Cannot be preparing namespaces and not have cloned it.");
        prepareNamespace(clone);
        postVisits.push(() => visitNamespaceContents(clone));
      } else {
        visitSubgraph();
      }
    }
    if (type.isFinished) {
      $2(realm).type.finishType(clone);
    }
    if (type.kind === "Namespace" && mutateSubNamespace) {
      compilerAssert(mutating, "Cannot be preparing namespaces and not have cloned it.");
      visitSubNamespaces(clone);
    }
    if (type.kind !== "Namespace") {
      visitParents();
    }
    return clone;
    function initializeClone() {
      clone = $2(realm).type.clone(type);
      mutating = true;
      seen.set([type, activeMutators], clone);
      seen.set([type, mutatorsToApply], clone);
    }
    function clearInterstitialFunctions() {
      for (const interstitial of interstitialFunctions) {
        interstitial();
      }
      interstitialFunctions.length = 0;
    }
    function mutateNamespaceProperty(root) {
      if (!options.mutateNamespaces) {
        return;
      }
      if ("namespace" in root && root.namespace) {
        const newNs = mutateSubgraphWorker(root.namespace, newMutators, false);
        compilerAssert(newNs.kind === "Namespace", `Expected to be mutated to a namespace`);
        clone.namespace = newNs;
      }
    }
    function prepareNamespace(root) {
      visitDecorators(root, true, newMutators);
      mutateNamespaceProperty(root);
    }
    function visitSubNamespaces(type2) {
      namespacesVisitedContent.add(type2);
      mutateSubMap(type2, "namespaces", true, newMutators);
    }
    function visitNamespaceContents(root) {
      mutateSubMap(root, "models", mutating, newMutators);
      mutateSubMap(root, "operations", mutating, newMutators);
      mutateSubMap(root, "interfaces", mutating, newMutators);
      mutateSubMap(root, "enums", mutating, newMutators);
      mutateSubMap(root, "unions", mutating, newMutators);
      mutateSubMap(root, "scalars", mutating, newMutators);
    }
    function visitModel(root) {
      mutateSubMap(root, "properties", mutating, newMutators);
      if (root.indexer) {
        const res = mutateSubgraphWorker(root.indexer.value, newMutators);
        if (mutating) {
          root.indexer.value = res;
        }
      }
      for (const [index, prop] of root.sourceModels.entries()) {
        const newModel = mutateSubgraphWorker(prop.model, newMutators);
        if (mutating) {
          mutate(root.sourceModels[index]).model = newModel;
        }
      }
      mutateProperty(root, "sourceModel", mutating, newMutators);
      mutateProperty(root, "baseModel", mutating, newMutators);
      mutateSubArray(root, "derivedModels", mutating, newMutators);
    }
    function visitSubgraph() {
      const root = clone ?? type;
      switch (root.kind) {
        case "Namespace":
          visitNamespaceContents(root);
          break;
        case "Model":
          visitModel(root);
          break;
        case "ModelProperty":
          mutateProperty(root, "type", mutating, newMutators);
          mutateProperty(root, "sourceProperty", mutating, newMutators);
          break;
        case "Tuple":
          mutateSubArray(root, "values", mutating, newMutators);
          break;
        case "Operation":
          mutateProperty(root, "parameters", mutating, newMutators);
          mutateProperty(root, "returnType", mutating, newMutators);
          mutateProperty(root, "sourceOperation", mutating, newMutators);
          break;
        case "Interface":
          mutateSubMap(root, "operations", mutating, newMutators);
          break;
        case "Enum":
          mutateSubMap(root, "members", mutating, newMutators);
          break;
        case "EnumMember":
          break;
        case "Union":
          mutateSubMap(root, "variants", mutating, newMutators);
          break;
        case "UnionVariant":
          mutateProperty(root, "type", mutating, newMutators);
          break;
        case "Scalar":
          mutateSubMap(root, "constructors", mutating, newMutators);
          mutateProperty(root, "baseScalar", mutating, newMutators);
          mutateSubArray(root, "derivedScalars", mutating, newMutators);
          break;
        case "ScalarConstructor":
          mutateProperty(root, "scalar", mutating, newMutators);
          break;
      }
      if ("templateMapper" in root) {
        mutateTemplateMapper(root, mutating, newMutators);
      }
      if ("decorators" in root) {
        visitDecorators(root, mutating, newMutators);
      }
      mutateNamespaceProperty(root);
    }
    function visitParents() {
      const root = clone ?? type;
      switch (root.kind) {
        case "ModelProperty":
          mutateProperty(root, "model", mutating, newMutators);
          break;
        case "Operation":
          mutateProperty(root, "interface", mutating, newMutators);
          break;
        case "EnumMember":
          mutateProperty(root, "enum", mutating, newMutators);
          break;
        case "UnionVariant":
          mutateProperty(root, "union", mutating, newMutators);
          break;
        case "ScalarConstructor":
          mutateProperty(root, "scalar", mutating, newMutators);
          break;
      }
    }
  }
  function visitDecorators(type, mutating, newMutators) {
    for (const [index, dec] of type.decorators.entries()) {
      const args = [];
      for (const arg of dec.args) {
        const jsValue = typeof arg.jsValue === "object" && arg.jsValue !== null && isType(arg.jsValue) && isMutableTypeWithNamespace(arg.jsValue) ? mutateSubgraphWorker(arg.jsValue, newMutators) : arg.jsValue;
        args.push({
          ...arg,
          value: isType(arg.value) && isMutableTypeWithNamespace(arg.value) ? mutateSubgraphWorker(arg.value, newMutators) : arg.value,
          jsValue
        });
      }
      if (mutating) {
        type.decorators[index] = { ...dec, args };
      }
    }
  }
  function mutateTemplateMapper(type, mutating, newMutators) {
    if (type.templateMapper === void 0) {
      return;
    }
    const mutatedMapper = {
      ...type.templateMapper,
      args: [],
      map: /* @__PURE__ */ new Map()
    };
    for (const arg of type.templateMapper.args) {
      mutate(mutatedMapper.args).push(mutateSubgraphWorker(arg, newMutators));
    }
    for (const [param, paramType] of type.templateMapper.map) {
      mutatedMapper.map.set(param, mutateSubgraphWorker(paramType, newMutators));
    }
    if (mutating) {
      type.templateMapper = mutatedMapper;
    }
  }
  function mutateSubMap(type, prop, mutate2, newMutators) {
    for (const [key, value] of type[prop].entries()) {
      const newValue = mutateSubgraphWorker(value, newMutators);
      if (mutate2) {
        type[prop].set(key, newValue);
        if (newValue.name !== value.name) {
          type[prop].rekey(key, newValue.name);
        }
      }
    }
  }
  function mutateSubArray(type, prop, mutate2, newMutators) {
    for (const [index, value] of type[prop].entries()) {
      const newValue = mutateSubgraphWorker(value, newMutators);
      if (mutate2) {
        type[prop][index] = newValue;
      }
    }
  }
  function mutateProperty(type, prop, mutating, newMutators) {
    if (type[prop] === void 0) {
      return;
    }
    const newValue = mutateSubgraphWorker(type[prop], newMutators);
    if (mutating) {
      type[prop] = newValue;
    }
  }
}

// src/typespec/core/packages/compiler/dist/src/lib/visibility.js
var $withDefaultKeyVisibility = (context, entity, visibility) => {
  const keyProperties = [...entity.properties].filter(([_2, prop]) => {
    return isKey(context.program, prop) && !getRawVisibilityStore(context.program, prop);
  });
  for (const [name, keyProp] of keyProperties) {
    entity.properties.set(name, context.program.checker.cloneType(keyProp, {
      decorators: [
        ...keyProp.decorators,
        {
          decorator: $visibility,
          args: [
            {
              value: visibility,
              jsValue: visibility
            }
          ]
        }
      ]
    }));
  }
};
var [getOperationVisibilityConfigRaw, setOperationVisibilityConfigRaw] = useStateMap(createStateSymbol("operationVisibilityConfig"));
function getOperationVisibilityConfig(program, operation) {
  let config = getOperationVisibilityConfigRaw(program, operation);
  if (!config) {
    config = {};
    setOperationVisibilityConfigRaw(program, operation, config);
  }
  return config;
}
var $parameterVisibility = (context, operation, ...modifiers) => {
  validateDecoratorUniqueOnNode(context, operation, $parameterVisibility);
  if (modifiers.length === 0) {
    reportDiagnostic(context.program, {
      code: "operation-visibility-constraint-empty",
      messageId: "parameter",
      target: context.decoratorTarget
    });
    return;
  }
  getOperationVisibilityConfig(context.program, operation).parameters = modifiers.map((m2) => m2.value);
};
var EmptyVisibilityProvider = {
  parameters: () => ({}),
  returnType: () => ({})
};
function getParameterVisibilityFilter(program, operation, defaultProvider) {
  const operationVisibilityConfig = getOperationVisibilityConfig(program, operation);
  if (!operationVisibilityConfig.parameters)
    return defaultProvider.parameters(program, operation);
  compilerAssert(operationVisibilityConfig.parameters.length !== 0, "Empty parameter visibility constraint.");
  return {
    // WARNING: the HTTP library depends on `any` being the only key in the filter object returned by this method.
    //          if you change this logic, you will need to update the HTTP library to account for differences in the
    //          returned object. HTTP does not currently have a way to express `all` or `none` constraints in the same
    //          way that the core visibility system does.
    any: new Set(operationVisibilityConfig.parameters)
  };
}
var $returnTypeVisibility = (context, operation, ...modifiers) => {
  validateDecoratorUniqueOnNode(context, operation, $parameterVisibility);
  if (modifiers.length === 0) {
    reportDiagnostic(context.program, {
      code: "operation-visibility-constraint-empty",
      messageId: "returnType",
      target: context.decoratorTarget
    });
    return;
  }
  getOperationVisibilityConfig(context.program, operation).returnType = modifiers.map((m2) => m2.value);
};
function getReturnTypeVisibilityFilter(program, operation, defaultProvider) {
  const visibilityConfig = getOperationVisibilityConfig(program, operation);
  if (!visibilityConfig.returnType)
    return defaultProvider.returnType(program, operation);
  compilerAssert(visibilityConfig.returnType.length !== 0, "Empty return type visibility constraint.");
  return {
    // WARNING: the HTTP library depends on `any` being the only key in the filter object returned by this method.
    //          if you change this logic, you will need to update the HTTP library to account for differences in the
    //          returned object. HTTP does not currently have a way to express `all` or `none` constraints in the same
    //          way that the core visibility system does.
    any: new Set(visibilityConfig.returnType)
  };
}
var $visibility = (context, target, ...modifiers) => {
  addVisibilityModifiers(context.program, target, modifiers.map((m2) => m2.value), context);
};
var $removeVisibility = (context, target, ...visibilities) => {
  removeVisibilityModifiers(context.program, target, visibilities.map((v2) => v2.value));
};
var $invisible = (context, target, visibilityClass) => {
  clearVisibilityModifiersForClass(context.program, target, visibilityClass);
};
var $defaultVisibility = (context, target, ...visibilities) => {
  validateDecoratorUniqueOnNode(context, target, $defaultVisibility);
  const modifierSet = /* @__PURE__ */ new Set();
  for (const visibility of visibilities) {
    if (visibility.value.enum !== target) {
      reportDiagnostic(context.program, {
        code: "default-visibility-not-member",
        target: context.decoratorTarget
      });
    } else {
      modifierSet.add(visibility.value);
    }
  }
  setDefaultModifierSetForVisibilityClass(context.program, target, modifierSet);
};
var $withVisibility = (context, target, ...modifiers) => {
  const modifierMembers = modifiers.map((m2) => m2.value);
  const filter = {
    all: new Set(modifierMembers)
  };
  const visibilityClasses = new Set(modifierMembers.map((m2) => m2.enum));
  filterModelPropertiesInPlace(target, (p2) => isVisible(context.program, p2, filter));
  for (const p2 of target.properties.values()) {
    for (const c2 of visibilityClasses) {
      resetVisibilityModifiersForClass(context.program, p2, c2);
    }
  }
};
var $withUpdateableProperties = (context, target) => {
  if (!validateDecoratorTarget(context, target, "@withUpdateableProperties", "Model")) {
    return;
  }
  const filter = {
    all: /* @__PURE__ */ new Set([getLifecycleVisibilityEnum(context.program).members.get("Update")])
  };
  filterModelPropertiesInPlace(target, (p2) => isVisible(context.program, p2, filter));
};
var VISIBILITY_FILTER_MUTATOR_CACHE = Symbol.for("TypeSpec.Core.visibilityFilterMutatorCache");
var $withVisibilityFilter = (context, target, _filter, nameTemplate) => {
  const filter = VisibilityFilter.fromDecoratorArgument(_filter);
  const mutatorCache = context.program[VISIBILITY_FILTER_MUTATOR_CACHE] ??= {};
  const byNameTemplate = mutatorCache.byNameTemplate ??= {};
  const mutatorCacheByNameTemplate = nameTemplate === void 0 ? mutatorCache.unnamed ??= {} : byNameTemplate[nameTemplate] ??= {};
  const mutatorCacheByVisibilityFilter = mutatorCacheByNameTemplate.byVisibilityFilter ??= /* @__PURE__ */ new Map();
  const vfKey = VisibilityFilter.toCacheKey(context.program, filter);
  let mutator = mutatorCacheByVisibilityFilter.get(vfKey);
  if (!mutator) {
    mutator = createVisibilityFilterMutator(filter, {
      decoratorFn: $withVisibilityFilter,
      nameTemplate
    });
    mutatorCacheByVisibilityFilter.set(vfKey, mutator);
  }
  setAlwaysMutate(context.program, target);
  const { type } = cachedMutateSubgraph(context.program, mutator, target);
  setAlwaysMutate(context.program, target, false);
  target.properties = type.properties;
};
var $withLifecycleUpdate = (context, target, nameTemplate) => {
  const mutatorCache = context.program[VISIBILITY_FILTER_MUTATOR_CACHE] ??= {};
  const byNameTemplate = mutatorCache.byNameTemplate ??= {};
  const mutatorCacheByNameTemplate = nameTemplate === void 0 ? mutatorCache.unnamed ??= {} : byNameTemplate[nameTemplate] ??= {};
  let mutator = mutatorCacheByNameTemplate.lifecycleUpdate;
  if (!mutator) {
    const lifecycle = getLifecycleVisibilityEnum(context.program);
    const lifecycleUpdate = {
      all: /* @__PURE__ */ new Set([lifecycle.members.get("Update")])
    };
    const lifecycleCreateOrUpdate = {
      any: /* @__PURE__ */ new Set([lifecycle.members.get("Create"), lifecycle.members.get("Update")])
    };
    const createOrUpdateMutator = createVisibilityFilterMutator(lifecycleCreateOrUpdate);
    mutator = createVisibilityFilterMutator(lifecycleUpdate, {
      recur: createOrUpdateMutator,
      decoratorFn: $withLifecycleUpdate,
      nameTemplate
    });
    mutatorCacheByNameTemplate.lifecycleUpdate = mutator;
  }
  setAlwaysMutate(context.program, target);
  const { type } = cachedMutateSubgraph(context.program, mutator, target);
  setAlwaysMutate(context.program, target, false);
  target.properties = type.properties;
};
var VISIBILITY_FILTER_MUTATOR_RESULT = Symbol.for("TypeSpec.Core.visibilityFilterMutatorResult");
function cachedMutateSubgraph(program, mutator, source) {
  const mutatorCache = mutator[VISIBILITY_FILTER_MUTATOR_RESULT] ??= /* @__PURE__ */ new WeakMap();
  const cached = mutatorCache.get(source);
  if (cached) {
    return cached;
  }
  const mutated = mutateSubgraph(program, [mutator], source);
  mutatorCache.set(source, mutated);
  return mutated;
}
function createVisibilityFilterMutator(filter, options = {}) {
  const visibilityClasses = VisibilityFilter.getVisibilityClasses(filter);
  const mpMutator = {
    name: "VisibilityFilterProperty",
    ModelProperty: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (prop, clone, program) => {
        let modified = false;
        const decorators = [];
        for (const decorator of prop.decorators) {
          const decFn = decorator.decorator;
          if (decFn === $visibility || decFn === $removeVisibility) {
            const nextArgs = decorator.args.filter((arg) => {
              if (arg.value.entityKind !== "Value")
                return false;
              const isString = arg.value.valueKind === "StringValue";
              const isOperativeVisibility = arg.value.valueKind === "EnumValue" && visibilityClasses.has(arg.value.value.enum);
              return !(isString || isOperativeVisibility);
            });
            modified ||= nextArgs.length !== decorator.args.length;
            if (nextArgs.length > 0) {
              decorators.push({
                ...decorator,
                args: nextArgs
              });
            }
          } else if (decFn !== $invisible) {
            decorators.push(decorator);
          }
        }
        clone.decorators = decorators;
        modified ||= decorators.length !== prop.decorators.length;
        for (const visibilityClass of visibilityClasses) {
          resetVisibilityModifiersForClass(program, clone, visibilityClass);
        }
        if (isVisibilitySubject(prop.type)) {
          clone.type = cachedMutateSubgraph(program, options.recur ?? self, prop.type).type;
          modified ||= clone.type !== prop.type;
        }
        return modified ? clone : prop;
      }
    }
  };
  const self = {
    name: "VisibilityFilter",
    Union: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (union, clone, program) => {
        let modified = false;
        for (const [key, member] of union.variants) {
          if (isVisibilitySubject(member.type)) {
            const variant = {
              ...member,
              type: cachedMutateSubgraph(program, self, member.type).type
            };
            clone.variants.set(key, variant);
            modified ||= variant.type !== member.type;
          }
        }
        rename(clone, options.nameTemplate);
        return modified ? clone : union;
      }
    },
    Model: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (model, clone, program, realm) => {
        let modified = false;
        if (model.indexer && isVisibilitySubject(model.indexer.value)) {
          clone.indexer = { ...model.indexer };
          mutate(clone.indexer).value = cachedMutateSubgraph(program, options.recur ?? self, model.indexer.value).type;
          if ($2(realm).array.is(model) && clone.name === "Array" && clone.indexer.value !== model.indexer.value) {
            return $2(program).array.create(clone.indexer.value);
          }
          if ($2(realm).record.is(model) && clone.name === "Record" && clone.indexer.value !== model.indexer.value) {
            return $2(program).record.create(clone.indexer.value);
          }
          modified ||= clone.indexer.value !== model.indexer.value;
        }
        for (const [key, prop] of model.properties) {
          if (!isVisible(program, prop, filter)) {
            clone.properties.delete(key);
            realm.remove(clone);
            modified = true;
          } else {
            const mutated = mutateSubgraph(program, [mpMutator], prop);
            clone.properties.set(key, mutated.type);
            modified ||= mutated.type.type !== prop.type;
          }
        }
        if (options.decoratorFn) {
          clone.decorators = clone.decorators.filter((d2) => d2.decorator !== options.decoratorFn);
          modified ||= clone.decorators.length !== model.decorators.length;
        }
        rename(clone, options.nameTemplate);
        return modified ? clone : model;
      }
    },
    ModelProperty: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (prop, clone, program) => {
        if (isVisibilitySubject(prop.type)) {
          clone.type = cachedMutateSubgraph(program, self, prop.type).type;
        }
        return clone.type !== prop.type ? clone : prop;
      }
    },
    UnionVariant: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (variant, clone, program) => {
        if (isVisibilitySubject(variant.type)) {
          clone.type = cachedMutateSubgraph(program, self, variant.type).type;
        }
        return clone.type !== variant.type ? clone : variant;
      }
    },
    Tuple: {
      filter: () => MutatorFlow.DoNotRecur,
      replace: (tuple, clone, program) => {
        let modified = false;
        for (const [index, element] of tuple.values.entries()) {
          if (isVisibilitySubject(element)) {
            clone.values[index] = cachedMutateSubgraph(program, self, element).type;
            modified ||= clone.values[index] !== element;
          }
        }
        return modified ? clone : tuple;
      }
    }
  };
  return self;
}
function rename(type, nameTemplate) {
  if (!nameTemplate || !type.name)
    return;
  const renamed = replaceTemplatedStringFromProperties(nameTemplate, type);
  type.name = renamed;
}
function isVisibilitySubject(t2) {
  return t2.kind === "Model" || t2.kind === "Union" || t2.kind === "ModelProperty" || t2.kind === "UnionVariant" || t2.kind === "Tuple";
}

// src/typespec/core/packages/compiler/dist/src/lib/decorators.js
var [getSummary, setSummary] = useStateMap(createStateSymbol("summary"));
var $summary = (context, target, text, sourceObject) => {
  if (sourceObject) {
    text = replaceTemplatedStringFromProperties(text, sourceObject);
  }
  setSummary(context.program, target, text);
};
var $doc = (context, target, text, sourceObject) => {
  validateDecoratorUniqueOnNode(context, target, $doc);
  if (sourceObject) {
    text = replaceTemplatedStringFromProperties(text, sourceObject);
  }
  setDocData(context.program, target, "self", { value: text, source: "decorator" });
};
function getDoc(program, target) {
  return getDocDataInternal(program, target, "self")?.value;
}
var $returnsDoc = (context, target, text) => {
  validateDecoratorUniqueOnNode(context, target, $doc);
  setDocData(context.program, target, "returns", { value: text, source: "decorator" });
};
function getReturnsDocData(program, target) {
  return getDocDataInternal(program, target, "returns");
}
function getReturnsDoc(program, target) {
  return getDocDataInternal(program, target, "returns")?.value;
}
var $errorsDoc = (context, target, text) => {
  validateDecoratorUniqueOnNode(context, target, $doc);
  setDocData(context.program, target, "errors", { value: text, source: "decorator" });
};
function getErrorsDocData(program, target) {
  return getDocDataInternal(program, target, "errors");
}
function getErrorsDoc(program, target) {
  return getDocDataInternal(program, target, "errors")?.value;
}
var $inspectType = (context, target, text) => {
  if (text)
    console.log(text);
  console.dir(target, { depth: 3 });
};
var $inspectTypeName = (context, target, text) => {
  if (text)
    console.log(text);
  console.log(getTypeName(target));
};
function isStringType(program, target) {
  const stringType = program.checker.getStdType("string");
  return target.kind === "Scalar" && program.checker.isTypeAssignableTo(target, stringType, target)[0];
}
function isNumericType(program, target) {
  const numericType = program.checker.getStdType("numeric");
  return target.kind === "Scalar" && program.checker.isTypeAssignableTo(target, numericType, target)[0];
}
function isTypeIn(type, condition) {
  if (type.kind === "Union") {
    return [...type.variants.values()].some((v2) => condition(v2.type));
  }
  return condition(type);
}
function validateTargetingANumeric(context, target, decoratorName) {
  const valid = isTypeIn(getPropertyType(target), (x2) => isNumericType(context.program, x2));
  if (!valid) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      format: {
        decorator: decoratorName,
        to: `type it is not a numeric`
      },
      target: context.decoratorTarget
    });
  }
  return valid;
}
function validateTargetingAString(context, target, decoratorName) {
  const propertyType = getPropertyType(target);
  const valid = isTypeIn(propertyType, (x2) => isStringType(context.program, x2));
  if (!valid) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      format: {
        decorator: decoratorName,
        to: propertyType.kind === "Union" ? `a union type that is not string compatible. The union must explicitly include a string type, and all union values should be strings. For example: union Test { string, "A", "B" }` : `type it is not a string`
      },
      target: context.decoratorTarget
    });
  }
  return valid;
}
function getTypeForArrayValidation(target) {
  if (target.kind === "ModelProperty") {
    return target.type;
  } else {
    return target.kind === "Model" ? target : target.type;
  }
}
function validateTargetingAnArray(context, target, decoratorName) {
  const targetType = getTypeForArrayValidation(target);
  const valid = isTypeIn(targetType, (x2) => x2.kind === "Model" && isArrayModelType(context.program, x2));
  if (!valid) {
    reportDiagnostic(context.program, {
      code: "decorator-wrong-target",
      format: {
        decorator: decoratorName,
        to: `non Array type`
      },
      target: context.decoratorTarget
    });
  }
  return valid;
}
var [getErrorState, setErrorState] = useStateSet(createStateSymbol("error"));
var $error = (context, entity) => {
  validateDecoratorUniqueOnNode(context, entity, $error);
  setErrorState(context.program, entity);
};
function isErrorModel(program, target) {
  if (target.kind !== "Model") {
    return false;
  }
  let current = target;
  while (current) {
    if (getErrorState(program, current)) {
      return true;
    }
    current = current.baseModel;
  }
  return false;
}
var [_getMediaTypeHint, setMediaTypeHint] = useStateMap(createStateSymbol("mediaTypeHint"));
var $mediaTypeHint = (context, target, mediaType) => {
  validateDecoratorUniqueOnNode(context, target, $mediaTypeHint);
  const mimeTypeObj = parseMimeType(mediaType);
  if (mimeTypeObj === void 0) {
    reportDiagnostic(context.program, {
      code: "invalid-mime-type",
      format: { mimeType: mediaType },
      target: context.getArgumentTarget(0)
    });
  }
  setMediaTypeHint(context.program, target, mediaType);
};
function getMediaTypeHint(program, target) {
  switch (target.kind) {
    case "Scalar":
      const isTypeSpecString = target.name === "string" && target.namespace?.name === "TypeSpec" && target.namespace.namespace === program.getGlobalNamespaceType();
      if (isTypeSpecString)
        return "text/plain";
    // Intentional fallthrough
    // eslint-disable-next-line no-fallthrough
    case "Union":
    case "Enum":
    case "Model": {
      const hint = _getMediaTypeHint(program, target);
      if (!hint) {
        const ancestor = target.kind === "Model" ? target.baseModel : target.kind === "Scalar" ? target.baseScalar : void 0;
        if (ancestor) {
          return getMediaTypeHint(program, ancestor);
        }
      }
      return hint;
    }
    default:
      return void 0;
  }
}
var [getFormat, setFormat] = useStateMap(createStateSymbol("format"));
var $format = (context, target, format) => {
  validateDecoratorUniqueOnNode(context, target, $format);
  if (!validateTargetingAString(context, target, "@format")) {
    return;
  }
  setFormat(context.program, target, format);
};
var [getPatternData, setPatternData] = useStateMap(createStateSymbol("patternValues"));
var $pattern = (context, target, pattern, validationMessage) => {
  validateDecoratorUniqueOnNode(context, target, $pattern);
  if (!validateTargetingAString(context, target, "@pattern")) {
    return;
  }
  try {
    new RegExp(pattern);
  } catch (e2) {
    reportDiagnostic(context.program, {
      code: "invalid-pattern-regex",
      target
    });
  }
  const patternData = {
    pattern,
    validationMessage
  };
  setPatternData(context.program, target, patternData);
};
function getPattern(program, target) {
  return getPatternData(program, target)?.pattern;
}
var $minLength = (context, target, minLength) => {
  validateDecoratorUniqueOnNode(context, target, $minLength);
  if (!validateTargetingAString(context, target, "@minLength") || !validateRange(context, minLength, getMaxLengthAsNumeric(context.program, target))) {
    return;
  }
  setMinLength(context.program, target, minLength);
};
var $maxLength = (context, target, maxLength) => {
  validateDecoratorUniqueOnNode(context, target, $maxLength);
  if (!validateTargetingAString(context, target, "@maxLength") || !validateRange(context, getMinLengthAsNumeric(context.program, target), maxLength)) {
    return;
  }
  setMaxLength(context.program, target, maxLength);
};
var $minItems = (context, target, minItems) => {
  validateDecoratorUniqueOnNode(context, target, $minItems);
  if (!validateTargetingAnArray(context, target, "@minItems")) {
    return;
  }
  if (!validateRange(context, minItems, getMaxItemsAsNumeric(context.program, target))) {
    return;
  }
  setMinItems(context.program, target, minItems);
};
var $maxItems = (context, target, maxItems) => {
  validateDecoratorUniqueOnNode(context, target, $maxItems);
  if (!validateTargetingAnArray(context, target, "@maxItems")) {
    return;
  }
  if (!validateRange(context, getMinItemsAsNumeric(context.program, target), maxItems)) {
    return;
  }
  setMaxItems(context.program, target, maxItems);
};
var $minValue = (context, target, minValue) => {
  validateDecoratorUniqueOnNode(context, target, $minValue);
  validateDecoratorNotOnType(context, target, $minValueExclusive, $minValue);
  const { program } = context;
  if (!validateTargetingANumeric(context, target, "@minValue")) {
    return;
  }
  if (!validateRange(context, minValue, getMaxValueAsNumeric(context.program, target) ?? getMaxValueExclusiveAsNumeric(context.program, target))) {
    return;
  }
  setMinValue(program, target, minValue);
};
var $maxValue = (context, target, maxValue) => {
  validateDecoratorUniqueOnNode(context, target, $maxValue);
  validateDecoratorNotOnType(context, target, $maxValueExclusive, $maxValue);
  const { program } = context;
  if (!validateTargetingANumeric(context, target, "@maxValue")) {
    return;
  }
  if (!validateRange(context, getMinValueAsNumeric(context.program, target) ?? getMinValueExclusiveAsNumeric(context.program, target), maxValue)) {
    return;
  }
  setMaxValue(program, target, maxValue);
};
var $minValueExclusive = (context, target, minValueExclusive) => {
  validateDecoratorUniqueOnNode(context, target, $minValueExclusive);
  validateDecoratorNotOnType(context, target, $minValue, $minValueExclusive);
  const { program } = context;
  if (!validateTargetingANumeric(context, target, "@minValueExclusive")) {
    return;
  }
  if (!validateRange(context, minValueExclusive, getMaxValueAsNumeric(context.program, target) ?? getMaxValueExclusiveAsNumeric(context.program, target))) {
    return;
  }
  setMinValueExclusive(program, target, minValueExclusive);
};
var $maxValueExclusive = (context, target, maxValueExclusive) => {
  validateDecoratorUniqueOnNode(context, target, $maxValueExclusive);
  validateDecoratorNotOnType(context, target, $maxValue, $maxValueExclusive);
  const { program } = context;
  if (!validateTargetingANumeric(context, target, "@maxValueExclusive")) {
    return;
  }
  if (!validateRange(context, getMinValueAsNumeric(context.program, target) ?? getMinValueExclusiveAsNumeric(context.program, target), maxValueExclusive)) {
    return;
  }
  setMaxValueExclusive(program, target, maxValueExclusive);
};
var [isSecret, markSecret] = useStateSet(createStateSymbol("secretTypes"));
var $secret = (context, target) => {
  validateDecoratorUniqueOnNode(context, target, $secret);
  if (!validateTargetingAString(context, target, "@secret")) {
    return;
  }
  markSecret(context.program, target);
};
var [getEncode, setEncodeData] = useStateMap(createStateSymbol("encode"));
var $encode = (context, target, encoding, encodeAs) => {
  validateDecoratorUniqueOnNode(context, target, $encode);
  const encodeData = computeEncoding(context.program, encoding, encodeAs);
  if (encodeData === void 0) {
    return;
  }
  const targetType = getPropertyType(target);
  validateEncodeData(context, targetType, encodeData);
  setEncodeData(context.program, target, encodeData);
};
function computeEncoding(program, encodingOrEncodeAs, encodeAs) {
  const strType = program.checker.getStdType("string");
  const resolvedEncodeAs = encodeAs ?? strType;
  if (typeof encodingOrEncodeAs === "string") {
    return { encoding: encodingOrEncodeAs, type: resolvedEncodeAs };
  } else if (isValue(encodingOrEncodeAs)) {
    const member = encodingOrEncodeAs.value;
    if (member.value && typeof member.value === "string") {
      return { encoding: member.value, type: resolvedEncodeAs };
    } else {
      return { encoding: getTypeName(member), type: resolvedEncodeAs };
    }
  } else {
    const originalType = encodingOrEncodeAs;
    if (originalType !== strType) {
      reportDiagnostic(program, {
        code: "invalid-encode",
        messageId: "firstArg",
        target: encodingOrEncodeAs
      });
      return void 0;
    }
    return { type: encodingOrEncodeAs };
  }
}
function validateEncodeData(context, target, encodeData) {
  function check(validTargets, validEncodeTypes) {
    const checker = context.program.checker;
    const isTargetValid = isTypeIn(target, (type) => validTargets.some((validTarget) => {
      return ignoreDiagnostics(checker.isTypeAssignableTo(type, checker.getStdType(validTarget), target));
    }));
    if (!isTargetValid) {
      reportDiagnostic(context.program, {
        code: "invalid-encode",
        messageId: "wrongType",
        format: {
          encoding: encodeData.encoding ?? "string",
          type: getTypeName(target),
          expected: validTargets.join(", ")
        },
        target: context.decoratorTarget
      });
    }
    const isEncodingTypeValid = validEncodeTypes.some((validEncoding) => {
      return ignoreDiagnostics(checker.isTypeAssignableTo(encodeData.type, checker.getStdType(validEncoding), target));
    });
    if (!isEncodingTypeValid) {
      const typeName = getTypeName(encodeData.type);
      reportDiagnostic(context.program, {
        code: "invalid-encode",
        messageId: ["unixTimestamp", "seconds"].includes(encodeData.encoding ?? "string") ? "wrongNumericEncodingType" : "wrongEncodingType",
        format: {
          encoding: encodeData.encoding,
          type: getTypeName(target),
          expected: validEncodeTypes.join(", "),
          actual: typeName
        },
        target: context.decoratorTarget
      });
    }
  }
  switch (encodeData.encoding) {
    case "rfc3339":
      return check(["utcDateTime", "offsetDateTime"], ["string"]);
    case "rfc7231":
      return check(["utcDateTime", "offsetDateTime"], ["string"]);
    case "unixTimestamp":
      return check(["utcDateTime"], ["integer"]);
    case "seconds":
      return check(["duration"], ["numeric"]);
    case "base64":
      return check(["bytes"], ["string"]);
    case "base64url":
      return check(["bytes"], ["string"]);
    case void 0:
      return check(["numeric"], ["string"]);
  }
}
var $withOptionalProperties = (context, target) => {
  target.properties.forEach((p2) => p2.optional = true);
};
var $withoutOmittedProperties = (context, target, omitProperties) => {
  const omitNames = /* @__PURE__ */ new Set();
  if (omitProperties.kind === "String") {
    omitNames.add(omitProperties.value);
  } else if (omitProperties.kind === "Union") {
    for (const variant of omitProperties.variants.values()) {
      if (variant.type.kind === "String") {
        omitNames.add(variant.type.value);
      }
    }
  }
  filterModelPropertiesInPlace(target, (prop) => !omitNames.has(prop.name));
};
var $withPickedProperties = (context, target, pickedProperties) => {
  const pickedNames = /* @__PURE__ */ new Set();
  if (pickedProperties.kind === "String") {
    pickedNames.add(pickedProperties.value);
  } else if (pickedProperties.kind === "Union") {
    for (const variant of pickedProperties.variants.values()) {
      if (variant.type.kind === "String") {
        pickedNames.add(variant.type.value);
      }
    }
  }
  filterModelPropertiesInPlace(target, (prop) => pickedNames.has(prop.name));
};
var $withoutDefaultValues = (context, target) => {
  target.properties.forEach((p2) => {
    delete p2.defaultValue;
  });
};
var [getTagsState, setTags] = useStateMap(createStateSymbol("tagProperties"));
var $tag = (context, target, tag) => {
  const tags = getTagsState(context.program, target);
  if (tags) {
    tags.push(tag);
  } else {
    setTags(context.program, target, [tag]);
  }
};
function getTags(program, target) {
  return getTagsState(program, target) || [];
}
function getAllTags(program, target) {
  const tags = /* @__PURE__ */ new Set();
  let current = target;
  while (current !== void 0) {
    for (const t2 of getTags(program, current)) {
      tags.add(t2);
    }
    if (current.kind === "Operation") {
      current = current.interface ?? current.namespace;
    } else {
      current = current.namespace;
    }
  }
  return tags.size > 0 ? Array.from(tags).reverse() : void 0;
}
var [getFriendlyName, setFriendlyName] = useStateMap(createStateSymbol("friendlyNames"));
var $friendlyName = (context, target, friendlyName, sourceObject) => {
  if (target.kind === "Model" || target.kind === "Operation") {
    if (context.decoratorTarget.kind === SyntaxKind.AugmentDecoratorStatement) {
      if (ignoreDiagnostics(context.program.checker.resolveTypeReference(context.decoratorTarget.targetType))?.node !== target.node) {
        return;
      }
    }
    if (context.decoratorTarget.kind === SyntaxKind.DecoratorExpression) {
      if (context.decoratorTarget.parent !== target.node) {
        return;
      }
    }
  }
  if (sourceObject) {
    friendlyName = replaceTemplatedStringFromProperties(friendlyName, sourceObject);
  }
  setFriendlyName(context.program, target, friendlyName);
};
var $key = (context, entity, altName) => {
  if (entity.optional) {
    reportDiagnostic(context.program, {
      code: "no-optional-key",
      format: { propertyName: entity.name },
      target: entity
    });
    return;
  }
  setKey(context.program, entity, altName || entity.name);
};
function getDeprecated(program, type) {
  return getDeprecationDetails(program, type)?.message;
}
var [getOverloads, setOverloads] = useStateMap(createStateSymbol("overloadedByKey"));
var [getOverloadedOperation, setOverloadBase] = useStateMap(createStateSymbol("overloadsOperation"));
var $overload = (context, target, overloadBase) => {
  const [paramValid, paramDiagnostics] = context.program.checker.isTypeAssignableTo(target.parameters, overloadBase.parameters, target);
  if (!paramValid)
    context.program.reportDiagnostics(paramDiagnostics);
  const [returnTypeValid, returnTypeDiagnostics] = context.program.checker.isTypeAssignableTo(target.returnType, overloadBase.returnType, target);
  if (!returnTypeValid)
    context.program.reportDiagnostics(returnTypeDiagnostics);
  if (!areOperationsInSameContainer(target, overloadBase)) {
    reportDiagnostic(context.program, {
      code: "overload-same-parent",
      target: context.decoratorTarget
    });
  }
  setOverloadBase(context.program, target, overloadBase);
  const existingOverloads = getOverloads(context.program, overloadBase) || new Array();
  setOverloads(context.program, overloadBase, existingOverloads.concat(target));
};
function areOperationsInSameContainer(op1, op2) {
  return op1.interface || op2.interface ? op1.interface === op2.interface : op1.namespace === op2.namespace;
}
function validateRange(context, min, max) {
  if (min === void 0 || max === void 0) {
    return true;
  }
  if (min.gt(max)) {
    reportDiagnostic(context.program, {
      code: "invalid-range",
      format: { start: min.toString(), end: max.toString() },
      target: context.decoratorTarget
    });
    return false;
  }
  return true;
}
var discriminatedDecorator = (context, entity, options = {}) => {
  setDiscriminatedOptions(context.program, entity, {
    envelope: "object",
    discriminatorPropertyName: "kind",
    envelopePropertyName: "value",
    ...options
  });
  const [_2, diagnostics] = getDiscriminatedUnion(context.program, entity);
  context.program.reportDiagnostics(diagnostics);
};
var $discriminator = (context, entity, propertyName) => {
  setDiscriminator(context.program, entity, { propertyName });
};
var [getExamplesState, setExamples] = useStateMap(createStateSymbol("examples"));
var $example = (context, target, _example, options) => {
  const decorator = target.decorators.find((d2) => d2.decorator === $example && d2.node === context.decoratorTarget);
  compilerAssert(decorator, `Couldn't find @example decorator`, context.decoratorTarget);
  const rawExample = decorator.args[0].value;
  if (Realm.realmForType.get(target) === void 0) {
    if (!checkExampleValid(context.program, rawExample, target.kind === "ModelProperty" ? target.type : target, context.getArgumentTarget(0))) {
      return;
    }
  }
  let list = getExamplesState(context.program, target);
  if (list === void 0) {
    list = [];
    setExamples(context.program, target, list);
  }
  list.push({ value: rawExample, ...options });
};
function getExamples(program, target) {
  return getExamplesState(program, target) ?? [];
}
var [getOpExamplesState, setOpExamples] = useStateMap(createStateSymbol("opExamples"));
var $opExample = (context, target, _example, options) => {
  const decorator = target.decorators.find((d2) => d2.decorator === $opExample && d2.node === context.decoratorTarget);
  compilerAssert(decorator, `Couldn't find @opExample decorator`, context.decoratorTarget);
  const rawExampleConfig = decorator.args[0].value;
  const parameters = rawExampleConfig.properties.get("parameters")?.value;
  const returnType = rawExampleConfig.properties.get("returnType")?.value;
  if (Realm.realmForType.get(target) === void 0) {
    if (parameters && !checkExampleValid(context.program, parameters, target.parameters, context.getArgumentTarget(0))) {
      return;
    }
    if (returnType && !checkExampleValid(context.program, returnType, target.returnType, context.getArgumentTarget(0))) {
      return;
    }
  }
  let list = getOpExamplesState(context.program, target);
  if (list === void 0) {
    list = [];
    setOpExamples(context.program, target, list);
  }
  list.push({ parameters, returnType, ...options });
};
function checkExampleValid(program, value, target, diagnosticTarget) {
  const exactType = program.checker.getValueExactType(value);
  const [assignable, diagnostics] = program.checker.isTypeAssignableTo(exactType ?? value.type, target, diagnosticTarget);
  if (!assignable) {
    program.reportDiagnostics(diagnostics);
  }
  return assignable;
}
function getOpExamples(program, target) {
  return getOpExamplesState(program, target) ?? [];
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/enum.js
defineKit({
  enum: {
    create(desc) {
      const en2 = this.program.checker.createType({
        kind: "Enum",
        name: desc.name,
        decorators: decoratorApplication(this, desc.decorators),
        members: createRekeyableMap()
      });
      if (Array.isArray(desc.members)) {
        for (const member of desc.members) {
          member.enum = en2;
          en2.members.set(member.name, member);
        }
      } else {
        for (const [name, member] of Object.entries(desc.members ?? {})) {
          en2.members.set(name, this.enumMember.create({ name, value: member, enum: en2 }));
        }
      }
      this.program.checker.finishType(en2);
      return en2;
    },
    is(type) {
      return type.entityKind === "Type" && type.kind === "Enum";
    },
    createFromUnion(type) {
      if (!type.name) {
        throw new Error("Cannot create an enum from an anonymous union.");
      }
      const enumMembers = [];
      for (const variant of type.variants.values()) {
        if (variant.name && typeof variant.name === "symbol" || !this.literal.isString(variant.type) && !this.literal.isNumeric(variant.type)) {
          continue;
        }
        const variantDoc = getDoc(this.program, variant);
        enumMembers.push(this.enumMember.create({
          name: variant.name,
          value: variant.type.value,
          decorators: variantDoc ? [[$doc, variantDoc]] : void 0
        }));
      }
      const unionDoc = getDoc(this.program, type);
      return this.enum.create({
        name: type.name,
        members: enumMembers,
        decorators: unionDoc ? [[$doc, unionDoc]] : void 0
      });
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/intrinsic.js
defineKit({
  intrinsic: {
    get any() {
      return this.program.checker.anyType;
    },
    get error() {
      return this.program.checker.errorType;
    },
    get never() {
      return this.program.checker.neverType;
    },
    get null() {
      return this.program.checker.nullType;
    },
    get void() {
      return this.program.checker.voidType;
    },
    is(entity) {
      return entity.entityKind === "Type" && entity.kind === "Intrinsic";
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/literal.js
defineKit({
  literal: {
    create(value) {
      return this.program.checker.createLiteralType(value);
    },
    createString(value) {
      return this.program.checker.createLiteralType(value);
    },
    createNumeric(value) {
      return this.program.checker.createLiteralType(value);
    },
    createBoolean(value) {
      return this.program.checker.createLiteralType(value);
    },
    isBoolean(type) {
      return type.entityKind === "Type" && type.kind === "Boolean";
    },
    isString(type) {
      return type.entityKind === "Type" && type.kind === "String";
    },
    isNumeric(type) {
      return type.entityKind === "Type" && type.kind === "Number";
    },
    is(type) {
      return this.literal.isBoolean(type) || this.literal.isNumeric(type) || this.literal.isString(type);
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/model-property.js
defineKit({
  modelProperty: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "ModelProperty";
    },
    getEncoding(type) {
      return getEncode(this.program, type) ?? getEncode(this.program, type.type);
    },
    getFormat(type) {
      return getFormat(this.program, type) ?? getFormat(this.program, type.type);
    },
    getVisibilityForClass(property, visibilityClass) {
      return getVisibilityForClass(this.program, property, visibilityClass);
    },
    create(desc) {
      return this.program.checker.createType({
        kind: "ModelProperty",
        name: desc.name,
        type: desc.type,
        optional: desc.optional ?? false,
        decorators: [],
        defaultValue: desc.defaultValue
      });
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/lib/intrinsic/decorators.js
var indexTypeKey = Symbol.for(`TypeSpec.index`);
var indexerDecorator = (context, target, key, value) => {
  const indexer = { key, value };
  context.program.stateMap(indexTypeKey).set(target, indexer);
};
function getIndexer(program, target) {
  return program.stateMap(indexTypeKey).get(target);
}
var docFromCommentDecorator = (context, target, key, text) => {
  setDocData(context.program, target, key, { value: text, source: "comment" });
};
var prototypeGetterKey = Symbol.for(`TypeSpec.Prototypes.getter`);
function getterDecorator(context, target) {
  context.program.stateMap(prototypeGetterKey).set(target, true);
}

// src/typespec/core/packages/compiler/dist/src/core/binder.js
var DecoratorFunctionPattern = /^\$/;
var SymbolTable = class extends Map {
  duplicates = /* @__PURE__ */ new Map();
  constructor(source) {
    super();
    if (source) {
      this.include(source);
    }
  }
  /** {@inheritdoc MutableSymboleTable} */
  include(source, parentSym) {
    for (const [key, value] of source) {
      super.set(key, { ...value, parent: parentSym ?? value.parent });
    }
    for (const [key, value] of source.duplicates) {
      this.duplicates.set(key, new Set(value));
    }
  }
  // First set for a given key wins, but record all duplicates for diagnostics.
  set(key, value) {
    const existing = super.get(key);
    if (existing === void 0) {
      super.set(key, value);
    } else {
      if (existing.flags & 8192) {
        mutate(existing).flags |= 16384;
      }
      const duplicateArray = this.duplicates.get(existing);
      if (duplicateArray) {
        duplicateArray.add(value);
      } else {
        this.duplicates.set(existing, /* @__PURE__ */ new Set([existing, value]));
      }
    }
    return this;
  }
};
function createSymbolTable(source) {
  return new SymbolTable(source);
}
function createBinder(program) {
  let currentFile;
  let parentNode;
  let fileNamespace;
  let scope;
  return {
    bindSourceFile,
    bindJsSourceFile,
    bindNode
  };
  function isFunctionName(name) {
    return DecoratorFunctionPattern.test(name);
  }
  function getFunctionName(name) {
    return name.replace(DecoratorFunctionPattern, "");
  }
  function bindJsSourceFile(sourceFile) {
    if (sourceFile.symbol !== void 0) {
      return;
    }
    fileNamespace = void 0;
    mutate(sourceFile).symbol = createSymbol(
      sourceFile,
      sourceFile.file.path,
      32768 | 1048576
      /* SymbolFlags.Declaration */
    );
    const rootNs = sourceFile.esmExports["namespace"];
    for (const [key, member] of Object.entries(sourceFile.esmExports)) {
      let name;
      let kind;
      if (key === "$flags") {
        const context = getLocationContext(program, sourceFile);
        if (context.type === "library" || context.type === "project") {
          mutate(context).flags = member;
        }
      } else if (key === "$decorators") {
        const value = member;
        for (const [namespaceName, decorators] of Object.entries(value)) {
          for (const [decoratorName, decorator] of Object.entries(decorators)) {
            bindFunctionImplementation(namespaceName === "" ? [] : namespaceName.split("."), "decorator", decoratorName, decorator, sourceFile);
          }
        }
      } else if (typeof member === "function") {
        if (isFunctionName(key)) {
          name = getFunctionName(key);
          kind = "decorator";
          if (name === "onValidate") {
            const context = getLocationContext(program, sourceFile);
            const metadata = context.type === "library" ? context.metadata : { type: "file" };
            program.onValidate(member, metadata);
            continue;
          } else if (name === "onEmit") {
            continue;
          }
        } else {
          name = key;
          kind = "function";
        }
        const nsParts = resolveJSMemberNamespaceParts(rootNs, member);
        bindFunctionImplementation(nsParts, kind, name, member, sourceFile);
      }
    }
  }
  function bindFunctionImplementation(nsParts, kind, name, fn2, sourceFile) {
    let containerSymbol = sourceFile.symbol;
    const tracer = program.tracer.sub("bind.js");
    for (const part of nsParts) {
      const existingBinding = containerSymbol.exports.get(part);
      const jsNamespaceNode = {
        kind: SyntaxKind.JsNamespaceDeclaration,
        id: {
          kind: SyntaxKind.Identifier,
          sv: part,
          pos: 0,
          end: 0,
          flags: 0,
          symbol: void 0
        },
        pos: sourceFile.pos,
        end: sourceFile.end,
        parent: sourceFile,
        flags: 0,
        symbol: void 0
      };
      const sym2 = createSymbol(jsNamespaceNode, part, 256 | 1048576, containerSymbol);
      mutate(jsNamespaceNode).symbol = sym2;
      if (existingBinding) {
        if (existingBinding.flags & 256) {
          containerSymbol = existingBinding;
        } else {
          mutate(containerSymbol.exports).set(part, sym2);
        }
      } else {
        mutate(sym2).exports = createSymbolTable();
        mutate(containerSymbol.exports).set(part, sym2);
        containerSymbol = sym2;
      }
    }
    let sym;
    if (kind === "decorator") {
      tracer.trace("decorator", `Bound decorator "@${name}" in namespace "${nsParts.join(".")}".`);
      sym = createSymbol(sourceFile, "@" + name, 512 | 1048576 | 2097152, containerSymbol);
    } else {
      tracer.trace("function", `Bound function "${name}" in namespace "${nsParts.join(".")}".`);
      sym = createSymbol(sourceFile, name, 2048 | 1048576 | 2097152, containerSymbol);
    }
    mutate(sym).value = fn2;
    mutate(containerSymbol.exports).set(sym.name, sym);
  }
  function resolveJSMemberNamespaceParts(rootNs, member) {
    const memberNs = member.namespace;
    const nsParts = [];
    if (rootNs) {
      nsParts.push(...rootNs.split("."));
    }
    if (memberNs) {
      nsParts.push(...memberNs.split("."));
    }
    return nsParts;
  }
  function bindSourceFile(script) {
    if (script.locals !== void 0) {
      return;
    }
    mutate(script).locals = createSymbolTable();
    mutate(script).symbol = createSymbol(
      script,
      script.file.path,
      32768
      /* SymbolFlags.SourceFile */
    );
    mutate(script.symbol).exports = createSymbolTable();
    fileNamespace = void 0;
    currentFile = script;
    scope = script;
    bindNode(script);
  }
  function bindNode(node) {
    if (!node)
      return;
    mutate(node).parent = parentNode;
    switch (node.kind) {
      case SyntaxKind.ModelStatement:
        bindModelStatement(node);
        break;
      case SyntaxKind.ModelExpression:
        bindModelExpression(node);
        break;
      case SyntaxKind.ModelProperty:
        bindModelProperty(node);
        break;
      case SyntaxKind.IntersectionExpression:
        bindIntersectionExpression(node);
        break;
      case SyntaxKind.ScalarStatement:
        bindScalarStatement(node);
        break;
      case SyntaxKind.ScalarConstructor:
        bindScalarConstructor(node);
        break;
      case SyntaxKind.InterfaceStatement:
        bindInterfaceStatement(node);
        break;
      case SyntaxKind.UnionStatement:
        bindUnionStatement(node);
        break;
      case SyntaxKind.AliasStatement:
        bindAliasStatement(node);
        break;
      case SyntaxKind.ConstStatement:
        bindConstStatement(node);
        break;
      case SyntaxKind.EnumStatement:
        bindEnumStatement(node);
        break;
      case SyntaxKind.EnumMember:
        bindEnumMember(node);
        break;
      case SyntaxKind.UnionVariant:
        bindUnionVariant(node);
        break;
      case SyntaxKind.NamespaceStatement:
        bindNamespaceStatement(node);
        break;
      case SyntaxKind.OperationStatement:
        bindOperationStatement(node);
        break;
      case SyntaxKind.TemplateParameterDeclaration:
        bindTemplateParameterDeclaration(node);
        break;
      case SyntaxKind.UsingStatement:
        bindUsingStatement(node);
        break;
      case SyntaxKind.DecoratorDeclarationStatement:
        bindDecoratorDeclarationStatement(node);
        break;
      case SyntaxKind.FunctionDeclarationStatement:
        bindFunctionDeclarationStatement(node);
        break;
      case SyntaxKind.FunctionParameter:
        bindFunctionParameter(node);
        break;
    }
    const prevParent = parentNode;
    parentNode = node;
    if (hasScope(node)) {
      const prevScope = scope;
      scope = node;
      visitChildren(node, bindNode);
      if ("locals" in node) {
        program.reportDuplicateSymbols(node.locals);
      }
      scope = prevScope;
    } else {
      visitChildren(node, bindNode);
    }
    parentNode = prevParent;
  }
  function bindTemplateParameterDeclaration(node) {
    declareSymbol(
      node,
      1024 | 1048576
      /* SymbolFlags.Declaration */
    );
  }
  function bindModelStatement(node) {
    declareSymbol(
      node,
      2 | 1048576
      /* SymbolFlags.Declaration */
    );
    mutate(node).locals = new SymbolTable();
  }
  function bindModelExpression(node) {
    bindSymbol(
      node,
      2
      /* SymbolFlags.Model */
    );
  }
  function bindModelProperty(node) {
    declareMember(node, 65536, node.id.sv);
  }
  function bindIntersectionExpression(node) {
    bindSymbol(
      node,
      2
      /* SymbolFlags.Model */
    );
  }
  function bindScalarStatement(node) {
    declareSymbol(
      node,
      4 | 1048576
      /* SymbolFlags.Declaration */
    );
    mutate(node).locals = new SymbolTable();
  }
  function bindScalarConstructor(node) {
    declareMember(node, 65536, node.id.sv);
  }
  function bindInterfaceStatement(node) {
    declareSymbol(
      node,
      32 | 1048576
      /* SymbolFlags.Declaration */
    );
    mutate(node).locals = new SymbolTable();
  }
  function bindUnionStatement(node) {
    declareSymbol(
      node,
      64 | 1048576
      /* SymbolFlags.Declaration */
    );
    mutate(node).locals = new SymbolTable();
  }
  function bindAliasStatement(node) {
    declareSymbol(
      node,
      128 | 1048576
      /* SymbolFlags.Declaration */
    );
    mutate(node).locals = new SymbolTable();
  }
  function bindConstStatement(node) {
    declareSymbol(
      node,
      131072 | 1048576
      /* SymbolFlags.Declaration */
    );
  }
  function bindEnumStatement(node) {
    declareSymbol(
      node,
      16 | 1048576
      /* SymbolFlags.Declaration */
    );
  }
  function bindEnumMember(node) {
    declareMember(node, 65536, node.id.sv);
  }
  function bindUnionVariant(node) {
    if (node.id) {
      declareMember(node, 65536, node.id.sv);
    }
  }
  function bindNamespaceStatement(statement) {
    const effectiveScope = fileNamespace ?? scope;
    const existingBinding = effectiveScope.symbol.exports.get(statement.id.sv);
    if (existingBinding && existingBinding.flags & 256) {
      mutate(statement).symbol = existingBinding;
      mutate(statement).locals = createSymbolTable();
      mutate(existingBinding.declarations).push(statement);
    } else {
      mutate(statement).locals = createSymbolTable();
      declareSymbol(
        statement,
        256 | 1048576
        /* SymbolFlags.Declaration */
      );
    }
    currentFile.namespaces.push(statement);
    if (statement.statements === void 0) {
      fileNamespace = statement;
      let current = statement;
      while (current.kind !== SyntaxKind.TypeSpecScript) {
        currentFile.inScopeNamespaces.push(current);
        current = current.parent;
      }
    }
  }
  function bindUsingStatement(statement) {
    mutate(currentFile.usings).push(statement);
  }
  function bindOperationStatement(statement) {
    if (scope.kind === SyntaxKind.InterfaceStatement) {
      declareMember(statement, 8 | 65536 | 1048576, statement.id.sv);
    } else {
      declareSymbol(
        statement,
        8 | 1048576
        /* SymbolFlags.Declaration */
      );
    }
    mutate(statement).locals = createSymbolTable();
  }
  function bindDecoratorDeclarationStatement(node) {
    declareSymbol(node, 512 | 1048576, `@${node.id.sv}`);
  }
  function bindFunctionDeclarationStatement(node) {
    declareSymbol(
      node,
      2048 | 1048576
      /* SymbolFlags.Declaration */
    );
  }
  function bindFunctionParameter(node) {
    const symbol = createSymbol(node, node.id.sv, 4096 | 1048576, scope.symbol);
    mutate(node).symbol = symbol;
  }
  function declareSymbol(node, flags, name) {
    compilerAssert(flags & 1048576, `Expected declaration symbol: ${name}`, node);
    switch (scope.kind) {
      case SyntaxKind.NamespaceStatement:
        return declareNamespaceMember(node, flags, name);
      case SyntaxKind.TypeSpecScript:
      case SyntaxKind.JsSourceFile:
        return declareScriptMember(node, flags, name);
      default:
        const key = name ?? node.id.sv;
        const symbol = createSymbol(node, key, flags, scope?.symbol);
        mutate(node).symbol = symbol;
        mutate(scope.locals).set(key, symbol);
        return symbol;
    }
  }
  function bindSymbol(node, flags) {
    const symbol = createSymbol(node, "-", flags, scope?.symbol);
    mutate(node).symbol = symbol;
    return symbol;
  }
  function declareNamespaceMember(node, flags, name) {
    if (flags & 256 && mergeNamespaceDeclarations(node, scope)) {
      return;
    }
    const key = name ?? node.id.sv;
    const symbol = createSymbol(node, key, flags, scope.symbol);
    mutate(node).symbol = symbol;
    mutate(scope.symbol.exports).set(key, symbol);
    return symbol;
  }
  function declareScriptMember(node, flags, name) {
    const effectiveScope = fileNamespace ?? scope;
    if (flags & 256 && mergeNamespaceDeclarations(node, effectiveScope)) {
      return;
    }
    const key = name ?? node.id.sv;
    const symbol = createSymbol(node, key, flags, fileNamespace?.symbol);
    mutate(node).symbol = symbol;
    mutate(effectiveScope.symbol.exports).set(key, symbol);
    return symbol;
  }
  function declareMember(node, flags, name) {
    const symbol = createSymbol(node, name, flags, scope.symbol);
    mutate(node).symbol = symbol;
    mutate(scope.symbol.members).set(name, symbol);
    return symbol;
  }
  function mergeNamespaceDeclarations(node, scope2) {
    const existingBinding = scope2.symbol.exports.get(node.id.sv);
    if (existingBinding && existingBinding.flags & 256) {
      mutate(existingBinding.declarations).push(node);
      mutate(node).symbol = existingBinding;
      return true;
    }
    return false;
  }
}
function hasScope(node) {
  switch (node.kind) {
    case SyntaxKind.ModelStatement:
    case SyntaxKind.ModelExpression:
    case SyntaxKind.ScalarStatement:
    case SyntaxKind.ConstStatement:
    case SyntaxKind.AliasStatement:
    case SyntaxKind.TypeSpecScript:
    case SyntaxKind.InterfaceStatement:
    case SyntaxKind.OperationStatement:
    case SyntaxKind.UnionStatement:
    case SyntaxKind.EnumStatement:
      return true;
    case SyntaxKind.NamespaceStatement:
      return node.statements !== void 0;
    default:
      return false;
  }
}
function createSymbol(node, name, flags, parent, value) {
  let exports;
  if (flags & 33024) {
    exports = createSymbolTable();
  }
  let members;
  if (flags & 118) {
    members = createSymbolTable();
  }
  compilerAssert(!(flags & 1048576) || node !== void 0, "Declaration without node");
  return {
    declarations: flags & 1048576 ? [node] : [],
    node: !(flags & 1048576) ? node : void 0,
    name,
    exports,
    members,
    flags,
    value,
    parent,
    metatypeMembers: createSymbolTable()
  };
}
function getSymNode(sym) {
  return sym.flags & 1048576 ? sym.declarations[0] : sym.node;
}

// src/typespec/core/packages/compiler/dist/src/core/compiler-code-fixes/change-identifier.codefix.js
function createChangeIdentifierCodeFix(node, newIdentifier) {
  return defineCodeFix({
    id: "change-identifier",
    label: `Change ${node.sv} to ${newIdentifier}`,
    fix: (context) => {
      const location = getSourceLocation(node);
      return context.replaceText(location, newIdentifier);
    }
  });
}

// src/typespec/core/packages/compiler/dist/src/core/compiler-code-fixes/convert-to-value.codefix.js
function createTupleToArrayValueCodeFix(node) {
  return defineCodeFix({
    id: "tuple-to-array-value",
    label: `Convert to an array value \`#[]\``,
    fix: (context) => {
      const result = [];
      addCreatedCodeFixResult(node);
      createChildTupleToArrValCodeFix(node, addCreatedCodeFixResult);
      return result;
      function addCreatedCodeFixResult(node2) {
        const location = getSourceLocation(node2);
        result.push(context.prependText(location, "#"));
      }
    }
  });
}
function createModelToObjectValueCodeFix(node) {
  return defineCodeFix({
    id: "model-to-object-value",
    label: `Convert to an object value \`#{}\``,
    fix: (context) => {
      const result = [];
      addCreatedCodeFixResult(node);
      createChildModelToObjValCodeFix(node, addCreatedCodeFixResult);
      return result;
      function addCreatedCodeFixResult(node2) {
        const location = getSourceLocation(node2);
        result.push(context.prependText(location, "#"));
      }
    }
  });
}
function createChildTupleToArrValCodeFix(node, addCreatedCodeFixResult) {
  for (const childNode of node.values) {
    if (childNode.kind === SyntaxKind.ModelExpression) {
      addCreatedCodeFixResult(childNode);
      createChildModelToObjValCodeFix(childNode, addCreatedCodeFixResult);
    } else if (childNode.kind === SyntaxKind.TupleExpression) {
      addCreatedCodeFixResult(childNode);
      createChildTupleToArrValCodeFix(childNode, addCreatedCodeFixResult);
    }
  }
}
function createChildModelToObjValCodeFix(node, addCreatedCodeFixResult) {
  for (const prop of node.properties.values()) {
    if (prop.kind === SyntaxKind.ModelProperty) {
      const childNode = prop.value;
      if (childNode.kind === SyntaxKind.ModelExpression) {
        addCreatedCodeFixResult(childNode);
        createChildModelToObjValCodeFix(childNode, addCreatedCodeFixResult);
      } else if (childNode.kind === SyntaxKind.TupleExpression) {
        addCreatedCodeFixResult(childNode);
        createChildTupleToArrValCodeFix(childNode, addCreatedCodeFixResult);
      }
    }
  }
}

// src/typespec/core/packages/compiler/dist/src/core/helpers/string-template-utils.js
function isStringTemplateSerializable(stringTemplate) {
  if (stringTemplate.stringValue !== void 0) {
    return [true, []];
  } else {
    return [false, explainStringTemplateNotSerializable(stringTemplate)];
  }
}
function explainStringTemplateNotSerializable(stringTemplate) {
  const diagnostics = createDiagnosticCollector();
  for (const span of stringTemplate.spans) {
    if (span.isInterpolated) {
      switch (span.type.kind) {
        case "String":
        case "Number":
        case "Boolean":
          break;
        case "StringTemplate":
          diagnostics.pipe(isStringTemplateSerializable(span.type));
          break;
        case "TemplateParameter":
          if (span.type.constraint && span.type.constraint.valueType !== void 0) {
            break;
          }
        // eslint-disable-next-line no-fallthrough
        default:
          diagnostics.add(createDiagnostic({
            code: "non-literal-string-template",
            target: span
          }));
      }
    }
  }
  return diagnostics.diagnostics;
}

// src/typespec/core/packages/compiler/dist/src/core/numeric.js
var InvalidNumericError = class extends Error {
  code = "InvalidNumeric";
};
var InternalDataSym = Symbol.for("NumericInternalData");
function isNumeric(arg) {
  return typeof arg === "object" && arg !== null && InternalDataSym in arg;
}
function Numeric(stringValue) {
  if (new.target) {
    throw new Error("Numeric is not a constructor");
  }
  const data = parse(stringValue);
  const isInteger2 = data.d === 0;
  const obj = {
    [InternalDataSym]: data,
    isInteger: isInteger2
  };
  const numeric = setTypedProptotype(obj, NumericPrototype);
  return Object.freeze(numeric);
}
function setTypedProptotype(obj, prototype) {
  Object.setPrototypeOf(obj, prototype);
  return obj;
}
function parse(original) {
  let stringValue = original;
  let start = 0;
  let sign = 1;
  let n2;
  let exp;
  let decimal = void 0;
  if (stringValue[0] === "-") {
    start = 1;
    sign = -1;
  }
  const second = stringValue[start + 1]?.toLowerCase();
  if (stringValue[start] === "0" && (second === "b" || second === "x" || second === "o")) {
    try {
      n2 = BigInt(stringValue.slice(start));
      exp = n2.toString().length;
      decimal = 0;
    } catch {
      throw new InvalidNumericError(`Invalid numeric value: ${original}`);
    }
  } else {
    while (stringValue[start] === "0") {
      start++;
    }
    const decimalPointIndex = stringValue.indexOf(".");
    const adjustedPointIndex = decimalPointIndex - start;
    if (decimalPointIndex !== -1) {
      exp = adjustedPointIndex;
      stringValue = stringValue.replace(".", "");
    }
    let i2;
    if ((i2 = stringValue.search(/e/i)) > 0) {
      if (exp === void 0) {
        exp = i2 - start;
      }
      exp += Number(stringValue.slice(i2 + 1));
      stringValue = stringValue.slice(start, i2);
      decimal = Math.max(stringValue.length - exp, 0);
    } else if (exp === void 0) {
      exp = stringValue.length - start;
      stringValue = stringValue.slice(start);
    } else {
      stringValue = stringValue.slice(start);
    }
    let end = stringValue.length;
    while (stringValue[end - 1] === "0" && end > adjustedPointIndex) {
      end--;
    }
    if (start === adjustedPointIndex + 1) {
      let cur = adjustedPointIndex;
      while (stringValue[cur] === "0" && cur < end) {
        cur++;
        exp--;
      }
    }
    try {
      stringValue = stringValue.slice(0, end);
      stringValue = stringValue + "0".repeat(Math.max(exp - stringValue.length, 0));
      n2 = BigInt(stringValue);
      if (n2 === 0n) {
        decimal = 0;
      } else if (decimal === void 0) {
        decimal = Math.max(stringValue.length - Math.max(exp, 0), 0);
      }
    } catch {
      throw new InvalidNumericError(`Invalid numeric value: ${original}`);
    }
  }
  return { n: n2, e: exp, s: sign, d: decimal };
}
function stringify(value) {
  if (value.n === 0n)
    return "0";
  const n2 = value.n.toString();
  const sign = value.s === -1 ? "-" : "";
  const int = value.e <= 0 ? "0" : n2.slice(0, value.e);
  const decimal = value.e < n2.length ? "." + n2.slice(-value.d).padStart(value.d, "0") : "";
  return sign + int + decimal;
}
var equals = (a2, b2) => a2.n === b2.n && a2.e === b2.e;
var compare = (a2, b2) => {
  if (a2.s < b2.s) {
    return -1;
  } else if (a2.s > b2.s) {
    return 1;
  }
  const neg = a2.s;
  if (a2.e < b2.e) {
    return -1 * neg;
  } else if (a2.e > b2.e) {
    return 1 * neg;
  }
  let aN = a2.n;
  let bN = b2.n;
  if (a2.d < b2.d) {
    aN *= 10n ** BigInt(b2.d - a2.d);
  } else {
    bN *= 10n ** BigInt(a2.d - b2.d);
  }
  if (aN < bN)
    return -1 * neg;
  if (aN > bN)
    return 1 * neg;
  return 0;
};
var NumericPrototype = {
  toString: function() {
    return stringify(this[InternalDataSym]);
  },
  asNumber: function() {
    const num = Number(stringify(this[InternalDataSym]));
    return equals(this[InternalDataSym], Numeric(num.toString())[InternalDataSym]) ? num : null;
  },
  asBigInt: function() {
    if (!this.isInteger) {
      return null;
    }
    const { s: s2, n: n2 } = this[InternalDataSym];
    return BigInt(s2) * n2;
  },
  equals: function(other) {
    return equals(this[InternalDataSym], other[InternalDataSym]);
  },
  lt: function(other) {
    return compare(this[InternalDataSym], other[InternalDataSym]) === -1;
  },
  lte: function(other) {
    return compare(this[InternalDataSym], other[InternalDataSym]) <= 0;
  },
  gt: function(other) {
    return compare(this[InternalDataSym], other[InternalDataSym]) === 1;
  },
  gte: function(other) {
    return compare(this[InternalDataSym], other[InternalDataSym]) >= 0;
  }
};
NumericPrototype.toString = function() {
  return stringify(this[InternalDataSym]);
};

// src/typespec/core/packages/compiler/dist/src/core/numeric-ranges.js
var numericRanges = {
  int64: [
    Numeric("-9223372036854775808"),
    Numeric("9223372036854775807"),
    { int: true, isJsNumber: false }
  ],
  int32: [Numeric("-2147483648"), Numeric("2147483647"), { int: true, isJsNumber: true }],
  int16: [Numeric("-32768"), Numeric("32767"), { int: true, isJsNumber: true }],
  int8: [Numeric("-128"), Numeric("127"), { int: true, isJsNumber: true }],
  uint64: [Numeric("0"), Numeric("18446744073709551615"), { int: true, isJsNumber: false }],
  uint32: [Numeric("0"), Numeric("4294967295"), { int: true, isJsNumber: true }],
  uint16: [Numeric("0"), Numeric("65535"), { int: true, isJsNumber: true }],
  uint8: [Numeric("0"), Numeric("255"), { int: true, isJsNumber: true }],
  safeint: [
    Numeric(Number.MIN_SAFE_INTEGER.toString()),
    Numeric(Number.MAX_SAFE_INTEGER.toString()),
    { int: true, isJsNumber: true }
  ],
  float32: [Numeric("-3.4e38"), Numeric("3.4e38"), { int: false, isJsNumber: true }],
  float64: [
    Numeric(`${-Number.MAX_VALUE}`),
    Numeric(Number.MAX_VALUE.toString()),
    { int: false, isJsNumber: true }
  ]
};

// src/typespec/core/packages/compiler/dist/src/core/js-marshaller.js
function marshallTypeForJS(value, valueConstraint) {
  switch (value.valueKind) {
    case "BooleanValue":
    case "StringValue":
      return value.value;
    case "NumericValue":
      return numericValueToJs(value, valueConstraint);
    case "ObjectValue":
      return objectValueToJs(value);
    case "ArrayValue":
      return arrayValueToJs(value);
    case "EnumValue":
      return value;
    case "NullValue":
      return null;
    case "ScalarValue":
      return value;
  }
}
function isNumericScalar(scalar) {
  let current = scalar;
  while (current) {
    if (current.name === "numeric" && current.namespace?.name === "TypeSpec") {
      return true;
    }
    current = current.baseScalar;
  }
  return false;
}
function canNumericConstraintBeJsNumber(type) {
  if (type === void 0)
    return true;
  switch (type.kind) {
    case "Scalar":
      if (isNumericScalar(type)) {
        return numericRanges[type.name]?.[2].isJsNumber;
      } else {
        return true;
      }
    case "Union":
      return [...type.variants.values()].every((x2) => canNumericConstraintBeJsNumber(x2.type));
    default:
      return true;
  }
}
function numericValueToJs(type, valueConstraint) {
  const canBeANumber = canNumericConstraintBeJsNumber(valueConstraint);
  if (canBeANumber) {
    const asNumber = type.value.asNumber();
    compilerAssert(asNumber !== null, `Numeric value '${type.value.toString()}' is not a able to convert to a number without loosing precision.`);
    return asNumber;
  }
  return type.value;
}
function objectValueToJs(type) {
  const result = {};
  for (const [key, value] of type.properties) {
    result[key] = marshallTypeForJS(value.value, void 0);
  }
  return result;
}
function arrayValueToJs(type) {
  return type.values.map((x2) => marshallTypeForJS(x2, void 0));
}

// src/typespec/core/packages/compiler/dist/src/core/type-relation-checker.js
var Related;
(function(Related2) {
  Related2[Related2["false"] = 0] = "false";
  Related2[Related2["true"] = 1] = "true";
  Related2[Related2["maybe"] = 2] = "maybe";
})(Related || (Related = {}));
var ReflectionNameToKind = {
  Enum: "Enum",
  EnumMember: "EnumMember",
  Interface: "Interface",
  Model: "Model",
  ModelProperty: "ModelProperty",
  Namespace: "Namespace",
  Operation: "Operation",
  Scalar: "Scalar",
  TemplateParameter: "TemplateParameter",
  Tuple: "Tuple",
  Union: "Union",
  UnionVariant: "UnionVariant"
};
function createTypeRelationChecker(program, checker) {
  return {
    isTypeAssignableTo,
    isValueOfType,
    isReflectionType,
    areScalarsRelated
  };
  function isTypeAssignableTo(source, target, diagnosticTarget) {
    const [related, errors] = isTypeAssignableToInternal(source, target, diagnosticTarget, new MultiKeyMap());
    return [related === Related.true, convertErrorsToDiagnostics(errors, diagnosticTarget)];
  }
  function isTargetChildOf(target, base) {
    const errorNode = "kind" in target && typeof target.kind === "number" ? target : target.node;
    const baseNode = "kind" in base && typeof base.kind === "number" ? base : base.node;
    let currentNode = errorNode;
    while (currentNode) {
      if (currentNode === baseNode) {
        return true;
      }
      currentNode = currentNode.parent;
    }
    return false;
  }
  function convertErrorsToDiagnostics(errors, diagnosticBase) {
    return errors.flatMap((x2) => convertErrorToDiagnostic(x2, diagnosticBase));
  }
  function combineErrorMessage(error) {
    let message = error.message;
    let current = error.children[0];
    let indent = "  ";
    while (current !== void 0) {
      message += current.message.split("\n").map((line) => `
${indent}${line}`).join("");
      indent += "  ";
      current = current.children[0];
    }
    return message;
  }
  function flattenErrors(error, diagnosticBase) {
    if (!isTargetChildOf(error.target, diagnosticBase)) {
      return [{ ...error, target: diagnosticBase }];
    }
    if (error.children.length === 0) {
      return [error];
    }
    return error.children.flatMap((x2) => flattenErrors(x2, error.target));
  }
  function convertErrorToDiagnostic(error, diagnosticBase) {
    const flattened = flattenErrors(error, diagnosticBase);
    return flattened.map((error2) => {
      const messageBase = error2.skipIfFirst && error2.children.length > 0 ? error2.children[0] : error2;
      const message = combineErrorMessage(messageBase);
      return {
        severity: "error",
        code: error2.code,
        message,
        target: error2.target
      };
    });
  }
  function isValueOfType(source, target, diagnosticTarget) {
    const [related, errors] = isValueOfTypeInternal(source, target, diagnosticTarget, new MultiKeyMap());
    return [related === Related.true, convertErrorsToDiagnostics(errors, diagnosticTarget)];
  }
  function isTypeAssignableToInternal(source, target, diagnosticTarget, relationCache) {
    const cached = relationCache.get([source, target]);
    if (cached !== void 0) {
      return [cached, []];
    }
    const [result, diagnostics] = isTypeAssignableToWorker(source, target, diagnosticTarget, new MultiKeyMap());
    relationCache.set([source, target], result);
    return [result, diagnostics];
  }
  function isTypeAssignableToWorker(source, target, diagnosticTarget, relationCache) {
    if ("kind" in source && source.kind === "TemplateParameter") {
      source = source.constraint ?? checker.anyType;
    }
    if (target.entityKind === "Indeterminate") {
      target = target.type;
    }
    if (source === target)
      return [Related.true, []];
    if (isValue(target)) {
      return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
    if (source.entityKind === "Indeterminate") {
      return isIndeterminateEntityAssignableTo(source, target, diagnosticTarget, relationCache);
    }
    if (target.entityKind === "MixedParameterConstraint") {
      return isAssignableToMixedParameterConstraint(source, target, diagnosticTarget, relationCache);
    }
    if (isValue(source) || source.entityKind === "MixedParameterConstraint" && source.valueType) {
      return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
    if (source.entityKind === "MixedParameterConstraint") {
      return isTypeAssignableToInternal(source.type, target, diagnosticTarget, relationCache);
    }
    const isSimpleTypeRelated = isSimpleTypeAssignableTo(source, target);
    if (isSimpleTypeRelated === true) {
      return [Related.true, []];
    } else if (isSimpleTypeRelated === false) {
      return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
    if (source.kind === "Union") {
      for (const variant of source.variants.values()) {
        const [variantAssignable] = isTypeAssignableToInternal(variant.type, target, diagnosticTarget, relationCache);
        if (!variantAssignable) {
          return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
        }
      }
      return [Related.true, []];
    }
    if (target.kind === "Model" && source.kind === "Model" && target.name !== "object" && target.indexer === void 0 && source.indexer && source.indexer.key.name === "integer") {
      return [
        Related.false,
        [
          createTypeRelationError({
            code: "missing-index",
            format: {
              indexType: getTypeName(source.indexer.key),
              sourceType: getTypeName(target)
            },
            diagnosticTarget
          })
        ]
      ];
    } else if (target.kind === "Model" && isArrayModelType(program, target) && source.kind === "Model") {
      if (isArrayModelType(program, source)) {
        return hasIndexAndIsAssignableTo(source, target, diagnosticTarget, relationCache);
      } else {
        return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
      }
    } else if (target.kind === "Model" && source.kind === "Model") {
      return areModelsRelated(source, target, diagnosticTarget, relationCache);
    } else if (target.kind === "Model" && isArrayModelType(program, target) && source.kind === "Tuple") {
      return isTupleAssignableToArray(source, target, diagnosticTarget, relationCache);
    } else if (target.kind === "Tuple" && source.kind === "Tuple") {
      return isTupleAssignableToTuple(source, target, diagnosticTarget, relationCache);
    } else if (target.kind === "Union") {
      return isAssignableToUnion(source, target, diagnosticTarget, relationCache);
    } else if (target.kind === "Enum") {
      return isAssignableToEnum(source, target, diagnosticTarget);
    }
    return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
  }
  function isIndeterminateEntityAssignableTo(indeterminate, target, diagnosticTarget, relationCache) {
    const [typeRelated, typeDiagnostics] = isTypeAssignableToInternal(indeterminate.type, target, diagnosticTarget, relationCache);
    if (typeRelated) {
      return [Related.true, []];
    }
    if (target.entityKind === "MixedParameterConstraint" && target.valueType) {
      const [valueRelated] = isTypeAssignableToInternal(indeterminate.type, target.valueType, diagnosticTarget, relationCache);
      if (valueRelated) {
        return [Related.true, []];
      }
    }
    return [Related.false, typeDiagnostics];
  }
  function isAssignableToValueType(source, target, diagnosticTarget, relationCache) {
    if (!isValue(source)) {
      return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
    return isValueOfTypeInternal(source, target, diagnosticTarget, relationCache);
  }
  function isAssignableToMixedParameterConstraint(source, target, diagnosticTarget, relationCache) {
    if ("entityKind" in source && source.entityKind === "MixedParameterConstraint") {
      if (source.type && target.type) {
        const [variantAssignable, diagnostics] = isTypeAssignableToInternal(source.type, target.type, diagnosticTarget, relationCache);
        if (variantAssignable === Related.false) {
          return [Related.false, diagnostics];
        }
        return [Related.true, []];
      }
      if (source.valueType && target.valueType) {
        const [variantAssignable, diagnostics] = isTypeAssignableToInternal(source.valueType, target.valueType, diagnosticTarget, relationCache);
        if (variantAssignable === Related.false) {
          return [Related.false, diagnostics];
        }
        return [Related.true, []];
      }
      return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
    if (target.type) {
      const [related] = isTypeAssignableToInternal(source, target.type, diagnosticTarget, relationCache);
      if (related) {
        return [Related.true, []];
      }
    }
    if (target.valueType) {
      const [related] = isAssignableToValueType(source, target.valueType, diagnosticTarget, relationCache);
      if (related) {
        return [Related.true, []];
      }
    }
    return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
  }
  function isValueOfTypeInternal(source, target, diagnosticTarget, relationCache) {
    return isTypeAssignableToInternal(source.type, target, diagnosticTarget, relationCache);
  }
  function isReflectionType(type) {
    return type.kind === "Model" && type.namespace?.name === "Reflection" && type.namespace?.namespace?.name === "TypeSpec";
  }
  function isRelatedToScalar(source, target) {
    switch (source.kind) {
      case "Number":
        return isNumericLiteralRelatedTo(source, target);
      case "String":
      case "StringTemplate":
        return isStringLiteralRelatedTo(source, target);
      case "Boolean":
        return areScalarsRelated(target, checker.getStdType("boolean"));
      case "Scalar":
        return areScalarsRelated(source, target);
      case "Union":
        return void 0;
      default:
        return false;
    }
  }
  function areScalarsRelated(source, target) {
    let current = source;
    while (current) {
      if (current === target) {
        return true;
      }
      current = current.baseScalar;
    }
    return false;
  }
  function isSimpleTypeAssignableTo(source, target) {
    if (isNeverType(source))
      return true;
    if (isVoidType(target))
      return false;
    if (isUnknownType(target))
      return true;
    if (isReflectionType(target)) {
      return source.kind === ReflectionNameToKind[target.name];
    }
    if (target.kind === "Scalar") {
      return isRelatedToScalar(source, target);
    }
    if (source.kind === "Scalar" && target.kind === "Model") {
      return false;
    }
    if (target.kind === "String") {
      return source.kind === "String" && source.value === target.value || source.kind === "StringTemplate" && source.stringValue === target.value;
    }
    if (target.kind === "StringTemplate" && target.stringValue) {
      return source.kind === "String" && source.value === target.stringValue || source.kind === "StringTemplate" && source.stringValue === target.stringValue;
    }
    if (target.kind === "Number") {
      return source.kind === "Number" && target.value === source.value;
    }
    return void 0;
  }
  function isNumericLiteralRelatedTo(source, target) {
    if (!isNumericAssignableToNumericScalar(source.numericValue, target)) {
      return false;
    }
    const min = getMinValueAsNumeric(program, target);
    const max = getMaxValueAsNumeric(program, target);
    const minExclusive = getMinValueExclusiveAsNumeric(program, target);
    const maxExclusive = getMaxValueExclusiveAsNumeric(program, target);
    if (min && source.numericValue.lt(min)) {
      return false;
    }
    if (minExclusive && source.numericValue.lte(minExclusive)) {
      return false;
    }
    if (max && source.numericValue.gt(max)) {
      return false;
    }
    if (maxExclusive && source.numericValue.gte(maxExclusive)) {
      return false;
    }
    return true;
  }
  function isNumericAssignableToNumericScalar(source, target) {
    if (!areScalarsRelated(target, checker.getStdType("numeric"))) {
      return false;
    }
    while (!target.namespace || !isTypeSpecNamespace2(target.namespace)) {
      compilerAssert(target.baseScalar, "Should not be possible to be derived from TypeSpec.numeric and not have a base when not in TypeSpec namespace.");
      target = target.baseScalar;
    }
    if (target.name === "numeric")
      return true;
    if (target.name === "decimal")
      return true;
    if (target.name === "decimal128")
      return true;
    const isInt = source.isInteger;
    if (target.name === "integer")
      return isInt;
    if (target.name === "float")
      return true;
    if (!(target.name in numericRanges))
      return false;
    const [low, high, options] = numericRanges[target.name];
    return source.gte(low) && source.lte(high) && (!options.int || isInt);
  }
  function isStringLiteralRelatedTo(source, target) {
    if (!areScalarsRelated(target, checker.getStdType("string"))) {
      return false;
    }
    if (source.kind === "StringTemplate") {
      return true;
    }
    const len = source.value.length;
    const min = getMinLength(program, target);
    const max = getMaxLength(program, target);
    if (min && len < min) {
      return false;
    }
    if (max && len > max) {
      return false;
    }
    return true;
  }
  function areModelsRelated(source, target, diagnosticTarget, relationCache) {
    relationCache.set([source, target], Related.maybe);
    const errors = [];
    const remainingProperties = new Map(source.properties);
    for (const prop of walkPropertiesInherited(target)) {
      const sourceProperty = getProperty2(source, prop.name);
      if (sourceProperty === void 0) {
        if (!prop.optional) {
          errors.push(createTypeRelationError({
            code: "missing-property",
            format: {
              propertyName: prop.name,
              sourceType: getTypeName(source),
              targetType: getTypeName(target)
            },
            diagnosticTarget: source
          }));
        }
      } else {
        remainingProperties.delete(prop.name);
        if (sourceProperty.optional && !prop.optional) {
          errors.push(createTypeRelationError({
            code: "property-required",
            format: {
              propName: prop.name,
              targetType: getTypeName(target)
            },
            diagnosticTarget
          }));
        }
        const [related, propErrors] = isTypeAssignableToInternal(sourceProperty.type, prop.type, diagnosticTarget, relationCache);
        if (!related) {
          errors.push(...wrapUnassignablePropertyErrors(sourceProperty, propErrors));
        }
      }
    }
    if (target.indexer) {
      const [_2, indexerDiagnostics] = arePropertiesAssignableToIndexer(remainingProperties, target.indexer.value, diagnosticTarget, relationCache);
      errors.push(...indexerDiagnostics);
      if (source.name !== "" && target.indexer.key.name !== "integer") {
        const [related, indexDiagnostics] = hasIndexAndIsAssignableTo(source, target, diagnosticTarget, relationCache);
        if (!related) {
          errors.push(...indexDiagnostics);
        }
      }
    } else if (shouldCheckExcessProperties(source)) {
      for (const [propName, prop] of remainingProperties) {
        if (shouldCheckExcessProperty(prop)) {
          errors.push(createTypeRelationError({
            code: "unexpected-property",
            format: {
              propertyName: propName,
              type: getEntityName(target)
            },
            diagnosticTarget: prop
          }));
        }
      }
    }
    return [
      errors.length === 0 ? Related.true : Related.false,
      wrapUnassignableErrors(source, target, errors)
    ];
  }
  function shouldCheckExcessProperties(model) {
    return model.node?.kind === SyntaxKind.ObjectLiteral;
  }
  function shouldCheckExcessProperty(prop) {
    return prop.node?.kind === SyntaxKind.ObjectLiteralProperty && prop.node.parent === prop.model?.node;
  }
  function getProperty2(model, name) {
    return model.properties.get(name) ?? (model.baseModel !== void 0 ? getProperty2(model.baseModel, name) : void 0);
  }
  function arePropertiesAssignableToIndexer(properties, indexerConstaint, diagnosticTarget, relationCache) {
    for (const prop of properties.values()) {
      const [related, diagnostics] = isTypeAssignableToInternal(prop.type, indexerConstaint, diagnosticTarget, relationCache);
      if (!related) {
        return [Related.false, diagnostics];
      }
    }
    return [Related.true, []];
  }
  function hasIndexAndIsAssignableTo(source, target, diagnosticTarget, relationCache) {
    if (source.indexer === void 0 || source.indexer.key !== target.indexer.key) {
      return [
        Related.false,
        [
          createTypeRelationError({
            code: "missing-index",
            format: {
              indexType: getTypeName(target.indexer.key),
              sourceType: getTypeName(source)
            },
            diagnosticTarget
          })
        ]
      ];
    }
    return isTypeAssignableToInternal(source.indexer.value, target.indexer.value, diagnosticTarget, relationCache);
  }
  function isTupleAssignableToArray(source, target, diagnosticTarget, relationCache) {
    const minItems = getMinItems(program, target);
    const maxItems = getMaxItems(program, target);
    if (minItems !== void 0 && source.values.length < minItems) {
      return [
        Related.false,
        [
          createUnassignableDiagnostic(source, target, diagnosticTarget, `Source has ${source.values.length} element(s) but target requires ${minItems}.`)
        ]
      ];
    }
    if (maxItems !== void 0 && source.values.length > maxItems) {
      return [
        Related.false,
        [
          createUnassignableDiagnostic(source, target, diagnosticTarget, `Source has ${source.values.length} element(s) but target only allows ${maxItems}.`)
        ]
      ];
    }
    for (const item of source.values) {
      const [related, diagnostics] = isTypeAssignableToInternal(item, target.indexer.value, diagnosticTarget, relationCache);
      if (!related) {
        return [Related.false, diagnostics];
      }
    }
    return [Related.true, []];
  }
  function isTupleAssignableToTuple(source, target, diagnosticTarget, relationCache) {
    if (source.values.length !== target.values.length) {
      return [
        Related.false,
        [
          createUnassignableDiagnostic(source, target, diagnosticTarget, `Source has ${source.values.length} element(s) but target requires ${target.values.length}.`)
        ]
      ];
    }
    for (const [index, sourceItem] of source.values.entries()) {
      const targetItem = target.values[index];
      const [related, diagnostics] = isTypeAssignableToInternal(sourceItem, targetItem, diagnosticTarget, relationCache);
      if (!related) {
        return [Related.false, diagnostics];
      }
    }
    return [Related.true, []];
  }
  function isAssignableToUnion(source, target, diagnosticTarget, relationCache) {
    if (source.kind === "UnionVariant" && source.union === target) {
      return [Related.true, []];
    }
    for (const option of target.variants.values()) {
      const [related] = isTypeAssignableToInternal(source, option.type, diagnosticTarget, relationCache);
      if (related) {
        return [Related.true, []];
      }
    }
    return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
  }
  function isAssignableToEnum(source, target, diagnosticTarget) {
    switch (source.kind) {
      case "Enum":
        if (source === target) {
          return [Related.true, []];
        } else {
          return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
        }
      case "EnumMember":
        if (source.enum === target) {
          return [Related.true, []];
        } else {
          return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
        }
      default:
        return [Related.false, [createUnassignableDiagnostic(source, target, diagnosticTarget)]];
    }
  }
  function isTypeSpecNamespace2(namespace) {
    return namespace.name === "TypeSpec" && namespace.namespace === checker.getGlobalNamespaceType();
  }
}
function wrapUnassignableErrors(source, target, errors) {
  const error = createUnassignableDiagnostic(source, target, source);
  error.children = errors;
  return [error];
}
function wrapUnassignablePropertyErrors(source, errors) {
  const error = createTypeRelationError({
    code: "property-unassignable",
    diagnosticTarget: source,
    format: {
      propName: source.name
    },
    skipIfFirst: true
  });
  error.children = errors;
  return [error];
}
function createTypeRelationError({ code, format, details, diagnosticTarget, skipIfFirst }) {
  const diag = createDiagnostic({
    code,
    format,
    target: NoTarget
  });
  return {
    code,
    message: details ? `${diag.message}
  ${details}` : diag.message,
    target: diagnosticTarget,
    skipIfFirst,
    children: []
  };
}
function createUnassignableDiagnostic(source, target, diagnosticTarget, details) {
  return createTypeRelationError({
    code: "unassignable",
    format: {
      sourceType: getEntityName(source),
      targetType: getEntityName(target)
    },
    diagnosticTarget,
    details
  });
}

// src/typespec/core/packages/compiler/dist/src/core/checker.js
var TypeInstantiationMap = class extends MultiKeyMap {
};
function createChecker(program, resolver) {
  const waitingForResolution = /* @__PURE__ */ new Map();
  const stats = {
    createdTypes: 0,
    finishedTypes: 0
  };
  const stdTypes = {};
  const indeterminateEntities = /* @__PURE__ */ new WeakMap();
  const docFromCommentForSym = /* @__PURE__ */ new Map();
  const referenceSymCache = /* @__PURE__ */ new WeakMap();
  const valueExactTypes = /* @__PURE__ */ new WeakMap();
  let onCheckerDiagnostic = (x2) => {
    program.reportDiagnostic(x2);
  };
  const typePrototype = {};
  const globalNamespaceType = createGlobalNamespaceType();
  const nodeDeprecationMap = /* @__PURE__ */ new Map();
  const errorType = createAndFinishType({ kind: "Intrinsic", name: "ErrorType" });
  const voidType = createAndFinishType({ kind: "Intrinsic", name: "void" });
  const neverType = createAndFinishType({ kind: "Intrinsic", name: "never" });
  const unknownType = createAndFinishType({ kind: "Intrinsic", name: "unknown" });
  const nullType = createAndFinishType({ kind: "Intrinsic", name: "null" });
  const pendingResolutions = new PendingResolutions();
  const typespecNamespaceBinding = resolver.symbols.global.exports.get("TypeSpec");
  if (typespecNamespaceBinding) {
    initializeTypeSpecIntrinsics();
  }
  const templateParameterUsageMap = /* @__PURE__ */ new Map();
  const checker = {
    getTypeForNode,
    checkProgram,
    checkSourceFile,
    getLiteralType,
    getGlobalNamespaceType,
    cloneType,
    resolveRelatedSymbols,
    resolveCompletions,
    neverType,
    errorType,
    nullType,
    anyType: unknownType,
    voidType,
    typePrototype,
    createType,
    createAndFinishType,
    createLiteralType,
    finishType,
    isStdType: isStdType2,
    getStdType,
    resolveTypeReference,
    resolveTypeOrValueReference,
    getValueForNode,
    getTypeOrValueForNode,
    getValueExactType,
    getTemplateParameterUsageMap,
    isTypeAssignableTo: void 0,
    stats
  };
  const relation = createTypeRelationChecker(program, checker);
  checker.isTypeAssignableTo = relation.isTypeAssignableTo;
  return checker;
  function getTemplateParameterUsageMap() {
    return templateParameterUsageMap;
  }
  function wrapInstantiationDiagnostic(diagnostic, templateMapper) {
    if (templateMapper === void 0 || typeof diagnostic.target !== "object")
      return diagnostic;
    return {
      ...diagnostic,
      target: {
        node: diagnostic.target,
        templateMapper
      }
    };
  }
  function reportCheckerDiagnostic(diagnostic, mapper) {
    onCheckerDiagnostic(wrapInstantiationDiagnostic(diagnostic, mapper));
  }
  function reportCheckerDiagnostics(diagnostics) {
    diagnostics.forEach((x2) => reportCheckerDiagnostic(x2));
  }
  function initializeTypeSpecIntrinsics() {
    mutate(typespecNamespaceBinding.exports).set("log", {
      flags: 2048,
      name: "log",
      value(p2, ...strs) {
        program.trace("log", strs.join(" "));
        return voidType;
      },
      declarations: [],
      node: void 0
      // TODO: is this correct?
    });
    mutate(resolver.symbols.null).type = nullType;
    getSymbolLinks(resolver.symbols.null).type = nullType;
  }
  function getStdType(name) {
    const type = stdTypes[name];
    if (type !== void 0) {
      return type;
    }
    const sym = typespecNamespaceBinding?.exports?.get(name);
    compilerAssert(sym, `Unexpected missing symbol to std type "${name}"`);
    if (sym.flags & 2) {
      checkModelStatement(sym.declarations[0], void 0);
    } else {
      checkScalar(sym.declarations[0], void 0);
    }
    const loadedType = stdTypes[name];
    compilerAssert(loadedType, `TypeSpec std type "${name}" should have been initalized before using array syntax.`);
    return loadedType;
  }
  function linkType(links, type, mapper) {
    if (mapper === void 0) {
      links.declaredType = type;
      links.instantiations = new TypeInstantiationMap();
    } else if (links.instantiations) {
      links.instantiations.set(mapper.args, type);
    }
  }
  function linkMemberType(links, type, mapper) {
    if (mapper === void 0) {
      links.declaredType = type;
    }
  }
  function checkMemberSym(sym, mapper) {
    const symbolLinks = getSymbolLinks(sym);
    const memberContainer = getTypeForNode(getSymNode(sym.parent), mapper);
    const type = symbolLinks.declaredType ?? symbolLinks.type;
    if (type) {
      return type;
    } else {
      return checkMember(getSymNode(sym), mapper, memberContainer);
    }
  }
  function checkMember(node, mapper, containerType) {
    switch (node.kind) {
      case SyntaxKind.ModelProperty:
        return checkModelProperty(node, mapper);
      case SyntaxKind.EnumMember:
        return checkEnumMember(node, mapper, containerType);
      case SyntaxKind.OperationStatement:
        return checkOperation(node, mapper, containerType);
      case SyntaxKind.UnionVariant:
        return checkUnionVariant(node, mapper);
      case SyntaxKind.ScalarConstructor:
        return checkScalarConstructor(node, mapper, containerType);
    }
  }
  function getTypeForTypeOrIndeterminate(entity) {
    if (entity.entityKind === "Indeterminate") {
      return entity.type;
    }
    return entity;
  }
  function getTypeForNode(node, mapper) {
    const entity = checkNode(node, mapper);
    if (entity === null) {
      return errorType;
    }
    if (entity.entityKind === "Indeterminate") {
      return entity.type;
    }
    if (isValue(entity)) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "value-in-type",
        target: node
      }));
      return errorType;
    }
    if (entity.kind === "TemplateParameter") {
      if (entity.constraint?.valueType) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "value-in-type",
          messageId: "referenceTemplate",
          target: node
        }));
      }
    }
    return entity;
  }
  function getValueForNode(node, mapper, constraint) {
    const initial = checkNode(node, mapper, constraint);
    if (initial === null) {
      return null;
    }
    let entity;
    if (initial.entityKind === "Indeterminate") {
      entity = getValueFromIndeterminate(initial.type, constraint, node);
    } else {
      entity = initial;
    }
    if (entity === null) {
      return null;
    }
    if (isValue(entity)) {
      return constraint ? inferScalarsFromConstraints(entity, constraint.type) : entity;
    }
    if (entity.kind === "TemplateParameter" && entity.constraint?.valueType && entity.constraint.type === void 0 && mapper === void 0) {
      return createValue({
        entityKind: "Value",
        valueKind: "TemplateValue",
        type: entity.constraint.valueType
      }, entity.constraint.valueType);
    }
    reportExpectedValue(node, entity);
    return null;
  }
  function reportExpectedValue(target, type) {
    if (type.kind === "Model" && type.name === "" && target.kind === SyntaxKind.ModelExpression) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "expect-value",
        messageId: "model",
        format: { name: getTypeName(type) },
        codefixes: [createModelToObjectValueCodeFix(target)],
        target
      }));
    } else if (type.kind === "Tuple" && target.kind === SyntaxKind.TupleExpression) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "expect-value",
        messageId: "tuple",
        format: { name: getTypeName(type) },
        codefixes: [createTupleToArrayValueCodeFix(target)],
        target
      }));
    } else {
      reportCheckerDiagnostic(createDiagnostic({
        code: "expect-value",
        format: { name: getTypeName(type) },
        target
      }));
    }
  }
  function getValueFromIndeterminate(type, constraint, node) {
    switch (type.kind) {
      case "String":
      case "StringTemplate":
        return checkStringValue(type, constraint, node);
      case "Number":
        return checkNumericValue(type, constraint, node);
      case "Boolean":
        return checkBooleanValue(type, constraint, node);
      case "EnumMember":
        return checkEnumValue(type, constraint, node);
      case "UnionVariant":
        return getValueFromIndeterminate(type.type, constraint, node);
      case "Intrinsic":
        switch (type.name) {
          case "null":
            return checkNullValue(type, constraint, node);
        }
        return type;
      default:
        return type;
    }
  }
  function interceptTypesUsedAsValue(type) {
    switch (type.kind) {
      case "Tuple":
        return interceptTupleUsedAsValue(type);
      case "Model":
        return interceptModelExpressionUsedAsValue(type);
      default:
        return type;
    }
  }
  function interceptModelExpressionUsedAsValue(model) {
    if (model.node?.kind !== SyntaxKind.ModelExpression) {
      return model;
    }
    reportCheckerDiagnostic(createDiagnostic({
      code: "expect-value",
      codefixes: [createModelToObjectValueCodeFix(model.node)],
      messageId: "modelExpression",
      target: model.node
    }));
    return null;
  }
  function interceptTupleUsedAsValue(tuple) {
    if (tuple.node?.kind !== SyntaxKind.TupleExpression) {
      return tuple;
    }
    reportCheckerDiagnostic(createDiagnostic({
      code: "expect-value",
      codefixes: [createTupleToArrayValueCodeFix(tuple.node)],
      messageId: "tuple",
      target: tuple.node
    }));
    return null;
  }
  function shouldTryInterceptTypeUsedAsValue(constraint) {
    return Boolean(constraint?.valueType && !constraint.type);
  }
  function getTypeOrValueForNode(node, mapper, constraint) {
    const valueConstraint = extractValueOfConstraints(constraint);
    const entity = checkNode(node, mapper, valueConstraint);
    if (entity === null) {
      return entity;
    } else if (isType(entity)) {
      if (shouldTryInterceptTypeUsedAsValue(constraint?.constraint)) {
        return interceptTypesUsedAsValue(entity);
      } else {
        return entity;
      }
    } else if (isValue(entity)) {
      return entity;
    }
    compilerAssert(entity.entityKind === "Indeterminate", "Expected indeterminate entity");
    if (valueConstraint) {
      const valueDiagnostics = [];
      const oldDiagnosticHook = onCheckerDiagnostic;
      onCheckerDiagnostic = (x2) => valueDiagnostics.push(x2);
      const result = getValueFromIndeterminate(entity.type, valueConstraint, node);
      onCheckerDiagnostic = oldDiagnosticHook;
      if (result) {
        reportCheckerDiagnostics(valueDiagnostics);
        return result;
      }
    }
    return entity.type;
  }
  function extractValueOfConstraints(constraint) {
    if (constraint?.constraint.valueType) {
      return { kind: constraint.kind, type: constraint.constraint.valueType };
    } else {
      return void 0;
    }
  }
  function checkNode(node, mapper, valueConstraint) {
    switch (node.kind) {
      case SyntaxKind.ModelExpression:
        return checkModel(node, mapper);
      case SyntaxKind.ModelStatement:
        return checkModel(node, mapper);
      case SyntaxKind.ModelProperty:
        return checkModelProperty(node, mapper);
      case SyntaxKind.ScalarStatement:
        return checkScalar(node, mapper);
      case SyntaxKind.AliasStatement:
        return checkAlias(node, mapper);
      case SyntaxKind.EnumStatement:
        return checkEnum(node, mapper);
      case SyntaxKind.EnumMember:
        return checkEnumMember(node, mapper);
      case SyntaxKind.InterfaceStatement:
        return checkInterface(node, mapper);
      case SyntaxKind.UnionStatement:
        return checkUnion(node, mapper);
      case SyntaxKind.UnionVariant:
        return checkUnionVariant(node, mapper);
      case SyntaxKind.NamespaceStatement:
      case SyntaxKind.JsNamespaceDeclaration:
        return checkNamespace(node);
      case SyntaxKind.OperationStatement:
        return checkOperation(node, mapper);
      case SyntaxKind.NumericLiteral:
        return checkNumericLiteral(node);
      case SyntaxKind.BooleanLiteral:
        return checkBooleanLiteral(node);
      case SyntaxKind.StringLiteral:
        return checkStringLiteral(node);
      case SyntaxKind.TupleExpression:
        return checkTupleExpression(node, mapper);
      case SyntaxKind.StringTemplateExpression:
        return checkStringTemplateExpresion(node, mapper);
      case SyntaxKind.ArrayExpression:
        return checkArrayExpression(node, mapper);
      case SyntaxKind.UnionExpression:
        return checkUnionExpression(node, mapper);
      case SyntaxKind.IntersectionExpression:
        return checkIntersectionExpression(node, mapper);
      case SyntaxKind.DecoratorDeclarationStatement:
        return checkDecoratorDeclaration(node, mapper);
      case SyntaxKind.FunctionDeclarationStatement:
        return checkFunctionDeclaration(node, mapper);
      case SyntaxKind.TypeReference:
        return checkTypeOrValueReference(node, mapper);
      case SyntaxKind.TemplateArgument:
        return checkTemplateArgument(node, mapper);
      case SyntaxKind.TemplateParameterDeclaration:
        return checkTemplateParameterDeclaration(node, mapper);
      case SyntaxKind.VoidKeyword:
        return voidType;
      case SyntaxKind.NeverKeyword:
        return neverType;
      case SyntaxKind.UnknownKeyword:
        return unknownType;
      case SyntaxKind.ObjectLiteral:
        return checkObjectValue(node, mapper, valueConstraint);
      case SyntaxKind.ArrayLiteral:
        return checkArrayValue(node, mapper, valueConstraint);
      case SyntaxKind.ConstStatement:
        return checkConst(node);
      case SyntaxKind.CallExpression:
        return checkCallExpression(node, mapper);
      case SyntaxKind.TypeOfExpression:
        return checkTypeOfExpression(node, mapper);
      case SyntaxKind.AugmentDecoratorStatement:
        return checkAugmentDecorator(node);
      case SyntaxKind.UsingStatement:
        return checkUsings(node);
      default:
        return errorType;
    }
  }
  function getNodeSym(node) {
    const symbol = node.kind === SyntaxKind.OperationStatement && node.parent?.kind === SyntaxKind.InterfaceStatement ? getSymbolForMember(node) : node.symbol;
    return symbol;
  }
  function isTypeSpecNamespace2(namespace) {
    return namespace.name === "TypeSpec" && namespace.namespace === globalNamespaceType;
  }
  function isInTypeSpecNamespace2(type) {
    return Boolean(type.namespace && isTypeSpecNamespace2(type.namespace));
  }
  function checkTemplateParameterDeclaration(node, mapper) {
    const parentNode = node.parent;
    const grandParentNode = parentNode.parent;
    const links = getSymbolLinks(node.symbol);
    if (!templateParameterUsageMap.has(node)) {
      templateParameterUsageMap.set(node, false);
    }
    if (pendingResolutions.has(getNodeSym(node), ResolutionKind.Constraint)) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "circular-constraint",
          format: { typeName: node.id.sv },
          target: node.constraint
        }));
      }
      return errorType;
    }
    let type = links.declaredType;
    if (type === void 0) {
      if (grandParentNode) {
        if (grandParentNode.locals?.has(node.id.sv)) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "shadow",
            format: { name: node.id.sv },
            target: node
          }));
        }
      }
      const index = parentNode.templateParameters.findIndex((v2) => v2 === node);
      type = links.declaredType = createAndFinishType({
        kind: "TemplateParameter",
        node
      });
      if (node.constraint) {
        pendingResolutions.start(getNodeSym(node), ResolutionKind.Constraint);
        type.constraint = getParamConstraintEntityForNode(node.constraint);
        pendingResolutions.finish(getNodeSym(node), ResolutionKind.Constraint);
      }
      if (node.default) {
        type.default = unknownType;
        type.default = checkTemplateParameterDefault(node.default, parentNode.templateParameters, index, type.constraint);
      }
    }
    return mapper ? mapper.getMappedType(type) : type;
  }
  function getResolvedTypeParameterDefault(declaredType, node, mapper) {
    if (declaredType.default === void 0) {
      return void 0;
    }
    if (isType(declaredType.default) && isErrorType(declaredType.default) || declaredType.default === null) {
      return declaredType.default;
    }
    return checkNode(node.default, mapper);
  }
  function checkTemplateParameterDefault(nodeDefault, templateParameters, index, constraint) {
    function visit(node) {
      const entity = checkNode(node);
      let hasError = false;
      if (entity !== null && "kind" in entity && entity.kind === "TemplateParameter") {
        for (let i2 = index; i2 < templateParameters.length; i2++) {
          if (entity.node?.symbol === templateParameters[i2].symbol) {
            reportCheckerDiagnostic(createDiagnostic({ code: "invalid-template-default", target: node }));
            return void 0;
          }
        }
        return entity;
      }
      visitChildren(node, (x2) => {
        const visited = visit(x2);
        if (visited === void 0) {
          hasError = true;
        }
      });
      return hasError ? void 0 : entity;
    }
    const type = visit(nodeDefault) ?? errorType;
    if (!("kind" in type && isErrorType(type)) && constraint) {
      checkTypeAssignable(type, constraint, nodeDefault);
    }
    return type;
  }
  function checkTypeReference(node, mapper, instantiateTemplate2 = true) {
    const sym = resolveTypeReferenceSym(node, mapper);
    if (!sym) {
      return errorType;
    }
    const type = checkTypeReferenceSymbol(sym, node, mapper, instantiateTemplate2);
    return type;
  }
  function checkTypeOrValueReference(node, mapper, instantiateTemplate2 = true) {
    const sym = resolveTypeReferenceSym(node, mapper);
    if (!sym) {
      return errorType;
    }
    return checkTypeOrValueReferenceSymbol(sym, node, mapper, instantiateTemplate2) ?? errorType;
  }
  function checkTemplateArgument(node, mapper) {
    return checkNode(node.argument, mapper);
  }
  function resolveTypeOrValueReference(node) {
    const oldDiagnosticHook = onCheckerDiagnostic;
    const diagnostics = [];
    onCheckerDiagnostic = (x2) => diagnostics.push(x2);
    const entity = checkTypeOrValueReference(node, void 0, false);
    onCheckerDiagnostic = oldDiagnosticHook;
    return [entity === errorType ? void 0 : entity, diagnostics];
  }
  function resolveTypeReference(node) {
    const oldDiagnosticHook = onCheckerDiagnostic;
    const diagnostics = [];
    onCheckerDiagnostic = (x2) => diagnostics.push(x2);
    const type = checkTypeReference(node, void 0, false);
    onCheckerDiagnostic = oldDiagnosticHook;
    return [type === errorType ? void 0 : type, diagnostics];
  }
  function copyDeprecation(sourceType, destType) {
    const deprecationDetails = getDeprecationDetails(program, sourceType);
    if (deprecationDetails) {
      markDeprecated(program, destType, deprecationDetails);
    }
  }
  function checkDeprecated(type, node, target) {
    if (node) {
      const deprecationDetails2 = getDeprecationDetails(program, node);
      if (deprecationDetails2) {
        reportDeprecation(program, target, deprecationDetails2.message, reportCheckerDiagnostic);
        return;
      }
    }
    const deprecationDetails = getDeprecationDetails(program, type);
    if (deprecationDetails) {
      reportDeprecation(program, target, deprecationDetails.message, reportCheckerDiagnostic);
    }
  }
  function isTypeReferenceContextDeprecated(node) {
    function checkDeprecatedNode(node2) {
      if (!nodeDeprecationMap.has(node2)) {
        nodeDeprecationMap.set(node2, (node2.directives ?? []).findIndex((d2) => d2.target.sv === "deprecated") >= 0);
      }
      return nodeDeprecationMap.get(node2);
    }
    switch (node.kind) {
      case SyntaxKind.ModelStatement:
        return checkDeprecatedNode(node);
      case SyntaxKind.OperationStatement:
        return checkDeprecatedNode(node) || node.parent.kind === SyntaxKind.InterfaceStatement && isTypeReferenceContextDeprecated(node.parent);
      case SyntaxKind.InterfaceStatement:
        return checkDeprecatedNode(node);
      case SyntaxKind.IntersectionExpression:
      case SyntaxKind.UnionExpression:
      case SyntaxKind.ModelProperty:
      case SyntaxKind.OperationSignatureDeclaration:
      case SyntaxKind.OperationSignatureReference:
        return isTypeReferenceContextDeprecated(node.parent);
      default:
        return false;
    }
  }
  function checkTemplateInstantiationArgs(node, args, decls, mapper, parentMapper) {
    const params = /* @__PURE__ */ new Map();
    const positional = [];
    const initMap = new Map(decls.map((decl) => {
      const declaredType = checkTemplateParameterDeclaration(decl, void 0);
      positional.push(declaredType);
      params.set(decl.id.sv, declaredType);
      return [
        declaredType,
        {
          decl,
          checkArgument: null
        }
      ];
    }));
    let named = false;
    for (const [arg, idx] of args.map((v2, i2) => [v2, i2])) {
      let deferredCheck2 = function() {
        return [arg, checkNode(arg.argument, mapper)];
      };
      var deferredCheck = deferredCheck2;
      if (arg.name) {
        named = true;
        const param = params.get(arg.name.sv);
        if (!param) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "unknownName",
            format: {
              name: arg.name.sv
            },
            target: arg
          }));
          continue;
        }
        if (initMap.get(param).checkArgument !== null) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "specifiedAgain",
            format: {
              name: arg.name.sv
            },
            target: arg
          }));
          continue;
        }
        initMap.get(param).checkArgument = deferredCheck2;
      } else {
        if (named) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "positionalAfterNamed",
            target: arg
          }));
        }
        if (idx >= positional.length) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "tooMany",
            target: node
          }));
          continue;
        }
        const param = positional[idx];
        initMap.get(param).checkArgument ??= deferredCheck2;
      }
    }
    const finalMap = initMap;
    const mapperParams = [];
    const mapperArgs = [];
    for (const [param, { decl, checkArgument: init }] of [...initMap]) {
      let commit2 = function(param2, type2) {
        finalMap.set(param2, type2);
        mapperParams.push(param2);
        mapperArgs.push(type2);
      };
      var commit = commit2;
      if (init === null) {
        const argumentMapper = createTypeMapper(mapperParams, mapperArgs, { node, mapper }, parentMapper);
        const defaultValue = getResolvedTypeParameterDefault(param, decl, argumentMapper);
        if (defaultValue) {
          commit2(param, defaultValue);
        } else {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "missing",
            format: {
              name: decl.id.sv
            },
            target: node
          }));
          commit2(param, param.constraint?.type ?? unknownType);
        }
        continue;
      }
      const [argNode, type] = init();
      if (type === null) {
        commit2(param, unknownType);
        continue;
      }
      if (param.constraint) {
        const constraint = param.constraint.type?.kind === "TemplateParameter" ? finalMap.get(param.constraint.type) : param.constraint;
        if (isType(type) && shouldTryInterceptTypeUsedAsValue(param.constraint)) {
          const converted = interceptTypesUsedAsValue(type);
          if (converted !== type) {
            commit2(param, type);
            continue;
          }
        }
        if (param.constraint && !checkArgumentAssignable(type, constraint, argNode)) {
          const effectiveType = param.constraint.type ?? unknownType;
          commit2(param, effectiveType);
          continue;
        }
      } else if (isErrorType(type)) {
        commit2(param, unknownType);
        continue;
      } else if (isValue(type)) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "value-in-type",
          messageId: "noTemplateConstraint",
          target: argNode
        }));
        commit2(param, unknownType);
        continue;
      }
      commit2(param, type);
    }
    return finalMap;
  }
  function checkTypeReferenceSymbol(sym, node, mapper, instantiateTemplates = true) {
    const result = checkTypeOrValueReferenceSymbol(sym, node, mapper, instantiateTemplates);
    if (result === null || isValue(result)) {
      reportCheckerDiagnostic(createDiagnostic({ code: "value-in-type", target: node }));
      return errorType;
    }
    if (result.entityKind === "Indeterminate") {
      return result.type;
    }
    return result;
  }
  function checkTypeOrValueReferenceSymbol(sym, node, mapper, instantiateTemplates = true) {
    const entity = checkTypeOrValueReferenceSymbolWorker(sym, node, mapper, instantiateTemplates);
    if (entity !== null && isType(entity) && entity.kind === "TemplateParameter") {
      templateParameterUsageMap.set(entity.node, true);
    }
    return entity;
  }
  function checkTypeOrValueReferenceSymbolWorker(sym, node, mapper, instantiateTemplates = true) {
    if (sym.flags & 131072) {
      return getValueForNode(sym.declarations[0], mapper);
    }
    if (sym.flags & 512) {
      reportCheckerDiagnostic(createDiagnostic({ code: "invalid-type-ref", messageId: "decorator", target: sym }));
      return errorType;
    }
    if (sym.flags & 2048) {
      reportCheckerDiagnostic(createDiagnostic({ code: "invalid-type-ref", messageId: "function", target: sym }));
      return errorType;
    }
    const argumentNodes = node.kind === SyntaxKind.TypeReference ? node.arguments : [];
    const symbolLinks = getSymbolLinks(sym);
    let baseType;
    if (sym.flags & 1048576 && sym.flags & (2 | 4 | 128 | 32 | 8 | 64)) {
      const decl = sym.declarations[0];
      if (!isTemplatedNode(decl)) {
        if (argumentNodes.length > 0) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-template-args",
            messageId: "notTemplate",
            target: node
          }));
        }
        if (sym.flags & 4194304) {
          compilerAssert(sym.type, "Expected late bound symbol to have type");
          return sym.type;
        } else if (symbolLinks.declaredType) {
          baseType = symbolLinks.declaredType;
        } else if (sym.flags & 65536) {
          baseType = checkMemberSym(sym, mapper);
        } else {
          baseType = checkDeclaredTypeOrIndeterminate(sym, decl, mapper);
        }
      } else {
        const declaredType = getOrCheckDeclaredType(sym, decl, mapper);
        const templateParameters = decl.templateParameters;
        const instantiation = checkTemplateInstantiationArgs(node, argumentNodes, templateParameters, mapper, declaredType.templateMapper);
        baseType = getOrInstantiateTemplate(decl, [...instantiation.keys()], [...instantiation.values()], { node, mapper }, declaredType.templateMapper, instantiateTemplates);
      }
    } else {
      const symNode = getSymNode(sym);
      if (argumentNodes.length > 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-template-args",
          messageId: "notTemplate",
          target: node
        }));
      }
      if (sym.flags & 4194304) {
        compilerAssert(sym.type, `Expected late bound symbol to have type`);
        return sym.type;
      } else if (sym.flags & 1024) {
        const mapped = checkTemplateParameterDeclaration(symNode, mapper);
        baseType = mapped;
      } else if (symbolLinks.type) {
        baseType = symbolLinks.type;
      } else if (symbolLinks.declaredType) {
        baseType = symbolLinks.declaredType;
      } else {
        if (sym.flags & 65536) {
          baseType = checkMemberSym(sym, mapper);
        } else {
          baseType = getTypeForNode(symNode, mapper);
          symbolLinks.type = baseType;
        }
      }
    }
    const declarationNode = getSymNode(sym);
    if (declarationNode && mapper === void 0 && isType(baseType)) {
      if (!isTypeReferenceContextDeprecated(node.parent)) {
        checkDeprecated(baseType, declarationNode, node);
      }
    }
    if (isType(baseType) && (baseType.kind === "EnumMember" || baseType.kind === "UnionVariant") || isNullType(baseType)) {
      return createIndeterminateEntity(baseType);
    }
    return baseType;
  }
  function getOrCheckDeclaredType(sym, decl, mapper) {
    const symbolLinks = getSymbolLinks(sym);
    if (symbolLinks.declaredType) {
      return symbolLinks.declaredType;
    }
    if (sym.flags & 4194304) {
      compilerAssert(sym.type, "Expected late bound symbol to have type");
      return sym.type;
    }
    if (sym.flags & 65536) {
      return checkMemberSym(sym, mapper);
    } else {
      return checkDeclaredType(sym, decl, mapper);
    }
  }
  function checkDeclaredTypeOrIndeterminate(sym, node, mapper) {
    const type = sym.flags & 2 ? checkModelStatement(node, mapper) : sym.flags & 4 ? checkScalar(node, mapper) : sym.flags & 128 ? checkAlias(node, mapper) : sym.flags & 32 ? checkInterface(node, mapper) : sym.flags & 8 ? checkOperation(node, mapper) : checkUnion(node, mapper);
    return type;
  }
  function checkDeclaredType(sym, node, mapper) {
    return getTypeForTypeOrIndeterminate(checkDeclaredTypeOrIndeterminate(sym, node, mapper));
  }
  function getOrInstantiateTemplate(templateNode, params, args, source, parentMapper, instantiateTempalates = true) {
    const symbolLinks = templateNode.kind === SyntaxKind.OperationStatement && templateNode.parent.kind === SyntaxKind.InterfaceStatement ? getSymbolLinksForMember(templateNode) : getSymbolLinks(templateNode.symbol);
    compilerAssert(symbolLinks, `Unexpected checker error. symbolLinks was not defined for ${SyntaxKind[templateNode.kind]}`);
    if (symbolLinks.instantiations === void 0) {
      const type = getTypeForNode(templateNode);
      if (isErrorType(type)) {
        return errorType;
      } else {
        compilerAssert(false, `Unexpected checker error. symbolLinks.instantiations was not defined for ${SyntaxKind[templateNode.kind]}`);
      }
    }
    const mapper = createTypeMapper(params, args, source, parentMapper);
    const cached = symbolLinks.instantiations?.get(mapper.args);
    if (cached) {
      return cached;
    }
    if (instantiateTempalates) {
      return instantiateTemplate(symbolLinks.instantiations, templateNode, params, mapper);
    } else {
      return errorType;
    }
  }
  function instantiateTemplate(instantiations, templateNode, params, mapper) {
    const type = getTypeForNode(templateNode, mapper);
    if (!instantiations.get(mapper.args)) {
      instantiations.set(mapper.args, type);
    }
    if (type.kind === "Model") {
      type.templateNode = templateNode;
    }
    return type;
  }
  function checkMixedParameterConstraintUnion(node, mapper) {
    const values = [];
    const types = [];
    for (const option of node.options) {
      const [kind, type] = getTypeOrValueOfTypeForNode(option, mapper);
      if (kind === "value") {
        values.push(type);
      } else {
        types.push(type);
      }
    }
    return {
      entityKind: "MixedParameterConstraint",
      node,
      valueType: values.length === 0 ? void 0 : values.length === 1 ? values[0] : createConstraintUnion(node, values),
      type: types.length === 0 ? void 0 : types.length === 1 ? types[0] : createConstraintUnion(node, types)
    };
  }
  function createConstraintUnion(node, options) {
    const variants = createRekeyableMap();
    const union = createAndFinishType({
      kind: "Union",
      node,
      options,
      decorators: [],
      variants,
      expression: true
    });
    for (const option of options) {
      const name = Symbol("indexer-union-variant");
      variants.set(name, createAndFinishType({
        kind: "UnionVariant",
        node: void 0,
        type: option,
        name,
        union,
        decorators: []
      }));
    }
    return union;
  }
  function checkUnionExpression(node, mapper) {
    const unionType = createAndFinishType({
      kind: "Union",
      node,
      get options() {
        return Array.from(this.variants.values()).map((v2) => v2.type);
      },
      expression: true,
      namespace: getParentNamespaceType(node),
      variants: createRekeyableMap(),
      decorators: []
    });
    for (const o2 of node.options) {
      const type = getTypeForNode(o2, mapper);
      if (type === neverType) {
        continue;
      }
      if (type.kind === "Union" && type.expression) {
        for (const [name, variant] of type.variants) {
          unionType.variants.set(name, variant);
        }
      } else {
        const variant = createType({
          kind: "UnionVariant",
          type,
          name: Symbol("name"),
          decorators: [],
          node: void 0,
          union: unionType
        });
        unionType.variants.set(variant.name, variant);
      }
    }
    linkMapper(unionType, mapper);
    return unionType;
  }
  function checkIntersectionExpression(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const intersection = initModel(node);
    const options = node.options.map((o2) => [o2, getTypeForNode(o2, mapper)]);
    ensureResolved(options.map(([, type]) => type), intersection, () => {
      const type = mergeModelTypes(node.symbol, node, options, mapper, intersection);
      linkType(links, type, mapper);
      finishType(intersection);
    });
    return intersection;
  }
  function ensureResolved(types, awaitingType, callback) {
    const waitingFor = /* @__PURE__ */ new Set();
    for (const type of types) {
      if (type === void 0)
        continue;
      if (type.creating) {
        waitingFor.add(type);
      }
    }
    function check() {
      if (waitingFor.size === 0) {
        callback();
      }
    }
    for (const type of waitingFor) {
      waitingForResolution.set(type, [
        ...waitingForResolution.get(type) || [],
        [
          awaitingType,
          () => {
            waitingFor.delete(type);
            check();
          }
        ]
      ]);
    }
    check();
  }
  function checkDecoratorDeclaration(node, mapper) {
    const symbol = getMergedSymbol(node.symbol);
    const links = getSymbolLinks(symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const namespace = getParentNamespaceType(node);
    compilerAssert(namespace, `Decorator ${node.id.sv} should have resolved a namespace or found the global namespace.`);
    const name = node.id.sv;
    if (!(node.modifierFlags & 2)) {
      reportCheckerDiagnostic(createDiagnostic({ code: "decorator-extern", target: node }));
    }
    const implementation = symbol.value;
    if (implementation === void 0) {
      reportCheckerDiagnostic(createDiagnostic({ code: "missing-implementation", target: node }));
    }
    const decoratorType = createType({
      kind: "Decorator",
      name: `@${name}`,
      namespace,
      node,
      target: checkFunctionParameter(node.target, mapper, true),
      parameters: node.parameters.map((x2) => checkFunctionParameter(x2, mapper, true)),
      implementation: implementation ?? (() => {
      })
    });
    namespace.decoratorDeclarations.set(name, decoratorType);
    linkType(links, decoratorType, mapper);
    return decoratorType;
  }
  function checkFunctionDeclaration(node, mapper) {
    reportCheckerDiagnostic(createDiagnostic({ code: "function-unsupported", target: node }));
    return errorType;
  }
  function checkFunctionParameter(node, mapper, mixed) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType) {
      return links.declaredType;
    }
    if (node.rest && node.type && !(node.type.kind === SyntaxKind.ArrayExpression || node.type.kind === SyntaxKind.ValueOfExpression && node.type.target.kind === SyntaxKind.ArrayExpression)) {
      reportCheckerDiagnostic(createDiagnostic({ code: "rest-parameter-array", target: node.type }));
    }
    const base = {
      kind: "FunctionParameter",
      node,
      name: node.id.sv,
      optional: node.optional,
      rest: node.rest,
      implementation: node.symbol.value
    };
    let parameterType;
    if (mixed) {
      const type = node.type ? getParamConstraintEntityForNode(node.type) : {
        entityKind: "MixedParameterConstraint",
        type: unknownType
      };
      parameterType = createType({
        ...base,
        type,
        mixed: true,
        implementation: node.symbol.value
      });
    } else {
      parameterType = createType({
        ...base,
        mixed: false,
        type: node.type ? getTypeForNode(node.type) : unknownType,
        implementation: node.symbol.value
      });
    }
    linkType(links, parameterType, mapper);
    return parameterType;
  }
  function getTypeOrValueOfTypeForNode(node, mapper) {
    switch (node.kind) {
      case SyntaxKind.ValueOfExpression:
        const target = getTypeForNode(node.target, mapper);
        return ["value", target];
      default:
        return ["type", getTypeForNode(node, mapper)];
    }
  }
  function getParamConstraintEntityForNode(node, mapper) {
    switch (node.kind) {
      case SyntaxKind.UnionExpression:
        return checkMixedParameterConstraintUnion(node, mapper);
      default:
        const [kind, entity] = getTypeOrValueOfTypeForNode(node, mapper);
        return {
          entityKind: "MixedParameterConstraint",
          node,
          type: kind === "value" ? void 0 : entity,
          valueType: kind === "value" ? entity : void 0
        };
    }
  }
  function mergeModelTypes(parentModelSym, node, options, mapper, intersection) {
    const properties = intersection.properties;
    const indexers = [];
    const modelOptions = options.filter((entry) => {
      const [optionNode, option] = entry;
      if (option.kind === "TemplateParameter") {
        return false;
      }
      if (option.kind !== "Model") {
        reportCheckerDiagnostic(createDiagnostic({ code: "intersect-non-model", target: optionNode }));
        return false;
      }
      return true;
    });
    for (const [optionNode, option] of modelOptions) {
      if (option.indexer) {
        if (option.indexer.key.name === "integer") {
          reportCheckerDiagnostic(createDiagnostic({
            code: "intersect-invalid-index",
            messageId: "array",
            target: optionNode
          }));
        } else {
          indexers.push(option.indexer);
        }
      }
    }
    for (const [_2, option] of modelOptions) {
      intersection.sourceModels.push({ usage: "intersection", model: option });
      const allProps = walkPropertiesInherited(option);
      for (const prop of allProps) {
        if (properties.has(prop.name)) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "intersect-duplicate-property",
            format: { propName: prop.name },
            target: node
          }));
          continue;
        }
        const memberSym = parentModelSym && getMemberSymbol(parentModelSym, prop.name);
        const overrides = {
          sourceProperty: prop,
          model: intersection
        };
        const newPropType = memberSym ? cloneTypeForSymbol(memberSym, prop, overrides) : cloneType(prop, overrides);
        properties.set(prop.name, newPropType);
        linkIndirectMember(node, newPropType, mapper);
        for (const indexer of indexers.filter((x2) => x2 !== option.indexer)) {
          checkPropertyCompatibleWithIndexer(indexer, prop, node);
        }
      }
    }
    if (indexers.length === 1) {
      intersection.indexer = indexers[0];
    } else if (indexers.length > 1) {
      intersection.indexer = {
        key: indexers[0].key,
        value: mergeModelTypes(void 0, node, indexers.map((x2) => [x2.value.node, x2.value]), mapper, initModel(node))
      };
    }
    linkMapper(intersection, mapper);
    return finishType(intersection);
  }
  function checkArrayExpression(node, mapper) {
    const elementType = getTypeForNode(node.elementType, mapper);
    const arrayType = getStdType("Array");
    const arrayNode = arrayType.node;
    const param = getTypeForNode(arrayNode.templateParameters[0]);
    return getOrInstantiateTemplate(arrayNode, [param], [elementType], { node, mapper }, void 0);
  }
  function checkNamespace(node) {
    const links = getSymbolLinks(getMergedSymbol(node.symbol));
    let type = links.type;
    if (!type) {
      type = initializeTypeForNamespace(node);
    }
    if (node.kind === SyntaxKind.NamespaceStatement) {
      if (isArray(node.statements)) {
        node.statements.forEach((x2) => checkNode(x2));
      } else if (node.statements) {
        const subNs = checkNamespace(node.statements);
        type.namespaces.set(subNs.name, subNs);
      }
    }
    return type;
  }
  function initializeTypeForNamespace(node) {
    compilerAssert(node.symbol, "Namespace is unbound.", node);
    const mergedSymbol = getMergedSymbol(node.symbol);
    const symbolLinks = getSymbolLinks(mergedSymbol);
    if (!symbolLinks.type) {
      const namespace = getParentNamespaceType(node);
      const name = node.id.sv;
      const type = createType({
        kind: "Namespace",
        name,
        namespace,
        node,
        models: /* @__PURE__ */ new Map(),
        scalars: /* @__PURE__ */ new Map(),
        operations: /* @__PURE__ */ new Map(),
        namespaces: /* @__PURE__ */ new Map(),
        interfaces: /* @__PURE__ */ new Map(),
        unions: /* @__PURE__ */ new Map(),
        enums: /* @__PURE__ */ new Map(),
        decoratorDeclarations: /* @__PURE__ */ new Map(),
        functionDeclarations: /* @__PURE__ */ new Map(),
        decorators: []
      });
      symbolLinks.type = type;
      for (const sourceNode of mergedSymbol.declarations) {
        if (sourceNode.kind !== SyntaxKind.NamespaceStatement)
          continue;
        type.decorators = type.decorators.concat(checkDecorators(type, sourceNode, void 0));
      }
      finishType(type);
      namespace?.namespaces.set(name, type);
    }
    return symbolLinks.type;
  }
  function getParentNamespaceType(node) {
    if (node === globalNamespaceType.node)
      return void 0;
    if (node.kind === SyntaxKind.ModelExpression || node.kind === SyntaxKind.IntersectionExpression || node.kind === SyntaxKind.UnionExpression) {
      let parent = node.parent;
      while (parent !== void 0) {
        if (parent.kind === SyntaxKind.AliasStatement || parent.kind === SyntaxKind.ModelStatement || parent.kind === SyntaxKind.ScalarStatement || parent.kind === SyntaxKind.OperationStatement || parent.kind === SyntaxKind.EnumStatement || parent.kind === SyntaxKind.InterfaceStatement || parent.kind === SyntaxKind.UnionStatement || parent.kind === SyntaxKind.ModelExpression || parent.kind === SyntaxKind.IntersectionExpression || parent.kind === SyntaxKind.UnionExpression) {
          return getParentNamespaceType(parent);
        } else {
          parent = parent.parent;
        }
      }
      return void 0;
    }
    if (node.kind === SyntaxKind.OperationStatement && node.parent && node.parent.kind === SyntaxKind.InterfaceStatement) {
      return getParentNamespaceType(node.parent);
    }
    if (!node.symbol.parent) {
      return globalNamespaceType;
    }
    if (node.symbol.parent.declarations[0].kind === SyntaxKind.TypeSpecScript || node.symbol.parent.declarations[0].kind === SyntaxKind.JsSourceFile) {
      return globalNamespaceType;
    }
    const mergedSymbol = getMergedSymbol(node.symbol.parent);
    const symbolLinks = getSymbolLinks(mergedSymbol);
    if (!symbolLinks.type) {
      const namespaceNode = mergedSymbol.declarations.find((x2) => x2.kind === SyntaxKind.NamespaceStatement || x2.kind === SyntaxKind.JsNamespaceDeclaration);
      compilerAssert(namespaceNode, "Can't find namespace declaration node.", node);
      symbolLinks.type = initializeTypeForNamespace(namespaceNode);
    }
    return symbolLinks.type;
  }
  function checkOperation(node, mapper, parentInterface) {
    const inInterface = node.parent?.kind === SyntaxKind.InterfaceStatement;
    const symbol = inInterface ? getSymbolForMember(node) : node.symbol;
    const links = symbol && getSymbolLinks(symbol);
    if (links) {
      if (links.declaredType && mapper === void 0) {
        return links.declaredType;
      }
    }
    if (mapper === void 0 && inInterface) {
      compilerAssert(parentInterface, "Operation in interface should already have been checked.", node.parent);
    }
    checkTemplateDeclaration(node, mapper);
    if (isTemplatedNode(node) && mapper !== void 0 && parentInterface) {
      mapper = { ...mapper, partial: true };
    }
    const namespace = getParentNamespaceType(node);
    const name = node.id.sv;
    const { resolvedSymbol: parameterModelSym } = resolver.resolveMetaMemberByName(symbol, "parameters");
    if (parameterModelSym?.members) {
      const members = resolver.getAugmentedSymbolTable(parameterModelSym.members);
      const paramDocs = extractParamDocs(node);
      for (const [name2, memberSym] of members) {
        const doc = paramDocs.get(name2);
        if (doc) {
          docFromCommentForSym.set(memberSym, doc);
        }
      }
    }
    const operationType = createType({
      kind: "Operation",
      name,
      namespace,
      parameters: null,
      returnType: voidType,
      node,
      decorators: [],
      interface: parentInterface
    });
    if (links) {
      linkType(links, operationType, mapper);
    }
    const parent = node.parent;
    function finishOperation() {
      operationType.parameters.namespace = namespace;
      operationType.decorators.push(...checkDecorators(operationType, node, mapper));
      const runDecorators = parent.kind === SyntaxKind.InterfaceStatement ? shouldRunDecorators(parent, mapper) && shouldRunDecorators(node, mapper) : shouldRunDecorators(node, mapper);
      return finishType(operationType, { skipDecorators: !runDecorators });
    }
    if (node.signature.kind === SyntaxKind.OperationSignatureReference) {
      const baseOperation = checkOperationIs(node, node.signature.baseOperation, mapper);
      if (baseOperation) {
        ensureResolved([baseOperation], operationType, () => {
          operationType.sourceOperation = baseOperation;
          const clone = initializeClone(baseOperation.parameters, {
            properties: createRekeyableMap()
          });
          clone.properties = createRekeyableMap(Array.from(baseOperation.parameters.properties.entries()).map(([key, prop]) => [
            key,
            cloneTypeForSymbol(getMemberSymbol(parameterModelSym, prop.name), prop, {
              model: clone,
              sourceProperty: prop
            })
          ]));
          operationType.parameters = finishType(clone);
          operationType.returnType = baseOperation.returnType;
          operationType.decorators.push(...baseOperation.decorators);
          finishOperation();
        });
      } else {
        operationType.parameters = initModel();
        operationType.returnType = voidType;
        finishOperation();
      }
    } else {
      operationType.parameters = getTypeForNode(node.signature.parameters, mapper);
      operationType.returnType = getTypeForNode(node.signature.returnType, mapper);
      ensureResolved([operationType.parameters], operationType, () => {
        finishOperation();
      });
    }
    linkMapper(operationType, mapper);
    if (parent.kind !== SyntaxKind.InterfaceStatement && mapper === void 0) {
      namespace?.operations.set(name, operationType);
    }
    return operationType;
  }
  function checkOperationIs(operation, opReference, mapper) {
    if (!opReference)
      return void 0;
    const opSymId = getNodeSym(operation);
    if (opSymId) {
      pendingResolutions.start(opSymId, ResolutionKind.BaseType);
    }
    const target = resolver.getNodeLinks(opReference).resolvedSymbol;
    if (target && pendingResolutions.has(target, ResolutionKind.BaseType)) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "circular-op-signature",
          format: { typeName: target.name },
          target: opReference
        }));
      }
      return void 0;
    }
    const baseOperation = getTypeForNode(opReference, mapper);
    if (opSymId) {
      pendingResolutions.finish(opSymId, ResolutionKind.BaseType);
    }
    if (isErrorType(baseOperation)) {
      return void 0;
    }
    if (baseOperation.kind !== "Operation") {
      reportCheckerDiagnostic(createDiagnostic({ code: "is-operation", target: opReference }));
      return;
    }
    return baseOperation;
  }
  function getGlobalNamespaceType() {
    return globalNamespaceType;
  }
  function getGlobalNamespaceNode() {
    return resolver.symbols.global.declarations[0];
  }
  function checkTupleExpression(node, mapper) {
    return createAndFinishType({
      kind: "Tuple",
      node,
      values: node.values.map((v2) => getTypeForNode(v2, mapper))
    });
  }
  function getSymbolLinks(s2) {
    return resolver.getSymbolLinks(s2);
  }
  function resolveRelatedSymbols(id, mapper) {
    let sym;
    const { node, kind } = getIdentifierContext(id);
    switch (kind) {
      case IdentifierKind.ModelExpressionProperty:
      case IdentifierKind.ObjectLiteralProperty:
        const model = getReferencedModel(node);
        return model.map((m2) => getMemberSymbol(m2.node.symbol, id.sv)).filter((m2) => m2 !== void 0);
      case IdentifierKind.ModelStatementProperty:
      case IdentifierKind.Declaration:
        const links = resolver.getNodeLinks(id);
        return links.resolvedSymbol === void 0 ? void 0 : [links.resolvedSymbol];
      case IdentifierKind.Other:
        return void 0;
      case IdentifierKind.Decorator:
      case IdentifierKind.Function:
      case IdentifierKind.Using:
      case IdentifierKind.TypeReference:
        let ref = id;
        let resolveDecorator = kind === IdentifierKind.Decorator;
        if (id.parent?.kind === SyntaxKind.MemberExpression) {
          if (id.parent.id === id) {
            ref = id.parent;
          } else {
            resolveDecorator = false;
          }
        }
        sym = resolveTypeReferenceSym(ref, mapper, resolveDecorator);
        break;
      case IdentifierKind.TemplateArgument:
        const templates = getTemplateDeclarationsForArgument(node, mapper);
        const firstMatchingParameter = templates.flatMap((t2) => t2.templateParameters).find((p2) => p2.id.sv === id.sv);
        if (firstMatchingParameter) {
          sym = getMergedSymbol(firstMatchingParameter.symbol);
        }
        break;
      default:
        const _assertNever = kind;
        compilerAssert(false, "Unreachable");
    }
    if (sym) {
      if (sym.symbolSource) {
        return [sym.symbolSource];
      } else {
        return [sym];
      }
    }
    return void 0;
  }
  function getTemplateDeclarationsForArgument(node, mapper) {
    const ref = node.parent;
    let resolved = resolveTypeReferenceSym(ref, mapper, false);
    if (!resolved && hasParseError(ref) && ref.target !== void 0) {
      resolved = resolveTypeReferenceSym(ref.target, mapper, false);
    }
    return resolved?.declarations.filter((n2) => isTemplatedNode(n2)) ?? [];
  }
  function getReferencedModel(propertyNode) {
    const isModelOrArrayValue = (n2) => n2?.kind === SyntaxKind.ArrayLiteral || n2?.kind === SyntaxKind.ObjectLiteral;
    const isModelOrArrayType = (n2) => n2?.kind === SyntaxKind.ModelExpression || n2?.kind === SyntaxKind.TupleExpression;
    const isModelOrArray = (n2) => isModelOrArrayValue(n2) || isModelOrArrayType(n2);
    const path = [];
    let preNode;
    const foundNode = getFirstAncestor(propertyNode, (n2) => {
      pushToModelPath(n2, preNode, path);
      preNode = n2;
      return isModelOrArray(n2) && (n2.parent?.kind === SyntaxKind.TemplateParameterDeclaration || n2.parent?.kind === SyntaxKind.TemplateArgument || n2.parent?.kind === SyntaxKind.DecoratorExpression) || isModelOrArrayValue(n2) && (n2.parent?.kind === SyntaxKind.CallExpression || n2.parent?.kind === SyntaxKind.ConstStatement);
    });
    let refType;
    switch (foundNode?.parent?.kind) {
      case SyntaxKind.TemplateParameterDeclaration:
      case SyntaxKind.TemplateArgument:
        refType = getReferencedTypeFromTemplateDeclaration(foundNode);
        break;
      case SyntaxKind.DecoratorExpression:
        refType = getReferencedTypeFromDecoratorArgument(foundNode);
        break;
      case SyntaxKind.CallExpression:
        refType = getReferencedTypeFromScalarConstructor(foundNode);
        break;
      case SyntaxKind.ConstStatement:
        refType = getReferencedTypeFromConstAssignment(foundNode);
        break;
    }
    return getNestedModel(refType, path);
    function pushToModelPath(node, preNode2, path2) {
      if (node.kind === SyntaxKind.ArrayLiteral || node.kind === SyntaxKind.TupleExpression) {
        const index = node.values.findIndex((n2) => n2 === preNode2);
        if (index >= 0) {
          path2.unshift({ tupleIndex: index });
        } else {
          compilerAssert(false, "not expected, can't find child from the parent?");
        }
      }
      if (node.kind === SyntaxKind.ModelProperty || node.kind === SyntaxKind.ObjectLiteralProperty) {
        path2.unshift({ propertyName: node.id.sv });
      }
    }
    function getNestedModel(modelOrTupleOrUnion, path2) {
      let cur = modelOrTupleOrUnion;
      if (cur && cur.kind !== "Model" && cur.kind !== "Tuple" && cur.kind !== "Union") {
        return [];
      }
      if (path2.length === 0) {
        switch (cur?.kind) {
          case "Model":
            return [cur];
          case "Union":
            const models = [];
            for (const variant of cur.variants.values()) {
              if (variant.type.kind === "Model" || variant.type.kind === "Tuple" || variant.type.kind === "Union") {
                models.push(...getNestedModel(variant.type, path2) ?? []);
              }
            }
            return models;
          default:
            return [];
        }
      }
      const seg = path2[0];
      switch (cur?.kind) {
        case "Tuple":
          if (seg.tupleIndex !== void 0 && seg.tupleIndex >= 0 && seg.tupleIndex < cur.values.length) {
            return getNestedModel(cur.values[seg.tupleIndex], path2.slice(1));
          } else {
            return [];
          }
        case "Model":
          if (cur.name === "Array" && seg.tupleIndex !== void 0) {
            cur = cur.templateMapper?.args[0];
          } else if (cur.name !== "Array" && seg.propertyName) {
            cur = cur.properties.get(seg.propertyName)?.type;
          } else {
            return [];
          }
          return getNestedModel(cur, path2.slice(1));
        case "Union":
          const models = [];
          for (const variant of cur.variants.values()) {
            if (variant.type.kind === "Model" || variant.type.kind === "Tuple" || variant.type.kind === "Union") {
              models.push(...getNestedModel(variant.type, path2) ?? []);
            }
          }
          return models;
        default:
          return [];
      }
    }
    function getReferencedTypeFromTemplateDeclaration(node) {
      let templateParmaeterDeclNode = void 0;
      if (node?.parent?.kind === SyntaxKind.TemplateArgument && node?.parent?.parent?.kind === SyntaxKind.TypeReference) {
        const argNode = node.parent;
        const refNode = node.parent.parent;
        const decl = getTemplateDeclarationsForArgument(
          argNode,
          // We should be giving the argument so the mapper here should be undefined
          void 0
          /* mapper */
        );
        const index = refNode.arguments.findIndex((n2) => n2 === argNode);
        if (decl.length > 0 && decl[0].templateParameters.length > index) {
          templateParmaeterDeclNode = decl[0].templateParameters[index];
        }
      } else if (node.parent?.kind === SyntaxKind.TemplateParameterDeclaration) {
        templateParmaeterDeclNode = node?.parent;
      }
      if (templateParmaeterDeclNode?.kind !== SyntaxKind.TemplateParameterDeclaration || !templateParmaeterDeclNode.constraint) {
        return void 0;
      }
      let constraintType;
      if (isModelOrArrayValue(node) && templateParmaeterDeclNode.constraint.kind === SyntaxKind.ValueOfExpression) {
        constraintType = program.checker.getTypeForNode(templateParmaeterDeclNode.constraint.target);
      } else if (isModelOrArrayType(node) && templateParmaeterDeclNode.constraint.kind !== SyntaxKind.ValueOfExpression) {
        constraintType = program.checker.getTypeForNode(templateParmaeterDeclNode.constraint);
      }
      return constraintType;
    }
    function getReferencedTypeFromScalarConstructor(argNode) {
      const callExpNode = argNode?.parent;
      if (callExpNode?.kind !== SyntaxKind.CallExpression) {
        return void 0;
      }
      const ctorType = checkCallExpressionTarget(callExpNode, void 0);
      if (ctorType?.kind !== "ScalarConstructor") {
        return void 0;
      }
      const argIndex = callExpNode.arguments.findIndex((n2) => n2 === argNode);
      if (argIndex < 0 || argIndex >= ctorType.parameters.length) {
        return void 0;
      }
      const arg = ctorType.parameters[argIndex];
      return arg.type;
    }
    function getReferencedTypeFromConstAssignment(valueNode) {
      const constNode = valueNode?.parent;
      if (!constNode || constNode.kind !== SyntaxKind.ConstStatement || !constNode.type || constNode.value !== valueNode) {
        return void 0;
      }
      return program.checker.getTypeForNode(constNode.type);
    }
    function getReferencedTypeFromDecoratorArgument(decArgNode) {
      const decNode = decArgNode?.parent;
      if (decNode?.kind !== SyntaxKind.DecoratorExpression) {
        return void 0;
      }
      const decSym = program.checker.resolveRelatedSymbols(decNode.target.kind === SyntaxKind.MemberExpression ? decNode.target.id : decNode.target);
      if (!decSym || decSym.length <= 0) {
        return void 0;
      }
      const decDecl = decSym[0].declarations.find((x2) => x2.kind === SyntaxKind.DecoratorDeclarationStatement);
      if (!decDecl) {
        return void 0;
      }
      const decType = program.checker.getTypeForNode(decDecl);
      compilerAssert(decType.kind === "Decorator", "Expected type to be a Decorator.");
      const argIndex = decNode.arguments.findIndex((n2) => n2 === decArgNode);
      if (argIndex < 0 || argIndex >= decType.parameters.length) {
        return void 0;
      }
      const decArg = decType.parameters[argIndex];
      let type;
      if (isModelOrArrayValue(decArgNode)) {
        type = decArg.type.valueType;
      } else if (isModelOrArrayType(decArgNode)) {
        type = decArg.type.type ?? decArg.type.valueType;
      } else {
        compilerAssert(false, "not expected node type to get reference model from decorator argument");
      }
      return type;
    }
  }
  function resolveCompletions(identifier) {
    const completions = /* @__PURE__ */ new Map();
    const { kind, node: ancestor } = getIdentifierContext(identifier);
    switch (kind) {
      case IdentifierKind.Using:
      case IdentifierKind.Decorator:
      case IdentifierKind.Function:
      case IdentifierKind.TypeReference:
      case IdentifierKind.ModelExpressionProperty:
      case IdentifierKind.ModelStatementProperty:
      case IdentifierKind.ObjectLiteralProperty:
        break;
      // supported
      case IdentifierKind.Other:
        return completions;
      // not implemented
      case IdentifierKind.Declaration:
        return completions;
      // cannot complete, name can be chosen arbitrarily
      case IdentifierKind.TemplateArgument: {
        const templates = getTemplateDeclarationsForArgument(ancestor, void 0);
        for (const template of templates) {
          for (const param of template.templateParameters) {
            addCompletion(param.id.sv, param.symbol);
          }
        }
        return completions;
      }
      default:
        const _assertNever = kind;
        compilerAssert(false, "Unreachable");
    }
    if (kind === IdentifierKind.ModelStatementProperty) {
      const model = ancestor.parent;
      const modelType = program.checker.getTypeForNode(model);
      const baseType = modelType.baseModel;
      const baseNode = baseType?.node;
      if (!baseNode) {
        return completions;
      }
      for (const prop of baseType.properties.values()) {
        if (identifier.sv === prop.name || !modelType.properties.has(prop.name)) {
          const sym = getMemberSymbol(baseNode.symbol, prop.name);
          if (sym) {
            addCompletion(prop.name, sym);
          }
        }
      }
    } else if (kind === IdentifierKind.ModelExpressionProperty || kind === IdentifierKind.ObjectLiteralProperty) {
      const model = getReferencedModel(ancestor);
      if (model.length <= 0) {
        return completions;
      }
      const curModelNode = ancestor.parent;
      for (const curModel of model) {
        for (const prop of walkPropertiesInherited(curModel)) {
          if (identifier.sv === prop.name || !curModelNode.properties.find((p2) => (p2.kind === SyntaxKind.ModelProperty || p2.kind === SyntaxKind.ObjectLiteralProperty) && p2.id.sv === prop.name)) {
            const sym = getMemberSymbol(curModel.node.symbol, prop.name);
            if (sym) {
              addCompletion(prop.name, sym);
            }
          }
        }
      }
    } else if (identifier.parent && identifier.parent.kind === SyntaxKind.MemberExpression) {
      let base = resolver.getNodeLinks(identifier.parent.base).resolvedSymbol;
      if (base) {
        if (base.flags & 128) {
          base = getAliasedSymbol(base, void 0);
        }
        if (base) {
          if (identifier.parent.selector === "::") {
            if (base?.node === void 0 && base?.declarations && base.declarations.length > 0) {
              const nodeModels = base?.declarations[0];
              if (nodeModels.kind === SyntaxKind.OperationStatement) {
                const operation = nodeModels;
                addCompletion("parameters", operation.symbol);
                addCompletion("returnType", operation.symbol);
              }
            } else if (base?.node?.kind === SyntaxKind.ModelProperty) {
              const metaProperty = base.node;
              addCompletion("type", metaProperty.symbol);
            }
          } else {
            addCompletions(base.exports ?? base.members);
          }
        }
      }
    } else {
      if (kind === IdentifierKind.TypeReference && exprIsBareIdentifier(ancestor) && ancestor.parent?.kind === SyntaxKind.TemplateArgument && ancestor.parent.name === void 0) {
        const templates = getTemplateDeclarationsForArgument(ancestor.parent, void 0);
        for (const template of templates) {
          for (const param of template.templateParameters) {
            addCompletion(param.id.sv, param.symbol, { suffix: " = " });
          }
        }
      }
      let scope = identifier.parent;
      while (scope && scope.kind !== SyntaxKind.TypeSpecScript) {
        if (scope.symbol && scope.symbol.exports) {
          const mergedSymbol = getMergedSymbol(scope.symbol);
          addCompletions(mergedSymbol.exports);
        }
        if ("locals" in scope) {
          addCompletions(scope.locals);
        }
        scope = scope.parent;
      }
      if (scope && scope.kind === SyntaxKind.TypeSpecScript) {
        for (const ns of scope.inScopeNamespaces) {
          const mergedSymbol = getMergedSymbol(ns.symbol);
          addCompletions(mergedSymbol.exports);
        }
        addCompletions(resolver.symbols.global.exports);
        addCompletions(scope.locals);
      }
    }
    return completions;
    function addCompletions(table) {
      if (!table) {
        return;
      }
      table = resolver.getAugmentedSymbolTable(table);
      for (const [key, sym] of table) {
        if (sym.flags & 16384) {
          const duplicates = table.duplicates.get(sym);
          for (const duplicate of duplicates) {
            if (duplicate.flags & 8192) {
              const fqn = getFullyQualifiedSymbolName(duplicate.symbolSource);
              addCompletion(fqn, duplicate);
            }
          }
        } else {
          addCompletion(key, sym);
        }
      }
    }
    function addCompletion(key, sym, options = {}) {
      if (sym.symbolSource) {
        sym = sym.symbolSource;
      }
      if (!shouldAddCompletion(sym)) {
        return;
      }
      if (key.startsWith("@")) {
        key = key.slice(1);
      }
      if (!completions.has(key)) {
        completions.set(key, { ...options, sym });
      }
    }
    function shouldAddCompletion(sym) {
      switch (kind) {
        case IdentifierKind.ModelExpressionProperty:
        case IdentifierKind.ModelStatementProperty:
        case IdentifierKind.ObjectLiteralProperty:
          return !!(sym.flags & 65536);
        case IdentifierKind.Decorator:
          return !!(sym.flags & (512 | 256));
        case IdentifierKind.Using:
          return !!(sym.flags & 256);
        case IdentifierKind.TypeReference:
          return !(sym.flags & (2048 | 512));
        case IdentifierKind.TemplateArgument:
          return !!(sym.flags & 1024);
        default:
          compilerAssert(false, "We should have bailed up-front on other kinds.");
      }
    }
  }
  function getCodefixesForUnknownIdentifier(node) {
    switch (node.sv) {
      case "number":
        return [createChangeIdentifierCodeFix(node, "float64")];
      default:
        return void 0;
    }
  }
  function resolveTypeReferenceSym(node, mapper, options) {
    const resolvedOptions = typeof options === "boolean" ? { ...defaultSymbolResolutionOptions, resolveDecorators: options } : { ...defaultSymbolResolutionOptions, ...options ?? {} };
    if (mapper === void 0 && resolvedOptions.checkTemplateTypes && referenceSymCache.has(node)) {
      return referenceSymCache.get(node);
    }
    const sym = resolveTypeReferenceSymInternal(node, mapper, resolvedOptions);
    if (resolvedOptions.checkTemplateTypes) {
      referenceSymCache.set(node, sym);
    }
    return sym;
  }
  function resolveTypeReferenceSymInternal(node, mapper, options) {
    if (hasParseError(node)) {
      return void 0;
    }
    if (node.kind === SyntaxKind.TypeReference) {
      return resolveTypeReferenceSym(node.target, mapper, options);
    } else if (node.kind === SyntaxKind.Identifier) {
      const links = resolver.getNodeLinks(node);
      if (mapper === void 0 && links.resolutionResult) {
        if (mapper === void 0 && // do not report error when instantiating
        links.resolutionResult & (ResolutionResultFlags.NotFound | ResolutionResultFlags.Unknown)) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-ref",
            messageId: options.resolveDecorators ? "decorator" : "identifier",
            format: { id: printTypeReferenceNode(node) },
            target: node,
            codefixes: getCodefixesForUnknownIdentifier(node)
          }));
        } else if (links.resolutionResult & ResolutionResultFlags.Ambiguous) {
          reportAmbiguousIdentifier(node, links.ambiguousSymbols);
        }
      }
      const sym = links.resolvedSymbol;
      return sym?.symbolSource ?? sym;
    } else if (node.kind === SyntaxKind.MemberExpression) {
      let base = resolveTypeReferenceSym(node.base, mapper, {
        ...options,
        resolveDecorators: false
        // when resolving decorator the base cannot also be one
      });
      if (!base) {
        return void 0;
      }
      if (base.flags & 128) {
        const aliasedSym = getAliasedSymbol(base, mapper);
        if (!aliasedSym) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-ref",
            messageId: "node",
            format: {
              id: node.id.sv,
              nodeName: base.declarations[0] ? SyntaxKind[base.declarations[0].kind] : "Unknown node"
            },
            target: node
          }));
          return void 0;
        }
        base = aliasedSym;
      }
      return resolveMemberInContainer(base, node, options);
    }
    compilerAssert(false, `Unknown type reference kind "${SyntaxKind[node.kind]}"`, node);
  }
  function reportAmbiguousIdentifier(node, symbols) {
    const duplicateNames = symbols.map((s2) => getFullyQualifiedSymbolName(s2, { useGlobalPrefixAtTopLevel: true }));
    program.reportDiagnostic(createDiagnostic({
      code: "ambiguous-symbol",
      format: { name: node.sv, duplicateNames: duplicateNames.join(", ") },
      target: node
    }));
  }
  function resolveMemberInContainer(base, node, options) {
    const { finalSymbol: sym, resolvedSymbol: nextSym } = resolver.resolveMemberExpressionForSym(base, node, options);
    const symbol = nextSym ?? sym;
    if (symbol) {
      return symbol;
    }
    if (base.flags & 256) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-ref",
        messageId: "underNamespace",
        format: {
          namespace: getFullyQualifiedSymbolName(base),
          id: node.id.sv
        },
        target: node
      }));
    } else if (base.flags & 512) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-ref",
        messageId: "inDecorator",
        format: { id: node.id.sv },
        target: node
      }));
    } else if (base.flags & 2048) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-ref",
        messageId: "node",
        format: { id: node.id.sv, nodeName: "function" },
        target: node
      }));
    } else if (base.flags & 118) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-ref",
        messageId: node.selector === "." ? "member" : "metaProperty",
        format: { kind: getMemberKindName(getSymNode(base)), id: node.id.sv },
        target: node
      }));
    } else {
      const symNode = getSymNode(base);
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-ref",
        messageId: "node",
        format: {
          id: node.id.sv,
          nodeName: symNode ? SyntaxKind[symNode.kind] : "Unknown node"
        },
        target: node
      }));
    }
    return void 0;
  }
  function getMemberKindName(node) {
    switch (node.kind) {
      case SyntaxKind.ModelStatement:
      case SyntaxKind.ModelExpression:
        return "Model";
      case SyntaxKind.ModelProperty:
        return "ModelProperty";
      case SyntaxKind.EnumStatement:
        return "Enum";
      case SyntaxKind.InterfaceStatement:
        return "Interface";
      case SyntaxKind.UnionStatement:
        return "Union";
      default:
        return "Type";
    }
  }
  function getAliasedSymbol(aliasSymbol, mapper) {
    const node = getSymNode(aliasSymbol);
    const links = resolver.getSymbolLinks(aliasSymbol);
    if (!links.aliasResolutionIsTemplate) {
      return links.aliasedSymbol ?? resolver.getNodeLinks(node).resolvedSymbol;
    }
    const aliasType = getTypeForNode(node, mapper);
    if (isErrorType(aliasType)) {
      return void 0;
    }
    switch (aliasType.kind) {
      case "Model":
      case "Interface":
      case "Union":
        if (isTemplateInstance(aliasType)) {
          lateBindMemberContainer(aliasType);
          return aliasType.symbol;
        }
      // fallthrough
      default:
        return getMergedSymbol(aliasType.node.symbol) ?? aliasSymbol;
    }
  }
  function checkStringTemplateExpresion(node, mapper) {
    let hasType = false;
    let hasValue = false;
    const spanTypeOrValues = node.spans.map((span) => [span, checkNode(span.expression, mapper)]);
    for (const [_2, typeOrValue] of spanTypeOrValues) {
      if (typeOrValue !== null) {
        if (isValue(typeOrValue)) {
          hasValue = true;
        } else if ("kind" in typeOrValue && typeOrValue.kind === "TemplateParameter") {
          if (typeOrValue.constraint) {
            if (typeOrValue.constraint.valueType) {
              hasValue = true;
            }
            if (typeOrValue.constraint.type) {
              hasType = true;
            }
          } else {
            hasType = true;
          }
        } else {
          hasType = true;
        }
      }
    }
    if (hasType && hasValue) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "mixed-string-template",
        target: node
      }));
      return null;
    }
    if (hasValue) {
      let str = node.head.value;
      for (const [span, typeOrValue] of spanTypeOrValues) {
        if (typeOrValue !== null && (!("kind" in typeOrValue) || typeOrValue.kind !== "TemplateParameter")) {
          compilerAssert(typeOrValue !== null && isValue(typeOrValue), "Expected value.");
          str += stringifyValueForTemplate(typeOrValue);
        }
        str += span.literal.value;
      }
      return checkStringValue(createLiteralType(str), void 0, node);
    } else {
      let hasNonStringElement = false;
      let stringValue = node.head.value;
      const spans = [createTemplateSpanLiteral(node.head)];
      for (const [span, typeOrValue] of spanTypeOrValues) {
        compilerAssert(typeOrValue !== null && !isValue(typeOrValue), "Expected type.");
        const type = typeOrValue.entityKind === "Indeterminate" ? typeOrValue.type : typeOrValue;
        const spanValue = createTemplateSpanValue(span.expression, type);
        spans.push(spanValue);
        const spanValueAsString = stringifyTypeForTemplate(type);
        if (spanValueAsString !== void 0) {
          stringValue += spanValueAsString;
        } else {
          hasNonStringElement = true;
        }
        spans.push(createTemplateSpanLiteral(span.literal));
        stringValue += span.literal.value;
      }
      return createIndeterminateEntity(createType({
        kind: "StringTemplate",
        node,
        spans,
        stringValue: hasNonStringElement ? void 0 : stringValue
      }));
    }
  }
  function createIndeterminateEntity(type) {
    const existing = indeterminateEntities.get(type);
    if (existing) {
      return existing;
    }
    const entity = {
      entityKind: "Indeterminate",
      type
    };
    indeterminateEntities.set(type, entity);
    return entity;
  }
  function stringifyTypeForTemplate(type) {
    switch (type.kind) {
      case "String":
      case "Number":
      case "Boolean":
        return String(type.value);
      case "StringTemplate":
        if (type.stringValue !== void 0) {
          return type.stringValue;
        }
        return void 0;
      default:
        return void 0;
    }
  }
  function stringifyValueForTemplate(value) {
    switch (value.valueKind) {
      case "StringValue":
      case "NumericValue":
      case "BooleanValue":
        return value.value.toString();
      default:
        reportCheckerDiagnostic(createDiagnostic({
          code: "non-literal-string-template",
          target: value
        }));
        return `[${value.valueKind}]`;
    }
  }
  function createTemplateSpanLiteral(node) {
    return createType({
      kind: "StringTemplateSpan",
      node,
      isInterpolated: false,
      type: getLiteralType(node)
    });
  }
  function createTemplateSpanValue(node, type) {
    return createType({
      kind: "StringTemplateSpan",
      node,
      isInterpolated: true,
      type
    });
  }
  function checkStringLiteral(str) {
    return createIndeterminateEntity(getLiteralType(str));
  }
  function checkNumericLiteral(num) {
    return createIndeterminateEntity(getLiteralType(num));
  }
  function checkBooleanLiteral(bool) {
    return createIndeterminateEntity(getLiteralType(bool));
  }
  function checkProgram() {
    checkDuplicateSymbols();
    for (const file of program.sourceFiles.values()) {
      checkDuplicateUsings(file);
      for (const ns of file.namespaces) {
        initializeTypeForNamespace(ns);
      }
    }
    for (const file of program.sourceFiles.values()) {
      checkSourceFile(file);
    }
    internalDecoratorValidation();
    assertNoPendingResolutions();
  }
  function assertNoPendingResolutions() {
    if (waitingForResolution.size === 0) {
      return;
    }
    const message = [
      "Unexpected pending resolutions found",
      ...[...waitingForResolution.entries()].flatMap(([type, items]) => {
        const base = `  (${type.kind}) ${getTypeName(type)} => `;
        return items.map(([item], index) => `${index === 0 ? base : " ".repeat(base.length)}${getTypeName(item)}`);
      })
    ].join("\n");
    compilerAssert(false, message);
  }
  function checkDuplicateSymbols() {
    program.reportDuplicateSymbols(resolver.symbols.global.exports);
    for (const file of program.sourceFiles.values()) {
      for (const ns of file.namespaces) {
        const exports = getMergedSymbol(ns.symbol).exports ?? ns.symbol.exports;
        program.reportDuplicateSymbols(exports);
      }
    }
  }
  function checkDuplicateUsings(file) {
    const duplicateTrackers = /* @__PURE__ */ new Map();
    function getTracker(sym) {
      const existing = duplicateTrackers.get(sym);
      if (existing)
        return existing;
      const newTacker = new DuplicateTracker();
      duplicateTrackers.set(sym, newTacker);
      return newTacker;
    }
    for (const using of file.usings) {
      const ns = using.parent;
      const sym = getMergedSymbol(ns.symbol);
      const tracker = getTracker(sym);
      const targetSym = resolver.getNodeLinks(using.name).resolvedSymbol;
      if (!targetSym)
        continue;
      tracker.track(targetSym, using);
    }
    for (const tracker of duplicateTrackers.values()) {
      for (const [_2, nodes] of tracker.entries()) {
        for (const node of nodes) {
          program.reportDiagnostic(createDiagnostic({
            code: "duplicate-using",
            format: { usingName: typeReferenceToString(node.name) },
            target: node
          }));
        }
      }
    }
  }
  function internalDecoratorValidation() {
    validateInheritanceDiscriminatedUnions(program);
  }
  function checkSourceFile(file) {
    for (const statement of file.statements) {
      checkNode(statement, void 0);
    }
  }
  function checkTemplateDeclaration(node, mapper) {
    if (mapper === void 0) {
      for (const templateParameter of node.templateParameters) {
        checkTemplateParameterDeclaration(templateParameter, void 0);
      }
    }
  }
  function checkModel(node, mapper) {
    if (node.kind === SyntaxKind.ModelStatement) {
      return checkModelStatement(node, mapper);
    } else {
      return checkModelExpression(node, mapper);
    }
  }
  function checkModelStatement(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    checkTemplateDeclaration(node, mapper);
    const decorators = [];
    const type = createType({
      kind: "Model",
      name: node.id.sv,
      node,
      properties: createRekeyableMap(),
      namespace: getParentNamespaceType(node),
      decorators,
      sourceModels: [],
      derivedModels: []
    });
    linkType(links, type, mapper);
    if (node.symbol.members) {
      const members = resolver.getAugmentedSymbolTable(node.symbol.members);
      const propDocs = extractPropDocs(node);
      for (const [name, memberSym] of members) {
        const doc = propDocs.get(name);
        if (doc) {
          docFromCommentForSym.set(memberSym, doc);
        }
      }
    }
    const isBase = checkModelIs(node, node.is, mapper);
    ensureResolved([
      isBase,
      ...node.properties.filter((x2) => x2.kind === SyntaxKind.ModelSpreadProperty).map((x2) => checkSpreadTarget(node, x2.target, mapper))
    ], type, () => {
      if (isBase) {
        type.sourceModel = isBase;
        type.sourceModels.push({ usage: "is", model: isBase });
        decorators.push(...isBase.decorators);
        if (isBase.indexer) {
          type.indexer = isBase.indexer;
        }
        for (const prop of isBase.properties.values()) {
          const memberSym = getMemberSymbol(node.symbol, prop.name);
          const newProp = cloneTypeForSymbol(memberSym, prop, {
            sourceProperty: prop,
            model: type
          });
          linkIndirectMember(node, newProp, mapper);
          type.properties.set(prop.name, newProp);
        }
      }
      if (isBase) {
        type.baseModel = isBase.baseModel;
      } else if (node.extends) {
        type.baseModel = checkClassHeritage(node, node.extends, mapper);
        if (type.baseModel) {
          copyDeprecation(type.baseModel, type);
        }
      }
      if (type.baseModel) {
        type.baseModel.derivedModels.push(type);
      }
      if (mapper === void 0) {
        type.namespace?.models.set(type.name, type);
      }
      checkModelProperties(node, type.properties, type, mapper);
      decorators.push(...checkDecorators(type, node, mapper));
      linkMapper(type, mapper);
      finishType(type, { skipDecorators: !shouldRunDecorators(node, mapper) });
      lateBindMemberContainer(type);
      lateBindMembers(type);
      const indexer = getIndexer(program, type);
      if (type.name === "Array" && isInTypeSpecNamespace2(type)) {
        stdTypes.Array = type;
      } else if (type.name === "Record" && isInTypeSpecNamespace2(type)) {
        stdTypes.Record = type;
      }
      if (indexer) {
        type.indexer = indexer;
      }
    });
    return type;
  }
  function shouldRunDecorators(node, mapper) {
    if (node.templateParameters.length === 0) {
      return true;
    }
    if (mapper === void 0) {
      return false;
    }
    return !mapper.partial && mapper.args.every((t2) => isValue(t2) || t2.entityKind === "Indeterminate" || t2.kind !== "TemplateParameter");
  }
  function checkModelExpression(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const type = initModel(node);
    const properties = type.properties;
    linkType(links, type, mapper);
    linkMapper(type, mapper);
    ensureResolved(node.properties.filter((x2) => x2.kind === SyntaxKind.ModelSpreadProperty).map((x2) => checkSpreadTarget(node, x2.target, mapper)), type, () => {
      checkModelProperties(node, properties, type, mapper);
      finishType(type);
    });
    return type;
  }
  function findIndexer(model) {
    let current = model;
    while (current) {
      if (current.indexer) {
        return current.indexer;
      }
      current = current.baseModel;
    }
    return void 0;
  }
  function checkPropertyCompatibleWithModelIndexer(parentModel, property, diagnosticTarget) {
    const indexer = findIndexer(parentModel);
    if (indexer === void 0) {
      return;
    }
    return checkPropertyCompatibleWithIndexer(indexer, property, diagnosticTarget);
  }
  function checkPropertyCompatibleWithIndexer(indexer, property, diagnosticTarget) {
    if (indexer.key.name === "integer") {
      reportCheckerDiagnostics([
        createDiagnostic({
          code: "no-array-properties",
          target: diagnosticTarget
        })
      ]);
      return;
    }
    const [valid, diagnostics] = relation.isTypeAssignableTo(property.type, indexer.value, diagnosticTarget);
    if (!valid)
      reportCheckerDiagnostic(createDiagnostic({
        code: "incompatible-indexer",
        format: { message: diagnostics.map((x2) => `  ${x2.message}`).join("\n") },
        target: diagnosticTarget.kind === SyntaxKind.ModelProperty ? diagnosticTarget.value : diagnosticTarget
      }));
  }
  function checkModelProperties(node, properties, parentModel, mapper) {
    let spreadIndexers;
    for (const prop of node.properties) {
      if ("id" in prop) {
        const newProp = checkModelProperty(prop, mapper);
        newProp.model = parentModel;
        checkPropertyCompatibleWithModelIndexer(parentModel, newProp, prop);
        defineProperty(properties, newProp);
      } else {
        const [newProperties, additionalIndexer] = checkSpreadProperty(node.symbol, prop.target, parentModel, mapper);
        if (additionalIndexer) {
          if (spreadIndexers) {
            spreadIndexers.push(additionalIndexer);
          } else {
            spreadIndexers = [additionalIndexer];
          }
        }
        for (const newProp of newProperties) {
          linkIndirectMember(node, newProp, mapper);
          checkPropertyCompatibleWithModelIndexer(parentModel, newProp, prop);
          defineProperty(properties, newProp, prop);
        }
      }
    }
    if (spreadIndexers) {
      const value = spreadIndexers.length === 1 ? spreadIndexers[0].value : createUnion(spreadIndexers.map((i2) => i2.value));
      parentModel.indexer = {
        key: spreadIndexers[0].key,
        value
      };
    }
  }
  function checkObjectValue(node, mapper, constraint) {
    const properties = checkObjectLiteralProperties(node, mapper);
    if (properties === null) {
      return null;
    }
    const preciseType = createTypeForObjectValue(node, properties);
    if (constraint && !checkTypeOfValueMatchConstraint(preciseType, constraint, node)) {
      return null;
    }
    return createValue({
      entityKind: "Value",
      valueKind: "ObjectValue",
      node,
      properties,
      type: constraint ? constraint.type : preciseType
    }, preciseType);
  }
  function createTypeForObjectValue(node, properties) {
    const model = createType({
      kind: "Model",
      name: "",
      node,
      properties: createRekeyableMap(),
      decorators: [],
      derivedModels: [],
      sourceModels: []
    });
    for (const prop of properties.values()) {
      model.properties.set(prop.name, createModelPropertyForObjectPropertyDescriptor(prop, model));
    }
    return finishType(model);
  }
  function createModelPropertyForObjectPropertyDescriptor(prop, parentModel) {
    return createAndFinishType({
      kind: "ModelProperty",
      node: prop.node,
      model: parentModel,
      optional: false,
      name: prop.name,
      type: prop.value.type,
      decorators: []
    });
  }
  function checkObjectLiteralProperties(node, mapper) {
    const properties = /* @__PURE__ */ new Map();
    let hasError = false;
    for (const prop of node.properties) {
      if ("id" in prop) {
        const value = getValueForNode(prop.value, mapper);
        if (value === null) {
          hasError = true;
        } else {
          properties.set(prop.id.sv, { name: prop.id.sv, value, node: prop });
        }
      } else {
        const targetType = checkObjectSpreadProperty(prop.target, mapper);
        if (targetType) {
          for (const [name, value] of targetType.properties) {
            properties.set(name, { ...value });
          }
        }
      }
    }
    return hasError ? null : properties;
  }
  function checkObjectSpreadProperty(targetNode, mapper) {
    const value = getValueForNode(targetNode, mapper);
    if (value === null) {
      return null;
    }
    if (value.valueKind !== "ObjectValue") {
      reportCheckerDiagnostic(createDiagnostic({ code: "spread-object", target: targetNode }));
      return null;
    }
    return value;
  }
  function checkArrayValue(node, mapper, constraint) {
    let hasError = false;
    const values = node.values.map((itemNode) => {
      const value = getValueForNode(itemNode, mapper);
      if (value === null) {
        hasError = true;
      }
      return value;
    });
    if (hasError) {
      return null;
    }
    const preciseType = createTypeForArrayValue(node, values);
    if (constraint && !checkTypeOfValueMatchConstraint(preciseType, constraint, node)) {
      return null;
    }
    return createValue({
      entityKind: "Value",
      valueKind: "ArrayValue",
      node,
      values,
      type: constraint ? constraint.type : preciseType
    }, preciseType);
  }
  function createValue(value, preciseType) {
    valueExactTypes.set(value, preciseType);
    return value;
  }
  function copyValue(value, overrides) {
    const newValue = { ...value, ...overrides };
    const preciseType = valueExactTypes.get(value);
    if (preciseType) {
      valueExactTypes.set(newValue, preciseType);
    }
    return newValue;
  }
  function createTypeForArrayValue(node, values) {
    return createAndFinishType({
      kind: "Tuple",
      node,
      values: values.map((x2) => x2.type)
    });
  }
  function inferScalarForPrimitiveValue(type, literalType) {
    if (type === void 0) {
      return void 0;
    }
    switch (type.kind) {
      case "Scalar":
        if (ignoreDiagnostics(checker.isTypeAssignableTo(literalType, type, literalType))) {
          return type;
        }
        return void 0;
      case "Union":
        let found = void 0;
        for (const variant of type.variants.values()) {
          const scalar = inferScalarForPrimitiveValue(variant.type, literalType);
          if (scalar) {
            if (found) {
              reportCheckerDiagnostic(createDiagnostic({
                code: "ambiguous-scalar-type",
                format: {
                  value: getTypeName(literalType),
                  types: [found, scalar].map((x2) => x2.name).join(", "),
                  example: found.name
                },
                target: literalType
              }));
              return void 0;
            } else {
              found = scalar;
            }
          }
        }
        return found;
      default:
        return void 0;
    }
  }
  function checkStringValue(literalType, constraint, node) {
    if (constraint && !checkTypeOfValueMatchConstraint(literalType, constraint, node)) {
      return null;
    }
    let value;
    if (literalType.kind === "StringTemplate") {
      if (literalType.stringValue) {
        value = literalType.stringValue;
      } else {
        reportCheckerDiagnostics(explainStringTemplateNotSerializable(literalType));
        return null;
      }
    } else {
      value = literalType.value;
    }
    const scalar = inferScalarForPrimitiveValue(constraint?.type, literalType);
    return createValue({
      entityKind: "Value",
      valueKind: "StringValue",
      value,
      type: constraint ? constraint.type : literalType,
      scalar
    }, literalType);
  }
  function checkNumericValue(literalType, constraint, node) {
    if (constraint && !checkTypeOfValueMatchConstraint(literalType, constraint, node)) {
      return null;
    }
    const scalar = inferScalarForPrimitiveValue(constraint?.type, literalType);
    return createValue({
      entityKind: "Value",
      valueKind: "NumericValue",
      value: Numeric(literalType.valueAsString),
      type: constraint ? constraint.type : literalType,
      scalar
    }, literalType);
  }
  function checkBooleanValue(literalType, constraint, node) {
    if (constraint && !checkTypeOfValueMatchConstraint(literalType, constraint, node)) {
      return null;
    }
    const scalar = inferScalarForPrimitiveValue(constraint?.type, literalType);
    return createValue({
      entityKind: "Value",
      valueKind: "BooleanValue",
      value: literalType.value,
      type: constraint ? constraint.type : literalType,
      scalar
    }, literalType);
  }
  function checkNullValue(literalType, constraint, node) {
    if (constraint && !checkTypeOfValueMatchConstraint(literalType, constraint, node)) {
      return null;
    }
    return createValue({
      entityKind: "Value",
      valueKind: "NullValue",
      type: constraint ? constraint.type : literalType,
      value: null
    }, literalType);
  }
  function checkEnumValue(literalType, constraint, node) {
    if (constraint && !checkTypeOfValueMatchConstraint(literalType, constraint, node)) {
      return null;
    }
    return createValue({
      entityKind: "Value",
      valueKind: "EnumValue",
      type: constraint ? constraint.type : literalType,
      value: literalType
    }, literalType);
  }
  function checkCallExpressionTarget(node, mapper) {
    const target = checkTypeReference(node.target, mapper);
    if (target.kind === "Scalar" || target.kind === "ScalarConstructor") {
      return target;
    } else {
      reportCheckerDiagnostic(createDiagnostic({
        code: "non-callable",
        format: { type: target.kind },
        target: node.target
      }));
      return null;
    }
  }
  function checkPrimitiveArg(node, scalar, valueKind) {
    if (node.arguments.length !== 1) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-primitive-init",
        target: node.target
      }));
      return null;
    }
    const argNode = node.arguments[0];
    const value = getValueForNode(argNode, void 0);
    if (value === null) {
      return null;
    }
    if (value.valueKind !== valueKind) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-primitive-init",
        messageId: "invalidArg",
        format: { actual: value.valueKind, expected: valueKind },
        target: argNode
      }));
      return null;
    }
    if (!checkValueOfType(value, scalar, argNode)) {
      return null;
    }
    return copyValue(value, { scalar, type: scalar });
  }
  function createScalarValue(node, mapper, declaration) {
    let hasError = false;
    const minArgs = declaration.parameters.filter((x2) => !x2.optional && !x2.rest).length ?? 0;
    const maxArgs = declaration.parameters[declaration.parameters.length - 1]?.rest ? void 0 : declaration.parameters.length;
    if (node.arguments.length < minArgs || maxArgs !== void 0 && node.arguments.length > maxArgs) {
      if (node.arguments.length < minArgs) {
        hasError = true;
      }
      if (maxArgs === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-argument-count",
          messageId: "atLeast",
          format: { actual: node.arguments.length.toString(), expected: minArgs.toString() },
          target: node
        }));
      } else {
        const expected = minArgs === maxArgs ? minArgs.toString() : `${minArgs}-${maxArgs}`;
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-argument-count",
          format: { actual: node.arguments.length.toString(), expected },
          target: node
        }));
      }
    }
    const resolvedArgs = [];
    for (const [index, parameter] of declaration.parameters.entries()) {
      if (parameter.rest) {
        const restType = getIndexType(parameter.type);
        if (restType) {
          for (let i2 = index; i2 < node.arguments.length; i2++) {
            const argNode2 = node.arguments[i2];
            if (argNode2) {
              const arg = getValueForNode(argNode2, mapper, { kind: "argument", type: restType });
              if (arg === null) {
                hasError = true;
                continue;
              }
              if (checkValueOfType(arg, restType, argNode2)) {
                resolvedArgs.push(arg);
              } else {
                hasError = true;
              }
            }
          }
        }
        break;
      }
      const argNode = node.arguments[index];
      if (argNode) {
        const arg = getValueForNode(argNode, mapper, {
          kind: "argument",
          type: parameter.type
        });
        if (arg === null) {
          hasError = true;
          continue;
        }
        if (checkValueOfType(arg, parameter.type, argNode)) {
          resolvedArgs.push(arg);
        } else {
          hasError = true;
        }
      }
    }
    if (hasError) {
      return null;
    }
    return {
      entityKind: "Value",
      valueKind: "ScalarValue",
      value: {
        name: declaration.name,
        args: resolvedArgs
      },
      scalar: declaration.scalar,
      type: declaration.scalar
    };
  }
  function checkCallExpression(node, mapper) {
    const target = checkCallExpressionTarget(node, mapper);
    if (target === null) {
      return null;
    }
    if (target.kind === "ScalarConstructor") {
      return createScalarValue(node, mapper, target);
    }
    if (relation.areScalarsRelated(target, getStdType("string"))) {
      return checkPrimitiveArg(node, target, "StringValue");
    } else if (relation.areScalarsRelated(target, getStdType("numeric"))) {
      return checkPrimitiveArg(node, target, "NumericValue");
    } else if (relation.areScalarsRelated(target, getStdType("boolean"))) {
      return checkPrimitiveArg(node, target, "BooleanValue");
    } else {
      reportCheckerDiagnostic(createDiagnostic({
        code: "named-init-required",
        format: { typeKind: target.kind },
        target: node.target
      }));
      return null;
    }
  }
  function checkTypeOfExpression(node, mapper) {
    const entity = checkNode(node.target, mapper, void 0);
    if (entity === null) {
      return errorType;
    }
    if (entity.entityKind === "Indeterminate") {
      return entity.type;
    }
    if (isType(entity)) {
      if (entity.kind === "TemplateParameter") {
        if (entity.constraint === void 0 || entity.constraint.type !== void 0) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "expect-value",
            messageId: "templateConstraint",
            format: { name: getTypeName(entity) },
            target: node.target
          }));
          return errorType;
        } else if (entity.constraint.valueType) {
          return entity.constraint.valueType;
        }
      }
      reportCheckerDiagnostic(createDiagnostic({
        code: "expect-value",
        format: { name: getTypeName(entity) },
        target: node.target
      }));
      return entity;
    }
    return entity.type;
  }
  function createUnion(options) {
    const variants = createRekeyableMap();
    const union = createAndFinishType({
      kind: "Union",
      node: void 0,
      options,
      decorators: [],
      variants,
      expression: true
    });
    for (const option of options) {
      const name = Symbol("indexer-union-variant");
      variants.set(name, createAndFinishType({
        kind: "UnionVariant",
        node: void 0,
        type: option,
        name,
        union,
        decorators: []
      }));
    }
    return union;
  }
  function defineProperty(properties, newProp, diagnosticTarget) {
    if (properties.has(newProp.name)) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "duplicate-property",
        format: { propName: newProp.name },
        target: diagnosticTarget ?? newProp
      }));
      return;
    }
    const overriddenProp = getOverriddenProperty(newProp);
    if (overriddenProp) {
      const [isAssignable, _2] = relation.isTypeAssignableTo(newProp.type, overriddenProp.type, newProp);
      const parentType = getTypeName(overriddenProp.type);
      const newPropType = getTypeName(newProp.type);
      let invalid = false;
      if (!isAssignable) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "override-property-mismatch",
          format: { propName: newProp.name, propType: newPropType, parentType },
          target: diagnosticTarget ?? newProp
        }));
        invalid = true;
      }
      if (!overriddenProp.optional && newProp.optional) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "override-property-mismatch",
          messageId: "disallowedOptionalOverride",
          format: { propName: overriddenProp.name },
          target: diagnosticTarget ?? newProp
        }));
        invalid = true;
      }
      if (invalid)
        return;
    }
    properties.set(newProp.name, newProp);
  }
  function lateBindMemberContainer(type) {
    if (type.symbol)
      return;
    switch (type.kind) {
      case "Model":
        type.symbol = createSymbol(
          type.node,
          type.name,
          2 | 4194304
          /* SymbolFlags.LateBound */
        );
        mutate(type.symbol).type = type;
        break;
      case "Interface":
        type.symbol = createSymbol(
          type.node,
          type.name,
          32 | 4194304
          /* SymbolFlags.LateBound */
        );
        mutate(type.symbol).type = type;
        break;
      case "Union":
        if (!type.name)
          return;
        type.symbol = createSymbol(
          type.node,
          type.name,
          64 | 4194304
          /* SymbolFlags.LateBound */
        );
        mutate(type.symbol).type = type;
        break;
    }
  }
  function lateBindMembers(type) {
    compilerAssert(type.symbol, "Type must have a symbol to late bind members");
    const containerSym = type.symbol;
    compilerAssert(containerSym.members, "Container symbol didn't have members at late-bind");
    const containerMembers = resolver.getAugmentedSymbolTable(containerSym.members);
    switch (type.kind) {
      case "Model":
        for (const prop of walkPropertiesInherited(type)) {
          lateBindMember(
            prop,
            65536 | 1048576
            /* SymbolFlags.Declaration */
          );
        }
        break;
      case "Scalar":
        for (const member of type.constructors.values()) {
          lateBindMember(
            member,
            65536 | 1048576
            /* SymbolFlags.Declaration */
          );
        }
        break;
      case "Enum":
        for (const member of type.members.values()) {
          lateBindMember(
            member,
            65536 | 1048576
            /* SymbolFlags.Declaration */
          );
        }
        break;
      case "Interface":
        for (const member of type.operations.values()) {
          lateBindMember(
            member,
            65536 | 8 | 1048576
            /* SymbolFlags.Declaration */
          );
        }
        break;
      case "Union":
        for (const variant of type.variants.values()) {
          lateBindMember(
            variant,
            65536 | 1048576
            /* SymbolFlags.Declaration */
          );
        }
        break;
    }
    function lateBindMember(member, kind) {
      if (!member.node || typeof member.name !== "string") {
        return;
      }
      const sym = createSymbol(member.node, member.name, kind | 4194304, containerSym);
      mutate(sym).type = member;
      compilerAssert(containerSym.members, "containerSym.members is undefined");
      containerMembers.set(member.name, sym);
    }
  }
  function checkClassHeritage(model, heritageRef, mapper) {
    if (heritageRef.kind === SyntaxKind.ModelExpression) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "extend-model",
        messageId: "modelExpression",
        target: heritageRef
      }));
      return void 0;
    }
    if (heritageRef.kind !== SyntaxKind.TypeReference && heritageRef.kind !== SyntaxKind.ArrayExpression) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "extend-model",
        target: heritageRef
      }));
      return void 0;
    }
    const modelSymId = getNodeSym(model);
    pendingResolutions.start(modelSymId, ResolutionKind.BaseType);
    const target = resolver.getNodeLinks(heritageRef).resolvedSymbol;
    if (target && pendingResolutions.has(target, ResolutionKind.BaseType)) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "circular-base-type",
          format: { typeName: target.name },
          target
        }));
      }
      return void 0;
    }
    const heritageType = getTypeForNode(heritageRef, mapper);
    pendingResolutions.finish(modelSymId, ResolutionKind.BaseType);
    if (isErrorType(heritageType)) {
      compilerAssert(program.hasError(), "Should already have reported an error.", heritageRef);
      return void 0;
    }
    if (heritageType.kind !== "Model") {
      reportCheckerDiagnostic(createDiagnostic({ code: "extend-model", target: heritageRef }));
      return void 0;
    }
    if (heritageType.name === "") {
      reportCheckerDiagnostic(createDiagnostic({
        code: "extend-model",
        messageId: "modelExpression",
        target: heritageRef
      }));
    }
    return heritageType;
  }
  function checkModelIs(model, isExpr, mapper) {
    if (!isExpr)
      return void 0;
    const modelSymId = getNodeSym(model);
    pendingResolutions.start(modelSymId, ResolutionKind.BaseType);
    let isType2;
    if (isExpr.kind === SyntaxKind.ModelExpression) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "is-model",
        messageId: "modelExpression",
        target: isExpr
      }));
      return void 0;
    } else if (isExpr.kind === SyntaxKind.ArrayExpression) {
      isType2 = checkArrayExpression(isExpr, mapper);
    } else if (isExpr.kind === SyntaxKind.TypeReference) {
      const target = resolver.getNodeLinks(isExpr).resolvedSymbol;
      if (target && pendingResolutions.has(target, ResolutionKind.BaseType)) {
        if (mapper === void 0) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "circular-base-type",
            format: { typeName: target.name },
            target
          }));
        }
        return void 0;
      }
      isType2 = getTypeForNode(isExpr, mapper);
    } else {
      reportCheckerDiagnostic(createDiagnostic({ code: "is-model", target: isExpr }));
      return void 0;
    }
    pendingResolutions.finish(modelSymId, ResolutionKind.BaseType);
    if (isType2.kind !== "Model") {
      reportCheckerDiagnostic(createDiagnostic({ code: "is-model", target: isExpr }));
      return;
    }
    if (isType2.name === "") {
      reportCheckerDiagnostic(createDiagnostic({ code: "is-model", messageId: "modelExpression", target: isExpr }));
      return void 0;
    }
    return isType2;
  }
  function checkSpreadTarget(model, target, mapper) {
    const modelSymId = getNodeSym(model);
    const targetSym = resolver.getNodeLinks(target).resolvedSymbol;
    if (targetSym === modelSymId) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "spread-model",
          messageId: "selfSpread",
          target
        }));
      }
      return void 0;
    }
    const type = getTypeForNode(target, mapper);
    return type;
  }
  function checkSpreadProperty(parentModelSym, targetNode, parentModel, mapper) {
    const targetType = getTypeForNode(targetNode, mapper);
    if (targetType.kind === "TemplateParameter" || isErrorType(targetType)) {
      return [[], void 0];
    }
    if (targetType.kind !== "Model") {
      reportCheckerDiagnostic(createDiagnostic({ code: "spread-model", target: targetNode }), mapper);
      return [[], void 0];
    }
    if (isArrayModelType(program, targetType)) {
      reportCheckerDiagnostic(createDiagnostic({ code: "spread-model", target: targetNode }), mapper);
      return [[], void 0];
    }
    parentModel.sourceModels.push({ usage: "spread", model: targetType });
    const props = [];
    for (const prop of walkPropertiesInherited(targetType)) {
      const memberSym = getMemberSymbol(parentModelSym, prop.name);
      props.push(cloneTypeForSymbol(memberSym, prop, {
        sourceProperty: prop,
        model: parentModel
      }));
    }
    return [props, targetType.indexer];
  }
  function linkIndirectMember(containerNode, member, mapper) {
    if (mapper !== void 0) {
      return;
    }
    compilerAssert(typeof member.name === "string", "Cannot link unmapped unions");
    if (containerNode.symbol === void 0) {
      return;
    }
    const memberSym = getMemberSymbol(containerNode.symbol, member.name);
    if (memberSym) {
      const links = resolver.getSymbolLinks(memberSym);
      linkMemberType(links, member, mapper);
    }
  }
  function checkModelProperty(prop, mapper) {
    const sym = getSymbolForMember(prop);
    const links = getSymbolLinksForMember(prop);
    if (links && links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const name = prop.id.sv;
    const type = createType({
      kind: "ModelProperty",
      name,
      node: prop,
      optional: prop.optional,
      type: void 0,
      decorators: []
    });
    if (pendingResolutions.has(sym, ResolutionKind.Type) && mapper === void 0) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "circular-prop",
        format: { propName: name },
        target: prop
      }));
      type.type = errorType;
    } else {
      pendingResolutions.start(sym, ResolutionKind.Type);
      type.type = getTypeForNode(prop.value, mapper);
      if (prop.default) {
        const defaultValue = checkDefaultValue(prop.default, type.type, mapper);
        if (defaultValue !== null) {
          type.defaultValue = defaultValue;
        }
      }
      if (links) {
        linkType(links, type, mapper);
      }
    }
    type.decorators = checkDecorators(type, prop, mapper);
    const parentTemplate = getParentTemplateNode(prop);
    linkMapper(type, mapper);
    let runDecorators = false;
    if (!parentTemplate || shouldRunDecorators(parentTemplate, mapper)) {
      const docComment = docFromCommentForSym.get(sym);
      if (docComment) {
        type.decorators.unshift(createDocFromCommentDecorator("self", docComment));
      }
      runDecorators = true;
    }
    pendingResolutions.finish(sym, ResolutionKind.Type);
    return finishType(type, { skipDecorators: !runDecorators });
  }
  function createDocFromCommentDecorator(key, doc) {
    return {
      decorator: docFromCommentDecorator,
      args: [
        { value: createLiteralType(key), jsValue: key },
        { value: createLiteralType(doc), jsValue: doc }
      ]
    };
  }
  function checkDefaultValue(defaultNode, type, mapper) {
    if (isErrorType(type)) {
      return null;
    }
    const defaultValue = getValueForNode(defaultNode, mapper, {
      kind: "assignment",
      type
    });
    if (defaultValue === null) {
      return null;
    }
    const [related, diagnostics] = relation.isValueOfType(defaultValue, type, defaultNode);
    if (!related) {
      reportCheckerDiagnostics(diagnostics);
      return null;
    } else if (defaultValue.valueKind === "TemplateValue") {
      return null;
    } else {
      return { ...defaultValue, type };
    }
  }
  function checkDecoratorApplication(targetType, decNode, mapper) {
    const sym = resolveTypeReferenceSym(decNode.target, void 0, true);
    if (!sym) {
      return void 0;
    }
    if (!(sym.flags & 512)) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-decorator",
        format: { id: sym.name },
        target: decNode
      }));
      return void 0;
    }
    const symbolLinks = getSymbolLinks(sym);
    let hasError = false;
    if (symbolLinks.declaredType === void 0) {
      const decoratorDeclNode = sym.declarations.find((x2) => x2.kind === SyntaxKind.DecoratorDeclarationStatement);
      if (decoratorDeclNode) {
        checkDecoratorDeclaration(decoratorDeclNode, void 0);
      }
    }
    if (symbolLinks.declaredType) {
      compilerAssert(symbolLinks.declaredType.kind === "Decorator", `Expected to find a decorator type but got ${symbolLinks.declaredType.kind}`);
      if (!checkDecoratorTarget(targetType, symbolLinks.declaredType, decNode)) {
        hasError = true;
      }
    }
    const [argsHaveError, args] = checkDecoratorArguments(decNode, mapper, symbolLinks.declaredType);
    if (hasError || argsHaveError) {
      return void 0;
    }
    return {
      definition: symbolLinks.declaredType,
      decorator: sym.value ?? ((...args2) => {
      }),
      node: decNode,
      args
    };
  }
  function checkDecoratorTarget(targetType, declaration, decoratorNode) {
    const [targetValid] = relation.isTypeAssignableTo(targetType, declaration.target.type, decoratorNode);
    if (!targetValid) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "decorator-wrong-target",
        messageId: "withExpected",
        format: {
          decorator: declaration.name,
          to: getTypeName(targetType),
          expected: getEntityName(declaration.target.type)
        },
        target: decoratorNode
      }));
    }
    return targetValid;
  }
  function checkDecoratorArguments(node, mapper, declaration) {
    if (declaration === void 0) {
      return [
        false,
        node.arguments.map((argNode) => {
          let type = checkNode(argNode, mapper) ?? errorType;
          if (type.entityKind === "Indeterminate") {
            type = type.type;
          }
          return {
            value: type,
            jsValue: type,
            node: argNode
          };
        })
      ];
    }
    let hasError = false;
    const minArgs = declaration.parameters.filter((x2) => !x2.optional && !x2.rest).length ?? 0;
    const maxArgs = declaration.parameters[declaration.parameters.length - 1]?.rest ? void 0 : declaration.parameters.length;
    if (node.arguments.length < minArgs || maxArgs !== void 0 && node.arguments.length > maxArgs) {
      if (node.arguments.length < minArgs) {
        hasError = true;
      }
      if (maxArgs === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-argument-count",
          messageId: "atLeast",
          format: { actual: node.arguments.length.toString(), expected: minArgs.toString() },
          target: node
        }));
      } else {
        const expected = minArgs === maxArgs ? minArgs.toString() : `${minArgs}-${maxArgs}`;
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-argument-count",
          format: { actual: node.arguments.length.toString(), expected },
          target: node
        }));
      }
    }
    const resolvedArgs = [];
    function resolveArg(argNode, perParamType) {
      const arg = getTypeOrValueForNode(argNode, mapper, {
        kind: "argument",
        constraint: perParamType
      });
      if (arg !== null && !(isType(arg) && isErrorType(arg)) && checkArgumentAssignable(arg, perParamType, argNode)) {
        return {
          value: arg,
          node: argNode,
          jsValue: resolveDecoratorArgJsValue(arg, extractValueOfConstraints({
            kind: "argument",
            constraint: perParamType
          }))
        };
      } else {
        return void 0;
      }
    }
    for (const [index, parameter] of declaration.parameters.entries()) {
      if (parameter.rest) {
        const restType = extractRestParamConstraint(parameter.type);
        if (restType) {
          for (let i2 = index; i2 < node.arguments.length; i2++) {
            const argNode2 = node.arguments[i2];
            if (argNode2) {
              const arg = resolveArg(argNode2, restType);
              if (arg) {
                resolvedArgs.push(arg);
              } else {
                hasError = true;
              }
            }
          }
        }
        break;
      }
      const argNode = node.arguments[index];
      if (argNode) {
        const arg = resolveArg(argNode, parameter.type);
        if (arg) {
          resolvedArgs.push(arg);
        } else {
          hasError = true;
        }
      }
    }
    return [hasError, resolvedArgs];
  }
  function extractRestParamConstraint(constraint) {
    let valueType;
    let type;
    if (constraint.valueType) {
      if (constraint.valueType.kind === "Model" && isArrayModelType(program, constraint.valueType)) {
        valueType = constraint.valueType.indexer.value;
      } else {
        return void 0;
      }
    }
    if (constraint.type) {
      if (constraint.type.kind === "Model" && isArrayModelType(program, constraint.type)) {
        type = constraint.type.indexer.value;
      } else {
        return void 0;
      }
    }
    return {
      entityKind: "MixedParameterConstraint",
      type,
      valueType
    };
  }
  function getIndexType(type) {
    return type.kind === "Model" ? type.indexer?.value : void 0;
  }
  function resolveDecoratorArgJsValue(value, valueConstraint) {
    if (valueConstraint !== void 0) {
      if (isValue(value)) {
        return marshallTypeForJS(value, valueConstraint.type);
      } else {
        return value;
      }
    }
    return value;
  }
  function checkArgumentAssignable(argumentType, parameterType, diagnosticTarget) {
    const [valid] = relation.isTypeAssignableTo(argumentType, parameterType, diagnosticTarget);
    if (!valid) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "invalid-argument",
        format: {
          value: getEntityName(argumentType),
          expected: getEntityName(parameterType)
        },
        target: diagnosticTarget
      }));
    }
    return valid;
  }
  function checkAugmentDecorators(sym, targetType, mapper) {
    const augmentDecoratorNodes = resolver.getAugmentDecoratorsForSym(sym);
    const decorators = [];
    for (const decNode of augmentDecoratorNodes) {
      const decorator = checkDecoratorApplication(targetType, decNode, mapper);
      if (decorator) {
        decorators.unshift(decorator);
      }
    }
    return decorators;
  }
  function checkAugmentDecorator(node) {
    resolveTypeReferenceSym(node.targetType, void 0);
    const links = resolver.getNodeLinks(node.targetType);
    if (links.isTemplateInstantiation) {
      program.reportDiagnostic(createDiagnostic({
        code: "augment-decorator-target",
        messageId: "noInstance",
        target: node.targetType
      }));
    } else if (links.finalSymbol?.flags && ~links.finalSymbol.flags & 1048576 && ~links.finalSymbol.flags & 65536) {
      program.reportDiagnostic(createDiagnostic({
        code: "augment-decorator-target",
        messageId: links.finalSymbol.flags & 2 ? "noModelExpression" : links.finalSymbol.flags & 64 ? "noUnionExpression" : "default",
        target: node.targetType
      }));
    } else if (links.finalSymbol?.flags && links.finalSymbol.flags & 128) {
      const aliasNode = getSymNode(links.finalSymbol);
      program.reportDiagnostic(createDiagnostic({
        code: "augment-decorator-target",
        messageId: aliasNode.value.kind === SyntaxKind.UnionExpression ? "noUnionExpression" : "default",
        target: node.targetType
      }));
    }
    return errorType;
  }
  function checkUsings(node) {
    const usedSym = resolveTypeReferenceSym(node.name, void 0);
    if (usedSym) {
      if (~usedSym.flags & 256) {
        reportCheckerDiagnostic(createDiagnostic({ code: "using-invalid-ref", target: node.name }));
      }
    }
    return errorType;
  }
  function checkDecorators(targetType, node, mapper) {
    const sym = isMemberNode(node) ? getSymbolForMember(node) ?? node.symbol : getMergedSymbol(node.symbol);
    const decorators = [];
    const augmentDecoratorNodes = resolver.getAugmentDecoratorsForSym(sym);
    const decoratorNodes = [
      ...augmentDecoratorNodes,
      // the first decorator will be executed at last, so augmented decorator should be placed at first.
      ...node.decorators
    ];
    for (const decNode of decoratorNodes) {
      const decorator = checkDecoratorApplication(targetType, decNode, mapper);
      if (decorator) {
        decorators.unshift(decorator);
      }
    }
    const docComment = extractMainDoc(targetType);
    if (docComment) {
      decorators.unshift(createDocFromCommentDecorator("self", docComment));
    }
    if (targetType.kind === "Operation") {
      const returnTypesDocs = extractReturnsDocs(targetType);
      if (returnTypesDocs.returns) {
        decorators.unshift(createDocFromCommentDecorator("returns", returnTypesDocs.returns));
      }
      if (returnTypesDocs.errors) {
        decorators.unshift(createDocFromCommentDecorator("errors", returnTypesDocs.errors));
      }
    } else if (targetType.kind === "ModelProperty") {
    }
    return decorators;
  }
  function checkScalar(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    checkTemplateDeclaration(node, mapper);
    const decorators = [];
    const type = createType({
      kind: "Scalar",
      name: node.id.sv,
      node,
      constructors: /* @__PURE__ */ new Map(),
      namespace: getParentNamespaceType(node),
      decorators,
      derivedScalars: []
    });
    linkType(links, type, mapper);
    if (node.extends) {
      type.baseScalar = checkScalarExtends(node, node.extends, mapper);
      if (type.baseScalar) {
        copyDeprecation(type.baseScalar, type);
        type.baseScalar.derivedScalars.push(type);
      }
    }
    checkScalarConstructors(type, node, type.constructors, mapper);
    decorators.push(...checkDecorators(type, node, mapper));
    if (mapper === void 0) {
      type.namespace?.scalars.set(type.name, type);
    }
    linkMapper(type, mapper);
    if (isInTypeSpecNamespace2(type)) {
      stdTypes[type.name] = type;
    }
    return finishType(type, { skipDecorators: !shouldRunDecorators(node, mapper) });
  }
  function checkScalarExtends(scalar, extendsRef, mapper) {
    const symId = getNodeSym(scalar);
    pendingResolutions.start(symId, ResolutionKind.BaseType);
    const target = resolver.getNodeLinks(extendsRef).resolvedSymbol;
    if (target && pendingResolutions.has(target, ResolutionKind.BaseType)) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "circular-base-type",
          format: { typeName: target.declarations[0].id.sv },
          target
        }));
      }
      return void 0;
    }
    const extendsType = getTypeForNode(extendsRef, mapper);
    pendingResolutions.finish(symId, ResolutionKind.BaseType);
    if (isErrorType(extendsType)) {
      compilerAssert(program.hasError(), "Should already have reported an error.", extendsRef);
      return void 0;
    }
    if (extendsType.kind !== "Scalar") {
      reportCheckerDiagnostic(createDiagnostic({ code: "extend-model", target: extendsRef }));
      return void 0;
    }
    return extendsType;
  }
  function checkScalarConstructors(parentScalar, node, constructors, mapper) {
    if (parentScalar.baseScalar) {
      for (const member of parentScalar.baseScalar.constructors.values()) {
        const newConstructor = cloneTypeForSymbol(getMemberSymbol(node.symbol, member.name), {
          ...member,
          scalar: parentScalar
        });
        linkIndirectMember(node, newConstructor, mapper);
        constructors.set(member.name, newConstructor);
      }
    }
    for (const member of node.members) {
      const constructor = checkScalarConstructor(member, mapper, parentScalar);
      if (constructors.has(constructor.name)) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "constructor-duplicate",
          format: { name: constructor.name.toString() },
          target: member
        }));
        continue;
      }
      constructors.set(constructor.name, constructor);
    }
  }
  function checkScalarConstructor(node, mapper, parentScalar) {
    const name = node.id.sv;
    const links = getSymbolLinksForMember(node);
    if (links && links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const member = createType({
      kind: "ScalarConstructor",
      scalar: parentScalar,
      name,
      node,
      parameters: node.parameters.map((x2) => checkFunctionParameter(x2, mapper, false))
    });
    linkMapper(member, mapper);
    if (links) {
      linkType(links, member, mapper);
    }
    return finishType(member, {
      skipDecorators: !shouldRunDecorators(node.parent, mapper)
    });
  }
  function checkAlias(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    checkTemplateDeclaration(node, mapper);
    const aliasSymId = getNodeSym(node);
    if (pendingResolutions.has(aliasSymId, ResolutionKind.Type)) {
      if (mapper === void 0) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "circular-alias-type",
          format: { typeName: node.id.sv },
          target: node
        }));
      }
      links.declaredType = errorType;
      return errorType;
    }
    pendingResolutions.start(aliasSymId, ResolutionKind.Type);
    const type = checkNode(node.value, mapper);
    if (type === null) {
      links.declaredType = errorType;
      return errorType;
    }
    if (isValue(type)) {
      reportCheckerDiagnostic(createDiagnostic({ code: "value-in-type", target: node.value }));
      links.declaredType = errorType;
      return errorType;
    }
    linkType(links, type, mapper);
    pendingResolutions.finish(aliasSymId, ResolutionKind.Type);
    return type;
  }
  function checkConst(node) {
    const links = getSymbolLinks(node.symbol);
    if (links.value !== void 0) {
      return links.value;
    }
    const type = node.type ? getTypeForNode(node.type, void 0) : void 0;
    if (pendingResolutions.has(node.symbol, ResolutionKind.Value)) {
      reportCheckerDiagnostic(createDiagnostic({
        code: "circular-const",
        format: { name: node.id.sv },
        target: node
      }));
      return null;
    }
    pendingResolutions.start(node.symbol, ResolutionKind.Value);
    const value = getValueForNode(node.value, void 0, type && { kind: "assignment", type });
    pendingResolutions.finish(node.symbol, ResolutionKind.Value);
    if (value === null || type && !checkValueOfType(value, type, node.id)) {
      links.value = null;
      return links.value;
    }
    links.value = type ? copyValue(value, { type }) : copyValue(value);
    return links.value;
  }
  function inferScalarsFromConstraints(value, type) {
    switch (value.valueKind) {
      case "BooleanValue":
      case "StringValue":
      case "NumericValue":
        if (value.scalar === void 0) {
          const scalar = inferScalarForPrimitiveValue(type, value.type);
          return copyValue(value, { scalar });
        }
        return value;
      case "ArrayValue":
      case "ObjectValue":
      case "EnumValue":
      case "NullValue":
      case "ScalarValue":
        return value;
    }
  }
  function checkEnum(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (!links.type) {
      const enumType = links.type = createType({
        kind: "Enum",
        name: node.id.sv,
        node,
        members: createRekeyableMap(),
        decorators: []
      });
      const memberNames = /* @__PURE__ */ new Set();
      for (const member of node.members) {
        if (member.kind === SyntaxKind.EnumMember) {
          const memberType = checkEnumMember(member, mapper, enumType);
          if (memberNames.has(memberType.name)) {
            reportCheckerDiagnostic(createDiagnostic({
              code: "enum-member-duplicate",
              format: { name: memberType.name },
              target: node
            }));
            continue;
          }
          memberNames.add(memberType.name);
          enumType.members.set(memberType.name, memberType);
        } else {
          const members = checkEnumSpreadMember(node.symbol, enumType, member.target, mapper, memberNames);
          for (const memberType of members) {
            linkIndirectMember(node, memberType, mapper);
            enumType.members.set(memberType.name, memberType);
          }
        }
      }
      const namespace = getParentNamespaceType(node);
      enumType.namespace = namespace;
      enumType.namespace?.enums.set(enumType.name, enumType);
      enumType.decorators = checkDecorators(enumType, node, mapper);
      linkMapper(enumType, mapper);
      finishType(enumType);
    }
    return links.type;
  }
  function checkInterface(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    checkTemplateDeclaration(node, mapper);
    const interfaceType = createType({
      kind: "Interface",
      decorators: [],
      node,
      namespace: getParentNamespaceType(node),
      sourceInterfaces: [],
      operations: createRekeyableMap(),
      name: node.id.sv
    });
    linkType(links, interfaceType, mapper);
    interfaceType.decorators = checkDecorators(interfaceType, node, mapper);
    const ownMembers = checkInterfaceMembers(node, mapper, interfaceType);
    for (const extendsNode of node.extends) {
      const extendsType = getTypeForNode(extendsNode, mapper);
      if (extendsType.kind !== "Interface") {
        reportCheckerDiagnostic(createDiagnostic({ code: "extends-interface", target: extendsNode }));
        continue;
      }
      for (const member of extendsType.operations.values()) {
        if (interfaceType.operations.has(member.name)) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "extends-interface-duplicate",
            format: { name: member.name },
            target: extendsNode
          }));
        }
        const newMember = cloneTypeForSymbol(getMemberSymbol(node.symbol, member.name), member, {
          interface: interfaceType
        });
        if (!ownMembers.has(member.name)) {
          linkIndirectMember(node, newMember, mapper);
        }
        copyDeprecation(member, newMember);
        interfaceType.operations.set(newMember.name, newMember);
      }
      interfaceType.sourceInterfaces.push(extendsType);
    }
    for (const [key, value] of ownMembers) {
      interfaceType.operations.set(key, value);
    }
    linkMapper(interfaceType, mapper);
    if (mapper === void 0) {
      interfaceType.namespace?.interfaces.set(interfaceType.name, interfaceType);
    }
    lateBindMemberContainer(interfaceType);
    lateBindMembers(interfaceType);
    return finishType(interfaceType, {
      skipDecorators: !shouldRunDecorators(node, mapper)
    });
  }
  function checkInterfaceMembers(node, mapper, interfaceType) {
    const ownMembers = /* @__PURE__ */ new Map();
    for (const opNode of node.operations) {
      const opType = checkOperation(opNode, mapper, interfaceType);
      if (ownMembers.has(opType.name)) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "interface-duplicate",
          format: { name: opType.name },
          target: opNode
        }));
        continue;
      }
      ownMembers.set(opType.name, opType);
    }
    return ownMembers;
  }
  function checkUnion(node, mapper) {
    const links = getSymbolLinks(node.symbol);
    if (links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    checkTemplateDeclaration(node, mapper);
    const variants = createRekeyableMap();
    const unionType = createType({
      kind: "Union",
      decorators: [],
      node,
      namespace: getParentNamespaceType(node),
      name: node.id.sv,
      variants,
      get options() {
        return Array.from(this.variants.values()).map((v2) => v2.type);
      },
      expression: false
    });
    linkType(links, unionType, mapper);
    unionType.decorators = checkDecorators(unionType, node, mapper);
    checkUnionVariants(unionType, node, variants, mapper);
    linkMapper(unionType, mapper);
    if (mapper === void 0) {
      unionType.namespace?.unions.set(unionType.name, unionType);
    }
    lateBindMemberContainer(unionType);
    lateBindMembers(unionType);
    return finishType(unionType, { skipDecorators: !shouldRunDecorators(node, mapper) });
  }
  function checkUnionVariants(parentUnion, node, variants, mapper) {
    for (const variantNode of node.options) {
      const variantType = checkUnionVariant(variantNode, mapper);
      variantType.union = parentUnion;
      if (variants.has(variantType.name)) {
        reportCheckerDiagnostic(createDiagnostic({
          code: "union-duplicate",
          format: { name: variantType.name.toString() },
          target: variantNode
        }));
        continue;
      }
      variants.set(variantType.name, variantType);
    }
  }
  function checkUnionVariant(variantNode, mapper) {
    const links = getSymbolLinksForMember(variantNode);
    if (links && links.declaredType && mapper === void 0) {
      return links.declaredType;
    }
    const name = variantNode.id ? variantNode.id.sv : Symbol("name");
    const type = getTypeForNode(variantNode.value, mapper);
    const variantType = createType({
      kind: "UnionVariant",
      name,
      node: variantNode,
      decorators: [],
      type,
      union: void 0
    });
    variantType.decorators = checkDecorators(variantType, variantNode, mapper);
    linkMapper(variantType, mapper);
    if (links) {
      linkType(links, variantType, mapper);
    }
    return finishType(variantType, {
      skipDecorators: !shouldRunDecorators(variantNode.parent, mapper)
    });
  }
  function isMemberNode(node) {
    return node.symbol && !!(node.symbol.flags & 65536);
  }
  function getMemberSymbol(parentSym, name) {
    return parentSym ? resolver.getAugmentedSymbolTable(parentSym.members).get(name) : void 0;
  }
  function getSymbolForMember(node) {
    if (!node.id) {
      return void 0;
    }
    const name = node.id.sv;
    const parentSym = node.parent?.symbol;
    return parentSym ? getMemberSymbol(parentSym, name) : void 0;
  }
  function getSymbolLinksForMember(node) {
    const sym = getSymbolForMember(node);
    return sym ? getSymNode(sym) === node ? getSymbolLinks(sym) : void 0 : void 0;
  }
  function checkEnumMember(node, mapper, parentEnum) {
    const name = node.id.sv;
    const links = getSymbolLinksForMember(node);
    if (links?.type) {
      return links.type;
    }
    compilerAssert(parentEnum, "Enum member should already have been checked.");
    const value = node.value ? node.value.value : void 0;
    const member = createType({
      kind: "EnumMember",
      enum: parentEnum,
      name,
      node,
      value,
      decorators: []
    });
    if (links) {
      links.type = member;
    }
    member.decorators = checkDecorators(member, node, mapper);
    return finishType(member);
  }
  function checkEnumSpreadMember(parentEnumSym, parentEnum, targetNode, mapper, existingMemberNames) {
    const members = [];
    const targetType = getTypeForNode(targetNode, mapper);
    if (!isErrorType(targetType)) {
      if (targetType.kind !== "Enum") {
        reportCheckerDiagnostic(createDiagnostic({ code: "spread-enum", target: targetNode }));
        return members;
      }
      for (const member of targetType.members.values()) {
        if (existingMemberNames.has(member.name)) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "enum-member-duplicate",
            format: { name: member.name },
            target: targetNode
          }));
        } else {
          existingMemberNames.add(member.name);
          const memberSym = getMemberSymbol(parentEnumSym, member.name);
          const clonedMember = cloneTypeForSymbol(memberSym, member, {
            enum: parentEnum,
            sourceMember: member
          });
          if (clonedMember) {
            members.push(clonedMember);
          }
        }
      }
    }
    return members;
  }
  function checkDirectives(node, type) {
    let hasDeprecation = false;
    for (const directive of node.directives ?? []) {
      if (directive.target.sv === "deprecated") {
        const message = directive.arguments[0];
        if (message === void 0) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-deprecation-argument",
            messageId: "missing",
            target: directive
          }));
          continue;
        }
        let messageStr;
        if (message.kind !== SyntaxKind.StringLiteral) {
          reportCheckerDiagnostic(createDiagnostic({
            code: "invalid-deprecation-argument",
            format: { kind: SyntaxKind[message.kind] },
            target: directive.arguments[0]
          }));
          messageStr = "<missing message>";
        } else {
          messageStr = message.value;
        }
        if (hasDeprecation === true) {
          reportCheckerDiagnostic(createDiagnostic({ code: "duplicate-deprecation", target: node }));
        } else {
          hasDeprecation = true;
          markDeprecated(program, type, {
            message: messageStr
          });
        }
      }
    }
  }
  function createAndFinishType(typeDef) {
    createType(typeDef);
    return finishType(typeDef);
  }
  function initModel(node) {
    return createType({
      kind: "Model",
      node,
      name: "",
      namespace: node && getParentNamespaceType(node),
      properties: createRekeyableMap(),
      decorators: [],
      derivedModels: [],
      sourceModels: []
    });
  }
  function createType(typeDef) {
    stats.createdTypes++;
    Object.setPrototypeOf(typeDef, typePrototype);
    typeDef.isFinished = false;
    typeDef.creating = true;
    const createdType = typeDef;
    createdType.entityKind = "Type";
    if (createdType.node) {
      checkDirectives(createdType.node, createdType);
    }
    return createdType;
  }
  function finishType(typeDef, options = {}) {
    stats.finishedTypes++;
    if (!options.skipDecorators) {
      if ("decorators" in typeDef) {
        for (const decApp of typeDef.decorators) {
          applyDecoratorToType(program, decApp, typeDef);
        }
      }
      typeDef.isFinished = true;
      Object.setPrototypeOf(typeDef, typePrototype);
    }
    markAsChecked(typeDef);
    return typeDef;
  }
  function markAsChecked(type) {
    if (!type.creating)
      return;
    delete type.creating;
    const pending = waitingForResolution.get(type);
    if (pending) {
      pending.forEach(([_2, resolution]) => resolution());
    }
    waitingForResolution.delete(type);
  }
  function getLiteralType(node) {
    return createLiteralType(node.value, node);
  }
  function getMergedSymbol(sym) {
    return resolver.getMergedSymbol(sym);
  }
  function createGlobalNamespaceType() {
    const sym = resolver.symbols.global;
    const type = createType({
      kind: "Namespace",
      name: "",
      node: getGlobalNamespaceNode(),
      models: /* @__PURE__ */ new Map(),
      scalars: /* @__PURE__ */ new Map(),
      operations: /* @__PURE__ */ new Map(),
      namespaces: /* @__PURE__ */ new Map(),
      interfaces: /* @__PURE__ */ new Map(),
      unions: /* @__PURE__ */ new Map(),
      enums: /* @__PURE__ */ new Map(),
      decoratorDeclarations: /* @__PURE__ */ new Map(),
      functionDeclarations: /* @__PURE__ */ new Map(),
      decorators: []
    });
    getSymbolLinks(sym).type = type;
    type.decorators = checkAugmentDecorators(sym, type, void 0);
    return finishType(type);
  }
  function initializeClone(type, additionalProps) {
    let clone;
    switch (type.kind) {
      case "Model":
        const newModel = createType({
          ...type,
          decorators: [...type.decorators],
          properties: void 0,
          ...additionalProps
        });
        if (!("properties" in additionalProps)) {
          newModel.properties = createRekeyableMap(Array.from(type.properties.entries()).map(([key, prop]) => [
            key,
            cloneType(prop, { model: newModel })
          ]));
        }
        clone = newModel;
        break;
      case "Union":
        const newUnion = createType({
          ...type,
          decorators: [...type.decorators],
          variants: void 0,
          get options() {
            return Array.from(this.variants.values()).map((v2) => v2.type);
          },
          ...additionalProps
        });
        if (!("variants" in additionalProps)) {
          newUnion.variants = createRekeyableMap(Array.from(type.variants.entries()).map(([key, prop]) => [
            key,
            cloneType(prop, { union: newUnion })
          ]));
        }
        clone = newUnion;
        break;
      case "Interface":
        const newInterface = createType({
          ...type,
          decorators: [...type.decorators],
          operations: void 0,
          ...additionalProps
        });
        if (!("operations" in additionalProps)) {
          newInterface.operations = createRekeyableMap(Array.from(type.operations.entries()).map(([key, prop]) => [
            key,
            cloneType(prop, { interface: newInterface })
          ]));
        }
        clone = newInterface;
        break;
      case "Enum":
        const newEnum = createType({
          ...type,
          decorators: [...type.decorators],
          members: void 0,
          ...additionalProps
        });
        if (!("members" in additionalProps)) {
          newEnum.members = createRekeyableMap(Array.from(type.members.entries()).map(([key, prop]) => [
            key,
            cloneType(prop, { enum: newEnum })
          ]));
        }
        clone = newEnum;
        break;
      default:
        clone = createType({
          ...type,
          ..."decorators" in type ? { decorators: [...type.decorators] } : {},
          ...additionalProps
        });
        break;
    }
    return clone;
  }
  function cloneType(type, additionalProps = {}) {
    const clone = initializeClone(type, additionalProps);
    compilerAssert(clone.kind === type.kind, "cloneType must not change type kind");
    return finishType(clone, { skipDecorators: !type.isFinished });
  }
  function cloneTypeForSymbol(sym, type, additionalProps = {}) {
    let clone = initializeClone(type, additionalProps);
    if ("decorators" in clone) {
      const docComment = docFromCommentForSym.get(sym);
      if (docComment) {
        clone.decorators.push(createDocFromCommentDecorator("self", docComment));
      }
      for (const dec of checkAugmentDecorators(sym, clone, void 0)) {
        clone.decorators.push(dec);
      }
    }
    if (type.isFinished) {
      clone = finishType(clone);
    }
    compilerAssert(clone.kind === type.kind, "cloneType must not change type kind");
    return clone;
  }
  function createLiteralType(value, node) {
    if (program.literalTypes.has(value)) {
      return program.literalTypes.get(value);
    }
    let type;
    switch (typeof value) {
      case "string":
        type = createType({ kind: "String", value });
        break;
      case "boolean":
        type = createType({ kind: "Boolean", value });
        break;
      case "number":
        let valueAsString;
        if (node) {
          compilerAssert(node.kind === SyntaxKind.NumericLiteral, "Must pass numeric literal node or undefined when creating a numeric literal type");
          valueAsString = node.valueAsString;
        } else {
          valueAsString = String(value);
        }
        type = createType({
          kind: "Number",
          value,
          valueAsString,
          numericValue: Numeric(valueAsString)
        });
        break;
    }
    program.literalTypes.set(value, type);
    return finishType(type);
  }
  function checkTypeOfValueMatchConstraint(source, constraint, diagnosticTarget) {
    const [related, diagnostics] = relation.isTypeAssignableTo(source, constraint.type, diagnosticTarget);
    if (!related) {
      if (constraint.kind === "argument") {
        reportCheckerDiagnostic(createDiagnostic({
          code: "invalid-argument",
          format: {
            value: getEntityName(source),
            expected: getEntityName(constraint.type)
          },
          target: diagnosticTarget
        }));
      } else {
        reportCheckerDiagnostics(diagnostics);
      }
    }
    return related;
  }
  function checkTypeAssignable(source, target, diagnosticTarget) {
    const [related, diagnostics] = relation.isTypeAssignableTo(source, target, diagnosticTarget);
    if (!related) {
      reportCheckerDiagnostics(diagnostics);
    }
    return related;
  }
  function checkValueOfType(source, target, diagnosticTarget) {
    const [related, diagnostics] = relation.isValueOfType(source, target, diagnosticTarget);
    if (!related) {
      reportCheckerDiagnostics(diagnostics);
    }
    return related;
  }
  function isStdType2(type, stdType) {
    if (type.kind !== "Model" && type.kind !== "Scalar" || type.namespace === void 0 || !isTypeSpecNamespace2(type.namespace))
      return false;
    if (type.kind === "Scalar")
      return stdType === void 0 || stdType === type.name;
    if (stdType === "Array" && type === stdTypes["Array"])
      return true;
    if (stdType === "Record" && type === stdTypes["Record"])
      return true;
    if (type.kind === "Model")
      return stdType === void 0 || stdType === type.name;
    return false;
  }
  function getValueExactType(value) {
    return valueExactTypes.get(value);
  }
}
function getNamedSourceModels(property) {
  if (!property.sourceProperty) {
    return void 0;
  }
  const set = /* @__PURE__ */ new Set();
  for (let p2 = property; p2; p2 = p2.sourceProperty) {
    if (p2.model?.name) {
      set.add(p2.model);
    }
  }
  return set;
}
function addDerivedModels(models, possiblyDerivedModels) {
  for (const element of possiblyDerivedModels) {
    if (!models.has(element)) {
      for (let t2 = element.baseModel; t2; t2 = t2.baseModel) {
        if (models.has(t2)) {
          models.add(element);
          break;
        }
      }
    }
  }
}
function createTypeMapper(parameters, args, source, parentMapper) {
  const map = new Map(parentMapper?.map ?? []);
  for (const [index, param] of parameters.entries()) {
    map.set(param, args[index]);
  }
  return {
    partial: false,
    args: [...parentMapper?.args ?? [], ...args],
    getMappedType: (type) => {
      return map.get(type) ?? type;
    },
    source,
    map
  };
}
function getEffectiveModelType(program, model, filter) {
  if (filter) {
    model = filterModelProperties(program, model, filter);
  }
  if (model.name) {
    return model;
  }
  compilerAssert(!model.baseModel, "Anonymous model with base model.");
  if (model.properties.size === 0) {
    return model;
  }
  let candidates;
  for (const property of model.properties.values()) {
    const sources = getNamedSourceModels(property);
    if (!sources) {
      return model;
    }
    if (!candidates) {
      candidates = sources;
      continue;
    }
    addDerivedModels(sources, candidates);
    for (const candidate of candidates) {
      if (!sources.has(candidate)) {
        candidates.delete(candidate);
      }
    }
  }
  let match;
  for (const candidate of candidates ?? []) {
    if (model.properties.size === countPropertiesInherited(candidate)) {
      match = candidate;
      break;
    }
    if (filter && !match && model.properties.size === countPropertiesInherited(candidate, filter)) {
      match = candidate;
      continue;
    }
  }
  return match ?? model;
}
function filterModelProperties(program, model, filter) {
  let filtered = false;
  for (const property of walkPropertiesInherited(model)) {
    if (!filter(property)) {
      filtered = true;
      break;
    }
  }
  if (!filtered) {
    return model;
  }
  const realm = Realm.realmForType.get(model);
  const typekit = realm ? $2(realm) : $2(program);
  const newModel = typekit.model.create({
    name: "",
    indexer: void 0,
    properties: {},
    decorators: [],
    derivedModels: [],
    sourceModels: [{ usage: "spread", model }]
  });
  for (const property of walkPropertiesInherited(model)) {
    if (filter(property)) {
      const newProperty = typekit.type.clone(property);
      Object.assign(newProperty, {
        sourceProperty: property,
        model: newModel
      });
      newModel.properties.set(property.name, newProperty);
      typekit.type.finishType(newProperty);
    }
  }
  return program.checker.finishType(newModel);
}
function getOverriddenProperty(property) {
  compilerAssert(property.model, "Parent model must be set before overridden property can be found.");
  for (let current = property.model.baseModel; current; current = current.baseModel) {
    const overridden = current.properties.get(property.name);
    if (overridden) {
      return overridden;
    }
  }
  return void 0;
}
function* walkPropertiesInherited(model) {
  const returned = /* @__PURE__ */ new Set();
  for (let current = model; current; current = current.baseModel) {
    for (const property of current.properties.values()) {
      if (returned.has(property.name)) {
        continue;
      }
      returned.add(property.name);
      yield property;
    }
  }
}
function countPropertiesInherited(model, filter) {
  let count = 0;
  for (const property of walkPropertiesInherited(model)) {
    if (!filter || filter(property)) {
      count++;
    }
  }
  return count;
}
function linkMapper(typeDef, mapper) {
  if (mapper) {
    compilerAssert(!typeDef.templateMapper, "Mapper provided but template arguments already set.");
    typeDef.templateMapper = mapper;
  }
}
function extractMainDoc(type) {
  if (type.node?.docs === void 0) {
    return void 0;
  }
  let mainDoc = "";
  for (const doc of type.node.docs) {
    mainDoc += getDocContent(doc.content);
  }
  const trimmed = mainDoc.trim();
  return trimmed === "" ? void 0 : trimmed;
}
function extractReturnsDocs(type) {
  const result = {
    returns: void 0,
    errors: void 0
  };
  if (type.node?.docs === void 0) {
    return result;
  }
  for (const doc of type.node.docs) {
    for (const tag of doc.tags) {
      if (tag.kind === SyntaxKind.DocReturnsTag) {
        result.returns = getDocContent(tag.content);
      }
      if (tag.kind === SyntaxKind.DocErrorsTag) {
        result.errors = getDocContent(tag.content);
      }
    }
  }
  return result;
}
function extractParamDocs(node) {
  if (node.docs === void 0) {
    return /* @__PURE__ */ new Map();
  }
  const paramDocs = /* @__PURE__ */ new Map();
  for (const doc of node.docs) {
    for (const tag of doc.tags) {
      if (tag.kind === SyntaxKind.DocParamTag) {
        paramDocs.set(tag.paramName.sv, getDocContent(tag.content));
      }
    }
  }
  return paramDocs;
}
function extractPropDocs(node) {
  if (node.docs === void 0) {
    return /* @__PURE__ */ new Map();
  }
  const propDocs = /* @__PURE__ */ new Map();
  for (const doc of node.docs) {
    for (const tag of doc.tags) {
      if (tag.kind === SyntaxKind.DocPropTag) {
        propDocs.set(tag.propName.sv, getDocContent(tag.content));
      }
    }
  }
  return propDocs;
}
function getDocContent(content) {
  const docs = [];
  for (const node of content) {
    compilerAssert(node.kind === SyntaxKind.DocText, "No other doc content node kinds exist yet. Update this code appropriately when more are added.");
    docs.push(node.text);
  }
  return docs.join("");
}
function reportDeprecation(program, target, message, reportFunc) {
  if (program.compilerOptions.ignoreDeprecated !== true) {
    reportFunc(createDiagnostic({
      code: "deprecated",
      format: {
        message
      },
      target
    }));
  }
}
function applyDecoratorToType(program, decApp, target) {
  compilerAssert("decorators" in target, "Cannot apply decorator to non-decoratable type", target);
  for (const arg of decApp.args) {
    if (isType(arg.value) && isErrorType(arg.value)) {
      return;
    }
  }
  if (decApp.definition) {
    const deprecation = getDeprecationDetails(program, decApp.definition);
    if (deprecation !== void 0) {
      reportDeprecation(program, decApp.node ?? target, deprecation.message, program.reportDiagnostic);
    }
  }
  try {
    const args = decApp.args.map((x2) => x2.jsValue);
    const fn2 = decApp.decorator;
    const context = createDecoratorContext(program, decApp);
    fn2(context, target, ...args);
  } catch (error) {
    if (program.compilerOptions.designTimeBuild) {
      program.reportDiagnostic(createDiagnostic({
        code: "decorator-fail",
        format: { decoratorName: decApp.decorator.name, error: error.stack },
        target: decApp.node ?? target
      }));
    } else {
      throw error;
    }
  }
}
function createDecoratorContext(program, decApp) {
  function createPassThruContext(program2, decApp2) {
    return {
      program: program2,
      decoratorTarget: decApp2.node,
      getArgumentTarget: () => decApp2.node,
      call: (decorator, target, ...args) => {
        return decorator(createPassThruContext(program2, decApp2), target, ...args);
      }
    };
  }
  return {
    program,
    decoratorTarget: decApp.node,
    getArgumentTarget: (index) => {
      return decApp.args[index]?.node;
    },
    call: (decorator, target, ...args) => {
      return decorator(createPassThruContext(program, decApp), target, ...args);
    }
  };
}
function isTemplatedNode(node) {
  return "templateParameters" in node && node.templateParameters.length > 0;
}
var ResolutionKind;
(function(ResolutionKind2) {
  ResolutionKind2[ResolutionKind2["Value"] = 0] = "Value";
  ResolutionKind2[ResolutionKind2["Type"] = 1] = "Type";
  ResolutionKind2[ResolutionKind2["BaseType"] = 2] = "BaseType";
  ResolutionKind2[ResolutionKind2["Constraint"] = 3] = "Constraint";
})(ResolutionKind || (ResolutionKind = {}));
var PendingResolutions = class {
  #data = /* @__PURE__ */ new Map();
  start(symId, kind) {
    let existing = this.#data.get(symId);
    if (existing === void 0) {
      existing = /* @__PURE__ */ new Set();
      this.#data.set(symId, existing);
    }
    existing.add(kind);
  }
  has(symId, kind) {
    return this.#data.get(symId)?.has(kind) ?? false;
  }
  finish(symId, kind) {
    const existing = this.#data.get(symId);
    if (existing === void 0) {
      return;
    }
    existing?.delete(kind);
    if (existing.size === 0) {
      this.#data.delete(symId);
    }
  }
};
var defaultSymbolResolutionOptions = {
  resolveDecorators: false,
  checkTemplateTypes: true
};
function printTypeReferenceNode(node) {
  switch (node.kind) {
    case SyntaxKind.MemberExpression:
      return `${printTypeReferenceNode(node.base)}.${printTypeReferenceNode(node.id)}`;
    case SyntaxKind.TypeReference:
      return printTypeReferenceNode(node.target);
    case SyntaxKind.Identifier:
      return node.sv;
  }
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/model.js
var indexCache = /* @__PURE__ */ new Map();
defineKit({
  model: {
    create(desc) {
      const properties = createRekeyableMap(Array.from(Object.entries(desc.properties)));
      const model = this.program.checker.createType({
        kind: "Model",
        name: desc.name ?? "",
        decorators: decoratorApplication(this, desc.decorators),
        properties,
        derivedModels: desc.derivedModels ?? [],
        sourceModels: desc.sourceModels ?? [],
        indexer: desc.indexer
      });
      this.program.checker.finishType(model);
      return model;
    },
    is(type) {
      return type.entityKind === "Type" && type.kind === "Model";
    },
    isExpresion(type) {
      return type.name === "";
    },
    getEffectiveModel(model, filter) {
      return getEffectiveModelType(this.program, model, filter);
    },
    getIndexType(model) {
      if (indexCache.has(model)) {
        return indexCache.get(model);
      }
      if (!model.indexer) {
        return void 0;
      }
      if (model.indexer.key.name === "string") {
        const record = this.record.create(model.indexer.value);
        indexCache.set(model, record);
        return record;
      }
      if (model.indexer.key.name === "integer") {
        const array = this.array.create(model.indexer.value);
        indexCache.set(model, array);
        return array;
      }
      return void 0;
    },
    getProperties(model, options = {}) {
      const properties = copyMap(model.properties);
      const discriminator = this.model.getDiscriminatedUnion(model);
      if (discriminator) {
        const discriminatorName = discriminator.propertyName;
        properties.set(discriminatorName, this.modelProperty.create({ name: discriminatorName, type: this.builtin.string }));
      }
      if (options.includeExtended) {
        let base = model.baseModel;
        while (base) {
          for (const [key, value] of base.properties) {
            if (!properties.has(key)) {
              properties.set(key, value);
            }
          }
          base = base.baseModel;
        }
      }
      return properties;
    },
    getAdditionalPropertiesRecord(model) {
      if (this.model.is(model) && model.sourceModel && this.record.is(model.sourceModel)) {
        return model.sourceModel;
      }
      if (model.baseModel && this.record.is(model.baseModel)) {
        return model.baseModel;
      }
      const indexType = this.model.getIndexType(model);
      if (indexType && this.record.is(indexType)) {
        return indexType;
      }
      if (model.baseModel) {
        return this.model.getAdditionalPropertiesRecord(model.baseModel);
      }
      return void 0;
    },
    getDiscriminatedUnion: createDiagnosable(function(model) {
      const discriminator = getDiscriminator(this.program, model);
      if (!discriminator) {
        return [void 0, []];
      }
      return getDiscriminatedUnionFromInheritance(model, discriminator);
    })
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/operation.js
defineKit({
  operation: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "Operation";
    },
    getPagingMetadata: createDiagnosable(function(operation) {
      return getPagingOperation(this.program, operation);
    }),
    create(desc) {
      const parametersModel = this.model.create({
        name: `${desc.name}Parameters`,
        properties: desc.parameters.reduce((acc, property) => {
          acc[property.name] = property;
          return acc;
        }, {})
      });
      const operation = this.program.checker.createType({
        kind: "Operation",
        name: desc.name,
        decorators: [],
        parameters: parametersModel,
        returnType: desc.returnType
      });
      this.program.checker.finishType(operation);
      return operation;
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/record.js
defineKit({
  record: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "Model" && isRecordModelType(this.program, type) && type.properties.size === 0;
    },
    getElementType(type) {
      if (!this.record.is(type)) {
        throw new Error("Type is not a record.");
      }
      return type.indexer.value;
    },
    create(elementType) {
      return this.model.create({
        name: "Record",
        properties: {},
        indexer: {
          key: this.builtin.string,
          value: elementType
        }
      });
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/scalar.js
defineKit({
  scalar: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "Scalar";
    },
    extendsBoolean: extendsStdType("boolean"),
    extendsBytes: extendsStdType("bytes"),
    extendsDecimal: extendsStdType("decimal"),
    extendsDecimal128: extendsStdType("decimal128"),
    extendsDuration: extendsStdType("duration"),
    extendsFloat: extendsStdType("float"),
    extendsFloat32: extendsStdType("float32"),
    extendsFloat64: extendsStdType("float64"),
    extendsInt8: extendsStdType("int8"),
    extendsInt16: extendsStdType("int16"),
    extendsInt32: extendsStdType("int32"),
    extendsInt64: extendsStdType("int64"),
    extendsInteger: extendsStdType("integer"),
    extendsNumeric: extendsStdType("numeric"),
    extendsOffsetDateTime: extendsStdType("offsetDateTime"),
    extendsPlainDate: extendsStdType("plainDate"),
    extendsPlainTime: extendsStdType("plainTime"),
    extendsSafeint: extendsStdType("safeint"),
    extendsString: extendsStdType("string"),
    extendsUint8: extendsStdType("uint8"),
    extendsUint16: extendsStdType("uint16"),
    extendsUint32: extendsStdType("uint32"),
    extendsUint64: extendsStdType("uint64"),
    extendsUrl: extendsStdType("url"),
    extendsUtcDateTime: extendsStdType("utcDateTime"),
    isBoolean: isStdType("boolean"),
    isBytes: isStdType("bytes"),
    isDecimal: isStdType("decimal"),
    isDecimal128: isStdType("decimal128"),
    isDuration: isStdType("duration"),
    isFloat: isStdType("float"),
    isFloat32: isStdType("float32"),
    isFloat64: isStdType("float64"),
    isInt8: isStdType("int8"),
    isInt16: isStdType("int16"),
    isInt32: isStdType("int32"),
    isInt64: isStdType("int64"),
    isInteger: isStdType("integer"),
    isNumeric: isStdType("numeric"),
    isOffsetDateTime: isStdType("offsetDateTime"),
    isPlainDate: isStdType("plainDate"),
    isPlainTime: isStdType("plainTime"),
    isSafeint: isStdType("safeint"),
    isString: isStdType("string"),
    isUint8: isStdType("uint8"),
    isUint16: isStdType("uint16"),
    isUint32: isStdType("uint32"),
    isUint64: isStdType("uint64"),
    isUrl: isStdType("url"),
    isUtcDateTime: isStdType("utcDateTime"),
    getStdBase(type) {
      const tspNamespace = this.program.resolveTypeReference("TypeSpec")[0];
      let current = type;
      while (current) {
        if (current.namespace === tspNamespace) {
          return current;
        }
        current = current.baseScalar;
      }
      return null;
    },
    getEncoding(type) {
      return getEncode(this.program, type);
    },
    getFormat(type) {
      return getFormat(this.program, type);
    }
  }
});
function isStdType(typeName) {
  return function(type) {
    return type === this.program.checker.getStdType(typeName);
  };
}
function extendsStdType(typeName) {
  return function(type) {
    if (!this.scalar.is(type)) {
      return false;
    }
    return isIntrinsicType(this.program, type, typeName);
  };
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/tuple.js
defineKit({
  tuple: {
    is(type) {
      return type.entityKind === "Type" && type.kind === "Tuple";
    },
    create(values = []) {
      const tuple = this.program.checker.createType({
        kind: "Tuple",
        name: "Tuple",
        values
      });
      this.program.checker.finishType(tuple);
      return tuple;
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/utils/get-plausible-name.js
function getPlausibleName(type) {
  let name = type.name ?? "TypeExpression";
  if (isTemplateInstance(type)) {
    const namePrefix = type.templateMapper.args.map((a2) => {
      if (a2.entityKind === "Type") {
        switch (a2.kind) {
          case "Scalar":
            const name2 = getPlausibleName(a2);
            return capitalize(name2);
          case "Model":
          case "Interface":
          case "Enum":
          case "Union":
            return getPlausibleName(a2);
        }
      }
      return "name" in a2 ? a2.name : "";
    }).join("_");
    name = `${namePrefix}${name}`;
  }
  return name;
}

// src/typespec/core/packages/compiler/dist/src/typekit/kits/type.js
defineKit({
  type: {
    is(entity) {
      return entity.entityKind === "Type";
    },
    finishType(type) {
      this.program.checker.finishType(type);
    },
    clone(type) {
      let clone;
      switch (type.kind) {
        case "Model":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            derivedModels: [...type.derivedModels],
            sourceModels: type.sourceModels.map((x2) => ({ ...x2 })),
            properties: copyMap(type.properties),
            indexer: type.indexer ? { ...type.indexer } : void 0
          });
          break;
        case "Union":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            variants: copyMap(type.variants),
            get options() {
              return Array.from(this.variants.values()).map((v2) => v2.type);
            }
          });
          break;
        case "Interface":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            operations: copyMap(type.operations)
          });
          break;
        case "Enum":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            members: copyMap(type.members)
          });
          break;
        case "Namespace":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            instantiationParameters: type.instantiationParameters ? [...type.instantiationParameters] : void 0,
            models: copyMap(type.models),
            decoratorDeclarations: copyMap(type.decoratorDeclarations),
            enums: copyMap(type.enums),
            unions: copyMap(type.unions),
            operations: copyMap(type.operations),
            interfaces: copyMap(type.interfaces),
            namespaces: copyMap(type.namespaces),
            scalars: copyMap(type.scalars)
          });
          break;
        case "Scalar":
          clone = this.program.checker.createType({
            ...type,
            decorators: [...type.decorators],
            derivedScalars: [...type.derivedScalars],
            constructors: copyMap(type.constructors)
          });
          break;
        case "Tuple":
          clone = this.program.checker.createType({
            ...type,
            values: [...type.values]
          });
          break;
        default:
          clone = this.program.checker.createType({
            ...type,
            ..."decorators" in type ? { decorators: [...type.decorators] } : {}
          });
          break;
      }
      this.realm.addType(clone);
      return clone;
    },
    isError(type) {
      return isErrorModel(this.program, type);
    },
    getEncodedName(type, encoding) {
      return resolveEncodedName(this.program, type, encoding);
    },
    getSummary(type) {
      return getSummary(this.program, type);
    },
    getDoc(type) {
      return getDoc(this.program, type);
    },
    getPlausibleName(type) {
      return getPlausibleName(type);
    },
    maxValue(type) {
      return getMaxValue(this.program, type);
    },
    minValue(type) {
      return getMinValue(this.program, type);
    },
    maxLength(type) {
      return getMaxLength(this.program, type);
    },
    minLength(type) {
      return getMinLength(this.program, type);
    },
    maxItems(type) {
      return getMaxItems(this.program, type);
    },
    maxValueExclusive(type) {
      return getMaxValueExclusive(this.program, type);
    },
    minValueExclusive(type) {
      return getMinValueExclusive(this.program, type);
    },
    minItems(type) {
      return getMinItems(this.program, type);
    },
    isNever(type) {
      return isNeverType(type);
    },
    isUserDefined(type) {
      return getLocationContext(this.program, type).type === "project";
    },
    inNamespace(type, namespace) {
      if (type === namespace) {
        return true;
      }
      switch (type.kind) {
        case "ModelProperty":
          if (type.model) {
            return this.type.inNamespace(type.model, namespace);
          }
          break;
        case "EnumMember":
          return this.type.inNamespace(type.enum, namespace);
        case "UnionVariant":
          return this.type.inNamespace(type.union, namespace);
        case "Operation":
          if (type.interface) {
            return this.type.inNamespace(type.interface, namespace);
          }
          break;
      }
      if ("namespace" in type && type.namespace) {
        return this.type.inNamespace(type.namespace, namespace);
      }
      return false;
    },
    isAssignableTo: createDiagnosable(function(source, target, diagnosticTarget) {
      return this.program.checker.isTypeAssignableTo(source, target, diagnosticTarget ?? source);
    }),
    resolve: createDiagnosable(function(reference, kind) {
      const [type, diagnostics] = this.program.resolveTypeReference(reference);
      if (type && kind && type.kind !== kind) {
        throw new Error(`Type kind mismatch: expected ${kind}, got ${type.kind}`);
      }
      return [type, diagnostics];
    })
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/union-variant.js
defineKit({
  unionVariant: {
    create(desc) {
      const variant = this.program.checker.createType({
        kind: "UnionVariant",
        name: desc.name ?? Symbol("name"),
        decorators: decoratorApplication(this, desc.decorators),
        type: desc.type,
        union: desc.union
      });
      this.program.checker.finishType(variant);
      return variant;
    },
    is(type) {
      return type.entityKind === "Type" && type.kind === "UnionVariant";
    }
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/union.js
var UnionKit = defineKit({
  union: {
    filter(union, filterFn) {
      const variants = Array.from(union.variants.values()).filter(filterFn);
      return this.union.create({ variants });
    },
    create(descOrChildren) {
      let descriptor;
      if (Array.isArray(descOrChildren)) {
        descriptor = {
          decorators: [],
          variants: descOrChildren.map((child) => {
            const memberDoc = getDoc(this.program, child);
            return this.unionVariant.create({
              type: child,
              decorators: memberDoc ? [[$doc, memberDoc]] : void 0
            });
          })
        };
      } else {
        descriptor = descOrChildren;
      }
      const union = this.program.checker.createType({
        kind: "Union",
        name: descriptor.name,
        decorators: decoratorApplication(this, descriptor.decorators),
        variants: createRekeyableMap(),
        get options() {
          return Array.from(this.variants.values()).map((v2) => v2.type);
        },
        expression: descriptor.name === void 0
      });
      if (Array.isArray(descriptor.variants)) {
        for (const variant of descriptor.variants) {
          union.variants.set(variant.name, variant);
          variant.union = union;
        }
      } else if (descriptor.variants) {
        for (const [name, value] of Object.entries(descriptor.variants)) {
          union.variants.set(name, this.unionVariant.create({ name, type: this.literal.create(value) }));
        }
      }
      this.program.checker.finishType(union);
      return union;
    },
    createFromEnum(type) {
      const enumDoc = getDoc(this.program, type);
      return this.union.create({
        name: type.name,
        decorators: enumDoc ? [[$doc, enumDoc]] : void 0,
        variants: Array.from(type.members.values()).map((member) => {
          const memberDoc = getDoc(this.program, member);
          const value = member.value ?? member.name;
          return this.unionVariant.create({
            name: member.name,
            type: this.literal.create(value),
            decorators: memberDoc ? [[$doc, memberDoc]] : void 0
          });
        })
      });
    },
    is(type) {
      return type.entityKind === "Type" && type.kind === "Union";
    },
    isValidEnum(type) {
      for (const variant of type.variants.values()) {
        if (!this.literal.isString(variant.type) && !this.literal.isNumeric(variant.type)) {
          return false;
        }
      }
      return true;
    },
    isExtensible(type) {
      const variants = Array.from(type.variants.values());
      if (variants.length === 0) {
        return false;
      }
      for (let i2 = 0; i2 < variants.length; i2++) {
        let isCommon = true;
        for (let j2 = 0; j2 < variants.length; j2++) {
          if (i2 === j2) {
            continue;
          }
          const assignable = ignoreDiagnostics(this.program.checker.isTypeAssignableTo(variants[j2].type, variants[i2].type, type));
          if (!assignable) {
            isCommon = false;
            break;
          }
        }
        if (isCommon) {
          return true;
        }
      }
      return false;
    },
    isExpression(type) {
      return type.name === void 0 || type.name === "";
    },
    getDiscriminatedUnion: createDiagnosable(function(type) {
      return getDiscriminatedUnion(this.program, type);
    })
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/kits/value.js
defineKit({
  value: {
    is(value) {
      return value.entityKind === "Value";
    },
    create(value) {
      if (typeof value === "string") {
        return this.value.createString(value);
      } else if (typeof value === "number") {
        return this.value.createNumeric(value);
      } else {
        return this.value.createBoolean(value);
      }
    },
    createString(value) {
      return {
        entityKind: "Value",
        value,
        valueKind: "StringValue",
        type: this.literal.createString(value),
        scalar: void 0
      };
    },
    createNumeric(value) {
      const valueAsString = String(value);
      return {
        entityKind: "Value",
        value: Numeric(valueAsString),
        valueKind: "NumericValue",
        type: this.literal.createNumeric(value),
        scalar: void 0
      };
    },
    createBoolean(value) {
      return {
        entityKind: "Value",
        value,
        valueKind: "BooleanValue",
        type: this.literal.createBoolean(value),
        scalar: void 0
      };
    },
    isBoolean(type) {
      return this.value.is(type) && type.valueKind === "BooleanValue";
    },
    isString(type) {
      return this.value.is(type) && type.valueKind === "StringValue";
    },
    isNumeric(type) {
      return this.value.is(type) && type.valueKind === "NumericValue";
    },
    isArray(type) {
      return this.value.is(type) && type.valueKind === "ArrayValue";
    },
    isObject(type) {
      return this.value.is(type) && type.valueKind === "ObjectValue";
    },
    isEnum(type) {
      return this.value.is(type) && type.valueKind === "EnumValue";
    },
    isNull(type) {
      return this.value.is(type) && type.valueKind === "NullValue";
    },
    isScalar(type) {
      return this.value.is(type) && type.valueKind === "ScalarValue";
    },
    isAssignableTo: createDiagnosable(function(source, target, diagnosticTarget) {
      return this.program.checker.isTypeAssignableTo(source, target, diagnosticTarget ?? source);
    }),
    resolve: createDiagnosable(function(reference, kind) {
      const [value, diagnostics] = this.program.resolveTypeOrValueReference(reference);
      if (value && !isValue(value)) {
        return [void 0, diagnostics];
      }
      if (value && kind && value.valueKind !== kind) {
        throw new Error(`Value kind mismatch: expected ${kind}, got ${value.valueKind}`);
      }
      return [value, diagnostics];
    })
  }
});

// src/typespec/core/packages/compiler/dist/src/typekit/index.js
var DEFAULT_REALM = Symbol.for("TypeSpec.Typekit.DEFAULT_TYPEKIT_REALM");
function _$(arg) {
  let realm;
  if (Object.hasOwn(arg, "projectRoot")) {
    realm = arg[DEFAULT_REALM] ??= new Realm(arg, "default typekit realm");
  } else {
    realm = arg;
  }
  return realm.typekit;
}
var $2 = _$;

export {
  Realm,
  getMinValueAsNumeric,
  getMinValue,
  getMaxValueAsNumeric,
  getMaxValue,
  getMinValueExclusiveAsNumeric,
  getMinValueExclusive,
  getMaxValueExclusiveAsNumeric,
  getMaxValueExclusive,
  getMinLengthAsNumeric,
  getMinLength,
  getMaxLengthAsNumeric,
  getMaxLength,
  getMinItemsAsNumeric,
  getMinItems,
  getMaxItemsAsNumeric,
  getMaxItems,
  getDocData,
  getDiscriminator,
  getDiscriminatedTypes,
  indexerDecorator,
  docFromCommentDecorator,
  getterDecorator,
  createDiagnosable,
  isErrorType,
  isVoidType,
  isNeverType,
  isUnknownType,
  isNullType,
  isType,
  isValue,
  isArrayModelType,
  isRecordModelType,
  isTemplateInstance,
  isDeclaredType,
  isTemplateDeclaration,
  isTemplateDeclarationOrInstance,
  isGlobalNamespace,
  isDeclaredInNamespace,
  getFullyQualifiedSymbolName,
  isTypeSpecValueTypeOf,
  typespecTypeToJson,
  validateDecoratorUniqueOnNode,
  validateDecoratorNotOnType,
  getPropertyType,
  isDeprecated,
  getDeprecationDetails,
  markDeprecated,
  getDiscriminatedUnion,
  getDiscriminatedUnionFromInheritance,
  getTypeName,
  getEntityName,
  isStdNamespace,
  getNamespaceFullName,
  getKey,
  isKey,
  $encodedName,
  resolveEncodedName,
  validateEncodedNamesConflicts,
  navigateProgram,
  navigateType,
  scopeNavigationToNamespace,
  navigateTypesInNamespace,
  mapEventEmitterToNodeListener,
  getProperty,
  EventEmitter,
  serializeValueAsJson,
  isList,
  listDecorator,
  offsetDecorator,
  pageIndexDecorator,
  pageSizeDecorator,
  pageItemsDecorator,
  continuationTokenDecorator,
  nextLinkDecorator,
  prevLinkDecorator,
  firstLinkDecorator,
  lastLinkDecorator,
  validatePagingOperations,
  getPagingOperation,
  getService,
  listServices,
  isService,
  addService,
  $service,
  isSealed,
  sealVisibilityModifiers,
  sealVisibilityModifiersForProgram,
  addVisibilityModifiers,
  removeVisibilityModifiers,
  clearVisibilityModifiersForClass,
  resetVisibilityModifiersForClass,
  getVisibilityForClass,
  hasVisibility,
  VisibilityFilter,
  isVisible,
  getLifecycleVisibilityEnum,
  getLocationContext,
  MutatorFlow,
  isMutableType,
  mutateSubgraphWithNamespace,
  mutateSubgraph,
  $withDefaultKeyVisibility,
  $parameterVisibility,
  EmptyVisibilityProvider,
  getParameterVisibilityFilter,
  $returnTypeVisibility,
  getReturnTypeVisibilityFilter,
  $visibility,
  $removeVisibility,
  $invisible,
  $defaultVisibility,
  $withVisibility,
  $withUpdateableProperties,
  $withVisibilityFilter,
  $withLifecycleUpdate,
  getSummary,
  $summary,
  $doc,
  getDoc,
  $returnsDoc,
  getReturnsDocData,
  getReturnsDoc,
  $errorsDoc,
  getErrorsDocData,
  getErrorsDoc,
  $inspectType,
  $inspectTypeName,
  isStringType,
  isNumericType,
  $error,
  isErrorModel,
  $mediaTypeHint,
  getMediaTypeHint,
  getFormat,
  $format,
  getPatternData,
  $pattern,
  getPattern,
  $minLength,
  $maxLength,
  $minItems,
  $maxItems,
  $minValue,
  $maxValue,
  $minValueExclusive,
  $maxValueExclusive,
  isSecret,
  $secret,
  getEncode,
  $encode,
  $withOptionalProperties,
  $withoutOmittedProperties,
  $withPickedProperties,
  $withoutDefaultValues,
  $tag,
  getTags,
  getAllTags,
  getFriendlyName,
  $friendlyName,
  $key,
  getDeprecated,
  getOverloads,
  getOverloadedOperation,
  $overload,
  discriminatedDecorator,
  $discriminator,
  $example,
  getExamples,
  $opExample,
  getOpExamples,
  UnionKit,
  isNumeric,
  Numeric,
  $2 as $,
  createSymbolTable,
  createBinder,
  createSymbol,
  getSymNode,
  explainStringTemplateNotSerializable,
  createChecker,
  getEffectiveModelType,
  filterModelProperties,
  walkPropertiesInherited
};
