@hygraph/cli 0.0.14 → 0.0.16

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/cli.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { r as __toESM, t as __commonJSMin } from "./rolldown-runtime.js";
2
2
  import { t as VERSION } from "./version.js";
3
- import { C as assetReverseApiId, S as require_kinds, _ as typeDefinitionName, a as SLUG_DEFAULTS, b as require_parser, c as environment, d as isEmptyRichText, f as richTextActions, g as splitTypeDefinitions, h as convertOAuthToIR, i as target, l as FIELD_DEFAULTS, m as convertHeadersToIR, n as stage, o as collectIntents, p as REMOTE_DEFAULTS, s as convertEnvironmentToIR, u as RICH_TEXT_ACTIONS, v as byApiId$1, w as isEmpty, x as require_GraphQLError, y as byPrefix } from "./define2.js";
3
+ import { C as require_parser, D as isEmpty, E as assetReverseApiId, S as sidebarElementKey, T as require_kinds, _ as splitTypeDefinitions, a as SLUG_DEFAULTS, b as byPrefix, c as environment, d as RICH_TEXT_ACTIONS, f as isEmptyRichText, g as convertOAuthToIR, h as convertHeadersToIR, i as target, l as SYSTEM_SIDEBAR_DISPLAY_NAMES, m as REMOTE_DEFAULTS, n as stage, o as collectIntents, p as richTextActions, s as convertEnvironmentToIR, u as FIELD_DEFAULTS, v as typeDefinitionName, w as require_GraphQLError, x as bySidebarElementKey, y as byApiId$1 } from "./define2.js";
4
4
  import { EventEmitter } from "node:events";
5
5
  import childProcess from "node:child_process";
6
6
  import path, { dirname, resolve } from "node:path";
