@sanity/cli 6.0.0-alpha.13 β 6.0.0-alpha.14
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/README.md +17 -6
- package/dist/actions/build/buildApp.js +4 -3
- package/dist/actions/build/buildApp.js.map +1 -1
- package/dist/actions/build/buildStudio.js +1 -0
- package/dist/actions/build/buildStudio.js.map +1 -1
- package/dist/actions/build/buildVendorDependencies.js +15 -36
- package/dist/actions/build/buildVendorDependencies.js.map +1 -1
- package/dist/actions/build/checkRequiredDependencies.js +7 -5
- package/dist/actions/build/checkRequiredDependencies.js.map +1 -1
- package/dist/actions/build/checkStudioDependencyVersions.js +6 -6
- package/dist/actions/build/checkStudioDependencyVersions.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +2 -2
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/deploy/deployStudio.js +2 -2
- package/dist/actions/deploy/deployStudio.js.map +1 -1
- package/dist/actions/dev/startStudioDevServer.js +2 -2
- package/dist/actions/dev/startStudioDevServer.js.map +1 -1
- package/dist/actions/manifest/extractManifest.js +2 -2
- package/dist/actions/manifest/extractManifest.js.map +1 -1
- package/dist/actions/schema/extractSchema.js +7 -32
- package/dist/actions/schema/extractSchema.js.map +1 -1
- package/dist/actions/schema/extractSchemaWatcher.js +126 -0
- package/dist/actions/schema/extractSchemaWatcher.js.map +1 -0
- package/dist/actions/schema/formatSchemaValidation.js +5 -1
- package/dist/actions/schema/formatSchemaValidation.js.map +1 -1
- package/dist/actions/schema/getExtractOptions.js +16 -0
- package/dist/actions/schema/getExtractOptions.js.map +1 -0
- package/dist/actions/schema/runSchemaExtraction.js +39 -0
- package/dist/actions/schema/runSchemaExtraction.js.map +1 -0
- package/dist/actions/schema/watchExtractSchema.js +71 -0
- package/dist/actions/schema/watchExtractSchema.js.map +1 -0
- package/dist/commands/schema/extract.js +32 -4
- package/dist/commands/schema/extract.js.map +1 -1
- package/dist/server/previewServer.js +2 -2
- package/dist/server/previewServer.js.map +1 -1
- package/dist/telemetry/extractSchema.telemetry.js +5 -0
- package/dist/telemetry/extractSchema.telemetry.js.map +1 -1
- package/dist/util/compareDependencyVersions.js +3 -5
- package/dist/util/compareDependencyVersions.js.map +1 -1
- package/dist/util/getLocalPackageVersion.js +30 -22
- package/dist/util/getLocalPackageVersion.js.map +1 -1
- package/dist/util/getWorkspace.js +1 -1
- package/dist/util/getWorkspace.js.map +1 -1
- package/oclif.manifest.json +187 -165
- package/package.json +3 -4
- package/dist/util/readModuleVersion.js +0 -21
- package/dist/util/readModuleVersion.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/deployApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {styleText} from 'node:util'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_ORGANIZATION_ID} from '../../util/errorMessages.js'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/deployApp.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {styleText} from 'node:util'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_ORGANIZATION_ID} from '../../util/errorMessages.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {buildApp} from '../build/buildApp.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {extractAppManifest} from '../manifest/extractAppManifest.js'\nimport {type AppManifest} from '../manifest/types.js'\nimport {checkDir} from './checkDir.js'\nimport {createUserApplicationForApp} from './createUserApplicationForApp.js'\nimport {deployDebug} from './deployDebug.js'\nimport {findUserApplicationForApp} from './findUserApplicationForApp.js'\nimport {type DeployAppOptions} from './types.js'\n\n/**\n * Deploy a Sanity application.\n *\n * @internal\n */\nexport async function deployApp(options: DeployAppOptions) {\n const {cliConfig, flags, output, sourceDir, workDir} = options\n\n const organizationId = cliConfig.app?.organizationId\n const appId = getAppId(cliConfig)\n const isAutoUpdating = shouldAutoUpdate({cliConfig, flags, output})\n const installedSdkVersion = await getLocalPackageVersion('@sanity/sdk-react', workDir)\n\n if (!installedSdkVersion) {\n output.error(`Failed to find installed @sanity/sdk-react version`, {exit: 1})\n return\n }\n\n if (!organizationId) {\n output.error(NO_ORGANIZATION_ID, {exit: 1})\n return\n }\n\n let spin = spinner('Verifying local content...')\n\n try {\n let userApplication = await findUserApplicationForApp({\n cliConfig,\n organizationId,\n output,\n })\n\n deployDebug(`User application found`, userApplication)\n\n if (!userApplication) {\n deployDebug(`No user application found. Creating a new one`)\n\n userApplication = await createUserApplicationForApp(organizationId)\n deployDebug(`User application created`, userApplication)\n }\n\n // Warn about missing app ID if auto updates are enabled\n if (isAutoUpdating && !appId) {\n warnAboutMissingAppId({appType: 'app', output})\n }\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n deployDebug(`Building app`)\n await buildApp({\n autoUpdatesEnabled: isAutoUpdating,\n cliConfig,\n flags,\n outDir: sourceDir,\n output,\n workDir,\n })\n }\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spin = spin.start()\n try {\n await checkDir(sourceDir)\n spin.succeed()\n } catch (err) {\n spin.fail()\n deployDebug('Error checking directory', err)\n output.error('Error checking directory', {exit: 1})\n return\n }\n\n // Create a tarball of the given directory\n const parentDir = dirname(sourceDir)\n const base = basename(sourceDir)\n const tarball = pack(parentDir, {entries: [base]}).pipe(createGzip())\n let manifest: AppManifest | undefined\n try {\n manifest = await extractAppManifest({flags, workDir})\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n deployDebug('Error extracting app manifest', err)\n output.warn(`Error extracting app manifest: ${message}`)\n }\n\n spin = spinner('Deploying...').start()\n await createDeployment({\n applicationId: userApplication.id,\n isApp: true,\n isAutoUpdating,\n manifest,\n tarball,\n version: installedSdkVersion,\n })\n\n spin.succeed()\n\n // And let the user know we're done\n output.log(`\\nπ ${styleText('bold', 'Success!')} Application deployed`)\n\n if (!appId) {\n output.log(`\\nββββ ${styleText('bold', 'Next step:')} ββββ`)\n output.log(\n styleText(\n 'bold',\n '\\nAdd the deployment.appId to your sanity.cli.js or sanity.cli.ts file:',\n ),\n )\n output.log(`\n${styleText(\n 'dim',\n `app: {\n // your application config hereβ¦\n}`,\n)},\n${styleText(\n ['bold', 'green'],\n `deployment: {\n appId: '${userApplication.id}',\n}\\n`,\n)}`)\n }\n } catch (error) {\n spin.clear()\n // Don't throw generic error if user cancels\n if (error.name === 'ExitPromptError') {\n output.error('Deployment cancelled by user', {exit: 1})\n return\n }\n // If the error is a CLIError, we can just output the message & error options (if any), while ensuring we exit\n if (error instanceof CLIError) {\n const {message, ...errorOptions} = error\n output.error(message, {...errorOptions, exit: 1})\n return\n }\n\n deployDebug('Error deploying application', error)\n output.error(`Error deploying application: ${error}`, {exit: 1})\n }\n}\n"],"names":["basename","dirname","styleText","createGzip","CLIError","spinner","pack","createDeployment","getAppId","NO_ORGANIZATION_ID","getLocalPackageVersion","warnAboutMissingAppId","buildApp","shouldAutoUpdate","extractAppManifest","checkDir","createUserApplicationForApp","deployDebug","findUserApplicationForApp","deployApp","options","cliConfig","flags","output","sourceDir","workDir","organizationId","app","appId","isAutoUpdating","installedSdkVersion","error","exit","spin","userApplication","appType","shouldBuild","build","autoUpdatesEnabled","outDir","start","succeed","err","fail","parentDir","base","tarball","entries","pipe","manifest","message","Error","String","warn","applicationId","id","isApp","version","log","clear","name","errorOptions"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QA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,gBAAgBqB,EAAE;YACjCC,OAAO;YACP3B;YACAoB;YACAH;YACAW,SAAS3B;QACX;QAEAG,KAAKQ,OAAO;QAEZ,mCAAmC;QACnClB,OAAOmC,GAAG,CAAC,CAAC,KAAK,EAAExD,UAAU,QAAQ,YAAY,qBAAqB,CAAC;QAEvE,IAAI,CAAC0B,OAAO;YACVL,OAAOmC,GAAG,CAAC,CAAC,OAAO,EAAExD,UAAU,QAAQ,cAAc,KAAK,CAAC;YAC3DqB,OAAOmC,GAAG,CACRxD,UACE,QACA;YAGJqB,OAAOmC,GAAG,CAAC,CAAC;AAClB,EAAExD,UACA,OACA,CAAC;;CAEF,CAAC,EACA;AACF,EAAEA,UACA;gBAAC;gBAAQ;aAAQ,EACjB,CAAC;UACO,EAAEgC,gBAAgBqB,EAAE,CAAC;GAC5B,CAAC,GACD;QACC;IACF,EAAE,OAAOxB,OAAO;QACdE,KAAK0B,KAAK;QACV,4CAA4C;QAC5C,IAAI5B,MAAM6B,IAAI,KAAK,mBAAmB;YACpCrC,OAAOQ,KAAK,CAAC,gCAAgC;gBAACC,MAAM;YAAC;YACrD;QACF;QACA,8GAA8G;QAC9G,IAAID,iBAAiB3B,UAAU;YAC7B,MAAM,EAAC8C,OAAO,EAAE,GAAGW,cAAa,GAAG9B;YACnCR,OAAOQ,KAAK,CAACmB,SAAS;gBAAC,GAAGW,YAAY;gBAAE7B,MAAM;YAAC;YAC/C;QACF;QAEAf,YAAY,+BAA+Bc;QAC3CR,OAAOQ,KAAK,CAAC,CAAC,6BAA6B,EAAEA,OAAO,EAAE;YAACC,MAAM;QAAC;IAChE;AACF"}
|
|
@@ -7,7 +7,7 @@ import { pack } from 'tar-fs';
|
|
|
7
7
|
import { createDeployment } from '../../services/userApplications.js';
|
|
8
8
|
import { getAppId } from '../../util/appId.js';
|
|
9
9
|
import { NO_PROJECT_ID } from '../../util/errorMessages.js';
|
|
10
|
-
import {
|
|
10
|
+
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
11
11
|
import { buildStudio } from '../build/buildStudio.js';
|
|
12
12
|
import { shouldAutoUpdate } from '../build/shouldAutoUpdate.js';
|
|
13
13
|
import { checkDir } from './checkDir.js';
|
|
@@ -19,7 +19,7 @@ export async function deployStudio(options) {
|
|
|
19
19
|
const appHost = cliConfig.studioHost;
|
|
20
20
|
const appId = getAppId(cliConfig);
|
|
21
21
|
const projectId = cliConfig.api?.projectId;
|
|
22
|
-
const installedSanityVersion = await
|
|
22
|
+
const installedSanityVersion = await getLocalPackageVersion('sanity', workDir);
|
|
23
23
|
const isAutoUpdating = shouldAutoUpdate({
|
|
24
24
|
cliConfig,
|
|
25
25
|
flags,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/deployStudio.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {styleText} from 'node:util'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_PROJECT_ID} from '../../util/errorMessages.js'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/deployStudio.ts"],"sourcesContent":["import {basename, dirname} from 'node:path'\nimport {styleText} from 'node:util'\nimport {createGzip} from 'node:zlib'\n\nimport {CLIError} from '@oclif/core/errors'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {pack} from 'tar-fs'\n\nimport {createDeployment} from '../../services/userApplications.js'\nimport {getAppId} from '../../util/appId.js'\nimport {NO_PROJECT_ID} from '../../util/errorMessages.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {buildStudio} from '../build/buildStudio.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {checkDir} from './checkDir.js'\nimport {createStudioUserApplication} from './createStudioUserApplication.js'\nimport {deployDebug} from './deployDebug.js'\nimport {findUserApplicationForStudio} from './findUserApplicationForStudio.js'\nimport {type DeployAppOptions} from './types.js'\n\nexport async function deployStudio(options: DeployAppOptions) {\n const {cliConfig, flags, output, sourceDir, workDir} = options\n\n const appHost = cliConfig.studioHost\n const appId = getAppId(cliConfig)\n const projectId = cliConfig.api?.projectId\n const installedSanityVersion = await getLocalPackageVersion('sanity', workDir)\n const isAutoUpdating = shouldAutoUpdate({cliConfig, flags, output})\n\n if (!installedSanityVersion) {\n output.error(`Failed to find installed sanity version`, {exit: 1})\n return\n }\n\n if (!projectId) {\n output.error(NO_PROJECT_ID, {exit: 1})\n return\n }\n\n let spin = spinner('Verifying local content')\n\n try {\n let userApplication = await findUserApplicationForStudio({\n appHost,\n appId,\n output,\n projectId,\n })\n\n if (!userApplication) {\n // otherwise, prompt the user for a hostname\n output.log('Your project has not been assigned a studio hostname.')\n output.log('To deploy your Sanity Studio to our hosted sanity.studio service,')\n output.log('you will need one. Please enter the part you want to use.')\n\n userApplication = await createStudioUserApplication(projectId)\n\n deployDebug('Created user application', userApplication)\n }\n\n deployDebug('Found user application', userApplication)\n\n // Always build the project, unless --no-build is passed\n const shouldBuild = flags.build\n if (shouldBuild) {\n deployDebug(`Building studio`)\n await buildStudio({\n autoUpdatesEnabled: isAutoUpdating,\n cliConfig,\n flags,\n outDir: sourceDir,\n output,\n workDir,\n })\n }\n\n // TODO: Implement schema deployment\n // await deploySchemasAction(\n // {\n // 'extract-manifest': shouldBuild,\n // 'manifest-dir': `${sourceDir}/static`,\n // 'schema-required': flags['schema-required'],\n // 'verbose': flags.verbose,\n // },\n // {...context, manifestExtractor: createManifestExtractor(context)},\n // )\n\n // Ensure that the directory exists, is a directory and seems to have valid content\n spin = spin.start()\n try {\n await checkDir(sourceDir)\n spin.succeed()\n } catch (err) {\n spin.fail()\n deployDebug('Error checking directory', err)\n output.error('Error checking directory', {exit: 1})\n }\n\n // Create a tarball of the given directory\n const parentDir = dirname(sourceDir)\n const base = basename(sourceDir)\n const tarball = pack(parentDir, {entries: [base]}).pipe(createGzip())\n\n spin = spinner('Deploying to sanity.studio').start()\n\n const {location} = await createDeployment({\n applicationId: userApplication.id,\n isApp: false,\n isAutoUpdating,\n projectId,\n tarball,\n version: installedSanityVersion,\n })\n\n spin.succeed()\n\n // And let the user know we're done\n output.log(`\\nSuccess! Studio deployed to ${styleText('cyan', location || 'unknown URL')}`)\n\n if (!appId) {\n output.log(`\\nAdd ${styleText('cyan', `deployment: { appId: '${userApplication.id}' }`)}`)\n output.log(`to sanity.cli.js or sanity.cli.ts`)\n output.log(`to avoid prompting on next deploy.`)\n }\n } catch (error) {\n // if the error is a CLIError, we can just output the message and exit\n if (error instanceof CLIError) {\n output.error(error.message, {exit: 1})\n return\n }\n\n spin.fail()\n deployDebug('Error deploying studio', error)\n output.error(`Error deploying studio: ${error}`, {exit: 1})\n }\n}\n"],"names":["basename","dirname","styleText","createGzip","CLIError","spinner","pack","createDeployment","getAppId","NO_PROJECT_ID","getLocalPackageVersion","buildStudio","shouldAutoUpdate","checkDir","createStudioUserApplication","deployDebug","findUserApplicationForStudio","deployStudio","options","cliConfig","flags","output","sourceDir","workDir","appHost","studioHost","appId","projectId","api","installedSanityVersion","isAutoUpdating","error","exit","spin","userApplication","log","shouldBuild","build","autoUpdatesEnabled","outDir","start","succeed","err","fail","parentDir","base","tarball","entries","pipe","location","applicationId","id","isApp","version","message"],"mappings":"AAAA,SAAQA,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAC3C,SAAQC,SAAS,QAAO,YAAW;AACnC,SAAQC,UAAU,QAAO,YAAW;AAEpC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,IAAI,QAAO,SAAQ;AAE3B,SAAQC,gBAAgB,QAAO,qCAAoC;AACnE,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,8BAA6B;AACzD,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,S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,MAAM;YAAC;YACpC;QACF;QAEAC,KAAKU,IAAI;QACT5B,YAAY,0BAA0BgB;QACtCV,OAAOU,KAAK,CAAC,CAAC,wBAAwB,EAAEA,OAAO,EAAE;YAACC,MAAM;QAAC;IAC3D;AACF"}
|
|
@@ -7,9 +7,9 @@ import { gracefulServerDeath } from '../../server/gracefulServerDeath.js';
|
|
|
7
7
|
import { getProjectById } from '../../services/projects.js';
|
|
8
8
|
import { getAppId } from '../../util/appId.js';
|
|
9
9
|
import { compareDependencyVersions } from '../../util/compareDependencyVersions.js';
|
|
10
|
+
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
10
11
|
import { getPackageManagerChoice } from '../../util/packageManager/packageManagerChoice.js';
|
|
11
12
|
import { upgradePackages } from '../../util/packageManager/upgradePackages.js';
|
|
12
|
-
import { readModuleVersion } from '../../util/readModuleVersion.js';
|
|
13
13
|
import { warnAboutMissingAppId } from '../../util/warnAboutMissingAppId.js';
|
|
14
14
|
import { checkRequiredDependencies } from '../build/checkRequiredDependencies.js';
|
|
15
15
|
import { checkStudioDependencyVersions } from '../build/checkStudioDependencyVersions.js';
|
|
@@ -138,7 +138,7 @@ export async function startStudioDevServer(options) {
|
|
|
138
138
|
const startupDuration = Date.now() - startTime;
|
|
139
139
|
const url = `http://${httpHost || 'localhost'}:${port}${config.basePath}`;
|
|
140
140
|
const appType = 'Sanity Studio';
|
|
141
|
-
const viteVersion = await
|
|
141
|
+
const viteVersion = await getLocalPackageVersion('vite', import.meta.url);
|
|
142
142
|
spin.succeed();
|
|
143
143
|
loggerInfo(`${appType} ` + `using ${styleText('cyan', `vite@${viteVersion}`)} ` + `ready in ${styleText('cyan', `${Math.ceil(startupDuration)}ms`)} ` + `and running at ${styleText('cyan', url)}`);
|
|
144
144
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startStudioDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {getProjectById} from '../../services/projects.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {readModuleVersion} from '../../util/readModuleVersion.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {checkRequiredDependencies} from '../build/checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from '../build/checkStudioDependencyVersions.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {devDebug} from './devDebug.js'\nimport {getCoreAppURL} from './getCoreAppUrl.js'\nimport {getDevServerConfig} from './getDevServerConfig.js'\nimport {type DevActionOptions} from './types.js'\n\nexport async function startStudioDevServer(\n options: DevActionOptions,\n): Promise<{close?: () => Promise<void>}> {\n const {cliConfig, flags, output, workDir} = options\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined\n\n const loadInDashboard = flags['load-in-dashboard']\n\n // Check studio dependency versions\n await checkStudioDependencyVersions(workDir, output)\n\n const {installedSanityVersion} = await checkRequiredDependencies(options)\n\n // Check if auto-updates are enabled\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\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\n output.log(`${logSymbols.info} Running with auto-updates enabled`)\n\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n\n const appId = getAppId(cliConfig)\n\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir, {appId})\n } catch (err) {\n output.warn(`Failed to compare local versions against auto-updating versions: ${err}`)\n }\n\n if (!appId) {\n warnAboutMissingAppId({\n appType: 'studio',\n output,\n projectId,\n })\n }\n\n // mismatch between local and auto-updating dependencies\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 if (isInteractive()) {\n const shouldUpgrade = await confirm({\n default: true,\n message: styleText('yellow', `${message}Do you want to upgrade local versions?`),\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 {output, workDir},\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.log(styleText('yellow', message))\n }\n }\n }\n\n const config = getDevServerConfig({cliConfig, flags, output, workDir})\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard', {exit: 1})\n }\n\n try {\n const project = await getProjectById(projectId!)\n organizationId = project.organizationId!\n } catch (error) {\n devDebug('Error getting organization id from project id', error)\n output.error('Failed to get organization id from project id', {exit: 1})\n }\n }\n\n try {\n const startTime = Date.now()\n const spin = spinner('Starting dev server').start()\n const {close, 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 if (loadInDashboard) {\n spin.succeed()\n\n output.log(`Dev server started on port ${port}`)\n output.log(`View your studio in the Sanity dashboard here:`)\n output.log(\n styleText(\n ['blue', 'underline'],\n getCoreAppURL({\n httpHost,\n httpPort: port,\n organizationId: organizationId!,\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 const viteVersion = await readModuleVersion(import.meta.url, 'vite')\n spin.succeed()\n\n loggerInfo(\n `${appType} ` +\n `using ${styleText('cyan', `vite@${viteVersion}`)} ` +\n `ready in ${styleText('cyan', `${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${styleText('cyan', url)}`,\n )\n }\n\n return {close}\n } catch (err) {\n devDebug('Error starting studio dev server', err)\n throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["styleText","isInteractive","confirm","logSymbols","spinner","semver","startDevServer","gracefulServerDeath","getProjectById","getAppId","compareDependencyVersions","getPackageManagerChoice","upgradePackages","readModuleVersion","warnAboutMissingAppId","checkRequiredDependencies","checkStudioDependencyVersions","shouldAutoUpdate","devDebug","getCoreAppURL","getDevServerConfig","startStudioDevServer","options","cliConfig","flags","output","workDir","projectId","api","organizationId","loadInDashboard","installedSanityVersion","autoUpdatesEnabled","cleanSanityVersion","parse","version","Error","sanityDependencies","name","log","info","result","appId","err","warn","appType","length","message","map","mod","pkg","installed","remote","join","shouldUpgrade","default","packageManager","interactive","chosen","packages","res","config","error","exit","project","startTime","Date","now","spin","start","close","server","loggerInfo","logger","port","httpHost","succeed","httpPort","startupDuration","url","basePath","viteVersion","Math","ceil"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAChE,OAAOC,YAAY,SAAQ;AAE3B,SAAQC,cAAc,QAAO,4BAA2B;AACxD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAAQC,cAAc,QAAO,6BAA4B;AACzD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,yBAAyB,QAAO,0CAAyC;AACjF,SAAQC,uBAAuB,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,MAAM;QAEhD;QAEA,OAAO;YAACT;QAAK;IACf,EAAE,OAAO3B,KAAK;QACZzB,SAAS,oCAAoCyB;QAC7C,MAAMpC,oBAAoB,OAAOsD,OAAOc,QAAQ,EAAEd,OAAOgB,QAAQ,EAAElC;IACrE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startStudioDevServer.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {isInteractive} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport semver from 'semver'\n\nimport {startDevServer} from '../../server/devServer.js'\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {getProjectById} from '../../services/projects.js'\nimport {getAppId} from '../../util/appId.js'\nimport {compareDependencyVersions} from '../../util/compareDependencyVersions.js'\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {getPackageManagerChoice} from '../../util/packageManager/packageManagerChoice.js'\nimport {upgradePackages} from '../../util/packageManager/upgradePackages.js'\nimport {warnAboutMissingAppId} from '../../util/warnAboutMissingAppId.js'\nimport {checkRequiredDependencies} from '../build/checkRequiredDependencies.js'\nimport {checkStudioDependencyVersions} from '../build/checkStudioDependencyVersions.js'\nimport {shouldAutoUpdate} from '../build/shouldAutoUpdate.js'\nimport {devDebug} from './devDebug.js'\nimport {getCoreAppURL} from './getCoreAppUrl.js'\nimport {getDevServerConfig} from './getDevServerConfig.js'\nimport {type DevActionOptions} from './types.js'\n\nexport async function startStudioDevServer(\n options: DevActionOptions,\n): Promise<{close?: () => Promise<void>}> {\n const {cliConfig, flags, output, workDir} = options\n const projectId = cliConfig?.api?.projectId\n let organizationId: string | undefined\n\n const loadInDashboard = flags['load-in-dashboard']\n\n // Check studio dependency versions\n await checkStudioDependencyVersions(workDir, output)\n\n const {installedSanityVersion} = await checkRequiredDependencies(options)\n\n // Check if auto-updates are enabled\n const autoUpdatesEnabled = shouldAutoUpdate({cliConfig, flags, output})\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\n output.log(`${logSymbols.info} Running with auto-updates enabled`)\n\n // Check local versions against deployed versions\n let result: Awaited<ReturnType<typeof compareDependencyVersions>> | undefined\n\n const appId = getAppId(cliConfig)\n\n try {\n result = await compareDependencyVersions(sanityDependencies, workDir, {appId})\n } catch (err) {\n output.warn(`Failed to compare local versions against auto-updating versions: ${err}`)\n }\n\n if (!appId) {\n warnAboutMissingAppId({\n appType: 'studio',\n output,\n projectId,\n })\n }\n\n // mismatch between local and auto-updating dependencies\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 if (isInteractive()) {\n const shouldUpgrade = await confirm({\n default: true,\n message: styleText('yellow', `${message}Do you want to upgrade local versions?`),\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 {output, workDir},\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.log(styleText('yellow', message))\n }\n }\n }\n\n const config = getDevServerConfig({cliConfig, flags, output, workDir})\n\n if (loadInDashboard) {\n if (!projectId) {\n output.error('Project Id is required to load in dashboard', {exit: 1})\n }\n\n try {\n const project = await getProjectById(projectId!)\n organizationId = project.organizationId!\n } catch (error) {\n devDebug('Error getting organization id from project id', error)\n output.error('Failed to get organization id from project id', {exit: 1})\n }\n }\n\n try {\n const startTime = Date.now()\n const spin = spinner('Starting dev server').start()\n const {close, 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 if (loadInDashboard) {\n spin.succeed()\n\n output.log(`Dev server started on port ${port}`)\n output.log(`View your studio in the Sanity dashboard here:`)\n output.log(\n styleText(\n ['blue', 'underline'],\n getCoreAppURL({\n httpHost,\n httpPort: port,\n organizationId: organizationId!,\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 const viteVersion = await getLocalPackageVersion('vite', import.meta.url)\n spin.succeed()\n\n loggerInfo(\n `${appType} ` +\n `using ${styleText('cyan', `vite@${viteVersion}`)} ` +\n `ready in ${styleText('cyan', `${Math.ceil(startupDuration)}ms`)} ` +\n `and running at ${styleText('cyan', url)}`,\n )\n }\n\n return {close}\n } catch (err) {\n devDebug('Error starting studio dev server', err)\n throw gracefulServerDeath('dev', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["styleText","isInteractive","confirm","logSymbols","spinner","semver","startDevServer","gracefulServerDeath","getProjectById","getAppId","compareDependencyVersions","getLocalPackageVersion","getPackageManagerChoice","upgradePackages","warnAboutMissingAppId","checkRequiredDependencies","checkStudioDependencyVersions","shouldAutoUpdate","devDebug","getCoreAppURL","getDevServerConfig","startStudioDevServer","options","cliConfig","flags","output","workDir","projectId","api","organizationId","loadInDashboard","installedSanityVersion","autoUpdatesEnabled","cleanSanityVersion","parse","version","Error","sanityDependencies","name","log","info","result","appId","err","warn","appType","length","message","map","mod","pkg","installed","remote","join","shouldUpgrade","default","packageManager","interactive","chosen","packages","res","config","error","exit","project","startTime","Date","now","spin","start","close","server","loggerInfo","logger","port","httpHost","succeed","httpPort","startupDuration","url","basePath","viteVersion","Math","ceil"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,aAAa,QAAO,mB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;YACxEX,KAAKQ,OAAO;YAEZJ,WACE,GAAG3B,QAAQ,CAAC,CAAC,GACX,CAAC,MAAM,EAAE7C,UAAU,QAAQ,CAAC,KAAK,EAAEiF,aAAa,EAAE,CAAC,CAAC,GACpD,CAAC,SAAS,EAAEjF,UAAU,QAAQ,GAAGkF,KAAKC,IAAI,CAACL,iBAAiB,EAAE,CAAC,EAAE,CAAC,CAAC,GACnE,CAAC,eAAe,EAAE9E,UAAU,QAAQ+E,MAAM;QAEhD;QAEA,OAAO;YAACT;QAAK;IACf,EAAE,OAAO3B,KAAK;QACZzB,SAAS,oCAAoCyB;QAC7C,MAAMpC,oBAAoB,OAAOsD,OAAOc,QAAQ,EAAEd,OAAOgB,QAAQ,EAAElC;IACrE;AACF"}
|
|
@@ -2,7 +2,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
|
|
|
2
2
|
import { join, resolve } from 'node:path';
|
|
3
3
|
import { findProjectRoot, getTimer, studioWorkerTask } from '@sanity/cli-core';
|
|
4
4
|
import { spinner } from '@sanity/cli-core/ux';
|
|
5
|
-
import {
|
|
5
|
+
import { getLocalPackageVersion } from '../../util/getLocalPackageVersion.js';
|
|
6
6
|
import { SchemaExtractionError } from '../schema/utils/SchemaExtractionError.js';
|
|
7
7
|
import { manifestDebug } from './debug.js';
|
|
8
8
|
import { writeWorkspaceFiles } from './writeWorkspaceFiles.js';
|
|
@@ -61,7 +61,7 @@ export async function extractManifest(outPath) {
|
|
|
61
61
|
* 2: Added tools file.
|
|
62
62
|
* 3. Added studioVersion field.
|
|
63
63
|
*/ createdAt: new Date().toISOString(),
|
|
64
|
-
studioVersion: await
|
|
64
|
+
studioVersion: await getLocalPackageVersion('sanity', workDir),
|
|
65
65
|
version: 3,
|
|
66
66
|
workspaces: workspaceFiles
|
|
67
67
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/manifest/extractManifest.ts"],"sourcesContent":["import {mkdir, writeFile} from 'node:fs/promises'\nimport {join, resolve} from 'node:path'\n\nimport {findProjectRoot, getTimer, Output, studioWorkerTask} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/manifest/extractManifest.ts"],"sourcesContent":["import {mkdir, writeFile} from 'node:fs/promises'\nimport {join, resolve} from 'node:path'\n\nimport {findProjectRoot, getTimer, Output, studioWorkerTask} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {getLocalPackageVersion} from '../../util/getLocalPackageVersion.js'\nimport {type ExtractSchemaWorkerError} from '../schema/types.js'\nimport {SchemaExtractionError} from '../schema/utils/SchemaExtractionError.js'\nimport {manifestDebug} from './debug.js'\nimport {\n type CreateManifest,\n type CreateWorkspaceManifest,\n type ExtractManifestWorkerData,\n} from './types'\nimport {writeWorkspaceFiles} from './writeWorkspaceFiles.js'\n\nexport const MANIFEST_FILENAME = 'create-manifest.json'\n\n/** Escape-hatch env flags to change action behavior */\nconst FEATURE_ENABLED_ENV_NAME = 'SANITY_CLI_EXTRACT_MANIFEST_ENABLED'\nconst EXTRACT_MANIFEST_ENABLED = process.env[FEATURE_ENABLED_ENV_NAME] !== 'false'\nconst EXTRACT_MANIFEST_LOG_ERRORS = process.env.SANITY_CLI_EXTRACT_MANIFEST_LOG_ERRORS === 'true'\n\nconst CREATE_TIMER = 'create-manifest'\n\ninterface ExtractManifestOptions {\n outPath: string\n output: Output\n}\n\n/**\n * This function will never throw.\n * @returns `undefined` if extract succeeded - caught error if it failed\n */\nexport async function extractManifestSafe(\n options: ExtractManifestOptions,\n): Promise<Error | undefined> {\n const {outPath, output} = options\n if (!EXTRACT_MANIFEST_ENABLED) {\n return undefined\n }\n\n try {\n await extractManifest(outPath)\n return undefined\n } catch (err) {\n if (EXTRACT_MANIFEST_LOG_ERRORS) {\n output.error(err)\n }\n return err\n }\n}\n\ninterface ExtractManifestWorkerResult {\n type: 'success'\n workspaceManifests: CreateWorkspaceManifest[]\n}\n\ntype ExtractManifestWorkerMessage = ExtractManifestWorkerResult | ExtractSchemaWorkerError\n\nexport async function extractManifest(outPath: string): Promise<void> {\n const projectRoot = await findProjectRoot(process.cwd())\n\n const workDir = projectRoot.directory\n const configPath = projectRoot.path\n const staticPath = resolve(join(workDir, outPath))\n const path = join(staticPath, MANIFEST_FILENAME)\n\n const timer = getTimer()\n timer.start(CREATE_TIMER)\n const spin = spinner('Extracting manifest').start()\n\n try {\n const result = await studioWorkerTask<ExtractManifestWorkerMessage>(\n new URL('extractManifest.worker.js', import.meta.url),\n {\n name: 'extractManifest',\n studioRootPath: workDir,\n workerData: {configPath, workDir} satisfies ExtractManifestWorkerData,\n },\n )\n\n if (result.type === 'error') {\n throw new SchemaExtractionError(result.error, result.validation)\n }\n\n await mkdir(staticPath, {recursive: true})\n\n const workspaceFiles = await writeWorkspaceFiles(result.workspaceManifests, staticPath)\n\n const manifest: CreateManifest = {\n /**\n * Version history:\n * 1: Initial release.\n * 2: Added tools file.\n * 3. Added studioVersion field.\n */\n createdAt: new Date().toISOString(),\n studioVersion: await getLocalPackageVersion('sanity', workDir),\n version: 3,\n workspaces: workspaceFiles,\n }\n\n await writeFile(path, JSON.stringify(manifest, null, 2))\n const manifestDuration = timer.end(CREATE_TIMER)\n\n spin.succeed(`Extracted manifest (${manifestDuration.toFixed(0)}ms)`)\n } catch (err) {\n manifestDebug('Error extracting manifest', err)\n spin.fail()\n\n throw err\n }\n}\n"],"names":["mkdir","writeFile","join","resolve","findProjectRoot","getTimer","studioWorkerTask","spinner","getLocalPackageVersion","SchemaExtractionError","manifestDebug","writeWorkspaceFiles","MANIFEST_FILENAME","FEATURE_ENABLED_ENV_NAME","EXTRACT_MANIFEST_ENABLED","process","env","EXTRACT_MANIFEST_LOG_ERRORS","SANITY_CLI_EXTRACT_MANIFEST_LOG_ERRORS","CREATE_TIMER","extractManifestSafe","options","outPath","output","undefined","extractManifest","err","error","projectRoot","cwd","workDir","directory","configPath","path","staticPath","timer","start","spin","result","URL","url","name","studioRootPath","workerData","type","validation","recursive","workspaceFiles","workspaceManifests","manifest","createdAt","Date","toISOString","studioVersion","version","workspaces","JSON","stringify","manifestDuration","end","succeed","toFixed","fail"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,SAAS,QAAO,mBAAkB;AACjD,SAAQC,IAAI,EAAEC,OAAO,QAAO,YAAW;AAEvC,SAAQC,eAAe,EAAEC,QAAQ,EAAUC,gBAAgB,QAAO,mBAAkB;AACpF,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,SAAQC,qBAAqB,QAAO,2CAA0C;AAC9E,SAAQC,aAAa,QAAO,aAAY;AAMxC,SAAQC,mBAAmB,QAAO,2BAA0B;AAE5D,OAAO,MAAMC,oBAAoB,uBAAsB;AAEvD,qDAAqD,GACrD,MAAMC,2BAA2B;AACjC,MAAMC,2BAA2BC,QAAQC,GAAG,CAACH,yBAAyB,KAAK;AAC3E,MAAMI,8BAA8BF,QAAQC,GAAG,CAACE,sCAAsC,KAAK;AAE3F,MAAMC,eAAe;AAOrB;;;CAGC,GACD,OAAO,eAAeC,oBACpBC,OAA+B;IAE/B,MAAM,EAACC,OAAO,EAAEC,MAAM,EAAC,GAAGF;IAC1B,IAAI,CAACP,0BAA0B;QAC7B,OAAOU;IACT;IAEA,IAAI;QACF,MAAMC,gBAAgBH;QACtB,OAAOE;IACT,EAAE,OAAOE,KAAK;QACZ,IAAIT,6BAA6B;YAC/BM,OAAOI,KAAK,CAACD;QACf;QACA,OAAOA;IACT;AACF;AASA,OAAO,eAAeD,gBAAgBH,OAAe;IACnD,MAAMM,cAAc,MAAMxB,gBAAgBW,QAAQc,GAAG;IAErD,MAAMC,UAAUF,YAAYG,SAAS;IACrC,MAAMC,aAAaJ,YAAYK,IAAI;IACnC,MAAMC,aAAa/B,QAAQD,KAAK4B,SAASR;IACzC,MAAMW,OAAO/B,KAAKgC,YAAYtB;IAE9B,MAAMuB,QAAQ9B;IACd8B,MAAMC,KAAK,CAACjB;IACZ,MAAMkB,OAAO9B,QAAQ,uBAAuB6B,KAAK;IAEjD,IAAI;QACF,MAAME,SAAS,MAAMhC,iBACnB,IAAIiC,IAAI,6BAA6B,YAAYC,GAAG,GACpD;YACEC,MAAM;YACNC,gBAAgBZ;YAChBa,YAAY;gBAACX;gBAAYF;YAAO;QAClC;QAGF,IAAIQ,OAAOM,IAAI,KAAK,SAAS;YAC3B,MAAM,IAAInC,sBAAsB6B,OAAOX,KAAK,EAAEW,OAAOO,UAAU;QACjE;QAEA,MAAM7C,MAAMkC,YAAY;YAACY,WAAW;QAAI;QAExC,MAAMC,iBAAiB,MAAMpC,oBAAoB2B,OAAOU,kBAAkB,EAAEd;QAE5E,MAAMe,WAA2B;YAC/B;;;;;OAKC,GACDC,WAAW,IAAIC,OAAOC,WAAW;YACjCC,eAAe,MAAM7C,uBAAuB,UAAUsB;YACtDwB,SAAS;YACTC,YAAYR;QACd;QAEA,MAAM9C,UAAUgC,MAAMuB,KAAKC,SAAS,CAACR,UAAU,MAAM;QACrD,MAAMS,mBAAmBvB,MAAMwB,GAAG,CAACxC;QAEnCkB,KAAKuB,OAAO,CAAC,CAAC,oBAAoB,EAAEF,iBAAiBG,OAAO,CAAC,GAAG,GAAG,CAAC;IACtE,EAAE,OAAOnC,KAAK;QACZhB,cAAc,6BAA6BgB;QAC3CW,KAAKyB,IAAI;QAET,MAAMpC;IACR;AACF"}
|
|
@@ -1,52 +1,27 @@
|
|
|
1
|
-
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
-
import { join, resolve } from 'node:path';
|
|
3
1
|
import { exit } from '@oclif/core/errors';
|
|
4
|
-
import { getCliTelemetry
|
|
2
|
+
import { getCliTelemetry } from '@sanity/cli-core';
|
|
5
3
|
import { spinner } from '@sanity/cli-core/ux';
|
|
6
4
|
import { SchemaExtractedTrace } from '../../telemetry/extractSchema.telemetry.js';
|
|
7
5
|
import { formatSchemaValidation } from './formatSchemaValidation.js';
|
|
6
|
+
import { runSchemaExtraction } from './runSchemaExtraction.js';
|
|
8
7
|
import { schemasExtractDebug } from './utils/debug.js';
|
|
9
8
|
import { SchemaExtractionError } from './utils/SchemaExtractionError.js';
|
|
10
|
-
const FILENAME = 'schema.json';
|
|
11
9
|
export async function extractSchema(options) {
|
|
12
|
-
const {
|
|
13
|
-
const {
|
|
10
|
+
const { extractOptions, output } = options;
|
|
11
|
+
const { enforceRequiredFields, format, outputPath } = extractOptions;
|
|
14
12
|
const spin = spinner(enforceRequiredFields ? 'Extracting schema with enforced required fields' : 'Extracting schema').start();
|
|
15
|
-
const workDir = projectRoot.directory;
|
|
16
13
|
const trace = getCliTelemetry().trace(SchemaExtractedTrace);
|
|
17
14
|
trace.start();
|
|
18
15
|
try {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
const result = await studioWorkerTask(new URL('extractSanitySchema.worker.js', import.meta.url), {
|
|
23
|
-
name: 'extractSanitySchema',
|
|
24
|
-
studioRootPath: workDir,
|
|
25
|
-
workerData: {
|
|
26
|
-
configPath: projectRoot.path,
|
|
27
|
-
enforceRequiredFields,
|
|
28
|
-
workDir,
|
|
29
|
-
workspaceName
|
|
30
|
-
}
|
|
31
|
-
});
|
|
32
|
-
if (result.type === 'error') {
|
|
33
|
-
throw new SchemaExtractionError(result.error, result.validation);
|
|
34
|
-
}
|
|
35
|
-
const schema = result.schema;
|
|
16
|
+
spin.text = `Writing schema to ${outputPath}`;
|
|
17
|
+
const schema = await runSchemaExtraction(extractOptions);
|
|
36
18
|
trace.log({
|
|
37
19
|
enforceRequiredFields,
|
|
38
20
|
schemaAllTypesCount: schema.length,
|
|
39
21
|
schemaDocumentTypesCount: schema.filter((type)=>type.type === 'document').length,
|
|
40
|
-
schemaFormat:
|
|
22
|
+
schemaFormat: format,
|
|
41
23
|
schemaTypesCount: schema.filter((type)=>type.type === 'type').length
|
|
42
24
|
});
|
|
43
|
-
const outputDir = path ? resolve(join(workDir, path)) : workDir;
|
|
44
|
-
const outputPath = join(outputDir, FILENAME);
|
|
45
|
-
await mkdir(outputDir, {
|
|
46
|
-
recursive: true
|
|
47
|
-
});
|
|
48
|
-
spin.text = `Writing schema to ${outputPath}`;
|
|
49
|
-
await writeFile(outputPath, `${JSON.stringify(schema, null, 2)}\n`);
|
|
50
25
|
spin.succeed(enforceRequiredFields ? `Extracted schema to ${outputPath} with enforced required fields` : `Extracted schema to ${outputPath}`);
|
|
51
26
|
trace.complete();
|
|
52
27
|
} catch (err) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/schema/extractSchema.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/schema/extractSchema.ts"],"sourcesContent":["import {exit} from '@oclif/core/errors'\nimport {getCliTelemetry, type Output} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {SchemaExtractedTrace} from '../../telemetry/extractSchema.telemetry.js'\nimport {formatSchemaValidation} from './formatSchemaValidation.js'\nimport {type ExtractOptions} from './getExtractOptions.js'\nimport {runSchemaExtraction} from './runSchemaExtraction.js'\nimport {schemasExtractDebug} from './utils/debug.js'\nimport {SchemaExtractionError} from './utils/SchemaExtractionError.js'\n\ninterface ExtractSchemaActionOptions {\n extractOptions: ExtractOptions\n output: Output\n}\n\nexport async function extractSchema(options: ExtractSchemaActionOptions): Promise<void> {\n const {extractOptions, output} = options\n const {enforceRequiredFields, format, outputPath} = extractOptions\n\n const spin = spinner(\n enforceRequiredFields ? 'Extracting schema with enforced required fields' : 'Extracting schema',\n ).start()\n\n const trace = getCliTelemetry().trace(SchemaExtractedTrace)\n trace.start()\n\n try {\n spin.text = `Writing schema to ${outputPath}`\n\n const schema = await runSchemaExtraction(extractOptions)\n\n trace.log({\n enforceRequiredFields,\n schemaAllTypesCount: schema.length,\n schemaDocumentTypesCount: schema.filter((type) => type.type === 'document').length,\n schemaFormat: format,\n schemaTypesCount: schema.filter((type) => type.type === 'type').length,\n })\n\n spin.succeed(\n enforceRequiredFields\n ? `Extracted schema to ${outputPath} with enforced required fields`\n : `Extracted schema to ${outputPath}`,\n )\n\n trace.complete()\n } catch (err) {\n trace.error(err)\n schemasExtractDebug('Failed to extract schema', err)\n spin.fail(\n enforceRequiredFields\n ? 'Failed to extract schema with enforced required fields'\n : 'Failed to extract schema',\n )\n\n // Display validation errors if available\n if (err instanceof SchemaExtractionError && err.validation && err.validation.length > 0) {\n output.log('')\n output.log(formatSchemaValidation(err.validation))\n }\n\n if (err instanceof Error) {\n output.error(err.message, {exit: 1})\n }\n\n exit(1)\n }\n}\n"],"names":["exit","getCliTelemetry","spinner","SchemaExtractedTrace","formatSchemaValidation","runSchemaExtraction","schemasExtractDebug","SchemaExtractionError","extractSchema","options","extractOptions","output","enforceRequiredFields","format","outputPath","spin","start","trace","text","schema","log","schemaAllTypesCount","length","schemaDocumentTypesCount","filter","type","schemaFormat","schemaTypesCount","succeed","complete","err","error","fail","validation","Error","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,qBAAoB;AACvC,SAAQC,eAAe,QAAoB,mBAAkB;AAC7D,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,oBAAoB,QAAO,6CAA4C;AAC/E,SAAQC,sBAAsB,QAAO,8BAA6B;AAElE,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAAQC,mBAAmB,QAAO,mBAAkB;AACpD,SAAQC,qBAAqB,QAAO,mCAAkC;AAOtE,OAAO,eAAeC,cAAcC,OAAmC;IACrE,MAAM,EAACC,cAAc,EAAEC,MAAM,EAAC,GAAGF;IACjC,MAAM,EAACG,qBAAqB,EAAEC,MAAM,EAAEC,UAAU,EAAC,GAAGJ;IAEpD,MAAMK,OAAOb,QACXU,wBAAwB,oDAAoD,qBAC5EI,KAAK;IAEP,MAAMC,QAAQhB,kBAAkBgB,KAAK,CAACd;IACtCc,MAAMD,KAAK;IAEX,IAAI;QACFD,KAAKG,IAAI,GAAG,CAAC,kBAAkB,EAAEJ,YAAY;QAE7C,MAAMK,SAAS,MAAMd,oBAAoBK;QAEzCO,MAAMG,GAAG,CAAC;YACRR;YACAS,qBAAqBF,OAAOG,MAAM;YAClCC,0BAA0BJ,OAAOK,MAAM,CAAC,CAACC,OAASA,KAAKA,IAAI,KAAK,YAAYH,MAAM;YAClFI,cAAcb;YACdc,kBAAkBR,OAAOK,MAAM,CAAC,CAACC,OAASA,KAAKA,IAAI,KAAK,QAAQH,MAAM;QACxE;QAEAP,KAAKa,OAAO,CACVhB,wBACI,CAAC,oBAAoB,EAAEE,WAAW,8BAA8B,CAAC,GACjE,CAAC,oBAAoB,EAAEA,YAAY;QAGzCG,MAAMY,QAAQ;IAChB,EAAE,OAAOC,KAAK;QACZb,MAAMc,KAAK,CAACD;QACZxB,oBAAoB,4BAA4BwB;QAChDf,KAAKiB,IAAI,CACPpB,wBACI,2DACA;QAGN,yCAAyC;QACzC,IAAIkB,eAAevB,yBAAyBuB,IAAIG,UAAU,IAAIH,IAAIG,UAAU,CAACX,MAAM,GAAG,GAAG;YACvFX,OAAOS,GAAG,CAAC;YACXT,OAAOS,GAAG,CAAChB,uBAAuB0B,IAAIG,UAAU;QAClD;QAEA,IAAIH,eAAeI,OAAO;YACxBvB,OAAOoB,KAAK,CAACD,IAAIK,OAAO,EAAE;gBAACnC,MAAM;YAAC;QACpC;QAEAA,KAAK;IACP;AACF"}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { dirname, isAbsolute, relative } from 'node:path';
|
|
2
|
+
import { spinner } from '@sanity/cli-core/ux';
|
|
3
|
+
import { watch as chokidarWatch } from 'chokidar';
|
|
4
|
+
import { debounce } from 'lodash-es';
|
|
5
|
+
import { glob } from 'tinyglobby';
|
|
6
|
+
import { formatSchemaValidation } from './formatSchemaValidation.js';
|
|
7
|
+
import { runSchemaExtraction } from './runSchemaExtraction.js';
|
|
8
|
+
import { schemasExtractDebug } from './utils/debug.js';
|
|
9
|
+
import { SchemaExtractionError } from './utils/SchemaExtractionError.js';
|
|
10
|
+
/** Default glob patterns to watch for schema changes */ export const DEFAULT_WATCH_PATTERNS = [
|
|
11
|
+
'sanity.config.{js,jsx,ts,tsx,mjs}',
|
|
12
|
+
'schema*/**/*.{js,jsx,ts,tsx,mjs}'
|
|
13
|
+
];
|
|
14
|
+
/** Default patterns to ignore when watching */ const IGNORED_PATTERNS = [
|
|
15
|
+
'**/node_modules/**',
|
|
16
|
+
'**/.git/**',
|
|
17
|
+
'**/dist/**',
|
|
18
|
+
'**/lib/**',
|
|
19
|
+
'**/.sanity/**'
|
|
20
|
+
];
|
|
21
|
+
/**
|
|
22
|
+
* Creates an extraction runner with concurrency control.
|
|
23
|
+
* If extraction is already running, queues one more extraction to run after completion.
|
|
24
|
+
* Multiple queued requests are coalesced into a single pending extraction.
|
|
25
|
+
*/ function createExtractionRunner(onExtract) {
|
|
26
|
+
const state = {
|
|
27
|
+
isExtracting: false,
|
|
28
|
+
pendingExtraction: false
|
|
29
|
+
};
|
|
30
|
+
async function runExtraction() {
|
|
31
|
+
if (state.isExtracting) {
|
|
32
|
+
state.pendingExtraction = true;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
state.isExtracting = true;
|
|
36
|
+
state.pendingExtraction = false;
|
|
37
|
+
try {
|
|
38
|
+
await onExtract();
|
|
39
|
+
} finally{
|
|
40
|
+
state.isExtracting = false;
|
|
41
|
+
// If a change came in during extraction, run again
|
|
42
|
+
if (state.pendingExtraction) {
|
|
43
|
+
state.pendingExtraction = false;
|
|
44
|
+
await runExtraction();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
runExtraction,
|
|
50
|
+
state
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Starts a schema watcher that extracts schema on file changes.
|
|
55
|
+
* Returns a watcher instance and a stop function.
|
|
56
|
+
*/ export async function startExtractSchemaWatcher(options) {
|
|
57
|
+
const { extractOptions, onExtraction, output, watchPatterns } = options;
|
|
58
|
+
const { configPath, enforceRequiredFields, outputPath } = extractOptions;
|
|
59
|
+
const workDir = dirname(configPath);
|
|
60
|
+
// Helper function to run extraction with spinner and error handling
|
|
61
|
+
const runExtraction = async ()=>{
|
|
62
|
+
const spin = spinner(enforceRequiredFields ? 'Extracting schema with enforced required fields' : 'Extracting schema...').start();
|
|
63
|
+
const extractionStartTime = Date.now();
|
|
64
|
+
try {
|
|
65
|
+
await runSchemaExtraction(extractOptions);
|
|
66
|
+
spin.succeed(enforceRequiredFields ? `Extracted schema to ${outputPath} with enforced required fields` : `Extracted schema to ${outputPath}`);
|
|
67
|
+
const duration = Date.now() - extractionStartTime;
|
|
68
|
+
onExtraction?.({
|
|
69
|
+
duration,
|
|
70
|
+
success: true
|
|
71
|
+
});
|
|
72
|
+
return true;
|
|
73
|
+
} catch (err) {
|
|
74
|
+
const duration = Date.now() - extractionStartTime;
|
|
75
|
+
onExtraction?.({
|
|
76
|
+
duration,
|
|
77
|
+
success: false
|
|
78
|
+
});
|
|
79
|
+
schemasExtractDebug('Failed to extract schema', err);
|
|
80
|
+
spin.fail('Extraction failed');
|
|
81
|
+
// Display validation errors if available
|
|
82
|
+
if (err instanceof SchemaExtractionError && err.validation && err.validation.length > 0) {
|
|
83
|
+
output.log('');
|
|
84
|
+
output.log(formatSchemaValidation(err.validation));
|
|
85
|
+
} else if (err instanceof Error) {
|
|
86
|
+
output.error(err.message, {
|
|
87
|
+
exit: 1
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
// Run initial extraction
|
|
94
|
+
await runExtraction();
|
|
95
|
+
const absoluteWatchPatterns = await glob(watchPatterns, {
|
|
96
|
+
absolute: true,
|
|
97
|
+
ignore: IGNORED_PATTERNS
|
|
98
|
+
});
|
|
99
|
+
// Create extraction runner with concurrency control
|
|
100
|
+
const { runExtraction: runConcurrentExtraction } = createExtractionRunner(async ()=>{
|
|
101
|
+
await runExtraction();
|
|
102
|
+
});
|
|
103
|
+
// Debounced extraction trigger (1 second delay)
|
|
104
|
+
const debouncedExtract = debounce(()=>{
|
|
105
|
+
void runConcurrentExtraction();
|
|
106
|
+
}, 1000);
|
|
107
|
+
const watcher = chokidarWatch(absoluteWatchPatterns, {
|
|
108
|
+
cwd: workDir,
|
|
109
|
+
ignoreInitial: true
|
|
110
|
+
});
|
|
111
|
+
watcher.on('all', (event, filePath)=>{
|
|
112
|
+
const timestamp = new Date().toLocaleTimeString();
|
|
113
|
+
const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath;
|
|
114
|
+
output.log(`[${timestamp}] ${event}: ${relativePath}`);
|
|
115
|
+
debouncedExtract();
|
|
116
|
+
});
|
|
117
|
+
watcher.on('error', (err)=>{
|
|
118
|
+
output.error(`Watcher error: ${err instanceof Error ? err.message : String(err)}`);
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
close: ()=>watcher.close(),
|
|
122
|
+
watcher
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
//# sourceMappingURL=extractSchemaWatcher.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/schema/extractSchemaWatcher.ts"],"sourcesContent":["import {dirname, isAbsolute, relative} from 'node:path'\n\nimport {type Output} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {watch as chokidarWatch, type FSWatcher} from 'chokidar'\nimport {debounce} from 'lodash-es'\nimport {glob} from 'tinyglobby'\n\nimport {formatSchemaValidation} from './formatSchemaValidation.js'\nimport {type ExtractOptions} from './getExtractOptions.js'\nimport {runSchemaExtraction} from './runSchemaExtraction.js'\nimport {schemasExtractDebug} from './utils/debug.js'\nimport {SchemaExtractionError} from './utils/SchemaExtractionError.js'\n\n/** Default glob patterns to watch for schema changes */\nexport const DEFAULT_WATCH_PATTERNS = [\n 'sanity.config.{js,jsx,ts,tsx,mjs}',\n 'schema*/**/*.{js,jsx,ts,tsx,mjs}',\n]\n\n/** Default patterns to ignore when watching */\nconst IGNORED_PATTERNS = [\n '**/node_modules/**',\n '**/.git/**',\n '**/dist/**',\n '**/lib/**',\n '**/.sanity/**',\n]\n\ninterface ExtractSchemaWatcherOptions {\n extractOptions: ExtractOptions\n output: Output\n watchPatterns: string[]\n\n onExtraction?: (result: {duration: number; success: boolean}) => void\n}\n\ninterface ExtractSchemaWatcher {\n close: () => Promise<void>\n watcher: FSWatcher\n}\n\n/** State for tracking extraction status */\ninterface WatchState {\n isExtracting: boolean\n pendingExtraction: boolean\n}\n\n/** Return type for createExtractionRunner */\ninterface ExtractionRunner {\n runExtraction: () => Promise<void>\n state: WatchState\n}\n\n/**\n * Creates an extraction runner with concurrency control.\n * If extraction is already running, queues one more extraction to run after completion.\n * Multiple queued requests are coalesced into a single pending extraction.\n */\nfunction createExtractionRunner(onExtract: () => Promise<void>): ExtractionRunner {\n const state: WatchState = {\n isExtracting: false,\n pendingExtraction: false,\n }\n\n async function runExtraction(): Promise<void> {\n if (state.isExtracting) {\n state.pendingExtraction = true\n return\n }\n\n state.isExtracting = true\n state.pendingExtraction = false\n\n try {\n await onExtract()\n } finally {\n state.isExtracting = false\n\n // If a change came in during extraction, run again\n if (state.pendingExtraction) {\n state.pendingExtraction = false\n await runExtraction()\n }\n }\n }\n\n return {runExtraction, state}\n}\n\n/**\n * Starts a schema watcher that extracts schema on file changes.\n * Returns a watcher instance and a stop function.\n */\nexport async function startExtractSchemaWatcher(\n options: ExtractSchemaWatcherOptions,\n): Promise<ExtractSchemaWatcher> {\n const {extractOptions, onExtraction, output, watchPatterns} = options\n\n const {configPath, enforceRequiredFields, outputPath} = extractOptions\n const workDir = dirname(configPath)\n\n // Helper function to run extraction with spinner and error handling\n const runExtraction = async (): Promise<boolean> => {\n const spin = spinner(\n enforceRequiredFields\n ? 'Extracting schema with enforced required fields'\n : 'Extracting schema...',\n ).start()\n const extractionStartTime = Date.now()\n\n try {\n await runSchemaExtraction(extractOptions)\n\n spin.succeed(\n enforceRequiredFields\n ? `Extracted schema to ${outputPath} with enforced required fields`\n : `Extracted schema to ${outputPath}`,\n )\n\n const duration = Date.now() - extractionStartTime\n onExtraction?.({duration, success: true})\n\n return true\n } catch (err) {\n const duration = Date.now() - extractionStartTime\n onExtraction?.({duration, success: false})\n\n schemasExtractDebug('Failed to extract schema', err)\n spin.fail('Extraction failed')\n\n // Display validation errors if available\n if (err instanceof SchemaExtractionError && err.validation && err.validation.length > 0) {\n output.log('')\n output.log(formatSchemaValidation(err.validation))\n } else if (err instanceof Error) {\n output.error(err.message, {exit: 1})\n }\n\n return false\n }\n }\n\n // Run initial extraction\n await runExtraction()\n\n const absoluteWatchPatterns = await glob(watchPatterns, {\n absolute: true,\n ignore: IGNORED_PATTERNS,\n })\n\n // Create extraction runner with concurrency control\n const {runExtraction: runConcurrentExtraction} = createExtractionRunner(async () => {\n await runExtraction()\n })\n\n // Debounced extraction trigger (1 second delay)\n const debouncedExtract = debounce(() => {\n void runConcurrentExtraction()\n }, 1000)\n\n const watcher: FSWatcher = chokidarWatch(absoluteWatchPatterns, {\n cwd: workDir,\n ignoreInitial: true,\n })\n\n watcher.on('all', (event, filePath) => {\n const timestamp = new Date().toLocaleTimeString()\n const relativePath = isAbsolute(filePath) ? relative(workDir, filePath) : filePath\n output.log(`[${timestamp}] ${event}: ${relativePath}`)\n debouncedExtract()\n })\n\n watcher.on('error', (err) => {\n output.error(`Watcher error: ${err instanceof Error ? err.message : String(err)}`)\n })\n\n return {\n close: () => watcher.close(),\n watcher,\n }\n}\n"],"names":["dirname","isAbsolute","relative","spinner","watch","chokidarWatch","debounce","glob","formatSchemaValidation","runSchemaExtraction","schemasExtractDebug","SchemaExtractionError","DEFAULT_WATCH_PATTERNS","IGNORED_PATTERNS","createExtractionRunner","onExtract","state","isExtracting","pendingExtraction","runExtraction","startExtractSchemaWatcher","options","extractOptions","onExtraction","output","watchPatterns","configPath","enforceRequiredFields","outputPath","workDir","spin","start","extractionStartTime","Date","now","succeed","duration","success","err","fail","validation","length","log","Error","error","message","exit","absoluteWatchPatterns","absolute","ignore","runConcurrentExtraction","debouncedExtract","watcher","cwd","ignoreInitial","on","event","filePath","timestamp","toLocaleTimeString","relativePath","String","close"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,UAAU,EAAEC,QAAQ,QAAO,YAAW;AAGvD,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,SAASC,aAAa,QAAuB,WAAU;AAC/D,SAAQC,QAAQ,QAAO,YAAW;AAClC,SAAQC,IAAI,QAAO,aAAY;AAE/B,SAAQC,sBAAsB,QAAO,8BAA6B;AAElE,SAAQC,mBAAmB,QAAO,2BAA0B;AAC5D,SAAQC,mBAAmB,QAAO,mBAAkB;AACpD,SAAQC,qBAAqB,QAAO,mCAAkC;AAEtE,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB;IACpC;IACA;CACD,CAAA;AAED,6CAA6C,GAC7C,MAAMC,mBAAmB;IACvB;IACA;IACA;IACA;IACA;CACD;AA2BD;;;;CAIC,GACD,SAASC,uBAAuBC,SAA8B;IAC5D,MAAMC,QAAoB;QACxBC,cAAc;QACdC,mBAAmB;IACrB;IAEA,eAAeC;QACb,IAAIH,MAAMC,YAAY,EAAE;YACtBD,MAAME,iBAAiB,GAAG;YAC1B;QACF;QAEAF,MAAMC,YAAY,GAAG;QACrBD,MAAME,iBAAiB,GAAG;QAE1B,IAAI;YACF,MAAMH;QACR,SAAU;YACRC,MAAMC,YAAY,GAAG;YAErB,mDAAmD;YACnD,IAAID,MAAME,iBAAiB,EAAE;gBAC3BF,MAAME,iBAAiB,GAAG;gBAC1B,MAAMC;YACR;QACF;IACF;IAEA,OAAO;QAACA;QAAeH;IAAK;AAC9B;AAEA;;;CAGC,GACD,OAAO,eAAeI,0BACpBC,OAAoC;IAEpC,MAAM,EAACC,cAAc,EAAEC,YAAY,EAAEC,MAAM,EAAEC,aAAa,EAAC,GA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AAME,UAAqB/C,cAAc0C,uBAAuB;QAC9DM,KAAKxB;QACLyB,eAAe;IACjB;IAEAF,QAAQG,EAAE,CAAC,OAAO,CAACC,OAAOC;QACxB,MAAMC,YAAY,IAAIzB,OAAO0B,kBAAkB;QAC/C,MAAMC,eAAe3D,WAAWwD,YAAYvD,SAAS2B,SAAS4B,YAAYA;QAC1EjC,OAAOkB,GAAG,CAAC,CAAC,CAAC,EAAEgB,UAAU,EAAE,EAAEF,MAAM,EAAE,EAAEI,cAAc;QACrDT;IACF;IAEAC,QAAQG,EAAE,CAAC,SAAS,CAACjB;QACnBd,OAAOoB,KAAK,CAAC,CAAC,eAAe,EAAEN,eAAeK,QAAQL,IAAIO,OAAO,GAAGgB,OAAOvB,MAAM;IACnF;IAEA,OAAO;QACLwB,OAAO,IAAMV,QAAQU,KAAK;QAC1BV;IACF;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isatty } from 'node:tty';
|
|
2
2
|
import { styleText } from 'node:util';
|
|
3
3
|
import { logSymbols } from '@sanity/cli-core/ux';
|
|
4
|
+
import { generateHelpUrl } from '@sanity/generate-help-url';
|
|
4
5
|
const isTty = isatty(1);
|
|
5
6
|
const headers = {
|
|
6
7
|
error: isTty ? styleText([
|
|
@@ -63,7 +64,10 @@ export function formatSchemaValidation(validation) {
|
|
|
63
64
|
const header = `${headers[getAggregatedSeverity(groups)]} ${formattedTopLevelType}`;
|
|
64
65
|
const body = groups.toSorted((a, b)=>severityValues[getAggregatedSeverity(a)] - severityValues[getAggregatedSeverity(b)]).map((group)=>{
|
|
65
66
|
const formattedPath = ` ${styleText('bold', formatPath(group.path) || '(root)')}`;
|
|
66
|
-
const formattedMessages = group.problems.toSorted((a, b)=>severityValues[a.severity] - severityValues[b.severity]).map(({ message, severity })
|
|
67
|
+
const formattedMessages = group.problems.toSorted((a, b)=>severityValues[a.severity] - severityValues[b.severity]).map(({ helpId, message, severity })=>{
|
|
68
|
+
const help = helpId ? `\n See ${generateHelpUrl(helpId)}` : '';
|
|
69
|
+
return ` ${logSymbols[severity]} ${message}${help}`;
|
|
70
|
+
}).join('\n');
|
|
67
71
|
return `${formattedPath}\n${formattedMessages}`;
|
|
68
72
|
}).join('\n');
|
|
69
73
|
return `${header}\n${body}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/schema/formatSchemaValidation.ts"],"sourcesContent":["import {isatty} from 'node:tty'\nimport {styleText} from 'node:util'\n\nimport {logSymbols} from '@sanity/cli-core/ux'\nimport {type SchemaValidationProblemGroup, type SchemaValidationProblemPath} from '@sanity/types'\n\nconst isTty = isatty(1)\n\nconst headers = {\n error: isTty ? styleText(['bold', 'bgRed', 'black'], ' ERROR ') : styleText('red', '[ERROR]'),\n warning: isTty\n ? styleText(['bold', 'bgYellow', 'black'], ' WARN ')\n : styleText('yellow', '[WARN]'),\n}\n\nconst severityValues = {error: 0, warning: 1}\n\nfunction formatPath(pathSegments: SchemaValidationProblemPath) {\n const format = (\n [curr, ...next]: SchemaValidationProblemPath,\n mode: 'array' | 'object' = 'object',\n ): string => {\n if (!curr) return ''\n if (curr.kind === 'property') return format(next, curr.name === 'of' ? 'array' : 'object')\n\n const name = curr.name || `<anonymous_${curr.type}>`\n return `${mode === 'array' ? `[${name}]` : `.${name}`}${format(next)}`\n }\n\n return format(pathSegments.slice(1)).slice(1) // removes the top-level type and leading `.`\n}\n\nexport function getAggregatedSeverity(\n groupOrGroups: SchemaValidationProblemGroup | SchemaValidationProblemGroup[],\n): 'error' | 'warning' {\n const groups = Array.isArray(groupOrGroups) ? groupOrGroups : [groupOrGroups]\n return groups\n .flatMap((group) => group.problems.map((problem) => problem.severity))\n .includes('error')\n ? 'error'\n : 'warning'\n}\n\nexport function formatSchemaValidation(validation: SchemaValidationProblemGroup[]): string {\n let unnamedTopLevelTypeCount = 0\n const validationByTypeMap: Record<string, SchemaValidationProblemGroup[]> = {}\n\n for (const group of validation) {\n const [firstSegment] = group.path\n if (!firstSegment) continue\n if (firstSegment.kind !== 'type') continue\n\n const topLevelType =\n firstSegment.name || `<unnamed_${firstSegment.type}_type_${unnamedTopLevelTypeCount++}>`\n\n if (!validationByTypeMap[topLevelType]) {\n validationByTypeMap[topLevelType] = []\n }\n\n validationByTypeMap[topLevelType].push(group)\n }\n\n const validationByType = Object.entries(validationByTypeMap)\n\n const formatted = validationByType\n .toSorted((a, b) => {\n const [aType, aGroups] = a\n const [bType, bGroups] = b\n const aValue = severityValues[getAggregatedSeverity(aGroups)]\n const bValue = severityValues[getAggregatedSeverity(bGroups)]\n if (aValue === bValue) return aType.localeCompare(bType, 'en-US')\n return aValue - bValue\n })\n .map(([topLevelType, groups]) => {\n const formattedTopLevelType = isTty\n ? styleText(['bgWhite', 'black'], ` ${topLevelType} `)\n : `[${topLevelType}]`\n\n const header = `${headers[getAggregatedSeverity(groups)]} ${formattedTopLevelType}`\n const body = groups\n .toSorted(\n (a, b) =>\n severityValues[getAggregatedSeverity(a)] - severityValues[getAggregatedSeverity(b)],\n )\n .map((group) => {\n const formattedPath = ` ${styleText('bold', formatPath(group.path) || '(root)')}`\n const formattedMessages = group.problems\n .toSorted((a, b) => severityValues[a.severity] - severityValues[b.severity])\n .map(({message, severity}) => ` ${logSymbols[severity]} ${message}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/schema/formatSchemaValidation.ts"],"sourcesContent":["import {isatty} from 'node:tty'\nimport {styleText} from 'node:util'\n\nimport {logSymbols} from '@sanity/cli-core/ux'\nimport {generateHelpUrl} from '@sanity/generate-help-url'\nimport {type SchemaValidationProblemGroup, type SchemaValidationProblemPath} from '@sanity/types'\n\nconst isTty = isatty(1)\n\nconst headers = {\n error: isTty ? styleText(['bold', 'bgRed', 'black'], ' ERROR ') : styleText('red', '[ERROR]'),\n warning: isTty\n ? styleText(['bold', 'bgYellow', 'black'], ' WARN ')\n : styleText('yellow', '[WARN]'),\n}\n\nconst severityValues = {error: 0, warning: 1}\n\nfunction formatPath(pathSegments: SchemaValidationProblemPath) {\n const format = (\n [curr, ...next]: SchemaValidationProblemPath,\n mode: 'array' | 'object' = 'object',\n ): string => {\n if (!curr) return ''\n if (curr.kind === 'property') return format(next, curr.name === 'of' ? 'array' : 'object')\n\n const name = curr.name || `<anonymous_${curr.type}>`\n return `${mode === 'array' ? `[${name}]` : `.${name}`}${format(next)}`\n }\n\n return format(pathSegments.slice(1)).slice(1) // removes the top-level type and leading `.`\n}\n\nexport function getAggregatedSeverity(\n groupOrGroups: SchemaValidationProblemGroup | SchemaValidationProblemGroup[],\n): 'error' | 'warning' {\n const groups = Array.isArray(groupOrGroups) ? groupOrGroups : [groupOrGroups]\n return groups\n .flatMap((group) => group.problems.map((problem) => problem.severity))\n .includes('error')\n ? 'error'\n : 'warning'\n}\n\nexport function formatSchemaValidation(validation: SchemaValidationProblemGroup[]): string {\n let unnamedTopLevelTypeCount = 0\n const validationByTypeMap: Record<string, SchemaValidationProblemGroup[]> = {}\n\n for (const group of validation) {\n const [firstSegment] = group.path\n if (!firstSegment) continue\n if (firstSegment.kind !== 'type') continue\n\n const topLevelType =\n firstSegment.name || `<unnamed_${firstSegment.type}_type_${unnamedTopLevelTypeCount++}>`\n\n if (!validationByTypeMap[topLevelType]) {\n validationByTypeMap[topLevelType] = []\n }\n\n validationByTypeMap[topLevelType].push(group)\n }\n\n const validationByType = Object.entries(validationByTypeMap)\n\n const formatted = validationByType\n .toSorted((a, b) => {\n const [aType, aGroups] = a\n const [bType, bGroups] = b\n const aValue = severityValues[getAggregatedSeverity(aGroups)]\n const bValue = severityValues[getAggregatedSeverity(bGroups)]\n if (aValue === bValue) return aType.localeCompare(bType, 'en-US')\n return aValue - bValue\n })\n .map(([topLevelType, groups]) => {\n const formattedTopLevelType = isTty\n ? styleText(['bgWhite', 'black'], ` ${topLevelType} `)\n : `[${topLevelType}]`\n\n const header = `${headers[getAggregatedSeverity(groups)]} ${formattedTopLevelType}`\n const body = groups\n .toSorted(\n (a, b) =>\n severityValues[getAggregatedSeverity(a)] - severityValues[getAggregatedSeverity(b)],\n )\n .map((group) => {\n const formattedPath = ` ${styleText('bold', formatPath(group.path) || '(root)')}`\n const formattedMessages = group.problems\n .toSorted((a, b) => severityValues[a.severity] - severityValues[b.severity])\n .map(({helpId, message, severity}) => {\n const help = helpId ? `\\n See ${generateHelpUrl(helpId)}` : ''\n return ` ${logSymbols[severity]} ${message}${help}`\n })\n .join('\\n')\n\n return `${formattedPath}\\n${formattedMessages}`\n })\n .join('\\n')\n\n return `${header}\\n${body}`\n })\n .join('\\n\\n')\n\n return formatted\n}\n"],"names":["isatty","styleText","logSymbols","generateHelpUrl","isTty","headers","error","warning","severityValues","formatPath","pathSegments","format","curr","next","mode","kind","name","type","slice","getAggregatedSeverity","groupOrGroups","groups","Array","isArray","flatMap","group","problems","map","problem","severity","includes","formatSchemaValidation","validation","unnamedTopLevelTypeCount","validationByTypeMap","firstSegment","path","topLevelType","push","validationByType","Object","entries","formatted","toSorted","a","b","aType","aGroups","bType","bGroups","aValue","bValue","localeCompare","formattedTopLevelType","header","body","formattedPath","formattedMessages","helpId","message","help","join"],"mappings":"AAAA,SAAQA,MAAM,QAAO,WAAU;AAC/B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,UAAU,QAAO,sBAAqB;AAC9C,SAAQC,eAAe,QAAO,4BAA2B;AAGzD,MAAMC,QAAQJ,OAAO;AAErB,MAAMK,UAAU;IACdC,OAAOF,QAAQH,UAAU;QAAC;QAAQ;QAAS;KAAQ,EAAE,aAAaA,UAAU,OAAO;IACnFM,SAASH,QACLH,UAAU;QAAC;QAAQ;QAAY;KAAQ,EAAE,YACzCA,UAAU,UAAU;AAC1B;AAEA,MAAMO,iBAAiB;IAACF,OAAO;IAAGC,SAAS;AAAC;AAE5C,SAASE,WAAWC,YAAyC;IAC3D,MAAMC,SAAS,CACb,CAACC,MAAM,GAAGC,KAAkC,EAC5CC,OAA2B,QAAQ;QAEnC,IAAI,CAACF,MAAM,OAAO;QAClB,IAAIA,KAA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B;QACjD,GACCI,IAAI,CAAC;QAER,OAAO,GAAGP,OAAO,EAAE,EAAEC,MAAM;IAC7B,GACCM,IAAI,CAAC;IAER,OAAOnB;AACT"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { join, resolve } from 'node:path';
|
|
2
|
+
export function getExtractOptions({ flags, projectRoot, schemaExtraction }) {
|
|
3
|
+
const pathFlag = flags.path ?? schemaExtraction?.path;
|
|
4
|
+
const outputDir = pathFlag ? resolve(join(projectRoot.directory, pathFlag)) : projectRoot.directory;
|
|
5
|
+
const outputPath = join(outputDir, 'schema.json');
|
|
6
|
+
return {
|
|
7
|
+
configPath: projectRoot.path,
|
|
8
|
+
enforceRequiredFields: flags['enforce-required-fields'] ?? schemaExtraction?.enforceRequiredFields ?? false,
|
|
9
|
+
format: flags.format ?? 'groq-type-nodes',
|
|
10
|
+
outputPath,
|
|
11
|
+
watchPatterns: flags['watch-patterns'] ?? schemaExtraction?.watchPatterns ?? [],
|
|
12
|
+
workspace: flags.workspace ?? schemaExtraction?.workspace
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=getExtractOptions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/schema/getExtractOptions.ts"],"sourcesContent":["import {join, resolve} from 'node:path'\n\nimport {type CliConfig, ProjectRootResult} from '@sanity/cli-core'\n\nimport {type ExtractSchemaCommand} from '../../commands/schema/extract.js'\n\nexport interface ExtractOptions {\n configPath: string\n enforceRequiredFields: boolean\n format: string\n outputPath: string\n watchPatterns: string[]\n workspace: string | undefined\n}\n\ninterface GetExtractionOptions {\n flags: ExtractSchemaCommand['flags']\n projectRoot: ProjectRootResult\n schemaExtraction: CliConfig['schemaExtraction']\n}\n\nexport function getExtractOptions({\n flags,\n projectRoot,\n schemaExtraction,\n}: GetExtractionOptions): ExtractOptions {\n const pathFlag = flags.path ?? schemaExtraction?.path\n const outputDir = pathFlag\n ? resolve(join(projectRoot.directory, pathFlag))\n : projectRoot.directory\n const outputPath = join(outputDir, 'schema.json')\n\n return {\n configPath: projectRoot.path,\n enforceRequiredFields:\n flags['enforce-required-fields'] ?? schemaExtraction?.enforceRequiredFields ?? false,\n format: flags.format ?? 'groq-type-nodes',\n outputPath,\n watchPatterns: flags['watch-patterns'] ?? schemaExtraction?.watchPatterns ?? [],\n workspace: flags.workspace ?? schemaExtraction?.workspace,\n }\n}\n"],"names":["join","resolve","getExtractOptions","flags","projectRoot","schemaExtraction","pathFlag","path","outputDir","directory","outputPath","configPath","enforceRequiredFields","format","watchPatterns","workspace"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,OAAO,QAAO,YAAW;AAqBvC,OAAO,SAASC,kBAAkB,EAChCC,KAAK,EACLC,WAAW,EACXC,gBAAgB,EACK;IACrB,MAAMC,WAAWH,MAAMI,IAAI,IAAIF,kBAAkBE;IACjD,MAAMC,YAAYF,WACdL,QAAQD,KAAKI,YAAYK,SAAS,EAAEH,aACpCF,YAAYK,SAAS;IACzB,MAAMC,aAAaV,KAAKQ,WAAW;IAEnC,OAAO;QACLG,YAAYP,YAAYG,IAAI;QAC5BK,uBACET,KAAK,CAAC,0BAA0B,IAAIE,kBAAkBO,yBAAyB;QACjFC,QAAQV,MAAMU,MAAM,IAAI;QACxBH;QACAI,eAAeX,KAAK,CAAC,iBAAiB,IAAIE,kBAAkBS,iBAAiB,EAAE;QAC/EC,WAAWZ,MAAMY,SAAS,IAAIV,kBAAkBU;IAClD;AACF"}
|