var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
import { b as getAugmentedNamespace, g as getDefaultExportFromCjs, c as commonjsGlobal, d as createSchemaPredicate, z, i as isExecuteActionObject, e as isSubmitActionObject, f as optionsSchema, L as Logger, C as Cache, E as Emitter, N as Network, h as getConfigResponseSchema, j as configSchema, u as unionType, o as objectType, s as stringType, k as jwtDecode, l as getUserResponseSchema, m as userSchema, n as getUserAvatarResponseSchema, p as setTimezoneInputSchema, q as setTimezoneResponseSchema, t as getSpacesResponseSchema, v as getViewInputSchema, w as getViewResponseSchema, x as askInputSchema, y as askResponseSchema, A as isNotification, B as getNotificationsInputSchema, D as getNotificationsResponseSchema, F as getNotificationInputSchema, G as getNotificationResponseSchema, H as actionNotificationInputSchema, I as actionNotificationResponseSchema, J as deleteNotificationInputSchema, K as deleteNotificationResponseSchema, M as viewNotificationInputSchema, O as viewNotificationResponseSchema } from "./index-DfKyER7q.js";
import { v as _copyObject, w as keysIn_1, x as _getPrototype, y as _cloneArrayBuffer, c as _Symbol, z as _cloneTypedArray, h as isObjectLike_1, r as _baseUnary, A as _nodeUtilExports, d as _Stack, B as _cloneBufferExports, C as _copyArray, D as _initCloneObject, i as isBufferExports, j as isObject_1, g as isArray_1, E as _assignValue, u as merge } from "./merge-CTGDJLlb.js";
import { k as keys_1, c as _getSymbols, b as _arrayPush, s as stubArray_1, d as _baseGetAllKeys, a as _getTag, _ as _getAllKeys } from "./_getTag-BY4WvAdg.js";
var lib = { exports: {} };
function e(e2) {
  this.message = e2;
}
e.prototype = new Error(), e.prototype.name = "InvalidCharacterError";
var r = "undefined" != typeof window && window.atob && window.atob.bind(window) || function(r2) {
  var t2 = String(r2).replace(/=+$/, "");
  if (t2.length % 4 == 1)
    throw new e("'atob' failed: The string to be decoded is not correctly encoded.");
  for (var n2, o2, a = 0, i = 0, c = ""; o2 = t2.charAt(i++); ~o2 && (n2 = a % 4 ? 64 * n2 + o2 : o2, a++ % 4) ? c += String.fromCharCode(255 & n2 >> (-2 * a & 6)) : 0)
    o2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o2);
  return c;
};
function t(e2) {
  var t2 = e2.replace(/-/g, "+").replace(/_/g, "/");
  switch (t2.length % 4) {
    case 0:
      break;
    case 2:
      t2 += "==";
      break;
    case 3:
      t2 += "=";
      break;
    default:
      throw "Illegal base64url string!";
  }
  try {
    return function(e3) {
      return decodeURIComponent(r(e3).replace(/(.)/g, function(e4, r2) {
        var t3 = r2.charCodeAt(0).toString(16).toUpperCase();
        return t3.length < 2 && (t3 = "0" + t3), "%" + t3;
      }));
    }(t2);
  } catch (e3) {
    return r(t2);
  }
}
function n(e2) {
  this.message = e2;
}
function o(e2, r2) {
  if ("string" != typeof e2)
    throw new n("Invalid token specified");
  var o2 = true === (r2 = r2 || {}).header ? 0 : 1;
  try {
    return JSON.parse(t(e2.split(".")[o2]));
  } catch (e3) {
    throw new n("Invalid token specified: " + e3.message);
  }
}
n.prototype = new Error(), n.prototype.name = "InvalidTokenError";
const jwtDecode_esm = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  InvalidTokenError: n,
  default: o
}, Symbol.toStringTag, { value: "Module" }));
const require$$0 = /* @__PURE__ */ getAugmentedNamespace(jwtDecode_esm);
(function(module, exports) {
  var __importDefault = commonjsGlobal && commonjsGlobal.__importDefault || function(mod) {
    return mod && mod.__esModule ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  const jwt_decode_1 = __importDefault(require$$0);
  function jwtCache2({ getToken, eagerRefreshMilliseconds = 0, minimumValidityMilliseconds = 1e3 }) {
    let disposed = false;
    let statePromise;
    let nextState;
    let timeout;
    const getState = async () => {
      const token = await getToken();
      const decoded = jwt_decode_1.default(token);
      if (typeof decoded === "object" && decoded !== null && typeof decoded.exp === "number") {
        const expiry = decoded.exp * 1e3;
        return { token, expiry };
      } else {
        throw new Error(`You can only cache a JWT if it has an "exp" that is an integer number of seconds`);
      }
    };
    const handleEagerRefresh = (state, currentStatePromise) => {
      if (disposed)
        return;
      if (eagerRefreshMilliseconds) {
        timeout = setTimeout(() => {
          if (statePromise === currentStatePromise) {
            const thisNextState = nextState = getState();
            thisNextState.then((state2) => {
              if (nextState === thisNextState && statePromise === currentStatePromise) {
                statePromise = thisNextState;
                handleEagerRefresh(state2, thisNextState);
              }
            }, (_ex) => {
              if (nextState === thisNextState && statePromise === currentStatePromise) {
                nextState = void 0;
              }
            });
          }
        }, state.expiry - Date.now() - minimumValidityMilliseconds - eagerRefreshMilliseconds);
      }
    };
    const getUpdatedToken = async (currentStatePromise) => {
      if (statePromise && currentStatePromise !== statePromise) {
        return (await statePromise).token;
      }
      statePromise = nextState !== null && nextState !== void 0 ? nextState : getState();
      nextState = void 0;
      try {
        const state = await statePromise;
        handleEagerRefresh(state, statePromise);
        return state.token;
      } catch (ex) {
        statePromise = void 0;
        throw ex;
      }
    };
    if (eagerRefreshMilliseconds) {
      getUpdatedToken(void 0).catch(() => {
      });
    }
    return {
      dispose: () => {
        disposed = true;
        if (timeout) {
          clearTimeout(timeout);
        }
      },
      getToken: async () => {
        if (disposed) {
          throw new Error(`Cannot get token after disposing jwt-cache`);
        }
        const stateP = statePromise;
        if (!stateP) {
          return await getUpdatedToken(stateP);
        }
        const state = await stateP;
        if (state.expiry - Date.now() >= minimumValidityMilliseconds) {
          return state.token;
        }
        return await getUpdatedToken(stateP);
      }
    };
  }
  exports.default = jwtCache2;
  module.exports = Object.assign(jwtCache2, { default: jwtCache2 });
})(lib, lib.exports);
var libExports = lib.exports;
const jwtCache = /* @__PURE__ */ getDefaultExportFromCjs(libExports);
const copyProperty = (to, from, property, ignoreNonConfigurable) => {
  if (property === "length" || property === "prototype") {
    return;
  }
  if (property === "arguments" || property === "caller") {
    return;
  }
  const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
  const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
  if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
    return;
  }
  Object.defineProperty(to, property, fromDescriptor);
};
const canCopyProperty = function(toDescriptor, fromDescriptor) {
  return toDescriptor === void 0 || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
};
const changePrototype = (to, from) => {
  const fromPrototype = Object.getPrototypeOf(from);
  if (fromPrototype === Object.getPrototypeOf(to)) {
    return;
  }
  Object.setPrototypeOf(to, fromPrototype);
};
const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/
${fromBody}`;
const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, "toString");
const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, "name");
const changeToString = (to, from, name2) => {
  const withName = name2 === "" ? "" : `with ${name2.trim()}() `;
  const newToString = wrappedToString.bind(null, withName, from.toString());
  Object.defineProperty(newToString, "name", toStringName);
  Object.defineProperty(to, "toString", { ...toStringDescriptor, value: newToString });
};
function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
  const { name: name2 } = to;
  for (const property of Reflect.ownKeys(from)) {
    copyProperty(to, from, property, ignoreNonConfigurable);
  }
  changePrototype(to, from);
  changeToString(to, from, name2);
  return to;
}
const cacheStore = /* @__PURE__ */ new WeakMap();
function pMemoize(fn, { cacheKey = ([firstArgument]) => firstArgument, cache = /* @__PURE__ */ new Map() } = {}) {
  const promiseCache = /* @__PURE__ */ new Map();
  const memoized = function(...arguments_) {
    const key = cacheKey(arguments_);
    if (promiseCache.has(key)) {
      return promiseCache.get(key);
    }
    const promise = (async () => {
      try {
        if (cache && await cache.has(key)) {
          return await cache.get(key);
        }
        const promise2 = fn.apply(this, arguments_);
        const result = await promise2;
        try {
          return result;
        } finally {
          if (cache) {
            await cache.set(key, result);
          }
        }
      } finally {
        promiseCache.delete(key);
      }
    })();
    promiseCache.set(key, promise);
    return promise;
  };
  mimicFunction(memoized, fn, {
    ignoreNonConfigurable: true
  });
  cacheStore.set(memoized, cache);
  return memoized;
}
function arrayEach$1(array, iteratee) {
  var index = -1, length = array == null ? 0 : array.length;
  while (++index < length) {
    if (iteratee(array[index], index, array) === false) {
      break;
    }
  }
  return array;
}
var _arrayEach = arrayEach$1;
var copyObject$3 = _copyObject, keys$1 = keys_1;
function baseAssign$1(object, source) {
  return object && copyObject$3(source, keys$1(source), object);
}
var _baseAssign = baseAssign$1;
var copyObject$2 = _copyObject, keysIn$2 = keysIn_1;
function baseAssignIn$1(object, source) {
  return object && copyObject$2(source, keysIn$2(source), object);
}
var _baseAssignIn = baseAssignIn$1;
var copyObject$1 = _copyObject, getSymbols$1 = _getSymbols;
function copySymbols$1(source, object) {
  return copyObject$1(source, getSymbols$1(source), object);
}
var _copySymbols = copySymbols$1;
var arrayPush = _arrayPush, getPrototype = _getPrototype, getSymbols = _getSymbols, stubArray = stubArray_1;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbolsIn$2 = !nativeGetSymbols ? stubArray : function(object) {
  var result = [];
  while (object) {
    arrayPush(result, getSymbols(object));
    object = getPrototype(object);
  }
  return result;
};
var _getSymbolsIn = getSymbolsIn$2;
var copyObject = _copyObject, getSymbolsIn$1 = _getSymbolsIn;
function copySymbolsIn$1(source, object) {
  return copyObject(source, getSymbolsIn$1(source), object);
}
var _copySymbolsIn = copySymbolsIn$1;
var baseGetAllKeys = _baseGetAllKeys, getSymbolsIn = _getSymbolsIn, keysIn$1 = keysIn_1;
function getAllKeysIn$1(object) {
  return baseGetAllKeys(object, keysIn$1, getSymbolsIn);
}
var _getAllKeysIn = getAllKeysIn$1;
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
function initCloneArray$1(array) {
  var length = array.length, result = new array.constructor(length);
  if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) {
    result.index = array.index;
    result.input = array.input;
  }
  return result;
}
var _initCloneArray = initCloneArray$1;
var cloneArrayBuffer$1 = _cloneArrayBuffer;
function cloneDataView$1(dataView, isDeep) {
  var buffer = isDeep ? cloneArrayBuffer$1(dataView.buffer) : dataView.buffer;
  return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var _cloneDataView = cloneDataView$1;
var reFlags = /\w*$/;
function cloneRegExp$1(regexp) {
  var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  result.lastIndex = regexp.lastIndex;
  return result;
}
var _cloneRegExp = cloneRegExp$1;
var Symbol$1 = _Symbol;
var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol$1(symbol) {
  return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var _cloneSymbol = cloneSymbol$1;
var cloneArrayBuffer = _cloneArrayBuffer, cloneDataView = _cloneDataView, cloneRegExp = _cloneRegExp, cloneSymbol = _cloneSymbol, cloneTypedArray = _cloneTypedArray;
var boolTag$1 = "[object Boolean]", dateTag$1 = "[object Date]", mapTag$2 = "[object Map]", numberTag$1 = "[object Number]", regexpTag$1 = "[object RegExp]", setTag$2 = "[object Set]", stringTag$1 = "[object String]", symbolTag$1 = "[object Symbol]";
var arrayBufferTag$1 = "[object ArrayBuffer]", dataViewTag$1 = "[object DataView]", float32Tag$1 = "[object Float32Array]", float64Tag$1 = "[object Float64Array]", int8Tag$1 = "[object Int8Array]", int16Tag$1 = "[object Int16Array]", int32Tag$1 = "[object Int32Array]", uint8Tag$1 = "[object Uint8Array]", uint8ClampedTag$1 = "[object Uint8ClampedArray]", uint16Tag$1 = "[object Uint16Array]", uint32Tag$1 = "[object Uint32Array]";
function initCloneByTag$1(object, tag, isDeep) {
  var Ctor = object.constructor;
  switch (tag) {
    case arrayBufferTag$1:
      return cloneArrayBuffer(object);
    case boolTag$1:
    case dateTag$1:
      return new Ctor(+object);
    case dataViewTag$1:
      return cloneDataView(object, isDeep);
    case float32Tag$1:
    case float64Tag$1:
    case int8Tag$1:
    case int16Tag$1:
    case int32Tag$1:
    case uint8Tag$1:
    case uint8ClampedTag$1:
    case uint16Tag$1:
    case uint32Tag$1:
      return cloneTypedArray(object, isDeep);
    case mapTag$2:
      return new Ctor();
    case numberTag$1:
    case stringTag$1:
      return new Ctor(object);
    case regexpTag$1:
      return cloneRegExp(object);
    case setTag$2:
      return new Ctor();
    case symbolTag$1:
      return cloneSymbol(object);
  }
}
var _initCloneByTag = initCloneByTag$1;
var getTag$2 = _getTag, isObjectLike$1 = isObjectLike_1;
var mapTag$1 = "[object Map]";
function baseIsMap$1(value) {
  return isObjectLike$1(value) && getTag$2(value) == mapTag$1;
}
var _baseIsMap = baseIsMap$1;
var baseIsMap = _baseIsMap, baseUnary$1 = _baseUnary, nodeUtil$1 = _nodeUtilExports;
var nodeIsMap = nodeUtil$1 && nodeUtil$1.isMap;
var isMap$1 = nodeIsMap ? baseUnary$1(nodeIsMap) : baseIsMap;
var isMap_1 = isMap$1;
var getTag$1 = _getTag, isObjectLike = isObjectLike_1;
var setTag$1 = "[object Set]";
function baseIsSet$1(value) {
  return isObjectLike(value) && getTag$1(value) == setTag$1;
}
var _baseIsSet = baseIsSet$1;
var baseIsSet = _baseIsSet, baseUnary = _baseUnary, nodeUtil = _nodeUtilExports;
var nodeIsSet = nodeUtil && nodeUtil.isSet;
var isSet$1 = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
var isSet_1 = isSet$1;
var Stack = _Stack, arrayEach = _arrayEach, assignValue = _assignValue, baseAssign = _baseAssign, baseAssignIn = _baseAssignIn, cloneBuffer = _cloneBufferExports, copyArray = _copyArray, copySymbols = _copySymbols, copySymbolsIn = _copySymbolsIn, getAllKeys = _getAllKeys, getAllKeysIn = _getAllKeysIn, getTag = _getTag, initCloneArray = _initCloneArray, initCloneByTag = _initCloneByTag, initCloneObject = _initCloneObject, isArray = isArray_1, isBuffer = isBufferExports, isMap = isMap_1, isObject = isObject_1, isSet = isSet_1, keys = keys_1, keysIn = keysIn_1;
var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG$1 = 4;
var argsTag = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
function baseClone$1(value, bitmask, customizer, key, object, stack) {
  var result, isDeep = bitmask & CLONE_DEEP_FLAG$1, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
  if (customizer) {
    result = object ? customizer(value, key, object, stack) : customizer(value);
  }
  if (result !== void 0) {
    return result;
  }
  if (!isObject(value)) {
    return value;
  }
  var isArr = isArray(value);
  if (isArr) {
    result = initCloneArray(value);
    if (!isDeep) {
      return copyArray(value, result);
    }
  } else {
    var tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
    if (isBuffer(value)) {
      return cloneBuffer(value, isDeep);
    }
    if (tag == objectTag || tag == argsTag || isFunc && !object) {
      result = isFlat || isFunc ? {} : initCloneObject(value);
      if (!isDeep) {
        return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value));
      }
    } else {
      if (!cloneableTags[tag]) {
        return object ? value : {};
      }
      result = initCloneByTag(value, tag, isDeep);
    }
  }
  stack || (stack = new Stack());
  var stacked = stack.get(value);
  if (stacked) {
    return stacked;
  }
  stack.set(value, result);
  if (isSet(value)) {
    value.forEach(function(subValue) {
      result.add(baseClone$1(subValue, bitmask, customizer, subValue, value, stack));
    });
  } else if (isMap(value)) {
    value.forEach(function(subValue, key2) {
      result.set(key2, baseClone$1(subValue, bitmask, customizer, key2, value, stack));
    });
  }
  var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
  var props = isArr ? void 0 : keysFunc(value);
  arrayEach(props || value, function(subValue, key2) {
    if (props) {
      key2 = subValue;
      subValue = value[key2];
    }
    assignValue(result, key2, baseClone$1(subValue, bitmask, customizer, key2, value, stack));
  });
  return result;
}
var _baseClone = baseClone$1;
var baseClone = _baseClone;
var CLONE_DEEP_FLAG = 1, CLONE_SYMBOLS_FLAG = 4;
function cloneDeep(value) {
  return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
var cloneDeep_1 = cloneDeep;
const cloneDeep$1 = /* @__PURE__ */ getDefaultExportFromCjs(cloneDeep_1);
const isRecordLike = createSchemaPredicate(
  z.custom((data) => {
    return typeof data === "object" && data != null;
  })
);
class RecursiveIterator {
  constructor(root) {
    __publicField(this, "queue");
    __publicField(this, "state");
    this.queue = this.getDescriptors(root);
    this.state = this.queue[0];
  }
  getDescriptors(parent, path = []) {
    if (!isRecordLike(parent))
      return [];
    return Object.entries(parent).map(([key, value]) => ({
      key,
      value,
      parent,
      path: [...path, key]
    }));
  }
  next() {
    if (this.state) {
      const { value, path } = this.state;
      this.queue.push(...this.getDescriptors(value, path));
    }
    this.state = this.queue.shift();
    return this.state ? {
      done: false,
      value: this.state
    } : {
      done: true,
      value: this.state
    };
  }
  [Symbol.iterator]() {
    return this;
  }
}
function injectActionData(view, data) {
  view = cloneDeep$1(view);
  for (const { value } of new RecursiveIterator(view)) {
    if (isExecuteActionObject(value) || isSubmitActionObject(value)) {
      merge(value, { data: { __internal__: data } });
    }
  }
  return view;
}
const name = "@workgrid-widgets/core";
const version = "1.6.1";
async function swr(cache, key, schema, fetch) {
  let value;
  try {
    value = await cache.get(key);
    await cache.remove(key);
  } catch {
  }
  const promise = (async () => {
    const value2 = await fetch();
    await cache.set(key, value2);
    return value2;
  })();
  if (value) {
    try {
      return schema.parse(value);
    } catch {
    }
  }
  value = await promise;
  return schema.parse(value);
}
class Core {
  constructor(options) {
    __publicField(this, "client", `${name}/${version}`);
    __publicField(this, "options");
    __publicField(this, "cache");
    __publicField(this, "emitter");
    __publicField(this, "logger");
    __publicField(this, "network");
    __publicField(this, "createLogger");
    __publicField(this, "on");
    __publicField(this, "off");
    __publicField(this, "emit");
    this.options = optionsSchema.parse(options);
    const logger = this.options.logger ?? new Logger({ core: this, ...this.options.loggerOptions });
    this.logger = logger.create({ prefix: "core" });
    this.createLogger = this.logger.create.bind(this.logger);
    this.cache = this.options.cache ?? new Cache({ core: this, ...this.options.cacheOptions });
    this.emitter = this.options.emitter ?? new Emitter({ core: this, ...this.options.emitterOptions });
    this.network = this.options.network ?? new Network({ core: this, ...this.options.networkOptions });
    this.on = this.emitter.on.bind(this.emitter);
    this.off = this.emitter.off.bind(this.emitter);
    this.emit = this.emitter.emit.bind(this.emitter);
    this.getToken = jwtCache({ getToken: this.logger.wrapFn(this.getToken.bind(this)) }).getToken;
    this.getApiHost = pMemoize(this.logger.wrapFn(this.getApiHost.bind(this)));
    this.getConfig = pMemoize(this.logger.wrapFn(this.getConfig.bind(this)));
    this.getUser = pMemoize(this.logger.wrapFn(this.getUser.bind(this)));
  }
  /**
   * Resolve a user token
   */
  async getToken() {
    let token = await this.options.getToken(this);
    if (token instanceof Response) {
      token = await token.text();
    }
    return token;
  }
  /**
   * Resolve the api host
   */
  async getApiHost() {
    return this.options.getApiHost(this);
  }
  /**
   * Fetch the client config
   */
  async getConfig() {
    const key = await this.options.getKey(this);
    const cacheKey = `config/${key ?? "DEFAULT"}`;
    return swr(this.cache, cacheKey, configSchema, async () => {
      const token = await this.getToken();
      const response = await this.network.get("v1/admin/client-config", {
        headers: {
          Authorization: `Bearer ${token}`
        },
        searchParams: {
          key: key ?? ""
        }
      });
      const config = getConfigResponseSchema.parse(await response.json());
      return config;
    });
  }
  /**
   * Fetch the current user
   */
  async getUser() {
    const token = await this.getToken();
    const subject = unionType([
      objectType({ sub: stringType() }).transform((token2) => token2.sub),
      objectType({ email: stringType() }).transform((token2) => token2.email)
    ]).parse(jwtDecode(token));
    const cacheKey = `user/${subject}`;
    return swr(this.cache, cacheKey, userSchema, async () => {
      const token2 = await this.getToken();
      const response = await this.network.get("v1/admin/user", {
        headers: {
          Authorization: `Bearer ${token2}`
        }
      });
      const user = getUserResponseSchema.parse(await response.json());
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      if (user.timezone !== timezone)
        void this.setTimezone({ timezone });
      user.timezone = timezone;
      return user;
    });
  }
  /**
   * Fetch the current user avatar
   */
  async getUserAvatar() {
    const token = await this.getToken();
    const response = await this.network.get("v1/admin/user/avatar", {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    return getUserAvatarResponseSchema.parse(await response.json());
  }
  /**
   * Update the user timezone
   */
  async setTimezone(options) {
    const resolvedOptions = setTimezoneInputSchema.parse(options);
    const token = await this.getToken();
    const response = await this.network.post("v1/graphql", {
      headers: {
        Authorization: `Bearer ${token}`
      },
      json: {
        query: (
          /* graphql */
          `
          mutation ($authContext: AuthContext!, $input: UpdateTimezoneInput!) {
            currentUser: updateTimezone(authContext: $authContext, input: $input) {
              timezone
            }
          }
        `
        ),
        variables: {
          authContext: { spaceId: "auto", tenantId: "auto", userId: "auto" },
          input: { timezone: resolvedOptions.timezone }
        }
      }
    });
    return setTimezoneResponseSchema.parse(await response.json());
  }
  /**
   * Fetch spaces
   */
  async getSpaces() {
    const token = await this.getToken();
    const response = await this.network.get(`v1/userspaces`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    return getSpacesResponseSchema.parse(await response.json());
  }
  /**
   * Fetch a microapp view
   */
  async getView(options) {
    const resolvedOptions = getViewInputSchema.parse(options);
    const token = await this.getToken();
    const response = await this.network.post(`v1/appbuilder/userapps/${resolvedOptions.endpoint}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId
      },
      json: { data: resolvedOptions.data }
    });
    let view = getViewResponseSchema.parse(await response.json());
    view = injectActionData(view, {
      spaceId: resolvedOptions.spaceId
    });
    return view;
  }
  /**
   * Prompt the ask api
   */
  async ask(options) {
    const resolvedOptions = askInputSchema.parse(options);
    const token = await this.getToken();
    const response = await this.network.post("v3/ask", {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId
      },
      json: {
        locale: "en_US",
        channel: "unified",
        utterance: resolvedOptions.message,
        ...resolvedOptions.id ? { id: resolvedOptions.id } : {},
        ...resolvedOptions.data
      }
    });
    const data = askResponseSchema.parse(await response.json());
    return {
      ...data,
      items: data.items.map((item) => {
        if ("view" in item) {
          const actionData = {
            spaceId: resolvedOptions.spaceId
          };
          if (isNotification(item)) {
            actionData.notificationId = item.metadata.id;
          }
          return {
            ...item,
            view: injectActionData(item.view, actionData)
          };
        }
        return item;
      })
    };
  }
  /**
   * Fetch notifications
   */
  async getNotifications(options) {
    const resolvedOptions = getNotificationsInputSchema.parse(options);
    const token = await this.getToken();
    let endpoint = `v1/usernotifications`;
    if (resolvedOptions.location === "todo")
      endpoint = "v1/todo";
    if (resolvedOptions.location === "toknow")
      endpoint = "v1/toknow";
    const searchParameters = {
      orderBy: "date",
      includeMicroapps: true
    };
    if (resolvedOptions.cursor)
      searchParameters.cursor = resolvedOptions.cursor;
    if (resolvedOptions.limit)
      searchParameters.limit = String(resolvedOptions.limit);
    if (resolvedOptions.since)
      searchParameters.since = resolvedOptions.since;
    if (resolvedOptions.until)
      searchParameters.until = resolvedOptions.until;
    const response = await this.network.get(endpoint, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId,
        Accept: 'application/vnd.microsoft.card.adaptive;features="delete"'
      },
      searchParams: searchParameters
    });
    let data = getNotificationsResponseSchema.parse(await response.json());
    data = {
      ...data,
      notifications: data.notifications.map((notification) => ({
        ...notification,
        view: injectActionData(notification.view, {
          spaceId: resolvedOptions.spaceId,
          notificationId: notification.metadata.id
        })
      })),
      showMoreNotifications: data.showMoreNotifications ? injectActionData(data.showMoreNotifications, {
        spaceId: resolvedOptions.spaceId
      }) : void 0
    };
    return data;
  }
  /**
   * Fetch single notification
   */
  async getNotification(options) {
    const resolvedOptions = getNotificationInputSchema.parse(options);
    const token = await this.getToken();
    const response = await this.network.get(`v1/usernotifications/${resolvedOptions.notificationId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId,
        Accept: 'application/vnd.microsoft.card.adaptive;features="delete"'
      }
    });
    const data = getNotificationResponseSchema.parse(await response.json());
    const view = injectActionData(data.view, {
      spaceId: resolvedOptions.spaceId,
      notificationId: data.metadata.id
    });
    return view;
  }
  /**
   * Action a notification
   */
  async actionNotification(options) {
    const resolvedOptions = actionNotificationInputSchema.parse(options);
    const token = await this.getToken();
    const { data, analytics, ...rest } = resolvedOptions.data;
    const response = await this.network.post(`v1/usernotifications/${resolvedOptions.notificationId}/action`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId,
        Accept: 'application/vnd.microsoft.card.adaptive;features="delete"'
      },
      json: {
        data: { ...rest, ...data },
        analytics
      }
    });
    return actionNotificationResponseSchema.parse(await response.json());
  }
  /**
   * Delete a notification
   */
  async deleteNotification(options) {
    const resolvedOptions = deleteNotificationInputSchema.parse(options);
    const token = await this.getToken();
    const response = await this.network.delete(`v1/usernotifications/${resolvedOptions.notificationId}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId,
        Accept: 'application/vnd.microsoft.card.adaptive;features="delete"'
      }
    });
    return deleteNotificationResponseSchema.parse(await response.json());
  }
  /**
   * Track notification views
   */
  async viewNotification(options) {
    const resolvedOptions = viewNotificationInputSchema.parse(options);
    const token = await this.getToken();
    const type = { summary: "view", detail: "view-detail" }[resolvedOptions.location];
    const response = await this.network.put(`v1/usernotifications/${resolvedOptions.notificationId}/${type}`, {
      headers: {
        Authorization: `Bearer ${token}`,
        "x-workgrid-space": resolvedOptions.spaceId
      }
    });
    return viewNotificationResponseSchema.parse(await response.json());
  }
}
export {
  actionNotificationInputSchema,
  actionNotificationResponseSchema,
  askInputSchema,
  askResponseSchema,
  configSchema,
  Core as default,
  deleteNotificationInputSchema,
  deleteNotificationResponseSchema,
  getConfigResponseSchema,
  getNotificationInputSchema,
  getNotificationResponseSchema,
  getNotificationsInputSchema,
  getNotificationsResponseSchema,
  getSpacesResponseSchema,
  getUserAvatarResponseSchema,
  getUserResponseSchema,
  getViewInputSchema,
  getViewResponseSchema,
  optionsSchema,
  setTimezoneInputSchema,
  setTimezoneResponseSchema,
  userSchema,
  viewNotificationInputSchema,
  viewNotificationResponseSchema
};
//# sourceMappingURL=index-CSNTLUKh.js.map