7
7
  import fs, { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
8
  import process$1 from "node:process";
9
- import { stripVTControlCharacters } from "node:util";
9
+ import { isDeepStrictEqual, stripVTControlCharacters } from "node:util";
10
10
  import { createInterface } from "node:readline/promises";
11
11
  import { createHash } from "node:crypto";
12
12
  import { createJiti } from "jiti";
@@ -3316,12 +3316,39 @@ const SchemaDefinitionDocument = new TypedDocumentString(`
3316
3316
  apiId
3317
3317
  __typename
3318
3318
  }
3319
+ taxonomies {
3320
+ apiId
3321
+ __typename
3322
+ }
3319
3323
  systemModels: models(includeSystemModels: true) {
3320
3324
  apiId
3321
3325
  __typename
3322
3326
  }
3323
3327
  models(includeSystemModels: false) {
3324
3328
  apiId
3329
+ sidebarElements {
3330
+ displayName
3331
+ description
3332
+ config
3333
+ position
3334
+ createdAt
3335
+ ... on SystemSidebarElement {
3336
+ type
3337
+ __typename
3338
+ }
3339
+ ... on AppSidebarElement {
3340
+ appElement {
3341
+ apiId
3342
+ app {
3343
+ apiId
3344
+ __typename
3345
+ }
3346
+ __typename
3347
+ }
3348
+ __typename
3349
+ }
3350
+ __typename
3351
+ }
3325
3352
  fields(includeHiddenFields: true, includeApiOnlyFields: true) {
3326
3353
  apiId
3327
3354
  ... on RelationalField {
@@ -3888,9 +3915,10 @@ function isRename(change) {
3888
3915
  * reference's update that drops a model deletes that model's field back, a
3889
3916
  * rich text update that drops an embedded model deletes the embeds of its
3890
3917
  * entries, and turning a field's variants off deletes its variant values.
3918
+ * Removing a sidebar panel keeps all content.
3891
3919
  */
3892
3920
  function isDestructive(change) {
3893
- return change.action === "delete" || dropsUnionMember(change) || dropsEmbed(change) || dropsVariants(change);
3921
+ return change.action === "delete" && change.resource !== "sidebarElement" || dropsUnionMember(change) || dropsEmbed(change) || dropsVariants(change);
3894
3922
  }
3895
3923
  /** A field update that turns variants off: Hygraph deletes its variant values. */
3896
3924
  function dropsVariants(change) {
@@ -11876,12 +11904,11 @@ function createComponentUnionField({ parent }, field) {
11876
11904
  }
11877
11905
  /**
11878
11906
  * Only the attributes that change are sent. A rename is `newApiId`; the
11879
- * members are sent whole and replace the old ones. `list` and the
11880
- * visibility cannot change: the diff deletes and creates the field
11881
- * instead.
11907
+ * members are sent whole and replace the old ones. `list` cannot change:
11908
+ * the diff deletes and creates the field instead.
11882
11909
  */
11883
11910
  function updateComponentUnionField(change) {
11884
- const { apiId, displayName, description, components, visibilityCondition, variantEnabled, position } = change.changes;
11911
+ const { apiId, displayName, description, components, visibility, visibilityCondition, variantEnabled, position } = change.changes;
11885
11912
  const input = {
11886
11913
  apiId: change.apiId,
11887
11914
  parentApiId: change.parent
@@ -11890,6 +11917,7 @@ function updateComponentUnionField(change) {
11890
11917
  if (displayName) input.displayName = displayName.to;
11891
11918
  if (description) input.description = description.to;
11892
11919
  if (components) input.componentApiIds = components.to;
11920
+ if (visibility) input.visibility = visibility.to;
11893
11921
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
11894
11922
  if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
11895
11923
  if (position) input.position = position.to;
@@ -12452,13 +12480,14 @@ const RESOURCE_TITLES = {
12452
12480
  remoteSource: "Remote sources",
12453
12481
  component: "Components",
12454
12482
  model: "Models",
12483
+ sidebarElement: "Sidebars",
12455
12484
  field: "Fields"
12456
12485
  };
12457
12486
  /**
12458
12487
  * The order the sections are listed in: locales and stages first, an
12459
12488
  * enumeration before its values, a taxonomy before its nodes, a model or
12460
12489
  * component before its fields, enumerations, taxonomies and remote sources
12461
- * before the fields that use them.
12490
+ * before the fields that use them, a model before its sidebar.
12462
12491
  */
12463
12492
  const RESOURCES = [
12464
12493
  "locale",
@@ -12470,6 +12499,7 @@ const RESOURCES = [
12470
12499
  "remoteSource",
12471
12500
  "component",
12472
12501
  "model",
12502
+ "sidebarElement",
12473
12503
  "field"
12474
12504
  ];
12475
12505
  /**
@@ -12526,6 +12556,7 @@ function operation(change) {
12526
12556
  case "remoteSource": return remoteSourceOperation(change);
12527
12557
  case "component": return `${change.action}Component`;
12528
12558
  case "model": return `${change.action}Model`;
12559
+ case "sidebarElement": return `${change.action}SidebarElement`;
12529
12560
  case "field": return fieldOperation(change);
12530
12561
  }
12531
12562
  }
@@ -12540,6 +12571,7 @@ function renderChangeLine(change, width, colors) {
12540
12571
  case "remoteSource": return renderRemoteSourceChange(change, width, colors);
12541
12572
  case "component": return renderComponentChange(change, width, colors);
12542
12573
  case "model": return renderModelChange(change, width, colors);
12574
+ case "sidebarElement": return renderSidebarElementChange(change, width, colors);
12543
12575
  case "field": return renderFieldChange(change, width, colors);
12544
12576
  }
12545
12577
  }
@@ -12777,6 +12809,61 @@ function renderModelChange(change, width, colors) {
12777
12809
  case "delete": return [` ${colors.red(`- ${op}`)} ${change.apiId} ${colors.yellow(`⚠ deletes the model and all its entries`)}`];
12778
12810
  }
12779
12811
  }
12812
+ /**
12813
+ * A panel is named by its model and its type, an app panel by its app and
12814
+ * element: `Post PREVIEW_URLS`, `Post app seo/panel`. Removing a panel
12815
+ * keeps all content.
12816
+ */
12817
+ function renderSidebarElementChange(change, width, colors) {
12818
+ const op = operation(change).padEnd(width);
12819
+ const subject = `${change.model} ${panelName(change.element)}`;
12820
+ switch (change.action) {
12821
+ case "create": return [` ${colors.green(`+ ${op}`)} ${subject}`, ...renderRows(panelRows(change.element), colors)];
12822
+ case "update": return [` ${colors.yellow(`~ ${op}`)} ${subject}`, ...renderAttributes(change.changes, colors)];
12823
+ case "delete": return [` ${colors.red(`- ${op}`)} ${subject}`];
12824
+ }
12825
+ }
12826
+ function panelName(element) {
12827
+ switch (element.kind) {
12828
+ case "system": return element.type;
12829
+ case "previewUrls": return "PREVIEW_URLS";
12830
+ case "app": return `app ${element.appApiId}/${element.appElementApiId}`;
12831
+ }
12832
+ }
12833
+ /** A created panel's settings, those at their default left out. */
12834
+ function panelRows(element) {
12835
+ switch (element.kind) {
12836
+ case "system": return [];
12837
+ case "previewUrls": return [
12838
+ {
12839
+ attribute: "previewUrls",
12840
+ text: value(element.previewUrls)
12841
+ },
12842
+ ...element.variantPreviewUrls === null ? [] : [{
12843
+ attribute: "variantPreviewUrls",
12844
+ text: value(element.variantPreviewUrls)
12845
+ }],
12846
+ ...element.openInNewTab ? [{
12847
+ attribute: "openInNewTab",
12848
+ text: value(true)
12849
+ }] : []
12850
+ ];
12851
+ case "app": return [
12852
+ {
12853
+ attribute: "displayName",
12854
+ text: value(element.displayName)
12855
+ },
12856
+ ...element.description === null ? [] : [{
12857
+ attribute: "description",
12858
+ text: value(element.description)
12859
+ }],
12860
+ ...element.config === null ? [] : [{
12861
+ attribute: "config",
12862
+ text: settingsText(element.config)
12863
+ }]
12864
+ ];
12865
+ }
12866
+ }
12780
12867
  /** A field is named by its model or component and its apiId: `Post.featured`. */
12781
12868
  function renderFieldChange(change, width, colors) {
12782
12869
  const op = operation(change).padEnd(width);
@@ -12916,6 +13003,10 @@ function changeRow(attribute, change) {
12916
13003
  attribute: "renderer",
12917
13004
  text: `${rendererText(from)} → ${rendererText(to)}`
12918
13005
  };
13006
+ if (attribute === "config") return {
13007
+ attribute,
13008
+ text: `${settingsText(from)} → ${settingsText(to)}`
13009
+ };
12919
13010
  if (!NESTED.has(attribute) || !(isRecord$1(from) || isRecord$1(to))) {
12920
13011
  const text = (side) => side === null ? NULL_TEXT[attribute] ?? value(side) : value(side);
12921
13012
  return {
@@ -12959,6 +13050,10 @@ function rendererText(renderer) {
12959
13050
  const config = app.config === null ? "" : ` ${JSON.stringify(app.config)}`;
12960
13051
  return `app ${app.appApiId}/${app.appElementApiId}${config}`;
12961
13052
  }
13053
+ /** An app's settings on one line, nulls kept, as `rendererText` shows them. */
13054
+ function settingsText(config) {
13055
+ return config === null ? "(none)" : JSON.stringify(config);
13056
+ }
12962
13057
  function isRecord$1(value) {
12963
13058
  return typeof value === "object" && value !== null && !Array.isArray(value);
12964
13059
  }
@@ -13211,6 +13306,42 @@ const richTextFieldSchema = strictObject({
13211
13306
  renamedFrom: string$1().nullable()
13212
13307
  });
13213
13308
  //#endregion
13309
+ //#region src/define/resources/sidebar.zod.ts
13310
+ /** Shared by the model's schema and by the plan artifact. */
13311
+ const systemSidebarElementTypeSchema = _enum([
13312
+ "AGENTS",
13313
+ "CONTENT_WORKFLOWS",
13314
+ "INFORMATION",
13315
+ "LOCALIZATIONS",
13316
+ "RELEASES",
13317
+ "STAGES",
13318
+ "TAGS",
13319
+ "VARIANTS",
13320
+ "VERSIONS"
13321
+ ]);
13322
+ /** Shared by the model's schema and by the plan artifact. */
13323
+ const previewUrlSchema$1 = strictObject({
13324
+ name: string$1(),
13325
+ template: string$1()
13326
+ });
13327
+ const sidebarElementSchema$1 = union([
13328
+ strictObject({ element: systemSidebarElementTypeSchema }),
13329
+ strictObject({
13330
+ element: literal("PREVIEW_URLS"),
13331
+ previewUrls: array(previewUrlSchema$1),
13332
+ variantPreviewUrls: array(previewUrlSchema$1),
13333
+ openInNewTab: boolean()
13334
+ }),
13335
+ strictObject({
13336
+ element: literal("app"),
13337
+ appApiId: string$1(),
13338
+ appElementApiId: string$1(),
13339
+ displayName: string$1(),
13340
+ description: string$1().nullable(),
13341
+ config: record(string$1(), json())
13342
+ })
13343
+ ]);
13344
+ //#endregion
13214
13345
  //#region src/define/resources/stage.zod.ts
13215
13346
  /** Shared by the stage's schema and by the plan artifact. */
13216
13347
  const stageColorSchema = _enum([
@@ -13794,6 +13925,118 @@ const fieldRefSchema = strictObject({
13794
13925
  parent: string$1(),
13795
13926
  apiId: string$1()
13796
13927
  });
13928
+ const fieldChangeSchema = discriminatedUnion("action", [
13929
+ strictObject({
13930
+ action: literal("create"),
13931
+ resource: literal("field"),
13932
+ parent: string$1(),
13933
+ field: fieldSchema$1,
13934
+ migrationValue: migrationValueSchema.optional(),
13935
+ partner: referenceTwoWayFieldSchema$1.optional(),
13936
+ members: array(strictObject({
13937
+ parent: string$1(),
13938
+ field: referenceUnionMemberFieldSchema$1
13939
+ })).optional(),
13940
+ memberName: string$1().optional()
13941
+ }),
13942
+ discriminatedUnion("kind", [strictObject({
13943
+ action: literal("update"),
13944
+ resource: literal("field"),
13945
+ parent: string$1(),
13946
+ apiId: string$1(),
13947
+ kind: _enum([
13948
+ "boolean",
13949
+ "string",
13950
+ "date",
13951
+ "dateTime",
13952
+ "int",
13953
+ "float",
13954
+ "enumeration",
13955
+ "taxonomy",
13956
+ "json",
13957
+ "richText",
13958
+ "color",
13959
+ "location",
13960
+ "component",
13961
+ "componentUnion",
13962
+ "referenceOneWay",
13963
+ "referenceTwoWay",
13964
+ "referenceUnion",
13965
+ "referenceUnionMember",
13966
+ "asset",
13967
+ "remote"
13968
+ ]),
13969
+ changes: strictObject({
13970
+ apiId: attributeChangeSchema(string$1()),
13971
+ formRenderer: attributeChangeSchema(union([stringFormRendererSchema, appRendererSchema]).nullable()),
13972
+ displayName: attributeChangeSchema(string$1()),
13973
+ description: attributeChangeSchema(string$1().nullable()),
13974
+ required: attributeChangeSchema(boolean()),
13975
+ unique: attributeChangeSchema(boolean()),
13976
+ localized: attributeChangeSchema(boolean()),
13977
+ title: attributeChangeSchema(boolean()),
13978
+ visibility: attributeChangeSchema(fieldVisibilitySchema),
13979
+ visibilityCondition: attributeChangeSchema(visibilityConditionSchema.nullable()),
13980
+ variantEnabled: attributeChangeSchema(boolean()),
13981
+ initialValue: attributeChangeSchema(initialValueSchema),
13982
+ position: attributeChangeSchema(number()),
13983
+ validations: attributeChangeSchema(union([stringValidationRulesSchema$1, numberValidationRulesSchema]).nullable()),
13984
+ slug: attributeChangeSchema(slugSettingsSchema.nullable()),
13985
+ components: attributeChangeSchema(array(string$1())),
13986
+ to: attributeChangeSchema(array(string$1())),
13987
+ rules: attributeChangeSchema(referenceRulesSchema.nullable()),
13988
+ embeds: attributeChangeSchema(array(string$1()).nullable()),
13989
+ actions: attributeChangeSchema(richTextActionsSchema.nullable()),
13990
+ source: attributeChangeSchema(string$1()),
13991
+ returnType: attributeChangeSchema(string$1()),
13992
+ method: attributeChangeSchema(remoteFieldMethodSchema),
13993
+ query: attributeChangeSchema(string$1().nullable()),
13994
+ path: attributeChangeSchema(string$1().nullable()),
13995
+ headers: attributeChangeSchema(remoteHeadersSchema.nullable()),
13996
+ forwardClientHeaders: attributeChangeSchema(boolean()),
13997
+ cacheTTLSeconds: attributeChangeSchema(number()),
13998
+ args: attributeChangeSchema(array(remoteFieldArgSchema))
13999
+ }).partial(),
14000
+ migrationValue: migrationValueSchema.optional(),
14001
+ memberPositions: record(string$1(), number()).optional()
14002
+ }), strictObject({
14003
+ action: literal("update"),
14004
+ resource: literal("field"),
14005
+ parent: string$1(),
14006
+ apiId: string$1(),
14007
+ kind: literal("unsupported"),
14008
+ type: string$1(),
14009
+ changes: strictObject({ position: attributeChangeSchema(number()) })
14010
+ })]),
14011
+ strictObject({
14012
+ action: literal("delete"),
14013
+ resource: literal("field"),
14014
+ parent: string$1(),
14015
+ apiId: string$1(),
14016
+ partner: fieldRefSchema.optional(),
14017
+ members: array(fieldRefSchema).optional()
14018
+ })
14019
+ ]);
14020
+ const sidebarElementSchema = discriminatedUnion("kind", [
14021
+ strictObject({
14022
+ kind: literal("system"),
14023
+ type: systemSidebarElementTypeSchema
14024
+ }),
14025
+ strictObject({
14026
+ kind: literal("previewUrls"),
14027
+ previewUrls: array(previewUrlSchema$1),
14028
+ variantPreviewUrls: array(previewUrlSchema$1).nullable(),
14029
+ openInNewTab: boolean()
14030
+ }),
14031
+ strictObject({
14032
+ kind: literal("app"),
14033
+ appApiId: string$1(),
14034
+ appElementApiId: string$1(),
14035
+ displayName: string$1(),
14036
+ description: string$1().nullable(),
14037
+ config: record(string$1(), json()).nullable()
14038
+ })
14039
+ ]);
13797
14040
  const changeSchema = discriminatedUnion("resource", [
13798
14041
  localeChangeSchema,
13799
14042
  stageChangeSchema,
@@ -13807,95 +14050,34 @@ const changeSchema = discriminatedUnion("resource", [
13807
14050
  discriminatedUnion("action", [
13808
14051
  strictObject({
13809
14052
  action: literal("create"),
13810
- resource: literal("field"),
13811
- parent: string$1(),
13812
- field: fieldSchema$1,
13813
- migrationValue: migrationValueSchema.optional(),
13814
- partner: referenceTwoWayFieldSchema$1.optional(),
13815
- members: array(strictObject({
13816
- parent: string$1(),
13817
- field: referenceUnionMemberFieldSchema$1
13818
- })).optional(),
13819
- memberName: string$1().optional()
14053
+ resource: literal("sidebarElement"),
14054
+ model: string$1(),
14055
+ element: sidebarElementSchema
13820
14056
  }),
13821
- discriminatedUnion("kind", [strictObject({
14057
+ strictObject({
13822
14058
  action: literal("update"),
13823
- resource: literal("field"),
13824
- parent: string$1(),
13825
- apiId: string$1(),
13826
- kind: _enum([
13827
- "boolean",
13828
- "string",
13829
- "date",
13830
- "dateTime",
13831
- "int",
13832
- "float",
13833
- "enumeration",
13834
- "taxonomy",
13835
- "json",
13836
- "richText",
13837
- "color",
13838
- "location",
13839
- "component",
13840
- "componentUnion",
13841
- "referenceOneWay",
13842
- "referenceTwoWay",
13843
- "referenceUnion",
13844
- "referenceUnionMember",
13845
- "asset",
13846
- "remote"
13847
- ]),
14059
+ resource: literal("sidebarElement"),
14060
+ model: string$1(),
14061
+ element: sidebarElementSchema,
13848
14062
  changes: strictObject({
13849
- apiId: attributeChangeSchema(string$1()),
13850
- formRenderer: attributeChangeSchema(union([stringFormRendererSchema, appRendererSchema]).nullable()),
14063
+ position: attributeChangeSchema(number()),
14064
+ previewUrls: attributeChangeSchema(array(previewUrlSchema$1)),
14065
+ variantPreviewUrls: attributeChangeSchema(array(previewUrlSchema$1).nullable()),
14066
+ openInNewTab: attributeChangeSchema(boolean()),
13851
14067
  displayName: attributeChangeSchema(string$1()),
13852
14068
  description: attributeChangeSchema(string$1().nullable()),
13853
- required: attributeChangeSchema(boolean()),
13854
- unique: attributeChangeSchema(boolean()),
13855
- localized: attributeChangeSchema(boolean()),
13856
- title: attributeChangeSchema(boolean()),
13857
- visibility: attributeChangeSchema(fieldVisibilitySchema),
13858
- visibilityCondition: attributeChangeSchema(visibilityConditionSchema.nullable()),
13859
- variantEnabled: attributeChangeSchema(boolean()),
13860
- initialValue: attributeChangeSchema(initialValueSchema),
13861
- position: attributeChangeSchema(number()),
13862
- validations: attributeChangeSchema(union([stringValidationRulesSchema$1, numberValidationRulesSchema]).nullable()),
13863
- slug: attributeChangeSchema(slugSettingsSchema.nullable()),
13864
- components: attributeChangeSchema(array(string$1())),
13865
- to: attributeChangeSchema(array(string$1())),
13866
- rules: attributeChangeSchema(referenceRulesSchema.nullable()),
13867
- embeds: attributeChangeSchema(array(string$1()).nullable()),
13868
- actions: attributeChangeSchema(richTextActionsSchema.nullable()),
13869
- source: attributeChangeSchema(string$1()),
13870
- returnType: attributeChangeSchema(string$1()),
13871
- method: attributeChangeSchema(remoteFieldMethodSchema),
13872
- query: attributeChangeSchema(string$1().nullable()),
13873
- path: attributeChangeSchema(string$1().nullable()),
13874
- headers: attributeChangeSchema(remoteHeadersSchema.nullable()),
13875
- forwardClientHeaders: attributeChangeSchema(boolean()),
13876
- cacheTTLSeconds: attributeChangeSchema(number()),
13877
- args: attributeChangeSchema(array(remoteFieldArgSchema))
14069
+ config: attributeChangeSchema(record(string$1(), json()).nullable())
13878
14070
  }).partial(),
13879
- migrationValue: migrationValueSchema.optional(),
13880
- memberPositions: record(string$1(), number()).optional()
13881
- }), strictObject({
13882
- action: literal("update"),
13883
- resource: literal("field"),
13884
- parent: string$1(),
13885
- apiId: string$1(),
13886
- kind: literal("unsupported"),
13887
- type: string$1(),
13888
- changes: strictObject({ position: attributeChangeSchema(number()) })
13889
- })]),
14071
+ title: string$1().optional()
14072
+ }),
13890
14073
  strictObject({
13891
14074
  action: literal("delete"),
13892
- resource: literal("field"),
13893
- parent: string$1(),
13894
- apiId: string$1(),
13895
- partner: fieldRefSchema.optional(),
13896
- members: array(fieldRefSchema).optional()
14075
+ resource: literal("sidebarElement"),
14076
+ model: string$1(),
14077
+ element: sidebarElementSchema
13897
14078
  })
13898
- ])
14079
+ ]),
14080
+ fieldChangeSchema
13899
14081
  ]);
13900
14082
  const planSchema = strictObject({
13901
14083
  formatVersion: literal(1),
@@ -14035,6 +14217,150 @@ function examples(rows) {
14035
14217
  ].join("\n");
14036
14218
  }
14037
14219
  //#endregion
14220
+ //#region src/diff/resources/sidebar.ts
14221
+ /**
14222
+ * The changes that take a model's sidebar from `from` to `to`. A panel is
14223
+ * matched by its type, or an app panel by its app and element. Deletes
14224
+ * come first, so a created app panel may take the title of a deleted one.
14225
+ * Creates follow in the config's order, then the updates of settings, then
14226
+ * the moves. `oldTitles` are the live titles of Hygraph's panels that
14227
+ * differ from today's, which an update of such a panel carries.
14228
+ */
14229
+ function diffSidebar(model, from, to, oldTitles = {}) {
14230
+ const fromElements = new Map(from.map((element) => [sidebarElementKey(element), element]));
14231
+ const toKeys = new Set(to.map(sidebarElementKey));
14232
+ const ordered = to.toSorted((a, b) => a.position - b.position);
14233
+ const changes = {
14234
+ deletes: from.filter((element) => !toKeys.has(sidebarElementKey(element))).map((element) => ({
14235
+ action: "delete",
14236
+ resource: "sidebarElement",
14237
+ model,
14238
+ element: attributes$4(element)
14239
+ })),
14240
+ creates: [],
14241
+ updates: [],
14242
+ moves: []
14243
+ };
14244
+ for (const element of ordered) {
14245
+ const fromElement = fromElements.get(sidebarElementKey(element));
14246
+ if (!fromElement) {
14247
+ changes.creates.push({
14248
+ action: "create",
14249
+ resource: "sidebarElement",
14250
+ model,
14251
+ element: attributes$4(element)
14252
+ });
14253
+ continue;
14254
+ }
14255
+ const settings = diffSidebarElement(fromElement, element);
14256
+ if (Object.keys(settings).length > 0) changes.updates.push({
14257
+ action: "update",
14258
+ resource: "sidebarElement",
14259
+ model,
14260
+ element: attributes$4(element),
14261
+ changes: settings
14262
+ });
14263
+ }
14264
+ changes.moves = moves$1(model, from, ordered, toKeys);
14265
+ for (const update of [...changes.updates, ...changes.moves]) {
14266
+ const title = oldTitles[sidebarElementKey(update.element)];
14267
+ if (title !== void 0) update.title = title;
14268
+ }
14269
+ return changes;
14270
+ }
14271
+ /**
14272
+ * The settings of `to` that differ from `from`, each with both values.
14273
+ * Position is left out: moves are worked out for the whole sidebar.
14274
+ */
14275
+ function diffSidebarElement(from, to) {
14276
+ const changes = {};
14277
+ if (from.kind === "previewUrls" && to.kind === "previewUrls") {
14278
+ if (!isDeepStrictEqual(from.previewUrls, to.previewUrls)) changes.previewUrls = {
14279
+ from: from.previewUrls,
14280
+ to: to.previewUrls
14281
+ };
14282
+ if (!isDeepStrictEqual(from.variantPreviewUrls, to.variantPreviewUrls)) changes.variantPreviewUrls = {
14283
+ from: from.variantPreviewUrls,
14284
+ to: to.variantPreviewUrls
14285
+ };
14286
+ if (from.openInNewTab !== to.openInNewTab) changes.openInNewTab = {
14287
+ from: from.openInNewTab,
14288
+ to: to.openInNewTab
14289
+ };
14290
+ }
14291
+ if (from.kind === "app" && to.kind === "app") {
14292
+ if (from.displayName !== to.displayName) changes.displayName = {
14293
+ from: from.displayName,
14294
+ to: to.displayName
14295
+ };
14296
+ if (from.description !== to.description) changes.description = {
14297
+ from: from.description,
14298
+ to: to.description
14299
+ };
14300
+ if (!isDeepStrictEqual(from.config, to.config)) changes.config = {
14301
+ from: from.config,
14302
+ to: to.config
14303
+ };
14304
+ }
14305
+ return changes;
14306
+ }
14307
+ /**
14308
+ * The moves that put the panels in the config's order. Plays the migration
14309
+ * through as the server numbers the panels before every move: the deleted
14310
+ * panels gone, the created ones last. Then moves each panel into its
14311
+ * place, last to first, so a move never shifts a panel already in place.
14312
+ * The first panel is then in place without a move: the batch drops a move
14313
+ * to 0.
14314
+ */
14315
+ function moves$1(model, from, ordered, toKeys) {
14316
+ const fromKeys = new Set(from.map(sidebarElementKey));
14317
+ const playing = [...from.toSorted((a, b) => a.position - b.position).map(sidebarElementKey).filter((key) => toKeys.has(key)), ...ordered.map(sidebarElementKey).filter((key) => !fromKeys.has(key))];
14318
+ const changes = [];
14319
+ for (let index = ordered.length - 1; index > 0; index--) {
14320
+ const element = ordered[index];
14321
+ const key = sidebarElementKey(element);
14322
+ const current = playing.indexOf(key);
14323
+ if (current === index) continue;
14324
+ playing.splice(current, 1);
14325
+ playing.splice(index, 0, key);
14326
+ changes.push({
14327
+ action: "update",
14328
+ resource: "sidebarElement",
14329
+ model,
14330
+ element: attributes$4(element),
14331
+ changes: { position: {
14332
+ from: current,
14333
+ to: index
14334
+ } }
14335
+ });
14336
+ }
14337
+ return changes;
14338
+ }
14339
+ function attributes$4(element) {
14340
+ const { position: _position, ...rest } = element;
14341
+ return rest;
14342
+ }
14343
+ /**
14344
+ * The panels Hygraph gives a model it creates, as live reads them back:
14345
+ * its default set, and Tags in a project with Tags turned on, which is one
14346
+ * whose environments have the `EntryTag` taxonomy.
14347
+ */
14348
+ function newModelSidebar(tags) {
14349
+ return [
14350
+ "INFORMATION",
14351
+ "RELEASES",
14352
+ "STAGES",
14353
+ "LOCALIZATIONS",
14354
+ "VERSIONS",
14355
+ "AGENTS",
14356
+ ...tags ? ["TAGS"] : []
14357
+ ].map((type, position) => ({
14358
+ kind: "system",
14359
+ type,
14360
+ position
14361
+ })).toSorted(bySidebarElementKey);
14362
+ }
14363
+ //#endregion
14038
14364
  //#region src/live/resources/simple.zod.ts
14039
14365
  const liveVisibilityConditionSchema = object$1({
14040
14366
  baseField: string$1(),
@@ -14191,6 +14517,44 @@ function parseJSON(text) {
14191
14517
  }
14192
14518
  }
14193
14519
  //#endregion
14520
+ //#region src/live/resources/unsupported.zod.ts
14521
+ /** Not strict, as every live schema: the IR reads only the slot. */
14522
+ const createUnsupportedFieldSchema = object$1({
14523
+ apiId: string$1(),
14524
+ parentApiId: string$1(),
14525
+ position: number()
14526
+ });
14527
+ const createUnsupportedSimpleFieldSchema = object$1({
14528
+ apiId: string$1(),
14529
+ parentApiId: string$1(),
14530
+ position: number(),
14531
+ type: string$1()
14532
+ });
14533
+ const createRelationalFieldSchema = object$1({
14534
+ apiId: string$1(),
14535
+ parentApiId: string$1(),
14536
+ position: number(),
14537
+ type: string$1(),
14538
+ reverseField: object$1({
14539
+ apiId: string$1(),
14540
+ modelApiId: string$1(),
14541
+ position: number(),
14542
+ isUnidirectional: boolean().nullish()
14543
+ })
14544
+ });
14545
+ const createUnionFieldSchema = object$1({
14546
+ apiId: string$1(),
14547
+ parentApiId: string$1(),
14548
+ position: number(),
14549
+ reverseField: object$1({
14550
+ apiId: string$1(),
14551
+ positions: array(object$1({
14552
+ modelApiId: string$1(),
14553
+ position: number()
14554
+ }))
14555
+ })
14556
+ });
14557
+ //#endregion
14194
14558
  //#region src/live/resources/asset.ts
14195
14559
  /**
14196
14560
  * An asset field, in the same canonical form `convertAssetFieldToIR` gives
@@ -14254,6 +14618,25 @@ function convertCreateAssetFieldToIR(input, components) {
14254
14618
  }
14255
14619
  }];
14256
14620
  }
14621
+ /**
14622
+ * Every name on Asset that a relation's other side has, with the field it
14623
+ * is the other side of. A component's asset field has a hidden one, which
14624
+ * no IR holds. Renaming the field keeps the name.
14625
+ */
14626
+ function findFieldsBackOnAsset(ops) {
14627
+ return ops.flatMap((op) => {
14628
+ const parsed = createRelationalFieldSchema.safeParse(op.createRelationalField);
14629
+ if (!parsed.success || parsed.data.reverseField.modelApiId !== "Asset") return [];
14630
+ const { apiId, parentApiId, reverseField } = parsed.data;
14631
+ return [{
14632
+ apiId: reverseField.apiId,
14633
+ field: {
14634
+ parent: parentApiId,
14635
+ apiId
14636
+ }
14637
+ }];
14638
+ });
14639
+ }
14257
14640
  //#endregion
14258
14641
  //#region src/live/resources/boolean.zod.ts
14259
14642
  const createBooleanFieldSchema = object$1({
@@ -14674,7 +15057,11 @@ const createModelSchema = object$1({
14674
15057
  });
14675
15058
  //#endregion
14676
15059
  //#region src/live/resources/model.ts
14677
- /** The same canonical form `convertModelToIR` gives a model from the config. */
15060
+ /**
15061
+ * The same canonical form `convertModelToIR` gives a model from the config.
15062
+ * `schemaDefinition` leaves Hygraph's panels out, so `sidebar` is read
15063
+ * apart from it and is `null` here.
15064
+ */
14678
15065
  function convertCreateModelToIR(input) {
14679
15066
  const parsed = createModelSchema.safeParse(input);
14680
15067
  if (!parsed.success) throw new Error(`Invalid createModel params: \n${renderIssues(parsed.error.issues)}`);
@@ -14684,7 +15071,8 @@ function convertCreateModelToIR(input) {
14684
15071
  apiIdPlural: createModel.apiIdPlural,
14685
15072
  displayName: createModel.displayName,
14686
15073
  description: isEmpty(createModel.description) ? null : createModel.description,
14687
- fields: {}
15074
+ fields: {},
15075
+ sidebar: null
14688
15076
  };
14689
15077
  }
14690
15078
  //#endregion
@@ -15053,7 +15441,7 @@ function convertCreateRichTextFieldToIR(input, models) {
15053
15441
  if (!editor.supported) return null;
15054
15442
  const { formRenderer } = editor;
15055
15443
  const op = formRenderer === null ? input : withoutFormConfig(input);
15056
- if (!isSupported$1(op, models)) return null;
15444
+ if (!isSupported$2(op, models)) return null;
15057
15445
  const parsed = createRichTextFieldSchema.safeParse(op);
15058
15446
  if (!parsed.success) throw new Error(`Invalid createSimpleField params: \n${renderIssues(parsed.error.issues)}`);
15059
15447
  const field = parsed.data;
@@ -15102,7 +15490,7 @@ function withoutFormConfig(input) {
15102
15490
  * renderer is `GCMS`, or none in an op the batch wrote. An app's, which
15103
15491
  * `convertRendererToIR` reads, is taken out of the op before it gets here.
15104
15492
  */
15105
- function isSupported$1(input, models) {
15493
+ function isSupported$2(input, models) {
15106
15494
  const setup = richTextSetupSchema.safeParse(input);
15107
15495
  if (!setup.success) return false;
15108
15496
  const { formRenderer, formConfig, embedsEnabled, embeddableModels } = setup.data;
@@ -15150,7 +15538,7 @@ const SUPPORTED = [
15150
15538
  "GCMS_MARKDOWN",
15151
15539
  "GCMS_SLUG"
15152
15540
  ];
15153
- function isSupported(renderer) {
15541
+ function isSupported$1(renderer) {
15154
15542
  return SUPPORTED.some((supported) => supported === renderer);
15155
15543
  }
15156
15544
  /**
@@ -15172,7 +15560,7 @@ function editorOf(input) {
15172
15560
  if (!editor.supported) return null;
15173
15561
  if (editor.formRenderer !== null) return editor.formRenderer;
15174
15562
  const renderer = rendererOf(input);
15175
- return isSupported(renderer) ? renderer : null;
15563
+ return isSupported$1(renderer) ? renderer : null;
15176
15564
  }
15177
15565
  /**
15178
15566
  * The same canonical form `convertStringFieldToIR` gives a field from the
@@ -15453,44 +15841,6 @@ function fieldParents(environment) {
15453
15841
  return [...environment.models, ...environment.asset ? [environment.asset] : []];
15454
15842
  }
15455
15843
  //#endregion
15456
- //#region src/live/resources/unsupported.zod.ts
15457
- /** Not strict, as every live schema: the IR reads only the slot. */
15458
- const createUnsupportedFieldSchema = object$1({
15459
- apiId: string$1(),
15460
- parentApiId: string$1(),
15461
- position: number()
15462
- });
15463
- const createUnsupportedSimpleFieldSchema = object$1({
15464
- apiId: string$1(),
15465
- parentApiId: string$1(),
15466
- position: number(),
15467
- type: string$1()
15468
- });
15469
- const createRelationalFieldSchema = object$1({
15470
- apiId: string$1(),
15471
- parentApiId: string$1(),
15472
- position: number(),
15473
- type: string$1(),
15474
- reverseField: object$1({
15475
- apiId: string$1(),
15476
- modelApiId: string$1(),
15477
- position: number(),
15478
- isUnidirectional: boolean().nullish()
15479
- })
15480
- });
15481
- const createUnionFieldSchema = object$1({
15482
- apiId: string$1(),
15483
- parentApiId: string$1(),
15484
- position: number(),
15485
- reverseField: object$1({
15486
- apiId: string$1(),
15487
- positions: array(object$1({
15488
- modelApiId: string$1(),
15489
- position: number()
15490
- }))
15491
- })
15492
- });
15493
- //#endregion
15494
15844
  //#region src/live/resources/unsupported.ts
15495
15845
  /** A field op the CLI does not read, as the slot it holds. */
15496
15846
  function convertCreateUnsupportedFieldToIR(operation, input, type) {
@@ -15779,6 +16129,101 @@ function convertLocalesToIR(locales) {
15779
16129
  })).toSorted(byApiId$1);
15780
16130
  }
15781
16131
  //#endregion
16132
+ //#region src/live/resources/sidebar.zod.ts
16133
+ const previewUrlSchema = object$1({
16134
+ name: string$1(),
16135
+ template: string$1()
16136
+ });
16137
+ const previewUrlsConfigSchema = object$1({
16138
+ preview_urls: array(previewUrlSchema).nullish(),
16139
+ variant_preview_urls: array(previewUrlSchema).nullish(),
16140
+ open_preview_in_new_tab: boolean().nullish()
16141
+ });
16142
+ //#endregion
16143
+ //#region src/live/resources/sidebar.ts
16144
+ /**
16145
+ * The same canonical form `convertSidebarToIR` gives the config's sidebar.
16146
+ * Read from `contentModel.models`, not from `schemaDefinition`: its
16147
+ * `createModel` ops hold app panels only.
16148
+ *
16149
+ * Panels are numbered 0, 1, 2… in the order Hygraph stores, a tie in the
16150
+ * order they were made, as the server numbers them before a move. So the
16151
+ * gaps a new model's panels have are not a move. A panel of a legacy UI
16152
+ * extension is left out: the CLI cannot write one. `model` names the model
16153
+ * in an error.
16154
+ */
16155
+ function convertSidebarToIR(model, elements) {
16156
+ return elements.filter(isSupported).toSorted((a, b) => a.position - b.position || Date.parse(a.createdAt) - Date.parse(b.createdAt)).map((element, position) => convertSidebarElementToIR(model, element, position)).toSorted(bySidebarElementKey);
16157
+ }
16158
+ /**
16159
+ * Whether the model has a panel the CLI cannot read: one of a legacy UI
16160
+ * extension, or of an app that is no longer installed. Hygraph counts it
16161
+ * in the positions of the others.
16162
+ */
16163
+ function hasUnsupportedSidebarElement(elements) {
16164
+ return !elements.every(isSupported);
16165
+ }
16166
+ function isSupported(element) {
16167
+ return element.__typename === "SystemSidebarElement" || element.__typename === "AppSidebarElement";
16168
+ }
16169
+ function convertSidebarElementToIR(model, element, position) {
16170
+ switch (element.__typename) {
16171
+ case "SystemSidebarElement": return element.type === "PREVIEW_URLS" ? convertPreviewUrlsToIR(model, element.config, position) : {
16172
+ kind: "system",
16173
+ type: element.type,
16174
+ position
16175
+ };
16176
+ case "AppSidebarElement": return {
16177
+ kind: "app",
16178
+ appApiId: element.appElement.app.apiId,
16179
+ appElementApiId: element.appElement.apiId,
16180
+ displayName: element.displayName,
16181
+ description: isEmpty(element.description) ? null : element.description,
16182
+ config: element.config === null || Object.keys(element.config).length === 0 ? null : element.config,
16183
+ position
16184
+ };
16185
+ }
16186
+ }
16187
+ /**
16188
+ * A panel without links reads as one with none: the batch saves an update
16189
+ * without checking its links, and the next plan writes the config's.
16190
+ */
16191
+ function convertPreviewUrlsToIR(model, config, position) {
16192
+ const parsed = previewUrlsConfigSchema.safeParse(config ?? {});
16193
+ if (!parsed.success) throw new Error(`Invalid PREVIEW_URLS config on model "${model}": \n${renderIssues(parsed.error.issues)}`);
16194
+ const { preview_urls, variant_preview_urls, open_preview_in_new_tab } = parsed.data;
16195
+ return {
16196
+ kind: "previewUrls",
16197
+ previewUrls: (preview_urls ?? []).map(previewUrl),
16198
+ variantPreviewUrls: variant_preview_urls === void 0 || variant_preview_urls === null || variant_preview_urls.length === 0 ? null : variant_preview_urls.map(previewUrl),
16199
+ openInNewTab: open_preview_in_new_tab ?? false,
16200
+ position
16201
+ };
16202
+ }
16203
+ function previewUrl({ name, template }) {
16204
+ return {
16205
+ name,
16206
+ template
16207
+ };
16208
+ }
16209
+ /**
16210
+ * The titles live gives Hygraph's panels where they differ from the ones
16211
+ * Hygraph gives a panel today, by `sidebarElementKey`. The batch finds a
16212
+ * panel by its title, and Hygraph never renamed the panels it made before
16213
+ * a title changed: Entry information was Document information until
16214
+ * 2022.
16215
+ */
16216
+ function readOldSidebarTitles(elements) {
16217
+ return Object.fromEntries(elements.flatMap((element) => {
16218
+ if (element.__typename !== "SystemSidebarElement") return [];
16219
+ if (element.displayName === SYSTEM_SIDEBAR_DISPLAY_NAMES[element.type]) return [];
16220
+ return [[element.type === "PREVIEW_URLS" ? sidebarElementKey({ kind: "previewUrls" }) : sidebarElementKey({
16221
+ kind: "system",
16222
+ type: element.type
16223
+ }), element.displayName]];
16224
+ }));
16225
+ }
16226
+ //#endregion
15782
16227
  //#region src/live/resources/stage.ts
15783
16228
  /**
15784
16229
  * The same canonical form `convertStageToIR` gives the config's stages.
@@ -15825,7 +16270,8 @@ var LiveSchemaFailure = class extends Failure {};
15825
16270
  * locales and stages come from the same request's `contentModel`, and a
15826
16271
  * two-way relation's other side without its rules and condition, and a
15827
16272
  * union's members with the first one's settings, so they come from its
15828
- * `models`. Whether Segment exists comes from its system models.
16273
+ * `models`, as every model's sidebar does. Whether Segment exists comes
16274
+ * from its system models.
15829
16275
  */
15830
16276
  async function readLiveEnvironment(target, fetch) {
15831
16277
  if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
@@ -15845,6 +16291,7 @@ async function readLiveEnvironment(target, fetch) {
15845
16291
  const { segment, ...live } = convertSchemaDefinitionToIR(environment.schemaDefinition, partnerLookup(environment.contentModel.models), unions);
15846
16292
  const hasSegment = environment.contentModel.systemModels.some((model) => model.__typename === "SegmentModel");
15847
16293
  const components = new Set(environment.contentModel.components.map(({ apiId }) => apiId));
16294
+ const sidebars = new Map(environment.contentModel.models.map((model) => [model.apiId, convertSidebarToIR(model.apiId, model.sidebarElements)]));
15848
16295
  return {
15849
16296
  environmentId: environment.id,
15850
16297
  unsupportedPairs: findUnsupportedPairs(environment.schemaDefinition, live),
@@ -15857,10 +16304,21 @@ async function readLiveEnvironment(target, fetch) {
15857
16304
  config: element.__typename === "FieldAppElement" ? element.config : null
15858
16305
  }))
15859
16306
  })),
16307
+ fieldsBackOnAsset: findFieldsBackOnAsset(environment.schemaDefinition),
16308
+ oldSidebarTitles: Object.fromEntries(environment.contentModel.models.flatMap((model) => {
16309
+ const titles = readOldSidebarTitles(model.sidebarElements);
16310
+ return Object.keys(titles).length > 0 ? [[model.apiId, titles]] : [];
16311
+ })),
16312
+ newModelSidebar: newModelSidebar(environment.contentModel.taxonomies.some(({ apiId }) => apiId === "EntryTag")),
16313
+ modelsWithUnsupportedSidebarElements: environment.contentModel.models.filter((model) => hasUnsupportedSidebarElement(model.sidebarElements)).map(({ apiId }) => apiId),
15860
16314
  environment: {
15861
16315
  locales: convertLocalesToIR(environment.contentModel.locales),
15862
16316
  stages: convertStagesToIR(environment.contentModel.stages),
15863
16317
  ...live,
16318
+ models: live.models.map((model) => ({
16319
+ ...model,
16320
+ sidebar: sidebars.get(model.apiId) ?? []
16321
+ })),
15864
16322
  ...hasSegment && { segment: segment ?? {
15865
16323
  apiId: "Segment",
15866
16324
  fields: {}
@@ -16071,6 +16529,83 @@ function deleteModel(change) {
16071
16529
  return { apiId: change.apiId };
16072
16530
  }
16073
16531
  //#endregion
16532
+ //#region src/plan/resources/sidebar.ts
16533
+ /**
16534
+ * One sidebar change as an `updateModel` of its own, so the next one finds
16535
+ * the panels as this one left them.
16536
+ */
16537
+ function toBatchSidebarElementChange(change) {
16538
+ return { updateModel: {
16539
+ apiId: change.model,
16540
+ sidebarElementsToUpsert: upsert(change)
16541
+ } };
16542
+ }
16543
+ function upsert(change) {
16544
+ switch (change.action) {
16545
+ case "create": return create(change.element);
16546
+ case "delete": return remove(change.element);
16547
+ case "update": return { sidebarElementsToUpdate: [update(change)] };
16548
+ }
16549
+ }
16550
+ /** A created panel goes last; its move is a change of its own. */
16551
+ function create(element) {
16552
+ switch (element.kind) {
16553
+ case "system": return { systemSidebarElementsToCreate: [{ type: element.type }] };
16554
+ case "previewUrls": return { systemSidebarElementsToCreate: [{
16555
+ type: "PREVIEW_URLS",
16556
+ config: previewUrlsConfig(element)
16557
+ }] };
16558
+ case "app": return { customSidebarElementsToCreate: [{
16559
+ appApiId: element.appApiId,
16560
+ appElementApiId: element.appElementApiId,
16561
+ displayName: element.displayName,
16562
+ description: element.description,
16563
+ config: element.config ?? {}
16564
+ }] };
16565
+ }
16566
+ }
16567
+ function remove(element) {
16568
+ switch (element.kind) {
16569
+ case "system": return { systemSidebarElementsToDelete: [{ type: element.type }] };
16570
+ case "previewUrls": return { systemSidebarElementsToDelete: [{ type: "PREVIEW_URLS" }] };
16571
+ case "app": return { customSidebarElementsToDelete: [{
16572
+ appApiId: element.appApiId,
16573
+ appElementApiId: element.appElementApiId
16574
+ }] };
16575
+ }
16576
+ }
16577
+ /**
16578
+ * The batch finds the panel by its title before the update: Hygraph's own
16579
+ * by the title live gives it when that differs from today's, otherwise by
16580
+ * today's, and an app panel by its old one. It replaces
16581
+ * a preview panel's settings whole, and sends nothing for a description
16582
+ * changed to none, which it cannot clear.
16583
+ */
16584
+ function update({ element, changes, title: oldTitle }) {
16585
+ const input = { displayName: oldTitle ?? title(element, changes.displayName?.from) };
16586
+ if (changes.position) input.position = changes.position.to;
16587
+ if (element.kind === "previewUrls" && (changes.previewUrls || changes.variantPreviewUrls || changes.openInNewTab)) input.config = previewUrlsConfig(element);
16588
+ if (changes.displayName) input.newDisplayName = changes.displayName.to;
16589
+ if (changes.description && changes.description.to !== null) input.description = changes.description.to;
16590
+ if (changes.config) input.config = changes.config.to ?? {};
16591
+ return input;
16592
+ }
16593
+ function title(element, previous) {
16594
+ switch (element.kind) {
16595
+ case "system": return SYSTEM_SIDEBAR_DISPLAY_NAMES[element.type];
16596
+ case "previewUrls": return SYSTEM_SIDEBAR_DISPLAY_NAMES.PREVIEW_URLS;
16597
+ case "app": return previous ?? element.displayName;
16598
+ }
16599
+ }
16600
+ /** The settings as Studio writes them. */
16601
+ function previewUrlsConfig(element) {
16602
+ return {
16603
+ preview_urls: element.previewUrls,
16604
+ variant_preview_urls: element.variantPreviewUrls ?? [],
16605
+ open_preview_in_new_tab: element.openInNewTab
16606
+ };
16607
+ }
16608
+ //#endregion
16074
16609
  //#region src/plan/resources/stage.ts
16075
16610
  /** One stage change as the batch entry it becomes, keyed by its operation. */
16076
16611
  function toBatchStageChange(change) {
@@ -16184,6 +16719,7 @@ function toBatchChange(change) {
16184
16719
  case "remoteSource": return toBatchRemoteSourceChange(change);
16185
16720
  case "component": return toBatchComponentChange(change);
16186
16721
  case "model": return toBatchModelChange(change);
16722
+ case "sidebarElement": return toBatchSidebarElementChange(change);
16187
16723
  case "field": return toBatchFieldChange(change);
16188
16724
  }
16189
16725
  }
@@ -16203,6 +16739,12 @@ const messages = {
16203
16739
  ["model.duplicateRenamedFrom"]: (renamedFrom) => `More than one model is renamed from "${renamedFrom}".`,
16204
16740
  ["model.noTitleField"]: (apiId) => `Model "${apiId}" has no title field.`,
16205
16741
  ["model.apiIdReserved"]: (apiId) => `"${apiId}" is the apiId of a model Hygraph provides.`,
16742
+ ["model.sidebarDuplicate"]: (apiId, panel) => `Model "${apiId}" lists ${panel} more than once in sidebar.`,
16743
+ ["model.sidebarDuplicateDisplayName"]: (apiId, displayName) => `Model "${apiId}" has more than one sidebar panel titled "${displayName}".`,
16744
+ ["model.sidebarNoPreviewUrl"]: (apiId) => `The PREVIEW_URLS panel of model "${apiId}" has no previewUrls.`,
16745
+ ["model.sidebarPreviewUrlEmpty"]: (apiId, list) => `A link in ${list} of model "${apiId}"'s PREVIEW_URLS panel has an empty name or template.`,
16746
+ ["model.sidebarVariantsMissing"]: (apiId) => `Model "${apiId}" has fields with variants, and its sidebar has no VARIANTS panel. Hygraph adds the panel back whenever such a field changes.`,
16747
+ ["model.sidebarUnsupportedElement"]: (apiId) => `Model "${apiId}" has a sidebar panel the CLI cannot manage: one of a legacy UI extension, or of an app that is no longer installed. The CLI cannot place the other panels around it.`,
16206
16748
  ["systemModel.duplicate"]: (call) => `${call} is listed more than once in models.`,
16207
16749
  ["systemModel.fieldRequired"]: (apiId, field) => `Field "${field}" on ${apiId} is required. Hygraph refuses a required field on a model it provides.`,
16208
16750
  ["systemModel.fieldVariantEnabled"]: (apiId, field) => `Field "${field}" on ${apiId} has variants. Only fields of your models can have them.`,
@@ -16372,6 +16914,8 @@ const messages = {
16372
16914
  ["field.assetReverseFieldChanged"]: (parent, field, from, to) => `Asset field "${field}" on ${parent} has the field back "${from}" on Asset, and the config names "${to}".`,
16373
16915
  ["change.modelMissing"]: (action, apiId) => `Cannot ${action} model "${apiId}": it does not exist at that point of the migration.`,
16374
16916
  ["change.embedsReplaced"]: (field, models) => `Field "${field}" embeds only ${models}, which the plan deletes, and embeds a model the plan creates. It can embed the new model only after the create, and Hygraph refuses to delete a field's last embedded model before that.`,
16917
+ ["change.assetFieldBackInUse"]: (parent, field, back, holderParent, holder) => `Asset field "${field}" on ${parent} gets the field back "${back}" on Asset, a name ${nameHolder(holderParent, holder)} has.`,
16918
+ ["change.assetFieldNameInUse"]: (_parent, _field, name, holderParent, holder) => `The field "${name}" on Asset takes a name ${nameHolder(holderParent, holder)} has.`,
16375
16919
  ["change.componentMissing"]: (action, apiId) => `Cannot ${action} component "${apiId}": it does not exist at that point of the migration.`,
16376
16920
  ["change.enumerationMissing"]: (action, apiId) => `Cannot ${action} enumeration "${apiId}": it does not exist at that point of the migration.`,
16377
16921
  ["change.remoteSourceKindChanged"]: (prefix, from, to) => `Remote source "${prefix}" is ${from} in Hygraph, and the config makes it ${to}. Hygraph keeps a source's kind from when it was created.`,
@@ -16421,6 +16965,12 @@ const fixes = {
16421
16965
  ["model.duplicateRenamedFrom"]: "Keep renamedFrom on the model that continues it. The other models are created new.",
16422
16966
  ["model.noTitleField"]: "Set title: true on the field Studio should show entries by, such as a name or a heading.",
16423
16967
  ["model.apiIdReserved"]: "Use another apiId. To add fields to Asset, Query or Segment, put system.model.asset({ fields }), system.model.query({ fields }) or system.model.segment({ fields }) in models.",
16968
+ ["model.sidebarDuplicate"]: "List each panel once. A model has each of Hygraph's panels, and each app element's, at most once.",
16969
+ ["model.sidebarDuplicateDisplayName"]: "Give the app panel another displayName. Hygraph's panels are titled Entry information, Schedule, Stages, Localizations, Versions, Preview, Content workflows, Variants, Agents and Tags.",
16970
+ ["model.sidebarNoPreviewUrl"]: "Add at least one link to previewUrls, or remove the PREVIEW_URLS panel.",
16971
+ ["model.sidebarPreviewUrlEmpty"]: "Give every link a name and a template.",
16972
+ ["model.sidebarVariantsMissing"]: "Add { element: \"VARIANTS\" } to sidebar, or leave sidebar out.",
16973
+ ["model.sidebarUnsupportedElement"]: "Leave sidebar out and arrange the panels in Studio, or replace the panel with an app's panel in Studio.",
16424
16974
  ["systemModel.duplicate"]: "List it once, with all your fields on it.",
16425
16975
  ["systemModel.fieldRequired"]: "Set required: false.",
16426
16976
  ["systemModel.fieldVariantEnabled"]: "Set variantEnabled: false.",
@@ -16590,6 +17140,8 @@ const fixes = {
16590
17140
  ["field.assetReverseFieldChanged"]: (_parent, _field, from) => `To rename the field back, set renamedFrom: "${from}" on it in system.model.asset. Otherwise set reverse back to "${from}".`,
16591
17141
  ["change.modelMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a model from one place only.",
16592
17142
  ["change.embedsReplaced"]: "Create the new models in one apply. Then change embeds and delete the old models in the next.",
17143
+ ["change.assetFieldBackInUse"]: "Give the asset field another apiId. A field back on Asset keeps its name when its field is renamed, and the CLI cannot rename a component's.",
17144
+ ["change.assetFieldNameInUse"]: (parent, field) => parent === "Asset" ? "Give the field on Asset another apiId." : `Name another field back in reverse on "${field}", and give its assetReverseField on system.model.asset the same apiId.`,
16593
17145
  ["change.componentMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a component from one place only.",
16594
17146
  ["change.enumerationMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename an enumeration from one place only.",
16595
17147
  ["change.remoteSourceKindChanged"]: "Keep the kind the source has. To change it, remove the source and its remote fields from the config and apply, then add them back with the new kind and apply again.",
@@ -16630,6 +17182,10 @@ function upperFirst(text) {
16630
17182
  return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
16631
17183
  }
16632
17184
  /** The field back of an asset field, as the config declares it on Asset. */
17185
+ /** What has a name on Asset: a field there, or another field's field back. */
17186
+ function nameHolder(parent, field) {
17187
+ return parent === "Asset" ? `field "${field}" on Asset` : `the field back of "${field}" on ${parent}`;
17188
+ }
16633
17189
  function fieldBack(parent, field, back) {
16634
17190
  return `define.field.assetReverseField({ apiId: "${back}", displayName: "${back}", to: () => ${parent}, reverse: "${field}" })`;
16635
17191
  }
@@ -18537,6 +19093,67 @@ function localePath(apiId, attribute) {
18537
19093
  ];
18538
19094
  }
18539
19095
  //#endregion
19096
+ //#region src/define/resources/sidebar.validation.ts
19097
+ /**
19098
+ * What the server refuses in a model's sidebar: a panel twice, two panels
19099
+ * with one title, and a preview panel without links or with an empty one.
19100
+ */
19101
+ function validateSidebar(model, sidebar) {
19102
+ const validations = [];
19103
+ const keys = /* @__PURE__ */ new Set();
19104
+ const titles = new Set(sidebar.flatMap((element) => element.element === "app" ? [] : [SYSTEM_SIDEBAR_DISPLAY_NAMES[element.element]]));
19105
+ const displayNames = /* @__PURE__ */ new Set();
19106
+ sidebar.forEach((element, index) => {
19107
+ const path = [
19108
+ "models",
19109
+ model,
19110
+ "sidebar",
19111
+ String(index)
19112
+ ];
19113
+ const key = element.element === "app" ? `${element.appApiId}/${element.appElementApiId}` : element.element;
19114
+ if (keys.has(key)) validations.push({
19115
+ code: "model.sidebarDuplicate",
19116
+ severity: "error",
19117
+ path,
19118
+ message: messages["model.sidebarDuplicate"](model, describePanel(element)),
19119
+ fix: fixes["model.sidebarDuplicate"]
19120
+ });
19121
+ keys.add(key);
19122
+ if (element.element === "app") {
19123
+ if (titles.has(element.displayName) || displayNames.has(element.displayName)) validations.push({
19124
+ code: "model.sidebarDuplicateDisplayName",
19125
+ severity: "error",
19126
+ path: [...path, "displayName"],
19127
+ message: messages["model.sidebarDuplicateDisplayName"](model, element.displayName),
19128
+ fix: fixes["model.sidebarDuplicateDisplayName"]
19129
+ });
19130
+ displayNames.add(element.displayName);
19131
+ }
19132
+ if (element.element !== "PREVIEW_URLS") return;
19133
+ if (element.previewUrls.length === 0) validations.push({
19134
+ code: "model.sidebarNoPreviewUrl",
19135
+ severity: "error",
19136
+ path: [...path, "previewUrls"],
19137
+ message: messages["model.sidebarNoPreviewUrl"](model),
19138
+ fix: fixes["model.sidebarNoPreviewUrl"]
19139
+ });
19140
+ for (const list of ["previewUrls", "variantPreviewUrls"]) if (element[list].some(isIncomplete)) validations.push({
19141
+ code: "model.sidebarPreviewUrlEmpty",
19142
+ severity: "error",
19143
+ path: [...path, list],
19144
+ message: messages["model.sidebarPreviewUrlEmpty"](model, list),
19145
+ fix: fixes["model.sidebarPreviewUrlEmpty"]
19146
+ });
19147
+ });
19148
+ return validations;
19149
+ }
19150
+ function isIncomplete({ name, template }) {
19151
+ return name.trim() === "" || template.trim() === "";
19152
+ }
19153
+ function describePanel(element) {
19154
+ return element.element === "app" ? `the panel of app "${element.appApiId}" element "${element.appElementApiId}"` : `the ${element.element} panel`;
19155
+ }
19156
+ //#endregion
18540
19157
  //#region src/define/resources/model.validation.ts
18541
19158
  /**
18542
19159
  * What a model can tell about itself, its fields included. Uniqueness of
@@ -18587,6 +19204,14 @@ function validateModel(model) {
18587
19204
  kind: "model",
18588
19205
  apiId: model.apiId
18589
19206
  }, model.fields));
19207
+ if (model.sidebar !== null) validations.push(...validateSidebar(model.apiId, model.sidebar));
19208
+ if (model.sidebar !== null && !model.sidebar.some((element) => element.element === "VARIANTS") && model.fields.some((field) => field.__typename !== "UnsupportedField" && field.variantEnabled)) validations.push({
19209
+ code: "model.sidebarVariantsMissing",
19210
+ severity: "error",
19211
+ path: modelPath(model.apiId, "sidebar"),
19212
+ message: messages["model.sidebarVariantsMissing"](model.apiId),
19213
+ fix: fixes["model.sidebarVariantsMissing"]
19214
+ });
18590
19215
  if (model.fields.length > 0 && !model.fields.some((field) => field.__typename === "UnsupportedField" || "title" in field && field.title)) validations.push({
18591
19216
  code: "model.noTitleField",
18592
19217
  severity: "warning",
@@ -19735,9 +20360,9 @@ function basesFirst(creates) {
19735
20360
  /**
19736
20361
  * Hygraph cannot change a field's type or its `list` once it exists, nor an
19737
20362
  * enumeration field's enumeration or `localized`, a taxonomy field's
19738
- * taxonomy, a component field's component, a union's visibility or the
19739
- * model a reference references, nor turn a rich text's embeds off. A
19740
- * two-way pair is decided as a whole, in `pairTwoWayReferences`.
20363
+ * taxonomy, a component field's component or the model a reference
20364
+ * references, nor turn a rich text's embeds off. A two-way pair is decided
20365
+ * as a whole, in `pairTwoWayReferences`.
19741
20366
  */
19742
20367
  function changesInPlace(from, to) {
19743
20368
  if (from.kind === "unsupported" || to.kind === "unsupported") return from.kind === "unsupported" && to.kind === "unsupported" && from.type === to.type;
@@ -19745,7 +20370,6 @@ function changesInPlace(from, to) {
19745
20370
  if (from.kind === "taxonomy" && to.kind === "taxonomy") return from.list === to.list && from.taxonomy === to.taxonomy;
19746
20371
  if (from.kind === "remote" && to.kind === "remote") return from.list === to.list && from.type === to.type;
19747
20372
  if (from.kind === "component" && to.kind === "component") return from.list === to.list && from.component === to.component;
19748
- if (from.kind === "componentUnion" && to.kind === "componentUnion") return from.list === to.list && from.visibility === to.visibility;
19749
20373
  if (from.kind === "referenceOneWay" && to.kind === "referenceOneWay") return from.list === to.list && from.to === to.to;
19750
20374
  if (from.kind === "richText" && to.kind === "richText") return from.list === to.list && (from.embeds === null || to.embeds !== null);
19751
20375
  return from.kind === to.kind && from.list === to.list;
@@ -20277,15 +20901,18 @@ function parentsFirst(nodes) {
20277
20901
  * fields. A node is created before the nodes under it, and moves away
20278
20902
  * from a node before that node is deleted. A source whose type or
20279
20903
  * introspection URL changes is deleted in step 2 and created here;
20280
- * 5. component updates, component creates, model updates, then field
20281
- * updates, carrying only what differs, then remote source deletes. A
20904
+ * 5. component updates, component creates, model updates, the sidebar
20905
+ * changes of existing models, then field updates, carrying only what
20906
+ * differs, then remote source deletes. A listed Variants panel exists
20907
+ * before a field gets variants, which would make Hygraph add one. A
20282
20908
  * component update frees the names a create may claim, and a union
20283
20909
  * update finds the components it adds. A field update may move a remote
20284
20910
  * field off a source, which Hygraph cannot delete while a field uses it;
20285
20911
  * 6. component deletes. Hygraph refuses to delete a component while a
20286
20912
  * field uses it, so they wait for the field deletes and for the union
20287
20913
  * updates that drop them;
20288
- * 7. model creates, then field creates, so a new field's parent exists. A
20914
+ * 7. model creates, the sidebar changes of new models, then field
20915
+ * creates, so a new field's parent exists. A
20289
20916
  * base field is created before the fields whose condition names it;
20290
20917
  * then the union updates that add models, which may be new;
20291
20918
  * 8. conditions that name a field created in step 7, on fields that stay,
@@ -20311,9 +20938,13 @@ function diffEnvironment({ from, to, intents = {
20311
20938
  valueRenames: [],
20312
20939
  nodeRenames: [],
20313
20940
  migrationValues: []
20314
- }, unsupportedPairs = [], unsupportedUnions = [] }) {
20941
+ }, unsupportedPairs = [], unsupportedUnions = [], newModelSidebar: newModelSidebar$1 = newModelSidebar(false), oldSidebarTitles = {} }) {
20315
20942
  const { renamed, renames } = applyRenames(from, intents);
20316
20943
  const renameParent = followModelRenames(from, intents);
20944
+ const sidebarTitles = new Map(Object.entries(oldSidebarTitles).map(([apiId, titles]) => [renameParent({
20945
+ parent: apiId,
20946
+ apiId: ""
20947
+ }).parent, titles]));
20317
20948
  const pairs = pairTwoWayReferences(renamed, to, unsupportedPairs.map(([a, b]) => [renameParent(a), renameParent(b)]));
20318
20949
  const unions = groupUnionReferences(renamed, to, unsupportedUnions.map(({ owner, members }) => ({
20319
20950
  owner: renameParent(owner),
@@ -20350,9 +20981,16 @@ function diffEnvironment({ from, to, intents = {
20350
20981
  };
20351
20982
  const modelUpdates = [];
20352
20983
  const modelCreates = [];
20984
+ const sidebarUpdates = [];
20985
+ const sidebarCreates = [];
20353
20986
  for (const model of to.models) {
20354
20987
  const fromModel = fromModels.get(model.apiId) ?? null;
20355
20988
  pushFields(fromModel, model);
20989
+ const fromSidebar = fromModel ? fromModel.sidebar : newModelSidebar$1;
20990
+ if (model.sidebar !== null && fromSidebar !== null) {
20991
+ const sidebar = diffSidebar(model.apiId, fromSidebar, model.sidebar, sidebarTitles.get(model.apiId));
20992
+ (fromModel ? sidebarUpdates : sidebarCreates).push(...sidebar.deletes, ...sidebar.creates, ...sidebar.updates, ...sidebar.moves);
20993
+ }
20356
20994
  if (!fromModel) {
20357
20995
  modelCreates.push({
20358
20996
  action: "create",
@@ -20460,10 +21098,12 @@ function diffEnvironment({ from, to, intents = {
20460
21098
  ...componentUpdates,
20461
21099
  ...componentCreates,
20462
21100
  ...modelUpdates,
21101
+ ...sidebarUpdates,
20463
21102
  ...embeds.updates,
20464
21103
  ...remoteSources.deletes,
20465
21104
  ...componentDeletes,
20466
21105
  ...modelCreates,
21106
+ ...sidebarCreates,
20467
21107
  ...fieldCreates.map((change) => withFieldBack(change, to)),
20468
21108
  ...memberAdds,
20469
21109
  ...fieldConditions,
@@ -21792,10 +22432,12 @@ function createdOrDeleted(change) {
21792
22432
  * and a taxonomy keeps its root. The live default locale cannot be
21793
22433
  * deleted: Studio does not allow it, and the server needs a default. No
21794
22434
  * stage can be deleted yet: the batch cannot force it (FND-5033).
22435
+ * A field on Asset, and an asset field's field back, need their name free
22436
+ * on Asset.
21795
22437
  * Every change is checked, so two faults are two entries; a change that
21796
22438
  * cannot apply is left out of the state the later ones are checked against.
21797
22439
  */
21798
- function validateChangeSet({ from, changes }) {
22440
+ function validateChangeSet({ from, changes, fieldsBackOnAsset = [] }) {
21799
22441
  const models = new Map(from.models.map((model) => [model.apiId, model]));
21800
22442
  const components = new Map(from.components.map((component) => [component.apiId, component]));
21801
22443
  const componentApiIds = new Set(components.keys());
@@ -21807,6 +22449,10 @@ function validateChangeSet({ from, changes }) {
21807
22449
  root: taxonomy.nodes.find((node) => node.parent === null)?.apiId ?? null
21808
22450
  }]));
21809
22451
  const locales = new Map(from.locales.map((locale) => [locale.apiId, locale]));
22452
+ const onAsset = new Map([...Object.keys(from.asset?.fields ?? {}).map((apiId) => [apiId, {
22453
+ parent: "Asset",
22454
+ apiId
22455
+ }]), ...fieldsBackOnAsset.map(({ apiId, field }) => [apiId, { ...field }])]);
21810
22456
  let liveDefault = from.locales.find((locale) => locale.isDefault)?.apiId;
21811
22457
  const validations = [];
21812
22458
  const inUse = (attribute, value, ownApiId) => [...models.values()].some((model) => model.apiId !== ownApiId && model[attribute] === value) || attribute === "apiId" && value !== ownApiId && (components.has(value) || enumerations.has(value) || taxonomies.has(value));
@@ -21895,6 +22541,7 @@ function validateChangeSet({ from, changes }) {
21895
22541
  validateComponentsUsed(change);
21896
22542
  validateModelReferenced(change);
21897
22543
  validateModelsEmbedded(change);
22544
+ validateFieldBackOnAsset(change);
21898
22545
  if (turnsVariantsOn(change) && models.has(change.parent)) segment = true;
21899
22546
  if (change.parent === "Asset" || change.parent === "QueryModel" || change.parent === "Segment" && segment || models.has(change.parent) || components.has(change.parent)) break;
21900
22547
  const onComponent = componentApiIds.has(change.parent);
@@ -21972,6 +22619,82 @@ function validateChangeSet({ from, changes }) {
21972
22619
  fieldApiIdOf(change)
21973
22620
  ], `${change.action} a field that references`, apiId);
21974
22621
  }
22622
+ function validateFieldBackOnAsset(change) {
22623
+ const same = (ref, field) => ref?.parent === field.parent && ref.apiId === field.apiId;
22624
+ switch (change.action) {
22625
+ case "create": {
22626
+ const { field, parent, partner } = change;
22627
+ const names = [];
22628
+ if (parent === "Asset") names.push({
22629
+ name: field.apiId,
22630
+ code: "change.assetFieldNameInUse",
22631
+ key: "apiId"
22632
+ });
22633
+ if (field.kind === "asset") names.push(partner === void 0 ? {
22634
+ name: assetReverseApiId(field.apiId, parent),
22635
+ code: "change.assetFieldBackInUse",
22636
+ key: "apiId"
22637
+ } : {
22638
+ name: partner.apiId,
22639
+ code: "change.assetFieldNameInUse",
22640
+ key: "reverse"
22641
+ });
22642
+ const kind = componentApiIds.has(parent) ? "components" : "models";
22643
+ for (const { name, code, key } of names) {
22644
+ const holder = onAsset.get(name);
22645
+ if (holder === void 0) {
22646
+ onAsset.set(name, {
22647
+ parent,
22648
+ apiId: field.apiId
22649
+ });
22650
+ continue;
22651
+ }
22652
+ report(code, [
22653
+ kind,
22654
+ parent,
22655
+ "fields",
22656
+ field.apiId,
22657
+ key
22658
+ ], parent, field.apiId, name, holder.parent, holder.apiId);
22659
+ }
22660
+ return;
22661
+ }
22662
+ case "update": {
22663
+ const rename = unsupportedFieldMove(change) ? void 0 : change.changes.apiId;
22664
+ if (rename === void 0) return;
22665
+ if (change.parent === "Asset") {
22666
+ const holder = onAsset.get(rename.to);
22667
+ if (holder) {
22668
+ report("change.assetFieldNameInUse", [
22669
+ "models",
22670
+ "Asset",
22671
+ "fields",
22672
+ rename.to,
22673
+ "apiId"
22674
+ ], "Asset", rename.to, rename.to, holder.parent, holder.apiId);
22675
+ return;
22676
+ }
22677
+ const held = onAsset.get(change.apiId);
22678
+ if (held) {
22679
+ onAsset.delete(change.apiId);
22680
+ onAsset.set(rename.to, held);
22681
+ }
22682
+ }
22683
+ for (const field of onAsset.values()) if (same(change, field)) field.apiId = rename.to;
22684
+ return;
22685
+ }
22686
+ case "delete":
22687
+ if (change.parent === "Asset") onAsset.delete(change.apiId);
22688
+ for (const [name, field] of onAsset) if (same(change, field) || same(change.partner, field)) onAsset.delete(name);
22689
+ return;
22690
+ }
22691
+ }
22692
+ function moveHolders(from, to) {
22693
+ for (const field of onAsset.values()) if (field.parent === from) field.parent = to;
22694
+ }
22695
+ function dropHolders(parent) {
22696
+ for (const [name, field] of onAsset) if (field.parent === parent) onAsset.delete(name);
22697
+ }
21975
22698
  function validateLocaleChange(change) {
21976
22699
  switch (change.action) {
21977
22700
  case "create":
@@ -22034,10 +22757,13 @@ function validateChangeSet({ from, changes }) {
22034
22757
  if (componentNamesFree(updated, component.apiId)) {
22035
22758
  components.delete(component.apiId);
22036
22759
  components.set(updated.apiId, updated);
22760
+ moveHolders(component.apiId, updated.apiId);
22037
22761
  }
22038
22762
  break;
22039
22763
  }
22040
- case "delete": if (!components.delete(change.apiId)) report("change.componentMissing", ["components", change.apiId], "delete", change.apiId);
22764
+ case "delete":
22765
+ if (!components.delete(change.apiId)) report("change.componentMissing", ["components", change.apiId], "delete", change.apiId);
22766
+ dropHolders(change.apiId);
22041
22767
  }
22042
22768
  }
22043
22769
  function validateModelChange(change) {
@@ -22055,10 +22781,13 @@ function validateChangeSet({ from, changes }) {
22055
22781
  if (namesFree(updated, model.apiId)) {
22056
22782
  models.delete(model.apiId);
22057
22783
  models.set(updated.apiId, updated);
22784
+ moveHolders(model.apiId, updated.apiId);
22058
22785
  }
22059
22786
  break;
22060
22787
  }
22061
- case "delete": if (!models.delete(change.apiId)) report("change.modelMissing", ["models", change.apiId], "delete", change.apiId);
22788
+ case "delete":
22789
+ if (!models.delete(change.apiId)) report("change.modelMissing", ["models", change.apiId], "delete", change.apiId);
22790
+ dropHolders(change.apiId);
22062
22791
  }
22063
22792
  }
22064
22793
  function validateEnumerationChange(change) {
@@ -22316,6 +23045,30 @@ function validateAppSettings(field, element, declared, config, path) {
22316
23045
  function isRecord(value) {
22317
23046
  return typeof value === "object" && value !== null && !Array.isArray(value);
22318
23047
  }
23048
+ /**
23049
+ * A managed sidebar on a model with a panel the CLI cannot read. Hygraph
23050
+ * counts that panel in the positions the batch moves the others to, so a
23051
+ * move past it would land one place off, and every plan would make it
23052
+ * again. A model the config renames is found by its live apiId.
23053
+ */
23054
+ function validateSidebarElements({ to, intents, modelsWithUnsupportedSidebarElements }) {
23055
+ const unsupported = new Set(modelsWithUnsupportedSidebarElements);
23056
+ const renamedFrom = new Map(intents.renames.flatMap((rename) => rename.resource === "model" ? [[rename.apiId, rename.renamedFrom]] : []));
23057
+ return to.models.filter((model) => model.sidebar !== null && unsupported.has(renamedFrom.get(model.apiId) ?? model.apiId)).toSorted(byApiId$1).map((model) => {
23058
+ const code = "model.sidebarUnsupportedElement";
23059
+ return {
23060
+ code,
23061
+ severity: "error",
23062
+ path: [
23063
+ "models",
23064
+ model.apiId,
23065
+ "sidebar"
23066
+ ],
23067
+ message: messages[code](model.apiId),
23068
+ fix: fixes[code]
23069
+ };
23070
+ });
23071
+ }
22319
23072
  //#endregion
22320
23073
  //#region src/validations/render.ts
22321
23074
  /**
@@ -22869,6 +23622,7 @@ const modelSchema = strictObject({
22869
23622
  displayName: string$1(),
22870
23623
  description: string$1().nullable(),
22871
23624
  fields: array(fieldSchema),
23625
+ sidebar: array(sidebarElementSchema$1).nullable(),
22872
23626
  renamedFrom: string$1().nullable()
22873
23627
  });
22874
23628
  //#endregion
@@ -23116,7 +23870,7 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
23116
23870
  maybeRefuse(configValidations, "the config has");
23117
23871
  const desired = convertEnvironmentToIR(target.apply);
23118
23872
  const intents = collectIntents(target.apply);
23119
- const { environmentId, environment: live, unsupportedPairs, unsupportedUnions, apps } = await readLiveEnvironment(target, fetch);
23873
+ const { environmentId, environment: live, unsupportedPairs, unsupportedUnions, apps, fieldsBackOnAsset, newModelSidebar, oldSidebarTitles, modelsWithUnsupportedSidebarElements } = await readLiveEnvironment(target, fetch);
23120
23874
  maybeRefuse(validateRemoteSourceChanges({
23121
23875
  from: live,
23122
23876
  to: desired
@@ -23142,6 +23896,11 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
23142
23896
  to: desired,
23143
23897
  intents
23144
23898
  }), `the fields back on Asset do not match the asset fields,`);
23899
+ maybeRefuse(validateSidebarElements({
23900
+ to: desired,
23901
+ intents,
23902
+ modelsWithUnsupportedSidebarElements
23903
+ }), `the sidebars cannot be planned against ${target.environment},`);
23145
23904
  const segmentValidations = validateSegment({
23146
23905
  from: live,
23147
23906
  to: desired
@@ -23152,11 +23911,14 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
23152
23911
  to: desired,
23153
23912
  intents,
23154
23913
  unsupportedPairs,
23155
- unsupportedUnions
23914
+ unsupportedUnions,
23915
+ newModelSidebar,
23916
+ oldSidebarTitles
23156
23917
  });
23157
23918
  maybeRefuse(validateChangeSet({
23158
23919
  from: live,
23159
- changes: diffed
23920
+ changes: diffed,
23921
+ fieldsBackOnAsset
23160
23922
  }), `the changes cannot be applied to ${target.environment},`);
23161
23923
  const secrets = oAuthSecrets(target.apply);
23162
23924
  const attached = attachOAuthSecrets(diffed, secrets);
@@ -23458,6 +24220,17 @@ async function formatSource(source) {
23458
24220
  function string(value) {
23459
24221
  return JSON.stringify(value);
23460
24222
  }
24223
+ /** The characters of Hygraph's apiId rule, without its length limit. */
24224
+ const NAME = /^[A-Z][A-Za-z0-9_]*$/;
24225
+ /**
24226
+ * A name in code, such as a const. Only an apiId made of the characters of
24227
+ * Hygraph's rule is written as one; anything else could be code, so it is
24228
+ * refused. `kind` names the value in the error.
24229
+ */
24230
+ function identifier(name, kind = "apiId") {
24231
+ if (!NAME.test(name)) throw new Failure(`${string(name)} is not a valid ${kind}, so it cannot name a const in the config.`);
24232
+ return name;
24233
+ }
23461
24234
  /** A template literal, for text that spans lines. Nothing in it is interpolated. */
23462
24235
  function template(value) {
23463
24236
  return `\`${value.replaceAll(/[\\`]|\$\{/g, (match) => `\\${match}`)}\``;
@@ -23521,7 +24294,7 @@ function oAuthSecretEnvName(prefix) {
23521
24294
  }
23522
24295
  /** The name of the const `printRemoteSource` declares. */
23523
24296
  function remoteSourceConstName(source) {
23524
- return `${source.prefix}RemoteSource`;
24297
+ return `${identifier(source.prefix, "remote source prefix")}RemoteSource`;
23525
24298
  }
23526
24299
  /**
23527
24300
  * Every header value is a read of the variable `headerEnvNames` names,
@@ -23580,7 +24353,7 @@ function printAssetModelField(field) {
23580
24353
  return printBuilder("assetReverseField", [
23581
24354
  ["apiId", string(field.apiId)],
23582
24355
  ["displayName", string(field.displayName)],
23583
- ["to", `() => ${field.to}`],
24356
+ ["to", `() => ${identifier(field.to)}`],
23584
24357
  ["reverse", string(field.reverse)],
23585
24358
  ["description", field.description === null ? void 0 : string(field.description)],
23586
24359
  ["visibility", field.visibility === "API_ONLY" ? void 0 : string(field.visibility)]
@@ -23601,7 +24374,7 @@ function printField(parent, field) {
23601
24374
  return printBuilder("enumeration", [
23602
24375
  apiId,
23603
24376
  displayName,
23604
- ["enumeration", field.enumeration],
24377
+ ["enumeration", identifier(field.enumeration)],
23605
24378
  ...options
23606
24379
  ]);
23607
24380
  }
@@ -23610,13 +24383,13 @@ function printField(parent, field) {
23610
24383
  return printBuilder("taxonomy", [
23611
24384
  apiId,
23612
24385
  displayName,
23613
- ["taxonomy", field.taxonomy],
24386
+ ["taxonomy", identifier(field.taxonomy)],
23614
24387
  ...options
23615
24388
  ]);
23616
24389
  }
23617
24390
  case "richText": return printBuilder(customOf("richText", field.formRenderer), [
23618
24391
  ...fieldOptions(field, FIELD_DEFAULTS),
23619
- ["embeds", field.embeds === null ? void 0 : `[${field.embeds.map((apiId) => `() => ${apiId}`).join(", ")}]`],
24392
+ ["embeds", field.embeds === null ? void 0 : `[${field.embeds.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`],
23620
24393
  ["actions", field.actions === null ? void 0 : `[${field.actions.map(string).join(", ")}]`],
23621
24394
  rendererOption(field.formRenderer)
23622
24395
  ]);
@@ -23636,16 +24409,16 @@ function printField(parent, field) {
23636
24409
  const [builder, defaults] = BUILDERS[formRenderer];
23637
24410
  return printBuilder(builder, [...fieldOptions(field, defaults), ...stringOptions(field)]);
23638
24411
  }
23639
- case "component": return printBuilder("component", referenceOptions(field, ["component", `() => ${field.component}`]));
23640
- case "componentUnion": return printBuilder("componentUnion", referenceOptions(field, ["components", `[${field.components.map((apiId) => `() => ${apiId}`).join(", ")}]`]));
24412
+ case "component": return printBuilder("component", referenceOptions(field, ["component", `() => ${identifier(field.component)}`]));
24413
+ case "componentUnion": return printBuilder("componentUnion", referenceOptions(field, ["components", `[${field.components.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`]));
23641
24414
  case "asset": return printBuilder(customOf("asset", field.formRenderer), [...referenceOptions(field, ["reverse", field.reverse === void 0 ? void 0 : string(field.reverse)]), rendererOption(field.formRenderer)]);
23642
24415
  case "referenceOneWay": return printBuilder(customOf("referenceOneWay", field.formRenderer), [
23643
- ...referenceOptions(field, ["to", `() => ${field.to}`]),
24416
+ ...referenceOptions(field, ["to", `() => ${identifier(field.to)}`]),
23644
24417
  ["rules", printRules(field.rules)],
23645
24418
  rendererOption(field.formRenderer)
23646
24419
  ]);
23647
24420
  case "referenceTwoWay": {
23648
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
24421
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${identifier(field.to)}`]);
23649
24422
  return printBuilder(customOf("referenceTwoWay", field.formRenderer), [
23650
24423
  apiId,
23651
24424
  displayName,
@@ -23657,7 +24430,7 @@ function printField(parent, field) {
23657
24430
  ]);
23658
24431
  }
23659
24432
  case "referenceUnion": {
23660
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `[${field.to.map((apiId) => `() => ${apiId}`).join(", ")}]`]);
24433
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `[${field.to.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`]);
23661
24434
  return printBuilder("referenceUnion", [
23662
24435
  apiId,
23663
24436
  displayName,
@@ -23668,7 +24441,7 @@ function printField(parent, field) {
23668
24441
  ]);
23669
24442
  }
23670
24443
  case "referenceUnionMember": {
23671
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
24444
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${identifier(field.to)}`]);
23672
24445
  return printBuilder("referenceUnionMember", [
23673
24446
  apiId,
23674
24447
  displayName,
@@ -23851,7 +24624,7 @@ function printRegex(regex) {
23851
24624
  * const. Attributes at their default are left out.
23852
24625
  */
23853
24626
  function printComponent(component) {
23854
- return `const ${component.apiId} = define.component(${object([
24627
+ return `const ${identifier(component.apiId)} = define.component(${object([
23855
24628
  ["apiId", string(component.apiId)],
23856
24629
  ["apiIdPlural", string(component.apiIdPlural)],
23857
24630
  ["displayName", string(component.displayName)],
@@ -23869,7 +24642,7 @@ function printComponent(component) {
23869
24642
  */
23870
24643
  function printEnumeration(enumeration) {
23871
24644
  const values = enumeration.values.map((value) => `{ apiId: ${string(value.apiId)}, displayName: ${string(value.displayName)} }`);
23872
- return `const ${enumeration.apiId} = define.enumeration(${object([
24645
+ return `const ${identifier(enumeration.apiId)} = define.enumeration(${object([
23873
24646
  ["apiId", string(enumeration.apiId)],
23874
24647
  ["displayName", string(enumeration.displayName)],
23875
24648
  ["description", enumeration.description === null ? void 0 : string(enumeration.description)],
@@ -23893,19 +24666,52 @@ function printLocale(locale) {
23893
24666
  ])})`;
23894
24667
  }
23895
24668
  //#endregion
24669
+ //#region src/export/resources/sidebar.ts
24670
+ /**
24671
+ * A model's `sidebar` in panel order, settings at their default left out.
24672
+ * Export never writes one (see `withoutSidebars`); pull does, for a model
24673
+ * whose config sets it.
24674
+ */
24675
+ function printSidebar(sidebar) {
24676
+ return `[${sidebar.toSorted((a, b) => a.position - b.position).map(printSidebarElement).join(", ")}]`;
24677
+ }
24678
+ function printSidebarElement(element) {
24679
+ switch (element.kind) {
24680
+ case "system": return `{ element: ${string(element.type)} }`;
24681
+ case "previewUrls": return object([
24682
+ ["element", string("PREVIEW_URLS")],
24683
+ ["previewUrls", printPreviewUrls(element.previewUrls)],
24684
+ ["variantPreviewUrls", element.variantPreviewUrls === null ? void 0 : printPreviewUrls(element.variantPreviewUrls)],
24685
+ ["openInNewTab", element.openInNewTab ? "true" : void 0]
24686
+ ]);
24687
+ case "app": return object([
24688
+ ["element", string("app")],
24689
+ ["appApiId", string(element.appApiId)],
24690
+ ["appElementApiId", string(element.appElementApiId)],
24691
+ ["displayName", string(element.displayName)],
24692
+ ["description", element.description === null ? void 0 : string(element.description)],
24693
+ ["config", element.config === null ? void 0 : JSON.stringify(element.config)]
24694
+ ]);
24695
+ }
24696
+ }
24697
+ function printPreviewUrls(urls) {
24698
+ return `[${urls.map(({ name, template }) => `{ name: ${string(name)}, template: ${string(template)} }`).join(", ")}]`;
24699
+ }
24700
+ //#endregion
23896
24701
  //#region src/export/resources/model.ts
23897
24702
  /**
23898
24703
  * `const <apiId> = define.model({...});`. A model apiId is a valid
23899
24704
  * identifier, so it names the const. Attributes at their default are left
23900
- * out.
24705
+ * out, as is a sidebar the IR leaves to Hygraph.
23901
24706
  */
23902
24707
  function printModel(model) {
23903
- return `const ${model.apiId} = define.model(${object([
24708
+ return `const ${identifier(model.apiId)} = define.model(${object([
23904
24709
  ["apiId", string(model.apiId)],
23905
24710
  ["apiIdPlural", string(model.apiIdPlural)],
23906
24711
  ["displayName", string(model.displayName)],
23907
24712
  ["description", model.description === null ? void 0 : string(model.description)],
23908
- ["fields", printFields(model.apiId, model.fields)]
24713
+ ["fields", printFields(model.apiId, model.fields)],
24714
+ ["sidebar", model.sidebar === null ? void 0 : printSidebar(model.sidebar)]
23909
24715
  ])});`;
23910
24716
  }
23911
24717
  //#endregion
@@ -23981,7 +24787,7 @@ function printTaxonomy(taxonomy) {
23981
24787
  ["children", `[${below.map(printNode).join(", ")}]`]
23982
24788
  ]);
23983
24789
  };
23984
- return `const ${taxonomy.apiId} = define.taxonomy(${object([
24790
+ return `const ${identifier(taxonomy.apiId)} = define.taxonomy(${object([
23985
24791
  ["apiId", string(taxonomy.apiId)],
23986
24792
  ["displayName", string(taxonomy.displayName)],
23987
24793
  ["description", taxonomy.description === null ? void 0 : string(taxonomy.description)],
@@ -24001,6 +24807,43 @@ const NO_QUERY_FIELDS = {
24001
24807
  fields: {}
24002
24808
  };
24003
24809
  /**
24810
+ * `environment` with every model's sidebar left as it is, as export writes
24811
+ * it. Hygraph adds panels of its own over time, and a written sidebar
24812
+ * would remove each new one. A model takes its panels over by setting
24813
+ * `sidebar`.
24814
+ */
24815
+ function withoutSidebars(environment) {
24816
+ return {
24817
+ ...environment,
24818
+ models: environment.models.map((model) => ({
24819
+ ...model,
24820
+ sidebar: null
24821
+ }))
24822
+ };
24823
+ }
24824
+ /**
24825
+ * `live` with the sidebar left out of every model whose sidebar `config`
24826
+ * leaves as it is, so pull compares only the sidebars a config sets. A
24827
+ * model the config renames keeps its live sidebar under its old apiId.
24828
+ */
24829
+ function withConfigSidebars(config, live, intents) {
24830
+ const renamedFrom = new Map(intents.renames.flatMap((rename) => rename.resource === "model" ? [[rename.apiId, rename.renamedFrom]] : []));
24831
+ const managed = /* @__PURE__ */ new Set();
24832
+ for (const model of config.models) {
24833
+ if (model.sidebar === null) continue;
24834
+ managed.add(model.apiId);
24835
+ const from = renamedFrom.get(model.apiId);
24836
+ if (from !== void 0) managed.add(from);
24837
+ }
24838
+ return {
24839
+ ...live,
24840
+ models: live.models.map((model) => managed.has(model.apiId) ? model : {
24841
+ ...model,
24842
+ sidebar: null
24843
+ })
24844
+ };
24845
+ }
24846
+ /**
24004
24847
  * The config a user commits: one const per enumeration, then per
24005
24848
  * taxonomy, per remote source, per component and per model, in IR
24006
24849
  * order, then Asset and Query, also with no fields of yours, so the first
@@ -24034,7 +24877,7 @@ async function printConfig(target, environment) {
24034
24877
  * when live has it.
24035
24878
  */
24036
24879
  function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset, segment }) {
24037
- const list = (resources) => `[${resources.map((resource) => resource.apiId).join(", ")}]`;
24880
+ const list = (resources) => `[${resources.map((resource) => identifier(resource.apiId)).join(", ")}]`;
24038
24881
  return `const environment = define.environment({ ${[
24039
24882
  `locales: [${locales.map(printLocale).join(", ")}]`,
24040
24883
  `stages: [${stages.toSorted((a, b) => a.position - b.position).map(printStage).join(", ")}]`,
@@ -24292,7 +25135,7 @@ async function exportEnvironment(input) {
24292
25135
  });
24293
25136
  const { environment: environment$1 } = await readLiveEnvironment(target$1);
24294
25137
  return {
24295
- config: await printConfig(target$1, environment$1),
25138
+ config: await printConfig(target$1, withoutSidebars(environment$1)),
24296
25139
  environment: environment$1
24297
25140
  };
24298
25141
  }
@@ -24496,10 +25339,11 @@ async function pull(config, options, write, writeErr) {
24496
25339
  if (failed > 0) throw new PullFailure(`${failed} of ${targets.length} targets could not be pulled`);
24497
25340
  }
24498
25341
  async function pullTarget(target, { config, colors, full, write, writeErr }) {
24499
- const errors = validateEnvironment(target.apply).filter((validation) => validation.severity === "error");
25342
+ const errors = validateEnvironment(target.apply).filter((validation) => validation.severity === "error" && validation.code !== "model.sidebarVariantsMissing");
24500
25343
  if (errors.length > 0) throw new PullFailure(`the config has ${errors.length === 1 ? "1 error" : `${errors.length} errors`}:\n\n${renderValidations(errors)}`);
24501
25344
  const { environment: live } = await readLiveEnvironment(target);
24502
- const diff = await diffConfig(target, convertEnvironmentToIR(target.apply), live, { full });
25345
+ const desired = convertEnvironmentToIR(target.apply);
25346
+ const diff = await diffConfig(target, desired, withConfigSidebars(desired, live, collectIntents(target.apply)), { full });
24503
25347
  const rendered = renderPull(diff, {
24504
25348
  target,
24505
25349
  config,