import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  SiteContext,
  SiteState,
  resolveConfiguredSite,
  useSiteListClient
} from "./chunk-D7O6F2SQ.js";
import {
  useDebugLog
} from "./chunk-7VEP3B3B.js";
import {
  APP_CONFIG_PATH,
  BiProvider,
  SiteAuthProvider,
  TimeoutError,
  openBrowser,
  pWaitFor,
  saveAppConfig,
  useBiLogger,
  useDevCenterClient,
  useProjectModel,
  wixCliAction,
  wixCliAppFlowStepsAnswers
} from "./chunk-UVMRGZ5H.js";
import {
  Alert,
  Badge,
  CliError,
  CliErrorCode,
  I18nProvider,
  Key,
  SelectInput,
  SelectOptionAvailability,
  Spinner,
  Text,
  Trans,
  getTestOverrides,
  require_lib,
  require_react,
  useAsync,
  useAsyncCallback,
  useExit,
  useTranslation,
  use_input_default
} from "./chunk-32MMFZ46.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-PYIAC2GK.js";

// src/site/SiteProvider.tsx
init_esm_shims();
var import_react10 = __toESM(require_react(), 1);
var import_variant7 = __toESM(require_lib(), 1);

// src/site/ResolveSite.tsx
init_esm_shims();
var import_react9 = __toESM(require_react(), 1);
var import_variant6 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/index.ts
init_esm_shims();

// ../cli-site-selector/src/SiteSelector.tsx
init_esm_shims();
var import_react8 = __toESM(require_react(), 1);
var import_variant5 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/SiteTypeSelect.tsx
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);
var import_variant = __toESM(require_lib(), 1);

// ../cli-site-selector/src/bi.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);
function siteSelectorBiEvents(biLogger) {
  return {
    cliAction: ({
      question,
      action,
      key,
      additionalInfo
    }) => {
      void biLogger.report(
        wixCliAction({
          question,
          action,
          key,
          additionalInfo: JSON.stringify(additionalInfo)
        })
      );
    },
    cliFlowStepAnswered: ({
      question,
      answer,
      additionalInfo
    }) => {
      void biLogger.report(
        wixCliAppFlowStepsAnswers({
          question,
          answer,
          additionalInfo: JSON.stringify(additionalInfo)
        })
      );
    }
  };
}
function useSiteSelectorBi() {
  const biLogger = useBiLogger();
  return (0, import_react.useMemo)(() => siteSelectorBiEvents(biLogger), [biLogger]);
}

// ../cli-site-selector/src/SiteTypeSelect.tsx
var SiteTypeSelect = ({ onSubmit, onError, sites }) => {
  const bi = useSiteSelectorBi();
  const { t } = useTranslation();
  const { getDevSitesCount, getDevSitesLimit } = useDevCenterClient();
  const { status } = useAsync(
    () => Promise.all([getDevSitesCount(), getDevSitesLimit()]),
    [],
    { onError }
  );
  const handleSubmit = (option) => {
    void bi.cliFlowStepAnswered({
      question: t("site_type_select.label"),
      answer: option.title
    });
    onSubmit(option.value);
  };
  return (0, import_variant.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react2.default.createElement(Spinner, { text: t("general.loading") }),
    Success: ({ result: [devSitesCount, devSitesLimit] }) => {
      const isDevSitesLimitReached = devSitesCount >= devSitesLimit;
      const userHasNoSites = sites.length === 0;
      return /* @__PURE__ */ import_react2.default.createElement(
        SelectInput,
        {
          label: t("site_type_select.label"),
          options: [
            {
              availability: userHasNoSites ? SelectOptionAvailability.Disabled({
                reason: t("site_type_select.no_sites")
              }) : SelectOptionAvailability.Enabled(),
              title: t("site_type_select.pick_existing_site"),
              value: "select-existing-site"
            },
            {
              title: t("site_type_select.create_new_dev_site"),
              value: "create-dev-site",
              availability: isDevSitesLimitReached ? SelectOptionAvailability.Disabled({
                reason: t("site_type_select.create_new_dev_site.disabled", {
                  limit: devSitesLimit
                })
              }) : SelectOptionAvailability.Enabled()
            }
          ],
          onSubmit: handleSubmit
        }
      );
    }
  });
};

