@sanity/cli-build 5.1.0 → 5.2.1

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.
@@ -1,59 +1,70 @@
1
- import { CliConfig } from "@sanity/cli-core/types";
2
- import { ConfigEnv } from "vite";
3
- import { FSWatcher } from "chokidar";
4
- import { InlineConfig } from "vite";
5
- import { Output } from "@sanity/cli-core/types";
6
- import { Plugin } from "vite";
7
- import { PluginOptions } from "babel-plugin-react-compiler";
8
- import { UserViteConfig } from "@sanity/cli-core/types";
1
+ import { CliConfig, Output, UserViteConfig } from "@sanity/cli-core/types";
9
2
  import { WorkbenchExposes } from "@sanity/workbench-cli/build";
10
-
3
+ import { PluginOptions } from "babel-plugin-react-compiler";
4
+ import { ConfigEnv, InlineConfig, Plugin } from "vite";
5
+ import { FSWatcher } from "chokidar";
6
+ interface CompareDependencyVersions {
7
+ installed: string;
8
+ pkg: string;
9
+ remote: string;
10
+ }
11
+ interface UnresolvedPrerelease {
12
+ pkg: string;
13
+ version: string;
14
+ }
15
+ interface CompareDependencyVersionsResult {
16
+ mismatched: Array<CompareDependencyVersions>;
17
+ unresolvedPrerelease: Array<UnresolvedPrerelease>;
18
+ }
19
+ interface CompareDependencyVersionsOptions {
20
+ /** When provided, uses the app-specific module endpoint instead of the default endpoint. */
21
+ appId?: string;
22
+ }
11
23
  /**
12
- * Everything the production build needs to produce an auto-updating studio/app.
24
+ * @internal
13
25
  *
14
- * Auto-updating deployments load `sanity` (and friends) from Sanity's module
15
- * CDN via an import map, and load `react`/`react-dom`/`styled-components` from
16
- * hashed vendor chunks emitted by the build itself. These concerns always come
17
- * together: when auto-updates are disabled none of this applies and everything
18
- * is bundled as usual.
26
+ * Compares the versions of dependencies in the studio or app with their remote versions.
19
27
  *
20
- * @internal
21
- */
22
- declare interface AutoUpdatesBuildConfig {
23
- /** Import map entries for the packages served from Sanity's module CDN. */
24
- imports: Record<string, string>;
25
- /** Vendor packages to emit as hashed browser-loadable ESM chunks. */
26
- vendor: VendorBuildConfig;
27
- /** Stylesheets served from the module CDN, loaded via `<link>` tags. */
28
- cssUrls?: string[];
29
- }
30
-
31
- /**
32
- * Internal build app that avoids depending on flags for CLI config.
33
- * @param options - options for the build
28
+ * This function reads the package.json file in the provided working directory, and compares the versions of the dependencies
29
+ * specified in the `autoUpdatesImports` parameter with their remote versions. If the versions do not match, the dependency is
30
+ * added to a list of failed dependencies, which is returned by the function.
31
+ *
32
+ * The failed dependencies are anything that does not strictly match the remote version.
33
+ * This means that if a version is lower or greater by even a patch it will be marked as failed.
34
+ *
35
+ * @param packages - An array of packages with their name and version to compare against remote.
36
+ * @param workDir - The path to the working directory containing the package.json file.
37
+ * @param options - Optional configuration for version comparison.
38
+ *
39
+ * @returns A promise that resolves to an object containing `mismatched` (packages whose local and remote versions differ)
40
+ * and `unresolvedPrerelease` (packages with prerelease versions that could not be resolved remotely).
41
+ *
42
+ * @throws Throws an error if the remote version of a non-prerelease package cannot be fetched, or if the local version
43
+ * of a package cannot be parsed.
34
44
  */
