@sanity/workbench-cli 2.0.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/_internal_render.d.ts +12 -0
- package/dist/_exports/_internal_render.js +3 -0
- package/dist/_exports/_internal_render.js.map +1 -0
- package/dist/_exports/build.d.ts +1 -1
- package/dist/_exports/{defineApp-r_CmoZfS.d.ts → defineApp-DSvQx8rf.d.ts} +3 -21
- package/dist/_exports/deploy.d.ts +1 -1
- package/dist/_exports/index.d.ts +1 -1
- package/dist/_exports/{resolveWorkbenchApp-DqFqET9E.d.ts → resolveWorkbenchApp-Be9eU8mu.d.ts} +2 -2
- package/dist/_exports/{summarizeInterfaces-DBGiAwNT.d.ts → summarizeInterfaces-DLsq6P43.d.ts} +2 -2
- package/dist/_exports/undeploy.d.ts +1 -1
- package/dist/actions/build/vite/plugins/plugin-module-federation.js +7 -15
- package/dist/actions/build/vite/plugins/plugin-module-federation.js.map +1 -1
- package/dist/actions/dev/startWorkbenchDevServer.js +12 -30
- package/dist/actions/dev/startWorkbenchDevServer.js.map +1 -1
- package/dist/actions/dev/writeWorkbenchRuntime.js +2 -2
- package/dist/actions/dev/writeWorkbenchRuntime.js.map +1 -1
- package/dist/defineApp.js +1 -4
- package/dist/defineApp.js.map +1 -1
- package/dist/renderDashboard.js +63 -0
- package/dist/renderDashboard.js.map +1 -0
- package/package.json +12 -6
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
declare global {
|
|
2
|
+
var __SANITY_STAGING__: boolean | undefined;
|
|
3
|
+
}
|
|
4
|
+
interface DashboardConfig {
|
|
5
|
+
organizationId: string;
|
|
6
|
+
}
|
|
7
|
+
interface RenderDashboardOptions {
|
|
8
|
+
reactStrictMode?: boolean;
|
|
9
|
+
}
|
|
10
|
+
declare function renderDashboard(rootElement: HTMLElement | null, config: DashboardConfig, options?: RenderDashboardOptions): Promise<() => void>;
|
|
11
|
+
export { renderDashboard };
|
|
12
|
+
//# sourceMappingURL=_internal_render.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/_internal_render.ts"],"sourcesContent":["export {renderDashboard} from '../renderDashboard.js'\n"],"names":["renderDashboard"],"mappings":"AAAA,SAAQA,eAAe,QAAO,wBAAuB"}
|
package/dist/_exports/build.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as WorkbenchExposes, r as resolveWorkbenchApp, t as ResolvedWorkbenchApp } from "./resolveWorkbenchApp-
|
|
1
|
+
import { n as WorkbenchExposes, r as resolveWorkbenchApp, t as ResolvedWorkbenchApp } from "./resolveWorkbenchApp-Be9eU8mu.js";
|
|
2
2
|
import { PluginOption } from "vite";
|
|
3
3
|
/**
|
|
4
4
|
* Dep pre-bundling inputs for a workbench app's dev server.
|
|
@@ -79,30 +79,12 @@ declare const DefineAppInputSchema: z.ZodMiniObject<{
|
|
|
79
79
|
disabled: "disabled";
|
|
80
80
|
}>>;
|
|
81
81
|
}, z.core.$strip>;
|
|
82
|
-
/** The `asset_source` variant of an app's `views`. @public */
|
|
83
|
-
type AssetSourceView = Extract<NonNullable<z.output<typeof DefineAppInputSchema>['views']>[number], {
|
|
84
|
-
type: 'asset_source';
|
|
85
|
-
}>;
|
|
86
|
-
/** The `tile` variant of an app's `views`. @public */
|
|
87
|
-
type TileView = Extract<NonNullable<z.output<typeof DefineAppInputSchema>['views']>[number], {
|
|
88
|
-
type: 'tile';
|
|
89
|
-
}>;
|
|
90
82
|
/**
|
|
91
83
|
* User-facing input for `unstable_defineApp`. Excludes the internal
|
|
92
|
-
* `applicationType`, `isSingleton`, and `config
|
|
93
|
-
* not part of the public surface (Sanity-owned apps set them via
|
|
94
|
-
* `@ts-expect-error`). A union: an app declares an app `entry` (navigable) or
|
|
95
|
-
* panel `views`, never both — but `asset_source` and `tile` views are separate
|
|
96
|
-
* kinds and may accompany either.
|
|
84
|
+
* `applicationType`, `isSingleton`, and `config`.
|
|
97
85
|
* @public
|
|
98
86
|
*/
|
|
99
|
-
type DefineAppInput = Omit<z.output<typeof DefineAppInputSchema>, 'applicationType' | 'config' | '
|
|
100
|
-
entry?: never;
|
|
101
|
-
views?: NonNullable<z.output<typeof DefineAppInputSchema>['views']>;
|
|
102
|
-
} | {
|
|
103
|
-
entry?: string;
|
|
104
|
-
views?: (AssetSourceView | TileView)[];
|
|
105
|
-
});
|
|
87
|
+
type DefineAppInput = Omit<z.output<typeof DefineAppInputSchema>, 'applicationType' | 'config' | 'isSingleton'>;
|
|
106
88
|
/**
|
|
107
89
|
* Nominal brand the CLI discriminates on to enable the workbench build/deploy
|
|
108
90
|
* codepath. Registered via `Symbol.for` so the marker survives module-realm
|
|
@@ -166,4 +148,4 @@ interface DefineMediaLibraryInput {
|
|
|
166
148
|
*/
|
|
167
149
|
declare function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): DefineAppResult;
|
|
168
150
|
export { MediaLibraryField as a, unstable_defineApp as c, DockGroup as i, unstable_defineMediaLibrary as l, DefineAppResult as n, WorkbenchApp as o, DefineMediaLibraryInput as r, isWorkbenchApp as s, DefineAppInput as t };
|
|
169
|
-
//# sourceMappingURL=defineApp-
|
|
151
|
+
//# sourceMappingURL=defineApp-DSvQx8rf.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as getWorkbench, n as summarizeInterfaces, r as DeployableWorkbenchApp, t as DeployedInterface } from "./summarizeInterfaces-
|
|
1
|
+
import { i as getWorkbench, n as summarizeInterfaces, r as DeployableWorkbenchApp, t as DeployedInterface } from "./summarizeInterfaces-DLsq6P43.js";
|
|
2
2
|
import "./contract-DyG11fQ7.js";
|
|
3
3
|
import { AppVisibility, CliConfig, Output } from "@sanity/cli-core";
|
|
4
4
|
import "node:zlib";
|
package/dist/_exports/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as MediaLibraryField, c as unstable_defineApp, i as DockGroup, l as unstable_defineMediaLibrary, n as DefineAppResult, o as WorkbenchApp, r as DefineMediaLibraryInput, s as isWorkbenchApp, t as DefineAppInput } from "./defineApp-
|
|
1
|
+
import { a as MediaLibraryField, c as unstable_defineApp, i as DockGroup, l as unstable_defineMediaLibrary, n as DefineAppResult, o as WorkbenchApp, r as DefineMediaLibraryInput, s as isWorkbenchApp, t as DefineAppInput } from "./defineApp-DSvQx8rf.js";
|
|
2
2
|
import { a as VIEW_CONTRACT_VERSION, i as TileSize, n as SERVICE_CONTRACT_VERSION, o as ViewComponent, r as ServiceType, s as ViewComponentBaseProps, t as InterfaceType } from "./contract-DyG11fQ7.js";
|
|
3
3
|
import { AssetSourceComponentProps } from "@sanity/types";
|
|
4
4
|
/**
|
package/dist/_exports/{resolveWorkbenchApp-DqFqET9E.d.ts → resolveWorkbenchApp-Be9eU8mu.d.ts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as WorkbenchApp, t as DefineAppInput } from "./defineApp-
|
|
1
|
+
import { o as WorkbenchApp, t as DefineAppInput } from "./defineApp-DSvQx8rf.js";
|
|
2
2
|
import { AppVisibility, CliConfig } from "@sanity/cli-core";
|
|
3
3
|
/**
|
|
4
4
|
* Bundled so adding a declaration family touches this type and the artifact
|
|
@@ -38,4 +38,4 @@ interface ResolvedWorkbenchApp {
|
|
|
38
38
|
*/
|
|
39
39
|
declare function resolveWorkbenchApp(cliConfig: CliConfig | null | undefined): ResolvedWorkbenchApp | null;
|
|
40
40
|
export { WorkbenchExposes as n, resolveWorkbenchApp as r, ResolvedWorkbenchApp as t };
|
|
41
|
-
//# sourceMappingURL=resolveWorkbenchApp-
|
|
41
|
+
//# sourceMappingURL=resolveWorkbenchApp-Be9eU8mu.d.ts.map
|
package/dist/_exports/{summarizeInterfaces-DBGiAwNT.d.ts → summarizeInterfaces-DLsq6P43.d.ts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as WorkbenchExposes, t as ResolvedWorkbenchApp } from "./resolveWorkbenchApp-
|
|
1
|
+
import { n as WorkbenchExposes, t as ResolvedWorkbenchApp } from "./resolveWorkbenchApp-Be9eU8mu.js";
|
|
2
2
|
import { CliConfig } from "@sanity/cli-core";
|
|
3
3
|
import { z } from "zod/mini";
|
|
4
4
|
/**
|
|
@@ -59,4 +59,4 @@ declare function summarizeInterfaces({ services, views }: WorkbenchExposes): {
|
|
|
59
59
|
views: DeployedInterface[];
|
|
60
60
|
};
|
|
61
61
|
export { getWorkbench as i, summarizeInterfaces as n, DeployableWorkbenchApp as r, DeployedInterface as t };
|
|
62
|
-
//# sourceMappingURL=summarizeInterfaces-
|
|
62
|
+
//# sourceMappingURL=summarizeInterfaces-DLsq6P43.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as DeployableWorkbenchApp, t as DeployedInterface } from "./summarizeInterfaces-
|
|
1
|
+
import { r as DeployableWorkbenchApp, t as DeployedInterface } from "./summarizeInterfaces-DLsq6P43.js";
|
|
2
2
|
import "node:zlib";
|
|
3
3
|
import { UndeployAdapter, UndeployApplicationTarget, UndeployConfigTarget } from "@sanity/cli-core/undeploy";
|
|
4
4
|
interface ConfigSnapshot {
|
|
@@ -6,17 +6,10 @@ export function sanityModuleFederation({ exposes, name }) {
|
|
|
6
6
|
disableDynamicRemoteTypeHints: true,
|
|
7
7
|
remoteHmr: true
|
|
8
8
|
},
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
|
|
13
|
-
// worked around, declaration emit pulls in the user's own modules, which
|
|
14
|
-
// are noEmit projects never written to be declaration-emittable: TS2742
|
|
15
|
-
// (non-portable inferred types, endemic under pnpm) and TS4082 (private
|
|
16
|
-
// names in default exports) then fail the compile just the same.
|
|
17
|
-
dts: {
|
|
18
|
-
generateTypes: false
|
|
19
|
-
},
|
|
9
|
+
// Fully off (`false`, not `{generateTypes: false}`) so the dts plugin's
|
|
10
|
+
// dev worker and broker never load — left on, they crash `sanity dev` on
|
|
11
|
+
// Ctrl-C by sending on a still-CONNECTING websocket.
|
|
12
|
+
dts: false,
|
|
20
13
|
exposes,
|
|
21
14
|
filename: `${FEDERATION_FILE_NAME}.js`,
|
|
22
15
|
manifest: true,
|
|
@@ -32,10 +25,9 @@ export function sanityModuleFederation({ exposes, name }) {
|
|
|
32
25
|
// federation runtime, so we opt out of auto-share entirely.
|
|
33
26
|
shared: {}
|
|
34
27
|
});
|
|
35
|
-
// module-federation
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
// every actual plugin gets scoped.
|
|
28
|
+
// module-federation can deliver a plugin as a Promise resolving to an array;
|
|
29
|
+
// spreading a promise (or an array) yields a junk object that silently drops
|
|
30
|
+
// it. Recurse through the PluginOption shape so every actual plugin gets scoped.
|
|
39
31
|
const scopeToEnvironment = (option)=>{
|
|
40
32
|
if (!option) return option;
|
|
41
33
|
if (option instanceof Promise) return option.then((resolved)=>scopeToEnvironment(resolved));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-module-federation.ts"],"sourcesContent":["import {federation as moduleFederation, type ModuleFederationOptions} from '@module-federation/vite'\nimport {type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME, FEDERATION_FILE_NAME} from '../constants.js'\n\n/**\n * @internal\n */\nexport interface FederationOptions extends Pick<ModuleFederationOptions, 'exposes'> {\n /**\n * namespace of the federation build, used as the global variable name for the exposed modules\n * e.g `@acme/studio` would then allow you to import modules like `import (\"@acme/studio/Button\")`\n * defaults to your package.json name if not provided.\n */\n name: string\n}\n\nexport function sanityModuleFederation({exposes, name}: FederationOptions): PluginOption {\n const mfPlugins = moduleFederation({\n dev: {\n disableDynamicRemoteTypeHints: true,\n remoteHmr: true,\n },\n //
|
|
1
|
+
{"version":3,"sources":["../../../../../src/actions/build/vite/plugins/plugin-module-federation.ts"],"sourcesContent":["import {federation as moduleFederation, type ModuleFederationOptions} from '@module-federation/vite'\nimport {type Plugin, type PluginOption} from 'vite'\n\nimport {FEDERATION_DIR_NAME, FEDERATION_FILE_NAME} from '../constants.js'\n\n/**\n * @internal\n */\nexport interface FederationOptions extends Pick<ModuleFederationOptions, 'exposes'> {\n /**\n * namespace of the federation build, used as the global variable name for the exposed modules\n * e.g `@acme/studio` would then allow you to import modules like `import (\"@acme/studio/Button\")`\n * defaults to your package.json name if not provided.\n */\n name: string\n}\n\nexport function sanityModuleFederation({exposes, name}: FederationOptions): PluginOption {\n const mfPlugins = moduleFederation({\n dev: {\n disableDynamicRemoteTypeHints: true,\n remoteHmr: true,\n },\n // Fully off (`false`, not `{generateTypes: false}`) so the dts plugin's\n // dev worker and broker never load — left on, they crash `sanity dev` on\n // Ctrl-C by sending on a still-CONNECTING websocket.\n dts: false,\n exposes,\n filename: `${FEDERATION_FILE_NAME}.js`,\n manifest: true,\n name,\n // Resolves the remote entry path relative to the manifest rather than the\n // host origin.\n publicPath: 'auto',\n // @module-federation/vite auto-shares every package.json dependency\n // that exposes an `exports` field. That breaks for workspace packages with\n // subpath-only exports (no `.` entry) like `@sanity/cli-build` and\n // `@sanity/workbench`, because vite tries to resolve them as bare imports\n // and fails. Workbench remotes manage runtime sharing through the host's\n // federation runtime, so we opt out of auto-share entirely.\n shared: {},\n })\n\n // module-federation can deliver a plugin as a Promise resolving to an array;\n // spreading a promise (or an array) yields a junk object that silently drops\n // it. Recurse through the PluginOption shape so every actual plugin gets scoped.\n const scopeToEnvironment = (option: PluginOption): PluginOption => {\n if (!option) return option\n if (option instanceof Promise) return option.then((resolved) => scopeToEnvironment(resolved))\n if (Array.isArray(option)) return option.map((entry) => scopeToEnvironment(entry))\n return {\n ...option,\n // In dev, MF must run on client — the dev server serves through it.\n // In build, scope to the federation environment to keep the library build clean.\n applyToEnvironment: (env) =>\n env.config.command === 'serve' || env.name === FEDERATION_DIR_NAME,\n } satisfies Plugin\n }\n\n return mfPlugins.map((plugin: PluginOption) => scopeToEnvironment(plugin))\n}\n"],"names":["federation","moduleFederation","FEDERATION_DIR_NAME","FEDERATION_FILE_NAME","sanityModuleFederation","exposes","name","mfPlugins","dev","disableDynamicRemoteTypeHints","remoteHmr","dts","filename","manifest","publicPath","shared","scopeToEnvironment","option","Promise","then","resolved","Array","isArray","map","entry","applyToEnvironment","env","config","command","plugin"],"mappings":"AAAA,SAAQA,cAAcC,gBAAgB,QAAqC,0BAAyB;AAGpG,SAAQC,mBAAmB,EAAEC,oBAAoB,QAAO,kBAAiB;AAczE,OAAO,SAASC,uBAAuB,EAACC,OAAO,EAAEC,IAAI,EAAoB;IACvE,MAAMC,YAAYN,iBAAiB;QACjCO,KAAK;YACHC,+BAA+B;YAC/BC,WAAW;QACb;QACA,wEAAwE;QACxE,yEAAyE;QACzE,qDAAqD;QACrDC,KAAK;QACLN;QACAO,UAAU,GAAGT,qBAAqB,GAAG,CAAC;QACtCU,UAAU;QACVP;QACA,0EAA0E;QAC1E,eAAe;QACfQ,YAAY;QACZ,oEAAoE;QACpE,2EAA2E;QAC3E,mEAAmE;QACnE,0EAA0E;QAC1E,yEAAyE;QACzE,4DAA4D;QAC5DC,QAAQ,CAAC;IACX;IAEA,6EAA6E;IAC7E,6EAA6E;IAC7E,iFAAiF;IACjF,MAAMC,qBAAqB,CAACC;QAC1B,IAAI,CAACA,QAAQ,OAAOA;QACpB,IAAIA,kBAAkBC,SAAS,OAAOD,OAAOE,IAAI,CAAC,CAACC,WAAaJ,mBAAmBI;QACnF,IAAIC,MAAMC,OAAO,CAACL,SAAS,OAAOA,OAAOM,GAAG,CAAC,CAACC,QAAUR,mBAAmBQ;QAC3E,OAAO;YACL,GAAGP,MAAM;YACT,oEAAoE;YACpE,iFAAiF;YACjFQ,oBAAoB,CAACC,MACnBA,IAAIC,MAAM,CAACC,OAAO,KAAK,WAAWF,IAAIpB,IAAI,KAAKJ;QACnD;IACF;IAEA,OAAOK,UAAUgB,GAAG,CAAC,CAACM,SAAyBb,mBAAmBa;AACpE"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { subdebug } from '@sanity/cli-core';
|
|
2
3
|
import { isStaging } from '@sanity/cli-core/util';
|
|
3
4
|
import viteReact from '@vitejs/plugin-react';
|
|
4
5
|
import { createServer } from 'vite';
|
|
@@ -8,6 +9,8 @@ import { createExposesTracker } from './exposesSetId.js';
|
|
|
8
9
|
import { acquireWorkbenchLock, getRegisteredServers, isConfigOnlyServer, readWorkbenchLock, watchRegistry } from './registry.js';
|
|
9
10
|
import { writeWorkbenchRuntime } from './writeWorkbenchRuntime.js';
|
|
10
11
|
const devDebug = subdebug('dev');
|
|
12
|
+
const renderDashboardEntry = '@sanity/workbench-cli/_internal_render';
|
|
13
|
+
const renderDashboardPath = fileURLToPath(new URL('../../_exports/_internal_render.js', import.meta.url));
|
|
11
14
|
const noop = async ()=>{};
|
|
12
15
|
// Every server is a local app except a config-only one — a config
|
|
13
16
|
// with no interfaces (the media library). A server with both lands in both channels.
|
|
@@ -78,12 +81,7 @@ const toApplicationsPayload = (servers)=>({
|
|
|
78
81
|
}
|
|
79
82
|
};
|
|
80
83
|
}
|
|
81
|
-
|
|
82
|
-
* Start the workbench dev server when federation is enabled and the workbench
|
|
83
|
-
* package is available. If the desired port is already taken — by another
|
|
84
|
-
* workbench instance or an unrelated process — fall back to running without a
|
|
85
|
-
* workbench and let the app/studio dev server claim the configured port.
|
|
86
|
-
*/ export async function startWorkbenchDevServer(options) {
|
|
84
|
+
export async function startWorkbenchDevServer(options) {
|
|
87
85
|
const { cacheDir, cliConfig, httpHost, httpPort: workbenchPort, mode, output, reactStrictMode, workDir } = options;
|
|
88
86
|
// Workbench is opted into solely by calling `unstable_defineApp`.
|
|
89
87
|
if (!isWorkbenchApp(cliConfig?.app)) {
|
|
@@ -95,21 +93,6 @@ const toApplicationsPayload = (servers)=>({
|
|
|
95
93
|
workbenchPort
|
|
96
94
|
};
|
|
97
95
|
}
|
|
98
|
-
let workbenchAvailable = false;
|
|
99
|
-
try {
|
|
100
|
-
await resolveLocalPackage('sanity/workbench', workDir);
|
|
101
|
-
workbenchAvailable = true;
|
|
102
|
-
} catch {
|
|
103
|
-
devDebug('Workbench not available, skipping workbench dev server');
|
|
104
|
-
}
|
|
105
|
-
if (!workbenchAvailable) {
|
|
106
|
-
return {
|
|
107
|
-
close: noop,
|
|
108
|
-
httpHost,
|
|
109
|
-
workbenchAvailable,
|
|
110
|
-
workbenchPort
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
96
|
// Acquire an exclusive lock — only one workbench per machine.
|
|
114
97
|
// Uses O_EXCL which is atomic at the OS level, preventing races when
|
|
115
98
|
// multiple `sanity dev` processes start simultaneously (e.g. via turbo).
|
|
@@ -163,7 +146,7 @@ const toApplicationsPayload = (servers)=>({
|
|
|
163
146
|
await close();
|
|
164
147
|
},
|
|
165
148
|
httpHost,
|
|
166
|
-
workbenchAvailable,
|
|
149
|
+
workbenchAvailable: true,
|
|
167
150
|
workbenchPort: actualPort
|
|
168
151
|
};
|
|
169
152
|
}
|
|
@@ -192,14 +175,9 @@ async function createWorkbenchViteServer(options) {
|
|
|
192
175
|
logLevel: 'warn',
|
|
193
176
|
mode: 'development',
|
|
194
177
|
optimizeDeps: {
|
|
195
|
-
//
|
|
196
|
-
// from dep pre-bundling so that `import.meta.hot` is available at
|
|
197
|
-
// runtime — pre-bundled modules do not receive Vite's HMR client
|
|
198
|
-
// injection, which causes the custom HMR events for local application
|
|
199
|
-
// discovery to silently not fire.
|
|
178
|
+
// Keep this entry out of pre-bundling so Vite injects its HMR context.
|
|
200
179
|
exclude: [
|
|
201
|
-
|
|
202
|
-
'@sanity/workbench'
|
|
180
|
+
renderDashboardEntry
|
|
203
181
|
]
|
|
204
182
|
},
|
|
205
183
|
// viteReact looks inert here — it transforms none of the host's own modules —
|
|
@@ -216,6 +194,10 @@ async function createWorkbenchViteServer(options) {
|
|
|
216
194
|
] : []
|
|
217
195
|
],
|
|
218
196
|
resolve: {
|
|
197
|
+
// The generated Vite root cannot reliably resolve this package.
|
|
198
|
+
alias: {
|
|
199
|
+
[renderDashboardEntry]: renderDashboardPath
|
|
200
|
+
},
|
|
219
201
|
dedupe: [
|
|
220
202
|
'react',
|
|
221
203
|
'react-dom'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {type CliConfig, type Output, resolveLocalPackage, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n readWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst isLocalApp = (server: DevServerManifest): boolean => !isConfigOnlyServer(server)\n\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => isLocalApp(server))\n .map(({host, id, interfaces, manifest, port, projectId, type}) => ({\n host,\n id,\n interfaces,\n manifest,\n port,\n projectId,\n type,\n })),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n /** `dev` renders a live app and honors a local workbench-UI override; `preview`\n * (`sanity start`) previews a build and loads the deployed workbench UI. */\n mode: 'development' | 'preview'\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\n/**\n * Start the workbench dev server when federation is enabled and the workbench\n * package is available. If the desired port is already taken — by another\n * workbench instance or an unrelated process — fall back to running without a\n * workbench and let the app/studio dev server claim the configured port.\n */\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n mode,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into solely by calling `unstable_defineApp`.\n if (!isWorkbenchApp(cliConfig?.app)) {\n devDebug('Not a workbench app, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n let workbenchAvailable = false\n\n try {\n await resolveLocalPackage('sanity/workbench', workDir)\n workbenchAvailable = true\n } catch {\n devDebug('Workbench not available, skipping workbench dev server')\n }\n\n if (!workbenchAvailable) {\n return {close: noop, httpHost, workbenchAvailable, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n mode,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n mode: 'development' | 'preview'\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, mode, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n // `preview` loads `.env.development` (the env hook treats only `build`/`deploy`\n // as production), which points the workbench UI at a local dev server that\n // isn't running here. Ignore the override and load the deployed UI instead.\n const remoteUrl =\n mode === 'preview'\n ? undefined\n : parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Exclude sanity/workbench (and its transitive dep @sanity/workbench)\n // from dep pre-bundling so that `import.meta.hot` is available at\n // runtime — pre-bundled modules do not receive Vite's HMR client\n // injection, which causes the custom HMR events for local application\n // discovery to silently not fire.\n exclude: ['sanity', '@sanity/workbench'],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {dedupe: ['react', 'react-dom']},\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `unstable_defineApp`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to unstable_defineApp() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["resolveLocalPackage","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","readWorkbenchLock","watchRegistry","writeWorkbenchRuntime","devDebug","noop","isLocalApp","server","toApplicationsPayload","servers","applications","filter","map","host","id","interfaces","manifest","port","projectId","type","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","mode","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","undefined","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","organizationId","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","url","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader","name"],"mappings":"AAAA,SAAqCA,mBAAmB,EAAEC,QAAQ,QAAO,mBAAkB;AAC3F,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQC,YAAY,QAA2D,OAAM;AACrF,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,cAAc,QAAO,qBAAoB;AACjD,SAAQC,oBAAoB,QAAO,oBAAmB;AACtD,SACEC,oBAAoB,EAEpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,iBAAiB,EACjBC,aAAa,QACR,gBAAe;AACtB,SAAQC,qBAAqB,QAAO,6BAA4B;AAEhE,MAAMC,WAAWb,SAAS;AAE1B,MAAMc,OAAO,WAAa;AAE1B,kEAAkE;AAClE,qFAAqF;AACrF,MAAMC,aAAa,CAACC,SAAuC,CAACP,mBAAmBO;AAE/E,MAAMC,wBAAwB,CAACC,UAAkC,CAAA;QAC/DC,cAAcD,QACXE,MAAM,CAAC,CAACJ,SAAWD,WAAWC,SAC9BK,GAAG,CAAC,CAAC,EAACC,IAAI,EAAEC,EAAE,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,SAAS,EAAEC,IAAI,EAAC,GAAM,CAAA;gBACjEN;gBACAC;gBACAC;gBACAC;gBACAC;gBACAC;gBACAC;YACF,CAAA;QACFC,SAASX,QAAQY,OAAO,CAAC,CAAC,EAACD,OAAO,EAAEP,IAAI,EAAEI,IAAI,EAAC,GAI7C,AAHA,0EAA0E;YAC1E,6EAA6E;YAC7E,kCAAkC;YACjCG,CAAAA,WAAW,EAAE,AAAD,EAAGR,GAAG,CAAC,CAAC,EAACU,OAAO,EAAER,EAAE,EAAES,UAAU,EAAEC,OAAO,EAAE,GAAGC,QAAO,GAAM,CAAA;oBACtEH;oBACAG;oBACAX;oBACAS;oB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,QAAQ,CAAC,CAAC,EAAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAI,MAAM;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/startWorkbenchDevServer.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\n\nimport {type CliConfig, type Output, subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\nimport viteReact from '@vitejs/plugin-react'\nimport {createServer, type InlineConfig, type Plugin, type ViteDevServer} from 'vite'\nimport {z} from 'zod/mini'\n\nimport {isWorkbenchApp} from '../../defineApp.js'\nimport {createExposesTracker} from './exposesSetId.js'\nimport {\n acquireWorkbenchLock,\n type DevServerManifest,\n getRegisteredServers,\n isConfigOnlyServer,\n readWorkbenchLock,\n watchRegistry,\n} from './registry.js'\nimport {writeWorkbenchRuntime} from './writeWorkbenchRuntime.js'\n\nconst devDebug = subdebug('dev')\nconst renderDashboardEntry = '@sanity/workbench-cli/_internal_render'\nconst renderDashboardPath = fileURLToPath(\n new URL('../../_exports/_internal_render.js', import.meta.url),\n)\n\nconst noop = async () => {}\n\n// Every server is a local app except a config-only one — a config\n// with no interfaces (the media library). A server with both lands in both channels.\nconst isLocalApp = (server: DevServerManifest): boolean => !isConfigOnlyServer(server)\n\nconst toApplicationsPayload = (servers: DevServerManifest[]) => ({\n applications: servers\n .filter((server) => isLocalApp(server))\n .map(({host, id, interfaces, manifest, port, projectId, type}) => ({\n host,\n id,\n interfaces,\n manifest,\n port,\n projectId,\n type,\n })),\n configs: servers.flatMap(({configs, host, port}) =>\n // The registry stores the config flat; the workbench wire shape nests the\n // type-specific payload (`fields` for a media library) under `config`, keyed\n // by the `appType` discriminator.\n (configs ?? []).map(({appType, id, moduleName, version, ...config}) => ({\n appType,\n config,\n id,\n moduleName,\n remoteURL: `http://${host}:${port}`,\n version,\n })),\n ),\n})\n\n/**\n * Bridge the dev-server registry into a workbench Vite server's HMR channel so\n * the page tracks apps as they come and go. A changed interface set means a\n * rebuilt remote — full-reload to drop the stale remote-entry; otherwise\n * rebroadcast for a soft reconcile. Returns a detach fn.\n */\nfunction attachViteDevServerBridge(server: ViteDevServer): () => void {\n server.ws.on('sanity:workbench:get-local-applications', (_, client) => {\n client.send(\n 'sanity:workbench:local-applications',\n toApplicationsPayload(getRegisteredServers()),\n )\n })\n\n const setTracker = createExposesTracker()\n const registryWatcher = watchRegistry((servers) => {\n if (setTracker.hasChanged(servers)) {\n server.ws.send({type: 'full-reload'})\n return\n }\n server.ws.send('sanity:workbench:local-applications', toApplicationsPayload(servers))\n })\n\n return () => registryWatcher.close()\n}\n\n/**\n * Make the workbench remote act as the machine's workbench: claim the singleton\n * lock so app `sanity dev`s register into it instead of each starting their own,\n * and bridge the registry so the remote shows the local apps. No-op lock if one\n * is already held.\n */\nexport function startWorkbenchRemoteCoordinator(options: {\n httpHost: string | undefined\n port: number\n server: ViteDevServer\n}): {close: () => Promise<void>} {\n const {httpHost, port, server} = options\n\n const lock = acquireWorkbenchLock({host: httpHost || 'localhost', port})\n if (!lock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench lock already held by pid %d on port %d; bridging the registry without claiming it',\n existing?.pid,\n existing?.port,\n )\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n close: async () => {\n detachBridge()\n lock?.release()\n },\n }\n}\n\ninterface WorkbenchDevServerResult {\n close: () => Promise<void>\n httpHost: string | undefined\n workbenchAvailable: boolean\n workbenchPort: number\n}\n\nexport interface StartWorkbenchOptions {\n /** Dependency-cache dir for the workbench Vite server, kept apart from the user's own. */\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n httpPort: number\n /** `dev` renders a live app and honors a local workbench-UI override; `preview`\n * (`sanity start`) previews a build and loads the deployed workbench UI. */\n mode: 'development' | 'preview'\n output: Output\n /** Wrap the workbench in React StrictMode; the CLI resolves it (unset collapses to `false`). */\n reactStrictMode: boolean\n workDir: string\n}\n\nexport async function startWorkbenchDevServer(\n options: StartWorkbenchOptions,\n): Promise<WorkbenchDevServerResult> {\n const {\n cacheDir,\n cliConfig,\n httpHost,\n httpPort: workbenchPort,\n mode,\n output,\n reactStrictMode,\n workDir,\n } = options\n\n // Workbench is opted into solely by calling `unstable_defineApp`.\n if (!isWorkbenchApp(cliConfig?.app)) {\n devDebug('Not a workbench app, skipping workbench dev server')\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n // Acquire an exclusive lock — only one workbench per machine.\n // Uses O_EXCL which is atomic at the OS level, preventing races when\n // multiple `sanity dev` processes start simultaneously (e.g. via turbo).\n const workbenchLock = acquireWorkbenchLock({host: httpHost || 'localhost', port: workbenchPort})\n if (!workbenchLock) {\n const existing = readWorkbenchLock()\n devDebug(\n 'Workbench already running at pid %d on port %d, skipping',\n existing?.pid,\n existing?.port,\n )\n return {\n close: noop,\n httpHost: existing?.host ?? httpHost,\n workbenchAvailable: true,\n workbenchPort: existing?.port ?? workbenchPort,\n }\n }\n\n // The lock is already held; an exception here (runtime-file write failure,\n // invalid remote URL) would otherwise leak it until the next acquire prunes\n // the stale PID.\n let result: Awaited<ReturnType<typeof createWorkbenchViteServer>>\n try {\n result = await createWorkbenchViteServer({\n cacheDir,\n cliConfig,\n httpHost,\n mode,\n output,\n reactStrictMode,\n workbenchPort,\n workDir,\n })\n } catch (err) {\n workbenchLock.release()\n throw err\n }\n\n if (!result) {\n workbenchLock.release()\n return {close: noop, httpHost, workbenchAvailable: false, workbenchPort}\n }\n\n const {actualPort, close} = result\n workbenchLock.updatePort(actualPort)\n\n return {\n close: async () => {\n workbenchLock.release()\n await close()\n },\n httpHost,\n workbenchAvailable: true,\n workbenchPort: actualPort,\n }\n}\n\ninterface CreateWorkbenchViteServerOptions {\n cacheDir: string\n cliConfig: CliConfig\n httpHost: string | undefined\n mode: 'development' | 'preview'\n output: Output\n reactStrictMode: boolean\n workbenchPort: number\n workDir: string\n}\n\ninterface CreateWorkbenchViteServerResult {\n actualPort: number\n close: () => Promise<void>\n}\n\nasync function createWorkbenchViteServer(\n options: CreateWorkbenchViteServerOptions,\n): Promise<CreateWorkbenchViteServerResult | undefined> {\n const {cacheDir, cliConfig, httpHost, mode, output, reactStrictMode, workbenchPort, workDir} =\n options\n\n // `preview` loads `.env.development` (the env hook treats only `build`/`deploy`\n // as production), which points the workbench UI at a local dev server that\n // isn't running here. Ignore the override and load the deployed UI instead.\n const remoteUrl =\n mode === 'preview'\n ? undefined\n : parseRemoteUrl(process.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL)\n\n const organizationId = resolveOrganizationId(cliConfig)\n\n devDebug('Writing workbench runtime files')\n const root = await writeWorkbenchRuntime({\n cwd: workDir,\n organizationId,\n reactStrictMode,\n remoteUrl,\n })\n\n const viteConfig: InlineConfig = {\n // Custom cache directory so sanity's vite cache doesn't conflict with local vite projects\n cacheDir,\n configFile: false,\n define: {\n __SANITY_STAGING__: isStaging(),\n 'import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL': JSON.stringify(remoteUrl),\n },\n logLevel: 'warn',\n mode: 'development',\n optimizeDeps: {\n // Keep this entry out of pre-bundling so Vite injects its HMR context.\n exclude: [renderDashboardEntry],\n },\n // viteReact looks inert here — it transforms none of the host's own modules —\n // but it's load-bearing for the remotes. It serves the Fast Refresh runtime at\n // /@react-refresh and injects the preamble that defines window.$RefreshReg$. The\n // federated remotes loaded into this page are react-refresh transformed, so\n // without the preamble they throw \"can't detect preamble\", and without the\n // runtime their /@react-refresh import (wired by @module-federation/vite's\n // remoteHmr) fails. Dropping it as dead code broke every panel; see #1262.\n plugins: [viteReact(), ...(remoteUrl ? [remoteManifestPreloadHeaderPlugin(remoteUrl)] : [])],\n resolve: {\n // The generated Vite root cannot reliably resolve this package.\n alias: {[renderDashboardEntry]: renderDashboardPath},\n dedupe: ['react', 'react-dom'],\n },\n root,\n server: {\n host: httpHost,\n port: workbenchPort,\n strictPort: false,\n warmup: {\n clientFiles: ['./workbench.js'],\n },\n },\n }\n\n devDebug('Creating workbench vite server')\n const server = await createServer(viteConfig)\n try {\n await server.listen()\n } catch (err) {\n await server.close()\n output.warn(\n `Workbench dev server failed to start: ${err instanceof Error ? err.message : String(err)}`,\n )\n return undefined\n }\n\n // Vite may have picked a different port if the desired one was occupied\n const addr = server.httpServer?.address()\n const actualPort = typeof addr === 'object' && addr ? addr.port : workbenchPort\n\n // Fire-and-forget: warm the workbench remote's Vite transform pipeline so\n // the first browser request hits a pre-populated module graph.\n if (remoteUrl) {\n fetch(remoteUrl)\n .then((r) => r.body?.cancel())\n .catch(() => {})\n devDebug('Warming workbench remote at %s', remoteUrl)\n }\n\n const detachBridge = attachViteDevServerBridge(server)\n\n return {\n actualPort,\n close: async () => {\n detachBridge()\n await server.close()\n },\n }\n}\n\n// Workbench is opted into via `unstable_defineApp`, which carries the\n// organization ID. Deliberately no fallback (e.g. resolving it from the\n// configured project): the lookup would need an authenticated user and an\n// API round-trip on every startup for something the opt-in already declares.\nconst resolveOrganizationId = (cliConfig: CliConfig): string => {\n if (cliConfig.app?.organizationId) {\n return cliConfig.app.organizationId\n }\n\n throw new Error(\n 'Workbench requires an organization ID. Pass \"organizationId\" to unstable_defineApp() in sanity.cli.ts.',\n )\n}\n\n// Restricts protocol to http(s) so the URL is safe to interpolate into HTML\n// attributes and Link headers downstream.\nconst remoteUrlSchema = z.url({normalize: true, protocol: /^https?$/})\n\nfunction parseRemoteUrl(value: string | undefined): string | undefined {\n if (!value) return undefined\n\n const result = remoteUrlSchema.safeParse(value)\n\n if (!result.success) {\n throw new Error(\n `Invalid SANITY_INTERNAL_WORKBENCH_REMOTE_URL: ${value} (must be an http(s) URL)`,\n )\n }\n\n return result.data\n}\n\n/**\n * Sets a `Link: <remoteUrl>; rel=preload; as=fetch; crossorigin` response header\n * on the index document so the browser can start fetching the Module Federation\n * manifest as soon as response headers arrive — before HTML parsing reaches the\n * in-head preconnect hint. `as=fetch` matches how the federation runtime later\n * retrieves the JSON manifest, allowing the preload entry to satisfy that fetch.\n */\nfunction remoteManifestPreloadHeaderPlugin(remoteUrl: string): Plugin {\n return {\n apply: 'serve',\n configureServer(server) {\n server.middlewares.use((req, res, next) => {\n const pathname = (req.url || '/').split('?')[0]\n if (pathname === '/' || pathname === '/index.html') {\n res.setHeader('Link', `<${remoteUrl}>; rel=preload; as=fetch; crossorigin`)\n }\n next()\n })\n },\n name: 'sanity:workbench-remote-preload-header',\n }\n}\n"],"names":["fileURLToPath","subdebug","isStaging","viteReact","createServer","z","isWorkbenchApp","createExposesTracker","acquireWorkbenchLock","getRegisteredServers","isConfigOnlyServer","readWorkbenchLock","watchRegistry","writeWorkbenchRuntime","devDebug","renderDashboardEntry","renderDashboardPath","URL","url","noop","isLocalApp","server","toApplicationsPayload","servers","applications","filter","map","host","id","interfaces","manifest","port","projectId","type","configs","flatMap","appType","moduleName","version","config","remoteURL","attachViteDevServerBridge","ws","on","_","client","send","setTracker","registryWatcher","hasChanged","close","startWorkbenchRemoteCoordinator","options","httpHost","lock","existing","pid","detachBridge","release","startWorkbenchDevServer","cacheDir","cliConfig","httpPort","workbenchPort","mode","output","reactStrictMode","workDir","app","workbenchAvailable","workbenchLock","result","createWorkbenchViteServer","err","actualPort","updatePort","remoteUrl","undefined","parseRemoteUrl","process","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","organizationId","resolveOrganizationId","root","cwd","viteConfig","configFile","define","__SANITY_STAGING__","JSON","stringify","logLevel","optimizeDeps","exclude","plugins","remoteManifestPreloadHeaderPlugin","resolve","alias","dedupe","strictPort","warmup","clientFiles","listen","warn","Error","message","String","addr","httpServer","address","fetch","then","r","body","cancel","catch","remoteUrlSchema","normalize","protocol","value","safeParse","success","data","apply","configureServer","middlewares","use","req","res","next","pathname","split","setHeader","name"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AAEtC,SAAqCC,QAAQ,QAAO,mBAAkB;AACtE,SAAQC,SAAS,QAAO,wBAAuB;AAC/C,OAAOC,eAAe,uBAAsB;AAC5C,SAAQ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ACxE,0EAA0E;AAC1E,6EAA6E;AAC7E,MAAMiC,wBAAwB,CAACtB;IAC7B,IAAIA,UAAUO,GAAG,EAAEc,gBAAgB;QACjC,OAAOrB,UAAUO,GAAG,CAACc,cAAc;IACrC;IAEA,MAAM,IAAIuB,MACR;AAEJ;AAEA,4EAA4E;AAC5E,0CAA0C;AAC1C,MAAMY,kBAAkBhH,EAAEa,GAAG,CAAC;IAACoG,WAAW;IAAMC,UAAU;AAAU;AAEpE,SAASzC,eAAe0C,KAAyB;IAC/C,IAAI,CAACA,OAAO,OAAO3C;IAEnB,MAAMN,SAAS8C,gBAAgBI,SAAS,CAACD;IAEzC,IAAI,CAACjD,OAAOmD,OAAO,EAAE;QACnB,MAAM,IAAIjB,MACR,CAAC,8CAA8C,EAAEe,MAAM,yBAAyB,CAAC;IAErF;IAEA,OAAOjD,OAAOoD,IAAI;AACpB;AAEA;;;;;;CAMC,GACD,SAAS3B,kCAAkCpB,SAAiB;IAC1D,OAAO;QACLgD,OAAO;QACPC,iBAAgBxG,MAAM;YACpBA,OAAOyG,WAAW,CAACC,GAAG,CAAC,CAACC,KAAKC,KAAKC;gBAChC,MAAMC,WAAW,AAACH,CAAAA,IAAI9G,GAAG,IAAI,GAAE,EAAGkH,KAAK,CAAC,IAAI,CAAC,EAAE;gBAC/C,IAAID,aAAa,OAAOA,aAAa,eAAe;oBAClDF,IAAII,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAEzD,UAAU,qCAAqC,CAAC;gBAC5E;gBACAsD;YACF;QACF;QACAI,MAAM;IACR;AACF"}
|
|
@@ -6,9 +6,9 @@ const devDebug = subdebug('dev');
|
|
|
6
6
|
const workbenchJsTemplate = `\
|
|
7
7
|
// This file is auto-generated on 'sanity dev'
|
|
8
8
|
// Modifications to this file are automatically discarded
|
|
9
|
-
import {
|
|
9
|
+
import {renderDashboard} from "@sanity/workbench-cli/_internal_render"
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
renderDashboard(
|
|
12
12
|
document.getElementById("workbench"),
|
|
13
13
|
{organizationId: %SANITY_WORKBENCH_ORGANIZATION_ID%},
|
|
14
14
|
{reactStrictMode: %SANITY_WORKBENCH_REACT_STRICT_MODE%}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/dev/writeWorkbenchRuntime.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\n\nconst devDebug = subdebug('dev')\n\nconst workbenchJsTemplate = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/dev/writeWorkbenchRuntime.ts"],"sourcesContent":["import fs from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {subdebug} from '@sanity/cli-core'\nimport {isStaging} from '@sanity/cli-core/util'\n\nconst devDebug = subdebug('dev')\n\nconst workbenchJsTemplate = `\\\n// This file is auto-generated on 'sanity dev'\n// Modifications to this file are automatically discarded\nimport {renderDashboard} from \"@sanity/workbench-cli/_internal_render\"\n\nrenderDashboard(\n document.getElementById(\"workbench\"),\n {organizationId: %SANITY_WORKBENCH_ORGANIZATION_ID%},\n {reactStrictMode: %SANITY_WORKBENCH_REACT_STRICT_MODE%}\n)\n`\n\nconst indexHtmlTemplate = `\\\n<!DOCTYPE html>\n<!-- This file is auto-generated on 'sanity dev' -->\n<!-- Modifications to this file are automatically discarded -->\n<html>\n <head>\n <meta charset=\"UTF-8\" />\n%SANITY_WORKBENCH_PREFETCH_HINTS%\n </head>\n <body>\n <div id=\"workbench\"></div>\n <script>globalThis.__SANITY_STAGING__ = %SANITY_WORKBENCH_STAGING%</script>\n <script type=\"module\" src=\"./workbench.js\"></script>\n </body>\n</html>\n`\n\n/**\n * Generates the `.sanity/workbench` directory with static entry files for\n * the workbench Vite dev server.\n *\n * @param cwd - Current working directory (Sanity root dir)\n * @returns The absolute path to the written workbench runtime directory\n * @internal\n */\nexport async function writeWorkbenchRuntime(options: {\n cwd: string\n organizationId?: string\n reactStrictMode: boolean\n remoteUrl?: string\n}): Promise<string> {\n const {cwd, organizationId, reactStrictMode, remoteUrl} = options\n const workbenchDir = path.join(cwd, '.sanity', 'workbench')\n\n const workbenchJs = workbenchJsTemplate\n .replace(\n /%SANITY_WORKBENCH_ORGANIZATION_ID%/,\n organizationId === undefined ? 'undefined' : JSON.stringify(organizationId),\n )\n .replace(/%SANITY_WORKBENCH_REACT_STRICT_MODE%/, JSON.stringify(reactStrictMode))\n\n const prefetchHints = buildPrefetchHints(remoteUrl)\n\n // The runtime flag builds get via decorateIndexWithStagingScript — a vite\n // `define` never reaches pre-bundled dependencies like the SDK.\n const indexHtml = indexHtmlTemplate\n .replace(/%SANITY_WORKBENCH_PREFETCH_HINTS%/, prefetchHints)\n .replace(/%SANITY_WORKBENCH_STAGING%/, JSON.stringify(isStaging()))\n\n devDebug('Making workbench runtime directory')\n await fs.mkdir(workbenchDir, {recursive: true})\n\n devDebug('Writing workbench.js to workbench runtime directory')\n await fs.writeFile(path.join(workbenchDir, 'workbench.js'), workbenchJs)\n\n devDebug('Writing index.html to workbench runtime directory')\n await fs.writeFile(path.join(workbenchDir, 'index.html'), indexHtml)\n\n return workbenchDir\n}\n\nfunction buildPrefetchHints(remoteUrl: string | undefined): string {\n if (!remoteUrl) return ''\n\n try {\n const url = new URL(remoteUrl)\n return [\n ` <link rel=\"preconnect\" href=\"${url.origin}\" />`,\n ` <link rel=\"preload\" as=\"fetch\" href=\"${url.toString()}\" crossorigin />`,\n ].join('\\n')\n } catch {\n return ''\n }\n}\n"],"names":["fs","path","subdebug","isStaging","devDebug","workbenchJsTemplate","indexHtmlTemplate","writeWorkbenchRuntime","options","cwd","organizationId","reactStrictMode","remoteUrl","workbenchDir","join","workbenchJs","replace","undefined","JSON","stringify","prefetchHints","buildPrefetchHints","indexHtml","mkdir","recursive","writeFile","url","URL","origin","toString"],"mappings":"AAAA,OAA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CAAC;SAC7E,CAACf,IAAI,CAAC;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
package/dist/defineApp.js
CHANGED
|
@@ -74,10 +74,7 @@ z.refine((input)=>!(input.config && !input.isSingleton), {
|
|
|
74
74
|
path: [
|
|
75
75
|
'config'
|
|
76
76
|
]
|
|
77
|
-
}))
|
|
78
|
-
// navigable kinds. An `asset_source` view is a separate kind — a picker
|
|
79
|
-
// brokered to other apps — so it may sit alongside either.
|
|
80
|
-
z.refine((input)=>!(input.entry !== undefined && (input.views?.some((view)=>view.type === 'panel') ?? false)), 'An app cannot expose both an app view (`entry`) and panel views. Declare one or the other.')).check(z.refine((input)=>(input.views?.filter((view)=>view.type === 'panel').length ?? 0) <= 1, 'An app can expose at most one panel view.'));
|
|
77
|
+
}));
|
|
81
78
|
/**
|
|
82
79
|
* Nominal brand the CLI discriminates on to enable the workbench build/deploy
|
|
83
80
|
* codepath. Registered via `Symbol.for` so the marker survives module-realm
|
package/dist/defineApp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {ConfigSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard', 'media-library'])\n\n/** Dock groups an app can place itself into. */\nconst DockGroupSchema = z.enum(['dock.system', 'dock.applications', 'dock.user'])\n\n/**\n * Dock group identifier. The API does not block a user app from declaring a\n * reserved group (e.g. `dock.system`); priority conventions keep Sanity-owned\n * apps ahead.\n * @public\n */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/**\n * Runtime-validation schema for `unstable_defineApp`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /**\n * Deployed as a versioned snapshot on the app's org installation, not the\n * application service. Singletons only. Internal, so excluded from the public\n * `DefineAppInput` and set via `@ts-expect-error` like `applicationType`.\n * @internal\n */\n config: z.optional(ConfigSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /** Dock group to render in. Defaults to `dock.applications` when omitted. */\n group: z.optional(DockGroupSchema),\n /** Optional icon override (path to an SVG). Wins over manifest/studio icon. */\n icon: z.optional(z.string()),\n /**\n * Sanity-owned app deployed once, installed per org; excluded from the public `DefineAppInput`.\n * @internal\n */\n isSingleton: z.optional(z.boolean()),\n /** Organization that owns the app — the workbench runs and deploys against it. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `unstable_defineApp`\",\n ),\n /** Sort position within the group, ascending. Defaults to `100` when omitted. */\n priority: z.optional(z.number()),\n /** Background services the app runs (e.g. a `worker` emitting dock badges). */\n services: z.optional(\n z\n .array(ServiceDeclarationSchema, 'must be an array of services')\n .check(\n z.refine(\n (services) => new Set(services.map((service) => service.name)).size === services.length,\n 'Service `name` must be unique within an app',\n ),\n ),\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. dock panels). */\n views: z.optional(\n z\n .array(InterfaceDeclarationSchema, 'must be an array of panels')\n .check(\n z.refine(\n (views) => new Set(views.map((view) => view.name)).size === views.length,\n 'View `name` must be unique within an app',\n ),\n ),\n ),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n })\n .check(\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n .check(\n // An config belongs to a Sanity-owned singleton (the Media\n // Library). A non-singleton declaring one is rejected — see\n // {@link readConfig} for the runtime guard.\n z.refine((input) => !(input.config && !input.isSingleton), {\n error: '`config` is only supported for singleton apps',\n path: ['config'],\n }),\n )\n .check(\n // A navigable app view (`entry`) and dock panels are the mutually-exclusive\n // navigable kinds. An `asset_source` view is a separate kind — a picker\n // brokered to other apps — so it may sit alongside either.\n z.refine(\n (input) =>\n !(\n input.entry !== undefined &&\n (input.views?.some((view) => view.type === 'panel') ?? false)\n ),\n 'An app cannot expose both an app view (`entry`) and panel views. Declare one or the other.',\n ),\n )\n .check(\n z.refine(\n (input) => (input.views?.filter((view) => view.type === 'panel').length ?? 0) <= 1,\n 'An app can expose at most one panel view.',\n ),\n )\n\n/** The `asset_source` variant of an app's `views`. @public */\nexport type AssetSourceView = Extract<\n NonNullable<z.output<typeof DefineAppInputSchema>['views']>[number],\n {type: 'asset_source'}\n>\n\n/** The `tile` variant of an app's `views`. @public */\nexport type TileView = Extract<\n NonNullable<z.output<typeof DefineAppInputSchema>['views']>[number],\n {type: 'tile'}\n>\n\n/**\n * User-facing input for `unstable_defineApp`. Excludes the internal\n * `applicationType`, `isSingleton`, and `config` — validated by the schema but\n * not part of the public surface (Sanity-owned apps set them via\n * `@ts-expect-error`). A union: an app declares an app `entry` (navigable) or\n * panel `views`, never both — but `asset_source` and `tile` views are separate\n * kinds and may accompany either.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'config' | 'entry' | 'isSingleton' | 'views'\n> &\n (\n | {entry?: never; views?: NonNullable<z.output<typeof DefineAppInputSchema>['views']>}\n | {entry?: string; views?: (AssetSourceView | TileView)[]}\n )\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `unstable_defineApp`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `unstable_defineApp(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * The app's config, or `undefined` when it declares none. Throws\n * when a non-singleton declares one — configs belong to Sanity-owned singletons,\n * so build/dev/deploy all read it through here to reject the combination\n * consistently.\n * @internal\n */\nexport function readConfig(app: WorkbenchApp): WorkbenchApp['config'] | undefined {\n if (app.config && !app.isSingleton) {\n throw new Error('`config` is only supported for singleton apps')\n }\n return app.config\n}\n\n/**\n * Declare a Sanity Workbench application. Identity at runtime — returns the same\n * object reference, tagged with the workbench brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function unstable_defineApp(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Declare the Sanity Media Library as a workbench app — a singleton whose `fields` become its config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): DefineAppResult {\n return unstable_defineApp({\n // @ts-expect-error -- `applicationType`/`isSingleton`/`config` are internal, excluded from `DefineAppInput`; Sanity-owned apps set them\n applicationType: 'media-library',\n config: input.fields?.length ? {appType: 'media-library', fields: input.fields} : undefined,\n isSingleton: true,\n organizationId: input.organizationId,\n slug: 'media-library',\n title: 'Media Library',\n })\n}\n"],"names":["z","APP_SLUG_PATTERN","ConfigSchema","InterfaceDeclarationSchema","ServiceDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DockGroupSchema","DefineAppInputSchema","object","applicationType","optional","config","entry","string","group","icon","isSingleton","boolean","organizationId","priority","number","services","array","check","refine","Set","map","service","name","size","length","slug","regex","title","views","view","visibility","input","undefined","error","path","some","type","filter","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","readConfig","Error","unstable_defineApp","Object","defineProperty","configurable","enumerable","value","writable","unstable_defineMediaLibrary","fields","appType"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,YAAY,EAAEC,0BAA0B,EAAEC,wBAA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BI;AACrE;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,WAAWD,GAAiB;IAC1C,IAAIA,IAAIrC,MAAM,IAAI,CAACqC,IAAIhC,WAAW,EAAE;QAClC,MAAM,IAAIkC,MAAM;IAClB;IACA,OAAOF,IAAIrC,MAAM;AACnB;AAEA;;;;;;CAMC,GACD,OAAO,SAASwC,mBAAmBd,KAAqB;IACtD,OAAOe,OAAOC,cAAc,CAAChB,OAAOO,eAAe;QACjDU,cAAc;QACdC,YAAY;QACZC,OAAO;QACPC,UAAU;IACZ;AACF;AA2BA;;;CAGC,GACD,OAAO,SAASC,4BAA4BrB,KAA8B;IACxE,OAAOc,mBAAmB;QACxB,wIAAwI;QACxI1C,iBAAiB;QACjBE,QAAQ0B,MAAMsB,MAAM,EAAE7B,SAAS;YAAC8B,SAAS;YAAiBD,QAAQtB,MAAMsB,MAAM;QAAA,IAAIrB;QAClFtB,aAAa;QACbE,gBAAgBmB,MAAMnB,cAAc;QACpCa,MAAM;QACNE,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../src/defineApp.ts"],"sourcesContent":["import {z} from 'zod/mini'\n\nimport {APP_SLUG_PATTERN} from './appSlug.js'\nimport {ConfigSchema, InterfaceDeclarationSchema, ServiceDeclarationSchema} from './contract.js'\n\n/**\n * Dashboard visibility values. Mirrors `APP_VISIBILITIES` in `@sanity/cli-core`\n * (which can't be imported here — pulling the barrel into this lean module bloats\n * the config-load path). Kept in sync by a type test in `defineApp.test.ts`.\n */\nconst APP_VISIBILITIES = ['default', 'unlisted', 'disabled'] as const\n\n/**\n * Internal application discriminator. Sanity-owned singleton apps only;\n * validated by the schema but excluded from the public `DefineAppInput` type.\n */\nconst ApplicationType = z.enum(['coreApp', 'studio', 'canvas', 'dashboard', 'media-library'])\n\n/** Dock groups an app can place itself into. */\nconst DockGroupSchema = z.enum(['dock.system', 'dock.applications', 'dock.user'])\n\n/**\n * Dock group identifier. The API does not block a user app from declaring a\n * reserved group (e.g. `dock.system`); priority conventions keep Sanity-owned\n * apps ahead.\n * @public\n */\nexport type DockGroup = z.output<typeof DockGroupSchema>\n\n/**\n * Runtime-validation schema for `unstable_defineApp`.\n * @internal\n */\nexport const DefineAppInputSchema = z\n .object({\n /**\n * Internal — Sanity-owned singleton apps only. Validated here but excluded\n * from the public `DefineAppInput` type.\n * @internal\n */\n applicationType: z.optional(ApplicationType),\n /**\n * Deployed as a versioned snapshot on the app's org installation, not the\n * application service. Singletons only. Internal, so excluded from the public\n * `DefineAppInput` and set via `@ts-expect-error` like `applicationType`.\n * @internal\n */\n config: z.optional(ConfigSchema),\n /**\n * App entrypoint module. Defaults to `./src/App.tsx` when omitted. The build\n * derives the app's navigable `app` view from it. SDK apps only — setting it\n * on a studio is rejected (studio app views are not yet implemented).\n */\n entry: z.optional(z.string(\"must be a path to the app's entry file\")),\n /** Dock group to render in. Defaults to `dock.applications` when omitted. */\n group: z.optional(DockGroupSchema),\n /** Optional icon override (path to an SVG). Wins over manifest/studio icon. */\n icon: z.optional(z.string()),\n /**\n * Sanity-owned app deployed once, installed per org; excluded from the public `DefineAppInput`.\n * @internal\n */\n isSingleton: z.optional(z.boolean()),\n /** Organization that owns the app — the workbench runs and deploys against it. */\n organizationId: z.string(\n \"App `organizationId` is required — pass the owning organization's ID to `unstable_defineApp`\",\n ),\n /** Sort position within the group, ascending. Defaults to `100` when omitted. */\n priority: z.optional(z.number()),\n /** Background services the app runs (e.g. a `worker` emitting dock badges). */\n services: z.optional(\n z\n .array(ServiceDeclarationSchema, 'must be an array of services')\n .check(\n z.refine(\n (services) => new Set(services.map((service) => service.name)).size === services.length,\n 'Service `name` must be unique within an app',\n ),\n ),\n ),\n slug: z\n .string('App `slug` is required — the hostname the application is created at on deploy')\n .check(\n z.regex(\n APP_SLUG_PATTERN,\n 'App `slug` must be lowercase alphanumerics and hyphens, starting with a letter and ending with an alphanumeric',\n ),\n ),\n /** User-facing app title. Wins over studio.config.ts title on merge. */\n title: z.string(),\n /** Views the app exposes (e.g. dock panels). */\n views: z.optional(\n z\n .array(InterfaceDeclarationSchema, 'must be an array of panels')\n .check(\n z.refine(\n (views) => new Set(views.map((view) => view.name)).size === views.length,\n 'View `name` must be unique within an app',\n ),\n ),\n ),\n /** Dashboard visibility of the app. Defaults to `default` when omitted. */\n visibility: z.optional(z.enum(APP_VISIBILITIES)),\n })\n .check(\n // Studio app views are not implemented yet. A studio that declares `entry`\n // (the SDK app-view entrypoint) is rejected here rather than silently\n // generating one; studios keep navigating via their existing render path.\n z.refine((input) => !(input.applicationType === 'studio' && input.entry !== undefined), {\n error: 'App views for studios are not implemented yet',\n path: ['entry'],\n }),\n )\n .check(\n // An config belongs to a Sanity-owned singleton (the Media\n // Library). A non-singleton declaring one is rejected — see\n // {@link readConfig} for the runtime guard.\n z.refine((input) => !(input.config && !input.isSingleton), {\n error: '`config` is only supported for singleton apps',\n path: ['config'],\n }),\n )\n\n/**\n * User-facing input for `unstable_defineApp`. Excludes the internal\n * `applicationType`, `isSingleton`, and `config`.\n * @public\n */\nexport type DefineAppInput = Omit<\n z.output<typeof DefineAppInputSchema>,\n 'applicationType' | 'config' | 'isSingleton'\n>\n\n/**\n * Nominal brand the CLI discriminates on to enable the workbench build/deploy\n * codepath. Registered via `Symbol.for` so the marker survives module-realm\n * boundaries — `@sanity/cli-core` re-derives the same global symbol with\n * `Symbol.for` rather than importing it, so it stays internal to this module.\n */\nconst WORKBENCH_APP: unique symbol = Symbol.for('sanity.workbench.defineApp')\n\n/**\n * The branded result of `unstable_defineApp`. Carries the same fields as the\n * input plus the internal brand — users only ever see `DefineAppInput`.\n * @public\n */\nexport type DefineAppResult = DefineAppInput & {readonly [WORKBENCH_APP]: true}\n\n/**\n * A branded app as the CLI reads it — the full schema shape, including the\n * internal fields `DefineAppInput` omits. Schema-derived so the narrowing\n * can't drift from what the schema validates.\n * @public\n */\nexport type WorkbenchApp = DefineAppResult & z.output<typeof DefineAppInputSchema>\n\n/**\n * Whether `app` is a branded `unstable_defineApp(...)` result — the sole\n * workbench opt-in.\n * @public\n */\nexport function isWorkbenchApp(app: unknown): app is WorkbenchApp {\n return typeof app === 'object' && app !== null && WORKBENCH_APP in app\n}\n\n/**\n * The app's config, or `undefined` when it declares none. Throws\n * when a non-singleton declares one — configs belong to Sanity-owned singletons,\n * so build/dev/deploy all read it through here to reject the combination\n * consistently.\n * @internal\n */\nexport function readConfig(app: WorkbenchApp): WorkbenchApp['config'] | undefined {\n if (app.config && !app.isSingleton) {\n throw new Error('`config` is only supported for singleton apps')\n }\n return app.config\n}\n\n/**\n * Declare a Sanity Workbench application. Identity at runtime — returns the same\n * object reference, tagged with the workbench brand. Field validation (the\n * `slug` pattern etc.) runs at build time in the CLI via `DefineAppInputSchema`;\n * this helper stays a thin, pure identity wrapper.\n * @public\n */\nexport function unstable_defineApp(input: DefineAppInput): DefineAppResult {\n return Object.defineProperty(input, WORKBENCH_APP, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n }) as DefineAppResult\n}\n\n/**\n * One custom field a media library exposes. `src` default-exports a `defineField(...)` schema type.\n * @public\n */\nexport interface MediaLibraryField {\n /** Unique within the media library. */\n name: string\n src: string\n title: string\n\n /** Readable outside the owning organization. */\n public?: boolean\n}\n\n/**\n * Sanity-owned singleton, so authors don't name or title the app — only `organizationId` is required.\n * @public\n */\nexport interface DefineMediaLibraryInput {\n /** Organization that owns the media library — the CLI runs and deploys against it. */\n organizationId: string\n\n fields?: MediaLibraryField[]\n}\n\n/**\n * Declare the Sanity Media Library as a workbench app — a singleton whose `fields` become its config.\n * @public\n */\nexport function unstable_defineMediaLibrary(input: DefineMediaLibraryInput): DefineAppResult {\n return unstable_defineApp({\n // @ts-expect-error -- `applicationType`/`isSingleton`/`config` are internal, excluded from `DefineAppInput`; Sanity-owned apps set them\n applicationType: 'media-library',\n config: input.fields?.length ? {appType: 'media-library', fields: input.fields} : undefined,\n isSingleton: true,\n organizationId: input.organizationId,\n slug: 'media-library',\n title: 'Media Library',\n })\n}\n"],"names":["z","APP_SLUG_PATTERN","ConfigSchema","InterfaceDeclarationSchema","ServiceDeclarationSchema","APP_VISIBILITIES","ApplicationType","enum","DockGroupSchema","DefineAppInputSchema","object","applicationType","optional","config","entry","string","group","icon","isSingleton","boolean","organizationId","priority","number","services","array","check","refine","Set","map","service","name","size","length","slug","regex","title","views","view","visibility","input","undefined","error","path","WORKBENCH_APP","Symbol","for","isWorkbenchApp","app","readConfig","Error","unstable_defineApp","Object","defineProperty","configurable","enumerable","value","writable","unstable_defineMediaLibrary","fields","appType"],"mappings":"AAAA,SAAQA,CAAC,QAAO,WAAU;AAE1B,SAAQC,gBAAgB,QAAO,eAAc;AAC7C,SAAQC,YAAY,EAAEC,0BAA0B,EAAEC,wBAAwB,QAAO,gBAAe;AAEhG;;;;CAIC,GACD,MAAMC,mBAAmB;IAAC;IAAW;IAAY;CAAW;AAE5D;;;CAGC,GACD,MAAMC,kBAAkBN,EAAEO,IAAI,CAAC;IAAC;IAAW;IAAU;IAAU;IAAa;CAAgB;AAE5F,8CAA8C,GAC9C,MAAMC,kBAAkBR,EAAEO,IAAI,CAAC;IAAC;IAAe;IAAqB;CAAY;AAUhF;;;CAGC,GACD,OAAO,MAAME,uBAAuBT,EACjCU,MAAM,CAAC;IACN;;;;KAIC,GACDC,iBAAiBX,EAAEY,QAAQ,CAACN;IAC5B;;;;;KAKC,GACDO,QAAQb,EAAEY,QAAQ,CAACV;IACnB;;;;KAIC,GACDY,OAAOd,EAAEY,QAAQ,CAACZ,EAAEe,MAAM,CAAC;IAC3B,2EAA2E,GAC3EC,OAAOhB,EAAEY,QAAQ,CAACJ;IAClB,6EAA6E,GAC7ES,MAAMjB,EAAEY,QAAQ,CAACZ,EAAEe,MAAM;IACzB;;;KAGC,GACDG,aAAalB,EAAEY,QAAQ,CAACZ,EAAEmB,OAAO;IACjC,gFAAgF,GAChFC,gBAAgBpB,EAAEe,MAAM,CACtB;IAEF,+EAA+E,GAC/EM,UAAUrB,EAAEY,QAAQ,CAACZ,E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,GAAY;IACzC,OAAO,OAAOA,QAAQ,YAAYA,QAAQ,QAAQJ,iBAAiBI;AACrE;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,WAAWD,GAAiB;IAC1C,IAAIA,IAAIlC,MAAM,IAAI,CAACkC,IAAI7B,WAAW,EAAE;QAClC,MAAM,IAAI+B,MAAM;IAClB;IACA,OAAOF,IAAIlC,MAAM;AACnB;AAEA;;;;;;CAMC,GACD,OAAO,SAASqC,mBAAmBX,KAAqB;IACtD,OAAOY,OAAOC,cAAc,CAACb,OAAOI,eAAe;QACjDU,cAAc;QACdC,YAAY;QACZC,OAAO;QACPC,UAAU;IACZ;AACF;AA2BA;;;CAGC,GACD,OAAO,SAASC,4BAA4BlB,KAA8B;IACxE,OAAOW,mBAAmB;QACxB,wIAAwI;QACxIvC,iBAAiB;QACjBE,QAAQ0B,MAAMmB,MAAM,EAAE1B,SAAS;YAAC2B,SAAS;YAAiBD,QAAQnB,MAAMmB,MAAM;QAAA,IAAIlB;QAClFtB,aAAa;QACbE,gBAAgBmB,MAAMnB,cAAc;QACpCa,MAAM;QACNE,OAAO;IACT;AACF"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/// <reference types="vite/client" />
|
|
2
|
+
// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.
|
|
3
|
+
import { createInstance } from '@module-federation/runtime';
|
|
4
|
+
import { BehaviorSubject } from 'rxjs';
|
|
5
|
+
const remoteName = 'workbench-remote';
|
|
6
|
+
const remoteModuleId = `${remoteName}/App`;
|
|
7
|
+
const localApplicationsEvent = 'sanity:workbench:local-applications';
|
|
8
|
+
const noop = ()=>{};
|
|
9
|
+
export async function renderDashboard(rootElement, config, options) {
|
|
10
|
+
if (!rootElement) {
|
|
11
|
+
throw new Error('Missing root element to mount application into');
|
|
12
|
+
}
|
|
13
|
+
const deployedDashboardHost = globalThis.__SANITY_STAGING__ === true ? 'workbench-apps-of5p8qpku.run.sanity.work' : 'workbench-apps-osyh1iet5.sanity.run';
|
|
14
|
+
const remoteUrl = import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ?? `https://${deployedDashboardHost}/mf-manifest.json`;
|
|
15
|
+
const federation = createInstance({
|
|
16
|
+
name: 'sanity-workbench',
|
|
17
|
+
remotes: [
|
|
18
|
+
{
|
|
19
|
+
entry: remoteUrl,
|
|
20
|
+
name: remoteName
|
|
21
|
+
}
|
|
22
|
+
]
|
|
23
|
+
});
|
|
24
|
+
let remoteModule;
|
|
25
|
+
try {
|
|
26
|
+
remoteModule = await federation.loadRemote(remoteModuleId);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
throw new Error(`Failed to load remote module "${remoteModuleId}"`, {
|
|
29
|
+
cause: error
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
if (!remoteModule || typeof remoteModule.render !== 'function') {
|
|
33
|
+
throw new Error(`Remote module "${remoteModuleId}" did not expose a render function`);
|
|
34
|
+
}
|
|
35
|
+
let appConfigs;
|
|
36
|
+
let cleanupHmr = noop;
|
|
37
|
+
let localApplications;
|
|
38
|
+
if (import.meta.hot) {
|
|
39
|
+
const hot = import.meta.hot;
|
|
40
|
+
const hmrLocalApplications = new BehaviorSubject([]);
|
|
41
|
+
const hmrAppConfigs = new BehaviorSubject([]);
|
|
42
|
+
const handler = (payload)=>{
|
|
43
|
+
hmrLocalApplications.next(payload.applications);
|
|
44
|
+
hmrAppConfigs.next(payload.configs ?? []);
|
|
45
|
+
};
|
|
46
|
+
localApplications = hmrLocalApplications;
|
|
47
|
+
appConfigs = hmrAppConfigs;
|
|
48
|
+
hot.on(localApplicationsEvent, handler);
|
|
49
|
+
hot.send('sanity:workbench:get-local-applications');
|
|
50
|
+
cleanupHmr = ()=>hot.off(localApplicationsEvent, handler);
|
|
51
|
+
}
|
|
52
|
+
const unmount = remoteModule.render(rootElement, {
|
|
53
|
+
appConfigs,
|
|
54
|
+
config,
|
|
55
|
+
localApplications
|
|
56
|
+
}, options);
|
|
57
|
+
return ()=>{
|
|
58
|
+
cleanupHmr();
|
|
59
|
+
unmount();
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=renderDashboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/renderDashboard.ts"],"sourcesContent":["/// <reference types=\"vite/client\" />\n\n// Keep this module browser-safe: Vite loads it directly in the generated dashboard runtime.\nimport {createInstance} from '@module-federation/runtime'\nimport {BehaviorSubject, type Observable} from 'rxjs'\n\ndeclare global {\n var __SANITY_STAGING__: boolean | undefined\n}\n\ninterface DashboardConfig {\n organizationId: string\n}\n\ninterface RenderDashboardOptions {\n reactStrictMode?: boolean\n}\n\ninterface DashboardRemoteModule {\n render: (\n rootElement: HTMLElement,\n props: {\n appConfigs?: Observable<unknown[]>\n config: DashboardConfig\n localApplications?: Observable<unknown[]>\n },\n options?: RenderDashboardOptions,\n ) => () => void\n}\n\nconst remoteName = 'workbench-remote'\nconst remoteModuleId = `${remoteName}/App`\nconst localApplicationsEvent = 'sanity:workbench:local-applications'\nconst noop = () => {}\n\nexport async function renderDashboard(\n rootElement: HTMLElement | null,\n config: DashboardConfig,\n options?: RenderDashboardOptions,\n): Promise<() => void> {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n\n const deployedDashboardHost =\n globalThis.__SANITY_STAGING__ === true\n ? 'workbench-apps-of5p8qpku.run.sanity.work'\n : 'workbench-apps-osyh1iet5.sanity.run'\n const remoteUrl =\n import.meta.env.SANITY_INTERNAL_WORKBENCH_REMOTE_URL ??\n `https://${deployedDashboardHost}/mf-manifest.json`\n\n const federation = createInstance({\n name: 'sanity-workbench',\n remotes: [{entry: remoteUrl, name: remoteName}],\n })\n\n let remoteModule: DashboardRemoteModule | null\n try {\n remoteModule = await federation.loadRemote<DashboardRemoteModule>(remoteModuleId)\n } catch (error) {\n throw new Error(`Failed to load remote module \"${remoteModuleId}\"`, {cause: error})\n }\n\n if (!remoteModule || typeof remoteModule.render !== 'function') {\n throw new Error(`Remote module \"${remoteModuleId}\" did not expose a render function`)\n }\n\n let appConfigs: BehaviorSubject<unknown[]> | undefined\n let cleanupHmr = noop\n let localApplications: BehaviorSubject<unknown[]> | undefined\n\n if (import.meta.hot) {\n const hot = import.meta.hot\n const hmrLocalApplications = new BehaviorSubject<unknown[]>([])\n const hmrAppConfigs = new BehaviorSubject<unknown[]>([])\n const handler = (payload: {applications: unknown[]; configs?: unknown[]}) => {\n hmrLocalApplications.next(payload.applications)\n hmrAppConfigs.next(payload.configs ?? [])\n }\n\n localApplications = hmrLocalApplications\n appConfigs = hmrAppConfigs\n hot.on(localApplicationsEvent, handler)\n hot.send('sanity:workbench:get-local-applications')\n cleanupHmr = () => hot.off(localApplicationsEvent, handler)\n }\n\n const unmount = remoteModule.render(rootElement, {appConfigs, config, localApplications}, options)\n\n return () => {\n cleanupHmr()\n unmount()\n }\n}\n"],"names":["createInstance","BehaviorSubject","remoteName","remoteModuleId","localApplicationsEvent","noop","renderDashboard","rootElement","config","options","Error","deployedDashboardHost","globalThis","__SANITY_STAGING__","remoteUrl","env","SANITY_INTERNAL_WORKBENCH_REMOTE_URL","federation","name","remotes","entry","remoteModule","loadRemote","error","cause","render","appConfigs","cleanupHmr","localApplications","hot","hmrLocalApplications","hmrAppConfigs","handler","payload","next","applications","configs","on","send","off","unmount"],"mappings":"AAAA,qCAAqC;AAErC,4FAA4F;AAC5F,SAAQA,cAAc,QAAO,6BAA4B;AACzD,SAAQC,eAAe,QAAwB,OAAM;AA0BrD,MAAMC,aAAa;AACnB,MAAMC,iBAAiB,GAAGD,WAAW,IAAI,CAAC;AAC1C,MAAME,yBAAyB;AAC/B,MAAMC,OAAO,KAAO;AAEpB,OAAO,eAAeC,gBACpBC,WAA+B,EAC/BC,MAAuB,EACvBC,OAAgC;IAEhC,IAAI,CAACF,aAAa;QAChB,MAAM,IAAIG,MAAM;IAClB;IAEA,MAAMC,wBACJC,WAAWC,kBAAkB,KAAK,OAC9B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cli",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Internal implementation detail of the Sanity CLI's unstable workbench support. Not intended for direct use.",
|
|
5
5
|
"homepage": "https://github.com/sanity-io/cli",
|
|
6
6
|
"bugs": "https://github.com/sanity-io/cli/issues",
|
|
@@ -43,6 +43,10 @@
|
|
|
43
43
|
"source": "./src/_exports/preview.ts",
|
|
44
44
|
"default": "./dist/_exports/preview.js"
|
|
45
45
|
},
|
|
46
|
+
"./_internal_render": {
|
|
47
|
+
"source": "./src/_exports/_internal_render.ts",
|
|
48
|
+
"default": "./dist/_exports/_internal_render.js"
|
|
49
|
+
},
|
|
46
50
|
"./undeploy": {
|
|
47
51
|
"source": "./src/_exports/undeploy.ts",
|
|
48
52
|
"default": "./dist/_exports/undeploy.js"
|
|
@@ -53,27 +57,29 @@
|
|
|
53
57
|
"access": "public"
|
|
54
58
|
},
|
|
55
59
|
"dependencies": {
|
|
60
|
+
"@module-federation/runtime": "2.8.2",
|
|
56
61
|
"@module-federation/vite": "1.20.7",
|
|
57
62
|
"@sanity/types": "^6.7.0",
|
|
58
|
-
"@vitejs/plugin-react": "^6.0
|
|
63
|
+
"@vitejs/plugin-react": "^6.1.0",
|
|
59
64
|
"form-data": "^4.0.5",
|
|
65
|
+
"rxjs": "^7.8.2",
|
|
60
66
|
"tar-fs": "^3.1.2",
|
|
61
67
|
"vite": "^8.2.1",
|
|
62
68
|
"zod": "^4.4.3",
|
|
63
|
-
"@sanity/cli-core": "^3.
|
|
69
|
+
"@sanity/cli-core": "^3.3.0"
|
|
64
70
|
},
|
|
65
71
|
"devDependencies": {
|
|
66
72
|
"@eslint/compat": "^2.1.0",
|
|
67
|
-
"@sanity/pkg-utils": "^12.
|
|
73
|
+
"@sanity/pkg-utils": "^12.2.0",
|
|
68
74
|
"@swc/cli": "^0.8.1",
|
|
69
75
|
"@swc/core": "^1.15.43",
|
|
70
76
|
"@types/node": "^22.20.0",
|
|
71
77
|
"@types/tar-fs": "^2.0.4",
|
|
72
|
-
"@vitest/coverage-istanbul": "^4.1.
|
|
78
|
+
"@vitest/coverage-istanbul": "^4.1.11",
|
|
73
79
|
"eslint": "^10.7.0",
|
|
74
80
|
"publint": "^0.3.21",
|
|
75
81
|
"typescript": "^6.0.3",
|
|
76
|
-
"vitest": "^4.1.
|
|
82
|
+
"vitest": "^4.1.11",
|
|
77
83
|
"@repo/package.config": "0.0.1",
|
|
78
84
|
"@repo/tsconfig": "3.70.0",
|
|
79
85
|
"@sanity/eslint-config-cli": "^1.1.3"
|