@sanity/workbench 0.1.0-alpha.1 → 0.1.0-alpha.10

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.
@@ -0,0 +1,504 @@
1
+ import type { SemVer } from "semver";
2
+ import { coerce, gt, gte, lt, rsort, valid } from "semver";
3
+
4
+ import type { Project } from "../../projects";
5
+ import { UserApplication } from "../user-application";
6
+ import {
7
+ type Workspace,
8
+ type StudioUserApplication,
9
+ ClientManifest as ClientManifestSchema,
10
+ } from "./schemas";
11
+ import { StudioWorkspace } from "./workspace";
12
+
13
+ const ClientManifest = ClientManifestSchema.superRefine((data, ctx) => {
14
+ if (!data.version) {
15
+ ctx.addIssue({
16
+ code: "invalid_type",
17
+ message: "Manifest version is too old",
18
+ expected: "number",
19
+ });
20
+ }
21
+
22
+ if (data.version < 2) {
23
+ ctx.addIssue({
24
+ code: "invalid_value",
25
+ message: "Manifest version is too old",
26
+ values: [2, 3],
27
+ });
28
+ }
29
+
30
+ if (data.version >= 3 && !data.studioVersion) {
31
+ ctx.addIssue({
32
+ code: "invalid_type",
33
+ message: "Manifest version 3 or higher requires a `studioVersion`",
34
+ expected: "string",
35
+ });
36
+ }
37
+ });
38
+
39
+ const DEFAULT_WORKSPACE_DATA = {
40
+ name: "default",
41
+ title: "Default",
42
+ basePath: "/",
43
+ } as const satisfies Omit<Workspace, "projectId">;
44
+
45
+ /**
46
+ * @public
47
+ */
48
+ export class StudioApplication extends UserApplication<
49
+ StudioUserApplication,
50
+ "studio",
51
+ never
52
+ > {
53
+ /**
54
+ * Returns a list of studio workspaces based on the application manifest.
55
+ * If there is no manifest, or alternatively it is not valid, then we create a default workspace.
56
+ */
57
+ readonly workspaces: readonly StudioWorkspace[] = [];
58
+
59
+ readonly project: Project<false, false>;
60
+
61
+ /**
62
+ * The projects actually referenced by this studio — the application's own
63
+ * project plus any project used by a workspace. Preserved so the instance
64
+ * can be re-constructed (e.g. by dock wrappers) without having to thread
65
+ * the full organization project list through again.
66
+ */
67
+ readonly projects: Project<false, false>[];
68
+
69
+ /**
70
+ * @param application - The studio application to create a list of workspaces for
71
+ * @param projects - The projects available in the organization. It's not enough to just pass
72
+ * the project that associates with the application because that is the project the app is deployed in relation to.
73
+ * The workspaces may have different projects completely.
74
+ */
75
+ constructor(
76
+ application: StudioUserApplication,
77
+ projects: Project<false, false>[],
78
+ options: {
79
+ isLocal?: boolean;
80
+ remoteApplication?: StudioApplication | null;
81
+ } = {},
82
+ ) {
83
+ super(application, "studio", options);
84
+
85
+ /**
86
+ * If the application has a manifest, then we validate it and create
87
+ * a workspace for each manifest entry. Otherwise, we will create a "default"
88
+ * workspace which is pretty much identical to when a user has a single workspace
89
+ * studio application using the term "default" in places.
90
+ */
91
+ let workspaces: Workspace[] = [];
92
+ if (this.hasManifest) {
93
+ /**
94
+ * If the workspaces fail to parse we dont want to throw an error because
95
+ * this could potentially crash the app. Instead we log a warning and return an empty array.
96
+ */
97
+ try {
98
+ workspaces = ClientManifest.parse(
99
+ application.manifestData?.value,
100
+ ).workspaces;
101
+ } catch (error) {
102
+ console.warn(
103
+ `Failed to parse manifest for application ${application.id}`,
104
+ error,
105
+ );
106
+ }
107
+ }
108
+
109
+ if (workspaces.length === 0) {
110
+ /**
111
+ * If the user application does not have a valid manifest or no workspaces,
112
+ * we attempt to get the manifest from the server-side maninfest first and then
113
+ * fall back to the live-manifest.
114
+ *
115
+ * In the future this should happen even before checking the traditional manifest,
116
+ * but for now we keep the current order to not introduce breaking changes.
117
+ *
118
+ * The live manifest is inherintly less reliable as it depends on which user has
119
+ * uploaded it, which is why this is wrapped in a feature flag for now.
120
+ */
121
+ const deploymentManifest = application.activeDeployment?.manifest;
122
+ // const liveManifest = growthbook.isOn('dashboard-use-live-manifest')
123
+ // ? application.config['live-manifest']?.value
124
+ // : null
125
+
126
+ const serverManifest = deploymentManifest; /*?? liveManifest*/
127
+ const serverManifestWorkspaces = serverManifest?.workspaces;
128
+
129
+ if (
130
+ Array.isArray(serverManifestWorkspaces) &&
131
+ serverManifestWorkspaces.length
132
+ ) {
133
+ workspaces = serverManifestWorkspaces;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Filter all the workspaces that have a project the user does not have access to.
139
+ */
140
+ const workspacesWithProjectsMap = workspaces.reduce((acc, workspace) => {
141
+ const project = projects.find((p) => p.id === workspace.projectId);
142
+
143
+ if (project) {
144
+ acc.set(workspace, project);
145
+ } else {
146
+ console.warn(
147
+ `Project not found for application ${application.id} and workspace ${workspace.name}. This workspace has been omitted.`,
148
+ );
149
+ }
150
+
151
+ return acc;
152
+ }, new Map<Workspace, Project<false, false>>());
153
+
154
+ const project = projects.find((p) => p.id === application.projectId);
155
+
156
+ if (!project) {
157
+ throw new Error(`Project not found for application ${application.id}`);
158
+ }
159
+
160
+ if (workspacesWithProjectsMap.size === 0) {
161
+ /**
162
+ * If there are still no workspaces, we create a default workspace.
163
+ */
164
+ workspacesWithProjectsMap.set(
165
+ {
166
+ ...DEFAULT_WORKSPACE_DATA,
167
+ projectId: application.projectId,
168
+ } satisfies Workspace,
169
+ project,
170
+ );
171
+ }
172
+
173
+ this.workspaces = Object.freeze(
174
+ Array.from(workspacesWithProjectsMap.entries()).map(([workspace, p]) => {
175
+ /**
176
+ * A workspace is considered the default if the dashboard generated it OR because
177
+ * the properties match that of the default workspace generated by the studio.
178
+ * Which is why these values will match because dashboard generates an identical
179
+ * workspace to the default studio one.
180
+ */
181
+ const isDefaultWorkspace =
182
+ workspace.name === DEFAULT_WORKSPACE_DATA.name &&
183
+ workspace.basePath === DEFAULT_WORKSPACE_DATA.basePath &&
184
+ workspace.title === DEFAULT_WORKSPACE_DATA.title;
185
+
186
+ return new StudioWorkspace(this, workspace, p, isDefaultWorkspace);
187
+ }),
188
+ );
189
+
190
+ this.project = project;
191
+
192
+ // Collect only the projects actually referenced by this studio — the
193
+ // application's own project plus any project used by a workspace.
194
+ const usedProjects = new Set<Project<false, false>>([project]);
195
+ for (const workspace of this.workspaces) {
196
+ usedProjects.add(workspace.project);
197
+ }
198
+ this.projects = Array.from(usedProjects);
199
+ }
200
+
201
+ get href() {
202
+ return this.isLocal
203
+ ? `/local/${this.id}`
204
+ : `/studio/${this.application.id}`;
205
+ }
206
+
207
+ get title() {
208
+ // Get the title from the user application, this has the highest precedence
209
+ const title = this.get("title");
210
+ if (title) {
211
+ return title;
212
+ }
213
+
214
+ // If there are multiple workspaces and the studio is internal, use the project display name
215
+ if (this.workspaces.length > 1 && this.get("urlType") === "internal") {
216
+ return this.project.displayName;
217
+ }
218
+
219
+ // Otherwise use the title of the first workspace
220
+ return this.workspaces[0].title;
221
+ }
222
+
223
+ get subtitle() {
224
+ return new URL(this.url).hostname;
225
+ }
226
+
227
+ get<TKey extends keyof StudioUserApplication>(
228
+ attr: TKey,
229
+ ): StudioUserApplication[TKey] {
230
+ if (!(attr in this.application)) {
231
+ throw new Error(
232
+ `Attribute ${attr.toString()} does not exist on studio ${this.application.id}`,
233
+ );
234
+ }
235
+
236
+ return this.application[attr];
237
+ }
238
+
239
+ get hasManifest(): boolean {
240
+ return (
241
+ typeof this.application.manifestData?.value?.version === "number" &&
242
+ this.application.manifestData?.value?.version >= 2
243
+ );
244
+ }
245
+
246
+ get hasSchema(): boolean {
247
+ // In this case we can not look at `this.workspaces` because it won't contain workspaces the user does
248
+ // not have access to. The application has a schema, even if the user can't access any of the workspaces,
249
+ // otherwise it would be displayed as not having a manifest in the setup guide and therefore considered
250
+ // partially compatible.
251
+ const workspaces = this.get("manifestData")?.value?.workspaces ?? [];
252
+
253
+ if (workspaces.length === 0) {
254
+ return false;
255
+ }
256
+
257
+ return workspaces.every((w) => Boolean(w.schema));
258
+ }
259
+
260
+ private resolveVersion() {
261
+ // const growthbook = getGrowthbook()
262
+
263
+ let version: string | undefined;
264
+
265
+ if (this.get("urlType") === "internal") {
266
+ version = this.get("activeDeployment")?.version;
267
+ } else {
268
+ const manifest = this.get("manifestData")?.value;
269
+ // The property 'studioVersion' exists only on external studios,
270
+ // starting from manifest.version 3
271
+ version =
272
+ manifest && "studioVersion" in manifest
273
+ ? manifest.studioVersion
274
+ : undefined;
275
+ }
276
+
277
+ /**
278
+ * Self-hosted studios are often not publicly accessible, which means that
279
+ * Brett often times cannot fetch the manifest to read the version. In this case
280
+ * we try to read the version from the deployment manifest or 'live-manifest', if it exists, to do
281
+ * everything we can to determine the version.
282
+ *
283
+ * Since the data of the live-maninfest can not be trusted, we also must validate
284
+ * that the version is a valid semver version before returning it. It always represents
285
+ * the last known version from when the studio was connected to Sanity's infrastructure,
286
+ * which might not be the version this studio is currently running (e.g. because the version
287
+ * has been downgraded).
288
+ */
289
+ const deploymentManifest = this.get("activeDeployment")?.manifest;
290
+ // const liveManifest = growthbook.isOn('dashboard-use-live-manifest')
291
+ // ? this.get('config')?.['live-manifest']?.value
292
+ // : null
293
+
294
+ const serverManifest = deploymentManifest; /*?? liveManifest*/
295
+ const bundleVersion = serverManifest?.bundleVersion;
296
+
297
+ if (bundleVersion && valid(coerce(bundleVersion))) {
298
+ if (!version || (version && gt(bundleVersion, version))) {
299
+ version = bundleVersion;
300
+ }
301
+ }
302
+
303
+ if (!version || !valid(coerce(version))) {
304
+ return null;
305
+ }
306
+
307
+ return coerce(version);
308
+ }
309
+
310
+ get version() {
311
+ const version = this.resolveVersion();
312
+ return version ? version.toString() : null;
313
+ }
314
+
315
+ get compatibilityStatus(): CompatibilityStatus {
316
+ return StudioApplication.resolveCompatibilityStatus(this);
317
+ }
318
+
319
+ /**
320
+ * Used to calculate the compatibility status of a given studio application.
321
+ * Optionally if you've resolved the version elsewhere provide that value to
322
+ * get the new compatibility status without mutating the application.
323
+ */
324
+ static resolveCompatibilityStatus(
325
+ application: StudioApplication,
326
+ version: string | null = application.version,
327
+ ): CompatibilityStatus {
328
+ if (
329
+ version === null ||
330
+ lt(version, StudioApplication.MinimumStudioVersion)
331
+ ) {
332
+ return StudioApplication.CompatibilityStatuses.UNKNOWN;
333
+ }
334
+
335
+ if (
336
+ !application.hasSchema ||
337
+ !application.hasManifest ||
338
+ StudioApplication.resolveIssues(application, version).length > 0
339
+ ) {
340
+ return StudioApplication.CompatibilityStatuses.PARTIALLY_COMPATIBLE;
341
+ }
342
+
343
+ return StudioApplication.CompatibilityStatuses.FULLY_COMPATIBLE;
344
+ }
345
+
346
+ get isAutoRedirecting(): boolean {
347
+ return StudioApplication.resolveIsAutoRedirecting(this);
348
+ }
349
+
350
+ /**
351
+ * Mirrors the `isRedirectable` function from Saison defined in
352
+ * https://github.com/sanity-io/saison/blob/83556405d23e07f6d3a71c76249c67e33fe1101f/src/utils/applications.ts
353
+ *
354
+ * Returns whether a studio application is auto-redirecting, meaning it can only be accessed in the context of
355
+ * Dashboard.
356
+ */
357
+ static resolveIsAutoRedirecting(
358
+ application: StudioApplication,
359
+ versionArg = application.version,
360
+ ) {
361
+ let version: string | SemVer | null = versionArg;
362
+
363
+ if (application.get("urlType") === "external" || !version) {
364
+ return false;
365
+ }
366
+
367
+ if (!application.get("activeDeployment")?.isAutoUpdating) {
368
+ // If the studio is not auto-updating, we need to check if the version supports
369
+ // workspace switcher (3.92.0+) otherwise it would not be redirected.
370
+ return gt(version, "3.92.0");
371
+ }
372
+
373
+ const autoUpdatingVersion = application.get("autoUpdatingVersion");
374
+
375
+ if (autoUpdatingVersion) {
376
+ if (["next", "stable", "latest"].includes(autoUpdatingVersion)) {
377
+ return true;
378
+ }
379
+
380
+ const autoUpdatingVersionPinnedVersion = coerce(autoUpdatingVersion);
381
+
382
+ if (autoUpdatingVersionPinnedVersion) {
383
+ version = autoUpdatingVersionPinnedVersion;
384
+ }
385
+ }
386
+
387
+ return gt(version, StudioApplication.MinimumStudioVersion);
388
+ }
389
+
390
+ /**
391
+ * Returns a list of issues that prevent the studio from functioning properly in the Dashboard.
392
+ * This static value depends on the version of the studio that comes from the `activeDeployment` property.
393
+ * As such, if the studio is auto-updating, this list will be incorrect & instead you should use
394
+ * the static method `resolveIssues` to get the correct issues by passing the resolved version.
395
+ */
396
+ get issues(): StudioIssues {
397
+ return StudioApplication.resolveIssues(this);
398
+ }
399
+
400
+ static resolveIssues(
401
+ application: StudioApplication,
402
+ version: string | null = application.version,
403
+ ): StudioIssues {
404
+ const issues: StudioIssues = StudioApplication.Features.filter(
405
+ (feature) => {
406
+ return !application.isFeatureSupported(feature.id, version);
407
+ },
408
+ );
409
+
410
+ if (!application.hasManifest) {
411
+ issues.push({
412
+ id: StudioApplication.StudioIssues.ISSUE_MANIFEST,
413
+ });
414
+ }
415
+
416
+ return issues;
417
+ }
418
+
419
+ protected isFeatureSupported(
420
+ feature: StudioDashboardIssue,
421
+ version = this.version,
422
+ ) {
423
+ const featureVersion = StudioApplication.Features.find(
424
+ (_) => _.id === feature,
425
+ )?.version;
426
+
427
+ if (!featureVersion || !version) {
428
+ return false;
429
+ }
430
+
431
+ return gte(version, featureVersion);
432
+ }
433
+
434
+ toProtocolResource(): never {
435
+ throw new Error(
436
+ "Studio application resources cannot be converted to protocol resources",
437
+ );
438
+ }
439
+
440
+ static CompatibilityStatuses = {
441
+ UNKNOWN: "unknown",
442
+ PARTIALLY_COMPATIBLE: "partially-compatible",
443
+ FULLY_COMPATIBLE: "fully-compatible",
444
+ } as const;
445
+
446
+ static StudioIssues = {
447
+ ISSUE_ACTIVITY: "ACTIVITY",
448
+ ISSUE_AGENT: "AGENT",
449
+ ISSUE_FAVORITES: "FAVORITES",
450
+ ISSUE_URL_SYNCING: "URL_SYNCING",
451
+ ISSUE_UI_ADJUSTMENT: "UI_ADJUSTMENT",
452
+ ISSUE_CONTENT_MAPPING: "CONTENT_MAPPING",
453
+ ISSUE_LOGIN: "LOGIN",
454
+ ISSUE_MANIFEST: "MANIFEST",
455
+ } as const;
456
+
457
+ static Features = [
458
+ {
459
+ id: StudioApplication.StudioIssues.ISSUE_AGENT,
460
+ version: "5.1.0",
461
+ },
462
+ {
463
+ id: StudioApplication.StudioIssues.ISSUE_FAVORITES,
464
+ version: "3.88.1",
465
+ },
466
+ {
467
+ id: StudioApplication.StudioIssues.ISSUE_ACTIVITY,
468
+ version: "3.88.1",
469
+ },
470
+ {
471
+ id: StudioApplication.StudioIssues.ISSUE_URL_SYNCING,
472
+ version: "3.75.0",
473
+ },
474
+ {
475
+ id: StudioApplication.StudioIssues.ISSUE_UI_ADJUSTMENT,
476
+ version: "3.78.1",
477
+ },
478
+ {
479
+ id: StudioApplication.StudioIssues.ISSUE_CONTENT_MAPPING,
480
+ version: "3.68.0",
481
+ },
482
+ {
483
+ id: StudioApplication.StudioIssues.ISSUE_LOGIN,
484
+ version: "2.28.0",
485
+ },
486
+ ] satisfies StudioIssues;
487
+
488
+ static MinimumStudioVersion = "2.28.0" as const;
489
+
490
+ static MinimumStudioVersionWithNoIssues = rsort(
491
+ StudioApplication.Features.map((feature) => feature.version),
492
+ ).at(0);
493
+ }
494
+
495
+ type CompatibilityStatus =
496
+ (typeof StudioApplication.CompatibilityStatuses)[keyof typeof StudioApplication.CompatibilityStatuses];
497
+
498
+ type StudioDashboardIssue =
499
+ (typeof StudioApplication.StudioIssues)[keyof typeof StudioApplication.StudioIssues];
500
+
501
+ type StudioIssues = Array<{
502
+ id: StudioDashboardIssue;
503
+ version?: string;
504
+ }>;
@@ -0,0 +1,147 @@
1
+ import type { StudioResource as ProtocolStudioResource } from "@sanity/message-protocol";
2
+
3
+ import { AbstractApplication } from "../../applications/application";
4
+ import type { Project } from "../../projects";
5
+ import { joinUrlPaths, normalizePath } from "../../shared/urls";
6
+ import type { UserApplicationId } from "../user-application";
7
+ import type { Workspace } from "./schemas";
8
+ import type { StudioApplication } from "./studio";
9
+
10
+ /**
11
+ * @public
12
+ */
13
+ export class StudioWorkspace extends AbstractApplication<
14
+ "workspace",
15
+ ProtocolStudioResource
16
+ > {
17
+ /**
18
+ * Workspaces always belong to a studio application.
19
+ * They do not exist on their own & therefore can access
20
+ * information about the studio they're in via this property.
21
+ */
22
+ private readonly studioApplication: StudioApplication;
23
+ private readonly workspace: Workspace;
24
+ readonly project: Project<false, false>;
25
+ private readonly isDefaultWorkspace: boolean;
26
+
27
+ constructor(
28
+ studioApplication: StudioApplication,
29
+ workspace: Workspace,
30
+ project: Project<false, false>,
31
+ isDefaultWorkspace: boolean,
32
+ ) {
33
+ super("workspace");
34
+
35
+ this.studioApplication = studioApplication;
36
+ this.workspace = workspace;
37
+ this.project = project;
38
+ this.isDefaultWorkspace = isDefaultWorkspace;
39
+ }
40
+
41
+ /**
42
+ * The studio application that this workspace belongs to.
43
+ */
44
+ get studio() {
45
+ return this.studioApplication;
46
+ }
47
+
48
+ get id() {
49
+ return StudioWorkspace.makeId(this.studio.id, this.workspace.name);
50
+ }
51
+
52
+ get href() {
53
+ return joinUrlPaths(this.studio.href, this.workspace.name);
54
+ }
55
+
56
+ get title() {
57
+ /**
58
+ * If there's no manifest we will have created a single workspace for the application.
59
+ * In this circumstance we won't have a meaningful title, so instead we use the hostname of the appHost.
60
+ */
61
+ if (this.isDefaultWorkspace) {
62
+ return this.project.displayName;
63
+ }
64
+
65
+ return this.workspace.title;
66
+ }
67
+
68
+ get subtitle() {
69
+ if (this.isDefaultWorkspace) {
70
+ const isValidAppHost = URL.canParse(this.studio.get("appHost"));
71
+ const url = isValidAppHost
72
+ ? new URL(this.studio.get("appHost"))
73
+ : this.studio.url;
74
+
75
+ return url.hostname;
76
+ }
77
+
78
+ return this.get("subtitle");
79
+ }
80
+
81
+ get<TKey extends Exclude<keyof Workspace, "id" | "icon" | "title">>(
82
+ attr: TKey,
83
+ ): Workspace[TKey] {
84
+ return this.workspace[attr];
85
+ }
86
+
87
+ get isFederated() {
88
+ return this.studio.isFederated;
89
+ }
90
+
91
+ /**
92
+ * With comlink, studio-applications were not considered applications at all, only workspaces. This is partially why
93
+ * we create default workspaces when the application has no manifest or the manifest has no workspaces.
94
+ *
95
+ * Thereby, to create it we depend on a lot of information from the parent application even if it's duplicated across
96
+ * different workspaces.
97
+ */
98
+ toProtocolResource(): ProtocolStudioResource {
99
+ return {
100
+ ...this.workspace,
101
+ type: "studio",
102
+ userApplicationId: this.studio.id,
103
+ activeDeployment: this.studio.get("activeDeployment"),
104
+ autoUpdatingVersion: this.studio.get("autoUpdatingVersion"),
105
+ dashboardStatus: this.studio.get("dashboardStatus"),
106
+ url: this.studio.url.toString(),
107
+ href: this.href,
108
+ id: this.id,
109
+ hasManifest: true,
110
+ hasSchema: Boolean("schema" in this.workspace && this.workspace.schema),
111
+ manifest: (this.studio.get("manifestData")?.value ??
112
+ null) as ProtocolStudioResource["manifest"],
113
+ updatedAt: this.studio.get("updatedAt"),
114
+ version: this.studio.get("activeDeployment")?.version,
115
+ urlType: this.studio.get("urlType"),
116
+ config: this.studio.get("config"),
117
+ } satisfies ProtocolStudioResource;
118
+ }
119
+
120
+ /**
121
+ * @returns the URL to the workspace of a studio application.
122
+ */
123
+ get url(): URL {
124
+ const studioUrl = new URL(this.studio.url);
125
+ const normalizedUrlPath = normalizePath(studioUrl.pathname);
126
+
127
+ let finalBasePath = normalizePath(this.get("basePath"));
128
+
129
+ // the appHost may already contain the basepath for externally hosted studios
130
+ // or embedded studios, so we deduplicate the segments
131
+ if (finalBasePath.startsWith(normalizedUrlPath)) {
132
+ finalBasePath = finalBasePath.slice(normalizedUrlPath.length);
133
+ }
134
+
135
+ studioUrl.pathname = joinUrlPaths(normalizedUrlPath, finalBasePath);
136
+
137
+ return studioUrl;
138
+ }
139
+
140
+ static makeId(applicationId: UserApplicationId, workspaceName: string) {
141
+ return `${applicationId}-${workspaceName}`;
142
+ }
143
+
144
+ static splitId(id: string): [string, string] {
145
+ return id.split(new RegExp(/-(.*)/)).slice(0, 2) as [string, string];
146
+ }
147
+ }