35
- export declare function buildApp(options: BuildOptions): Promise<void>;
36
-
37
- export declare type BuildAppEventListener = BuildEventListener;
38
-
39
- declare interface BuildEventListener {
45
+ declare function compareDependencyVersions(packages: {
46
+ name: string;
47
+ version: string;
48
+ }[], workDir: string, { appId }?: CompareDependencyVersionsOptions): Promise<CompareDependencyVersionsResult>;
49
+ type MessageFunc = ({ message }: {
50
+ message: string;
51
+ }) => void;
52
+ interface BuildEventListener {
40
53
  onPreReleaseInInteractiveAutoUpdate(params: {
41
54
  prereleaseMessage: string;
42
55
  }): Promise<void>;
43
56
  onPreReleaseInNonInteractiveAutoUpdate: MessageFunc;
44
57
  }
45
-
46
- declare interface BuildOptions {
58
+ type BuildAppEventListener = BuildEventListener;
59
+ interface BuildOptions$1 {
47
60
  appId: string | undefined;
48
61
  appTitle: string | undefined;
49
62
  autoUpdatesEnabled: boolean;
50
63
  checkAppId: () => void;
51
- compareDependencyVersions: (
52
- packages: {
53
- name: string;
54
- version: string;
55
- }[],
56
- ) => Promise<CompareDependencyVersionsResult>;
64
+ compareDependencyVersions: (packages: {
65
+ name: string;
66
+ version: string;
67
+ }[]) => Promise<CompareDependencyVersionsResult>;
57
68
  determineBasePath: () => string;
58
69
  entry: string | undefined;
59
70
  eventListener: Partial<BuildAppEventListener>;
@@ -61,8 +72,8 @@ declare interface BuildOptions {
61
72
  minify: boolean;
62
73
  outDir: string | undefined;
63
74
  output: Output;
64
- reactCompiler: CliConfig["reactCompiler"];
65
- schemaExtraction: CliConfig["schemaExtraction"];
75
+ reactCompiler: CliConfig['reactCompiler'];
76
+ schemaExtraction: CliConfig['schemaExtraction'];
66
77
  sourceMap: boolean;
67
78
  stats: boolean;
68
79
  unattendedMode: boolean;
@@ -72,52 +83,87 @@ declare interface BuildOptions {
72
83
  /** The workbench app's bus identity (`__SANITY_APP_ID__`). */
73
84
  workbenchAppId?: string;
74
85
  }
75
-
76
- declare interface BuildOptions_2 {
77
- appId: string | undefined;
78
- autoUpdatesEnabled: boolean;
79
- checkAppId: () => void;
80
- compareDependencyVersions: (
81
- packages: {
82
- name: string;
83
- version: string;
84
- }[],
85
- ) => Promise<CompareDependencyVersionsResult>;
86
- determineBasePath: () => string;
87
- eventListener: Partial<BuildStudioEventListener>;
86
+ /**
87
+ * Internal build app that avoids depending on flags for CLI config.
88
+ * @param options - options for the build
89
+ */
90
+ declare function buildApp(options: BuildOptions$1): Promise<void>;
91
+ interface VendorBuildConfig {
92
+ /** Rolldown entry name -\> absolute path to the package entry file. */
93
+ entries: Record<string, string>;
94
+ /** Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name. */
95
+ namesByChunkName: Record<string, readonly string[]>;
96
+ /** Rolldown entry chunk name -\> bare import specifier (e.g. `react`, `react-dom/client`). */
97
+ specifiersByChunkName: Record<string, string>;
98
+ }
99
+ interface ResolveVendorBuildConfigOptions {
100
+ cwd: string;
88
101
  isApp: boolean;
89
- isWorkbenchApp: boolean;
90
- minify: boolean;
91
- outDir: string | undefined;
92
- output: Output;
93
- reactCompiler: boolean | CliConfig["reactCompiler"] | undefined;
94
- schemaExtraction: CliConfig["schemaExtraction"];
95
- sourceMap: boolean;
96
- stats: boolean;
97
- unattendedMode: boolean;
98
- vite: UserViteConfig | undefined;
99
- workDir: string;
102
+ }
103
+ /**
104
+ * Resolves vendor package entry points and metadata for a combined studio/app build.
105
+ * Does not run a build — callers add `entries` to the main Vite/Rolldown input and
106
+ * derive the import map from emitted vendor chunks after the single `vite.build`.
107
+ *
108
+ * @internal
109
+ */
110
+ declare function resolveVendorBuildConfig({ cwd, isApp }: ResolveVendorBuildConfigOptions): Promise<VendorBuildConfig>;
111
+ /**
112
+ * Everything the production build needs to produce an auto-updating studio/app.
113
+ *
114
+ * Auto-updating deployments load `sanity` (and friends) from Sanity's module
115
+ * CDN via an import map, and load `react`/`react-dom`/`styled-components` from
116
+ * hashed vendor chunks emitted by the build itself. These concerns always come
117
+ * together: when auto-updates are disabled none of this applies and everything
118
+ * is bundled as usual.
119
+ *
120
+ * @internal
121
+ */
122
+ interface AutoUpdatesBuildConfig {
123
+ /** Import map entries for the packages served from Sanity's module CDN. */
124
+ imports: Record<string, string>;
125
+ /** Vendor packages to emit as hashed browser-loadable ESM chunks. */
126
+ vendor: VendorBuildConfig;
127
+ /** Stylesheets served from the module CDN, loaded via `<link>` tags. */
128
+ cssUrls?: string[];
129
+ }
130
+ interface ChunkModule {
131
+ name: string;
132
+ renderedLength: number;
133
+ }
134
+ interface ChunkStats {
135
+ modules: ChunkModule[];
136
+ name: string;
137
+ }
138
+ interface StaticBuildOptions {
139
+ basePath: string;
140
+ cwd: string;
141
+ outputDir: string;
142
+ appTitle?: string;
143
+ autoUpdates?: AutoUpdatesBuildConfig;
144
+ entry?: string;
100
145
  exposes?: WorkbenchExposes;
146
+ isApp?: boolean;
147
+ /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */
148
+ isWorkbenchApp?: boolean;
149
+ minify?: boolean;
150
+ profile?: boolean;
151
+ reactCompiler?: boolean | PluginOptions;
152
+ schemaExtraction?: CliConfig['schemaExtraction'];
153
+ sourceMap?: boolean;
154
+ vite?: UserViteConfig;
101
155
  /** The workbench app's bus identity (`__SANITY_APP_ID__`). */
102
156
  workbenchAppId?: string;
103
157
  }
104
-
105
158
  /**
106
159
  * Builds static files
107
160
  *
108
161
  * @internal
109
162
  */
110
- export declare function buildStaticFiles(options: StaticBuildOptions): Promise<{
163
+ declare function buildStaticFiles(options: StaticBuildOptions): Promise<{
111
164
  chunks: ChunkStats[];
112
165
  }>;
113
-
114
- /**
115
- * Internal build studio that avoids depending on flags for CLI config.
116
- * @param options - options for the build
117
- */
118
- export declare function buildStudio(options: BuildOptions_2): Promise<void>;
119
-
120
- export declare interface BuildStudioEventListener extends BuildEventListener {
166
+ interface BuildStudioEventListener extends BuildEventListener {
121
167
  onBuildEnd: MessageFunc;
122
168
  onBuildFail: MessageFunc;
123
169
  onBuildStart: MessageFunc;
@@ -125,7 +171,9 @@ export declare interface BuildStudioEventListener extends BuildEventListener {
125
171
  onCleanOutputDirStart: MessageFunc;
126
172
  onIncompatibleDeclaredStyledComponentsVersionRange: MessageFunc;
127
173
  onIncompatibleInstalledStyledComponentsVersionRange: MessageFunc;
128
- onInteractiveNonDefaultOutputDir({ message }: { message: string }): Promise<{
174
+ onInteractiveNonDefaultOutputDir({ message }: {
175
+ message: string;
176
+ }): Promise<{
129
177
  shouldClean: boolean;
130
178
  }>;
131
179
  onInvalidStyledComponentsVersionRange: MessageFunc;
@@ -142,207 +190,71 @@ export declare interface BuildStudioEventListener extends BuildEventListener {
142
190
  versionMismatchWarning: string;
143
191
  }): void;
144
192
  }
145
-
146
- /**
147
- * Checks that the studio has declared and installed the required dependencies
148
- * needed by the Sanity modules. While we generally use regular, explicit
149
- * dependencies in modules, there are certain dependencies that are better
150
- * served being peer dependencies, such as react and styled-components.
151
- *
152
- * If these dependencies are not installed/declared, we report an error
153
- * and instruct the user to install them manually.
154
- *
155
- * Additionally, returns the version of the 'sanity' dependency from the package.json.
156
- */
157
- export declare function checkRequiredDependencies(
158
- options: CheckRequiredDependenciesOptions,
159
- ): Promise<CheckResult>;
160
-
161
- declare interface CheckRequiredDependenciesOptions {
193
+ interface BuildOptions {
194
+ appId: string | undefined;
195
+ autoUpdatesEnabled: boolean;
196
+ checkAppId: () => void;
197
+ compareDependencyVersions: (packages: {
198
+ name: string;
199
+ version: string;
200
+ }[]) => Promise<CompareDependencyVersionsResult>;
201
+ determineBasePath: () => string;
202
+ eventListener: Partial<BuildStudioEventListener>;
162
203
  isApp: boolean;
204
+ isWorkbenchApp: boolean;
205
+ minify: boolean;
206
+ outDir: string | undefined;
207
+ output: Output;
208
+ reactCompiler: boolean | CliConfig['reactCompiler'] | undefined;
209
+ schemaExtraction: CliConfig['schemaExtraction'];
210
+ sourceMap: boolean;
211
+ stats: boolean;
212
+ unattendedMode: boolean;
213
+ vite: UserViteConfig | undefined;
163
214
  workDir: string;
164
- onIncompatibleDeclaredStyledComponentsVersionRange?: BuildStudioEventListener["onIncompatibleDeclaredStyledComponentsVersionRange"];
165
- onIncompatibleInstalledStyledComponentsVersionRange?: BuildStudioEventListener["onIncompatibleInstalledStyledComponentsVersionRange"];
166
- onInvalidStyledComponentsVersionRange?: BuildStudioEventListener["onInvalidStyledComponentsVersionRange"];
167
- onNoDeclaredStyledComponentsVersion?: BuildStudioEventListener["onNoDeclaredStyledComponentsVersion"];
168
- onNoInstalledSanityVersion?: BuildStudioEventListener["onNoInstalledSanityVersion"];
169
- onNoInstalledStyledComponentsVersion?: BuildStudioEventListener["onNoInstalledStyledComponentsVersion"];
170
- }
171
-
172
- declare interface CheckResult {
173
- installedSanityVersion: string;
174
- }
175
-
176
- export declare function checkStudioDependencyVersions(
177
- workDir: string,
178
- output: Output,
179
- {
180
- packages,
181
- }?: {
182
- packages?: TrackedPackage[];
183
- },
184
- ): Promise<void>;
185
-
186
- declare interface ChunkModule {
187
- name: string;
188
- renderedLength: number;
189
- }
190
-
191
- declare interface ChunkStats {
192
- modules: ChunkModule[];
193
- name: string;
194
- }
195
-
196
- export declare interface CompareDependencyVersions {
197
- installed: string;
198
- pkg: string;
199
- remote: string;
215
+ exposes?: WorkbenchExposes;
216
+ /** The workbench app's bus identity (`__SANITY_APP_ID__`). */
217
+ workbenchAppId?: string;
200
218
  }
201
-
202
219
  /**
203
- * @internal
204
- *
205
- * Compares the versions of dependencies in the studio or app with their remote versions.
206
- *
207
- * This function reads the package.json file in the provided working directory, and compares the versions of the dependencies
208
- * specified in the `autoUpdatesImports` parameter with their remote versions. If the versions do not match, the dependency is
209
- * added to a list of failed dependencies, which is returned by the function.
210
- *
211
- * The failed dependencies are anything that does not strictly match the remote version.
212
- * This means that if a version is lower or greater by even a patch it will be marked as failed.
213
- *
214
- * @param packages - An array of packages with their name and version to compare against remote.
215
- * @param workDir - The path to the working directory containing the package.json file.
216
- * @param options - Optional configuration for version comparison.
217
- *
218
- * @returns A promise that resolves to an object containing `mismatched` (packages whose local and remote versions differ)
219
- * and `unresolvedPrerelease` (packages with prerelease versions that could not be resolved remotely).
220
- *
221
- * @throws Throws an error if the remote version of a non-prerelease package cannot be fetched, or if the local version
222
- * of a package cannot be parsed.
220
+ * Internal build studio that avoids depending on flags for CLI config.
221
+ * @param options - options for the build
223
222
  */
224
- export declare function compareDependencyVersions(
225
- packages: {
226
- name: string;
227
- version: string;
228
- }[],
229
- workDir: string,
230
- { appId }?: CompareDependencyVersionsOptions,
231
- ): Promise<CompareDependencyVersionsResult>;
232
-
233
- declare interface CompareDependencyVersionsOptions {
234
- /** When provided, uses the app-specific module endpoint instead of the default endpoint. */
235
- appId?: string;
223
+ declare function buildStudio(options: BuildOptions): Promise<void>;
224
+ interface CheckResult {
225
+ installedSanityVersion: string;
236
226
  }
237
-
238
- export declare interface CompareDependencyVersionsResult {
239
- mismatched: Array<CompareDependencyVersions>;
240
- unresolvedPrerelease: Array<UnresolvedPrerelease>;
227
+ interface CheckRequiredDependenciesOptions {
228
+ isApp: boolean;
229
+ workDir: string;
230
+ onIncompatibleDeclaredStyledComponentsVersionRange?: BuildStudioEventListener['onIncompatibleDeclaredStyledComponentsVersionRange'];
231
+ onIncompatibleInstalledStyledComponentsVersionRange?: BuildStudioEventListener['onIncompatibleInstalledStyledComponentsVersionRange'];
232
+ onInvalidStyledComponentsVersionRange?: BuildStudioEventListener['onInvalidStyledComponentsVersionRange'];
233
+ onNoDeclaredStyledComponentsVersion?: BuildStudioEventListener['onNoDeclaredStyledComponentsVersion'];
234
+ onNoInstalledSanityVersion?: BuildStudioEventListener['onNoInstalledSanityVersion'];
235
+ onNoInstalledStyledComponentsVersion?: BuildStudioEventListener['onNoInstalledStyledComponentsVersion'];
241
236
  }
242
-
243
- /**
244
- * Merge user-provided Vite configuration object or function
245
- *
246
- * @param defaultConfig - Default configuration object
247
- * @param userConfig - User-provided configuration object or function
248
- * @returns Merged configuration
249
- * @internal
250
- */
251
- export declare function extendViteConfigWithUserConfig(
252
- env: ConfigEnv,
253
- defaultConfig: InlineConfig,
254
- userConfig: UserViteConfig,
255
- ): Promise<InlineConfig>;
256
-
257
237
  /**
258
- * Get a configuration object for Vite based on the passed options
238
+ * Checks that the studio has declared and installed the required dependencies
239
+ * needed by the Sanity modules. While we generally use regular, explicit
240
+ * dependencies in modules, there are certain dependencies that are better
241
+ * served being peer dependencies, such as react and styled-components.
259
242
  *
260
- * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
261
- */
262
- export declare function getViteConfig(
263
- options: ViteOptions,
264
- ): Promise<InlineConfig>;
265
-
266
- declare type MessageFunc = ({ message }: { message: string }) => void;
267
-
268
- /**
269
- * Resolves vendor package entry points and metadata for a combined studio/app build.
270
- * Does not run a build — callers add `entries` to the main Vite/Rolldown input and
271
- * derive the import map from emitted vendor chunks after the single `vite.build`.
243
+ * If these dependencies are not installed/declared, we report an error
244
+ * and instruct the user to install them manually.
272
245
  *
273
- * @internal
274
- */
275
- export declare function resolveVendorBuildConfig({
276
- cwd,
277
- isApp,
278
- }: ResolveVendorBuildConfigOptions): Promise<VendorBuildConfig>;
279
-
280
- declare interface ResolveVendorBuildConfigOptions {
281
- cwd: string;
282
- isApp: boolean;
283
- }
284
-
285
- declare interface RuntimeOptions {
286
- cwd: string;
287
- reactStrictMode: boolean | undefined;
288
- watch: boolean;
289
- appTitle?: string;
290
- basePath?: string;
291
- entry?: string;
292
- isApp?: boolean;
293
- isWorkbenchApp?: boolean;
294
- }
295
-
296
- /**
297
- * Root directory (relative to the project) used by Sanity tooling for
298
- * build-time artifacts and caches — Vite's `cacheDir` and the dev-time
299
- * manifest output. Lives under `node_modules/` so it's out of `dist` and
300
- * ignored by default in typical `.gitignore` files.
246
+ * Additionally, returns the version of the 'sanity' dependency from the package.json.
301
247
  */
302
- export declare const SANITY_CACHE_DIR = "node_modules/.sanity";
303
-
304
- declare interface StaticBuildOptions {
305
- basePath: string;
306
- cwd: string;
307
- outputDir: string;
308
- appTitle?: string;
309
- autoUpdates?: AutoUpdatesBuildConfig;
310
- entry?: string;
311
- exposes?: WorkbenchExposes;
312
- isApp?: boolean;
313
- /** Workbench app (opted in via `unstable_defineApp`) — drives the federation build. */
314
- isWorkbenchApp?: boolean;
315
- minify?: boolean;
316
- profile?: boolean;
317
- reactCompiler?: boolean | PluginOptions;
318
- schemaExtraction?: CliConfig["schemaExtraction"];
319
- sourceMap?: boolean;
320
- vite?: UserViteConfig;
321
- /** The workbench app's bus identity (`__SANITY_APP_ID__`). */
322
- workbenchAppId?: string;
323
- }
324
-
325
- declare interface TrackedPackage {
248
+ declare function checkRequiredDependencies(options: CheckRequiredDependenciesOptions): Promise<CheckResult>;
249
+ interface TrackedPackage {
326
250
  deprecatedBelow: string | null;
327
251
  name: string;
328
252
  supported: string[];
329
253
  }
330
-
331
- export declare interface UnresolvedPrerelease {
332
- pkg: string;
333
- version: string;
334
- }
335
-
336
- declare interface VendorBuildConfig {
337
- /** Rolldown entry name -\> absolute path to the package entry file. */
338
- entries: Record<string, string>;
339
- /** Named exports each CommonJS entry must re-expose as ESM, keyed by chunk name. */
340
- namesByChunkName: Record<string, readonly string[]>;
341
- /** Rolldown entry chunk name -\> bare import specifier (e.g. `react`, `react-dom/client`). */
342
- specifiersByChunkName: Record<string, string>;
343
- }
344
-
345
- declare interface ViteOptions {
254
+ declare function checkStudioDependencyVersions(workDir: string, output: Output, { packages }?: {
255
+ packages?: TrackedPackage[];
256
+ }): Promise<void>;
257
+ interface ViteOptions {
346
258
  /**
347
259
  * Root path of the studio/sanity app
348
260
  */
@@ -358,7 +270,7 @@ declare interface ViteOptions {
358
270
  /**
359
271
  * Mode to run vite in - eg development or production
360
272
  */
361
- mode: "development" | "production";
273
+ mode: 'development' | 'production';
362
274
  reactCompiler: boolean | PluginOptions | undefined;
363
275
  /**
364
276
  * Additional plugins when configured, eg. typegen
@@ -393,7 +305,7 @@ declare interface ViteOptions {
393
305
  /**
394
306
  * Schema extraction configuration
395
307
  */
396
- schemaExtraction?: CliConfig["schemaExtraction"];
308
+ schemaExtraction?: CliConfig['schemaExtraction'];
397
309
  /**
398
310
  * HTTP development server configuration
399
311
  */
@@ -411,7 +323,31 @@ declare interface ViteOptions {
411
323
  */
412
324
  workbenchAppId?: string;
413
325
  }
414
-
326
+ /**
327
+ * Get a configuration object for Vite based on the passed options
328
+ *
329
+ * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally
330
+ */
331
+ declare function getViteConfig(options: ViteOptions): Promise<InlineConfig>;
332
+ /**
333
+ * Merge user-provided Vite configuration object or function
334
+ *
335
+ * @param defaultConfig - Default configuration object
336
+ * @param userConfig - User-provided configuration object or function
337
+ * @returns Merged configuration
338
+ * @internal
339
+ */
340
+ declare function extendViteConfigWithUserConfig(env: ConfigEnv, defaultConfig: InlineConfig, userConfig: UserViteConfig): Promise<InlineConfig>;
341
+ interface RuntimeOptions {
342
+ cwd: string;
343
+ reactStrictMode: boolean | undefined;
344
+ watch: boolean;
345
+ appTitle?: string;
346
+ basePath?: string;
347
+ entry?: string;
348
+ isApp?: boolean;
349
+ isWorkbenchApp?: boolean;
350
+ }
415
351
  /**
416
352
  * Generates the `.sanity/runtime` directory, and optionally watches for custom
417
353
  * document files, rebuilding when they change
@@ -420,12 +356,19 @@ declare interface ViteOptions {
420
356
  * @returns A watcher instance if watch is enabled, undefined otherwise
421
357
  * @internal
422
358
  */
423
- export declare function writeSanityRuntime(options: RuntimeOptions): Promise<{
359
+ declare function writeSanityRuntime(options: RuntimeOptions): Promise<{
424
360
  entries: {
425
361
  relativeConfigLocation: string | null;
426
362
  relativeEntry: string | null;
427
363
  };
428
364
  watcher: FSWatcher | undefined;
429
365
  }>;
430
-
431
- export {};
366
+ /**
367
+ * Root directory (relative to the project) used by Sanity tooling for
368
+ * build-time artifacts and caches — Vite's `cacheDir` and the dev-time
369
+ * manifest output. Lives under `node_modules/` so it's out of `dist` and
370
+ * ignored by default in typical `.gitignore` files.
371
+ */
372
+ declare const SANITY_CACHE_DIR = "node_modules/.sanity";
373
+ export { type BuildAppEventListener, type BuildStudioEventListener, type CompareDependencyVersions, type CompareDependencyVersionsResult, SANITY_CACHE_DIR, type UnresolvedPrerelease, buildApp, buildStaticFiles, buildStudio, checkRequiredDependencies, checkStudioDependencyVersions, compareDependencyVersions, extendViteConfigWithUserConfig, getViteConfig, resolveVendorBuildConfig, writeSanityRuntime };
374
+ //# sourceMappingURL=build.d.ts.map
@@ -1,53 +1,20 @@
1
- /**
2
- * Get environment variables prefixed with SANITY_APP_, as an object.
3
- *
4
- * @param options - Options for the environment variable loading
5
- * {@link StudioEnvVariablesOptions}
6
- * @returns Object of app environment variables
7
- *
8
- * @internal
9
- */
10
- export declare function getAppEnvironmentVariables(
11
- options?: StudioEnvVariablesOptions,
12
- ): Record<string, string>;
13
-
14
- /**
15
- * Get environment variables prefixed with SANITY_STUDIO_, as an object.
16
- *
17
- * @param options - Options for the environment variable loading
18
- * {@link StudioEnvVariablesOptions}
19
- * @returns Object of studio environment variables
20
- *
21
- * @example
22
- * ```tsx
23
- * getStudioEnvironmentVariables({prefix: 'process.env.', jsonEncode: true})
24
- * ```
25
- *
26
- * @public
27
- */
28
- export declare function getStudioEnvironmentVariables(
29
- options?: StudioEnvVariablesOptions,
30
- ): Record<string, string>;
31
-
32
1
  /**
33
2
  * The params for the `getStudioEnvironmentVariables` and `getAppEnvironmentVariables` function
34
3
  * that gets Studio/App-focused environment variables.
35
4
  *
36
5
  * @public
37
6
  */
38
- export declare interface StudioEnvVariablesOptions {
7
+ interface StudioEnvVariablesOptions {
39
8
  /**
40
9
  * When specified includes environment variables from dotenv files (`.env`), in the same way the studio does.
41
10
  * A `mode` must be specified, usually `development`
42
11
  * or `production`, which will load the corresponding `.env.development` or `.env.production`.
43
12
  * To specify where to look for the dotenv files, specify `options.envFile.envDir`.
44
13
  */
45
- envFile?:
46
- | false
47
- | {
48
- envDir?: string;
49
- mode: string;
50
- };
14
+ envFile?: false | {
15
+ envDir?: string;
16
+ mode: string;
17
+ };
51
18
  /**
52
19
  * When specified, JSON-encodes the values, which is handy if you want to pass
53
20
  * this to a bundlers hardcoded defines, such as Vite's `define` or Webpack's `DefinePlugin`.
@@ -59,5 +26,30 @@ export declare interface StudioEnvVariablesOptions {
59
26
  */
60
27
  prefix?: string;
61
28
  }
62
-
63
- export {};
29
+ /**
30
+ * Get environment variables prefixed with SANITY_STUDIO_, as an object.
31
+ *
32
+ * @param options - Options for the environment variable loading
33
+ * {@link StudioEnvVariablesOptions}
34
+ * @returns Object of studio environment variables
35
+ *
36
+ * @example
37
+ * ```tsx
38
+ * getStudioEnvironmentVariables({prefix: 'process.env.', jsonEncode: true})
39
+ * ```
40
+ *
41
+ * @public
42
+ */
43
+ declare function getStudioEnvironmentVariables(options?: StudioEnvVariablesOptions): Record<string, string>;
44
+ /**
45
+ * Get environment variables prefixed with SANITY_APP_, as an object.
46
+ *
47
+ * @param options - Options for the environment variable loading
48
+ * {@link StudioEnvVariablesOptions}
49
+ * @returns Object of app environment variables
50
+ *
51
+ * @internal
52
+ */
53
+ declare function getAppEnvironmentVariables(options?: StudioEnvVariablesOptions): Record<string, string>;
54
+ export { type StudioEnvVariablesOptions, getAppEnvironmentVariables, getStudioEnvironmentVariables };
55
+ //# sourceMappingURL=env.d.ts.map
@@ -1,21 +1,10 @@
1
- import { DefinedTelemetryTrace } from "@sanity/telemetry";
2
- import { extractSchema } from "@sanity/schema/_internal";
3
1
  import { ProjectRootResult } from "@sanity/cli-core/types";
4
2
  import { SchemaValidationProblemGroup } from "@sanity/types";
5
-
6
- /**
7
- * Creates a pattern matcher function for schema watch patterns.
8
- * Normalizes file paths to forward slashes and makes them relative before matching.
9
- *
10
- * @param patterns - Array of glob patterns to match against
11
- * @returns Function that takes a file path and workDir, returns true if file matches any pattern
12
- * @internal
13
- */
14
- export declare function createSchemaPatternMatcher(patterns: string[]): {
15
- isMatch: (filePath: string, workDir: string) => boolean;
16
- };
17
-
18
- export declare interface ExtractOptions {
3
+ import { extractSchema } from "@sanity/schema/_internal";
4
+ import "zod/mini";
5
+ declare function getAggregatedSeverity(groupOrGroups: SchemaValidationProblemGroup | SchemaValidationProblemGroup[]): 'error' | 'warning';
6
+ declare function formatSchemaValidation(validation: SchemaValidationProblemGroup[]): string;
7
+ interface ExtractOptions {
19
8
  configPath: string;
20
9
  enforceRequiredFields: boolean;
21
10
  format: string;
@@ -23,31 +12,7 @@ export declare interface ExtractOptions {
23
12
  watchPatterns: string[];
24
13
  workspace: string | undefined;
25
14
  }
26
-
27
- /** @internal */
28
- export declare interface ExtractSchemaWorkerError {
29
- error: string;
30
- type: "error";
31
- validation?: SchemaValidationProblemGroup[];
32
- }
33
-
34
- /**
35
- * Extracts validation problem groups from a SchemaError.
36
- */
37
- export declare function extractValidationFromSchemaError(
38
- error: unknown,
39
- workDir: string,
40
- ): Promise<SchemaValidationProblemGroup[] | undefined>;
41
-
42
- export declare function formatSchemaValidation(
43
- validation: SchemaValidationProblemGroup[],
44
- ): string;
45
-
46
- export declare function getAggregatedSeverity(
47
- groupOrGroups: SchemaValidationProblemGroup | SchemaValidationProblemGroup[],
48
- ): "error" | "warning";
49
-
50
- declare interface GetExtractOptions {
15
+ interface GetExtractOptions {
51
16
  enforceRequiredFields: boolean | undefined;
52
17
  format: string | undefined;
53
18
  path: string | undefined;
@@ -55,66 +20,63 @@ declare interface GetExtractOptions {
55
20
  watchPatterns: string[] | undefined;
56
21
  workspace: string | undefined;
57
22
  }
58
-
59
- export declare function getExtractOptions(
60
- options: GetExtractOptions,
61
- ): ExtractOptions;
62
-
23
+ declare function getExtractOptions(options: GetExtractOptions): ExtractOptions;
24
+ /**
25
+ * Creates a pattern matcher function for schema watch patterns.
26
+ * Normalizes file paths to forward slashes and makes them relative before matching.
27
+ *
28
+ * @param patterns - Array of glob patterns to match against
29
+ * @returns Function that takes a file path and workDir, returns true if file matches any pattern
30
+ * @internal
31
+ */
32
+ declare function createSchemaPatternMatcher(patterns: string[]): {
33
+ isMatch: (filePath: string, workDir: string) => boolean;
34
+ };
63
35
  /**
64
36
  * Core schema extraction logic.
65
37
  * Performs the extraction via worker and writes to file.
66
38
  * Throws SchemaExtractionError on failure.
67
39
  */
68
- export declare function runSchemaExtraction(
69
- extractOptions: Omit<ExtractOptions, "watchPatterns">,
70
- ): Promise<ReturnType<typeof extractSchema>>;
71
-
72
- export declare const SchemaDeploy: DefinedTelemetryTrace<
73
- SchemaDeployTraceData,
74
- void
75
- >;
76
-
77
- declare interface SchemaDeployTraceData {
78
- manifestDir: string;
79
- schemaRequired: boolean;
80
- extractManifest?: boolean;
40
+ declare function runSchemaExtraction(extractOptions: Omit<ExtractOptions, 'watchPatterns'>): Promise<ReturnType<typeof extractSchema>>;
41
+ /** @internal */
42
+ interface ExtractSchemaWorkerError {
43
+ error: string;
44
+ type: 'error';
45
+ validation?: SchemaValidationProblemGroup[];
46
+ }
47
+ /**
48
+ * Extracts validation problem groups from a SchemaError.
49
+ */
50
+ declare function extractValidationFromSchemaError(error: unknown, workDir: string): Promise<SchemaValidationProblemGroup[] | undefined>;
51
+ declare class SchemaExtractionError extends Error {
52
+ validation?: SchemaValidationProblemGroup[];
53
+ constructor(message: string, validation?: SchemaValidationProblemGroup[]);
81
54
  }
82
-
83
- export declare const SchemaExtractedTrace: DefinedTelemetryTrace<
84
- SchemaExtractedTraceAttributes,
85
- void
86
- >;
87
-
88
- declare interface SchemaExtractedTraceAttributes {
55
+ interface SchemaExtractedTraceAttributes {
89
56
  enforceRequiredFields: boolean;
90
57
  schemaAllTypesCount: number;
91
58
  schemaDocumentTypesCount: number;
92
59
  schemaFormat: string;
93
60
  schemaTypesCount: number;
94
61
  }
95
-
96
- export declare class SchemaExtractionError extends Error {
97
- validation?: SchemaValidationProblemGroup[];
98
- constructor(message: string, validation?: SchemaValidationProblemGroup[]);
62
+ type SchemaExtractionWatchModeAttributes = {
63
+ averageExtractionDuration: number;
64
+ extractionFailedCount: number;
65
+ extractionSuccessfulCount: number;
66
+ step: 'stopped';
67
+ watcherDuration: number;
68
+ } | {
69
+ enforceRequiredFields: boolean;
70
+ schemaFormat: string;
71
+ step: 'started';
72
+ };
73
+ interface SchemaDeployTraceData {
74
+ manifestDir: string;
75
+ schemaRequired: boolean;
76
+ extractManifest?: boolean;
99
77
  }
100
-
101
- declare type SchemaExtractionWatchModeAttributes =
102
- | {
103
- averageExtractionDuration: number;
104
- extractionFailedCount: number;
105
- extractionSuccessfulCount: number;
106
- step: "stopped";
107
- watcherDuration: number;
108
- }
109
- | {
110
- enforceRequiredFields: boolean;
111
- schemaFormat: string;
112
- step: "started";
113
- };
114
-
115
- export declare const SchemaExtractionWatchModeTrace: DefinedTelemetryTrace<
116
- SchemaExtractionWatchModeAttributes,
117
- void
118
- >;
119
-
120
- export {};
78
+ declare const SchemaExtractedTrace: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaExtractedTraceAttributes, void>;
79
+ declare const SchemaExtractionWatchModeTrace: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaExtractionWatchModeAttributes, void>;
80
+ declare const SchemaDeploy: import("@sanity/telemetry").DefinedTelemetryTrace<SchemaDeployTraceData, void>;
81
+ export { type ExtractOptions, type ExtractSchemaWorkerError, SchemaDeploy, SchemaExtractedTrace, SchemaExtractionError, SchemaExtractionWatchModeTrace, createSchemaPatternMatcher, extractValidationFromSchemaError, formatSchemaValidation, getAggregatedSeverity, getExtractOptions, runSchemaExtraction };
82
+ //# sourceMappingURL=extract.d.ts.map
@@ -30,7 +30,8 @@ const DEFAULT_PACKAGES = [
30
30
  name: '@sanity/ui',
31
31
  supported: [
32
32
  '^2',
33
- '^3'
33
+ '^3',
34
+ '^4'
34
35
  ]
35
36
  }
36
37
  ];
@@ -108,7 +109,10 @@ You _may_ encounter bugs while using these versions.
108
109
  }
109
110
  }
110
111
  function listPackages(pkgs) {
111
- return pkgs.map((pkg)=>`${pkg.name} (installed: ${pkg.installed}, want: ${pkg.deprecatedBelow || pkg.supported.join(' || ')})`).join('\n ');
112
+ return pkgs.map((pkg)=>{
113
+ const want = pkg.isDeprecated && !pkg.isUnsupported && !pkg.isUntested ? pkg.deprecatedBelow : pkg.supported.join(' || ');
114
+ return `${pkg.name} (installed: ${pkg.installed}, want: ${want})`;
115
+ }).join('\n ');
112
116
  }
113
117
  function getUpgradeInstructions(pkgs) {
114
118
  const inst = pkgs.map((pkg)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type Output} from '@sanity/cli-core/types'\nimport {coerce, gtr, ltr, rcompare, satisfies, type SemVer} from 'semver'\n\ninterface PackageInfo {\n deprecatedBelow: string | null\n installed: SemVer\n isDeprecated: boolean\n isUnsupported: boolean\n isUntested: boolean\n name: string\n supported: string[]\n}\n\ninterface TrackedPackage {\n deprecatedBelow: string | null\n name: string\n supported: string[]\n}\n\n// NOTE: when doing changes here, also remember to update versions in help docs at\n// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages\nconst DEFAULT_PACKAGES: TrackedPackage[] = [\n {deprecatedBelow: null, name: 'react', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'react-dom', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'styled-components', supported: ['^6']},\n {deprecatedBelow: '^3', name: '@sanity/ui', supported: ['^2', '^3']},\n]\n\nexport async function checkStudioDependencyVersions(\n workDir: string,\n output: Output,\n {packages = DEFAULT_PACKAGES}: {packages?: TrackedPackage[]} = {},\n): Promise<void> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const packageInfo = packages.map(async (pkg): Promise<false | PackageInfo> => {\n const dependency = dependencies[pkg.name]\n if (!dependency) {\n return false\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n const installed = coerce(packageVersion ?? dependency.replaceAll(/[\\D.]/g, ''))\n\n if (!installed) {\n return false\n }\n\n const supported = pkg.supported.join(' || ')\n\n // \"Untested\" is usually the case where we have not upgraded the React version requirements\n // before a release, but given that is usually works in a backwards-compatible way, we want\n // to indicate that it's _untested_, not necessarily _unsupported_\n // Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19\n const isUntested = !satisfies(installed, supported) && gtr(installed, supported)\n\n // \"Unsupported\" in that the installed version is _lower than_ the minimum version\n // Ex: Installed is react@18.0.0, but we require react@^19.2\n const isUnsupported = !satisfies(installed, supported) && !isUntested\n\n // \"Deprecated\" in that we will stop supporting it at some point in the near future,\n // so users should be prompted to upgrade\n const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false\n\n return {\n ...pkg,\n installed,\n isDeprecated,\n isUnsupported,\n isUntested,\n }\n })\n\n const installedPackages = (await Promise.all(packageInfo)).filter(\n (inp): inp is PackageInfo => inp !== false,\n )\n const unsupported = installedPackages.filter((pkg) => pkg.isUnsupported)\n const deprecated = installedPackages.filter((pkg) => !pkg.isUnsupported && pkg.isDeprecated)\n const untested = installedPackages.filter((pkg) => pkg.isUntested)\n\n if (deprecated.length > 0) {\n output.warn(`The following package versions have been deprecated and should be upgraded:\n\n ${listPackages(deprecated)}\n\nSupport for these will be removed in a future release!\n\n ${getUpgradeInstructions(deprecated)}\n`)\n }\n\n if (untested.length > 0) {\n output.warn(`The following package versions have not yet been marked as supported:\n\n ${listPackages(untested)}\n\nYou _may_ encounter bugs while using these versions.\n\n ${getDowngradeInstructions(untested)}\n`)\n }\n\n if (unsupported.length > 0) {\n output.error(\n `The following package versions are no longer supported and needs to be upgraded:\n\n ${listPackages(unsupported)}\n\n ${getUpgradeInstructions(unsupported)}\n`,\n {exit: 1},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map(\n (pkg) =>\n `${pkg.name} (installed: ${pkg.installed}, want: ${\n pkg.deprecatedBelow || pkg.supported.join(' || ')\n })`,\n )\n .join('\\n ')\n}\n\nfunction getUpgradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To upgrade, run either:\n\n npm install ${inst}\n\n or\n\n yarn add ${inst}\n\n or\n\n pnpm add ${inst}\n\n\nRead more at https://www.sanity.io/docs/help/upgrade-packages`\n}\n\nfunction getDowngradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To downgrade, run either:\n\n yarn add ${inst}\n\n or\n\n npm install ${inst}\n\n or\n\n pnpm install ${inst}`\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","coerce","gtr","ltr","rcompare","satisfies","DEFAULT_PACKAGES","deprecatedBelow","name","supported","checkStudioDependencyVersions","workDir","output","packages","manifest","join","skipSchemaValidation","dependencies","devDependencies","packageInfo","map","pkg","dependency","packageVersion","installed","replaceAll","isUntested","isUnsupported","isDeprecated","installedPackages","Promise","all","filter","inp","unsupported","deprecated","untested","length","warn","listPackages","getUpgradeInstructions","getDowngradeInstructions","error","exit","pkgs","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,MAAM,EAAEC,GAAG,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,SAAS,QAAoB,SAAQ;AAkBzE,kFAAkF;AAClF,sEAAsE;AACtE,MAAMC,mBAAqC;IACzC;QAACC,iBAAiB;QAAMC,MAAM;QAASC,WAAW;YAAC;SAAU;IAAA;IAC7D;QAACF,iBAAiB;QAAMC,MAAM;QAAaC,WAAW;YAAC;SAAU;IAAA;IACjE;QAACF,iBAAiB;QAAMC,MAAM;QAAqBC,WAAW;YAAC;SAAK;IAAA;IACpE;QAACF,iBAAiB;QAAMC,MAAM;QAAcC,WAAW;YAAC;YAAM;SAAK;IAAA;CACpE;AAED,OAAO,eAAeC,8BACpBC,OAAe,EACfC,MAAc,EACd,EAACC,WAAWP,gBAAgB,EAAgC,GAAG,CAAC,CAAC;IAEjE,MAAMQ,WAAW,MAAMd,gBAAgBF,KAAKiB,IAAI,CAACJ,SAAS,iBAAiB;QACzEK,sBAAsB;IACxB;IACA,MAAMC,eAAe;QAAC,GAAGH,UAAUG,YAAY;QAAE,GAAGH,UAAUI,eAAe;IAAA;IAE7E,MAAMC,cAAcN,SAASO,GAAG,CAAC,OAAOC;QACtC,MAAMC,aAAaL,YAAY,CAACI,IAAIb,IAAI,CAAC;QACzC,IAAI,CAACc,YAAY;YACf,OAAO;QACT;QAEA,MAAMC,iBAAiB,MAAMxB,uBAAuBsB,IAAIb,IAAI,EAAEG;QAC9D,MAAMa,YAAYvB,OAAOsB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;;cAIJ,EAAEA,KAAK;;;;eAIN,EAAEA,MAAM;AACvB"}
1
+ {"version":3,"sources":["../../../src/actions/build/checkStudioDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core/package-manager'\nimport {type Output} from '@sanity/cli-core/types'\nimport {coerce, gtr, ltr, rcompare, satisfies, type SemVer} from 'semver'\n\ninterface PackageInfo {\n deprecatedBelow: string | null\n installed: SemVer\n isDeprecated: boolean\n isUnsupported: boolean\n isUntested: boolean\n name: string\n supported: string[]\n}\n\ninterface TrackedPackage {\n deprecatedBelow: string | null\n name: string\n supported: string[]\n}\n\n// NOTE: when doing changes here, also remember to update versions in help docs at\n// https://sanity.io/admin/structure/docs;helpArticle;upgrade-packages\nconst DEFAULT_PACKAGES: TrackedPackage[] = [\n {deprecatedBelow: null, name: 'react', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'react-dom', supported: ['^19.2.2']},\n {deprecatedBelow: null, name: 'styled-components', supported: ['^6']},\n {deprecatedBelow: '^3', name: '@sanity/ui', supported: ['^2', '^3', '^4']},\n]\n\nexport async function checkStudioDependencyVersions(\n workDir: string,\n output: Output,\n {packages = DEFAULT_PACKAGES}: {packages?: TrackedPackage[]} = {},\n): Promise<void> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const packageInfo = packages.map(async (pkg): Promise<false | PackageInfo> => {\n const dependency = dependencies[pkg.name]\n if (!dependency) {\n return false\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n const installed = coerce(packageVersion ?? dependency.replaceAll(/[\\D.]/g, ''))\n\n if (!installed) {\n return false\n }\n\n const supported = pkg.supported.join(' || ')\n\n // \"Untested\" is usually the case where we have not upgraded the React version requirements\n // before a release, but given that is usually works in a backwards-compatible way, we want\n // to indicate that it's _untested_, not necessarily _unsupported_\n // Ex: Installed is react@20.0.0, but we've only _tested_ with react@^19\n const isUntested = !satisfies(installed, supported) && gtr(installed, supported)\n\n // \"Unsupported\" in that the installed version is _lower than_ the minimum version\n // Ex: Installed is react@18.0.0, but we require react@^19.2\n const isUnsupported = !satisfies(installed, supported) && !isUntested\n\n // \"Deprecated\" in that we will stop supporting it at some point in the near future,\n // so users should be prompted to upgrade\n const isDeprecated = pkg.deprecatedBelow ? ltr(installed, pkg.deprecatedBelow) : false\n\n return {\n ...pkg,\n installed,\n isDeprecated,\n isUnsupported,\n isUntested,\n }\n })\n\n const installedPackages = (await Promise.all(packageInfo)).filter(\n (inp): inp is PackageInfo => inp !== false,\n )\n const unsupported = installedPackages.filter((pkg) => pkg.isUnsupported)\n const deprecated = installedPackages.filter((pkg) => !pkg.isUnsupported && pkg.isDeprecated)\n const untested = installedPackages.filter((pkg) => pkg.isUntested)\n\n if (deprecated.length > 0) {\n output.warn(`The following package versions have been deprecated and should be upgraded:\n\n ${listPackages(deprecated)}\n\nSupport for these will be removed in a future release!\n\n ${getUpgradeInstructions(deprecated)}\n`)\n }\n\n if (untested.length > 0) {\n output.warn(`The following package versions have not yet been marked as supported:\n\n ${listPackages(untested)}\n\nYou _may_ encounter bugs while using these versions.\n\n ${getDowngradeInstructions(untested)}\n`)\n }\n\n if (unsupported.length > 0) {\n output.error(\n `The following package versions are no longer supported and needs to be upgraded:\n\n ${listPackages(unsupported)}\n\n ${getUpgradeInstructions(unsupported)}\n`,\n {exit: 1},\n )\n }\n}\n\nfunction listPackages(pkgs: PackageInfo[]) {\n return pkgs\n .map((pkg) => {\n const want =\n pkg.isDeprecated && !pkg.isUnsupported && !pkg.isUntested\n ? pkg.deprecatedBelow\n : pkg.supported.join(' || ')\n\n return `${pkg.name} (installed: ${pkg.installed}, want: ${want})`\n })\n .join('\\n ')\n}\n\nfunction getUpgradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To upgrade, run either:\n\n npm install ${inst}\n\n or\n\n yarn add ${inst}\n\n or\n\n pnpm add ${inst}\n\n\nRead more at https://www.sanity.io/docs/help/upgrade-packages`\n}\n\nfunction getDowngradeInstructions(pkgs: PackageInfo[]) {\n const inst = pkgs\n .map((pkg) => {\n const [highestSupported] = pkg.supported\n .map((version) => (coerce(version) || {version: ''}).version)\n .toSorted(rcompare)\n\n return `\"${pkg.name}@^${highestSupported}\"`\n })\n .join(' ')\n\n return `To downgrade, run either:\n\n yarn add ${inst}\n\n or\n\n npm install ${inst}\n\n or\n\n pnpm install ${inst}`\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","coerce","gtr","ltr","rcompare","satisfies","DEFAULT_PACKAGES","deprecatedBelow","name","supported","checkStudioDependencyVersions","workDir","output","packages","manifest","join","skipSchemaValidation","dependencies","devDependencies","packageInfo","map","pkg","dependency","packageVersion","installed","replaceAll","isUntested","isUnsupported","isDeprecated","installedPackages","Promise","all","filter","inp","unsupported","deprecated","untested","length","warn","listPackages","getUpgradeInstructions","getDowngradeInstructions","error","exit","pkgs","want","inst","highestSupported","version","toSorted"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,eAAe,QAAO,mCAAkC;AAExF,SAAQC,MAAM,EAAEC,GAAG,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,SAAS,QAAoB,SAAQ;AAkBzE,kFAAkF;AAClF,sEAAsE;AACtE,MAAMC,mBAAqC;IACzC;QAACC,iBAAiB;QAAMC,MAAM;QAASC,WAAW;YAAC;SAAU;IAAA;IAC7D;QAACF,iBAAiB;QAAMC,MAAM;QAAaC,WAAW;YAAC;SAAU;IAAA;IACjE;QAACF,iBAAiB;QAAMC,MAAM;QAAqBC,WAAW;YAAC;SAAK;IAAA;IACpE;QAACF,iBAAiB;QAAMC,MAAM;QAAcC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AC3DC,QAAQ,CAAC7C;QAEZ,OAAO,CAAC,CAAC,EAAEiB,IAAIb,IAAI,CAAC,EAAE,EAAEuC,iBAAiB,CAAC,CAAC;IAC7C,GACChC,IAAI,CAAC;IAER,OAAO,CAAC;;cAEI,EAAE+B,KAAK;;;;WAIV,EAAEA,KAAK;;;;WAIP,EAAEA,KAAK;;;6DAG2C,CAAC;AAC9D;AAEA,SAASL,yBAAyBG,IAAmB;IACnD,MAAME,OAAOF,KACVxB,GAAG,CAAC,CAACC;QACJ,MAAM,CAAC0B,iBAAiB,GAAG1B,IAAIZ,SAAS,CACrCW,GAAG,CAAC,CAAC4B,UAAY,AAAC/C,CAAAA,OAAO+C,YAAY;gBAACA,SAAS;YAAE,CAAA,EAAGA,OAAO,EAC3DC,QAAQ,CAAC7C;QAEZ,OAAO,CAAC,CAAC,EAAEiB,IAAIb,IAAI,CAAC,EAAE,EAAEuC,iBAAiB,CAAC,CAAC;IAC7C,GACChC,IAAI,CAAC;IAER,OAAO,CAAC;;WAEC,EAAE+B,KAAK;;;;cAIJ,EAAEA,KAAK;;;;eAIN,EAAEA,MAAM;AACvB"}
@@ -5,10 +5,10 @@ import { getCliTelemetry } from '@sanity/cli-core/telemetry';
5
5
  import { isStaging } from '@sanity/cli-core/util';
6
6
  import { workbenchOptimizeDeps, workbenchVitePlugins } from '@sanity/workbench-cli/build';
7
7
  import viteReact, { reactCompilerPreset } from '@vitejs/plugin-react';
8
- import debug from 'debug';
9
8
  import { esmExternalRequirePlugin, mergeConfig } from 'vite';
10
9
  import { SANITY_CACHE_DIR } from '../../constants.js';
11
10
  import { sanitySchemaExtractionPlugin } from '../schema/vite/plugin-schema-extraction.js';
11
+ import { buildDebug } from './buildDebug.js';
12
12
  import { VENDOR_DIR } from './constants.js';
13
13
  import { createExternalFromImportMap } from './createExternalFromImportMap.js';
14
14
  import { normalizeBasePath } from './normalizeBasePath.js';
@@ -294,10 +294,10 @@ function suppressUnusedImport(warning) {
294
294
  */ export async function extendViteConfigWithUserConfig(env, defaultConfig, userConfig) {
295
295
  let config = defaultConfig;
296
296
  if (typeof userConfig === 'function') {
297
- debug('Extending vite config using user-specified function');
297
+ buildDebug('Extending vite config using user-specified function');
298
298
  config = await userConfig(config, env);
299
299
  } else if (typeof userConfig === 'object') {
300
- debug('Merging vite config using user-specified object');
300
+ buildDebug('Merging vite config using user-specified object');
301
301
  config = mergeConfig(config, userConfig);
302
302
  }
303
303
  return config;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport debug from 'debug'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type PluginOption,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {VENDOR_DIR} from './constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: boolean | ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * Auto-updates configuration (production builds only). When set, vendor\n * packages are emitted as hashed ESM chunks by this build and the import map\n * in `index.html` is derived from the build output.\n */\n autoUpdates?: AutoUpdatesBuildConfig\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n exposes?: WorkbenchExposes\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * The workbench app's bus identity, stamped into its modules as\n * `__SANITY_APP_ID__` for `@sanity/runtime`. Only read for workbench apps.\n */\n workbenchAppId?: string\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdates,\n basePath: rawBasePath = '/',\n cwd,\n entries,\n exposes,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n workbenchAppId,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler\n ? [babel({presets: [reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)]})]\n : []),\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ]\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: isStaging(),\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n // Federation builds skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\n ]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\n if (autoUpdates) {\n viteConfig.plugins!.push(\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports\n // on the emitted vendor chunks; Rolldown only emits `export default` for a\n // CommonJS entry.\n createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName),\n // The import map and vendor specifiers are externals of the studio/app\n // bundle, resolved by the browser at runtime. They are handed to\n // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the\n // plugin both marks them external AND rewrites bundled CommonJS\n // `require()` calls of an external (e.g. react-dom requiring react) into\n // ESM imports, while `rolldownOptions.external` would short-circuit that\n // rewrite and leave a runtime `require` shim that throws in the browser.\n esmExternalRequirePlugin({\n external: createExternalFromImportMap({\n imports: {\n ...autoUpdates.imports,\n ...Object.fromEntries(\n Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier) => [\n specifier,\n '',\n ]),\n ),\n },\n }),\n }),\n )\n }\n\n const vendorChunkNames = autoUpdates\n ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName))\n : null\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n ...autoUpdates?.vendor.entries,\n },\n onwarn: onRolldownWarn,\n ...(autoUpdates\n ? {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so\n // the vendor named-exports plugin can edit chunks without a JS\n // dependency.\n experimental: {nativeMagicString: true},\n output: {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n },\n // App-style builds default to `preserveEntrySignatures: false`, which\n // treeshakes the exports off entry chunks. Vendor chunks are loaded by\n // the browser via the import map, so their exports must survive (e.g.\n // styled-components' native ESM exports). `exports-only` keeps exports\n // for entries that have them, while the export-less `sanity` app entry\n // still bundles as before.\n preserveEntrySignatures: 'exports-only',\n }\n : {}),\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Re-asserts the critical parts of the default config after a userland vite\n * config (`vite` in `sanity.cli.ts`) has been applied.\n *\n * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:\n * the `input` entries (the studio entry plus, for auto-updating studios/apps,\n * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the\n * vendor plugins rely on, and the `output` chunk naming. A userland config that\n * returns a brand-new object for any of these would silently break the build\n * (e.g. vendor chunks never emitted while the bundle still treats them as\n * external), so the default `rolldownOptions` are deep-merged back over the\n * userland config: userland additions survive, replacements of critical\n * options are healed.\n *\n * @param config - User-modified configuration\n * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(\n config: InlineConfig,\n defaultConfig: InlineConfig,\n): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: defaultConfig.build?.rolldownOptions ?? {},\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n debug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n debug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","isStaging","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","debug","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","VENDOR_DIR","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createVendorNamedExportsPlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","entries","exposes","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","workbenchAppId","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,SAEEC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO,uB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AC5CL,QAAQI,KAAK,GAAGJ,QAAQI,KAAK,CAACpC,MAAM,CAAC,CAACsC,IAAMA,MAAM;QAClD,IAAIN,QAAQI,KAAK,CAACG,MAAM,KAAK,GAAG,OAAO;IACzC;IAEA,mFAAmF;IACnF,IAAIP,QAAQQ,GAAG,EAAEC,MAAM,CAACC,KAAOA,GAAGL,QAAQ,CAAC,qBAAqBK,GAAGL,QAAQ,CAAC,sBAC1E,OAAO;IAET,OAAO;AACT;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,eAAeM,mBACpBC,MAAoB,EACpBC,aAA2B;IAE3B,IAAI,OAAOD,OAAOhF,KAAK,EAAEuD,iBAAiBC,UAAU,UAAU;QAC5D,MAAM,IAAI0B,UACR;IAEJ;IAEA,IAAI,CAACF,OAAOtD,IAAI,EAAE;QAChB,MAAM,IAAIyD,MACR;IAEJ;IAEA,OAAOrI,YAAYkI,QAAQ;QACzBhF,OAAO;YACLuD,iBAAiB0B,cAAcjF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe6B,+BACpBtE,GAAc,EACdmE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpCzI,MAAM;QACNoI,SAAS,MAAMK,WAAWL,QAAQlE;IACpC,OAAO,IAAI,OAAOuE,eAAe,UAAU;QACzCzI,MAAM;QACNoI,SAASlI,YAAYkI,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
1
+ {"version":3,"sources":["../../../src/actions/build/getViteConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport babel from '@rolldown/plugin-babel'\nimport {findProjectRoot} from '@sanity/cli-core/config'\nimport {getCliTelemetry} from '@sanity/cli-core/telemetry'\nimport {type CliConfig, type UserViteConfig} from '@sanity/cli-core/types'\nimport {isStaging} from '@sanity/cli-core/util'\nimport {\n type WorkbenchExposes,\n workbenchOptimizeDeps,\n workbenchVitePlugins,\n} from '@sanity/workbench-cli/build'\nimport viteReact, {reactCompilerPreset} from '@vitejs/plugin-react'\nimport {type PluginOptions as ReactCompilerConfig} from 'babel-plugin-react-compiler'\nimport {\n type ConfigEnv,\n esmExternalRequirePlugin,\n type InlineConfig,\n mergeConfig,\n type Plugin,\n type PluginOption,\n type Rolldown,\n} from 'vite'\n\nimport {SANITY_CACHE_DIR} from '../../constants.js'\nimport {sanitySchemaExtractionPlugin} from '../schema/vite/plugin-schema-extraction.js'\nimport {type AutoUpdatesBuildConfig} from './autoUpdates.js'\nimport {buildDebug} from './buildDebug.js'\nimport {VENDOR_DIR} from './constants.js'\nimport {createExternalFromImportMap} from './createExternalFromImportMap.js'\nimport {normalizeBasePath} from './normalizeBasePath.js'\nimport {sanityBuildEntries} from './vite/plugin-sanity-build-entries.js'\nimport {sanityFaviconsPlugin} from './vite/plugin-sanity-favicons.js'\nimport {sanityRuntimeRewritePlugin} from './vite/plugin-sanity-runtime-rewrite.js'\nimport {createVendorNamedExportsPlugin} from './vite/plugin-sanity-vendor-named-exports.js'\nimport {getDefaultFaviconsPath} from './writeFavicons.js'\n\ninterface ViteOptions {\n /**\n * Root path of the studio/sanity app\n */\n cwd: string\n\n entries: {\n relativeConfigLocation: string | null\n // `null` when a branded app declares no `entry` (sanity-io/workbench spec 002-workbench-extension-api, US5) — no app view.\n relativeEntry: string | null\n }\n\n /**\n * Returns the environment variables to be injected into the config.\n */\n getEnvironmentVariables(): Record<string, string>\n\n /**\n * Mode to run vite in - eg development or production\n */\n mode: 'development' | 'production'\n\n reactCompiler: boolean | ReactCompilerConfig | undefined\n\n /**\n * Additional plugins when configured, eg. typegen\n */\n additionalPlugins?: Plugin[]\n\n /**\n * Auto-updates configuration (production builds only). When set, vendor\n * packages are emitted as hashed ESM chunks by this build and the import map\n * in `index.html` is derived from the build output.\n */\n autoUpdates?: AutoUpdatesBuildConfig\n\n /**\n * Base path (eg under where to serve the app - `/studio` or similar)\n * Will be normalized to ensure it starts and ends with a `/`\n */\n basePath?: string\n\n exposes?: WorkbenchExposes\n\n isApp?: boolean\n\n /**\n * Whether this is a workbench app (opted in via `unstable_defineApp`). Drives\n * the module-federation build.\n */\n isWorkbenchApp?: boolean\n\n /**\n * Whether or not to minify the output (only used in `mode: 'production'`)\n */\n minify?: boolean\n\n /**\n * Output directory (eg where to place the built files, if any)\n */\n outputDir?: string\n\n /**\n * Schema extraction configuration\n */\n schemaExtraction?: CliConfig['schemaExtraction']\n\n /**\n * HTTP development server configuration\n */\n server?: {host?: string; port?: number}\n\n /**\n * Whether or not to enable source maps\n */\n sourceMap?: boolean\n\n /**\n * The workbench app's bus identity, stamped into its modules as\n * `__SANITY_APP_ID__` for `@sanity/runtime`. Only read for workbench apps.\n */\n workbenchAppId?: string\n}\n\n/**\n * Get a configuration object for Vite based on the passed options\n *\n * @internal Only meant for consumption inside of Sanity modules, do not depend on this externally\n */\nexport async function getViteConfig(options: ViteOptions): Promise<InlineConfig> {\n const {\n additionalPlugins,\n autoUpdates,\n basePath: rawBasePath = '/',\n cwd,\n entries,\n exposes,\n isApp,\n isWorkbenchApp,\n minify,\n mode,\n outputDir,\n reactCompiler,\n schemaExtraction,\n server,\n // default to `true` when `mode=development`\n sourceMap = options.mode === 'development',\n workbenchAppId,\n } = options\n\n const basePath = normalizeBasePath(rawBasePath)\n\n const configPath = (await findProjectRoot(cwd)).path\n\n const customFaviconsPath = path.join(cwd, 'static')\n const defaultFaviconsPath = await getDefaultFaviconsPath()\n const staticPath = `${basePath}static`\n\n const envVars = options.getEnvironmentVariables()\n\n const sharedPlugins: PluginOption = [\n viteReact(),\n ...(reactCompiler\n ? [babel({presets: [reactCompilerPreset(reactCompiler === true ? {} : reactCompiler)]})]\n : []),\n ...(schemaExtraction?.enabled\n ? [\n sanitySchemaExtractionPlugin({\n additionalPatterns: schemaExtraction.watchPatterns,\n configPath,\n enforceRequiredFields: schemaExtraction.enforceRequiredFields,\n outputPath: schemaExtraction.path,\n telemetryLogger: getCliTelemetry(),\n workDir: cwd,\n workspaceName: schemaExtraction.workspace,\n }),\n ]\n : []),\n ]\n\n const viteConfig: InlineConfig = {\n base: basePath,\n build: {\n outDir: outputDir || path.resolve(cwd, 'dist'),\n sourcemap: sourceMap,\n },\n // Define a custom cache directory so that sanity's vite cache\n // does not conflict with any potential local vite projects\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n configFile: false,\n define: {\n __SANITY_BUILD_TIMESTAMP__: JSON.stringify(Date.now()),\n __SANITY_STAGING__: isStaging(),\n 'process.env.MODE': JSON.stringify(mode),\n 'process.env.PKG_BUILD_VERSION': JSON.stringify(process.env.PKG_BUILD_VERSION),\n /**\n * Yes, double negatives are confusing.\n * The default value of `SC_DISABLE_SPEEDY` is `process.env.NODE_ENV === 'production'`: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/constants.ts#L34\n * Which means that in production, use the much faster way of inserting CSS rules, based on the CSSStyleSheet API (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule)\n * while in dev mode, use the slower way of inserting CSS rules, which appends text nodes to the `<style>` tag: https://github.com/styled-components/styled-components/blob/99c02f52d69e8e509c0bf012cadee7f8e819a6dd/packages/styled-components/src/sheet/Tag.ts#L74-L76\n * There are historical reasons for this, primarily that browsers initially did not support editing CSS rules in the DevTools inspector if `CSSStyleSheet.insetRule` were used.\n * However, that's no longer the case (since Chrome 81 back in April 2020: https://developer.chrome.com/docs/css-ui/css-in-js), the latest version of FireFox also supports it,\n * and there is no longer any reason to use the much slower method in dev mode.\n */\n 'process.env.SC_DISABLE_SPEEDY': JSON.stringify('false'),\n ...envVars,\n },\n envPrefix: isApp ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n logLevel: mode === 'production' ? 'silent' : 'info',\n mode,\n plugins: [\n // Federation builds skip the serve-only client plugins (favicons, runtime\n // rewrite) — they no-op at build. `sanityBuildEntries` is scoped to the\n // `client` environment so it emits the standalone SPA `index.html`\n // (bridge-free) when the workbench remote SPA is enabled, and no-ops in the\n // federation env / when no client env exists (see plugin-sanity-environment).\n ...(isWorkbenchApp\n ? [\n ...sharedPlugins,\n await workbenchVitePlugins({appId: workbenchAppId, cwd, entries, exposes, isApp}),\n {\n ...sanityBuildEntries({basePath, bridge: false, cwd, isApp}),\n applyToEnvironment: (env) => env.name === 'client',\n } satisfies Plugin,\n ]\n : [\n ...sharedPlugins,\n sanityFaviconsPlugin({\n customFaviconsPath,\n defaultFaviconsPath,\n staticUrlPath: staticPath,\n }),\n sanityRuntimeRewritePlugin(),\n sanityBuildEntries({autoUpdates, basePath, cwd, isApp}),\n ]),\n // Caller-provided plugins (e.g. typegen in dev) aren't client-specific,\n // so they apply to federation builds too.\n ...(additionalPlugins || []),\n ],\n resolve: {\n dedupe: ['react', 'react-dom', 'sanity', 'styled-components'],\n // Honor the studio's tsconfig `paths`, consistent with studioWorkerLoader.worker.ts.\n tsconfigPaths: true,\n },\n root: cwd,\n server: {\n host: server?.host,\n port: server?.port || 3333,\n // Apps drift to a free port (the reported URL embeds whichever port was\n // claimed), and workbench runs stack servers on adjacent ports — both\n // need the fallback. Studios fail fast on a busy port.\n strictPort: !isApp && !isWorkbenchApp,\n\n /**\n * Significantly speed up startup time,\n * and most importantly eliminates the `new dependencies optimized: foobar. optimized dependencies changed. reloading`\n * types of initial reload loops that otherwise happen as vite discovers deps that need to be optimized.\n * This option starts the traversal up front, and warms up the dep tree required to render the userland sanity.config.ts file,\n * and thus avoids frustrating reload loops.\n */\n warmup: {\n clientFiles: ['./.sanity/runtime/app.js'],\n },\n },\n }\n\n // Front-load the deps the federation `exposes` reach only via the host's\n // dynamic imports, which Vite's dep scanner (crawling from the HTML entry)\n // otherwise misses — see `workbenchOptimizeDeps`. Dev-server only; Vite\n // ignores `optimizeDeps` at build. Set before the userland `vite` hook so an\n // app can still extend the list.\n if (isWorkbenchApp && mode === 'development') {\n const runtimeDir = path.join(cwd, '.sanity', 'runtime')\n const appSources = [entries.relativeEntry, entries.relativeConfigLocation]\n .filter((relativePath): relativePath is string => relativePath !== null)\n .map((relativePath) => path.resolve(runtimeDir, relativePath))\n viteConfig.optimizeDeps = workbenchOptimizeDeps({appSources, cwd, exposes})\n }\n\n // Federation builds don't produce a client bundle — the federation\n // plugin configures its own environment and build entry point.\n if (mode === 'production' && !isWorkbenchApp) {\n if (autoUpdates) {\n viteConfig.plugins!.push(\n // Re-expose CommonJS named exports (react, react-dom) as real ESM exports\n // on the emitted vendor chunks; Rolldown only emits `export default` for a\n // CommonJS entry.\n createVendorNamedExportsPlugin(autoUpdates.vendor.namesByChunkName),\n // The import map and vendor specifiers are externals of the studio/app\n // bundle, resolved by the browser at runtime. They are handed to\n // `esmExternalRequirePlugin` rather than `rolldownOptions.external`: the\n // plugin both marks them external AND rewrites bundled CommonJS\n // `require()` calls of an external (e.g. react-dom requiring react) into\n // ESM imports, while `rolldownOptions.external` would short-circuit that\n // rewrite and leave a runtime `require` shim that throws in the browser.\n esmExternalRequirePlugin({\n external: createExternalFromImportMap({\n imports: {\n ...autoUpdates.imports,\n ...Object.fromEntries(\n Object.values(autoUpdates.vendor.specifiersByChunkName).map((specifier) => [\n specifier,\n '',\n ]),\n ),\n },\n }),\n }),\n )\n }\n\n const vendorChunkNames = autoUpdates\n ? new Set(Object.keys(autoUpdates.vendor.specifiersByChunkName))\n : null\n\n viteConfig.build = {\n ...viteConfig.build,\n\n assetsDir: 'static',\n emptyOutDir: false, // Rely on CLI to do this\n minify: minify ? 'oxc' : false,\n\n rolldownOptions: {\n input: {\n sanity: path.join(cwd, '.sanity', 'runtime', 'app.js'),\n ...autoUpdates?.vendor.entries,\n },\n onwarn: onRolldownWarn,\n ...(autoUpdates\n ? {\n // Expose Rolldown's native MagicString on `renderChunk`'s `meta` so\n // the vendor named-exports plugin can edit chunks without a JS\n // dependency.\n experimental: {nativeMagicString: true},\n output: {\n entryFileNames: (chunk) =>\n vendorChunkNames!.has(chunk.name)\n ? `${VENDOR_DIR}/[name]-[hash].mjs`\n : 'static/[name]-[hash].js',\n exports: 'named',\n },\n // App-style builds default to `preserveEntrySignatures: false`, which\n // treeshakes the exports off entry chunks. Vendor chunks are loaded by\n // the browser via the import map, so their exports must survive (e.g.\n // styled-components' native ESM exports). `exports-only` keeps exports\n // for entries that have them, while the export-less `sanity` app entry\n // still bundles as before.\n preserveEntrySignatures: 'exports-only',\n }\n : {}),\n },\n }\n }\n\n return viteConfig\n}\n\nfunction onRolldownWarn(warning: Rolldown.RolldownLog, warn: Rolldown.LoggingFunction) {\n if (suppressUnusedImport(warning)) {\n return\n }\n\n warn(warning)\n}\n\nfunction suppressUnusedImport(warning: Rolldown.RolldownLog & {ids?: string[]}): boolean {\n if (warning.code !== 'UNUSED_EXTERNAL_IMPORT') return false\n\n // Suppress:\n // ```\n // \"useDebugValue\" is imported from external module \"react\"…\n // ```\n if (warning.names?.includes('useDebugValue')) {\n warning.names = warning.names.filter((n) => n !== 'useDebugValue')\n if (warning.names.length === 0) return true\n }\n\n // If some library does something unexpected, we suppress since it isn't actionable\n if (warning.ids?.every((id) => id.includes('/node_modules/') || id.includes('\\\\node_modules\\\\')))\n return true\n\n return false\n}\n\n/**\n * Re-asserts the critical parts of the default config after a userland vite\n * config (`vite` in `sanity.cli.ts`) has been applied.\n *\n * Everything `getViteConfig` sets under `build.rolldownOptions` is load-bearing:\n * the `input` entries (the studio entry plus, for auto-updating studios/apps,\n * the vendor entries), `preserveEntrySignatures`, the `experimental` flags the\n * vendor plugins rely on, and the `output` chunk naming. A userland config that\n * returns a brand-new object for any of these would silently break the build\n * (e.g. vendor chunks never emitted while the bundle still treats them as\n * external), so the default `rolldownOptions` are deep-merged back over the\n * userland config: userland additions survive, replacements of critical\n * options are healed.\n *\n * @param config - User-modified configuration\n * @param defaultConfig - The configuration produced by `getViteConfig`, before the userland config was applied\n * @returns Merged configuration\n * @internal\n */\nexport async function finalizeViteConfig(\n config: InlineConfig,\n defaultConfig: InlineConfig,\n): Promise<InlineConfig> {\n if (typeof config.build?.rolldownOptions?.input !== 'object') {\n throw new TypeError(\n 'Vite config must contain `build.rolldownOptions.input`, and it must be an object',\n )\n }\n\n if (!config.root) {\n throw new Error(\n 'Vite config must contain `root` property, and must point to the Sanity root directory',\n )\n }\n\n return mergeConfig(config, {\n build: {\n rolldownOptions: defaultConfig.build?.rolldownOptions ?? {},\n },\n })\n}\n\n/**\n * Merge user-provided Vite configuration object or function\n *\n * @param defaultConfig - Default configuration object\n * @param userConfig - User-provided configuration object or function\n * @returns Merged configuration\n * @internal\n */\nexport async function extendViteConfigWithUserConfig(\n env: ConfigEnv,\n defaultConfig: InlineConfig,\n userConfig: UserViteConfig,\n): Promise<InlineConfig> {\n let config = defaultConfig\n\n if (typeof userConfig === 'function') {\n buildDebug('Extending vite config using user-specified function')\n config = await userConfig(config, env)\n } else if (typeof userConfig === 'object') {\n buildDebug('Merging vite config using user-specified object')\n config = mergeConfig(config, userConfig)\n }\n\n return config\n}\n"],"names":["path","babel","findProjectRoot","getCliTelemetry","isStaging","workbenchOptimizeDeps","workbenchVitePlugins","viteReact","reactCompilerPreset","esmExternalRequirePlugin","mergeConfig","SANITY_CACHE_DIR","sanitySchemaExtractionPlugin","buildDebug","VENDOR_DIR","createExternalFromImportMap","normalizeBasePath","sanityBuildEntries","sanityFaviconsPlugin","sanityRuntimeRewritePlugin","createVendorNamedExportsPlugin","getDefaultFaviconsPath","getViteConfig","options","additionalPlugins","autoUpdates","basePath","rawBasePath","cwd","entries","exposes","isApp","isWorkbenchApp","minify","mode","outputDir","reactCompiler","schemaExtraction","server","sourceMap","workbenchAppId","configPath","customFaviconsPath","join","defaultFaviconsPath","staticPath","envVars","getEnvironmentVariables","sharedPlugins","presets","enabled","additionalPatterns","watchPatterns","enforceRequiredFields","outputPath","telemetryLogger","workDir","workspaceName","workspace","viteConfig","base","build","outDir","resolve","sourcemap","cacheDir","configFile","define","__SANITY_BUILD_TIMESTAMP__","JSON","stringify","Date","now","__SANITY_STAGING__","process","env","PKG_BUILD_VERSION","envPrefix","logLevel","plugins","appId","bridge","applyToEnvironment","name","staticUrlPath","dedupe","tsconfigPaths","root","host","port","strictPort","warmup","clientFiles","runtimeDir","appSources","relativeEntry","relativeConfigLocation","filter","relativePath","map","optimizeDeps","push","vendor","namesByChunkName","external","imports","Object","fromEntries","values","specifiersByChunkName","specifier","vendorChunkNames","Set","keys","assetsDir","emptyOutDir","rolldownOptions","input","sanity","onwarn","onRolldownWarn","experimental","nativeMagicString","output","entryFileNames","chunk","has","exports","preserveEntrySignatures","warning","warn","suppressUnusedImport","code","names","includes","n","length","ids","every","id","finalizeViteConfig","config","defaultConfig","TypeError","Error","extendViteConfigWithUserConfig","userConfig"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,OAAOC,WAAW,yBAAwB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,eAAe,QAAO,6BAA4B;AAE1D,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,SAEEC,qBAAqB,EACrBC,oBAAoB,QACf,8BAA6B;AACpC,OAAOC,aAAYC,mBAAmB,QAAO,uBAAsB;AAEnE,SAEEC,wBAAwB,EAExBC,WAAW,QAIN,OAAM;AAEb,SAAQC,gBAAgB,QAAO,qBAAoB;AACnD,SAAQC,4BAA4B,QAAO,6CAA4C;AAEvF,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,UAAU,QAAO,iBAAgB;AACzC,SAAQC,2BAA2B,QAAO,mCAAkC;AAC5E,SAAQC,iBAAiB,QAAO,yBAAwB;AACxD,SAAQC,kBAAkB,QAAO,wCAAuC;AACxE,SAAQC,oBAAoB,QAAO,mCAAkC;AACrE,SAAQC,0BAA0B,QAAO,0CAAyC;AAClF,SAAQC,8BAA8B,QAAO,+CAA8C;AAC3F,SAAQC,sBAAsB,QAAO,qBAAoB;AAsFzD;;;;CAIC,GACD,OAAO,eAAeC,cAAcC,OAAoB;IACtD,MAAM,EACJC,iBAAiB,EACjBC,WAAW,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D,MACR;IAEJ;IAEA,OAAOtI,YAAYmI,QAAQ;QACzBhF,OAAO;YACLuD,iBAAiB0B,cAAcjF,KAAK,EAAEuD,mBAAmB,CAAC;QAC5D;IACF;AACF;AAEA;;;;;;;CAOC,GACD,OAAO,eAAe6B,+BACpBtE,GAAc,EACdmE,aAA2B,EAC3BI,UAA0B;IAE1B,IAAIL,SAASC;IAEb,IAAI,OAAOI,eAAe,YAAY;QACpCrI,WAAW;QACXgI,SAAS,MAAMK,WAAWL,QAAQlE;IACpC,OAAO,IAAI,OAAOuE,eAAe,UAAU;QACzCrI,WAAW;QACXgI,SAASnI,YAAYmI,QAAQK;IAC/B;IAEA,OAAOL;AACT"}
@@ -151,6 +151,11 @@ const EMPTY_ARRAY = [];
151
151
  /*#__PURE__*/ _jsx("div", {
152
152
  id: "sanity"
153
153
  }),
154
+ /*#__PURE__*/ _jsx("script", {
155
+ type: "application/json",
156
+ id: "sanity-resource-bindings",
157
+ children: "[]"
158
+ }),
154
159
  /*#__PURE__*/ _jsx("script", {
155
160
  src: entryPath,
156
161
  type: "module"
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/actions/build/renderDocumentWorker/components/DefaultDocument.tsx"],"sourcesContent":["import {Favicons} from './Favicons.js'\nimport {GlobalErrorHandler} from './GlobalErrorHandler.js'\nimport {NoJavascript} from './NoJavascript.js'\n\nconst globalStyles = `\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Regular.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 400;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Italic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 500;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Medium.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 500;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-MediumItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 600;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-SemiBold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 600;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-SemiBoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 700;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Bold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 700;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-BoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 800;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-ExtraBold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 800;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-ExtraBoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 900;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Black.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 900;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-BlackItalic.woff2\") format(\"woff2\");\n }\n html {\n @media (prefers-color-scheme: dark) {\n background-color: #13141b;\n }\n @media (prefers-color-scheme: light) {\n background-color: #ffffff;\n }\n }\n html,\n body,\n #sanity {\n height: 100%;\n }\n body {\n margin: 0;\n -webkit-font-smoothing: antialiased;\n }\n`\n\n/**\n * @hidden\n * @beta\n */\nexport interface DefaultDocumentProps {\n entryPath: string\n\n // Currently unused, but kept for potential future use\n basePath?: string\n\n css?: string[]\n}\n\nconst EMPTY_ARRAY: never[] = []\n\n/**\n * @internal\n */\nexport function DefaultDocument(props: DefaultDocumentProps): React.JSX.Element {\n const {css = EMPTY_ARRAY, entryPath} = props\n\n return (\n <html lang=\"en\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta\n content=\"width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover\"\n name=\"viewport\"\n />\n <meta content=\"noindex\" name=\"robots\" />\n <meta content=\"same-origin\" name=\"referrer\" />\n\n <Favicons />\n\n <title>Sanity Studio</title>\n\n <GlobalErrorHandler />\n\n {css.map((href) => (\n <link href={href} key={href} rel=\"stylesheet\" />\n ))}\n <style dangerouslySetInnerHTML={{__html: globalStyles}} />\n </head>\n <body>\n <div id=\"sanity\" />\n <script src={entryPath} type=\"module\" />\n <NoJavascript />\n </body>\n </html>\n )\n}\n"],"names":["Favicons","GlobalErrorHandler","NoJavascript","globalStyles","EMPTY_ARRAY","DefaultDocument","props","css","entryPath","html","lang","head","meta","charSet","content","name","title","map","href","link","rel","style","dangerouslySetInnerHTML","__html","body","div","id","script","src","type"],"mappings":";AAAA,SAAQA,QAAQ,QAAO,gBAAe;AACtC,SAAQC,kBAAkB,QAAO,0BAAyB;AAC1D,SAAQC,YAAY,QAAO,oBAAmB;AAE9C,MAAMC,eAAe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGtB,CAAC;AAeD,MAAMC,cAAuB,EAAE;AAE/B;;CAEC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;IACzD,MAAM,EAACC,MAAMH,WAAW,EAAEI,SAAS,EAAC,GAAGF;IAEvC,qBACE,MAACG;QAAKC,MAAK;;0BACT,MAACC;;kCACC,KAACC;wBAAKC,SAAQ;;kCACd,KAACD;wBACCE,SAAQ;wBACRC,MAAK;;kCAEP,KAACH;wBAAKE,SAAQ;wBAAUC,MAAK;;kCAC7B,KAACH;wBAAKE,SAAQ;wBAAcC,MAAK;;kCAEjC,KAACf;kCAED,KAACgB;kCAAM;;kCAEP,KAACf;oBAEAM,IAAIU,GAAG,CAAC,CAACC,qBACR,KAACC;4BAAKD,MAAMA;4BAAiBE,KAAI;2BAAVF;kCAEzB,KAACG;wBAAMC,yBAAyB;4BAACC,QAAQpB;wBAAY;;;;0BAEvD,MAACqB;;kCACC,KAACC;wBAAIC,IAAG;;kCACR,KAACC;wBAAOC,KAAKpB;wBAAWqB,MAAK;;kCAC7B,KAAC3B;;;;;AAIT"}
1
+ {"version":3,"sources":["../../../../../src/actions/build/renderDocumentWorker/components/DefaultDocument.tsx"],"sourcesContent":["import {Favicons} from './Favicons.js'\nimport {GlobalErrorHandler} from './GlobalErrorHandler.js'\nimport {NoJavascript} from './NoJavascript.js'\n\nconst globalStyles = `\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Regular.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 400;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Italic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 500;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Medium.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 500;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-MediumItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 600;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-SemiBold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 600;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-SemiBoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 700;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Bold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 700;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-BoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 800;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-ExtraBold.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 800;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-ExtraBoldItalic.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: normal;\n font-weight: 900;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-Black.woff2\") format(\"woff2\");\n }\n @font-face {\n font-family: Inter;\n font-style: italic;\n font-weight: 900;\n font-display: swap;\n src: url(\"https://studio-static.sanity.io/Inter-BlackItalic.woff2\") format(\"woff2\");\n }\n html {\n @media (prefers-color-scheme: dark) {\n background-color: #13141b;\n }\n @media (prefers-color-scheme: light) {\n background-color: #ffffff;\n }\n }\n html,\n body,\n #sanity {\n height: 100%;\n }\n body {\n margin: 0;\n -webkit-font-smoothing: antialiased;\n }\n`\n\n/**\n * @hidden\n * @beta\n */\nexport interface DefaultDocumentProps {\n entryPath: string\n\n // Currently unused, but kept for potential future use\n basePath?: string\n\n css?: string[]\n}\n\nconst EMPTY_ARRAY: never[] = []\n\n/**\n * @internal\n */\nexport function DefaultDocument(props: DefaultDocumentProps): React.JSX.Element {\n const {css = EMPTY_ARRAY, entryPath} = props\n\n return (\n <html lang=\"en\">\n <head>\n <meta charSet=\"utf-8\" />\n <meta\n content=\"width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover\"\n name=\"viewport\"\n />\n <meta content=\"noindex\" name=\"robots\" />\n <meta content=\"same-origin\" name=\"referrer\" />\n\n <Favicons />\n\n <title>Sanity Studio</title>\n\n <GlobalErrorHandler />\n\n {css.map((href) => (\n <link href={href} key={href} rel=\"stylesheet\" />\n ))}\n <style dangerouslySetInnerHTML={{__html: globalStyles}} />\n </head>\n <body>\n <div id=\"sanity\" />\n {/* Note: disable lint rule as brett depends on this specific ordering */}\n {/* eslint-disable-next-line perfectionist/sort-jsx-props */}\n <script type=\"application/json\" id=\"sanity-resource-bindings\">\n []\n </script>\n <script src={entryPath} type=\"module\" />\n <NoJavascript />\n </body>\n </html>\n )\n}\n"],"names":["Favicons","GlobalErrorHandler","NoJavascript","globalStyles","EMPTY_ARRAY","DefaultDocument","props","css","entryPath","html","lang","head","meta","charSet","content","name","title","map","href","link","rel","style","dangerouslySetInnerHTML","__html","body","div","id","script","type","src"],"mappings":";AAAA,SAAQA,QAAQ,QAAO,gBAAe;AACtC,SAAQC,kBAAkB,QAAO,0BAAyB;AAC1D,SAAQC,YAAY,QAAO,oBAAmB;AAE9C,MAAMC,eAAe,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGtB,CAAC;AAeD,MAAMC,cAAuB,EAAE;AAE/B;;CAEC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;IACzD,MAAM,EAACC,MAAMH,WAAW,EAAEI,SAAS,EAAC,GAAGF;IAEvC,qBACE,MAACG;QAAKC,MAAK;;0BACT,MAACC;;kCACC,KAACC;wBAAKC,SAAQ;;kCACd,KAACD;wBACCE,SAAQ;wBACRC,MAAK;;kCAEP,KAACH;wBAAKE,SAAQ;wBAAUC,MAAK;;kCAC7B,KAACH;wBAAKE,SAAQ;wBAAcC,MAAK;;kCAEjC,KAACf;kCAED,KAACgB;kCAAM;;kCAEP,KAACf;oBAEAM,IAAIU,GAAG,CAAC,CAACC,qBACR,KAACC;4BAAKD,MAAMA;4BAAiBE,KAAI;2BAAVF;kCAEzB,KAACG;wBAAMC,yBAAyB;4BAACC,QAAQpB;wBAAY;;;;0BAEvD,MAACqB;;kCACC,KAACC;wBAAIC,IAAG;;kCAGR,KAACC;wBAAOC,MAAK;wBAAmBF,IAAG;kCAA2B;;kCAG9D,KAACC;wBAAOE,KAAKrB;wBAAWoB,MAAK;;kCAC7B,KAAC1B;;;;;AAIT"}
@@ -4,12 +4,7 @@ import { createRequester } from '@sanity/cli-core/request';
4
4
  import { coerce, eq, prerelease, parse as semverParse } from 'semver';
5
5
  import { getModuleUrl } from '../actions/build/getAutoUpdatesImportMap.js';
6
6
  const defaultRequester = createRequester({
7
- middleware: {
8
- httpErrors: false,
9
- promise: {
10
- onlyBody: false
11
- }
12
- }
7
+ httpErrors: false
13
8
  });
14
9
  /**
15
10
  * @internal
@@ -83,8 +78,8 @@ async function getRemoteResolvedVersion(url) {
83
78
  let response;
84
79
  try {
85
80
  response = await defaultRequester({
86
- maxRedirects: 0,
87
81
  method: 'HEAD',
82
+ redirect: 'manual',
88
83
  url
89
84
  });
90
85
  } catch (err) {
@@ -94,17 +89,17 @@ async function getRemoteResolvedVersion(url) {
94
89
  });
95
90
  }
96
91
  // 302 is expected, but lets also handle 2xx
97
- if (response.statusCode < 400) {
98
- const resolved = response.headers['x-resolved-version'];
92
+ if (response.status < 400) {
93
+ const resolved = response.headers.get('x-resolved-version');
99
94
  if (!resolved) {
100
95
  throw new Error(`Missing 'x-resolved-version' header on response from HEAD ${url}`);
101
96
  }
102
97
  return resolved;
103
98
  }
104
- if (response.statusCode === 404) {
99
+ if (response.status === 404) {
105
100
  return null;
106
101
  }
107
- throw new Error(`Unexpected HTTP response: ${response.statusCode} ${response.statusMessage}`);
102
+ throw new Error(`Unexpected HTTP response: ${response.status} ${response.statusText}`);
108
103
  }
109
104
 
110
105
  //# sourceMappingURL=compareDependencyVersions.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/compareDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core'\nimport {createRequester} from '@sanity/cli-core/request'\nimport {coerce, eq, prerelease, parse as semverParse} from 'semver'\n\nimport {getModuleUrl} from '../actions/build/getAutoUpdatesImportMap.js'\n\nexport interface CompareDependencyVersions {\n installed: string\n pkg: string\n remote: string\n}\n\nexport interface UnresolvedPrerelease {\n pkg: string\n version: string\n}\n\nexport interface CompareDependencyVersionsResult {\n mismatched: Array<CompareDependencyVersions>\n unresolvedPrerelease: Array<UnresolvedPrerelease>\n}\n\nconst defaultRequester = createRequester({\n middleware: {httpErrors: false, promise: {onlyBody: false}},\n})\n\ninterface CompareDependencyVersionsOptions {\n /** When provided, uses the app-specific module endpoint instead of the default endpoint. */\n appId?: string\n}\n\n/**\n * @internal\n *\n * Compares the versions of dependencies in the studio or app with their remote versions.\n *\n * This function reads the package.json file in the provided working directory, and compares the versions of the dependencies\n * specified in the `autoUpdatesImports` parameter with their remote versions. If the versions do not match, the dependency is\n * added to a list of failed dependencies, which is returned by the function.\n *\n * The failed dependencies are anything that does not strictly match the remote version.\n * This means that if a version is lower or greater by even a patch it will be marked as failed.\n *\n * @param packages - An array of packages with their name and version to compare against remote.\n * @param workDir - The path to the working directory containing the package.json file.\n * @param options - Optional configuration for version comparison.\n *\n * @returns A promise that resolves to an object containing `mismatched` (packages whose local and remote versions differ)\n * and `unresolvedPrerelease` (packages with prerelease versions that could not be resolved remotely).\n *\n * @throws Throws an error if the remote version of a non-prerelease package cannot be fetched, or if the local version\n * of a package cannot be parsed.\n */\nexport async function compareDependencyVersions(\n packages: {name: string; version: string}[],\n workDir: string,\n {appId}: CompareDependencyVersionsOptions = {},\n): Promise<CompareDependencyVersionsResult> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const mismatched: Array<CompareDependencyVersions> = []\n const unresolvedPrerelease: Array<UnresolvedPrerelease> = []\n\n for (const pkg of packages) {\n // Skip packages that are not declared in the local package.json\n if (!dependencies[pkg.name]) {\n continue\n }\n\n const resolvedVersion = await getRemoteResolvedVersion(getModuleUrl(pkg, {appId}))\n\n if (resolvedVersion === null) {\n if (prerelease(pkg.version)) {\n unresolvedPrerelease.push({pkg: pkg.name, version: pkg.version})\n continue\n }\n throw new Error(\n `Failed to resolve remote version for ${pkg.name}@${pkg.version}: package not found`,\n )\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n\n const manifestVersion = dependencies[pkg.name]\n\n const installed = coerce(packageVersion ? semverParse(packageVersion) : coerce(manifestVersion))\n\n if (!installed) {\n throw new Error(`Failed to parse installed version for ${pkg.name}`)\n }\n\n if (!eq(resolvedVersion, installed.version)) {\n mismatched.push({\n installed: installed.version,\n pkg: pkg.name,\n remote: resolvedVersion,\n })\n }\n }\n\n return {mismatched, unresolvedPrerelease}\n}\n\nasync function getRemoteResolvedVersion(url: string): Promise<string | null> {\n let response\n try {\n response = await defaultRequester({\n maxRedirects: 0,\n method: 'HEAD',\n url,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to fetch remote version for ${url}: ${message}`, {cause: err})\n }\n\n // 302 is expected, but lets also handle 2xx\n if (response.statusCode < 400) {\n const resolved = response.headers['x-resolved-version']\n if (!resolved) {\n throw new Error(`Missing 'x-resolved-version' header on response from HEAD ${url}`)\n }\n return resolved\n }\n\n if (response.statusCode === 404) {\n return null\n }\n\n throw new Error(`Unexpected HTTP response: ${response.statusCode} ${response.statusMessage}`)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","createRequester","coerce","eq","prerelease","parse","semverParse","getModuleUrl","defaultRequester","middleware","httpErrors","promise","onlyBody","compareDependencyVersions","packages","workDir","appId","manifest","join","skipSchemaValidation","dependencies","devDependencies","mismatched","unresolvedPrerelease","pkg","name","resolvedVersion","getRemoteResolvedVersion","version","push","Error","packageVersion","manifestVersion","installed","remote","url","response","maxRedirects","method","err","message","String","cause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C,IAAI,EAAEV;QAE9D,MAAMiB,kBAAkBZ,YAAY,CAACI,IAAIC,IAAI,CAAC;QAE9C,MAAMQ,YAAY/B,OAAO6B,iBAAiBzB,YAAYyB,kBAAkB7B,OAAO8B;QAE/E,IAAI,CAACC,WAAW;YACd,MAAM,IAAIH,MAAM,CAAC,sCAAsC,EAAEN,IAAIC,IAAI,EAAE;QACrE;QAEA,IAAI,CAACtB,GAAGuB,iBAAiBO,UAAUL,OAAO,GAAG;YAC3CN,WAAWO,IAAI,CAAC;gBACdI,WAAWA,UAAUL,OAAO;gBAC5BJ,KAAKA,IAAIC,IAAI;gBACbS,QAAQR;YACV;QACF;IACF;IAEA,OAAO;QAACJ;QAAYC;IAAoB;AAC1C;AAEA,eAAeI,yBAAyBQ,GAAW;IACjD,IAAIC;IACJ,IAAI;QACFA,WAAW,MAAM5B,iBAAiB;YAChC6B,cAAc;YACdC,QAAQ;YACRH;QACF;IACF,EAAE,OAAOI,KAAK;QACZ,MAAMC,UAAUD,eAAeT,QAAQS,IAAIC,OAAO,GAAGC,OAAOF;QAC5D,MAAM,IAAIT,MAAM,CAAC,mCAAmC,EAAEK,IAAI,EAAE,EAAEK,SAAS,EAAE;YAACE,OAAOH;QAAG;IACtF;IAEA,4CAA4C;IAC5C,IAAIH,SAASO,UAAU,GAAG,KAAK;QAC7B,MAAMC,WAAWR,SAASS,OAAO,CAAC,qBAAqB;QACvD,IAAI,CAACD,UAAU;YACb,MAAM,IAAId,MAAM,CAAC,0DAA0D,EAAEK,KAAK;QACpF;QACA,OAAOS;IACT;IAEA,IAAIR,SAASO,UAAU,KAAK,KAAK;QAC/B,OAAO;IACT;IAEA,MAAM,IAAIb,MAAM,CAAC,0BAA0B,EAAEM,SAASO,UAAU,CAAC,CAAC,EAAEP,SAASU,aAAa,EAAE;AAC9F"}
1
+ {"version":3,"sources":["../../src/util/compareDependencyVersions.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {getLocalPackageVersion, readPackageJson} from '@sanity/cli-core'\nimport {createRequester} from '@sanity/cli-core/request'\nimport {coerce, eq, prerelease, parse as semverParse} from 'semver'\n\nimport {getModuleUrl} from '../actions/build/getAutoUpdatesImportMap.js'\n\nexport interface CompareDependencyVersions {\n installed: string\n pkg: string\n remote: string\n}\n\nexport interface UnresolvedPrerelease {\n pkg: string\n version: string\n}\n\nexport interface CompareDependencyVersionsResult {\n mismatched: Array<CompareDependencyVersions>\n unresolvedPrerelease: Array<UnresolvedPrerelease>\n}\n\nconst defaultRequester = createRequester({\n httpErrors: false,\n})\n\ninterface CompareDependencyVersionsOptions {\n /** When provided, uses the app-specific module endpoint instead of the default endpoint. */\n appId?: string\n}\n\n/**\n * @internal\n *\n * Compares the versions of dependencies in the studio or app with their remote versions.\n *\n * This function reads the package.json file in the provided working directory, and compares the versions of the dependencies\n * specified in the `autoUpdatesImports` parameter with their remote versions. If the versions do not match, the dependency is\n * added to a list of failed dependencies, which is returned by the function.\n *\n * The failed dependencies are anything that does not strictly match the remote version.\n * This means that if a version is lower or greater by even a patch it will be marked as failed.\n *\n * @param packages - An array of packages with their name and version to compare against remote.\n * @param workDir - The path to the working directory containing the package.json file.\n * @param options - Optional configuration for version comparison.\n *\n * @returns A promise that resolves to an object containing `mismatched` (packages whose local and remote versions differ)\n * and `unresolvedPrerelease` (packages with prerelease versions that could not be resolved remotely).\n *\n * @throws Throws an error if the remote version of a non-prerelease package cannot be fetched, or if the local version\n * of a package cannot be parsed.\n */\nexport async function compareDependencyVersions(\n packages: {name: string; version: string}[],\n workDir: string,\n {appId}: CompareDependencyVersionsOptions = {},\n): Promise<CompareDependencyVersionsResult> {\n const manifest = await readPackageJson(path.join(workDir, 'package.json'), {\n skipSchemaValidation: true,\n })\n const dependencies = {...manifest?.dependencies, ...manifest?.devDependencies}\n\n const mismatched: Array<CompareDependencyVersions> = []\n const unresolvedPrerelease: Array<UnresolvedPrerelease> = []\n\n for (const pkg of packages) {\n // Skip packages that are not declared in the local package.json\n if (!dependencies[pkg.name]) {\n continue\n }\n\n const resolvedVersion = await getRemoteResolvedVersion(getModuleUrl(pkg, {appId}))\n\n if (resolvedVersion === null) {\n if (prerelease(pkg.version)) {\n unresolvedPrerelease.push({pkg: pkg.name, version: pkg.version})\n continue\n }\n throw new Error(\n `Failed to resolve remote version for ${pkg.name}@${pkg.version}: package not found`,\n )\n }\n\n const packageVersion = await getLocalPackageVersion(pkg.name, workDir)\n\n const manifestVersion = dependencies[pkg.name]\n\n const installed = coerce(packageVersion ? semverParse(packageVersion) : coerce(manifestVersion))\n\n if (!installed) {\n throw new Error(`Failed to parse installed version for ${pkg.name}`)\n }\n\n if (!eq(resolvedVersion, installed.version)) {\n mismatched.push({\n installed: installed.version,\n pkg: pkg.name,\n remote: resolvedVersion,\n })\n }\n }\n\n return {mismatched, unresolvedPrerelease}\n}\n\nasync function getRemoteResolvedVersion(url: string): Promise<string | null> {\n let response\n try {\n response = await defaultRequester({\n method: 'HEAD',\n redirect: 'manual',\n url,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to fetch remote version for ${url}: ${message}`, {cause: err})\n }\n\n // 302 is expected, but lets also handle 2xx\n if (response.status < 400) {\n const resolved = response.headers.get('x-resolved-version')\n if (!resolved) {\n throw new Error(`Missing 'x-resolved-version' header on response from HEAD ${url}`)\n }\n return resolved\n }\n\n if (response.status === 404) {\n return null\n }\n\n throw new Error(`Unexpected HTTP response: ${response.status} ${response.statusText}`)\n}\n"],"names":["path","getLocalPackageVersion","readPackageJson","createRequester","coerce","eq","prerelease","parse","semverParse","getModuleUrl","defaultRequester","httpErrors","compareDependencyVersions","packages","workDir","appId","manifest","join","skipSchemaValidation","dependencies","devDependencies","mismatched","unresolvedPrerelease","pkg","name","resolvedVersion","getRemoteResolvedVersion","version","push","Error","packageVersion","manifestVersion","installed","remote","url","response","method","redirect","err","message","String","cause","status","resolved","headers","get","statusText"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAQC,sBAAsB,EAAEC,e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B;QAE/E,IAAI,CAACC,WAAW;YACd,MAAM,IAAIH,MAAM,CAAC,sCAAsC,EAAEN,IAAIC,IAAI,EAAE;QACrE;QAEA,IAAI,CAACnB,GAAGoB,iBAAiBO,UAAUL,OAAO,GAAG;YAC3CN,WAAWO,IAAI,CAAC;gBACdI,WAAWA,UAAUL,OAAO;gBAC5BJ,KAAKA,IAAIC,IAAI;gBACbS,QAAQR;YACV;QACF;IACF;IAEA,OAAO;QAACJ;QAAYC;IAAoB;AAC1C;AAEA,eAAeI,yBAAyBQ,GAAW;IACjD,IAAIC;IACJ,IAAI;QACFA,WAAW,MAAMzB,iBAAiB;YAChC0B,QAAQ;YACRC,UAAU;YACVH;QACF;IACF,EAAE,OAAOI,KAAK;QACZ,MAAMC,UAAUD,eAAeT,QAAQS,IAAIC,OAAO,GAAGC,OAAOF;QAC5D,MAAM,IAAIT,MAAM,CAAC,mCAAmC,EAAEK,IAAI,EAAE,EAAEK,SAAS,EAAE;YAACE,OAAOH;QAAG;IACtF;IAEA,4CAA4C;IAC5C,IAAIH,SAASO,MAAM,GAAG,KAAK;QACzB,MAAMC,WAAWR,SAASS,OAAO,CAACC,GAAG,CAAC;QACtC,IAAI,CAACF,UAAU;YACb,MAAM,IAAId,MAAM,CAAC,0DAA0D,EAAEK,KAAK;QACpF;QACA,OAAOS;IACT;IAEA,IAAIR,SAASO,MAAM,KAAK,KAAK;QAC3B,OAAO;IACT;IAEA,MAAM,IAAIb,MAAM,CAAC,0BAA0B,EAAEM,SAASO,MAAM,CAAC,CAAC,EAAEP,SAASW,UAAU,EAAE;AACvF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-build",
3
- "version": "5.1.0",
3
+ "version": "5.2.1",
4
4
  "description": "Internal Sanity package for building studios and apps",
5
5
  "keywords": [
6
6
  "cli",
@@ -52,10 +52,9 @@
52
52
  "@sanity/schema": "^6.7.0",
53
53
  "@sanity/telemetry": "^1.1.0",
54
54
  "@sanity/types": "^6.7.0",
55
- "@vitejs/plugin-react": "^6.0.3",
55
+ "@vitejs/plugin-react": "^6.0.5",
56
56
  "chokidar": "^5.0.0",
57
57
  "cjs-module-lexer": "^2.2.0",
58
- "debug": "^4.4.3",
59
58
  "empathic": "^2.0.1",
60
59
  "lodash-es": "^4.18.1",
61
60
  "node-html-parser": "^7.1.0",
@@ -64,17 +63,16 @@
64
63
  "react": "^19.2.7",
65
64
  "react-dom": "^19.2.7",
66
65
  "semver": "^7.8.1",
67
- "vite": "^8.1.5",
66
+ "vite": "^8.2.1",
68
67
  "zod": "^4.4.3",
69
- "@sanity/cli-core": "^2.7.0",
70
- "@sanity/workbench-cli": "^1.8.0"
68
+ "@sanity/cli-core": "^3.1.0",
69
+ "@sanity/workbench-cli": "^2.0.1"
71
70
  },
72
71
  "devDependencies": {
73
72
  "@eslint/compat": "^2.1.0",
74
- "@sanity/pkg-utils": "^11.0.9",
73
+ "@sanity/pkg-utils": "^12.1.2",
75
74
  "@swc/cli": "^0.8.1",
76
75
  "@swc/core": "^1.15.43",
77
- "@types/debug": "^4.1.13",
78
76
  "@types/lodash-es": "^4.17.12",
79
77
  "@types/node": "^22.20.0",
80
78
  "@types/picomatch": "^4.0.3",
@@ -90,9 +88,9 @@
90
88
  "styled-components": "^6.4.3",
91
89
  "typescript": "^6.0.3",
92
90
  "vitest": "^4.1.10",
93
- "@repo/package.config": "0.0.1",
94
91
  "@repo/tsconfig": "3.70.0",
95
- "@sanity/cli-test": "8.0.0",
92
+ "@repo/package.config": "0.0.1",
93
+ "@sanity/cli-test": "11.0.0",
96
94
  "@sanity/eslint-config-cli": "^1.1.3"
97
95
  },
98
96
  "peerDependencies": {