UNPKG

convex

Version:

Client for the Convex Cloud

224 lines (223 loc) 8.37 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var convexExport_exports = {}; __export(convexExport_exports, { convexExport: () => convexExport, downloadSnapshotExport: () => downloadSnapshotExport, startSnapshotExport: () => startSnapshotExport }); module.exports = __toCommonJS(convexExport_exports); var import_extra_typings = require("@commander-js/extra-typings"); var import_chalk = __toESM(require("chalk"), 1); var import_utils = require("./lib/utils/utils.js"); var import_context = require("../bundler/context.js"); var import_api = require("./lib/api.js"); var import_run = require("./lib/run.js"); var import_fs = require("../bundler/fs.js"); var import_path = __toESM(require("path"), 1); var import_dashboard = require("./dashboard.js"); var import_command = require("./lib/command.js"); var import_stream = require("stream"); const convexExport = new import_extra_typings.Command("export").summary("Export data from your deployment to a ZIP file").description( "Export data, and optionally file storage, from your Convex deployment to a ZIP file.\nBy default, this exports from your dev deployment." ).requiredOption( "--path <zipFilePath>", "Exports data into a ZIP file at this path, which may be a directory or unoccupied .zip path" ).addOption( new import_extra_typings.Option( "--include-file-storage", "Includes stored files (https://dashboard.convex.dev/deployment/files) in a _storage folder within the ZIP file" ) ).addDeploymentSelectionOptions((0, import_command.actionDescription)("Export data from")).showHelpAfterError().action(async (options) => { const ctx = import_context.oneoffContext; const deploymentSelection = (0, import_api.deploymentSelectionFromOptions)(options); const { adminKey, url: deploymentUrl, deploymentName } = await (0, import_api.fetchDeploymentCredentialsProvisionProd)(ctx, deploymentSelection); const inputPath = options.path; const includeStorage = !!options.includeFileStorage; await (0, import_utils.ensureHasConvexDependency)(ctx, "export"); const deploymentNotice = options.prod ? ` in your ${import_chalk.default.bold("prod")} deployment` : ""; (0, import_context.showSpinner)(ctx, `Creating snapshot export${deploymentNotice}`); const snapshotExportState = await startSnapshotExport(ctx, { includeStorage, inputPath, adminKey, deploymentUrl, deploymentName: deploymentName ?? null }); switch (snapshotExportState.state) { case "completed": (0, import_context.stopSpinner)(ctx); (0, import_context.logFinishedStep)( ctx, `Created snapshot export at timestamp ${snapshotExportState.start_ts}` ); (0, import_context.logFinishedStep)( ctx, `Export is available at ${await (0, import_dashboard.deploymentDashboardUrlPage)( deploymentName ?? null, "/settings/snapshot-export" )}` ); break; case "requested": case "in_progress": { return await ctx.crash({ exitCode: 1, errorType: "fatal", printedMessage: `WARNING: Export is continuing to run on the server.` }); } default: { const _ = snapshotExportState; return await ctx.crash({ exitCode: 1, errorType: "fatal", printedMessage: `unknown error: unexpected state ${snapshotExportState}`, errForSentry: `unexpected snapshot export state ${snapshotExportState.state}` }); } } (0, import_context.showSpinner)(ctx, `Downloading snapshot export to ${import_chalk.default.bold(inputPath)}`); const { filePath } = await downloadSnapshotExport(ctx, { snapshotExportTs: snapshotExportState.start_ts, inputPath, adminKey, deploymentUrl }); (0, import_context.stopSpinner)(ctx); (0, import_context.logFinishedStep)( ctx, `Downloaded snapshot export to ${import_chalk.default.bold(filePath)}` ); }); async function waitForStableExportState(ctx, deploymentUrl, adminKey) { const [donePromise, onDone] = (0, import_utils.waitUntilCalled)(); let snapshotExportState; await (0, import_run.subscribe)( ctx, deploymentUrl, adminKey, "_system/cli/exports:getLatest", {}, donePromise, { onChange: (value) => { snapshotExportState = value; switch (snapshotExportState.state) { case "requested": case "in_progress": break; case "completed": onDone(); break; default: { const _ = snapshotExportState; onDone(); } } } } ); return snapshotExportState; } async function startSnapshotExport(ctx, args) { const fetch = (0, import_utils.deploymentFetch)(args.deploymentUrl, args.adminKey); try { await fetch( `/api/export/request/zip?includeStorage=${args.includeStorage}`, { method: "POST" } ); } catch (e) { return await (0, import_utils.logAndHandleFetchError)(ctx, e); } const snapshotExportState = await waitForStableExportState( ctx, args.deploymentUrl, args.adminKey ); return snapshotExportState; } async function downloadSnapshotExport(ctx, args) { const inputPath = args.inputPath; const exportUrl = `/api/export/zip/${args.snapshotExportTs.toString()}?adminKey=${encodeURIComponent( args.adminKey )}`; const fetch = (0, import_utils.deploymentFetch)(args.deploymentUrl, args.adminKey); let response; try { response = await fetch(exportUrl, { method: "GET" }); } catch (e) { return await (0, import_utils.logAndHandleFetchError)(ctx, e); } let filePath; if (ctx.fs.exists(inputPath)) { const st = ctx.fs.stat(inputPath); if (st.isDirectory()) { const contentDisposition = response.headers.get("content-disposition") ?? ""; let filename = `snapshot_${args.snapshotExportTs.toString()}.zip`; if (contentDisposition.startsWith("attachment; filename=")) { filename = contentDisposition.slice("attachment; filename=".length); } filePath = import_path.default.join(inputPath, filename); } else { return await ctx.crash({ exitCode: 1, errorType: "invalid filesystem data", printedMessage: `Error: Path ${import_chalk.default.bold(inputPath)} already exists.` }); } } else { filePath = inputPath; } (0, import_context.changeSpinner)(ctx, `Downloading snapshot export to ${import_chalk.default.bold(filePath)}`); try { await import_fs.nodeFs.writeFileStream( filePath, import_stream.Readable.fromWeb(response.body) ); } catch (e) { (0, import_context.logFailure)(ctx, `Exporting data failed`); (0, import_context.logError)(ctx, import_chalk.default.red(e)); return await ctx.crash({ exitCode: 1, errorType: "fatal", printedMessage: `Exporting data failed: ${import_chalk.default.red(e)}` }); } return { filePath }; } //# sourceMappingURL=convexExport.js.map