// ../cli-site-selector/src/CreateDevSite.tsx
init_esm_shims();
var import_react5 = __toESM(require_react(), 1);
var import_variant3 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/WaitForAppToBeInstalled.tsx
init_esm_shims();
var import_react4 = __toESM(require_react(), 1);
var import_variant2 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/OpenBrowser.tsx
init_esm_shims();
var import_react3 = __toESM(require_react(), 1);
var OpenBrowser = ({ siteId, appId }) => {
  const { t } = useTranslation();
  const bi = useSiteSelectorBi();
  use_input_default(async (input, key) => {
    if (key.return) {
      bi.cliAction({
        question: t("install_app_on_site.warning.instructions"),
        key: "enter",
        action: "install_app_on_site"
      });
      await openBrowser(
        `https://manage.wix.com/installer/install?metaSiteId=${siteId}&appId=${appId}&platform=cli&version=latest`
      );
    }
  });
  return /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement(Trans, { i18nKey: "install_app_on_site.warning" }), /* @__PURE__ */ import_react3.default.createElement(
    Trans,
    {
      i18nKey: "install_app_on_site.warning.instructions",
      components: [/* @__PURE__ */ import_react3.default.createElement(Key, { value: "Enter" })]
    }
  ));
};

// ../cli-site-selector/src/WaitForAppToBeInstalled.tsx
var AppInstallData = (0, import_variant2.variant)({
  Success: {},
  Canceled: {}
});
function isAbortError(error) {
  return error && typeof error === "object" && "name" in error && error.name === "AbortError";
}
var WaitForAppToBeInstalled = ({
  appId,
  site,
  onSubmit,
  onError
}) => {
  const { isAppInstalled } = useDevCenterClient();
  const { status } = useAsync(
    async ({ signal }) => {
      const { pollInterval } = getTestOverrides();
      try {
        await pWaitFor(() => isAppInstalled(appId), {
          // Polling interval is set to 6.5 seconds to avoid rate limiting (429)
          interval: pollInterval ?? 6500,
          timeout: {
            milliseconds: 60 * 1e3 * 2,
            signal
          }
        });
        return AppInstallData.Success();
      } catch (error) {
        if (error instanceof TimeoutError) {
          throw new CliError({
            code: CliErrorCode.SiteSelectorTimedout(),
            cause: error
          });
        }
        if (isAbortError(error)) {
          return AppInstallData.Canceled();
        }
        throw error;
      }
    },
    [],
    {
      onError,
      onSuccess: (result) => {
        if ((0, import_variant2.isType)(result, AppInstallData.Success)) {
          onSubmit();
        }
      }
    }
  );
  return (0, import_variant2.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react4.default.createElement(OpenBrowser, { siteId: site.id, appId }),
    Success: () => /* @__PURE__ */ import_react4.default.createElement(Alert, { type: "success" }, /* @__PURE__ */ import_react4.default.createElement(Badge, { skin: "success" }, /* @__PURE__ */ import_react4.default.createElement(Trans, { i18nKey: "general.success" })), " ", /* @__PURE__ */ import_react4.default.createElement(Trans, { i18nKey: "install_app_on_site.finished_successfully" }))
  });
};

// ../cli-site-selector/src/CreateDevSite.tsx
var CreateDevSite = ({
  status,
  appId,
  onSubmit,
  onError
}) => {
  const { t } = useTranslation();
  return (0, import_variant3.match)(status, {
    NotRequested: () => null,
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react5.default.createElement(Spinner, { text: t("create_dev_site.loading") }),
    Success: ({ result }) => /* @__PURE__ */ import_react5.default.createElement(import_react5.default.Fragment, null, /* @__PURE__ */ import_react5.default.createElement(
      Trans,
      {
        i18nKey: "create_dev_site.success",
        components: [/* @__PURE__ */ import_react5.default.createElement(Text, { skin: "success", bold: true })],
        values: { name: result.displayName }
      }
    ), /* @__PURE__ */ import_react5.default.createElement(SiteAuthProvider, { siteId: result.id }, /* @__PURE__ */ import_react5.default.createElement(
      WaitForAppToBeInstalled,
      {
        appId,
        site: result,
        onSubmit: () => onSubmit(result),
        onError
      }
    )))
  });
};

// ../cli-site-selector/src/SelectExistingSite.tsx
init_esm_shims();
var import_react7 = __toESM(require_react(), 1);
var import_variant4 = __toESM(require_lib(), 1);

