sanity 4.9.0-next.18 → 4.9.0-next.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/_chunks-cjs/buildAction.js +17 -6
- package/lib/_chunks-cjs/buildAction.js.map +1 -1
- package/lib/_chunks-cjs/buildAction2.js +17 -6
- package/lib/_chunks-cjs/buildAction2.js.map +1 -1
- package/lib/_chunks-cjs/deployAction.js +23 -7
- package/lib/_chunks-cjs/deployAction.js.map +1 -1
- package/lib/_chunks-cjs/deployAction2.js +31 -9
- package/lib/_chunks-cjs/deployAction2.js.map +1 -1
- package/lib/_chunks-cjs/devAction.js +2 -2
- package/lib/_chunks-cjs/devAction.js.map +1 -1
- package/lib/_chunks-cjs/devAction2.js +30 -22
- package/lib/_chunks-cjs/devAction2.js.map +1 -1
- package/lib/_chunks-cjs/getAppId.js +23 -0
- package/lib/_chunks-cjs/getAppId.js.map +1 -0
- package/lib/_chunks-cjs/helpers.js +15 -12
- package/lib/_chunks-cjs/helpers.js.map +1 -1
- package/lib/_chunks-cjs/undeployAction.js +5 -2
- package/lib/_chunks-cjs/undeployAction.js.map +1 -1
- package/lib/_chunks-cjs/upgradePackages.js +4 -4
- package/lib/_chunks-cjs/upgradePackages.js.map +1 -1
- package/lib/_chunks-cjs/version.js +1 -1
- package/lib/_chunks-cjs/{shouldAutoUpdate.js → warnAboutMissingAppId.js} +39 -5
- package/lib/_chunks-cjs/warnAboutMissingAppId.js.map +1 -0
- package/lib/_chunks-es/version.mjs +1 -1
- package/package.json +14 -14
- package/lib/_chunks-cjs/shouldAutoUpdate.js.map +0 -1
@@ -18,7 +18,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
18
18
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
|
19
19
|
mod
|
20
20
|
));
|
21
|
-
var path = require("node:path"), chalk = require("chalk"), logSymbols = require("log-symbols"), semver = require("semver"), helpers = require("yargs/helpers"), yargs = require("yargs/yargs"), _internal = require("./_internal.js"), runtime = require("./runtime.js"), upgradePackages = require("./upgradePackages.js"),
|
21
|
+
var path = require("node:path"), chalk = require("chalk"), logSymbols = require("log-symbols"), semver = require("semver"), helpers = require("yargs/helpers"), yargs = require("yargs/yargs"), _internal = require("./_internal.js"), runtime = require("./runtime.js"), upgradePackages = require("./upgradePackages.js"), warnAboutMissingAppId = require("./warnAboutMissingAppId.js"), getAppId = require("./getAppId.js"), servers = require("./servers.js"), timing = require("./timing.js");
|
22
22
|
function _interopDefaultCompat(e) {
|
23
23
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
24
24
|
}
|
@@ -67,15 +67,12 @@ async function startDevServer(options) {
|
|
67
67
|
close: () => server.close()
|
68
68
|
};
|
69
69
|
}
|
70
|
-
const debug = _internal.debug.extend("dev"),
|
70
|
+
const debug = _internal.debug.extend("dev"), baseUrl = process.env.SANITY_INTERNAL_ENV === "staging" ? "https://sanity.work" : "https://sanity.io", getDefaultDashboardURL = ({
|
71
71
|
organizationId,
|
72
72
|
url
|
73
|
-
}) => {
|
74
|
-
|
75
|
-
|
76
|
-
});
|
77
|
-
return process.env.SANITY_INTERNAL_ENV === "staging" ? `https://sanity.work/@${organizationId}?${params.toString()}` : `https://sanity.io/@${organizationId}?${params.toString()}`;
|
78
|
-
}, getCoreApiURL = () => process.env.SANITY_INTERNAL_ENV === "staging" ? "https://sanity.work" : "https://sanity.io", getCoreURL = async ({
|
73
|
+
}) => `${baseUrl}/@${organizationId}?${new URLSearchParams({
|
74
|
+
url
|
75
|
+
}).toString()}`, getDashboardURL = async ({
|
79
76
|
fetchFn = globalThis.fetch,
|
80
77
|
timeout = 5e3,
|
81
78
|
organizationId,
|
@@ -86,26 +83,26 @@ const debug = _internal.debug.extend("dev"), getDefaultCoreURL = ({
|
|
86
83
|
const queryParams = new URLSearchParams({
|
87
84
|
organizationId,
|
88
85
|
url
|
89
|
-
}), res = await fetchFn(`${
|
86
|
+
}), res = await fetchFn(`${baseUrl}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`, {
|
90
87
|
signal: abortController.signal
|
91
88
|
});
|
92
|
-
return res.ok ? (await res.json()).url : (debug(`Failed to fetch
|
89
|
+
return res.ok ? (await res.json()).url : (debug(`Failed to fetch dashboard URL: ${res.statusText}`), getDefaultDashboardURL({
|
93
90
|
organizationId,
|
94
91
|
url
|
95
92
|
}));
|
96
93
|
} catch (err) {
|
97
|
-
return debug(`Failed to fetch
|
94
|
+
return debug(`Failed to fetch dashboard URL: ${err.message}`), getDefaultDashboardURL({
|
98
95
|
organizationId,
|
99
96
|
url
|
100
97
|
});
|
101
98
|
} finally {
|
102
99
|
clearTimeout(timer);
|
103
100
|
}
|
104
|
-
},
|
101
|
+
}, getDashboardAppURL = async ({
|
105
102
|
organizationId,
|
106
103
|
httpHost = "localhost",
|
107
104
|
httpPort = 3333
|
108
|
-
}) => await
|
105
|
+
}) => await getDashboardURL({
|
109
106
|
organizationId,
|
110
107
|
url: `http://${httpHost}:${httpPort}`
|
111
108
|
});
|
@@ -127,7 +124,8 @@ async function startSanityDevServer(args, context) {
|
|
127
124
|
apiClient,
|
128
125
|
workDir,
|
129
126
|
cliConfig,
|
130
|
-
prompt
|
127
|
+
prompt,
|
128
|
+
cliConfigPath
|
131
129
|
} = context, {
|
132
130
|
loadInDashboard
|
133
131
|
} = flags;
|
@@ -139,7 +137,7 @@ async function startSanityDevServer(args, context) {
|
|
139
137
|
} = await upgradePackages.checkRequiredDependencies(context);
|
140
138
|
if (didInstall)
|
141
139
|
return;
|
142
|
-
if (
|
140
|
+
if (warnAboutMissingAppId.shouldAutoUpdate({
|
143
141
|
flags,
|
144
142
|
cliConfig
|
145
143
|
})) {
|
@@ -152,11 +150,21 @@ async function startSanityDevServer(args, context) {
|
|
152
150
|
}, {
|
153
151
|
name: "@sanity/vision",
|
154
152
|
version: cleanSanityVersion
|
155
|
-
}]
|
156
|
-
|
153
|
+
}], appId = getAppId.getAppId({
|
154
|
+
cliConfig,
|
155
|
+
output
|
156
|
+
});
|
157
|
+
output.print(`${logSymbols.info} Running with auto-updates enabled`), appId || warnAboutMissingAppId.warnAboutMissingAppId({
|
158
|
+
appType: "studio",
|
159
|
+
cliConfigPath,
|
160
|
+
output,
|
161
|
+
projectId: cliConfig?.api?.projectId
|
162
|
+
});
|
157
163
|
let result;
|
158
164
|
try {
|
159
|
-
result = await
|
165
|
+
result = await warnAboutMissingAppId.compareDependencyVersions(sanityDependencies, workDir, {
|
166
|
+
appId
|
167
|
+
});
|
160
168
|
} catch (err) {
|
161
169
|
console.warn(new Error("Failed to compare local versions against auto-updating versions", {
|
162
170
|
cause: err
|
@@ -214,7 +222,7 @@ ${result.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime v
|
|
214
222
|
port
|
215
223
|
} = server.config.server, httpHost = config.httpHost || "localhost";
|
216
224
|
if (spinner.succeed(), loadInDashboard)
|
217
|
-
organizationId || (output.error("Organization Id not found for project"), process.exit(1)), output.print(`Dev server started on ${config.httpPort} port`), output.print("View your app in the Sanity dashboard here:"), output.print(chalk__default.default.blue(chalk__default.default.underline(await
|
225
|
+
organizationId || (output.error("Organization Id not found for project"), process.exit(1)), output.print(`Dev server started on ${config.httpPort} port`), output.print("View your app in the Sanity dashboard here:"), output.print(chalk__default.default.blue(chalk__default.default.underline(await getDashboardAppURL({
|
218
226
|
organizationId,
|
219
227
|
httpHost: config.httpHost,
|
220
228
|
httpPort: config.httpPort
|
@@ -253,12 +261,12 @@ function getDevServerConfig({
|
|
253
261
|
var devAction = /* @__PURE__ */ Object.freeze({
|
254
262
|
__proto__: null,
|
255
263
|
default: startSanityDevServer,
|
256
|
-
|
257
|
-
|
264
|
+
getDashboardAppURL,
|
265
|
+
getDashboardURL,
|
258
266
|
getDevServerConfig
|
259
267
|
});
|
260
268
|
exports.devAction = devAction;
|
261
|
-
exports.
|
269
|
+
exports.getDashboardAppURL = getDashboardAppURL;
|
262
270
|
exports.getDevServerConfig = getDevServerConfig;
|
263
271
|
exports.startDevServer = startDevServer;
|
264
272
|
//# sourceMappingURL=devAction2.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"devAction2.js","sources":["../../src/_internal/cli/server/devServer.ts","../../src/_internal/cli/actions/dev/devAction.ts"],"sourcesContent":["import {type ReactCompilerConfig, type UserViteConfig} from '@sanity/cli'\nimport {type ViteDevServer} from 'vite'\n\nimport {debug} from './debug'\nimport {extendViteConfigWithUserConfig, getViteConfig} from './getViteConfig'\nimport {writeSanityRuntime} from './runtime'\n\nexport interface DevServerOptions {\n cwd: string\n basePath: string\n staticPath: string\n\n httpPort: number\n httpHost?: string\n projectName?: string\n\n reactStrictMode: boolean\n reactCompiler: ReactCompilerConfig | undefined\n vite?: UserViteConfig\n entry?: string\n isApp?: boolean\n}\n\nexport interface DevServer {\n server: ViteDevServer\n close(): Promise<void>\n}\n\nexport async function startDevServer(options: DevServerOptions): Promise<DevServer> {\n const {\n cwd,\n httpPort,\n httpHost,\n basePath,\n reactStrictMode,\n vite: extendViteConfig,\n reactCompiler,\n entry,\n isApp,\n } = options\n\n debug('Writing Sanity runtime files')\n await writeSanityRuntime({cwd, reactStrictMode, watch: true, basePath, entry, isApp})\n\n debug('Resolving vite config')\n const mode = 'development'\n\n let viteConfig = await getViteConfig({\n basePath,\n mode: 'development',\n server: {port: httpPort, host: httpHost},\n cwd,\n reactCompiler,\n isApp,\n })\n\n // Extend Vite configuration with user-provided config\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'serve', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n debug('Creating vite server')\n const {createServer} = await import('vite')\n const server = await createServer(viteConfig)\n\n debug('Listening on specified port')\n await server.listen()\n\n return {\n server,\n close: () => server.close(),\n }\n}\n","/* eslint-disable max-statements */\nimport path from 'node:path'\n\nimport {\n type CliCommandArguments,\n type CliCommandContext,\n type CliConfig,\n type CliOutputter,\n} from '@sanity/cli'\nimport {type SanityProject} from '@sanity/client'\nimport chalk from 'chalk'\nimport {info} from 'log-symbols'\nimport semver from 'semver'\nimport {hideBin} from 'yargs/helpers'\nimport yargs from 'yargs/yargs'\n\nimport {debug as debugIt} from '../../debug'\nimport {type DevServerOptions, startDevServer} from '../../server/devServer'\nimport {checkRequiredDependencies} from '../../util/checkRequiredDependencies'\nimport {checkStudioDependencyVersions} from '../../util/checkStudioDependencyVersions'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions'\nimport {isInteractive} from '../../util/isInteractive'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages'\nimport {getSharedServerConfig, gracefulServerDeath} from '../../util/servers'\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport {getTimer} from '../../util/timing'\n\nexport interface StartDevServerCommandFlags {\n 'host'?: string\n 'port'?: string\n 'load-in-dashboard'?: boolean\n 'auto-updates'?: boolean\n 'force'?: boolean\n}\n\nconst debug = debugIt.extend('dev')\n\nconst getDefaultCoreURL = ({\n organizationId,\n url,\n}: {\n organizationId: string\n url: string\n}): string => {\n const params = new URLSearchParams({\n url,\n })\n\n return process.env.SANITY_INTERNAL_ENV === 'staging'\n ? `https://sanity.work/@${organizationId}?${params.toString()}`\n : `https://sanity.io/@${organizationId}?${params.toString()}`\n}\n\nconst getCoreApiURL = (): string => {\n return process.env.SANITY_INTERNAL_ENV === 'staging' ? 'https://sanity.work' : 'https://sanity.io'\n}\n\nexport const getCoreURL = async ({\n fetchFn = globalThis.fetch,\n timeout = 5000,\n organizationId,\n url,\n}: {\n fetchFn?: typeof globalThis.fetch\n timeout?: number\n organizationId: string\n url: string\n}): Promise<string> => {\n const abortController = new AbortController()\n // Wait for 5 seconds before aborting the request\n const timer = setTimeout(() => abortController.abort(), timeout)\n try {\n const queryParams = new URLSearchParams({\n organizationId,\n url,\n })\n\n const res = await fetchFn(\n `${getCoreApiURL()}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`,\n {\n signal: abortController.signal,\n },\n )\n\n if (!res.ok) {\n debug(`Failed to fetch core URL: ${res.statusText}`)\n return getDefaultCoreURL({organizationId, url})\n }\n\n const body = await res.json()\n return body.url\n } catch (err) {\n debug(`Failed to fetch core URL: ${err.message}`)\n return getDefaultCoreURL({organizationId, url})\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Gets the core URL from API or uses the default core URL\n */\nexport const getCoreAppURL = async ({\n organizationId,\n httpHost = 'localhost',\n httpPort = 3333,\n}: {\n organizationId: string\n httpHost?: string\n httpPort?: number\n}): Promise<string> => {\n const url = await getCoreURL({\n organizationId,\n url: `http://${httpHost}:${httpPort}`,\n })\n\n // <core-app-url>/<orgniazationId>?dev=<dev-server-url>\n return url\n}\n\nfunction parseCliFlags(args: {argv?: string[]}) {\n // Using slice(1) to remove the first argument, which is the command `dev` path to the CLI\n return yargs(hideBin(args.argv || process.argv).slice(1))\n .options('host', {type: 'string'})\n .options('port', {type: 'number'})\n .options('auto-updates', {type: 'boolean'})\n .option('load-in-dashboard', {type: 'boolean', default: false}).argv\n}\n\nexport default async function startSanityDevServer(\n args: CliCommandArguments<StartDevServerCommandFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const timers = getTimer()\n const flags = await parseCliFlags(args)\n const {output, apiClient, workDir, cliConfig, prompt, cliPackageManager} = context\n\n const {loadInDashboard} = flags\n\n timers.start('checkStudioDependencyVersions')\n await checkStudioDependencyVersions(workDir)\n timers.end('checkStudioDependencyVersions')\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n if ((await checkRequiredDependencies(context)).didInstall) {\n return\n }\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {didInstall, installedSanityVersion} = await checkRequiredDependencies(context)\n if (didInstall) {\n return\n }\n\n const autoUpdatesEnabled = shouldAutoUpdate({flags, cliConfig})\n const autoUpdatesImports = {}\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semver.parse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n const sanityDependencies = [\n {name: 'sanity', version: cleanSanityVersion},\n {name: '@sanity/vision', version: cleanSanityVersion},\n ]\n\n output.print(`${info} Running with auto-updates enabled`)\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir)\n } catch (err) {\n console.warn(\n new Error('Failed to compare local versions against auto-updating versions', {\n cause: err,\n }),\n )\n }\n if (result?.length) {\n const message =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you run with the same versions locally as will be used when deploying. \\n\\n` +\n `${result.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')} \\n\\n`\n\n // mismatch between local and auto-updating dependencies\n if (isInteractive) {\n const shouldUpgrade = await prompt.single({\n type: 'confirm',\n message: chalk.yellow(`${message}Do you want to upgrade local versions?`),\n default: true,\n })\n if (shouldUpgrade) {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: result.map((res) => [res.pkg, res.remote]),\n },\n context,\n )\n }\n } else {\n // In this case we warn the user but we don't ask them if they want to upgrade because it's not interactive.\n output.print(chalk.yellow(message))\n }\n }\n }\n\n // Try to load CLI configuration from sanity.cli.(js|ts)\n const config = getDevServerConfig({flags, workDir, cliConfig, output})\n\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined | null\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard')\n process.exit(1)\n }\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n })\n\n try {\n const project = await client.request<SanityProject>({uri: `/projects/${projectId}`})\n organizationId = project.organizationId\n } catch (err) {\n debug(`Failed to get organization Id from project Id: ${err}`)\n output.error('Failed to get organization Id from project Id')\n process.exit(1)\n }\n }\n\n try {\n const startTime = Date.now()\n const spinner = output.spinner('Starting dev server').start()\n const {server} = await startDevServer({...config})\n\n const {info: loggerInfo} = server.config.logger\n const {port} = server.config.server\n const httpHost = config.httpHost || 'localhost'\n\n spinner.succeed()\n\n if (loadInDashboard) {\n if (!organizationId) {\n output.error('Organization Id not found for project')\n process.exit(1)\n }\n\n output.print(`Dev server started on ${config.httpPort} port`)\n output.print(`View your app in the Sanity dashboard here:`)\n output.print(\n chalk.blue(\n chalk.underline(\n await getCoreAppURL({\n organizationId,\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n }),\n ),\n ),\n )\n } else {\n const startupDuration = Date.now() - startTime\n const url = `http://${httpHost || 'localhost'}:${port}${config.basePath}`\n const appType = 'Sanity Studio'\n\n loggerInfo(\n `${appType} ` +\n `using ${chalk.cyan(`vite@${require('vite/package.json').version}`)} ` +\n `ready in ${chalk.cyan(`${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${chalk.cyan(url)}`,\n )\n }\n } catch (err) {\n debug(`Failed to start dev server: ${err}`)\n gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n\nexport function getDevServerConfig({\n flags,\n workDir,\n cliConfig,\n output,\n}: {\n flags: {host?: string; port?: number}\n workDir: string\n cliConfig?: CliConfig\n output: CliOutputter\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = output.spinner('Checking configuration files...')\n const baseConfig = getSharedServerConfig({\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n cliConfig,\n })\n configSpinner.succeed()\n\n const env = process.env\n const reactStrictMode = env.SANITY_STUDIO_REACT_STRICT_MODE\n ? env.SANITY_STUDIO_REACT_STRICT_MODE === 'true'\n : Boolean(cliConfig?.reactStrictMode)\n\n if (env.SANITY_STUDIO_BASEPATH && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${env.SANITY_STUDIO_BASEPATH})`,\n )\n }\n\n return {\n ...baseConfig,\n staticPath: path.join(workDir, 'static'),\n reactStrictMode,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n }\n}\n"],"names":["startDevServer","options","cwd","httpPort","httpHost","basePath","reactStrictMode","vite","extendViteConfig","reactCompiler","entry","isApp","debug","writeSanityRuntime","watch","mode","viteConfig","getViteConfig","server","port","host","extendViteConfigWithUserConfig","command","createServer","listen","close","debugIt","extend","getDefaultCoreURL","organizationId","url","params","URLSearchParams","process","env","SANITY_INTERNAL_ENV","toString","getCoreApiURL","getCoreURL","fetchFn","globalThis","fetch","timeout","abortController","AbortController","timer","setTimeout","abort","queryParams","res","signal","ok","json","statusText","err","message","clearTimeout","getCoreAppURL","parseCliFlags","args","yargs","hideBin","argv","slice","type","option","default","startSanityDevServer","context","timers","getTimer","flags","output","apiClient","workDir","cliConfig","prompt","loadInDashboard","start","checkStudioDependencyVersions","end","checkRequiredDependencies","didInstall","installedSanityVersion","shouldAutoUpdate","cleanSanityVersion","semver","parse","version","Error","sanityDependencies","name","print","info","result","compareDependencyVersions","console","warn","cause","length","map","mod","pkg","installed","remote","join","isInteractive","single","chalk","yellow","upgradePackages","packageManager","getPackageManagerChoice","interactive","chosen","packages","config","getDevServerConfig","projectId","api","error","exit","client","requireUser","requireProject","request","uri","startTime","Date","now","spinner","loggerInfo","logger","succeed","blue","underline","startupDuration","cyan","require","Math","ceil","gracefulServerDeath","configSpinner","baseConfig","getSharedServerConfig","SANITY_STUDIO_REACT_STRICT_MODE","Boolean","SANITY_STUDIO_BASEPATH","project","staticPath","path","undefined"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsBA,eAAeC,SAA+C;AAClF,QAAM;AAAA,IACJC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC,MAAMC;AAAAA,IACNC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,EAAAA,IACE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AG;AAAA,EAClE;AACF;AAEO,SAAS+D,mBAAmB;AAAA,EACjC9C;AAAAA,EACAG;AAAAA,EACAC;AAAAA,EACAH;AAMF,GAAsC;AACpC,QAAMsE,gBAAgBtE,OAAO0D,QAAQ,iCAAiC,GAChEa,aAAaC,8BAAsB;AAAA,IACvCzE,OAAO;AAAA,MACLnD,MAAMmD,MAAMnD;AAAAA,MACZD,MAAMoD,MAAMpD;AAAAA,IAAAA;AAAAA,IAEduD;AAAAA,IACAC;AAAAA,EAAAA,CACD;AACDmE,gBAAcT,QAAAA;AAEd,QAAMnG,MAAMD,QAAQC,KACd5B,kBAAkB4B,IAAI+G,kCACxB/G,IAAI+G,oCAAoC,SACxCC,CAAAA,CAAQvE,WAAWrE;AAEvB,SAAI4B,IAAIiH,0BAA0BxE,WAAWyE,SAAS/I,YACpDmE,OAAOyB,KACL,oCAAoCtB,UAAUyE,QAAQ/I,QAAQ,2CAA2C6B,IAAIiH,sBAAsB,GACrI,GAGK;AAAA,IACL,GAAGJ;AAAAA,IACHM,YAAYC,cAAAA,QAAK7C,KAAK/B,SAAS,QAAQ;AAAA,IACvCpE;AAAAA,IACAG,eAAekE,aAAa,mBAAmBA,YAAYA,UAAUlE,gBAAgB8I;AAAAA,EAAAA;AAEzF;;;;;;;;;;;;"}
|
1
|
+
{"version":3,"file":"devAction2.js","sources":["../../src/_internal/cli/server/devServer.ts","../../src/_internal/cli/actions/dev/devAction.ts"],"sourcesContent":["import {type ReactCompilerConfig, type UserViteConfig} from '@sanity/cli'\nimport {type ViteDevServer} from 'vite'\n\nimport {debug} from './debug'\nimport {extendViteConfigWithUserConfig, getViteConfig} from './getViteConfig'\nimport {writeSanityRuntime} from './runtime'\n\nexport interface DevServerOptions {\n cwd: string\n basePath: string\n staticPath: string\n\n httpPort: number\n httpHost?: string\n projectName?: string\n\n reactStrictMode: boolean\n reactCompiler: ReactCompilerConfig | undefined\n vite?: UserViteConfig\n entry?: string\n isApp?: boolean\n}\n\nexport interface DevServer {\n server: ViteDevServer\n close(): Promise<void>\n}\n\nexport async function startDevServer(options: DevServerOptions): Promise<DevServer> {\n const {\n cwd,\n httpPort,\n httpHost,\n basePath,\n reactStrictMode,\n vite: extendViteConfig,\n reactCompiler,\n entry,\n isApp,\n } = options\n\n debug('Writing Sanity runtime files')\n await writeSanityRuntime({cwd, reactStrictMode, watch: true, basePath, entry, isApp})\n\n debug('Resolving vite config')\n const mode = 'development'\n\n let viteConfig = await getViteConfig({\n basePath,\n mode: 'development',\n server: {port: httpPort, host: httpHost},\n cwd,\n reactCompiler,\n isApp,\n })\n\n // Extend Vite configuration with user-provided config\n if (extendViteConfig) {\n viteConfig = await extendViteConfigWithUserConfig(\n {command: 'serve', mode},\n viteConfig,\n extendViteConfig,\n )\n }\n\n debug('Creating vite server')\n const {createServer} = await import('vite')\n const server = await createServer(viteConfig)\n\n debug('Listening on specified port')\n await server.listen()\n\n return {\n server,\n close: () => server.close(),\n }\n}\n","/* eslint-disable max-statements */\nimport path from 'node:path'\n\nimport {\n type CliCommandArguments,\n type CliCommandContext,\n type CliConfig,\n type CliOutputter,\n} from '@sanity/cli'\nimport {type SanityProject} from '@sanity/client'\nimport chalk from 'chalk'\nimport {info} from 'log-symbols'\nimport semver from 'semver'\nimport {hideBin} from 'yargs/helpers'\nimport yargs from 'yargs/yargs'\n\nimport {debug as debugIt} from '../../debug'\nimport {type DevServerOptions, startDevServer} from '../../server/devServer'\nimport {checkRequiredDependencies} from '../../util/checkRequiredDependencies'\nimport {checkStudioDependencyVersions} from '../../util/checkStudioDependencyVersions'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions'\nimport {getAppId} from '../../util/getAppId'\nimport {isInteractive} from '../../util/isInteractive'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages'\nimport {getSharedServerConfig, gracefulServerDeath} from '../../util/servers'\nimport {shouldAutoUpdate} from '../../util/shouldAutoUpdate'\nimport {getTimer} from '../../util/timing'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId'\n\nexport interface StartDevServerCommandFlags {\n 'host'?: string\n 'port'?: string\n 'load-in-dashboard'?: boolean\n 'auto-updates'?: boolean\n 'force'?: boolean\n}\n\nconst debug = debugIt.extend('dev')\n\nconst baseUrl =\n process.env.SANITY_INTERNAL_ENV === 'staging' ? 'https://sanity.work' : 'https://sanity.io'\n\nconst getDefaultDashboardURL = ({\n organizationId,\n url,\n}: {\n organizationId: string\n url: string\n}): string => {\n return `${baseUrl}/@${organizationId}?${new URLSearchParams({\n url,\n }).toString()}`\n}\n\nexport const getDashboardURL = async ({\n fetchFn = globalThis.fetch,\n timeout = 5000,\n organizationId,\n url,\n}: {\n fetchFn?: typeof globalThis.fetch\n timeout?: number\n organizationId: string\n url: string\n}): Promise<string> => {\n const abortController = new AbortController()\n // Wait for 5 seconds before aborting the request\n const timer = setTimeout(() => abortController.abort(), timeout)\n try {\n const queryParams = new URLSearchParams({\n organizationId,\n url,\n })\n\n const res = await fetchFn(\n `${baseUrl}/api/dashboard/mode/development/resolve-url?${queryParams.toString()}`,\n {\n signal: abortController.signal,\n },\n )\n\n if (!res.ok) {\n debug(`Failed to fetch dashboard URL: ${res.statusText}`)\n return getDefaultDashboardURL({organizationId, url})\n }\n\n const body = await res.json()\n return body.url\n } catch (err) {\n debug(`Failed to fetch dashboard URL: ${err.message}`)\n return getDefaultDashboardURL({organizationId, url})\n } finally {\n clearTimeout(timer)\n }\n}\n\n/**\n * Gets the dashboard URL from API or uses the default dashboard URL\n */\nexport const getDashboardAppURL = async ({\n organizationId,\n httpHost = 'localhost',\n httpPort = 3333,\n}: {\n organizationId: string\n httpHost?: string\n httpPort?: number\n}): Promise<string> => {\n const url = await getDashboardURL({\n organizationId,\n url: `http://${httpHost}:${httpPort}`,\n })\n\n // <dashboard-app-url>/<orgniazationId>?dev=<dev-server-url>\n return url\n}\n\nfunction parseCliFlags(args: {argv?: string[]}) {\n // Using slice(1) to remove the first argument, which is the command `dev` path to the CLI\n return yargs(hideBin(args.argv || process.argv).slice(1))\n .options('host', {type: 'string'})\n .options('port', {type: 'number'})\n .options('auto-updates', {type: 'boolean'})\n .option('load-in-dashboard', {type: 'boolean', default: false}).argv\n}\n\nexport default async function startSanityDevServer(\n args: CliCommandArguments<StartDevServerCommandFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const timers = getTimer()\n const flags = await parseCliFlags(args)\n const {output, apiClient, workDir, cliConfig, prompt, cliConfigPath} = context\n\n const {loadInDashboard} = flags\n\n timers.start('checkStudioDependencyVersions')\n await checkStudioDependencyVersions(workDir)\n timers.end('checkStudioDependencyVersions')\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n if ((await checkRequiredDependencies(context)).didInstall) {\n return\n }\n\n // If the check resulted in a dependency install, the CLI command will be re-run,\n // thus we want to exit early\n const {didInstall, installedSanityVersion} = await checkRequiredDependencies(context)\n if (didInstall) {\n return\n }\n\n const autoUpdatesEnabled = shouldAutoUpdate({flags, cliConfig})\n\n if (autoUpdatesEnabled) {\n // Get the clean version without build metadata: https://semver.org/#spec-item-10\n const cleanSanityVersion = semver.parse(installedSanityVersion)?.version\n if (!cleanSanityVersion) {\n throw new Error(`Failed to parse installed Sanity version: ${installedSanityVersion}`)\n }\n\n const sanityDependencies = [\n {name: 'sanity', version: cleanSanityVersion},\n {name: '@sanity/vision', version: cleanSanityVersion},\n ]\n const appId = getAppId({cliConfig, output})\n\n output.print(`${info} Running with auto-updates enabled`)\n if (!appId) {\n warnAboutMissingAppId({\n appType: 'studio',\n cliConfigPath,\n output,\n projectId: cliConfig?.api?.projectId,\n })\n }\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir, {appId})\n } catch (err) {\n console.warn(\n new Error('Failed to compare local versions against auto-updating versions', {\n cause: err,\n }),\n )\n }\n if (result?.length) {\n const message =\n `The following local package versions are different from the versions currently served at runtime.\\n` +\n `When using auto updates, we recommend that you run with the same versions locally as will be used when deploying. \\n\\n` +\n `${result.map((mod) => ` - ${mod.pkg} (local version: ${mod.installed}, runtime version: ${mod.remote})`).join('\\n')} \\n\\n`\n\n // mismatch between local and auto-updating dependencies\n if (isInteractive) {\n const shouldUpgrade = await prompt.single({\n type: 'confirm',\n message: chalk.yellow(`${message}Do you want to upgrade local versions?`),\n default: true,\n })\n if (shouldUpgrade) {\n await upgradePackages(\n {\n packageManager: (await getPackageManagerChoice(workDir, {interactive: false})).chosen,\n packages: result.map((res) => [res.pkg, res.remote]),\n },\n context,\n )\n }\n } else {\n // In this case we warn the user but we don't ask them if they want to upgrade because it's not interactive.\n output.print(chalk.yellow(message))\n }\n }\n }\n\n // Try to load CLI configuration from sanity.cli.(js|ts)\n const config = getDevServerConfig({flags, workDir, cliConfig, output})\n\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined | null\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard')\n process.exit(1)\n }\n\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n })\n\n try {\n const project = await client.request<SanityProject>({uri: `/projects/${projectId}`})\n organizationId = project.organizationId\n } catch (err) {\n debug(`Failed to get organization Id from project Id: ${err}`)\n output.error('Failed to get organization Id from project Id')\n process.exit(1)\n }\n }\n\n try {\n const startTime = Date.now()\n const spinner = output.spinner('Starting dev server').start()\n const {server} = await startDevServer({...config})\n\n const {info: loggerInfo} = server.config.logger\n const {port} = server.config.server\n const httpHost = config.httpHost || 'localhost'\n\n spinner.succeed()\n\n if (loadInDashboard) {\n if (!organizationId) {\n output.error('Organization Id not found for project')\n process.exit(1)\n }\n\n output.print(`Dev server started on ${config.httpPort} port`)\n output.print(`View your app in the Sanity dashboard here:`)\n output.print(\n chalk.blue(\n chalk.underline(\n await getDashboardAppURL({\n organizationId,\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n }),\n ),\n ),\n )\n } else {\n const startupDuration = Date.now() - startTime\n const url = `http://${httpHost || 'localhost'}:${port}${config.basePath}`\n const appType = 'Sanity Studio'\n\n loggerInfo(\n `${appType} ` +\n `using ${chalk.cyan(`vite@${require('vite/package.json').version}`)} ` +\n `ready in ${chalk.cyan(`${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${chalk.cyan(url)}`,\n )\n }\n } catch (err) {\n debug(`Failed to start dev server: ${err}`)\n gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n\nexport function getDevServerConfig({\n flags,\n workDir,\n cliConfig,\n output,\n}: {\n flags: {host?: string; port?: number}\n workDir: string\n cliConfig?: CliConfig\n output: CliOutputter\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = output.spinner('Checking configuration files...')\n const baseConfig = getSharedServerConfig({\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n cliConfig,\n })\n configSpinner.succeed()\n\n const env = process.env\n const reactStrictMode = env.SANITY_STUDIO_REACT_STRICT_MODE\n ? env.SANITY_STUDIO_REACT_STRICT_MODE === 'true'\n : Boolean(cliConfig?.reactStrictMode)\n\n if (env.SANITY_STUDIO_BASEPATH && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${env.SANITY_STUDIO_BASEPATH})`,\n )\n }\n\n return {\n ...baseConfig,\n staticPath: path.join(workDir, 'static'),\n reactStrictMode,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n }\n}\n"],"names":["startDevServer","options","cwd","httpPort","httpHost","basePath","reactStrictMode","vite","extendViteConfig","reactCompiler","entry","isApp","debug","writeSanityRuntime","watch","mode","viteConfig","getViteConfig","server","port","host","extendViteConfigWithUserConfig","command","createServer","listen","close","debugIt","extend","baseUrl","process","env","SANITY_INTERNAL_ENV","getDefaultDashboardURL","organizationId","url","URLSearchParams","toString","getDashboardURL","fetchFn","globalThis","fetch","timeout","abortController","AbortController","timer","setTimeout","abort","queryParams","res","signal","ok","json","statusText","err","message","clearTimeout","getDashboardAppURL","parseCliFlags","args","yargs","hideBin","argv","slice","type","option","default","startSanityDevServer","context","timers","getTimer","flags","output","apiClient","workDir","cliConfig","prompt","cliConfigPath","loadInDashboard","start","checkStudioDependencyVersions","end","checkRequiredDependencies","didInstall","installedSanityVersion","shouldAutoUpdate","cleanSanityVersion","semver","parse","version","Error","sanityDependencies","name","appId","getAppId","print","info","warnAboutMissingAppId","appType","projectId","api","result","compareDependencyVersions","console","warn","cause","length","map","mod","pkg","installed","remote","join","isInteractive","single","chalk","yellow","upgradePackages","packageManager","getPackageManagerChoice","interactive","chosen","packages","config","getDevServerConfig","error","exit","client","requireUser","requireProject","request","uri","startTime","Date","now","spinner","loggerInfo","logger","succeed","blue","underline","startupDuration","cyan","require","Math","ceil","gracefulServerDeath","configSpinner","baseConfig","getSharedServerConfig","SANITY_STUDIO_REACT_STRICT_MODE","Boolean","SANITY_STUDIO_BASEPATH","project","staticPath","path","undefined"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,eAAsBA,eAAeC,SAA+C;AAClF,QAAM;AAAA,IACJC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,IACAC,MAAMC;AAAAA,IACNC;AAAAA,IACAC;AAAAA,IACAC;AAAAA,EAAAA,IACEV;AAEJW,gBAAM,8BAA8B,GACpC,MAAMC,2BAAmB;AAAA,IAACX;AAAAA,IAAKI;AAAAA,IAAiBQ,OAAO;AAAA,IAAMT;AAAAA,IAAUK;AAAAA,IAAOC;AAAAA,EAAAA,CAAM,GAEpFC,QAAAA,MAAM,uBAAuB;AAC7B,QAAMG,OAAO;AAEb,MAAIC,aAAa,MAAMC,sBAAc;AAAA,IACnCZ;AAAAA,IACAU,MAAM;AAAA,IACNG,QAAQ;AAAA,MAACC,MAAMhB;AAAAA,MAAUiB,MAAMhB;AAAAA,IAAAA;AAAAA,IAC/BF;AAAAA,IACAO;AAAAA,IACAE;AAAA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AAA,IAEdsD;AAAAA,IACAC;AAAAA,EAAAA,CACD;AACDwE,gBAAcT,QAAAA;AAEd,QAAM3G,MAAMD,QAAQC,KACdxB,kBAAkBwB,IAAIuH,kCACxBvH,IAAIuH,oCAAoC,SACxCC,CAAAA,CAAQ5E,WAAWpE;AAEvB,SAAIwB,IAAIyH,0BAA0B7E,WAAW8E,SAASnJ,YACpDkE,OAAOgC,KACL,oCAAoC7B,UAAU8E,QAAQnJ,QAAQ,2CAA2CyB,IAAIyH,sBAAsB,GACrI,GAGK;AAAA,IACL,GAAGJ;AAAAA,IACHM,YAAYC,cAAAA,QAAK3C,KAAKtC,SAAS,QAAQ;AAAA,IACvCnE;AAAAA,IACAG,eAAeiE,aAAa,mBAAmBA,YAAYA,UAAUjE,gBAAgBkJ;AAAAA,EAAAA;AAEzF;;;;;;;;;;;;"}
|
@@ -0,0 +1,23 @@
|
|
1
|
+
"use strict";
|
2
|
+
var chalk = require("chalk");
|
3
|
+
function _interopDefaultCompat(e) {
|
4
|
+
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
5
|
+
}
|
6
|
+
var chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk);
|
7
|
+
function getAppId({
|
8
|
+
cliConfig,
|
9
|
+
output
|
10
|
+
}) {
|
11
|
+
const hasOldCliConfigFlag = cliConfig && "app" in cliConfig && cliConfig.app && "id" in cliConfig.app, hasNewCliConfigFlag = cliConfig && "deployment" in cliConfig && cliConfig.deployment && "appId" in cliConfig.deployment;
|
12
|
+
if (hasOldCliConfigFlag && hasNewCliConfigFlag)
|
13
|
+
throw new Error("Found both `app.id` (deprecated) and `deployment.appId` in sanity.cli.js. Please remove the deprecated `app.id`.");
|
14
|
+
const appId = hasOldCliConfigFlag ? cliConfig.app?.id : cliConfig?.deployment?.appId;
|
15
|
+
return hasOldCliConfigFlag && output?.warn(chalk__default.default.yellow(`The \`app.id\` config has moved to \`deployment.appId\`.
|
16
|
+
Please update \`sanity.cli.ts\` or \`sanity.cli.js\` and move:
|
17
|
+
${chalk__default.default.red(`app: {id: "${appId}", ... }`)}
|
18
|
+
to
|
19
|
+
${chalk__default.default.green(`deployment: {appId: "${appId}", ... }}`)})
|
20
|
+
`)), appId;
|
21
|
+
}
|
22
|
+
exports.getAppId = getAppId;
|
23
|
+
//# sourceMappingURL=getAppId.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"getAppId.js","sources":["../../src/_internal/cli/util/getAppId.ts"],"sourcesContent":["import {type CliConfig} from '@sanity/cli'\nimport chalk from 'chalk'\n\ninterface Options {\n cliConfig?: CliConfig\n output?: {warn: (message: string) => void}\n}\n\n/**\n * Gets appId from sanity.cli.config.ts/js\n * @param options - Options\n * @returns boolean\n * @internal\n */\nexport function getAppId({cliConfig, output}: Options): string | undefined {\n const hasOldCliConfigFlag =\n cliConfig && 'app' in cliConfig && cliConfig.app && 'id' in cliConfig.app\n\n const hasNewCliConfigFlag =\n cliConfig &&\n 'deployment' in cliConfig &&\n cliConfig.deployment &&\n 'appId' in cliConfig.deployment\n\n if (hasOldCliConfigFlag && hasNewCliConfigFlag) {\n throw new Error(\n 'Found both `app.id` (deprecated) and `deployment.appId` in sanity.cli.js. Please remove the deprecated `app.id`.',\n )\n }\n const appId = hasOldCliConfigFlag ? cliConfig.app?.id : cliConfig?.deployment?.appId\n\n if (hasOldCliConfigFlag) {\n output?.warn(\n chalk.yellow(\n `The \\`app.id\\` config has moved to \\`deployment.appId\\`.\nPlease update \\`sanity.cli.ts\\` or \\`sanity.cli.js\\` and move:\n${chalk.red(`app: {id: \"${appId}\", ... }`)}\nto\n${chalk.green(`deployment: {appId: \"${appId}\", ... }}`)})\n`,\n ),\n )\n }\n return appId\n}\n"],"names":["getAppId","cliConfig","output","hasOldCliConfigFlag","app","hasNewCliConfigFlag","deployment","Error","appId","id","warn","chalk","yellow","red","green"],"mappings":";;;;;;AAcO,SAASA,SAAS;AAAA,EAACC;AAAAA,EAAWC;AAAe,GAAuB;AACzE,QAAMC,sBACJF,aAAa,SAASA,aAAaA,UAAUG,OAAO,QAAQH,UAAUG,KAElEC,sBACJJ,aACA,gBAAgBA,aAChBA,UAAUK,cACV,WAAWL,UAAUK;AAEvB,MAAIH,uBAAuBE;AACzB,UAAM,IAAIE,MACR,kHACF;AAEF,QAAMC,QAAQL,sBAAsBF,UAAUG,KAAKK,KAAKR,WAAWK,YAAYE;AAE/E,SAAIL,uBACFD,QAAQQ,KACNC,eAAAA,QAAMC,OACJ;AAAA;AAAA,EAEND,eAAAA,QAAME,IAAI,cAAcL,KAAK,UAAU,CAAC;AAAA;AAAA,EAExCG,eAAAA,QAAMG,MAAM,wBAAwBN,KAAK,WAAW,CAAC;AAAA,CAEjD,CACF,GAEKA;AACT;;"}
|
@@ -21,9 +21,7 @@ async function getUserApplication({
|
|
21
21
|
appId
|
22
22
|
}) {
|
23
23
|
let query, uri = "/user-applications";
|
24
|
-
appId ?
|
25
|
-
appType: "coreApp"
|
26
|
-
}) : appHost ? query = {
|
24
|
+
appId ? uri = `/user-applications/${appId}` : appHost ? query = {
|
27
25
|
appHost
|
28
26
|
} : query = {
|
29
27
|
default: "true"
|
@@ -202,16 +200,20 @@ async function getOrCreateStudioFromConfig({
|
|
202
200
|
client,
|
203
201
|
context,
|
204
202
|
spinner,
|
205
|
-
appHost
|
203
|
+
appHost,
|
204
|
+
appId
|
206
205
|
}) {
|
207
206
|
const {
|
208
207
|
output
|
209
208
|
} = context, existingUserApplication = await getUserApplication({
|
210
209
|
client,
|
210
|
+
appId,
|
211
211
|
appHost
|
212
212
|
});
|
213
213
|
if (spinner.succeed(), existingUserApplication)
|
214
214
|
return existingUserApplication;
|
215
|
+
if (!appHost)
|
216
|
+
throw new Error(`Application not found. Application with id ${appId} does not exist`);
|
215
217
|
output.print("Your project has not been assigned a studio hostname."), output.print(`Creating https://${appHost}.sanity.studio`), output.print(""), spinner.start("Creating studio hostname");
|
216
218
|
try {
|
217
219
|
const response = await createUserApplication(client, {
|
@@ -228,6 +230,7 @@ async function getOrCreateAppFromConfig({
|
|
228
230
|
client,
|
229
231
|
context,
|
230
232
|
spinner,
|
233
|
+
appHost,
|
231
234
|
appId
|
232
235
|
}) {
|
233
236
|
const {
|
@@ -236,7 +239,8 @@ async function getOrCreateAppFromConfig({
|
|
236
239
|
if (appId) {
|
237
240
|
const existingUserApplication = await getUserApplication({
|
238
241
|
client,
|
239
|
-
appId
|
242
|
+
appId,
|
243
|
+
appHost
|
240
244
|
});
|
241
245
|
if (spinner.succeed(), existingUserApplication)
|
242
246
|
return existingUserApplication;
|
@@ -249,16 +253,15 @@ async function getOrCreateAppFromConfig({
|
|
249
253
|
}
|
250
254
|
async function getOrCreateUserApplicationFromConfig(options) {
|
251
255
|
const {
|
252
|
-
context
|
256
|
+
context,
|
257
|
+
appId,
|
258
|
+
appHost
|
253
259
|
} = options;
|
254
260
|
if (_internal.determineIsApp(context.cliConfig))
|
255
261
|
return getOrCreateAppFromConfig(options);
|
256
|
-
if (!
|
257
|
-
throw new Error("Studio
|
258
|
-
return getOrCreateStudioFromConfig(
|
259
|
-
...options,
|
260
|
-
appHost: options.appHost
|
261
|
-
});
|
262
|
+
if (!appId && !appHost)
|
263
|
+
throw new Error("Studio was detected, but neither appId or appHost (deprecated) found in CLI config");
|
264
|
+
return getOrCreateStudioFromConfig(options);
|
262
265
|
}
|
263
266
|
async function createDeployment({
|
264
267
|
client,
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"helpers.js","sources":["../../src/_internal/cli/actions/deploy/helpers.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type CliCommandContext, type CliOutputter} from '@sanity/cli'\nimport {type SanityClient} from '@sanity/client'\nimport FormData from 'form-data'\nimport {customAlphabet} from 'nanoid'\nimport readPkgUp from 'read-pkg-up'\n\nimport {debug as debugIt} from '../../debug'\nimport {determineIsApp} from '../../util/determineIsApp'\n\nexport const debug = debugIt.extend('deploy')\n\n// TODO: replace with `Promise.withResolvers()` once it lands in node\nfunction promiseWithResolvers<T>() {\n let resolve!: (t: T) => void\n let reject!: (err: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return {promise, resolve, reject}\n}\n\nexport interface ActiveDeployment {\n deployedAt: string\n deployedBy: string\n isActiveDeployment: boolean\n isAutoUpdating: boolean | null\n size: string | null\n createdAt: string\n updatedAt: string\n version: string\n}\n\nexport interface UserApplication {\n id: string\n projectId: string | null\n organizationId: string | null\n title: string | null\n appHost: string\n urlType: 'internal' | 'external'\n createdAt: string\n updatedAt: string\n type: 'studio' | 'coreApp'\n activeDeployment?: ActiveDeployment | null\n}\n\nexport interface GetUserApplicationsOptions {\n client: SanityClient\n organizationId?: string\n}\n\nexport interface GetUserApplicationOptions extends GetUserApplicationsOptions {\n appHost?: string\n appId?: string\n}\nexport async function getUserApplication({\n client,\n appHost,\n appId,\n}: GetUserApplicationOptions): Promise<UserApplication | null> {\n let query\n let uri = '/user-applications'\n if (appId) {\n uri = `/user-applications/${appId}`\n query = {appType: 'coreApp'}\n } else if (appHost) {\n query = {appHost}\n } else {\n query = {default: 'true'}\n }\n try {\n return await client.request({uri, query})\n } catch (e) {\n if (e?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user application', e)\n throw e\n }\n}\nexport async function getUserApplications({\n client,\n organizationId,\n}: GetUserApplicationsOptions): Promise<UserApplication[] | null> {\n const query: Record<string, string> = organizationId\n ? {organizationId: organizationId, appType: 'coreApp'}\n : {appType: 'studio'}\n try {\n return await client.request({\n uri: '/user-applications',\n query,\n })\n } catch (e) {\n if (e?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user applications', e)\n throw e\n }\n}\n\nfunction createUserApplication(\n client: SanityClient,\n body: Pick<UserApplication, 'appHost' | 'urlType' | 'type'> & {\n title?: string\n },\n organizationId?: string,\n): Promise<UserApplication> {\n const query: Record<string, string> = organizationId\n ? {organizationId: organizationId, appType: 'coreApp'}\n : {appType: 'studio'}\n return client.request({uri: '/user-applications', method: 'POST', body, query})\n}\n\ninterface SelectApplicationOptions {\n client: SanityClient\n prompt: GetOrCreateUserApplicationOptions['context']['prompt']\n message: string\n createNewLabel: string\n organizationId?: string\n}\n\n/**\n * Shared utility for selecting an existing application or opting to create a new one\n * @internal\n */\nasync function selectExistingApplication({\n client,\n prompt,\n message,\n createNewLabel,\n organizationId,\n}: SelectApplicationOptions): Promise<UserApplication | null> {\n const userApplications = await getUserApplications({client, organizationId})\n\n if (!userApplications?.length) {\n return null\n }\n\n const choices = userApplications.map((app) => ({\n value: app.appHost,\n name: app.title ?? app.appHost,\n }))\n\n const selected = await prompt.single({\n message,\n type: 'list',\n choices: [...choices, new prompt.Separator(), {value: 'new', name: createNewLabel}],\n })\n\n if (selected === 'new') {\n return null\n }\n\n return userApplications.find((app) => app.appHost === selected)!\n}\n\nexport interface GetOrCreateUserApplicationOptions {\n client: SanityClient\n context: Pick<CliCommandContext, 'output' | 'prompt' | 'cliConfig'>\n spinner: ReturnType<CliOutputter['spinner']>\n}\n\n/**\n * These functions handle the logic for managing user applications when\n * studioHost is not provided in the CLI config.\n *\n * @internal\n *\n * +-------------------------------+\n * | Fetch Existing user-app? |\n * +---------+--------------------+\n * |\n * +-----+-----+\n * | |\n * v v\n * +---------+ +-------------------------+\n * | Return | | Fetch all user apps |\n * | user-app| +-------------------------+\n * +---------+ |\n * v\n * +---------------------------+\n * | User apps found? |\n * +-----------+---------------+\n * |\n * +------v------+\n * | |\n * v v\n * +--------------------+ +------------------------+\n * | Show list and | | Prompt for hostname |\n * | prompt selection | | and create new app |\n * +--------------------+ +------------------------+\n */\nexport async function getOrCreateStudio({\n client,\n spinner,\n context,\n}: GetOrCreateUserApplicationOptions): Promise<UserApplication> {\n const {output, prompt} = context\n // if there is already an existing user-app, then just return it\n const existingUserApplication = await getUserApplication({client})\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n\n const selectedApp = await selectExistingApplication({\n client,\n prompt,\n message: 'Select existing studio hostname',\n createNewLabel: 'Create new studio hostname',\n })\n\n if (selectedApp) {\n return selectedApp\n }\n\n // otherwise, prompt the user for a hostname\n output.print('Your project has not been assigned a studio hostname.')\n output.print('To deploy your Sanity Studio to our hosted sanity.studio service,')\n output.print('you will need one. Please enter the part you want to use.')\n\n const {promise, resolve} = promiseWithResolvers<UserApplication>()\n\n await prompt.single({\n type: 'input',\n filter: (inp: string) => inp.replace(/\\.sanity\\.studio$/i, ''),\n message: 'Studio hostname (<value>.sanity.studio):',\n // if a string is returned here, it is relayed to the user and prompt allows\n // the user to try again until this function returns true\n validate: async (appHost: string) => {\n try {\n const response = await createUserApplication(client, {\n appHost,\n urlType: 'internal',\n type: 'studio',\n })\n resolve(response)\n return true\n } catch (e) {\n // if the name is taken, it should return a 409 so we relay to the user\n if ([402, 409].includes(e?.statusCode)) {\n return e?.response?.body?.message || 'Bad request' // just in case\n }\n\n debug('Error creating user application', e)\n // otherwise, it's a fatal error\n throw e\n }\n },\n })\n\n return await promise\n}\n\n/**\n * Creates a core application with an auto-generated hostname\n *\n * @internal\n */\nexport async function getOrCreateApplication({\n client,\n context,\n spinner,\n}: GetOrCreateUserApplicationOptions): Promise<UserApplication> {\n const {prompt, cliConfig} = context\n const organizationId = cliConfig && 'app' in cliConfig && cliConfig.app?.organizationId\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n const selectedApp = await selectExistingApplication({\n client,\n prompt,\n message: 'Select an existing deployed application',\n createNewLabel: 'Create new deployed application',\n organizationId: organizationId || undefined,\n })\n\n if (selectedApp) {\n return selectedApp\n }\n\n // First get the title from the user\n const title = await prompt.single({\n type: 'input',\n message: 'Enter a title for your application:',\n validate: (input: string) => input.length > 0 || 'Title is required',\n })\n\n const {promise, resolve, reject} = promiseWithResolvers<UserApplication>()\n\n // Try to create the application, retrying with new hostnames if needed\n const tryCreateApp = async () => {\n // appHosts have some restrictions (no uppercase, must start with a letter)\n const generateId = () => {\n const letters = 'abcdefghijklmnopqrstuvwxyz'\n const firstChar = customAlphabet(letters, 1)()\n const rest = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 11)()\n return `${firstChar}${rest}`\n }\n\n // we will likely prepend this with an org ID or other parameter in the future\n const appHost = generateId()\n\n try {\n const response = await createUserApplication(\n client,\n {\n appHost,\n urlType: 'internal',\n title,\n type: 'coreApp',\n },\n organizationId || undefined,\n )\n resolve(response)\n return true\n } catch (e) {\n // if the name is taken, generate a new one and try again\n if ([402, 409].includes(e?.statusCode)) {\n debug('App host taken, retrying with new host')\n return tryCreateApp()\n }\n\n debug('Error creating core application', e)\n reject(e)\n // otherwise, it's a fatal error\n throw e\n }\n }\n\n spinner.start('Creating application')\n\n await tryCreateApp()\n const response = await promise\n\n spinner.succeed()\n return response\n}\n\nexport interface BaseConfigOptions {\n client: SanityClient\n context: Pick<CliCommandContext, 'output' | 'prompt' | 'cliConfig'>\n spinner: ReturnType<CliOutputter['spinner']>\n}\n\ninterface StudioConfigOptions extends BaseConfigOptions {\n appHost: string\n}\n\ninterface AppConfigOptions extends BaseConfigOptions {\n appId?: string\n}\n\nasync function getOrCreateStudioFromConfig({\n client,\n context,\n spinner,\n appHost,\n}: StudioConfigOptions): Promise<UserApplication> {\n const {output} = context\n // if there is already an existing user-app, then just return it\n const existingUserApplication = await getUserApplication({client, appHost})\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n\n output.print('Your project has not been assigned a studio hostname.')\n output.print(`Creating https://${appHost}.sanity.studio`)\n output.print('')\n spinner.start('Creating studio hostname')\n\n try {\n const response = await createUserApplication(client, {\n appHost,\n urlType: 'internal',\n type: 'studio',\n })\n spinner.succeed()\n return response\n } catch (e) {\n spinner.fail()\n // if the name is taken, it should return a 409 so we relay to the user\n if ([402, 409].includes(e?.statusCode)) {\n throw new Error(e?.response?.body?.message || 'Bad request') // just in case\n }\n debug('Error creating user application from config', e)\n // otherwise, it's a fatal error\n throw e\n }\n}\n\nasync function getOrCreateAppFromConfig({\n client,\n context,\n spinner,\n appId,\n}: AppConfigOptions): Promise<UserApplication> {\n const {output, cliConfig} = context\n const organizationId = cliConfig && 'app' in cliConfig && cliConfig.app?.organizationId\n if (appId) {\n const existingUserApplication = await getUserApplication({\n client,\n appId,\n organizationId: organizationId || undefined,\n })\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n }\n\n // custom apps cannot arbitrarily create ids or hosts, so send them to create option\n output.print('The id provided in your configuration is not recognized.')\n output.print('Checking existing applications...')\n return getOrCreateApplication({client, context, spinner})\n}\n\n/**\n * This function handles the logic for managing user applications when\n * studioHost or appId is provided in the CLI config.\n *\n * @internal\n */\nexport async function getOrCreateUserApplicationFromConfig(\n options: BaseConfigOptions & {\n appHost?: string\n appId?: string\n },\n): Promise<UserApplication> {\n const {context} = options\n const isApp = determineIsApp(context.cliConfig)\n\n if (isApp) {\n return getOrCreateAppFromConfig(options)\n }\n\n if (!options.appHost) {\n throw new Error('Studio host was detected, but is invalid')\n }\n\n return getOrCreateStudioFromConfig({...options, appHost: options.appHost})\n}\n\nexport interface CreateDeploymentOptions {\n client: SanityClient\n applicationId: string\n version: string\n isAutoUpdating: boolean\n tarball: Gzip\n isApp?: boolean\n}\n\nexport async function createDeployment({\n client,\n tarball,\n applicationId,\n isAutoUpdating,\n version,\n isApp,\n}: CreateDeploymentOptions): Promise<{location: string}> {\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n formData.append('version', version)\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n\n return client.request({\n uri: `/user-applications/${applicationId}/deployments`,\n method: 'POST',\n headers: formData.getHeaders(),\n body: formData.pipe(new PassThrough()),\n query: isApp ? {appType: 'coreApp'} : {appType: 'studio'},\n })\n}\n\nexport interface DeleteUserApplicationOptions {\n client: SanityClient\n applicationId: string\n appType: 'coreApp' | 'studio'\n}\n\nexport async function deleteUserApplication({\n applicationId,\n client,\n appType,\n}: DeleteUserApplicationOptions): Promise<void> {\n await client.request({\n uri: `/user-applications/${applicationId}`,\n query: {\n appType,\n },\n method: 'DELETE',\n })\n}\n\nexport async function getInstalledSanityVersion(): Promise<string> {\n const sanityPkgPath = (await readPkgUp({cwd: __dirname}))?.path\n if (!sanityPkgPath) {\n throw new Error('Unable to resolve `sanity` module root')\n }\n\n const pkg = JSON.parse(await fs.readFile(sanityPkgPath, 'utf-8'))\n if (typeof pkg?.version !== 'string') {\n throw new Error('Unable to find version of `sanity` module')\n }\n return pkg.version\n}\n\nexport async function dirIsEmptyOrNonExistent(sourceDir: string): Promise<boolean> {\n try {\n const stats = await fs.stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`Directory ${sourceDir} is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n return true\n }\n\n throw err\n }\n\n const content = await fs.readdir(sourceDir)\n return content.length === 0\n}\n\nexport async function checkDir(sourceDir: string): Promise<void> {\n try {\n const stats = await fs.stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`Directory ${sourceDir} is not a directory`)\n }\n } catch (err) {\n const error = err.code === 'ENOENT' ? new Error(`Directory \"${sourceDir}\" does not exist`) : err\n\n throw error\n }\n\n try {\n await fs.stat(path.join(sourceDir, 'index.html'))\n } catch (err) {\n const error =\n err.code === 'ENOENT'\n ? new Error(\n [\n `\"${sourceDir}/index.html\" does not exist -`,\n '[SOURCE_DIR] must be a directory containing',\n 'a Sanity studio built using \"sanity build\"',\n ].join(' '),\n )\n : err\n\n throw error\n }\n}\n"],"names":["debug","debugIt","extend","promiseWithResolvers","resolve","reject","promise","Promise","res","rej","getUserApplication","client","appHost","appId","query","uri","appType","default","request","e","statusCode","getUserApplications","organizationId","createUserApplication","body","method","selectExistingApplication","prompt","message","createNewLabel","userApplications","length","choices","map","app","value","name","title","selected","single","type","Separator","find","getOrCreateStudio","spinner","context","output","existingUserApplication","succeed","selectedApp","print","filter","inp","replace","validate","response","urlType","includes","getOrCreateApplication","cliConfig","undefined","input","tryCreateApp","generateId","firstChar","customAlphabet","rest","start","getOrCreateStudioFromConfig","fail","Error","getOrCreateAppFromConfig","getOrCreateUserApplicationFromConfig","options","determineIsApp","createDeployment","tarball","applicationId","isAutoUpdating","version","isApp","formData","FormData","append","toString","contentType","filename","headers","getHeaders","pipe","PassThrough","deleteUserApplication","getInstalledSanityVersion","sanityPkgPath","readPkgUp","cwd","__dirname","path","pkg","JSON","parse","fs","readFile","dirIsEmptyOrNonExistent","sourceDir","stat","isDirectory","err","code","readdir","checkDir","join"],"mappings":";;;;;;AAcO,MAAMA,QAAQC,UAAAA,MAAQC,OAAO,QAAQ;AAG5C,SAASC,uBAA0B;AACjC,MAAIC,SACAC;AAKJ,SAAO;AAAA,IAACC,SAJQ,IAAIC,QAAW,CAACC,KAAKC,QAAQ;AAC3CL,gBAAUI,KACVH,SAASI;AAAAA,IACX,CAAC;AAAA,IACgBL;AAAAA,IAASC;AAAAA,EAAAA;AAC5B;AAmCA,eAAsBK,mBAAmB;AAAA,EACvCC;AAAAA,EACAC;AAAAA,EACAC;AACyB,GAAoC;AAC7D,MAAIC,OACAC,MAAM;AACNF,WACFE,MAAM,sBAAsBF,KAAK,IACjCC,QAAQ;AAAA,IAACE,SAAS;AAAA,EAAA,KACTJ,UACTE,QAAQ;AAAA,IAACF;AAAAA,EAAAA,IAETE,QAAQ;AAAA,IAACG,SAAS;AAAA,EAAA;AAEpB,MAAI;AACF,WAAO,MAAMN,OAAOO,QAAQ;AAAA,MAACH;AAAAA,MAAKD;AAAAA,IAAAA,CAAM;AAAA,EAC1C,SAASK,GAAG;AACV,QAAIA,GAAGC,eAAe;AACpB,aAAO;AAGTpB,UAAAA,MAAM,kCAAkCmB,CAAC,GACnCA;AAAAA,EACR;AACF;AACA,eAAsBE,oBAAoB;AAAA,EACxCV;AAAAA,EACAW;AAC0B,GAAsC;AAChE,QAAMR,QAAgCQ,iB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ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\nimport {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type CliCommandContext, type CliOutputter} from '@sanity/cli'\nimport {type SanityClient} from '@sanity/client'\nimport FormData from 'form-data'\nimport {customAlphabet} from 'nanoid'\nimport readPkgUp from 'read-pkg-up'\n\nimport {debug as debugIt} from '../../debug'\nimport {determineIsApp} from '../../util/determineIsApp'\n\nexport const debug = debugIt.extend('deploy')\n\n// TODO: replace with `Promise.withResolvers()` once it lands in node\nfunction promiseWithResolvers<T>() {\n let resolve!: (t: T) => void\n let reject!: (err: unknown) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return {promise, resolve, reject}\n}\n\nexport interface ActiveDeployment {\n deployedAt: string\n deployedBy: string\n isActiveDeployment: boolean\n isAutoUpdating: boolean | null\n size: string | null\n createdAt: string\n updatedAt: string\n version: string\n}\n\nexport interface UserApplication {\n id: string\n projectId: string | null\n organizationId: string | null\n title: string | null\n appHost: string\n urlType: 'internal' | 'external'\n createdAt: string\n updatedAt: string\n type: 'studio' | 'coreApp'\n activeDeployment?: ActiveDeployment | null\n}\n\nexport interface GetUserApplicationsOptions {\n client: SanityClient\n organizationId?: string\n}\n\nexport interface GetUserApplicationOptions extends GetUserApplicationsOptions {\n appHost?: string\n appId?: string\n}\nexport async function getUserApplication({\n client,\n appHost,\n appId,\n}: GetUserApplicationOptions): Promise<UserApplication | null> {\n let query\n let uri = '/user-applications'\n if (appId) {\n uri = `/user-applications/${appId}`\n } else if (appHost) {\n query = {appHost}\n } else {\n query = {default: 'true'}\n }\n try {\n return await client.request({uri, query})\n } catch (e) {\n if (e?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user application', e)\n throw e\n }\n}\nexport async function getUserApplications({\n client,\n organizationId,\n}: GetUserApplicationsOptions): Promise<UserApplication[] | null> {\n const query: Record<string, string> = organizationId\n ? {organizationId: organizationId, appType: 'coreApp'}\n : {appType: 'studio'}\n try {\n return await client.request({\n uri: '/user-applications',\n query,\n })\n } catch (e) {\n if (e?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user applications', e)\n throw e\n }\n}\n\nfunction createUserApplication(\n client: SanityClient,\n body: Pick<UserApplication, 'appHost' | 'urlType' | 'type'> & {\n title?: string\n },\n organizationId?: string,\n): Promise<UserApplication> {\n const query: Record<string, string> = organizationId\n ? {organizationId: organizationId, appType: 'coreApp'}\n : {appType: 'studio'}\n return client.request({uri: '/user-applications', method: 'POST', body, query})\n}\n\ninterface SelectApplicationOptions {\n client: SanityClient\n prompt: GetOrCreateUserApplicationOptions['context']['prompt']\n message: string\n createNewLabel: string\n organizationId?: string\n}\n\n/**\n * Shared utility for selecting an existing application or opting to create a new one\n * @internal\n */\nasync function selectExistingApplication({\n client,\n prompt,\n message,\n createNewLabel,\n organizationId,\n}: SelectApplicationOptions): Promise<UserApplication | null> {\n const userApplications = await getUserApplications({client, organizationId})\n\n if (!userApplications?.length) {\n return null\n }\n\n const choices = userApplications.map((app) => ({\n value: app.appHost,\n name: app.title ?? app.appHost,\n }))\n\n const selected = await prompt.single({\n message,\n type: 'list',\n choices: [...choices, new prompt.Separator(), {value: 'new', name: createNewLabel}],\n })\n\n if (selected === 'new') {\n return null\n }\n\n return userApplications.find((app) => app.appHost === selected)!\n}\n\nexport interface GetOrCreateUserApplicationOptions {\n client: SanityClient\n context: Pick<CliCommandContext, 'output' | 'prompt' | 'cliConfig'>\n spinner: ReturnType<CliOutputter['spinner']>\n}\n\n/**\n * These functions handle the logic for managing user applications when\n * studioHost is not provided in the CLI config.\n *\n * @internal\n *\n * +-------------------------------+\n * | Fetch Existing user-app? |\n * +---------+--------------------+\n * |\n * +-----+-----+\n * | |\n * v v\n * +---------+ +-------------------------+\n * | Return | | Fetch all user apps |\n * | user-app| +-------------------------+\n * +---------+ |\n * v\n * +---------------------------+\n * | User apps found? |\n * +-----------+---------------+\n * |\n * +------v------+\n * | |\n * v v\n * +--------------------+ +------------------------+\n * | Show list and | | Prompt for hostname |\n * | prompt selection | | and create new app |\n * +--------------------+ +------------------------+\n */\nexport async function getOrCreateStudio({\n client,\n spinner,\n context,\n}: GetOrCreateUserApplicationOptions): Promise<UserApplication> {\n const {output, prompt} = context\n // if there is already an existing user-app, then just return it\n const existingUserApplication = await getUserApplication({client})\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n\n const selectedApp = await selectExistingApplication({\n client,\n prompt,\n message: 'Select existing studio hostname',\n createNewLabel: 'Create new studio hostname',\n })\n\n if (selectedApp) {\n return selectedApp\n }\n\n // otherwise, prompt the user for a hostname\n output.print('Your project has not been assigned a studio hostname.')\n output.print('To deploy your Sanity Studio to our hosted sanity.studio service,')\n output.print('you will need one. Please enter the part you want to use.')\n\n const {promise, resolve} = promiseWithResolvers<UserApplication>()\n\n await prompt.single({\n type: 'input',\n filter: (inp: string) => inp.replace(/\\.sanity\\.studio$/i, ''),\n message: 'Studio hostname (<value>.sanity.studio):',\n // if a string is returned here, it is relayed to the user and prompt allows\n // the user to try again until this function returns true\n validate: async (appHost: string) => {\n try {\n const response = await createUserApplication(client, {\n appHost,\n urlType: 'internal',\n type: 'studio',\n })\n resolve(response)\n return true\n } catch (e) {\n // if the name is taken, it should return a 409 so we relay to the user\n if ([402, 409].includes(e?.statusCode)) {\n return e?.response?.body?.message || 'Bad request' // just in case\n }\n\n debug('Error creating user application', e)\n // otherwise, it's a fatal error\n throw e\n }\n },\n })\n\n return await promise\n}\n\n/**\n * Creates a core application with an auto-generated hostname\n *\n * @internal\n */\nexport async function getOrCreateApplication({\n client,\n context,\n spinner,\n}: GetOrCreateUserApplicationOptions): Promise<UserApplication> {\n const {prompt, cliConfig} = context\n const organizationId = cliConfig && 'app' in cliConfig && cliConfig.app?.organizationId\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n const selectedApp = await selectExistingApplication({\n client,\n prompt,\n message: 'Select an existing deployed application',\n createNewLabel: 'Create new deployed application',\n organizationId: organizationId || undefined,\n })\n\n if (selectedApp) {\n return selectedApp\n }\n\n // First get the title from the user\n const title = await prompt.single({\n type: 'input',\n message: 'Enter a title for your application:',\n validate: (input: string) => input.length > 0 || 'Title is required',\n })\n\n const {promise, resolve, reject} = promiseWithResolvers<UserApplication>()\n\n // Try to create the application, retrying with new hostnames if needed\n const tryCreateApp = async () => {\n // appHosts have some restrictions (no uppercase, must start with a letter)\n const generateId = () => {\n const letters = 'abcdefghijklmnopqrstuvwxyz'\n const firstChar = customAlphabet(letters, 1)()\n const rest = customAlphabet('abcdefghijklmnopqrstuvwxyz0123456789', 11)()\n return `${firstChar}${rest}`\n }\n\n // we will likely prepend this with an org ID or other parameter in the future\n const appHost = generateId()\n\n try {\n const response = await createUserApplication(\n client,\n {\n appHost,\n urlType: 'internal',\n title,\n type: 'coreApp',\n },\n organizationId || undefined,\n )\n resolve(response)\n return true\n } catch (e) {\n // if the name is taken, generate a new one and try again\n if ([402, 409].includes(e?.statusCode)) {\n debug('App host taken, retrying with new host')\n return tryCreateApp()\n }\n\n debug('Error creating core application', e)\n reject(e)\n // otherwise, it's a fatal error\n throw e\n }\n }\n\n spinner.start('Creating application')\n\n await tryCreateApp()\n const response = await promise\n\n spinner.succeed()\n return response\n}\n\nexport interface BaseConfigOptions {\n client: SanityClient\n context: Pick<CliCommandContext, 'output' | 'prompt' | 'cliConfig'>\n spinner: ReturnType<CliOutputter['spinner']>\n}\n\ntype UserApplicationConfigOptions = BaseConfigOptions &\n (\n | {\n /**\n * @deprecated – appHost is replaced by appId, but kept for backwards compat\n */\n appHost: string | undefined\n appId: undefined\n }\n | {\n appId: string | undefined\n /**\n * @deprecated – appHost is replaced by appId, but kept for backwards compat\n */\n appHost: undefined\n }\n )\n\nasync function getOrCreateStudioFromConfig({\n client,\n context,\n spinner,\n appHost,\n appId,\n}: UserApplicationConfigOptions): Promise<UserApplication> {\n const {output} = context\n // if there is already an existing user-app, then just return it\n const existingUserApplication = await getUserApplication({client, appId, appHost})\n\n // Complete the spinner so prompt can properly work\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n\n if (!appHost) {\n throw new Error(`Application not found. Application with id ${appId} does not exist`)\n }\n\n output.print('Your project has not been assigned a studio hostname.')\n output.print(`Creating https://${appHost}.sanity.studio`)\n output.print('')\n spinner.start('Creating studio hostname')\n\n try {\n const response = await createUserApplication(client, {\n appHost,\n urlType: 'internal',\n type: 'studio',\n })\n spinner.succeed()\n return response\n } catch (e) {\n spinner.fail()\n // if the name is taken, it should return a 409 so we relay to the user\n if ([402, 409].includes(e?.statusCode)) {\n throw new Error(e?.response?.body?.message || 'Bad request') // just in case\n }\n debug('Error creating user application from config', e)\n // otherwise, it's a fatal error\n throw e\n }\n}\n\nasync function getOrCreateAppFromConfig({\n client,\n context,\n spinner,\n appHost,\n appId,\n}: UserApplicationConfigOptions): Promise<UserApplication> {\n const {output, cliConfig} = context\n const organizationId = cliConfig && 'app' in cliConfig && cliConfig.app?.organizationId\n if (appId) {\n const existingUserApplication = await getUserApplication({\n client,\n appId,\n appHost,\n organizationId: organizationId || undefined,\n })\n spinner.succeed()\n\n if (existingUserApplication) {\n return existingUserApplication\n }\n }\n\n // custom apps cannot arbitrarily create ids or hosts, so send them to create option\n output.print('The id provided in your configuration is not recognized.')\n output.print('Checking existing applications...')\n return getOrCreateApplication({client, context, spinner})\n}\n\n/**\n * This function handles the logic for managing user applications when\n * studioHost or appId is provided in the CLI config.\n *\n * @internal\n */\nexport async function getOrCreateUserApplicationFromConfig(\n options: UserApplicationConfigOptions,\n): Promise<UserApplication> {\n const {context, appId, appHost} = options\n const isApp = determineIsApp(context.cliConfig)\n\n if (isApp) {\n return getOrCreateAppFromConfig(options)\n }\n\n if (!appId && !appHost) {\n throw new Error(\n 'Studio was detected, but neither appId or appHost (deprecated) found in CLI config',\n )\n }\n\n return getOrCreateStudioFromConfig(options)\n}\n\nexport interface CreateDeploymentOptions {\n client: SanityClient\n applicationId: string\n version: string\n isAutoUpdating: boolean\n tarball: Gzip\n isApp?: boolean\n}\n\nexport async function createDeployment({\n client,\n tarball,\n applicationId,\n isAutoUpdating,\n version,\n isApp,\n}: CreateDeploymentOptions): Promise<{location: string}> {\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n formData.append('version', version)\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n\n return client.request({\n uri: `/user-applications/${applicationId}/deployments`,\n method: 'POST',\n headers: formData.getHeaders(),\n body: formData.pipe(new PassThrough()),\n query: isApp ? {appType: 'coreApp'} : {appType: 'studio'},\n })\n}\n\nexport interface DeleteUserApplicationOptions {\n client: SanityClient\n applicationId: string\n appType: 'coreApp' | 'studio'\n}\n\nexport async function deleteUserApplication({\n applicationId,\n client,\n appType,\n}: DeleteUserApplicationOptions): Promise<void> {\n await client.request({\n uri: `/user-applications/${applicationId}`,\n query: {\n appType,\n },\n method: 'DELETE',\n })\n}\n\nexport async function getInstalledSanityVersion(): Promise<string> {\n const sanityPkgPath = (await readPkgUp({cwd: __dirname}))?.path\n if (!sanityPkgPath) {\n throw new Error('Unable to resolve `sanity` module root')\n }\n\n const pkg = JSON.parse(await fs.readFile(sanityPkgPath, 'utf-8'))\n if (typeof pkg?.version !== 'string') {\n throw new Error('Unable to find version of `sanity` module')\n }\n return pkg.version\n}\n\nexport async function dirIsEmptyOrNonExistent(sourceDir: string): Promise<boolean> {\n try {\n const stats = await fs.stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`Directory ${sourceDir} is not a directory`)\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n return true\n }\n\n throw err\n }\n\n const content = await fs.readdir(sourceDir)\n return content.length === 0\n}\n\nexport async function checkDir(sourceDir: string): Promise<void> {\n try {\n const stats = await fs.stat(sourceDir)\n if (!stats.isDirectory()) {\n throw new Error(`Directory ${sourceDir} is not a directory`)\n }\n } catch (err) {\n const error = err.code === 'ENOENT' ? new Error(`Directory \"${sourceDir}\" does not exist`) : err\n\n throw error\n }\n\n try {\n await fs.stat(path.join(sourceDir, 'index.html'))\n } catch (err) {\n const error =\n err.code === 'ENOENT'\n ? new Error(\n [\n `\"${sourceDir}/index.html\" does not exist -`,\n '[SOURCE_DIR] must be a directory containing',\n 'a Sanity studio built using \"sanity build\"',\n ].join(' '),\n )\n : err\n\n throw error\n }\n}\n"],"names":["debug","debugIt","extend","promiseWithResolvers","resolve","reject","promise","Promise","res","rej","getUserApplication","client","appHost","appId","query","uri","default","request","e","statusCode","getUserApplications","organizationId","appType","createUserApplication","body","method","selectExistingApplication","prompt","message","createNewLabel","userApplications","length","choices","map","app","value","name","title","selected","single","type","Separator","find","getOrCreateStudio","spinner","context","output","existingUserApplication","succeed","selectedApp","print","filter","inp","replace","validate","response","urlType","includes","getOrCreateApplication","cliConfig","undefined","input","tryCreateApp","generateId","firstChar","customAlphabet","rest","start","getOrCreateStudioFromConfig","Error","fail","getOrCreateAppFromConfig","getOrCreateUserApplicationFromConfig","options","determineIsApp","createDeployment","tarball","applicationId","isAutoUpdating","version","isApp","formData","FormData","append","toString","contentType","filename","headers","getHeaders","pipe","PassThrough","deleteUserApplication","getInstalledSanityVersion","sanityPkgPath","readPkgUp","cwd","__dirname","path","pkg","JSON","parse","fs","readFile","dirIsEmptyOrNonExistent","sourceDir","stat","isDirectory","err","code","readdir","checkDir","join"],"mappings":";;;;;;AAcO,MAAMA,QAAQC,UAAAA,MAAQC,OAAO,QAAQ;AAG5C,SAASC,uBAA0B;AACjC,MAAIC,SACAC;AAKJ,SAAO;AAAA,IAACC,SAJQ,IAAIC,QAAW,CAACC,KAAKC,QAAQ;AAC3CL,gBAAUI,KACVH,SAASI;AAAAA,IACX,CAAC;AAAA,IACgBL;AAAAA,IAASC;AAAAA,EAAAA;AAC5B;AAmCA,eAAsBK,mBAAmB;AAAA,EACvCC;AAAAA,EACAC;AAAAA,EACAC;AACyB,GAAoC;AAC7D,MAAIC,OACAC,MAAM;AACNF,U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D,SAAS,GAC1BE,YAAAA;AACT,YAAM,IAAIrC,MAAM,aAAamC,SAAS,qBAAqB;AAAA,EAE/D,SAASG,KAAK;AAGZ,UAFcA,IAAIC,SAAS,WAAW,IAAIvC,MAAM,cAAcmC,SAAS,kBAAkB,IAAIG;AAAAA,EAG/F;AAEA,MAAI;AACF,UAAMN,YAAAA,QAAGI,KAAKR,cAAAA,QAAKc,KAAKP,WAAW,YAAY,CAAC;AAAA,EAClD,SAASG,KAAK;AAYZ,UAVEA,IAAIC,SAAS,WACT,IAAIvC,MACF,CACE,IAAImC,SAAS,iCACb,+CACA,4CAA4C,EAC5CO,KAAK,GAAG,CACZ,IACAJ;AAAAA,EAGR;AACF;;;;;;;;;;;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
-
var _internal = require("./_internal.js"), helpers = require("./helpers.js");
|
2
|
+
var _internal = require("./_internal.js"), getAppId = require("./getAppId.js"), helpers = require("./helpers.js");
|
3
3
|
const debug = _internal.debug.extend("undeploy");
|
4
4
|
async function undeployAppAction(_, context) {
|
5
5
|
const {
|
@@ -15,7 +15,10 @@ async function undeployAppAction(_, context) {
|
|
15
15
|
apiVersion: "v2024-08-01"
|
16
16
|
});
|
17
17
|
let spinner = output.spinner("Checking application info").start();
|
18
|
-
const appId =
|
18
|
+
const appId = getAppId.getAppId({
|
19
|
+
cliConfig,
|
20
|
+
output
|
21
|
+
});
|
19
22
|
if (!appId) {
|
20
23
|
spinner.fail(), output.print("No application ID provided."), output.print("Please set id in `app` in sanity.cli.js or sanity.cli.ts."), output.print("Nothing to undeploy.");
|
21
24
|
return;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"undeployAction.js","sources":["../../src/_internal/cli/actions/app/undeployAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nimport {debug as debugIt} from '../../debug'\nimport {deleteUserApplication, getUserApplication} from '../deploy/helpers'\nimport {type UndeployStudioActionFlags} from '../deploy/undeployAction'\n\nconst debug = debugIt.extend('undeploy')\n\nexport default async function undeployAppAction(\n _: CliCommandArguments<UndeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, chalk, output, prompt, cliConfig} = context\n\n const client = apiClient({\n requireUser: true,\n requireProject: false,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n // Check that the project has an application ID\n let spinner = output.spinner('Checking application info').start()\n\n const appId = cliConfig
|
1
|
+
{"version":3,"file":"undeployAction.js","sources":["../../src/_internal/cli/actions/app/undeployAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'\n\nimport {debug as debugIt} from '../../debug'\nimport {getAppId} from '../../util/getAppId'\nimport {deleteUserApplication, getUserApplication} from '../deploy/helpers'\nimport {type UndeployStudioActionFlags} from '../deploy/undeployAction'\n\nconst debug = debugIt.extend('undeploy')\n\nexport default async function undeployAppAction(\n _: CliCommandArguments<UndeployStudioActionFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const {apiClient, chalk, output, prompt, cliConfig} = context\n\n const client = apiClient({\n requireUser: true,\n requireProject: false,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n // Check that the project has an application ID\n let spinner = output.spinner('Checking application info').start()\n\n const appId = getAppId({cliConfig, output})\n\n if (!appId) {\n spinner.fail()\n output.print(`No application ID provided.`)\n output.print('Please set id in `app` in sanity.cli.js or sanity.cli.ts.')\n output.print('Nothing to undeploy.')\n return\n }\n\n const userApplication = await getUserApplication({\n client,\n appId,\n })\n\n spinner.succeed()\n\n if (!userApplication) {\n spinner.fail()\n output.print('Application with the given ID does not exist.')\n output.print('Nothing to undeploy.')\n return\n }\n\n // Double-check\n output.print('')\n\n const shouldUndeploy = await prompt.single({\n type: 'confirm',\n default: false,\n message: `This will undeploy the following application:\n\n Title: ${chalk.yellow(userApplication.title)}\n ID: ${chalk.yellow(userApplication.id)}\n\n The application will no longer be available for any of your users if you proceed.\n\n Are you ${chalk.red('sure')} you want to undeploy?`.trim(),\n })\n\n if (!shouldUndeploy) {\n return\n }\n\n spinner = output.spinner('Undeploying application').start()\n try {\n await deleteUserApplication({\n client,\n applicationId: userApplication.id,\n appType: 'coreApp',\n })\n spinner.succeed()\n } catch (err) {\n spinner.fail()\n debug('Error undeploying application', err)\n throw err\n }\n\n output.print(\n `Application undeploy scheduled. It might take a few minutes before ${chalk.yellow(userApplication.title)} is unavailable.`,\n )\n}\n"],"names":["debug","debugIt","extend","undeployAppAction","_","context","apiClient","chalk","output","prompt","cliConfig","client","requireUser","requireProject","withConfig","apiVersion","spinner","start","appId","getAppId","fail","print","userApplication","getUserApplication","succeed","single","type","default","message","yellow","title","id","red","trim","deleteUserApplication","applicationId","appType","err"],"mappings":";;AAOA,MAAMA,QAAQC,UAAAA,MAAQC,OAAO,UAAU;AAEvC,eAA8BC,kBAC5BC,GACAC,SACe;AACf,QAAM;AAAA,IAACC;AAAAA,IAAWC;AAAAA,IAAOC;AAAAA,IAAQC;AAAAA,IAAQC;AAAAA,EAAAA,IAAaL,SAEhDM,SAASL,UAAU;AAAA,IACvBM,aAAa;AAAA,IACbC,gBAAgB;AAAA,EAAA,CACjB,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc;AAGzC,MAAIC,UAAUR,OAAOQ,QAAQ,2BAA2B,EAAEC,MAAAA;AAE1D,QAAMC,QAAQC,SAAAA,SAAS;AAAA,IAACT;AAAAA,IAAWF;AAAAA,EAAAA,CAAO;AAE1C,MAAI,CAACU,OAAO;AACVF,YAAQI,KAAAA,GACRZ,OAAOa,MAAM,6BAA6B,GAC1Cb,OAAOa,MAAM,2DAA2D,GACxEb,OAAOa,MAAM,sBAAsB;AACnC;AAAA,EACF;AAEA,QAAMC,kBAAkB,MAAMC,2BAAmB;AAAA,IAC/CZ;AAAAA,IACAO;AAAAA,EAAAA,CACD;AAID,MAFAF,QAAQQ,WAEJ,CAACF,iBAAiB;AACpBN,YAAQI,KAAAA,GACRZ,OAAOa,MAAM,+CAA+C,GAC5Db,OAAOa,MAAM,sBAAsB;AACnC;AAAA,EACF;AAkBA,MAfAb,OAAOa,MAAM,EAAE,GAeX,CAAA,CAbmB,MAAMZ,OAAOgB,OAAO;AAAA,IACzCC,MAAM;AAAA,IACNC,SAAS;AAAA,IACTC,SAAS;AAAA;AAAA,aAEArB,MAAMsB,OAAOP,gBAAgBQ,KAAK,CAAC;AAAA,aACnCvB,MAAMsB,OAAOP,gBAAgBS,EAAE,CAAC;AAAA;AAAA;AAAA;AAAA,YAIjCxB,MAAMyB,IAAI,MAAM,CAAC,yBAAyBC,KAAAA;AAAAA,EAAK,CACxD,GAMDjB;AAAAA,cAAUR,OAAOQ,QAAQ,yBAAyB,EAAEC,MAAAA;AACpD,QAAI;AACF,YAAMiB,8BAAsB;AAAA,QAC1BvB;AAAAA,QACAwB,eAAeb,gBAAgBS;AAAAA,QAC/BK,SAAS;AAAA,MAAA,CACV,GACDpB,QAAQQ,QAAAA;AAAAA,IACV,SAASa,KAAK;AACZrB,YAAAA,QAAQI,KAAAA,GACRpB,MAAM,iCAAiCqC,GAAG,GACpCA;AAAAA,IACR;AAEA7B,WAAOa,MACL,sEAAsEd,MAAMsB,OAAOP,gBAAgBQ,KAAK,CAAC,kBAC3G;AAAA,EAAA;AACF;;"}
|
@@ -1,5 +1,5 @@
|
|
1
1
|
"use strict";
|
2
|
-
var path = require("node:path"), generateHelpUrl_esm = require("./generate-help-url.esm.js"), resolveFrom = require("resolve-from"), semver = require("semver"),
|
2
|
+
var path = require("node:path"), generateHelpUrl_esm = require("./generate-help-url.esm.js"), resolveFrom = require("resolve-from"), semver = require("semver"), warnAboutMissingAppId = require("./warnAboutMissingAppId.js"), execa = require("execa"), oneline = require("oneline"), _internal = require("./_internal.js"), preferredPM = require("preferred-pm"), which = require("which");
|
3
3
|
function _interopDefaultCompat(e) {
|
4
4
|
return e && typeof e == "object" && "default" in e ? e : { default: e };
|
5
5
|
}
|
@@ -24,14 +24,14 @@ const PACKAGES = [{
|
|
24
24
|
deprecatedBelow: null
|
25
25
|
}];
|
26
26
|
async function checkStudioDependencyVersions(workDir) {
|
27
|
-
const manifest = await
|
27
|
+
const manifest = await warnAboutMissingAppId.readPackageJson(path__default.default.join(workDir, "package.json")), dependencies = {
|
28
28
|
...manifest.dependencies,
|
29
29
|
...manifest.devDependencies
|
30
30
|
}, packageInfo = PACKAGES.map(async (pkg) => {
|
31
31
|
const dependency = dependencies[pkg.name];
|
32
32
|
if (!dependency)
|
33
33
|
return !1;
|
34
|
-
const manifestPath = resolveFrom__default.default.silent(workDir, path__default.default.join(pkg.name, "package.json")), installed = semver__default.default.coerce(manifestPath ? (await
|
34
|
+
const manifestPath = resolveFrom__default.default.silent(workDir, path__default.default.join(pkg.name, "package.json")), installed = semver__default.default.coerce(manifestPath ? (await warnAboutMissingAppId.readPackageManifest(manifestPath)).version : dependency.replace(/[\D.]/g, ""));
|
35
35
|
if (!installed)
|
36
36
|
return !1;
|
37
37
|
const supported = pkg.supported.join(" || "), isUntested = !semver__default.default.satisfies(installed, supported) && semver__default.default.gtr(installed, supported), isUnsupported = !semver__default.default.satisfies(installed, supported) && !isUntested, isDeprecated = pkg.deprecatedBelow ? semver__default.default.ltr(installed, pkg.deprecatedBelow) : !1;
|
@@ -125,7 +125,7 @@ async function checkRequiredDependencies(context) {
|
|
125
125
|
const {
|
126
126
|
workDir: studioPath,
|
127
127
|
output
|
128
|
-
} = context, [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] = await Promise.all([await
|
128
|
+
} = context, [studioPackageManifest, installedStyledComponentsVersion, installedSanityVersion] = await Promise.all([await warnAboutMissingAppId.readPackageManifest(path__default.default.join(studioPath, "package.json"), defaultStudioManifestProps), await warnAboutMissingAppId.readModuleVersion(studioPath, "styled-components"), await warnAboutMissingAppId.readModuleVersion(studioPath, "sanity")]), wantedStyledComponentsVersionRange = peerDependencies["styled-components"];
|
129
129
|
if (!installedSanityVersion)
|
130
130
|
throw new Error("Failed to read the installed sanity version.");
|
131
131
|
const declaredStyledComponentsVersion = studioPackageManifest.dependencies["styled-components"] || studioPackageManifest.devDependencies["styled-components"];
|