import {
  fetch
} from "./chunk-KLJ2TVHE.js";
import {
  cacheRetrieve,
  cacheRetrieveOrRepopulate,
  cacheStore,
  versionSatisfies
} from "./chunk-HJBER2P6.js";
import {
  CLI_KIT_VERSION
} from "./chunk-DD26C7GE.js";
import {
  z
} from "./chunk-NLUGD7PZ.js";
import {
  AbortSilentError,
  outputDebug,
  renderError,
  renderInfo,
  renderWarning
} from "./chunk-LA4HX5WI.js";
import {
  init_cjs_shims
} from "./chunk-POZ5MGPT.js";

// ../cli-kit/dist/public/node/notifications-system.js
init_cjs_shims();

// ../cli-kit/dist/public/node/global-context.js
init_cjs_shims();
var _globalContext;
function getGlobalContext() {
  return _globalContext || (_globalContext = { currentCommandId: "" }), _globalContext;
}
function getCurrentCommandId() {
  return getGlobalContext().currentCommandId;
}
function setCurrentCommandId(commandId) {
  getGlobalContext().currentCommandId = commandId;
}

// ../cli-kit/dist/public/node/notifications-system.js
var URL = "https://cdn.shopify.com/static/cli/notifications.json", CACHE_DURATION_IN_MS = 3600 * 1e3;
function url() {
  return process.env.SHOPIFY_CLI_NOTIFICATIONS_URL ?? URL;
}
var NotificationSchema = z.object({
  id: z.string(),
  message: z.string(),
  type: z.enum(["info", "warning", "error"]),
  frequency: z.enum(["always", "once", "once_a_day", "once_a_week"]),
  ownerChannel: z.string(),
  cta: z.object({
    label: z.string(),
    url: z.string().url()
  }).optional(),
  title: z.string().optional(),
  minVersion: z.string().optional(),
  maxVersion: z.string().optional(),
  minDate: z.string().optional(),
  maxDate: z.string().optional(),
  commands: z.array(z.string()).optional(),
  surface: z.string().optional()
}), NotificationsSchema = z.object({ notifications: z.array(NotificationSchema) });
async function showNotificationsIfNeeded(currentSurfaces) {
  try {
    let notifications = await getNotifications(), commandId = getCurrentCommandId(), notificationsToShow = filterNotifications(notifications.notifications, commandId, currentSurfaces);
    outputDebug(`Notifications to show: ${notificationsToShow.length}`), await renderNotifications(notificationsToShow);
  } catch (error) {
    if (error.message === "abort")
      throw new AbortSilentError();
    let errorMessage = `Error retrieving notifications: ${error.message}`;
    outputDebug(errorMessage);
    let { sendErrorToBugsnag } = await import("./error-handler-5SBVAGLO.js");
    await sendErrorToBugsnag(errorMessage, "unexpected_error");
  }
}
async function renderNotifications(notifications) {
  notifications.slice(0, 2).forEach((notification) => {
    let content = {
      headline: notification.title,
      body: notification.message.replaceAll("\\n", `
`),
      link: notification.cta
    };
    switch (notification.type) {
      case "info": {
        renderInfo(content);
        break;
      }
      case "warning": {
        renderWarning(content);
        break;
      }
      case "error":
        throw renderError(content), new Error("abort");
    }
    cacheStore(`notification-${notification.id}`, (/* @__PURE__ */ new Date()).getTime().toString());
  });
}
async function getNotifications() {
  let cacheKey = `notifications-${url()}`, rawNotifications = await cacheRetrieveOrRepopulate(cacheKey, fetchNotifications, CACHE_DURATION_IN_MS), notifications = JSON.parse(rawNotifications);
  return NotificationsSchema.parse(notifications);
}
async function fetchNotifications() {
  outputDebug("No cached notifications found. Fetching them...");
  let response = await fetch(url(), { signal: AbortSignal.timeout(3 * 1e3) });
  if (response.status !== 200)
    throw new Error(`Failed to fetch notifications: ${response.statusText}`);
  return response.text();
}
function filterNotifications(notifications, commandId, currentSurfaces, today = new Date((/* @__PURE__ */ new Date()).setUTCHours(0, 0, 0, 0)), currentVersion = CLI_KIT_VERSION) {
  return notifications.filter((notification) => filterByVersion(notification, currentVersion)).filter((notifications2) => filterByDate(notifications2, today)).filter((notification) => filterByCommand(notification, commandId)).filter((notification) => filterBySurface(notification, commandId, currentSurfaces)).filter((notification) => filterByFrequency(notification));
}
function filterByVersion(notification, currentVersion) {
  let minVersion = !notification.minVersion || versionSatisfies(currentVersion, `>=${notification.minVersion}`), maxVersion = !notification.maxVersion || versionSatisfies(currentVersion, `<=${notification.maxVersion}`);
  return minVersion && maxVersion;
}
function filterByDate(notification, today) {
  let minDate = !notification.minDate || new Date(notification.minDate) <= today, maxDate = !notification.maxDate || new Date(notification.maxDate) >= today;
  return minDate && maxDate;
}
function filterByCommand(notification, commandId) {
  return commandId === "" ? !0 : !notification.commands || notification.commands.includes(commandId);
}
function filterBySurface(notification, commandId, surfacesFromContext) {
  let surfaceFromCommand = commandId.split(":")[0] ?? "all", notificationSurface = notification.surface ?? "all";
  return surfacesFromContext ? surfacesFromContext.includes(notificationSurface) : notificationSurface === surfaceFromCommand || notificationSurface === "all";
}
function filterByFrequency(notification) {
  if (!notification.frequency)
    return !0;
  let cacheKey = `notification-${notification.id}`, lastShown = cacheRetrieve(cacheKey)?.value;
  if (!lastShown)
    return !0;
  switch (notification.frequency) {
    case "always":
      return !0;
    case "once":
      return !1;
    case "once_a_day":
      return (/* @__PURE__ */ new Date()).getTime() - Number(lastShown) > 24 * 3600 * 1e3;
    case "once_a_week":
      return (/* @__PURE__ */ new Date()).getTime() - Number(lastShown) > 7 * 24 * 3600 * 1e3;
  }
}
function stringifyFilters(notification) {
  let filters = [];
  return notification.minDate && filters.push(`from ${notification.minDate}`), notification.maxDate && filters.push(`to ${notification.maxDate}`), notification.minVersion && filters.push(`from v${notification.minVersion}`), notification.maxVersion && filters.push(`to v${notification.maxVersion}`), notification.frequency === "once" && filters.push("show only once"), notification.frequency === "once_a_day" && filters.push("show once a day"), notification.frequency === "once_a_week" && filters.push("show once a week"), notification.surface && filters.push(`surface = ${notification.surface}`), notification.commands && filters.push(`commands = ${notification.commands.join(", ")}`), filters.join(`
`);
}

export {
  setCurrentCommandId,
  showNotificationsIfNeeded,
  getNotifications,
  stringifyFilters
};
//# sourceMappingURL=chunk-EMHZBYE7.js.map