// ../cli-site-selector/src/SiteListSelect.tsx
init_esm_shims();
var import_react6 = __toESM(require_react(), 1);
var SiteListSelect = ({ onSubmit, sites }) => {
  const { t } = useTranslation();
  const bi = useSiteSelectorBi();
  const handleSubmit = (0, import_react6.useCallback)(
    (option) => {
      bi.cliFlowStepAnswered({
        question: t("site_list_select.label"),
        answer: option.title
      });
      onSubmit(option.value);
    },
    [bi, onSubmit, t]
  );
  return /* @__PURE__ */ import_react6.default.createElement(
    SelectInput,
    {
      label: t("site_list_select.label"),
      options: sites.map((site) => ({
        key: site.id,
        title: site.displayName,
        description: site.viewUrl,
        value: site
      })),
      onSubmit: handleSubmit
    }
  );
};

// ../cli-site-selector/src/SelectExistingSite.tsx
var CheckAppInstalledOnSite = ({ appId, site, onSubmit, onError }) => {
  const { t } = useTranslation();
  const { isAppInstalled } = useDevCenterClient();
  const { status } = useAsync(async () => isAppInstalled(appId), [], {
    onError,
    onSuccess: (isInstalled) => {
      if (isInstalled) {
        onSubmit(site);
      }
    }
  });
  return (0, import_variant4.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react7.default.createElement(Spinner, { text: t("general.loading") }),
    Success: ({ result: isInstalled }) => {
      if (isInstalled) {
        return null;
      }
      return /* @__PURE__ */ import_react7.default.createElement(
        WaitForAppToBeInstalled,
        {
          appId,
          site,
          onSubmit: () => onSubmit(site),
          onError
        }
      );
    }
  });
};
var SelectExistingSite = ({
  sites,
  appId,
  onSubmit,
  onError
}) => {
  const [siteToInstallAppOn, setSiteToInstallAppOn] = (0, import_react7.useState)(
    null
  );
  return /* @__PURE__ */ import_react7.default.createElement(import_react7.default.Fragment, null, /* @__PURE__ */ import_react7.default.createElement(
    SiteListSelect,
    {
      onSubmit: (site) => setSiteToInstallAppOn(site),
      sites
    }
  ), siteToInstallAppOn && /* @__PURE__ */ import_react7.default.createElement(SiteAuthProvider, { siteId: siteToInstallAppOn.id }, /* @__PURE__ */ import_react7.default.createElement(
    CheckAppInstalledOnSite,
    {
      appId,
      site: siteToInstallAppOn,
      onSubmit: () => onSubmit(siteToInstallAppOn),
      onError
    }
  )));
};

// ../cli-site-selector/src/messages.json
var messages_default = {
  "general.loading": "Loading...",
  "general.success": "Success",
  "site_type_select.label": "Select Development Site",
  "site_type_select.create_new_dev_site": "Create a new Development Site",
  "site_type_select.create_new_dev_site.disabled": "You have reached the maximum number of {limit} Development Sites",
  "site_type_select.pick_existing_site": "Pick an existing site",
  "site_type_select.no_sites": "No sites found",
  "create_dev_site.loading": "Creating your new Development Site...",
  "create_dev_site.success": "Development Site <0>{name}</0> created successfully! \u{1F680}",
  "site_list_select.label": "Select Site",
  "install_app_on_site.warning": "Your new application needs to be installed on the selected Development Site",
  "install_app_on_site.warning.instructions": "Press <0/> to install the application in your browser",
  "install_app_on_site.finished_successfully": "App installed on Development Site."
};

// ../cli-site-selector/src/SiteSelector.tsx
var SiteSelector = ({
  appId,
  biLogger,
  onSubmit,
  onError
}) => {
  const [siteType, setSiteType] = (0, import_react8.useState)(null);
  const { createDevSite } = useDevCenterClient();
  const siteListClient = useSiteListClient();
  const { status } = useAsync(
    () => siteListClient.querySites({
      query: {
        cursorPaging: {
          limit: 100
        }
      }
    }),
    [],
    {
      onError
    }
  );
  const createSite = useAsyncCallback(() => createDevSite(), {
    onError
  });
  function handleSelectSiteType(siteType2) {
    setSiteType(siteType2);
    if (siteType2 === "create-dev-site") {
      void createSite.execute();
    }
  }
  return /* @__PURE__ */ import_react8.default.createElement(BiProvider, { value: biLogger }, /* @__PURE__ */ import_react8.default.createElement(I18nProvider, { messages: messages_default }, (0, import_variant5.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react8.default.createElement(Spinner, { text: /* @__PURE__ */ import_react8.default.createElement(Trans, { i18nKey: "general.loading" }) }),
    Success: ({ result: sites }) => /* @__PURE__ */ import_react8.default.createElement(import_react8.default.Fragment, null, /* @__PURE__ */ import_react8.default.createElement(
      SiteTypeSelect,
      {
        onSubmit: handleSelectSiteType,
        onError,
        sites
      }
    ), siteType === "create-dev-site" && /* @__PURE__ */ import_react8.default.createElement(
      CreateDevSite,
      {
        status: createSite.status,
        appId,
        onSubmit,
        onError
      }
    ), siteType === "select-existing-site" && /* @__PURE__ */ import_react8.default.createElement(
      SelectExistingSite,
      {
        sites,
        appId,
        onSubmit,
        onError
      }
    ))
  })));
};

