import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  PlatformLink
} from "./chunk-VKQEX5GC.js";
import {
  useVeloClient
} from "./chunk-ZY7YHRZR.js";
import "./chunk-DLEBD2WZ.js";
import "./chunk-RTNIG6ZW.js";
import "./chunk-O6HC4AYN.js";
import "./chunk-QRGKMYDD.js";
import {
  ComponentType,
  useDevCenterClient
} from "./chunk-M6WJXTS4.js";
import {
  gitGetUserInfo,
  gitPush,
  gitSetRemoteUrl,
  isInsideGitRepo
} from "./chunk-RF4NA2OH.js";
import "./chunk-NMCF7XG5.js";
import "./chunk-MHV22UIU.js";
import {
  useProjectModel
} from "./chunk-RDF2RA4E.js";
import "./chunk-4CMTZJ25.js";
import {
  useHttpClient
} from "./chunk-WFQIXGJV.js";
import {
  usePanoramaMethodLogger
} from "./chunk-ECBO3UFC.js";
import "./chunk-YNEGRO3E.js";
import {
  TimeoutError,
  openBrowser,
  pRetry,
  pWaitFor,
  resolveUrl,
  serializer,
  useErrorReporter,
  writeCrashReport
} from "./chunk-HWT3LUJJ.js";
import "./chunk-TOBTRYZF.js";
import "./chunk-7WVNO7VU.js";
import "./chunk-RPTAJN5Y.js";
import {
  Alert,
  Badge,
  Box_default,
  Link,
  Spinner,
  Text,
  useAsync
} from "./chunk-YL4347CI.js";
import {
  require_react
} from "./chunk-TODKQSCF.js";
import "./chunk-AFPDHQYI.js";
import "./chunk-HYKBBZLS.js";
import "./chunk-C5RTKQVL.js";
import "./chunk-SVUXJRFD.js";
import {
  getDebugLogFilePath
} from "./chunk-YT5BPQDJ.js";
import "./chunk-LU3R3EBR.js";
import {
  getTestOverrides
} from "./chunk-XZUGLEBK.js";
import "./chunk-VASURI4S.js";
import {
  external_exports
} from "./chunk-SDLCFZRL.js";
import {
  CliError,
  CliErrorCode,
  require_lib
} from "./chunk-MTT3QXBC.js";
import {
  __toESM,
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../cli-astro-commands/src/components/ConnectWixVibeCommand/index.ts
init_esm_shims();

// ../cli-astro-commands/src/components/ConnectWixVibeCommand/ConnectWixVibeCommand.tsx
init_esm_shims();
var import_react4 = __toESM(require_react(), 1);
var import_variant2 = __toESM(require_lib(), 1);

// ../create-new-packages/headless-command/src/index.tsx
init_esm_shims();
var import_react3 = __toESM(require_react(), 1);

// ../create-new-packages/headless-command/src/components/VibeRepositorySetupPolling.tsx
init_esm_shims();
var import_react2 = __toESM(require_react(), 1);
var import_variant = __toESM(require_lib(), 1);

// ../codestore-client/src/index.ts
init_esm_shims();

// ../codestore-client/src/useCodestoreClient.ts
init_esm_shims();
var import_react = __toESM(require_react(), 1);

// ../codestore-client/src/codestore-client.ts
init_esm_shims();

// ../../node_modules/@wix/ambassador-codestore-v1-project/build/es/http.impl.js
init_esm_shims();
var _createProjectRequest = {
  project: "_project",
  initialRevision: "_revision"
};
var _createProjectResponse = { project: "_project" };
var _project = {
  createdDate: "google.protobuf.Timestamp",
  updatedDate: "google.protobuf.Timestamp"
};
var _revision = { creationTime: "google.protobuf.Timestamp" };
function resolveWixCodestoreV1GitCodeStoreProjectsUrl(opts) {
  var domainToMappings = {
    "bo._base_domain_": [
      {
        srcPath: "/_api/git-code-store",
        destPath: ""
      }
    ],
    "wixbo.ai": [
      {
        srcPath: "/_api/git-code-store",
        destPath: ""
      }
    ],
    "wix-bo.com": [
      {
        srcPath: "/_api/git-code-store",
        destPath: ""
      }
    ],
    "manage._base_domain_": [
      {
        srcPath: "/_api/git-code-store",
        destPath: ""
      }
    ]
  };
  return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function createProject(payload) {
  var _a = serializer(_createProjectRequest, { _project, _revision }), toReq = _a.toJSON, fromReq = _a.fromJSON;
  var fromRes = serializer(_createProjectResponse, {
    _project
  }).fromJSON;
  function __createProject(_a2) {
    var host = _a2.host;
    var serializedData = toReq(payload);
    var metadata = {
      entityFqdn: "wix.codestore.v1.project",
      method: "POST",
      methodFqn: "wix.codestore.v1.GitCodeStoreProjects.CreateProject",
      migrationOptions: {
        optInTransformResponse: true
      },
      url: resolveWixCodestoreV1GitCodeStoreProjectsUrl({
        protoPath: "/v1/projects",
        data: serializedData,
        host
      }),
      data: serializedData,
      transformResponse: fromRes
    };
    return metadata;
  }
  __createProject.fromReq = fromReq;
  __createProject.__isAmbassador = true;
  return __createProject;
}

// ../../node_modules/@wix/ambassador-codestore-v1-project/build/es/types.impl.js
init_esm_shims();
var GitRemoteType;
(function(GitRemoteType2) {
  GitRemoteType2["UNKNOWN_GIT_REMOTE_TYPE"] = "UNKNOWN_GIT_REMOTE_TYPE";
  GitRemoteType2["S3"] = "S3";
  GitRemoteType2["GITHUB"] = "GITHUB";
})(GitRemoteType || (GitRemoteType = {}));
var WebhookIdentityType;
(function(WebhookIdentityType2) {
  WebhookIdentityType2["UNKNOWN"] = "UNKNOWN";
  WebhookIdentityType2["ANONYMOUS_VISITOR"] = "ANONYMOUS_VISITOR";
  WebhookIdentityType2["MEMBER"] = "MEMBER";
  WebhookIdentityType2["WIX_USER"] = "WIX_USER";
  WebhookIdentityType2["APP"] = "APP";
})(WebhookIdentityType || (WebhookIdentityType = {}));
var SortOrder;
(function(SortOrder2) {
  SortOrder2["ASC"] = "ASC";
  SortOrder2["DESC"] = "DESC";
})(SortOrder || (SortOrder = {}));

// ../codestore-client/src/schemas.ts
init_esm_shims();
var ProjectSchema = external_exports.object({
  id: external_exports.string()
}).passthrough();
var CreateProjectResponseSchema = external_exports.object({
  project: ProjectSchema
});

// ../codestore-client/src/codestore-client.ts
var { minRetryTimeout } = getTestOverrides();
var CodestoreClient = class {
  constructor(httpClient) {
    this.httpClient = httpClient;
    this.retryOptions = {
      retries: 3,
      minTimeout: minRetryTimeout,
      maxTimeout: 3 * 1e3
    };
  }
  retryOptions;
  createProject = async (projectId, userInfo) => {
    try {
      const { data } = await pRetry(
        () => this.httpClient.request(
          createProject({
            project: {
              id: projectId,
              gitRemoteType: GitRemoteType.S3,
              githubOptions: {
                appId: "b16d019c-d547-489b-a751-f277c1101847",
                appInstallationId: "103037700"
              }
            },
            initialRevision: {
              id: "1",
              description: "Initial revision",
              creationTime: /* @__PURE__ */ new Date(),
              author: {
                name: userInfo.name,
                email: userInfo.email
              }
            },
            files: [
              {
                path: "README.md",
                content: "Hello, Vibe!"
              }
            ]
          })
        ),
        this.retryOptions
      );
      return CreateProjectResponseSchema.parse(data).project;
    } catch (e) {
      throw new CliError({
        code: CliErrorCode.FailedToCreateCodestoreProject(),
        cause: e
      });
    }
  };
};

// ../codestore-client/src/useCodestoreClient.ts
function useCodestoreClient() {
  const httpClient = useHttpClient({ type: "backoffice" });
  const client = (0, import_react.useMemo)(() => new CodestoreClient(httpClient), [httpClient]);
  return usePanoramaMethodLogger(client);
}

// ../create-new-packages/headless-command/src/components/VibeRepositorySetupPolling.tsx
var VibeSetupResult = (0, import_variant.variant)({
  Success: (0, import_variant.fields)(),
  Canceled: {},
  Failed: {}
});
function isAbortError(error) {
  return error && typeof error === "object" && "name" in error && error.name === "AbortError";
}
var VibeRepositorySetupPolling = ({
  projectId,
  projectFolder,
  onSubmit
}) => {
  const { getGitHubOnboardingStatus, initGitHubRepository } = useVeloClient();
  const { reportError } = useErrorReporter();
  const { createProject: createProject2 } = useCodestoreClient();
  const { status } = useAsync(
    async ({ signal }) => {
      const { pollInterval } = getTestOverrides();
      const vibeSetupUrl = `https://manage.wix.com/_api/wix-headless-cli-github-integration-serverless?projectId=${projectId}`;
      await openBrowser(vibeSetupUrl);
      try {
        const repoInfo = await pWaitFor(
          async () => {
            const result = await getGitHubOnboardingStatus(projectId);
            if (result) {
              return pWaitFor.resolveWith(result);
            }
            return false;
          },
          {
            interval: pollInterval ?? 1e3,
            timeout: {
              milliseconds: 60 * 1e3 * 5,
              signal
            }
          }
        );
        const isGitRepo = await isInsideGitRepo(projectFolder);
        if (isGitRepo) {
          const currentUserInfo = await gitGetUserInfo(projectFolder);
          await createProject2(projectId, currentUserInfo);
          await initGitHubRepository(projectId);
          await gitSetRemoteUrl(projectFolder, "origin", repoInfo.htmlUrl);
          await gitPush(projectFolder, "origin", { force: true });
        }
        return VibeSetupResult.Success(repoInfo);
      } catch (error) {
        if (error instanceof TimeoutError) {
          throw new CliError({
            code: CliErrorCode.VibeRepositorySetupTimedout(),
            cause: error
          });
        }
        if (isAbortError(error)) {
          return VibeSetupResult.Canceled();
        }
        throw error;
      }
    },
    [projectFolder, projectId],
    {
      onSuccess: (result) => {
        if ((0, import_variant.isType)(result, VibeSetupResult.Success)) {
          onSubmit?.();
        }
      },
      onError: (error) => {
        reportError(error);
        writeCrashReport(getDebugLogFilePath(projectFolder), error, /* @__PURE__ */ new Date());
        return VibeSetupResult.Failed();
      }
    }
  );
  return (0, import_variant.match)(status, {
    Error: () => /* @__PURE__ */ import_react2.default.createElement(Box_default, { flexDirection: "column", gap: 1 }, /* @__PURE__ */ import_react2.default.createElement(Text, { skin: "error" }, "Failed to connect to Wix Vibe")),
    Loading: () => /* @__PURE__ */ import_react2.default.createElement(Box_default, { flexDirection: "column", gap: 1 }, /* @__PURE__ */ import_react2.default.createElement(Spinner, { text: "Opening browser for Wix Vibe setup..." }), /* @__PURE__ */ import_react2.default.createElement(Text, { skin: "secondary" }, "Complete the setup in your browser. Waiting for you to finish...")),
    Success: ({ result }) => (0, import_variant.match)(result, {
      Success: ({ repoName, htmlUrl }) => /* @__PURE__ */ import_react2.default.createElement(Box_default, { marginLeft: -2, marginBottom: 1 }, /* @__PURE__ */ import_react2.default.createElement(Alert, { type: "success" }, /* @__PURE__ */ import_react2.default.createElement(Badge, { skin: "success" }, "Success"), " ", /* @__PURE__ */ import_react2.default.createElement(Text, null, "GitHub repository '", repoName, "' created and Synced.", " ", /* @__PURE__ */ import_react2.default.createElement(Link, { url: htmlUrl }, "View Repository.")))),
      Canceled: () => null
    })
  });
};

// ../cli-astro-commands/src/components/ConnectWixVibeCommand/schemas.ts
init_esm_shims();
var backendWorkerComponentSchema = external_exports.object({
  compType: external_exports.literal(ComponentType.BACKEND_WORKER),
  compData: external_exports.object({
    backendWorker: external_exports.object({
      deploymentUrl: external_exports.string().optional()
    })
  }).passthrough()
}).passthrough();

// ../cli-astro-commands/src/components/ConnectWixVibeCommand/ConnectWixVibeCommand.tsx
var ConnectWixVibeCommand = () => {
  const {
    model: { projectFolder, config }
  } = useProjectModel();
  const { getGitHubOnboardingStatus } = useVeloClient();
  const { getAppByVersion } = useDevCenterClient();
  const [isConnected, setIsConnected] = (0, import_react4.useState)(false);
  const { status: connectionStatus } = useAsync(async () => {
    if (config.projectType !== "Site") {
      throw new CliError({
        code: CliErrorCode.ConnectUnsupportedForProjectType(),
        cause: null
      });
    }
    return {
      existingConnection: await getGitHubOnboardingStatus(config.appId),
      siteId: config.siteId
    };
  }, []);
  const getDeploymentUrl = (0, import_react4.useCallback)(async () => {
    const { data } = await getAppByVersion({ appId: config.appId });
    const backendWorkerComponent = data.components.find(
      (component) => component.compType === ComponentType.BACKEND_WORKER
    );
    const parsedBackendWorkerComponent = backendWorkerComponentSchema.safeParse(
      backendWorkerComponent
    );
    if (parsedBackendWorkerComponent.success) {
      return parsedBackendWorkerComponent.data.compData.backendWorker.deploymentUrl;
    }
  }, [getAppByVersion, config.appId]);
  const { status: deploymentUrlStatus } = useAsync(async () => {
    if (!isConnected) {
      return;
    }
    const deploymentUrl = await getDeploymentUrl();
    return deploymentUrl;
  }, [isConnected, config.appId]);
  return (0, import_variant2.match)(connectionStatus, {
    Error: () => null,
    Loading: () => /* @__PURE__ */ import_react4.default.createElement(Spinner, { text: "Checking Wix Vibe connection status..." }),
    Success: ({ result: { existingConnection, siteId } }) => {
      if (existingConnection) {
        return /* @__PURE__ */ import_react4.default.createElement(Box_default, { flexDirection: "column", gap: 1, marginTop: 1 }, /* @__PURE__ */ import_react4.default.createElement(Alert, { type: "insight" }, /* @__PURE__ */ import_react4.default.createElement(Text, null, "This project is already connected to Wix Vibe.", " ", /* @__PURE__ */ import_react4.default.createElement(Link, { url: existingConnection.htmlUrl }, "View Repository"), ".")));
      }
      return /* @__PURE__ */ import_react4.default.createElement(Box_default, { flexDirection: "column", marginTop: 1 }, /* @__PURE__ */ import_react4.default.createElement(
        VibeRepositorySetupPolling,
        {
          projectId: config.appId,
          projectFolder,
          onSubmit: () => setIsConnected(true)
        }
      ), isConnected && /* @__PURE__ */ import_react4.default.createElement(Box_default, { gap: 1, flexDirection: "column", marginBottom: 1 }, /* @__PURE__ */ import_react4.default.createElement(Text, null, "You can edit your site in the Wix Vibe Editor now."), /* @__PURE__ */ import_react4.default.createElement(Box_default, { paddingLeft: 2, flexDirection: "column" }, /* @__PURE__ */ import_react4.default.createElement(
        PlatformLink,
        {
          url: `https://vibe.wix.com/projects/${siteId}`,
          platform: "editor"
        }
      ), /* @__PURE__ */ import_react4.default.createElement(
        PlatformLink,
        {
          url: `https://manage.wix.com/dashboard/${siteId}`,
          platform: "dashboard"
        }
      ), (0, import_variant2.match)(deploymentUrlStatus, {
        Success: ({ result }) => result ? /* @__PURE__ */ import_react4.default.createElement(PlatformLink, { url: result, platform: "site" }) : null,
        Loading: () => null,
        Error: () => null
      }))));
    }
  });
};
export {
  ConnectWixVibeCommand
};
//# sourceMappingURL=ConnectWixVibeCommand-VADKDWAS.js.map