@sanity/workbench 0.1.0-alpha.12 → 0.1.0-alpha.13

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,798 @@
1
+ import { z } from "zod";
2
+ import { valid, coerce, gt, lt, gte, rsort } from "semver";
3
+ class AbstractApplication {
4
+ type;
5
+ constructor(type) {
6
+ this.type = type;
7
+ }
8
+ /**
9
+ * Whether the application is served by a local CLI dev server rather than a
10
+ * deployed remote. Defaults to `false`; user applications flip this when
11
+ * constructed from a `LocalUserApplication` payload.
12
+ */
13
+ get isLocal() {
14
+ return !1;
15
+ }
16
+ get initials() {
17
+ const SYMBOLS = /[^\p{Alpha}\p{N}\p{White_Space}]/gu, WHITESPACE = new RegExp("\\p{White_Space}+", "u"), ALPHANUMERIC_SEGMENTS = new RegExp("(\\p{N}+|\\p{Alpha}+)", "gu"), IS_NUMERIC = new RegExp("^\\p{N}+$", "u");
18
+ if (!this.title) return "";
19
+ const namesArray = this.title.replace(SYMBOLS, "").split(WHITESPACE).filter(Boolean);
20
+ if (namesArray.length === 0) return "";
21
+ if (namesArray.length === 1) {
22
+ const word = namesArray[0], segments = word.match(ALPHANUMERIC_SEGMENTS) || [];
23
+ return segments.length === 0 ? "" : segments.length === 1 ? word.length === 1 ? word.toUpperCase() : IS_NUMERIC.test(word) ? `${word.charAt(0)}${word.charAt(1)}`.toUpperCase() : word.charAt(0).toUpperCase() : `${segments[0].charAt(0)}${segments[1].charAt(0)}`.toUpperCase();
24
+ }
25
+ return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`.toUpperCase();
26
+ }
27
+ }
28
+ function getSanityDomain() {
29
+ return getSanityEnv() === "staging" ? "sanity.work" : "sanity.io";
30
+ }
31
+ function getApiHost() {
32
+ return `https://api.${getSanityDomain()}`;
33
+ }
34
+ function getSanityEnv() {
35
+ return typeof __SANITY_STAGING__ < "u" && __SANITY_STAGING__ === !0 ? "staging" : "production";
36
+ }
37
+ const OrganizationId = z.string().nonempty().brand("OrganizationId");
38
+ function brandOrganizationId(id) {
39
+ return OrganizationId.parse(id);
40
+ }
41
+ const OrganizationMember = z.object({
42
+ sanityUserId: z.string(),
43
+ isCurrentUser: z.boolean(),
44
+ user: z.object({
45
+ id: z.string(),
46
+ displayName: z.string(),
47
+ familyName: z.string(),
48
+ givenName: z.string(),
49
+ middleName: z.string().nullable(),
50
+ imageUrl: z.string().nullable(),
51
+ email: z.string(),
52
+ loginProvider: z.string()
53
+ }),
54
+ roles: z.array(
55
+ z.object({
56
+ name: z.string(),
57
+ title: z.string(),
58
+ description: z.string().optional()
59
+ })
60
+ )
61
+ }), Organization = z.object({
62
+ id: OrganizationId,
63
+ name: z.string(),
64
+ slug: z.string().nullable(),
65
+ createdAt: z.string(),
66
+ updatedAt: z.string(),
67
+ dashboardStatus: z.enum(["enabled", "disabled"]),
68
+ aiFeaturesStatus: z.enum(["enabled", "disabled"]),
69
+ defaultRoleName: z.string()
70
+ });
71
+ function parseOrganization(data, options) {
72
+ const includeMembers = options?.includeMembers ?? !0, includeFeatures = options?.includeFeatures ?? !0, extensions = {
73
+ ...includeMembers && {
74
+ members: z.array(OrganizationMember)
75
+ },
76
+ ...includeFeatures && {
77
+ features: z.array(z.string())
78
+ }
79
+ };
80
+ return (Object.keys(extensions).length > 0 ? Organization.extend(extensions) : Organization).parse(data);
81
+ }
82
+ const CanvasId = z.string().nonempty().brand("CanvasId");
83
+ function brandCanvasId(id) {
84
+ return CanvasId.parse(id);
85
+ }
86
+ const Canvas = z.object({
87
+ id: CanvasId,
88
+ organizationId: OrganizationId,
89
+ status: z.enum(["active", "provisioning"])
90
+ });
91
+ function parseCanvas(data) {
92
+ return Canvas.parse(data);
93
+ }
94
+ class CanvasApplication extends AbstractApplication {
95
+ canvas;
96
+ constructor(canvas) {
97
+ super("canvas"), this.canvas = canvas;
98
+ }
99
+ get id() {
100
+ return this.canvas.id;
101
+ }
102
+ get href() {
103
+ return "canvas";
104
+ }
105
+ get title() {
106
+ return "Canvas";
107
+ }
108
+ get url() {
109
+ return new URL(
110
+ `https://canvas.${getSanityDomain()}/o/${this.canvas.organizationId}`
111
+ );
112
+ }
113
+ get isFederated() {
114
+ return !1;
115
+ }
116
+ toProtocolResource() {
117
+ return {
118
+ type: "canvas",
119
+ id: this.id
120
+ };
121
+ }
122
+ }
123
+ const MediaLibraryId = z.string().nonempty().brand("MediaLibraryId");
124
+ function brandMediaLibraryId(id) {
125
+ return MediaLibraryId.parse(id);
126
+ }
127
+ const MediaLibrary = z.object({
128
+ id: MediaLibraryId,
129
+ organizationId: OrganizationId,
130
+ status: z.enum(["active", "provisioning"]),
131
+ aclMode: z.enum(["private", "public"])
132
+ });
133
+ function parseMediaLibrary(data) {
134
+ return MediaLibrary.parse(data);
135
+ }
136
+ class MediaLibraryApplication extends AbstractApplication {
137
+ library;
138
+ constructor(library) {
139
+ super("media-library"), this.library = library;
140
+ }
141
+ get id() {
142
+ return this.library.id;
143
+ }
144
+ get href() {
145
+ return "media";
146
+ }
147
+ get title() {
148
+ return "Media Library";
149
+ }
150
+ get isFederated() {
151
+ return !1;
152
+ }
153
+ get url() {
154
+ return new URL(
155
+ `https://media.${getSanityDomain()}/${this.library.organizationId}`
156
+ );
157
+ }
158
+ toProtocolResource() {
159
+ return {
160
+ type: "media-library",
161
+ id: this.id
162
+ };
163
+ }
164
+ }
165
+ const ProjectId = z.string().nonempty().brand("ProjectId");
166
+ function brandProjectId(id) {
167
+ return ProjectId.parse(id);
168
+ }
169
+ const ProjectMember = z.object({
170
+ id: z.string(),
171
+ createdAt: z.string(),
172
+ updatedAt: z.string(),
173
+ isCurrentUser: z.boolean(),
174
+ isRobot: z.boolean(),
175
+ roles: z.array(
176
+ z.object({
177
+ name: z.string(),
178
+ title: z.string(),
179
+ description: z.string()
180
+ })
181
+ )
182
+ }), Project = z.object({
183
+ id: ProjectId,
184
+ displayName: z.string(),
185
+ studioHost: z.string().nullable(),
186
+ organizationId: OrganizationId,
187
+ metadata: z.object({
188
+ color: z.string().optional(),
189
+ externalStudioHost: z.string().optional(),
190
+ initialTemplate: z.string().optional(),
191
+ cliInitializedAt: z.string().optional(),
192
+ integration: z.string().optional()
193
+ }),
194
+ isBlocked: z.boolean(),
195
+ isDisabled: z.boolean(),
196
+ isDisabledByUser: z.boolean(),
197
+ activityFeedEnabled: z.boolean(),
198
+ createdAt: z.string(),
199
+ updatedAt: z.string()
200
+ });
201
+ function parseProject(data, options) {
202
+ const includeMembers = options?.includeMembers ?? !0, includeFeatures = options?.includeFeatures ?? !0, extensions = {
203
+ ...includeMembers && { members: z.array(ProjectMember) },
204
+ ...includeFeatures && { features: z.array(z.string()) }
205
+ };
206
+ return (Object.keys(extensions).length > 0 ? Project.extend(extensions) : Project).parse(data);
207
+ }
208
+ const joinUrlPaths = (...paths) => {
209
+ let nextPath = null;
210
+ const safeJoinSegments = (segment1, segment2) => segment1 ? segment2 ? segment1.endsWith("/") && segment2.startsWith("/") ? segment1 + segment2.slice(1) : segment1.endsWith("/") || segment2.startsWith("/") ? segment1 + segment2 : `${segment1}/${segment2}` : segment1 : segment2 || "", validPaths = paths.filter(
211
+ (path) => path != null
212
+ );
213
+ for (const path of validPaths)
214
+ nextPath = safeJoinSegments(
215
+ nextPath,
216
+ path instanceof URL ? path.pathname : path
217
+ );
218
+ return nextPath ?? "";
219
+ };
220
+ function normalizePath(pathname) {
221
+ return pathname.startsWith("/") || (pathname = `/${pathname}`), pathname !== "/" && pathname.endsWith("/") && (pathname = pathname.slice(0, -1)), pathname;
222
+ }
223
+ const UserApplicationId = z.string().nonempty().brand("UserApplicationId");
224
+ function brandUserApplicationId(id) {
225
+ return UserApplicationId.parse(id);
226
+ }
227
+ const LocalUserApplicationBase = z.object({
228
+ host: z.string(),
229
+ port: z.number(),
230
+ /** The `deployment.appId` from the application's `sanity.cli.ts`, when set. */
231
+ id: z.string().optional(),
232
+ /**
233
+ * The `api.projectId` from the application's `sanity.cli.ts`. Available
234
+ * synchronously at dev-server startup (no manifest extraction required), so
235
+ * the studio's primary project is resolvable from the very first local
236
+ * application event.
237
+ */
238
+ projectId: z.string().optional()
239
+ }), LocalUserApplication = z.discriminatedUnion("type", [
240
+ LocalUserApplicationBase.extend({
241
+ type: z.literal("studio"),
242
+ manifest: z.custom().optional()
243
+ }),
244
+ LocalUserApplicationBase.extend({
245
+ type: z.literal("coreApp"),
246
+ manifest: z.custom().optional()
247
+ })
248
+ ]), UserApplicationBase = z.object({
249
+ id: UserApplicationId,
250
+ appHost: z.string(),
251
+ urlType: z.enum(["internal", "external"]),
252
+ createdAt: z.string(),
253
+ updatedAt: z.string(),
254
+ dashboardStatus: z.enum(["default", "disabled"])
255
+ }), ActiveDeployment = z.object({
256
+ id: z.string(),
257
+ version: z.string(),
258
+ isActiveDeployment: z.boolean(),
259
+ userApplicationId: z.string(),
260
+ isAutoUpdating: z.boolean(),
261
+ size: z.number(),
262
+ deployedAt: z.string(),
263
+ deployedBy: z.string(),
264
+ createdAt: z.string(),
265
+ updatedAt: z.string()
266
+ });
267
+ class UserApplication extends AbstractApplication {
268
+ application;
269
+ id;
270
+ /**
271
+ * For local applications (`isLocal === true`), the deployed application
272
+ * that shares the same `id` — if one was passed at construction. `null`
273
+ * for deployed applications or when no remote twin was provided.
274
+ */
275
+ remoteApplication;
276
+ #isLocal;
277
+ constructor(application, type, options = {}) {
278
+ super(type), this.application = application, this.id = brandUserApplicationId(application.id), this.#isLocal = options.isLocal ?? !1, this.remoteApplication = options.remoteApplication ?? null;
279
+ }
280
+ /**
281
+ * Local dev servers are rendered as federated remotes; deployed applications
282
+ * are rendered in an iframe.
283
+ */
284
+ get isFederated() {
285
+ return this.isLocal;
286
+ }
287
+ get isLocal() {
288
+ return this.#isLocal;
289
+ }
290
+ /**
291
+ * @returns A fully resolved URL instance for the application.
292
+ * For internal applications, constructs a URL using the Sanity studio domain
293
+ * pattern resolved from the environment at the consuming app's build time.
294
+ * For external applications (including local dev servers), returns the
295
+ * provided app host as a URL.
296
+ */
297
+ get url() {
298
+ return this.application.urlType === "internal" ? getSanityEnv() === "production" ? new URL(`https://${this.application.appHost}.sanity.studio`) : new URL(
299
+ `https://${this.application.appHost}.studio.${getSanityDomain()}`
300
+ ) : new URL(this.application.appHost);
301
+ }
302
+ }
303
+ const CoreAppUserApplicationManifest = z.object({
304
+ version: z.string(),
305
+ icon: z.string().optional(),
306
+ title: z.string().optional()
307
+ }), CoreAppUserApplicationBase = UserApplicationBase.extend({
308
+ title: z.string(),
309
+ organizationId: OrganizationId,
310
+ type: z.literal("coreApp")
311
+ }), CoreAppActiveDeployment = ActiveDeployment.extend({
312
+ manifest: CoreAppUserApplicationManifest.nullable()
313
+ }).nullable(), InternalCoreAppUserApplication = CoreAppUserApplicationBase.extend({
314
+ urlType: z.literal("internal"),
315
+ activeDeployment: CoreAppActiveDeployment
316
+ }), ExternalCoreAppUserApplication = CoreAppUserApplicationBase.extend({
317
+ urlType: z.literal("external"),
318
+ activeDeployment: CoreAppActiveDeployment
319
+ }), CoreAppUserApplication = z.discriminatedUnion("urlType", [
320
+ InternalCoreAppUserApplication,
321
+ ExternalCoreAppUserApplication
322
+ ]);
323
+ function parseCoreApplication(data) {
324
+ return CoreAppUserApplication.parse(data);
325
+ }
326
+ class CoreAppApplication extends UserApplication {
327
+ activeDeployment;
328
+ constructor(application, options = {}) {
329
+ super(application, "coreApp", options), this.activeDeployment = application.activeDeployment;
330
+ }
331
+ get href() {
332
+ return this.isLocal ? `/local/${this.id}` : `/application/${this.application.id}`;
333
+ }
334
+ get title() {
335
+ return this.manifest?.title ?? this.application.title;
336
+ }
337
+ /**
338
+ * Resolves the core app's manifest from `activeDeployment.manifest`. This
339
+ * is the canonical (and only) slot for core app manifests — both for
340
+ * Sanity-deployed apps and for local CLI dev-server apps, which synthesise
341
+ * a deployment to surface the live manifest.
342
+ */
343
+ get manifest() {
344
+ return this.activeDeployment?.manifest ?? null;
345
+ }
346
+ get subtitle() {
347
+ }
348
+ get updatedAt() {
349
+ return this.application.updatedAt;
350
+ }
351
+ get(attr) {
352
+ if (!(attr in this.application))
353
+ throw new Error(
354
+ `Attribute ${attr.toString()} does not exist on application ${this.application.id}`
355
+ );
356
+ return this.application[attr];
357
+ }
358
+ toProtocolResource() {
359
+ return {
360
+ ...this.application,
361
+ type: "application",
362
+ url: this.url.toString()
363
+ };
364
+ }
365
+ }
366
+ const Workspace = z.object({
367
+ name: z.string(),
368
+ title: z.string(),
369
+ subtitle: z.string().optional(),
370
+ basePath: z.string(),
371
+ projectId: ProjectId,
372
+ dataset: z.string().optional(),
373
+ icon: z.string().nullable().optional()
374
+ }), ServerManifest = z.object({
375
+ buildId: z.string().optional(),
376
+ bundleVersion: z.string().optional(),
377
+ version: z.string().optional(),
378
+ workspaces: z.array(
379
+ Workspace.extend({
380
+ dataset: z.string(),
381
+ schemaDescriptorId: z.string()
382
+ })
383
+ ).optional()
384
+ }), ClientManifest = z.object({
385
+ version: z.number(),
386
+ createdAt: z.string(),
387
+ studioVersion: z.string().optional(),
388
+ workspaces: z.array(
389
+ Workspace.extend({
390
+ schema: z.string(),
391
+ tools: z.string().optional()
392
+ })
393
+ )
394
+ }), StudioUserApplicationBase = UserApplicationBase.extend({
395
+ title: z.string().nullable(),
396
+ projectId: ProjectId,
397
+ type: z.literal("studio"),
398
+ /**
399
+ * @deprecated Use `manifestData` instead.
400
+ */
401
+ manifest: ClientManifest.nullable(),
402
+ manifestData: z.object({ value: ClientManifest }).nullable(),
403
+ autoUpdatingVersion: z.string().nullable(),
404
+ config: z.object({
405
+ "live-manifest": z.object({
406
+ createdAt: z.string(),
407
+ updatedAt: z.string(),
408
+ updatedBy: z.string(),
409
+ value: ServerManifest
410
+ }).optional()
411
+ })
412
+ }), InternalStudioUserApplication = StudioUserApplicationBase.extend({
413
+ urlType: z.literal("internal"),
414
+ activeDeployment: ActiveDeployment.extend({
415
+ manifest: ServerManifest.nullable()
416
+ })
417
+ }), ExternalStudioUserApplication = StudioUserApplicationBase.extend({
418
+ urlType: z.literal("external"),
419
+ activeDeployment: z.null()
420
+ }), StudioUserApplication = z.discriminatedUnion("urlType", [
421
+ InternalStudioUserApplication,
422
+ ExternalStudioUserApplication
423
+ ]);
424
+ function parseStudioUserApplication(data) {
425
+ return StudioUserApplication.parse(data);
426
+ }
427
+ class StudioWorkspace extends AbstractApplication {
428
+ /**
429
+ * Workspaces always belong to a studio application.
430
+ * They do not exist on their own & therefore can access
431
+ * information about the studio they're in via this property.
432
+ */
433
+ studioApplication;
434
+ workspace;
435
+ project;
436
+ isDefaultWorkspace;
437
+ constructor(studioApplication, workspace, project, isDefaultWorkspace) {
438
+ super("workspace"), this.studioApplication = studioApplication, this.workspace = workspace, this.project = project, this.isDefaultWorkspace = isDefaultWorkspace;
439
+ }
440
+ /**
441
+ * The studio application that this workspace belongs to.
442
+ */
443
+ get studio() {
444
+ return this.studioApplication;
445
+ }
446
+ get id() {
447
+ return StudioWorkspace.makeId(this.studio.id, this.workspace.name);
448
+ }
449
+ get href() {
450
+ return joinUrlPaths(this.studio.href, this.workspace.name);
451
+ }
452
+ get title() {
453
+ return this.isDefaultWorkspace ? this.project.displayName : this.workspace.title;
454
+ }
455
+ get subtitle() {
456
+ return this.isDefaultWorkspace ? (URL.canParse(this.studio.get("appHost")) ? new URL(this.studio.get("appHost")) : this.studio.url).hostname : this.get("subtitle");
457
+ }
458
+ get(attr) {
459
+ return this.workspace[attr];
460
+ }
461
+ get isFederated() {
462
+ return this.studio.isFederated;
463
+ }
464
+ /**
465
+ * With comlink, studio-applications were not considered applications at all, only workspaces. This is partially why
466
+ * we create default workspaces when the application has no manifest or the manifest has no workspaces.
467
+ *
468
+ * Thereby, to create it we depend on a lot of information from the parent application even if it's duplicated across
469
+ * different workspaces.
470
+ */
471
+ toProtocolResource() {
472
+ return {
473
+ ...this.workspace,
474
+ type: "studio",
475
+ userApplicationId: this.studio.id,
476
+ activeDeployment: this.studio.get("activeDeployment"),
477
+ autoUpdatingVersion: this.studio.get("autoUpdatingVersion"),
478
+ dashboardStatus: this.studio.get("dashboardStatus"),
479
+ url: this.studio.url.toString(),
480
+ href: this.href,
481
+ id: this.id,
482
+ hasManifest: !0,
483
+ hasSchema: !!("schema" in this.workspace && this.workspace.schema),
484
+ // The protocol resource requires the client-shaped manifest (workspaces
485
+ // with `schema`). Read those sources directly rather than the unified
486
+ // `manifest` getter, which may return a `ServerManifest` for studios
487
+ // with a deployment manifest.
488
+ manifest: this.studio.get("manifestData")?.value ?? this.studio.get("manifest") ?? null,
489
+ updatedAt: this.studio.get("updatedAt"),
490
+ version: this.studio.get("activeDeployment")?.version,
491
+ urlType: this.studio.get("urlType"),
492
+ config: this.studio.get("config")
493
+ };
494
+ }
495
+ /**
496
+ * @returns the URL to the workspace of a studio application.
497
+ */
498
+ get url() {
499
+ const studioUrl = new URL(this.studio.url), normalizedUrlPath = normalizePath(studioUrl.pathname);
500
+ let finalBasePath = normalizePath(this.get("basePath"));
501
+ return finalBasePath.startsWith(normalizedUrlPath) && (finalBasePath = finalBasePath.slice(normalizedUrlPath.length)), studioUrl.pathname = joinUrlPaths(normalizedUrlPath, finalBasePath), studioUrl;
502
+ }
503
+ static makeId(applicationId, workspaceName) {
504
+ return `${applicationId}-${workspaceName}`;
505
+ }
506
+ static splitId(id) {
507
+ return id.split(new RegExp(/-(.*)/)).slice(0, 2);
508
+ }
509
+ }
510
+ const Manifest = z.union([
511
+ ClientManifest.superRefine((data, ctx) => {
512
+ data.version || ctx.addIssue({
513
+ code: "invalid_type",
514
+ message: "Manifest version is too old",
515
+ expected: "number"
516
+ }), data.version < 2 && ctx.addIssue({
517
+ code: "invalid_value",
518
+ message: "Manifest version is too old",
519
+ values: [2, 3]
520
+ }), data.version >= 3 && !data.studioVersion && ctx.addIssue({
521
+ code: "invalid_type",
522
+ message: "Manifest version 3 or higher requires a `studioVersion`",
523
+ expected: "string"
524
+ });
525
+ }),
526
+ ServerManifest
527
+ ]), DEFAULT_WORKSPACE_DATA = {
528
+ name: "default",
529
+ title: "Default",
530
+ basePath: "/"
531
+ };
532
+ class StudioApplication extends UserApplication {
533
+ /**
534
+ * Returns a list of studio workspaces based on the application manifest.
535
+ * If there is no manifest, or alternatively it is not valid, then we create a default workspace.
536
+ */
537
+ workspaces = [];
538
+ project;
539
+ /**
540
+ * The projects actually referenced by this studio — the application's own
541
+ * project plus any project used by a workspace. Preserved so the instance
542
+ * can be re-constructed (e.g. by dock wrappers) without having to thread
543
+ * the full organization project list through again.
544
+ */
545
+ projects;
546
+ /**
547
+ * @param application - The studio application to create a list of workspaces for
548
+ * @param projects - The projects available in the organization. It's not enough to just pass
549
+ * the project that associates with the application because that is the project the app is deployed in relation to.
550
+ * The workspaces may have different projects completely.
551
+ */
552
+ constructor(application, projects, options = {}) {
553
+ super(application, "studio", options);
554
+ let workspaces = [];
555
+ const manifest = this.manifest;
556
+ if (manifest)
557
+ try {
558
+ workspaces = Manifest.parse(manifest).workspaces ?? [];
559
+ } catch (error) {
560
+ console.warn(
561
+ `Failed to parse manifest for application ${application.id}`,
562
+ error
563
+ );
564
+ }
565
+ const workspacesWithProjectsMap = workspaces.reduce((acc, workspace) => {
566
+ const project2 = projects.find((p) => p.id === workspace.projectId);
567
+ return project2 ? acc.set(workspace, project2) : console.warn(
568
+ `Project not found for application ${application.id} and workspace ${workspace.name}. This workspace has been omitted.`
569
+ ), acc;
570
+ }, /* @__PURE__ */ new Map()), project = projects.find((p) => p.id === application.projectId);
571
+ if (!project)
572
+ throw new Error(`Project not found for application ${application.id}`);
573
+ workspacesWithProjectsMap.size === 0 && workspacesWithProjectsMap.set(
574
+ {
575
+ ...DEFAULT_WORKSPACE_DATA,
576
+ projectId: application.projectId
577
+ },
578
+ project
579
+ ), this.workspaces = Object.freeze(
580
+ Array.from(workspacesWithProjectsMap.entries()).map(([workspace, p]) => {
581
+ const isDefaultWorkspace = workspace.name === DEFAULT_WORKSPACE_DATA.name && workspace.basePath === DEFAULT_WORKSPACE_DATA.basePath && workspace.title === DEFAULT_WORKSPACE_DATA.title;
582
+ return new StudioWorkspace(this, workspace, p, isDefaultWorkspace);
583
+ })
584
+ ), this.project = project;
585
+ const usedProjects = /* @__PURE__ */ new Set([project]);
586
+ for (const workspace of this.workspaces)
587
+ usedProjects.add(workspace.project);
588
+ this.projects = Array.from(usedProjects);
589
+ }
590
+ get href() {
591
+ return this.isLocal ? `/local/${this.id}` : `/studio/${this.application.id}`;
592
+ }
593
+ get title() {
594
+ return this.get("title") || (this.workspaces.length > 1 && this.get("urlType") === "internal" ? this.project.displayName : this.workspaces[0].title);
595
+ }
596
+ get subtitle() {
597
+ return new URL(this.url).hostname;
598
+ }
599
+ get(attr) {
600
+ if (!(attr in this.application))
601
+ throw new Error(
602
+ `Attribute ${attr.toString()} does not exist on studio ${this.application.id}`
603
+ );
604
+ return this.application[attr];
605
+ }
606
+ /**
607
+ * Resolves the studio's most authoritative manifest. The lookup order is:
608
+ *
609
+ * 1. `activeDeployment.manifest` — deployment manifests are the new
610
+ * primitive within Sanity and are preferred whenever available.
611
+ * 2. `manifestData.value` — fallback to support older studios that
612
+ * haven't produced a deployment manifest yet.
613
+ * 3. `application.manifest` — last-resort legacy field.
614
+ *
615
+ * Returns `null` when no manifest is available. The return shape is a
616
+ * union because the deployment and client manifests are not
617
+ * interchangeable — consumers that depend on client-only fields (e.g.
618
+ * `studioVersion`, workspace `schema`) must narrow or read the raw
619
+ * field they need.
620
+ */
621
+ get manifest() {
622
+ return this.application.activeDeployment?.manifest ?? this.application.manifestData?.value ?? this.application.manifest ?? null;
623
+ }
624
+ get hasManifest() {
625
+ const manifest = this.manifest;
626
+ return manifest ? typeof manifest.version != "number" || manifest.version >= 2 : !1;
627
+ }
628
+ get hasSchema() {
629
+ if (this.application.activeDeployment?.manifest) return !0;
630
+ const workspaces = (this.application.manifestData?.value ?? this.application.manifest)?.workspaces ?? [];
631
+ return workspaces.length === 0 ? !1 : workspaces.every((w) => !!w.schema);
632
+ }
633
+ resolveVersion() {
634
+ let version;
635
+ if (this.get("urlType") === "internal")
636
+ version = this.get("activeDeployment")?.version;
637
+ else {
638
+ const clientManifest = this.get("manifestData")?.value ?? this.get("manifest");
639
+ version = clientManifest && "studioVersion" in clientManifest ? clientManifest.studioVersion : void 0;
640
+ }
641
+ const bundleVersion = this.get("activeDeployment")?.manifest?.bundleVersion;
642
+ return bundleVersion && valid(coerce(bundleVersion)) && (!version || version && gt(bundleVersion, version)) && (version = bundleVersion), !version || !valid(coerce(version)) ? null : coerce(version);
643
+ }
644
+ get version() {
645
+ const version = this.resolveVersion();
646
+ return version ? version.toString() : null;
647
+ }
648
+ get compatibilityStatus() {
649
+ return StudioApplication.resolveCompatibilityStatus(this);
650
+ }
651
+ /**
652
+ * Used to calculate the compatibility status of a given studio application.
653
+ * Optionally if you've resolved the version elsewhere provide that value to
654
+ * get the new compatibility status without mutating the application.
655
+ */
656
+ static resolveCompatibilityStatus(application, version = application.version) {
657
+ return version === null || lt(version, StudioApplication.MinimumStudioVersion) ? StudioApplication.CompatibilityStatuses.UNKNOWN : !application.hasSchema || !application.hasManifest || StudioApplication.resolveIssues(application, version).length > 0 ? StudioApplication.CompatibilityStatuses.PARTIALLY_COMPATIBLE : StudioApplication.CompatibilityStatuses.FULLY_COMPATIBLE;
658
+ }
659
+ get isAutoRedirecting() {
660
+ return StudioApplication.resolveIsAutoRedirecting(this);
661
+ }
662
+ /**
663
+ * Mirrors the `isRedirectable` function from Saison defined in
664
+ * https://github.com/sanity-io/saison/blob/83556405d23e07f6d3a71c76249c67e33fe1101f/src/utils/applications.ts
665
+ *
666
+ * Returns whether a studio application is auto-redirecting, meaning it can only be accessed in the context of
667
+ * Dashboard.
668
+ */
669
+ static resolveIsAutoRedirecting(application, versionArg = application.version) {
670
+ let version = versionArg;
671
+ if (application.get("urlType") === "external" || !version)
672
+ return !1;
673
+ if (!application.get("activeDeployment")?.isAutoUpdating)
674
+ return gt(version, "3.92.0");
675
+ const autoUpdatingVersion = application.get("autoUpdatingVersion");
676
+ if (autoUpdatingVersion) {
677
+ if (["next", "stable", "latest"].includes(autoUpdatingVersion))
678
+ return !0;
679
+ const autoUpdatingVersionPinnedVersion = coerce(autoUpdatingVersion);
680
+ autoUpdatingVersionPinnedVersion && (version = autoUpdatingVersionPinnedVersion);
681
+ }
682
+ return gt(version, StudioApplication.MinimumStudioVersion);
683
+ }
684
+ /**
685
+ * Returns a list of issues that prevent the studio from functioning properly in the Dashboard.
686
+ * This static value depends on the version of the studio that comes from the `activeDeployment` property.
687
+ * As such, if the studio is auto-updating, this list will be incorrect & instead you should use
688
+ * the static method `resolveIssues` to get the correct issues by passing the resolved version.
689
+ */
690
+ get issues() {
691
+ return StudioApplication.resolveIssues(this);
692
+ }
693
+ static resolveIssues(application, version = application.version) {
694
+ const issues = StudioApplication.Features.filter(
695
+ (feature) => !application.isFeatureSupported(feature.id, version)
696
+ );
697
+ return application.hasManifest || issues.push({
698
+ id: StudioApplication.StudioIssues.ISSUE_MANIFEST
699
+ }), issues;
700
+ }
701
+ isFeatureSupported(feature, version = this.version) {
702
+ const featureVersion = StudioApplication.Features.find(
703
+ (_) => _.id === feature
704
+ )?.version;
705
+ return !featureVersion || !version ? !1 : gte(version, featureVersion);
706
+ }
707
+ toProtocolResource() {
708
+ throw new Error(
709
+ "Studio application resources cannot be converted to protocol resources"
710
+ );
711
+ }
712
+ static CompatibilityStatuses = {
713
+ UNKNOWN: "unknown",
714
+ PARTIALLY_COMPATIBLE: "partially-compatible",
715
+ FULLY_COMPATIBLE: "fully-compatible"
716
+ };
717
+ static StudioIssues = {
718
+ ISSUE_ACTIVITY: "ACTIVITY",
719
+ ISSUE_AGENT: "AGENT",
720
+ ISSUE_FAVORITES: "FAVORITES",
721
+ ISSUE_URL_SYNCING: "URL_SYNCING",
722
+ ISSUE_UI_ADJUSTMENT: "UI_ADJUSTMENT",
723
+ ISSUE_CONTENT_MAPPING: "CONTENT_MAPPING",
724
+ ISSUE_LOGIN: "LOGIN",
725
+ ISSUE_MANIFEST: "MANIFEST"
726
+ };
727
+ static Features = [
728
+ {
729
+ id: StudioApplication.StudioIssues.ISSUE_AGENT,
730
+ version: "5.1.0"
731
+ },
732
+ {
733
+ id: StudioApplication.StudioIssues.ISSUE_FAVORITES,
734
+ version: "3.88.1"
735
+ },
736
+ {
737
+ id: StudioApplication.StudioIssues.ISSUE_ACTIVITY,
738
+ version: "3.88.1"
739
+ },
740
+ {
741
+ id: StudioApplication.StudioIssues.ISSUE_URL_SYNCING,
742
+ version: "3.75.0"
743
+ },
744
+ {
745
+ id: StudioApplication.StudioIssues.ISSUE_UI_ADJUSTMENT,
746
+ version: "3.78.1"
747
+ },
748
+ {
749
+ id: StudioApplication.StudioIssues.ISSUE_CONTENT_MAPPING,
750
+ version: "3.68.0"
751
+ },
752
+ {
753
+ id: StudioApplication.StudioIssues.ISSUE_LOGIN,
754
+ version: "2.28.0"
755
+ }
756
+ ];
757
+ static MinimumStudioVersion = "2.28.0";
758
+ static MinimumStudioVersionWithNoIssues = rsort(
759
+ StudioApplication.Features.map((feature) => feature.version)
760
+ ).at(0);
761
+ }
762
+ export {
763
+ AbstractApplication,
764
+ ActiveDeployment,
765
+ CanvasApplication,
766
+ ClientManifest,
767
+ CoreAppApplication,
768
+ CoreAppUserApplicationManifest,
769
+ LocalUserApplication,
770
+ MediaLibraryApplication,
771
+ Organization,
772
+ OrganizationId,
773
+ Project,
774
+ ProjectId,
775
+ ServerManifest,
776
+ StudioApplication,
777
+ StudioUserApplication,
778
+ StudioWorkspace,
779
+ UserApplication,
780
+ UserApplicationBase,
781
+ UserApplicationId,
782
+ brandCanvasId,
783
+ brandMediaLibraryId,
784
+ brandOrganizationId,
785
+ brandProjectId,
786
+ brandUserApplicationId,
787
+ getApiHost,
788
+ getSanityDomain,
789
+ getSanityEnv,
790
+ joinUrlPaths,
791
+ parseCanvas,
792
+ parseCoreApplication,
793
+ parseMediaLibrary,
794
+ parseOrganization,
795
+ parseProject,
796
+ parseStudioUserApplication
797
+ };
798
+ //# sourceMappingURL=studio.js.map