// src/site/ResolveSite.tsx
var ResolveSite = ({ state, onSubmit }) => {
  const exit = useExit();
  const { t } = useTranslation();
  const { model } = useProjectModel();
  const biLogger = useBiLogger();
  return /* @__PURE__ */ import_react9.default.createElement(import_react9.default.Fragment, null, (0, import_variant6.match)(state, {
    NotConfigured: (0, import_variant6.constant)(
      /* @__PURE__ */ import_react9.default.createElement(Alert, { type: "insight" }, t("general.no_site_id_configured"))
    ),
    NotFound: ({ id }) => /* @__PURE__ */ import_react9.default.createElement(Alert, { type: "error" }, t("general.site_id_not_found", { id }))
  }), /* @__PURE__ */ import_react9.default.createElement(
    SiteSelector,
    {
      appId: model.config.appId,
      biLogger,
      onSubmit,
      onError: exit
    }
  ));
};

// src/site/SiteProvider.tsx
var SiteProvider = ({ children, siteId }) => {
  const exit = useExit();
  const {
    model: { projectFolder }
  } = useProjectModel();
  const writeDebugLog = useDebugLog();
  const siteListClient = useSiteListClient();
  const { t } = useTranslation();
  const { status, merge } = useAsync(
    async () => resolveConfiguredSite({
      projectFolder,
      siteListClient,
      siteId,
      writeDebugLog
    }),
    []
  );
  const setSite = (0, import_react10.useCallback)(
    async (site) => {
      try {
        await saveAppConfig(projectFolder, { siteId: site.id });
        merge({ result: SiteState.Resolved({ site }) });
      } catch (e) {
        throw new CliError({
          code: CliErrorCode.FailedToSaveDevelopmentSite({
            path: APP_CONFIG_PATH
          }),
          cause: e
        });
      }
    },
    [merge, projectFolder]
  );
  const handleResolveSite = (0, import_react10.useCallback)(
    (site) => setSite(site).catch(exit),
    [exit, setSite]
  );
  return (0, import_variant7.match)(status, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react10.default.createElement(Spinner, { text: t("dev_command.site_provider.loading") }),
    Success: ({ result: state }) => {
      return (0, import_variant7.match)(state, {
        NotConfigured: (variant2) => /* @__PURE__ */ import_react10.default.createElement(ResolveSite, { state: variant2, onSubmit: handleResolveSite }),
        NotFound: (variant2) => /* @__PURE__ */ import_react10.default.createElement(ResolveSite, { state: variant2, onSubmit: handleResolveSite }),
        Resolved: ({ site }) => /* @__PURE__ */ import_react10.default.createElement(
          SiteContext.Provider,
          {
            value: {
              site,
              setSite
            }
          },
          typeof children === "function" ? children(site) : children
        )
      });
    }
  });
};

// src/site/index.ts
init_esm_shims();

// src/components/Platform/usePlatform.tsx
init_esm_shims();
var import_react11 = __toESM(require_react(), 1);
var import_variant8 = __toESM(require_lib(), 1);
function usePlatform() {
  const { model } = useProjectModel();
  const isPlatformExists = (0, import_react11.useCallback)(
    (platformType) => model.components.some(
      (component) => component.platforms.some((0, import_variant8.isType)(platformType.type))
    ),
    [model.components]
  );
  const hasSinglePlatform = (0, import_react11.useCallback)(
    (platformType) => model.components.every(
      (component) => component.platforms.some((0, import_variant8.isType)(platformType.type)) || component.platforms.length === 0
    ),
    [model.components]
  );
  return {
    isPlatformExists,
    hasSinglePlatform
  };
}

export {
  SiteSelector,
  SiteProvider,
  usePlatform
};
//# sourceMappingURL=chunk-NUHN5M5Q.js.map