@hygraph/cli 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { r as __toESM, t as __commonJSMin } from "./rolldown-runtime.js";
2
2
  import { t as VERSION } from "./version.js";
3
- import { a as SLUG_DEFAULTS, c as environment, d as RICH_TEXT_ACTIONS, f as isEmptyRichText, h as isEmpty, i as target, l as byApiId$1, m as assetReverseApiId, n as stage, o as collectIntents, p as richTextActions, s as convertEnvironmentToIR, u as FIELD_DEFAULTS } from "./define2.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";
4
4
  import { EventEmitter } from "node:events";
5
5
  import childProcess from "node:child_process";
6
6
  import path, { dirname, resolve } from "node:path";
@@ -3425,6 +3425,10 @@ function unsupportedFieldMove(change) {
3425
3425
  function fieldApiIdOf(change) {
3426
3426
  return change.action === "create" ? change.field.apiId : change.apiId;
3427
3427
  }
3428
+ /** The prefix of the remote source a change is about. */
3429
+ function remoteSourcePrefixOf(change) {
3430
+ return change.action === "create" ? change.remoteSource.prefix : change.prefix;
3431
+ }
3428
3432
  //#endregion
3429
3433
  //#region node_modules/.pnpm/canonicalize@5.1.0/node_modules/canonicalize/lib/canonicalize.js
3430
3434
  function serializeString(value) {
@@ -3544,19 +3548,166 @@ function hashJSON(value) {
3544
3548
  function hashIR(ir) {
3545
3549
  return hashJSON(ir);
3546
3550
  }
3551
+ //#endregion
3552
+ //#region src/plan/masking.ts
3553
+ /**
3554
+ * Remote source header values hold tokens, and OAuth secrets are secrets,
3555
+ * so the plan carries a hash of each in their place: `plan.json` is kept as
3556
+ * a CI artifact and printed in job logs. A change still shows, as the hash
3557
+ * moves with the value. Apply puts the values back from the config it
3558
+ * plans again from.
3559
+ */
3560
+ const MASK = "sha256:";
3561
+ /** Every header value and OAuth secret in the changes, the live ones included, as its hash. */
3562
+ function maskSecrets(changes) {
3563
+ const hash = (value) => `${MASK}${hashJSON(value)}`;
3564
+ return mapSecrets(mapHeaders(changes, (headers) => mapValues(headers, hash)), hash);
3565
+ }
3566
+ /**
3567
+ * Every header value of the config's sources and remote fields, and every
3568
+ * OAuth secret, which the IR leaves out, by the hash `maskSecrets`
3569
+ * puts in its place.
3570
+ */
3571
+ function secretValues(desired, secrets = /* @__PURE__ */ new Map()) {
3572
+ const headers = [...desired.remoteSources.flatMap((source) => [source.headers, source.type === "GRAPHQL" ? source.introspectionHeaders : null]), ...[
3573
+ ...desired.models,
3574
+ ...desired.components,
3575
+ ...desired.asset ? [desired.asset] : [],
3576
+ ...desired.query ? [desired.query] : []
3577
+ ].flatMap((parent) => Object.values(parent.fields).map((field) => field.kind === "remote" ? field.headers : null))];
3578
+ return new Map([...byHash(headers.flatMap((each) => Object.values(each ?? {}).flat())), ...oAuthSecretValues(secrets)]);
3579
+ }
3580
+ /**
3581
+ * The OAuth secrets alone, by hash: what apply needs to check a plan's
3582
+ * secrets before the config is validated and converted.
3583
+ */
3584
+ function oAuthSecretValues(secrets) {
3585
+ return byHash([...secrets.values()].flatMap(({ secret }) => secret === null ? [] : [secret]));
3586
+ }
3587
+ function byHash(values) {
3588
+ return new Map(values.map((value) => [`${MASK}${hashJSON(value)}`, value]));
3589
+ }
3590
+ /**
3591
+ * The changes with the config's header values back in place of their
3592
+ * hashes, for the batch. Only the values a change sends need to be found:
3593
+ * those of `to`, which is the config. A hash the config does not have
3594
+ * stays as it is; apply refuses a plan whose config moved before it gets
3595
+ * here.
3596
+ */
3597
+ function unmaskSecrets(changes, values) {
3598
+ const unmask = (value) => values.get(value) ?? value;
3599
+ return mapSecrets(mapHeaders(changes, (headers) => mapValues(headers, unmask)), unmask);
3600
+ }
3601
+ function unsendableOAuthSecrets(changes) {
3602
+ return changes.flatMap((change) => {
3603
+ if (change.resource !== "remoteSource" || change.action === "delete") return [];
3604
+ const prefix = remoteSourcePrefixOf(change);
3605
+ if (change.clientSecret === null) return [{
3606
+ prefix,
3607
+ reason: "missing"
3608
+ }];
3609
+ if (change.clientSecret?.startsWith(MASK)) return [{
3610
+ prefix,
3611
+ reason: "changed"
3612
+ }];
3613
+ return [];
3614
+ });
3615
+ }
3616
+ /** Every OAuth secret a remote source change sends, passed through `map`. */
3617
+ function mapSecrets(changes, map) {
3618
+ return changes.map((change) => {
3619
+ if (change.resource !== "remoteSource" || change.action === "delete" || typeof change.clientSecret !== "string") return change;
3620
+ return {
3621
+ ...change,
3622
+ clientSecret: map(change.clientSecret)
3623
+ };
3624
+ });
3625
+ }
3626
+ function mapValues(headers, map) {
3627
+ return Object.fromEntries(Object.entries(headers).map(([name, values]) => [name, values.map(map)]));
3628
+ }
3629
+ /**
3630
+ * Every set of headers a remote source change or a remote field change
3631
+ * holds, passed through `map`.
3632
+ */
3633
+ function mapHeaders(changes, map) {
3634
+ const each = (headers) => headers === null ? null : map(headers);
3635
+ return changes.map((change) => {
3636
+ if (change.resource === "field") {
3637
+ if (change.action === "create" && change.field.kind === "remote") return {
3638
+ ...change,
3639
+ field: {
3640
+ ...change.field,
3641
+ headers: each(change.field.headers)
3642
+ }
3643
+ };
3644
+ if (change.action === "update" && change.kind === "remote" && change.changes.headers) {
3645
+ const { headers } = change.changes;
3646
+ return {
3647
+ ...change,
3648
+ changes: {
3649
+ ...change.changes,
3650
+ headers: {
3651
+ from: each(headers.from),
3652
+ to: each(headers.to)
3653
+ }
3654
+ }
3655
+ };
3656
+ }
3657
+ return change;
3658
+ }
3659
+ if (change.resource !== "remoteSource") return change;
3660
+ if (change.action === "create") {
3661
+ const source = change.remoteSource;
3662
+ return {
3663
+ ...change,
3664
+ remoteSource: source.type === "GRAPHQL" ? {
3665
+ ...source,
3666
+ headers: each(source.headers),
3667
+ introspectionHeaders: each(source.introspectionHeaders)
3668
+ } : {
3669
+ ...source,
3670
+ headers: each(source.headers)
3671
+ }
3672
+ };
3673
+ }
3674
+ if (change.action === "update") {
3675
+ const { headers, introspectionHeaders } = change.changes;
3676
+ return {
3677
+ ...change,
3678
+ headers: each(change.headers),
3679
+ introspectionHeaders: each(change.introspectionHeaders),
3680
+ changes: {
3681
+ ...change.changes,
3682
+ ...headers && { headers: {
3683
+ from: each(headers.from),
3684
+ to: each(headers.to)
3685
+ } },
3686
+ ...introspectionHeaders && { introspectionHeaders: {
3687
+ from: each(introspectionHeaders.from),
3688
+ to: each(introspectionHeaders.to)
3689
+ } }
3690
+ }
3691
+ };
3692
+ }
3693
+ return change;
3694
+ });
3695
+ }
3696
+ /** The changes hold a hash of each remote source header value, not the value. */
3547
3697
  function buildPlan({ target, desired, intents, live, changes }) {
3548
3698
  const planTarget = {
3549
3699
  project: target.project,
3550
3700
  environment: target.environment
3551
3701
  };
3702
+ const masked = maskSecrets(changes);
3552
3703
  return {
3553
3704
  formatVersion: 1,
3554
3705
  target: planTarget,
3555
3706
  desiredFingerprint: desiredFingerprint(desired, intents),
3556
3707
  liveFingerprint: hashIR(live),
3557
- planHash: planHash(planTarget, changes),
3558
- summary: summarise(changes),
3559
- changes
3708
+ planHash: planHash(planTarget, masked),
3709
+ summary: summarise(masked),
3710
+ changes: masked
3560
3711
  };
3561
3712
  }
3562
3713
  /** The config as written: its canonical IR and the renames it declares. */
@@ -5492,6 +5643,7 @@ const FIELD_FAMILY = {
5492
5643
  referenceUnionMember: "Union",
5493
5644
  component: "Component",
5494
5645
  componentUnion: "ComponentUnion",
5646
+ remote: "Remote",
5495
5647
  taxonomy: "Taxonomy"
5496
5648
  };
5497
5649
  /** Which family each of Hygraph's types belongs to. */
@@ -5555,6 +5707,10 @@ const FIELD_BUILDERS = {
5555
5707
  Taxonomy: {
5556
5708
  create: createTaxonomyField,
5557
5709
  update: updateTaxonomyField
5710
+ },
5711
+ Remote: {
5712
+ create: createRemoteField,
5713
+ update: updateRemoteField
5558
5714
  }
5559
5715
  };
5560
5716
  function familyOf(change) {
@@ -5912,13 +6068,15 @@ function createReferenceTwoWayField({ parent, partner }, field) {
5912
6068
  };
5913
6069
  }
5914
6070
  /**
5915
- * Asset gets the other side as Studio makes it: `imagePost` for a field
5916
- * `image` on `Post`, for its apiId and its displayName, as a list, and
5917
- * `API_ONLY`. It is two-way on a model; the server makes it one-way on a
5918
- * component. It has no position: the server gives it one.
6071
+ * Asset gets the other side in the same create. On a model, it is the
6072
+ * field back the config declares on Asset, the partner, with its own name,
6073
+ * description, visibility and slot; its condition, which the batch takes
6074
+ * no part of here, goes in an update after the creates. On a component,
6075
+ * the server makes it one-way and hidden, so the CLI names it as Studio
6076
+ * does, `iconCard` for `icon` on `Card`, a list and `API_ONLY`.
5919
6077
  */
5920
- function createAssetField({ parent }, field) {
5921
- const reverseApiId = assetReverseApiId(field.apiId, parent);
6078
+ function createAssetField({ parent, partner }, field) {
6079
+ const hidden = assetReverseApiId(field.apiId, parent);
5922
6080
  return {
5923
6081
  apiId: field.apiId,
5924
6082
  parentApiId: parent,
@@ -5930,13 +6088,22 @@ function createAssetField({ parent }, field) {
5930
6088
  visibility: field.visibility,
5931
6089
  visibilityCondition: field.visibilityCondition,
5932
6090
  position: field.position,
5933
- reverseField: {
5934
- apiId: reverseApiId,
5935
- displayName: reverseApiId,
6091
+ reverseField: partner === void 0 ? {
6092
+ apiId: hidden,
6093
+ displayName: hidden,
5936
6094
  modelApiId: "Asset",
5937
6095
  isUnidirectional: false,
5938
6096
  isList: true,
5939
6097
  visibility: "API_ONLY"
6098
+ } : {
6099
+ apiId: partner.apiId,
6100
+ displayName: partner.displayName,
6101
+ description: partner.description,
6102
+ modelApiId: "Asset",
6103
+ isUnidirectional: false,
6104
+ isList: true,
6105
+ visibility: partner.visibility,
6106
+ position: partner.position
5940
6107
  }
5941
6108
  };
5942
6109
  }
@@ -6045,6 +6212,98 @@ function slugFormConfig(slug) {
6045
6212
  automaticSlug: slug.template ?? ""
6046
6213
  };
6047
6214
  }
6215
+ /**
6216
+ * `visibility` is always sent: the batch's default, API_ONLY, is not the
6217
+ * config's. Headers and arguments are left out when there are none.
6218
+ */
6219
+ function createRemoteField({ parent }, field) {
6220
+ const remoteConfig = {
6221
+ remoteSourcePrefix: field.source,
6222
+ returnTypeApiId: field.returnType,
6223
+ method: field.method,
6224
+ forwardClientHeaders: field.forwardClientHeaders,
6225
+ cacheTTLSeconds: field.cacheTTLSeconds
6226
+ };
6227
+ if (field.query !== null) remoteConfig.graphQLQuery = field.query;
6228
+ if (field.path !== null) remoteConfig.restPath = field.path;
6229
+ if (field.headers !== null) remoteConfig.headers = field.headers;
6230
+ const input = {
6231
+ apiId: field.apiId,
6232
+ parentApiId: parent,
6233
+ type: field.type,
6234
+ displayName: field.displayName,
6235
+ description: field.description,
6236
+ isList: field.list,
6237
+ isRequired: field.required,
6238
+ visibility: field.visibility,
6239
+ position: field.position,
6240
+ remoteConfig
6241
+ };
6242
+ if (field.args.length > 0) input.inputArgs = field.args.map(remoteFieldArgInput);
6243
+ return input;
6244
+ }
6245
+ /**
6246
+ * Only the attributes that change are sent. A rename is `newApiId`. The
6247
+ * source's type cannot change: the diff deletes and creates the field
6248
+ * instead. Hygraph keeps headers it is sent `null` for; `{}` clears them.
6249
+ */
6250
+ function updateRemoteField(change) {
6251
+ const { apiId, displayName, description, required, visibility, position, source, returnType, method, query, path, headers, forwardClientHeaders, cacheTTLSeconds, args } = change.changes;
6252
+ const input = {
6253
+ apiId: change.apiId,
6254
+ parentApiId: change.parent
6255
+ };
6256
+ if (apiId) input.newApiId = apiId.to;
6257
+ if (displayName) input.displayName = displayName.to;
6258
+ if (description) input.description = description.to;
6259
+ if (required) input.isRequired = required.to;
6260
+ if (visibility) input.visibility = visibility.to;
6261
+ if (position) input.position = position.to;
6262
+ const remoteConfig = {};
6263
+ if (source) remoteConfig.remoteSourcePrefix = source.to;
6264
+ if (returnType) remoteConfig.returnTypeApiId = returnType.to;
6265
+ if (method) remoteConfig.method = method.to;
6266
+ if (query) remoteConfig.graphQLQuery = query.to;
6267
+ if (path) remoteConfig.restPath = path.to;
6268
+ if (headers) remoteConfig.headers = headers.to ?? {};
6269
+ if (forwardClientHeaders) remoteConfig.forwardClientHeaders = forwardClientHeaders.to;
6270
+ if (cacheTTLSeconds) remoteConfig.cacheTTLSeconds = cacheTTLSeconds.to;
6271
+ if (Object.keys(remoteConfig).length > 0) input.remoteConfig = remoteConfig;
6272
+ if (args) input.inputArgs = upsertRemoteFieldArgs(args.from, args.to);
6273
+ return input;
6274
+ }
6275
+ function remoteFieldArgInput(arg) {
6276
+ return {
6277
+ apiId: arg.apiId,
6278
+ remoteTypeApiId: arg.type,
6279
+ isRequired: arg.required,
6280
+ isList: arg.list
6281
+ };
6282
+ }
6283
+ /**
6284
+ * The arguments `to` adds, the ones that differ, and the ones it drops,
6285
+ * matched by apiId. An update names the argument by `argApiId` and sends
6286
+ * only what differs.
6287
+ */
6288
+ function upsertRemoteFieldArgs(from, to) {
6289
+ const before = new Map(from.map((arg) => [arg.apiId, arg]));
6290
+ const after = new Set(to.map((arg) => arg.apiId));
6291
+ const updates = [];
6292
+ for (const arg of to) {
6293
+ const old = before.get(arg.apiId);
6294
+ if (old === void 0) continue;
6295
+ const update = { argApiId: arg.apiId };
6296
+ if (old.type !== arg.type) update.remoteTypeApiId = arg.type;
6297
+ if (old.required !== arg.required) update.isRequired = arg.required;
6298
+ if (old.list !== arg.list) update.isList = arg.list;
6299
+ if (Object.keys(update).length > 1) updates.push(update);
6300
+ }
6301
+ return {
6302
+ fieldInputArgsToCreate: to.filter((arg) => !before.has(arg.apiId)).map(remoteFieldArgInput),
6303
+ fieldInputArgsToUpdate: updates,
6304
+ fieldInputArgsToDelete: from.filter((arg) => !after.has(arg.apiId)).map((arg) => ({ argApiId: arg.apiId }))
6305
+ };
6306
+ }
6048
6307
  function deleteField(change) {
6049
6308
  return {
6050
6309
  apiId: change.apiId,
@@ -6086,6 +6345,121 @@ function stringValidationsInput(validations) {
6086
6345
  function jsonValue(value) {
6087
6346
  return value === null ? null : JSON.stringify(value);
6088
6347
  }
6348
+ //#endregion
6349
+ //#region src/plan/resources/remoteSource.ts
6350
+ /** One remote source change as the batch entry it becomes, keyed by its operation. */
6351
+ function toBatchRemoteSourceChange(change) {
6352
+ switch (change.action) {
6353
+ case "create": return createRemoteSource(change);
6354
+ case "update": return change.type === "GRAPHQL" ? { updateGraphQLRemoteSource: updateGraphQLRemoteSource(change) } : { updateRESTRemoteSource: updateRESTRemoteSource(change) };
6355
+ case "delete": return { deleteRemoteSource: { prefix: change.prefix } };
6356
+ }
6357
+ }
6358
+ /** The name of the batch operation a remote source change becomes. */
6359
+ function remoteSourceOperation(change) {
6360
+ if (change.action === "delete") return "deleteRemoteSource";
6361
+ const type = change.action === "create" ? change.remoteSource.type : change.type;
6362
+ return `${change.action}${type === "GRAPHQL" ? "GraphQL" : "REST"}RemoteSource`;
6363
+ }
6364
+ /**
6365
+ * Headers, type definitions and OAuth are left out when there are none.
6366
+ * Hygraph introspects a GraphQL source while it creates it, signed in when
6367
+ * it has OAuth.
6368
+ */
6369
+ function createRemoteSource({ remoteSource, clientSecret }) {
6370
+ const common = {
6371
+ prefix: remoteSource.prefix,
6372
+ displayName: remoteSource.displayName,
6373
+ description: remoteSource.description,
6374
+ url: remoteSource.url,
6375
+ debugEnabled: remoteSource.debugEnabled,
6376
+ kind: remoteSource.kind,
6377
+ ...remoteSource.headers === null ? {} : { headers: remoteSource.headers },
6378
+ ...remoteSource.typeDefinitions.length === 0 ? {} : { remoteTypeDefinitions: joinSdl(remoteSource.typeDefinitions) },
6379
+ ...remoteSource.oAuth === null ? {} : { oAuth: oAuthInput(remoteSource.oAuth, clientSecret) }
6380
+ };
6381
+ if (remoteSource.type === "REST") return { createRESTRemoteSource: common };
6382
+ return { createGraphQLRemoteSource: {
6383
+ ...common,
6384
+ introspectionMethod: remoteSource.introspectionMethod,
6385
+ introspectionUrl: remoteSource.introspectionUrl,
6386
+ ...remoteSource.introspectionHeaders === null ? {} : { introspectionHeaders: remoteSource.introspectionHeaders }
6387
+ } };
6388
+ }
6389
+ /**
6390
+ * Only the attributes that change are sent, and both sets of headers: the
6391
+ * server clears the ones it is not sent.
6392
+ */
6393
+ function updateGraphQLRemoteSource(change) {
6394
+ const { displayName, introspectionMethod } = change.changes;
6395
+ const input = {
6396
+ prefix: change.prefix,
6397
+ ...updatedAttributes(change),
6398
+ headers: headersInput(change.headers),
6399
+ introspectionHeaders: headersInput(change.introspectionHeaders)
6400
+ };
6401
+ if (displayName) input.displayName = displayName.to;
6402
+ if (introspectionMethod) input.introspectionMethod = introspectionMethod.to;
6403
+ return input;
6404
+ }
6405
+ /** Only the attributes that change are sent, and the required `displayName`. */
6406
+ function updateRESTRemoteSource(change) {
6407
+ return {
6408
+ prefix: change.prefix,
6409
+ displayName: change.displayName,
6410
+ ...updatedAttributes(change)
6411
+ };
6412
+ }
6413
+ /**
6414
+ * The attributes both update operations take, those that change. OAuth
6415
+ * goes whole when it changes or a secret is sent; left out, Hygraph keeps
6416
+ * it.
6417
+ */
6418
+ function updatedAttributes({ changes, oAuth, clientSecret }) {
6419
+ const { description, url, headers, debugEnabled, typeDefinitions } = changes;
6420
+ const input = {};
6421
+ if (description) input.description = description.to;
6422
+ if (url) input.url = url.to;
6423
+ if (headers) input.headers = headersInput(headers.to);
6424
+ if (debugEnabled) input.debugEnabled = debugEnabled.to;
6425
+ if (changes.oAuth || typeof clientSecret === "string") input.oAuth = oAuth === null ? null : oAuthInput(oAuth, clientSecret);
6426
+ if (typeDefinitions) input.remoteTypeDefinitionsToUpsert = upsertTypeDefinitions(typeDefinitions.from, typeDefinitions.to);
6427
+ return input;
6428
+ }
6429
+ /**
6430
+ * Without a secret, Hygraph signs in with the one it keeps. No scopes is
6431
+ * `null`, as Studio sends it; an update keeps the scopes it is not sent.
6432
+ */
6433
+ function oAuthInput(oAuth, clientSecret) {
6434
+ return {
6435
+ clientId: oAuth.clientId,
6436
+ scopes: oAuth.scopes.length === 0 ? null : oAuth.scopes,
6437
+ authorizationGrantType: "client_credentials",
6438
+ authorizationUrl: oAuth.authorizationUrl,
6439
+ ...typeof clientSecret === "string" ? { clientSecret } : {}
6440
+ };
6441
+ }
6442
+ /** Hygraph keeps headers it is sent `null` for; `{}` clears them. */
6443
+ function headersInput(headers) {
6444
+ return headers ?? {};
6445
+ }
6446
+ /** The types `to` adds, the ones whose SDL differs, and the ones it drops. */
6447
+ function upsertTypeDefinitions(from, to) {
6448
+ const before = new Map(from.map((type) => [type.apiId, type.sdl]));
6449
+ const after = new Set(to.map((type) => type.apiId));
6450
+ return {
6451
+ remoteTypeDefinitionsToCreate: to.filter((type) => !before.has(type.apiId)).map((type) => ({ sdl: type.sdl })),
6452
+ remoteTypeDefinitionsToUpdate: to.filter((type) => before.has(type.apiId) && before.get(type.apiId) !== type.sdl).map((type) => ({
6453
+ apiId: type.apiId,
6454
+ sdl: type.sdl
6455
+ })),
6456
+ remoteTypeDefinitionsToDelete: from.filter((type) => !after.has(type.apiId)).map((type) => ({ apiId: type.apiId }))
6457
+ };
6458
+ }
6459
+ /** A create takes every type as one SDL document. */
6460
+ function joinSdl(types) {
6461
+ return { sdl: types.map((type) => type.sdl).join("\n") };
6462
+ }
6089
6463
  /** The heading each resource kind's changes are listed under. */
6090
6464
  const RESOURCE_TITLES = {
6091
6465
  locale: "Locales",
@@ -6094,6 +6468,7 @@ const RESOURCE_TITLES = {
6094
6468
  enumerationValue: "Enumeration values",
6095
6469
  taxonomy: "Taxonomies",
6096
6470
  taxonomyNode: "Taxonomy nodes",
6471
+ remoteSource: "Remote sources",
6097
6472
  component: "Components",
6098
6473
  model: "Models",
6099
6474
  field: "Fields"
@@ -6101,8 +6476,8 @@ const RESOURCE_TITLES = {
6101
6476
  /**
6102
6477
  * The order the sections are listed in: locales and stages first, an
6103
6478
  * enumeration before its values, a taxonomy before its nodes, a model or
6104
- * component before its fields, enumerations and taxonomies before the
6105
- * fields that use them.
6479
+ * component before its fields, enumerations, taxonomies and remote sources
6480
+ * before the fields that use them.
6106
6481
  */
6107
6482
  const RESOURCES = [
6108
6483
  "locale",
@@ -6111,6 +6486,7 @@ const RESOURCES = [
6111
6486
  "enumerationValue",
6112
6487
  "taxonomy",
6113
6488
  "taxonomyNode",
6489
+ "remoteSource",
6114
6490
  "component",
6115
6491
  "model",
6116
6492
  "field"
@@ -6166,6 +6542,7 @@ function operation(change) {
6166
6542
  case "enumerationValue": return "updateEnumeration";
6167
6543
  case "taxonomy": return `${change.action}Taxonomy`;
6168
6544
  case "taxonomyNode": return `${change.action}TaxonomyNode`;
6545
+ case "remoteSource": return remoteSourceOperation(change);
6169
6546
  case "component": return `${change.action}Component`;
6170
6547
  case "model": return `${change.action}Model`;
6171
6548
  case "field": return fieldOperation(change);
@@ -6179,6 +6556,7 @@ function renderChangeLine(change, width, colors) {
6179
6556
  case "enumerationValue": return renderEnumerationValueChange(change, width, colors);
6180
6557
  case "taxonomy": return renderTaxonomyChange(change, width, colors);
6181
6558
  case "taxonomyNode": return renderTaxonomyNodeChange(change, width, colors);
6559
+ case "remoteSource": return renderRemoteSourceChange(change, width, colors);
6182
6560
  case "component": return renderComponentChange(change, width, colors);
6183
6561
  case "model": return renderModelChange(change, width, colors);
6184
6562
  case "field": return renderFieldChange(change, width, colors);
@@ -6326,6 +6704,74 @@ function renderTaxonomyNodeChange(change, width, colors) {
6326
6704
  case "delete": return [` ${colors.red(`- ${op}`)} ${change.taxonomy}.${change.apiId} ${colors.yellow(`⚠ deletes the node and the nodes under it; the migration fails while entries hold one`)}`];
6327
6705
  }
6328
6706
  }
6707
+ /** A source is named by its prefix. Its types are listed by name. */
6708
+ function renderRemoteSourceChange(change, width, colors) {
6709
+ const op = operation(change).padEnd(width);
6710
+ switch (change.action) {
6711
+ case "create": {
6712
+ const source = change.remoteSource;
6713
+ const rows = [
6714
+ ["displayName", source.displayName],
6715
+ ["description", source.description],
6716
+ ["url", source.url],
6717
+ ["kind", source.kind],
6718
+ ["debugEnabled", source.debugEnabled || null],
6719
+ ["oAuth", source.oAuth],
6720
+ ...source.type === "GRAPHQL" ? [["introspectionMethod", source.introspectionMethod], ["introspectionUrl", source.introspectionUrl]] : []
6721
+ ].flatMap(([attribute, setting]) => setting === null ? [] : [settingRow(attribute, setting)]);
6722
+ const headers = [["headers", source.headers], ["introspectionHeaders", source.type === "GRAPHQL" ? source.introspectionHeaders : null]];
6723
+ for (const [attribute, each] of headers) if (each !== null) rows.push({
6724
+ attribute,
6725
+ text: Object.keys(each).join(", ")
6726
+ });
6727
+ if (source.typeDefinitions.length > 0) rows.push({
6728
+ attribute: "typeDefinitions",
6729
+ text: source.typeDefinitions.map((type) => type.apiId).join(", ")
6730
+ });
6731
+ rows.push(...secretRow(change.clientSecret));
6732
+ return [` ${colors.green(`+ ${op}`)} ${source.prefix}`, ...renderRows(rows, colors)];
6733
+ }
6734
+ case "update": {
6735
+ const { typeDefinitions, headers, introspectionHeaders, ...attributes } = change.changes;
6736
+ const rows = Object.entries(attributes).flatMap(([attribute, each]) => each === void 0 ? [] : [changeRow(attribute, each)]);
6737
+ for (const [attribute, each] of [["headers", headers], ["introspectionHeaders", introspectionHeaders]]) if (each) rows.push(keyedChanges(attribute, headerEntries(each.from), headerEntries(each.to)));
6738
+ if (typeDefinitions) rows.push(keyedChanges("typeDefinitions", typeDefinitions.from.map((type) => [type.apiId, type.sdl]), typeDefinitions.to.map((type) => [type.apiId, type.sdl])));
6739
+ rows.push(...secretRow(change.clientSecret));
6740
+ return [` ${colors.yellow(`~ ${op}`)} ${change.prefix}`, ...renderRows(rows, colors)];
6741
+ }
6742
+ case "delete": return [` ${colors.red(`- ${op}`)} ${change.prefix} ${colors.yellow(`⚠ deletes the remote source`)}`];
6743
+ }
6744
+ }
6745
+ /** Whether the change sends the OAuth secret, never its value or hash. */
6746
+ function secretRow(clientSecret) {
6747
+ if (clientSecret === void 0) return [];
6748
+ return [{
6749
+ attribute: "oAuth.clientSecret",
6750
+ text: clientSecret === null ? "not set: apply refuses this plan" : "sent from the config"
6751
+ }];
6752
+ }
6753
+ /**
6754
+ * One entry per key `to` adds, changes or drops: a type by its name, a
6755
+ * header by its name. Values are compared, never shown, so a header's
6756
+ * stays out of the output.
6757
+ */
6758
+ function keyedChanges(attribute, from, to) {
6759
+ const before = new Map(from);
6760
+ const after = new Map(to);
6761
+ return {
6762
+ attribute,
6763
+ text: "",
6764
+ entries: [.../* @__PURE__ */ new Set([...before.keys(), ...after.keys()])].toSorted().flatMap((apiId) => {
6765
+ if (!before.has(apiId)) return [[apiId, "added"]];
6766
+ if (!after.has(apiId)) return [[apiId, "removed"]];
6767
+ return before.get(apiId) === after.get(apiId) ? [] : [[apiId, "changed"]];
6768
+ })
6769
+ };
6770
+ }
6771
+ /** A header's values as one string, to compare. */
6772
+ function headerEntries(headers) {
6773
+ return Object.entries(headers ?? {}).map(([name, values]) => [name, values.join("\n")]);
6774
+ }
6329
6775
  function renderComponentChange(change, width, colors) {
6330
6776
  const op = operation(change).padEnd(width);
6331
6777
  switch (change.action) {
@@ -6366,9 +6812,16 @@ function renderFieldChange(change, width, colors) {
6366
6812
  ], colors)];
6367
6813
  case "update": {
6368
6814
  if (unsupportedFieldMove(change)) return [` ${colors.yellow(`~ ${op}`)} ${subject} ${colors.dim(change.type)}`, ...renderAttributes(change.changes, colors)];
6369
- const { apiId, ...attributes } = change.changes;
6815
+ const { apiId, headers, args, ...attributes } = change.changes;
6370
6816
  const warning = dropsUnionMember(change) ? ` ${colors.yellow(`⚠ deletes the content of the members it drops`)}` : dropsEmbed(change) ? ` ${colors.yellow(`⚠ deletes the embeds of the models it drops`)}` : makesAssetRequired(change) ? ` ${colors.yellow(`⚠ API creates must set it; entries without an asset may fail to read`)}` : "";
6371
- return [` ${colors.yellow(`~ ${op}`)} ${apiId ? `${subject} → ${apiId.to}` : subject}${warning}`, ...renderAttributes(attributes, colors, change.migrationValue)];
6817
+ const rows = Object.entries(attributes).flatMap(([attribute, each]) => each === void 0 ? [] : [changeRow(attribute, each)]);
6818
+ if (headers) rows.push(keyedChanges("headers", headerEntries(headers.from), headerEntries(headers.to)));
6819
+ if (args) rows.push(keyedChanges("args", args.from.map((arg) => [arg.apiId, JSON.stringify(arg)]), args.to.map((arg) => [arg.apiId, JSON.stringify(arg)])));
6820
+ if (change.migrationValue !== void 0) rows.push({
6821
+ attribute: "migrationValue",
6822
+ text: value(change.migrationValue)
6823
+ });
6824
+ return [` ${colors.yellow(`~ ${op}`)} ${apiId ? `${subject} → ${apiId.to}` : subject}${warning}`, ...renderRows(rows, colors)];
6372
6825
  }
6373
6826
  case "delete": {
6374
6827
  const { partner, members } = change;
@@ -6386,13 +6839,30 @@ const UNSHOWN = /* @__PURE__ */ new Set([
6386
6839
  ]);
6387
6840
  /** The shared defaults a create leaves out. Any other setting is shown unless `null`. */
6388
6841
  const DEFAULTS = FIELD_DEFAULTS;
6842
+ /** A remote field's defaults, and its `type`, which its source says. */
6843
+ const REMOTE_FIELD_DEFAULTS = {
6844
+ ...FIELD_DEFAULTS,
6845
+ ...REMOTE_DEFAULTS
6846
+ };
6389
6847
  /**
6390
6848
  * One line per setting of a new field, so the plan shows what will be
6391
6849
  * created. Settings at their default are left out, as export leaves them
6392
6850
  * out.
6393
6851
  */
6394
6852
  function settingRows(field, unshown = UNSHOWN) {
6395
- return Object.entries(field).flatMap(([attribute, setting]) => unshown.has(attribute) || setting === null || setting === DEFAULTS[attribute] ? [] : [settingRow(attribute, setting)]);
6853
+ const defaults = field.kind === "remote" ? REMOTE_FIELD_DEFAULTS : DEFAULTS;
6854
+ return Object.entries(field).flatMap(([attribute, setting]) => {
6855
+ if (unshown.has(attribute) || setting === null || setting === defaults[attribute] || field.kind === "remote" && attribute === "type") return [];
6856
+ if (field.kind === "remote" && attribute === "headers" && field.headers) return [{
6857
+ attribute,
6858
+ text: Object.keys(field.headers).join(", ")
6859
+ }];
6860
+ if (field.kind === "remote" && attribute === "args") return field.args.length === 0 ? [] : [{
6861
+ attribute,
6862
+ text: field.args.map((arg) => arg.apiId).join(", ")
6863
+ }];
6864
+ return [settingRow(attribute, setting)];
6865
+ });
6396
6866
  }
6397
6867
  /** The partner's own settings: its `to` and `reverse` point back at the field. */
6398
6868
  const UNSHOWN_ON_PARTNER = /* @__PURE__ */ new Set([
@@ -6433,7 +6903,7 @@ function renderAttributes(attributes, colors, migrationValue) {
6433
6903
  * Attributes shown as one line per entry below their name, for values too
6434
6904
  * long to read on one line.
6435
6905
  */
6436
- const NESTED = /* @__PURE__ */ new Set(["validations"]);
6906
+ const NESTED = /* @__PURE__ */ new Set(["validations", "oAuth"]);
6437
6907
  function settingRow(attribute, setting) {
6438
6908
  if (!NESTED.has(attribute) || !isRecord(setting)) return {
6439
6909
  attribute,
@@ -6442,7 +6912,7 @@ function settingRow(attribute, setting) {
6442
6912
  return {
6443
6913
  attribute,
6444
6914
  text: "",
6445
- entries: Object.entries(setting).flatMap(([key, entry]) => entry === null ? [] : [[key, value(entry)]])
6915
+ entries: Object.entries(setting).flatMap(([key, entry]) => entry === null || Array.isArray(entry) && entry.length === 0 ? [] : [[key, value(entry)]])
6446
6916
  };
6447
6917
  }
6448
6918
  /**
@@ -6547,11 +7017,20 @@ function renderWarningBox(title, lines, colors) {
6547
7017
  ""
6548
7018
  ].join("\n");
6549
7019
  }
7020
+ /**
7021
+ * What the server says when it cannot trade a remote source's OAuth client
7022
+ * for a token, often because the secret changed on the platform's side.
7023
+ */
7024
+ const OAUTH_FAILURE = "Failed to process OAuth";
6550
7025
  /** What the server said about a migration it did not finish, and where that leaves the environment. */
6551
7026
  function renderFailedMigration(migration) {
6552
7027
  const name = migration.name ?? migration.id;
6553
7028
  if (migration.status === "TIMEOUT") return `migration ${name} timed out on the server. Run plan to see what state the environment is in.`;
6554
- return [`migration ${name} failed: ${migration.errors ?? "the server gave no reason"}`, "Nothing was applied: the migration is one transaction and was rolled back. Run plan to see the environment as it is now."].join("\n");
7029
+ return [
7030
+ `migration ${name} failed: ${migration.errors ?? "the server gave no reason"}`,
7031
+ ...migration.errors?.includes(OAUTH_FAILURE) ? ["Hygraph could not sign in to a remote source with its OAuth client. If the client's secret changed, set the new one and plan with --rotate-secret <prefix>."] : [],
7032
+ "Nothing was applied: the migration is one transaction and was rolled back. Run plan to see the environment as it is now."
7033
+ ].join("\n");
6555
7034
  }
6556
7035
  function abbreviate(value) {
6557
7036
  return /^[0-9a-f]{64}$/.test(value) ? `sha256:${value.slice(0, 4)}…${value.slice(-4)}` : value;
@@ -7651,6 +8130,7 @@ const integer = /^-?\d+$/;
7651
8130
  const number$1 = /^-?\d+(?:\.\d+)?$/;
7652
8131
  const boolean$1 = /^(?:true|false)$/i;
7653
8132
  const _null$2 = /^null$/i;
8133
+ const _undefined$2 = /^undefined$/i;
7654
8134
  const lowercase = /^[^A-Z]*$/;
7655
8135
  const uppercase = /^[^a-z]*$/;
7656
8136
  //#endregion
@@ -8472,6 +8952,22 @@ const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
8472
8952
  return payload;
8473
8953
  };
8474
8954
  });
8955
+ const $ZodUndefined = /*@__PURE__*/ $constructor("$ZodUndefined", (inst, def) => {
8956
+ $ZodType.init(inst, def);
8957
+ inst._zod.pattern = _undefined$2;
8958
+ inst._zod.values = /* @__PURE__ */ new Set([void 0]);
8959
+ inst._zod.parse = (payload, _ctx) => {
8960
+ const input = payload.value;
8961
+ if (typeof input === "undefined") return payload;
8962
+ payload.issues.push({
8963
+ expected: "undefined",
8964
+ code: "invalid_type",
8965
+ input,
8966
+ inst
8967
+ });
8968
+ return payload;
8969
+ };
8970
+ });
8475
8971
  const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => {
8476
8972
  $ZodType.init(inst, def);
8477
8973
  inst._zod.pattern = _null$2;
@@ -10170,6 +10666,13 @@ function _boolean(Class, params) {
10170
10666
  });
10171
10667
  }
10172
10668
  // @__NO_SIDE_EFFECTS__
10669
+ function _undefined$1(Class, params) {
10670
+ return new Class({
10671
+ type: "undefined",
10672
+ ...normalizeParams(params)
10673
+ });
10674
+ }
10675
+ // @__NO_SIDE_EFFECTS__
10173
10676
  function _null$1(Class, params) {
10174
10677
  return new Class({
10175
10678
  type: "null",
@@ -10976,6 +11479,9 @@ const nullProcessor = (_schema, ctx, json, _params) => {
10976
11479
  json.enum = [null];
10977
11480
  } else json.type = "null";
10978
11481
  };
11482
+ const undefinedProcessor = (schema, ctx, json, params) => {
11483
+ handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema");
11484
+ };
10979
11485
  const neverProcessor = (_schema, _ctx, json, _params) => {
10980
11486
  json.not = {};
10981
11487
  };
@@ -11347,7 +11853,7 @@ const initializer = (inst, issues) => {
11347
11853
  const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
11348
11854
  //#endregion
11349
11855
  //#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/parse.js
11350
- const parse$2 = /* @__PURE__ */ _parse(ZodRealError);
11856
+ const parse$3 = /* @__PURE__ */ _parse(ZodRealError);
11351
11857
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
11352
11858
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
11353
11859
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
@@ -11479,7 +11985,7 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
11479
11985
  own(this, "~standard", value);
11480
11986
  },
11481
11987
  parse: function _parse(data, params) {
11482
- return parse$2(this, data, params, { callee: _parse });
11988
+ return parse$3(this, data, params, { callee: _parse });
11483
11989
  },
11484
11990
  parseAsync: async function _parseAsync(data, params) {
11485
11991
  return await parseAsync(this, data, params, { callee: _parseAsync });
@@ -11863,6 +12369,14 @@ const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
11863
12369
  function boolean(params) {
11864
12370
  return /* @__PURE__ */ _boolean(ZodBoolean, params);
11865
12371
  }
12372
+ const ZodUndefined = /*@__PURE__*/ $constructor("ZodUndefined", (inst, def) => {
12373
+ $ZodUndefined.init(inst, def);
12374
+ ZodType.init(inst, def);
12375
+ inst._zod.processJSONSchema = (ctx, json, params) => undefinedProcessor(inst, ctx, json, params);
12376
+ });
12377
+ function _undefined(params) {
12378
+ return /* @__PURE__ */ _undefined$1(ZodUndefined, params);
12379
+ }
11866
12380
  const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => {
11867
12381
  $ZodNull.init(inst, def);
11868
12382
  ZodType.init(inst, def);
@@ -12645,6 +13159,77 @@ const taxonomyNodeChangeSchema = discriminatedUnion("action", [
12645
13159
  apiId: string$1()
12646
13160
  })
12647
13161
  ]);
13162
+ const remoteHeadersSchema = record(string$1(), array(string$1()));
13163
+ const remoteSourceKindSchema = _enum([
13164
+ "CommerceLayer",
13165
+ "CommerceTools",
13166
+ "Custom"
13167
+ ]);
13168
+ const introspectionMethodSchema = _enum(["GET", "POST"]);
13169
+ const remoteTypeDefinitionSchema = strictObject({
13170
+ apiId: string$1(),
13171
+ sdl: string$1()
13172
+ });
13173
+ const remoteSourceOAuthSchema = strictObject({
13174
+ clientId: string$1(),
13175
+ scopes: array(string$1()),
13176
+ authorizationUrl: string$1()
13177
+ });
13178
+ const remoteSourceAttributes = {
13179
+ prefix: string$1(),
13180
+ displayName: string$1(),
13181
+ description: string$1().nullable(),
13182
+ url: string$1(),
13183
+ headers: remoteHeadersSchema.nullable(),
13184
+ debugEnabled: boolean(),
13185
+ kind: remoteSourceKindSchema,
13186
+ oAuth: remoteSourceOAuthSchema.nullable(),
13187
+ typeDefinitions: array(remoteTypeDefinitionSchema)
13188
+ };
13189
+ const remoteSourceChangeSchema = discriminatedUnion("action", [
13190
+ strictObject({
13191
+ action: literal("create"),
13192
+ resource: literal("remoteSource"),
13193
+ remoteSource: discriminatedUnion("type", [strictObject({
13194
+ ...remoteSourceAttributes,
13195
+ type: literal("GRAPHQL"),
13196
+ introspectionMethod: introspectionMethodSchema,
13197
+ introspectionUrl: string$1().nullable(),
13198
+ introspectionHeaders: remoteHeadersSchema.nullable()
13199
+ }), strictObject({
13200
+ ...remoteSourceAttributes,
13201
+ type: literal("REST")
13202
+ })]),
13203
+ clientSecret: string$1().nullable().optional()
13204
+ }),
13205
+ strictObject({
13206
+ action: literal("update"),
13207
+ resource: literal("remoteSource"),
13208
+ prefix: string$1(),
13209
+ type: _enum(["GRAPHQL", "REST"]),
13210
+ displayName: string$1(),
13211
+ headers: remoteHeadersSchema.nullable(),
13212
+ introspectionHeaders: remoteHeadersSchema.nullable(),
13213
+ oAuth: remoteSourceOAuthSchema.nullable(),
13214
+ clientSecret: string$1().nullable().optional(),
13215
+ changes: strictObject({
13216
+ displayName: attributeChangeSchema(string$1()),
13217
+ description: attributeChangeSchema(string$1().nullable()),
13218
+ url: attributeChangeSchema(string$1()),
13219
+ headers: attributeChangeSchema(remoteHeadersSchema.nullable()),
13220
+ debugEnabled: attributeChangeSchema(boolean()),
13221
+ oAuth: attributeChangeSchema(remoteSourceOAuthSchema.nullable()),
13222
+ introspectionMethod: attributeChangeSchema(introspectionMethodSchema),
13223
+ introspectionHeaders: attributeChangeSchema(remoteHeadersSchema.nullable()),
13224
+ typeDefinitions: attributeChangeSchema(array(remoteTypeDefinitionSchema))
13225
+ }).partial()
13226
+ }),
13227
+ strictObject({
13228
+ action: literal("delete"),
13229
+ resource: literal("remoteSource"),
13230
+ prefix: string$1()
13231
+ })
13232
+ ]);
12648
13233
  /**
12649
13234
  * Every value a field can hold as `initialValue` or `migrationValue`: any
12650
13235
  * JSON but `null`, as a JSON field holds it, which covers every other
@@ -12723,6 +13308,13 @@ const referenceUnionMemberFieldSchema$1 = strictObject({
12723
13308
  reverse: string$1(),
12724
13309
  required: literal(false)
12725
13310
  });
13311
+ const remoteFieldArgSchema = strictObject({
13312
+ apiId: string$1(),
13313
+ type: string$1(),
13314
+ required: boolean(),
13315
+ list: boolean()
13316
+ });
13317
+ const remoteFieldMethodSchema = _enum(["GET", "POST"]);
12726
13318
  const fieldSchema$1 = discriminatedUnion("kind", [
12727
13319
  strictObject({
12728
13320
  ...fieldAttributes,
@@ -12840,7 +13432,23 @@ const fieldSchema$1 = discriminatedUnion("kind", [
12840
13432
  referenceUnionMemberFieldSchema$1,
12841
13433
  strictObject({
12842
13434
  ...fieldAttributes,
12843
- kind: literal("asset")
13435
+ kind: literal("asset"),
13436
+ reverse: string$1().optional()
13437
+ }),
13438
+ strictObject({
13439
+ ...fieldAttributes,
13440
+ kind: literal("remote"),
13441
+ source: string$1(),
13442
+ type: _enum(["GRAPHQL", "REST"]),
13443
+ returnType: string$1(),
13444
+ method: remoteFieldMethodSchema,
13445
+ query: string$1().nullable(),
13446
+ path: string$1().nullable(),
13447
+ headers: remoteHeadersSchema.nullable(),
13448
+ forwardClientHeaders: boolean(),
13449
+ cacheTTLSeconds: number(),
13450
+ args: array(remoteFieldArgSchema),
13451
+ visibilityCondition: _null()
12844
13452
  })
12845
13453
  ]);
12846
13454
  const fieldRefSchema = strictObject({
@@ -12854,6 +13462,7 @@ const changeSchema = discriminatedUnion("resource", [
12854
13462
  enumerationValueChangeSchema,
12855
13463
  taxonomyChangeSchema,
12856
13464
  taxonomyNodeChangeSchema,
13465
+ remoteSourceChangeSchema,
12857
13466
  componentChangeSchema,
12858
13467
  modelChangeSchema,
12859
13468
  discriminatedUnion("action", [
@@ -12894,7 +13503,8 @@ const changeSchema = discriminatedUnion("resource", [
12894
13503
  "referenceTwoWay",
12895
13504
  "referenceUnion",
12896
13505
  "referenceUnionMember",
12897
- "asset"
13506
+ "asset",
13507
+ "remote"
12898
13508
  ]),
12899
13509
  changes: strictObject({
12900
13510
  apiId: attributeChangeSchema(string$1()),
@@ -12915,7 +13525,16 @@ const changeSchema = discriminatedUnion("resource", [
12915
13525
  to: attributeChangeSchema(array(string$1())),
12916
13526
  rules: attributeChangeSchema(referenceRulesSchema.nullable()),
12917
13527
  embeds: attributeChangeSchema(array(string$1()).nullable()),
12918
- actions: attributeChangeSchema(richTextActionsSchema.nullable())
13528
+ actions: attributeChangeSchema(richTextActionsSchema.nullable()),
13529
+ source: attributeChangeSchema(string$1()),
13530
+ returnType: attributeChangeSchema(string$1()),
13531
+ method: attributeChangeSchema(remoteFieldMethodSchema),
13532
+ query: attributeChangeSchema(string$1().nullable()),
13533
+ path: attributeChangeSchema(string$1().nullable()),
13534
+ headers: attributeChangeSchema(remoteHeadersSchema.nullable()),
13535
+ forwardClientHeaders: attributeChangeSchema(boolean()),
13536
+ cacheTTLSeconds: attributeChangeSchema(number()),
13537
+ args: attributeChangeSchema(array(remoteFieldArgSchema))
12919
13538
  }).partial(),
12920
13539
  migrationValue: migrationValueSchema.optional(),
12921
13540
  memberPositions: record(string$1(), number()).optional()
@@ -13129,6 +13748,7 @@ const createReferenceFieldSchema = object$1({
13129
13748
  visibilityCondition: liveVisibilityConditionSchema.nullish(),
13130
13749
  relationalFieldRules: object$1({ connections: liveRangeSchema.nullish() }).nullish(),
13131
13750
  reverseField: object$1({
13751
+ apiId: string$1(),
13132
13752
  modelApiId: string$1(),
13133
13753
  isUnidirectional: boolean().nullish()
13134
13754
  })
@@ -13231,17 +13851,24 @@ function parseJSON(text) {
13231
13851
  //#region src/live/resources/asset.ts
13232
13852
  /**
13233
13853
  * An asset field, in the same canonical form `convertAssetFieldToIR` gives
13234
- * a config field, without its other side on Asset, one-way or two-way.
13235
- * `null` for any other relation, and for an asset field with rules, which
13236
- * the CLI does not represent yet.
13854
+ * a config field, and on a model its field back on Asset. A two-way one,
13855
+ * on a model, names its field back in `reverseField`, read as the two-way
13856
+ * reference the config declares on Asset; its condition is left out, as
13857
+ * the same request does not read Asset's fields. A one-way one, on one of
13858
+ * `components`, has a hidden field back with no slot. `null` for any other
13859
+ * relation, for an asset field with rules, and for a one-way one on a
13860
+ * model or on Asset, which only the API makes: the CLI does not represent
13861
+ * them yet.
13237
13862
  */
13238
- function convertCreateAssetFieldToIR(input) {
13863
+ function convertCreateAssetFieldToIR(input, components) {
13239
13864
  const setup = referenceSetupSchema.safeParse(input);
13240
13865
  if (!setup.success || setup.data.type !== "ASSET" || setup.data.reverseField.modelApiId !== "Asset" || (setup.data.relationalFieldRules ?? null) !== null) return null;
13241
- const parsed = createReferenceFieldSchema.safeParse(input);
13866
+ const oneWay = setup.data.reverseField.isUnidirectional === true;
13867
+ const parsed = (oneWay ? createReferenceFieldSchema : createReferenceTwoWayFieldSchema).safeParse(input);
13242
13868
  if (!parsed.success) throw new Error(`Invalid createRelationalField params: \n${renderIssues(parsed.error.issues)}`);
13243
13869
  const field = parsed.data;
13244
- return {
13870
+ if (oneWay && !components.has(field.parentApiId)) return null;
13871
+ const asset = {
13245
13872
  parentApiId: field.parentApiId,
13246
13873
  field: {
13247
13874
  kind: "asset",
@@ -13252,9 +13879,29 @@ function convertCreateAssetFieldToIR(input) {
13252
13879
  list: field.isList ?? false,
13253
13880
  required: field.isRequired ?? false,
13254
13881
  visibility: field.visibility ?? "READ_WRITE",
13255
- visibilityCondition: convertVisibilityCondition(field.visibilityCondition)
13882
+ visibilityCondition: convertVisibilityCondition(field.visibilityCondition),
13883
+ ...!oneWay && { reverse: field.reverseField.apiId }
13256
13884
  }
13257
13885
  };
13886
+ if (oneWay || !("displayName" in field.reverseField)) return [asset];
13887
+ const back = field.reverseField;
13888
+ return [asset, {
13889
+ parentApiId: "Asset",
13890
+ field: {
13891
+ kind: "referenceTwoWay",
13892
+ apiId: back.apiId,
13893
+ displayName: back.displayName,
13894
+ description: isEmpty(back.description) ? null : back.description,
13895
+ to: field.parentApiId,
13896
+ reverse: field.apiId,
13897
+ rules: null,
13898
+ position: back.position,
13899
+ list: back.isList ?? true,
13900
+ required: false,
13901
+ visibility: back.visibility ?? "READ_WRITE",
13902
+ visibilityCondition: null
13903
+ }
13904
+ }];
13258
13905
  }
13259
13906
  //#endregion
13260
13907
  //#region src/live/resources/boolean.zod.ts
@@ -13399,7 +14046,7 @@ function convertCreateComponentFieldToIR(input) {
13399
14046
  parentApiId: field.parentApiId,
13400
14047
  field: {
13401
14048
  kind: "component",
13402
- ...attributes(field),
14049
+ ...attributes$3(field),
13403
14050
  component: field.componentApiId,
13404
14051
  required: field.isRequired ?? false
13405
14052
  }
@@ -13414,13 +14061,13 @@ function convertCreateComponentUnionFieldToIR(input) {
13414
14061
  parentApiId: field.parentApiId,
13415
14062
  field: {
13416
14063
  kind: "componentUnion",
13417
- ...attributes(field),
14064
+ ...attributes$3(field),
13418
14065
  components: field.componentApiIds.toSorted(),
13419
14066
  required: false
13420
14067
  }
13421
14068
  };
13422
14069
  }
13423
- function attributes(field) {
14070
+ function attributes$3(field) {
13424
14071
  return {
13425
14072
  apiId: field.apiId,
13426
14073
  displayName: field.displayName,
@@ -13814,22 +14461,176 @@ function convertRules$1(rules) {
13814
14461
  return connections === null ? null : { connections };
13815
14462
  }
13816
14463
  //#endregion
13817
- //#region src/live/resources/richText.zod.ts
14464
+ //#region src/live/resources/remote-field.zod.ts
14465
+ const headersSchema$3 = record(string$1(), union([string$1(), array(string$1())])).nullish();
14466
+ const createRemoteFieldSchema = object$1({
14467
+ apiId: string$1(),
14468
+ parentApiId: string$1(),
14469
+ type: _enum(["GRAPHQL", "REST"]),
14470
+ displayName: string$1(),
14471
+ description: string$1().nullish(),
14472
+ position: number(),
14473
+ isList: boolean().nullish(),
14474
+ isRequired: boolean().nullish(),
14475
+ visibility: fieldVisibilitySchema.nullish(),
14476
+ remoteConfig: object$1({
14477
+ remoteSourcePrefix: string$1(),
14478
+ returnTypeApiId: string$1(),
14479
+ method: _enum(["GET", "POST"]),
14480
+ graphQLQuery: string$1().nullish(),
14481
+ restPath: string$1().nullish(),
14482
+ headers: headersSchema$3,
14483
+ forwardClientHeaders: boolean().nullish(),
14484
+ cacheTTLSeconds: number().nullish()
14485
+ }),
14486
+ inputArgs: array(object$1({
14487
+ apiId: string$1(),
14488
+ remoteTypeApiId: string$1(),
14489
+ isRequired: boolean(),
14490
+ isList: boolean()
14491
+ })).nullish()
14492
+ });
14493
+ //#endregion
14494
+ //#region src/live/resources/remote-field.ts
13818
14495
  /**
13819
- * What tells whether the CLI can express the field, read before the op is
13820
- * checked. A value it does not expect keeps the field unsupported instead
13821
- * of failing the plan. The editor's config is strict: an update replaces
13822
- * it whole, so a setting the CLI does not know would be lost.
14496
+ * The same canonical form `convertRemoteFieldToIR` gives a field from the
14497
+ * config, position as Hygraph stores it. An empty query or path is none,
14498
+ * header values are lists, and the arguments sort by apiId. A config Hygraph
14499
+ * stores without a cache time caches for its default, 900 seconds.
13823
14500
  */
13824
- const richTextSetupSchema = object$1({
13825
- formRenderer: string$1().nullish(),
13826
- formConfig: strictObject({
13827
- actions: array(_enum(RICH_TEXT_ACTIONS)).nullish(),
13828
- appApiId: string$1().nullish(),
13829
- appElementApiId: string$1().nullish()
13830
- }).nullish(),
13831
- embedsEnabled: boolean().nullish(),
13832
- embeddableModels: array(string$1()).nullish()
14501
+ function convertCreateRemoteFieldToIR(input) {
14502
+ const parsed = createRemoteFieldSchema.safeParse(input);
14503
+ if (!parsed.success) throw new Error(`Invalid createRemoteField params: \n${renderIssues(parsed.error.issues)}`);
14504
+ const field = parsed.data;
14505
+ const config = field.remoteConfig;
14506
+ return {
14507
+ parentApiId: field.parentApiId,
14508
+ field: {
14509
+ kind: "remote",
14510
+ apiId: field.apiId,
14511
+ displayName: field.displayName,
14512
+ description: isEmpty(field.description) ? null : field.description,
14513
+ position: field.position,
14514
+ list: field.isList ?? false,
14515
+ required: field.isRequired ?? false,
14516
+ visibility: field.visibility ?? "READ_WRITE",
14517
+ visibilityCondition: null,
14518
+ source: config.remoteSourcePrefix,
14519
+ type: field.type,
14520
+ returnType: config.returnTypeApiId,
14521
+ method: config.method,
14522
+ query: isEmpty(config.graphQLQuery) ? null : config.graphQLQuery,
14523
+ path: isEmpty(config.restPath) ? null : config.restPath,
14524
+ headers: convertHeadersToIR(config.headers ?? {}),
14525
+ forwardClientHeaders: config.forwardClientHeaders ?? false,
14526
+ cacheTTLSeconds: config.cacheTTLSeconds ?? 900,
14527
+ args: (field.inputArgs ?? []).map((arg) => ({
14528
+ apiId: arg.apiId,
14529
+ type: arg.remoteTypeApiId,
14530
+ required: arg.isRequired,
14531
+ list: arg.isList
14532
+ })).toSorted(byApiId$1)
14533
+ }
14534
+ };
14535
+ }
14536
+ //#endregion
14537
+ //#region src/live/resources/remoteSource.zod.ts
14538
+ const headersSchema$2 = record(string$1(), union([string$1(), array(string$1())])).nullish();
14539
+ const kindSchema = _enum([
14540
+ "CommerceLayer",
14541
+ "CommerceTools",
14542
+ "Custom"
14543
+ ]);
14544
+ const attributes$2 = {
14545
+ prefix: string$1(),
14546
+ displayName: string$1(),
14547
+ description: string$1().nullish(),
14548
+ url: string$1(),
14549
+ headers: headersSchema$2,
14550
+ debugEnabled: boolean().nullish(),
14551
+ kind: kindSchema,
14552
+ remoteTypeDefinitions: object$1({ sdl: string$1() }).nullish(),
14553
+ oAuth: union([
14554
+ object$1({
14555
+ clientId: string$1(),
14556
+ scopes: string$1().nullish(),
14557
+ authorizationUrl: string$1()
14558
+ }),
14559
+ _null(),
14560
+ literal(false)
14561
+ ]).optional()
14562
+ };
14563
+ const createGraphQLRemoteSourceSchema = object$1({
14564
+ ...attributes$2,
14565
+ introspectionMethod: _enum(["GET", "POST"]).nullish(),
14566
+ introspectionUrl: string$1().nullish(),
14567
+ introspectionHeaders: headersSchema$2
14568
+ });
14569
+ const createRESTRemoteSourceSchema = object$1(attributes$2);
14570
+ //#endregion
14571
+ //#region src/live/resources/remoteSource.ts
14572
+ /**
14573
+ * The same canonical form `convertRemoteSourceToIR` gives a source from the
14574
+ * config. `schemaDefinition` returns every header value as a list and the
14575
+ * types as one document; the GraphQL source's introspected types are not
14576
+ * in it, and neither is the OAuth secret. A source without an
14577
+ * introspection method introspects with POST.
14578
+ */
14579
+ function convertCreateGraphQLRemoteSourceToIR(input) {
14580
+ const parsed = createGraphQLRemoteSourceSchema.safeParse(input);
14581
+ if (!parsed.success) throw new Error(`Invalid createGraphQLRemoteSource params: \n${renderIssues(parsed.error.issues)}`);
14582
+ const source = parsed.data;
14583
+ return {
14584
+ ...attributes$1(source),
14585
+ type: "GRAPHQL",
14586
+ introspectionMethod: source.introspectionMethod ?? "POST",
14587
+ introspectionUrl: isEmpty(source.introspectionUrl) ? null : source.introspectionUrl,
14588
+ introspectionHeaders: convertHeadersToIR(source.introspectionHeaders ?? {})
14589
+ };
14590
+ }
14591
+ function convertCreateRESTRemoteSourceToIR(input) {
14592
+ const parsed = createRESTRemoteSourceSchema.safeParse(input);
14593
+ if (!parsed.success) throw new Error(`Invalid createRESTRemoteSource params: \n${renderIssues(parsed.error.issues)}`);
14594
+ return {
14595
+ ...attributes$1(parsed.data),
14596
+ type: "REST"
14597
+ };
14598
+ }
14599
+ function attributes$1(source) {
14600
+ const sdl = source.remoteTypeDefinitions?.sdl;
14601
+ return {
14602
+ prefix: source.prefix,
14603
+ displayName: source.displayName,
14604
+ description: isEmpty(source.description) ? null : source.description,
14605
+ url: source.url,
14606
+ headers: convertHeadersToIR(source.headers ?? {}),
14607
+ debugEnabled: source.debugEnabled ?? false,
14608
+ kind: source.kind,
14609
+ oAuth: source.oAuth ? convertOAuthToIR({
14610
+ clientId: source.oAuth.clientId,
14611
+ scopes: (source.oAuth.scopes ?? "").split(" ").filter(Boolean),
14612
+ authorizationUrl: source.oAuth.authorizationUrl
14613
+ }) : null,
14614
+ typeDefinitions: isEmpty(sdl) ? [] : splitTypeDefinitions(sdl)
14615
+ };
14616
+ }
14617
+ //#endregion
14618
+ //#region src/live/resources/richText.zod.ts
14619
+ /**
14620
+ * What tells whether the CLI can express the field, read before the op is
14621
+ * checked. A value it does not expect keeps the field unsupported instead
14622
+ * of failing the plan. The editor's config is strict: an update replaces
14623
+ * it whole, so a setting the CLI does not know would be lost.
14624
+ */
14625
+ const richTextSetupSchema = object$1({
14626
+ formRenderer: string$1().nullish(),
14627
+ formConfig: strictObject({
14628
+ actions: array(_enum(RICH_TEXT_ACTIONS)).nullish(),
14629
+ appApiId: string$1().nullish(),
14630
+ appElementApiId: string$1().nullish()
14631
+ }).nullish(),
14632
+ embedsEnabled: boolean().nullish(),
14633
+ embeddableModels: array(string$1()).nullish()
13833
14634
  });
13834
14635
  const createRichTextFieldSchema = object$1({
13835
14636
  ...simpleFieldShape,
@@ -14217,6 +15018,12 @@ function convertRules(rules) {
14217
15018
  return connections === null ? null : { connections };
14218
15019
  }
14219
15020
  //#endregion
15021
+ //#region src/ir/parents.ts
15022
+ /** The models and Asset: the parents whose fields a relation can name. */
15023
+ function fieldParents(environment) {
15024
+ return [...environment.models, ...environment.asset ? [environment.asset] : []];
15025
+ }
15026
+ //#endregion
14220
15027
  //#region src/live/resources/unsupported.zod.ts
14221
15028
  /** Not strict, as every live schema: the IR reads only the slot. */
14222
15029
  const createUnsupportedFieldSchema = object$1({
@@ -14258,7 +15065,7 @@ const createUnionFieldSchema = object$1({
14258
15065
  //#region src/live/resources/unsupported.ts
14259
15066
  /** A field op the CLI does not read, as the slot it holds. */
14260
15067
  function convertCreateUnsupportedFieldToIR(operation, input, type) {
14261
- const field = parse$1(operation, createUnsupportedFieldSchema, input);
15068
+ const field = parse$2(operation, createUnsupportedFieldSchema, input);
14262
15069
  return {
14263
15070
  parentApiId: field.parentApiId,
14264
15071
  field: unsupportedField(field.apiId, type, field.position)
@@ -14266,7 +15073,7 @@ function convertCreateUnsupportedFieldToIR(operation, input, type) {
14266
15073
  }
14267
15074
  /** A simple type the CLI does not read, by the op's own `type`. */
14268
15075
  function convertCreateUnsupportedSimpleFieldToIR(input) {
14269
- const field = parse$1("createSimpleField", createUnsupportedSimpleFieldSchema, input);
15076
+ const field = parse$2("createSimpleField", createUnsupportedSimpleFieldSchema, input);
14270
15077
  return {
14271
15078
  parentApiId: field.parentApiId,
14272
15079
  field: unsupportedField(field.apiId, field.type, field.position)
@@ -14274,7 +15081,7 @@ function convertCreateUnsupportedSimpleFieldToIR(input) {
14274
15081
  }
14275
15082
  /** The relation's field, and its other side when that has a slot. */
14276
15083
  function convertCreateRelationalFieldToIR(input) {
14277
- const field = parse$1("createRelationalField", createRelationalFieldSchema, input);
15084
+ const field = parse$2("createRelationalField", createRelationalFieldSchema, input);
14278
15085
  const { reverseField } = field;
14279
15086
  return [{
14280
15087
  parentApiId: field.parentApiId,
@@ -14286,12 +15093,13 @@ function convertCreateRelationalFieldToIR(input) {
14286
15093
  }
14287
15094
  /**
14288
15095
  * The two-way relations `environment` holds as unsupported fields on both
14289
- * sides, such as one required on its first side. Deleting either side
14290
- * deletes the other, so the diff sends one delete for the two.
15096
+ * sides, such as one required on its first side, or one made on Asset.
15097
+ * Deleting either side deletes the other, so the diff sends one delete for
15098
+ * the two.
14291
15099
  */
14292
15100
  function findUnsupportedPairs(ops, environment) {
14293
- const models = new Map(environment.models.map((model) => [model.apiId, model]));
14294
- const unsupported = (parent, apiId) => models.get(parent)?.fields[apiId]?.kind === "unsupported";
15101
+ const parents = new Map(fieldParents(environment).map((parent) => [parent.apiId, parent]));
15102
+ const unsupported = (parent, apiId) => parents.get(parent)?.fields[apiId]?.kind === "unsupported";
14295
15103
  return ops.flatMap((op) => {
14296
15104
  const parsed = createRelationalFieldSchema.safeParse(op.createRelationalField);
14297
15105
  if (!parsed.success || parsed.data.reverseField.isUnidirectional) return [];
@@ -14336,7 +15144,7 @@ function findUnsupportedUnions(ops, environment, unions = NO_UNION_LOOKUP) {
14336
15144
  * ones, which the server does not number, so they have no slot.
14337
15145
  */
14338
15146
  function convertCreateUnionFieldToIR(input, components, unions = NO_UNION_LOOKUP) {
14339
- const field = parse$1("createUnionField", createUnionFieldSchema, input);
15147
+ const field = parse$2("createUnionField", createUnionFieldSchema, input);
14340
15148
  const owner = {
14341
15149
  parentApiId: field.parentApiId,
14342
15150
  field: unsupportedField(field.apiId, "UNION", field.position)
@@ -14368,7 +15176,7 @@ function unsupportedField(apiId, type, position) {
14368
15176
  position
14369
15177
  };
14370
15178
  }
14371
- function parse$1(operation, schema, input) {
15179
+ function parse$2(operation, schema, input) {
14372
15180
  const parsed = schema.safeParse(input);
14373
15181
  if (!parsed.success) throw new Error(`Invalid ${operation} params: \n${renderIssues(parsed.error.issues)}`);
14374
15182
  return parsed.data;
@@ -14381,28 +15189,51 @@ function parse$1(operation, schema, input) {
14381
15189
  * the default locale and Draft and Published, so `readLiveEnvironment`
14382
15190
  * reads them on their own. Only what the IR holds is read:
14383
15191
  * `createEnumeration` ops become enumerations, `createTaxonomy` ops
14384
- * taxonomies, `createComponent` ops components, `createModel` ops models,
14385
- * and the field ops handled below their fields. A field op the CLI cannot
14386
- * read yet becomes an unsupported field, which holds its slot. Every other
14387
- * op, `createLocale` and `createStage` included, and fields on anything
14388
- * but a model or a component, are skipped until the IR has a place for
14389
- * them. A two-way relation's other side takes its rules and condition from
14390
- * `partners`, which `schemaDefinition` leaves out, and a union's members
15192
+ * taxonomies, `createGraphQLRemoteSource` and `createRESTRemoteSource` ops
15193
+ * remote sources, `createComponent` ops components, `createModel` ops
15194
+ * models, and the field ops handled below their fields. A field op the CLI
15195
+ * cannot read yet becomes an unsupported field, which holds its slot.
15196
+ * Fields on Asset have no `createModel` to hang on: they go on `asset`,
15197
+ * which is there with no fields too, as every environment has Asset, and
15198
+ * an export always lists it. An asset field's field back is a two-way
15199
+ * reference there; the other side of any other relation on Asset is an
15200
+ * unsupported field. Fields on QueryModel, remote fields only, go on
15201
+ * `query` the same way, which is there and exported with no fields too.
15202
+ * Every other op, `createLocale` and `createStage`
15203
+ * included, and fields on anything but a model, a component, Asset or
15204
+ * QueryModel, are skipped until the IR has a place for them. A two-way
15205
+ * relation's other side takes its rules and condition from `partners`,
15206
+ * which `schemaDefinition` leaves out, and a union's members
14391
15207
  * their apiIds and settings from `unions`: `schemaDefinition` gives the
14392
15208
  * first one's.
14393
15209
  */
14394
15210
  function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(), unions = NO_UNION_LOOKUP) {
14395
15211
  const enumerations = [];
14396
15212
  const taxonomies = [];
15213
+ const remoteSources = [];
14397
15214
  const components = [];
14398
15215
  const models = [];
14399
15216
  for (const op of ops) {
14400
15217
  if ("createEnumeration" in op) enumerations.push(convertCreateEnumerationToIR(op.createEnumeration));
14401
15218
  if ("createTaxonomy" in op) taxonomies.push(convertCreateTaxonomyToIR(op.createTaxonomy));
15219
+ if ("createGraphQLRemoteSource" in op) remoteSources.push(convertCreateGraphQLRemoteSourceToIR(op.createGraphQLRemoteSource));
15220
+ if ("createRESTRemoteSource" in op) remoteSources.push(convertCreateRESTRemoteSourceToIR(op.createRESTRemoteSource));
14402
15221
  if ("createComponent" in op) components.push(convertCreateComponentToIR(op.createComponent));
14403
15222
  if ("createModel" in op) models.push(convertCreateModelToIR(op.createModel));
14404
15223
  }
14405
- const parents = new Map([...models, ...components].map((parent) => [parent.apiId, parent]));
15224
+ const asset = {
15225
+ apiId: "Asset",
15226
+ fields: {}
15227
+ };
15228
+ const query = {
15229
+ apiId: "QueryModel",
15230
+ fields: {}
15231
+ };
15232
+ const parents = new Map([
15233
+ ...[...models, ...components].map((parent) => [parent.apiId, parent]),
15234
+ [asset.apiId, asset],
15235
+ [query.apiId, query]
15236
+ ]);
14406
15237
  const modelApiIds = new Set(models.map((model) => model.apiId));
14407
15238
  const componentApiIds = new Set(components.map((component) => component.apiId));
14408
15239
  for (const op of ops) {
@@ -14426,33 +15257,45 @@ function convertSchemaDefinitionToIR(ops, partners = /* @__PURE__ */ new Map(),
14426
15257
  pair.forEach((side) => addField(parents, side));
14427
15258
  break;
14428
15259
  }
14429
- const read = convertCreateReferenceOneWayFieldToIR(op.createRelationalField, modelApiIds) ?? convertCreateAssetFieldToIR(op.createRelationalField);
14430
- if (read) {
14431
- addField(parents, read);
15260
+ const reference = convertCreateReferenceOneWayFieldToIR(op.createRelationalField, modelApiIds);
15261
+ if (reference) {
15262
+ addField(parents, reference);
15263
+ break;
15264
+ }
15265
+ const asset = convertCreateAssetFieldToIR(op.createRelationalField, componentApiIds);
15266
+ if (asset) {
15267
+ asset.forEach((live) => addField(parents, live));
14432
15268
  break;
14433
15269
  }
14434
15270
  for (const live of convertCreateRelationalFieldToIR(op.createRelationalField)) addField(parents, live);
14435
15271
  break;
14436
15272
  }
14437
- case "createUnionField":
14438
- for (const live of convertCreateReferenceUnionFieldToIR(op.createUnionField, modelApiIds, componentApiIds, unions) ?? convertCreateUnionFieldToIR(op.createUnionField, componentApiIds, unions)) addField(parents, live);
15273
+ case "createUnionField": {
15274
+ const [own, ...otherSides] = convertCreateReferenceUnionFieldToIR(op.createUnionField, modelApiIds, componentApiIds, unions) ?? convertCreateUnionFieldToIR(op.createUnionField, componentApiIds, unions);
15275
+ addField(parents, own);
15276
+ otherSides.forEach((live) => addField(parents, live));
14439
15277
  break;
15278
+ }
14440
15279
  case "createTaxonomyField":
14441
15280
  addField(parents, convertCreateTaxonomyFieldToIR(op.createTaxonomyField));
14442
15281
  break;
14443
- case "createRemoteField": addField(parents, convertCreateUnsupportedFieldToIR(operationName, op[operationName], UNSUPPORTED_TYPES[operationName]));
15282
+ case "createRemoteField": addField(parents, convertCreateRemoteFieldToIR(op.createRemoteField));
14444
15283
  }
14445
15284
  }
14446
15285
  return {
14447
15286
  enumerations: enumerations.toSorted(byApiId$1),
14448
15287
  taxonomies: taxonomies.toSorted(byApiId$1),
15288
+ remoteSources: remoteSources.toSorted(byPrefix),
14449
15289
  components: components.toSorted(byApiId$1),
14450
- models: models.toSorted(byApiId$1)
15290
+ models: models.toSorted(byApiId$1),
15291
+ asset,
15292
+ query
14451
15293
  };
14452
15294
  }
14453
- /** The type an unsupported field of each of these batch operations has. */
14454
- const UNSUPPORTED_TYPES = { createRemoteField: "REMOTE" };
14455
- /** Puts the field on its model or component. A field on anything else is skipped. */
15295
+ /**
15296
+ * Puts the field on its model, component, Asset or QueryModel. A field on
15297
+ * anything else is skipped.
15298
+ */
14456
15299
  function addField(parents, live) {
14457
15300
  const parent = parents.get(live.parentApiId);
14458
15301
  if (parent) parent.fields[live.field.apiId] = live.field;
@@ -14872,6 +15715,7 @@ function toBatchChange(change) {
14872
15715
  case "enumerationValue": return toBatchEnumerationValueChange(change);
14873
15716
  case "taxonomy": return toBatchTaxonomyChange(change);
14874
15717
  case "taxonomyNode": return toBatchTaxonomyNodeChange(change);
15718
+ case "remoteSource": return toBatchRemoteSourceChange(change);
14875
15719
  case "component": return toBatchComponentChange(change);
14876
15720
  case "model": return toBatchModelChange(change);
14877
15721
  case "field": return toBatchFieldChange(change);
@@ -14891,6 +15735,12 @@ const messages = {
14891
15735
  ["model.invalidRenamedFrom"]: (renamedFrom) => `"${renamedFrom}" is not a valid model apiId to rename from.`,
14892
15736
  ["model.renamedFromMatchesApiId"]: (apiId) => `Model "${apiId}" is renamed from its own apiId.`,
14893
15737
  ["model.noTitleField"]: (apiId) => `Model "${apiId}" has no title field.`,
15738
+ ["model.apiIdReserved"]: (apiId) => `"${apiId}" is the apiId of a model Hygraph provides.`,
15739
+ ["systemModel.duplicate"]: (call) => `${call} is listed more than once in models.`,
15740
+ ["systemModel.fieldRequired"]: (apiId, field) => `Field "${field}" on ${apiId} is required. Hygraph refuses a required field on a model it provides.`,
15741
+ ["systemModel.fieldUnion"]: (apiId, field) => `Field "${field}" on ${apiId} is a component union. Hygraph refuses one on a model it provides.`,
15742
+ ["systemModel.fieldReferenceTwoWay"]: (apiId, field) => `Field "${field}" on ${apiId} is a two-way reference. A two-way reference on ${apiId} is the field back of an asset field, which assetReverseField declares.`,
15743
+ ["systemModel.fieldNotRemote"]: (field) => `Field "${field}" on Query is not a remote field. Hygraph takes only remote fields on Query.`,
14894
15744
  ["model.duplicateApiId"]: (apiId) => `More than one model is declared with the apiId "${apiId}".`,
14895
15745
  ["model.duplicateDisplayName"]: (displayName) => `More than one model is called "${displayName}".`,
14896
15746
  ["component.invalidApiId"]: (apiId) => `"${apiId}" is not a valid component apiId.`,
@@ -14939,6 +15789,17 @@ const messages = {
14939
15789
  ["taxonomyNode.invalidRenamedFrom"]: (renamedFrom) => `"${renamedFrom}" is not a valid taxonomy node apiId to rename from.`,
14940
15790
  ["taxonomyNode.renamedFromMatchesApiId"]: (taxonomy, apiId) => `Node "${apiId}" of taxonomy "${taxonomy}" is renamed from its own apiId.`,
14941
15791
  ["taxonomyNode.duplicateRenamedFrom"]: (taxonomy, renamedFrom) => `Taxonomy "${taxonomy}" renames more than one node from "${renamedFrom}".`,
15792
+ ["remoteSource.invalidPrefix"]: (prefix) => `"${prefix}" is not a valid remote source prefix.`,
15793
+ ["remoteSource.duplicatePrefix"]: (prefix) => `More than one remote source is declared with the prefix "${prefix}".`,
15794
+ ["remoteSource.invalidUrl"]: (prefix, attribute, url) => `Remote source "${prefix}" has "${url}" as its ${attribute}, which is not an https URL.`,
15795
+ ["remoteSource.headerMissing"]: (prefix, header) => `Remote source "${prefix}" has no value for the header ${header}.`,
15796
+ ["remoteSource.oAuthOnCustom"]: (prefix) => `Remote source "${prefix}" is Custom and signs in with OAuth. Hygraph signs in with OAuth to CommerceTools and CommerceLayer sources only.`,
15797
+ ["remoteSource.oAuthClientIdMissing"]: (prefix) => `Remote source "${prefix}" signs in with OAuth without a client id.`,
15798
+ ["remoteSource.oAuthScopeInvalid"]: (prefix, scope, reason) => `Remote source "${prefix}" has the OAuth scope "${scope}", which ${reason}.`,
15799
+ ["remoteSource.oAuthSecretMissing"]: (prefix) => `This plan sends the OAuth secret of remote source "${prefix}", and the config's oAuth.clientSecret is empty. apply refuses the plan.`,
15800
+ ["remoteSource.invalidTypeDefinitions"]: (prefix, reason) => `Remote source "${prefix}" has remoteTypeDefinitions that are not type definitions: ${reason}`,
15801
+ ["remoteSource.duplicateTypeDefinition"]: (prefix, type) => `Remote source "${prefix}" declares the type "${type}" more than once in remoteTypeDefinitions.`,
15802
+ ["remoteSource.typeDefinitionNotInput"]: (prefix, type) => `GraphQL remote source "${prefix}" declares "${type}" in remoteTypeDefinitions, which is not an input type.`,
14942
15803
  ["field.invalidApiId"]: (apiId) => `"${apiId}" is not a valid field apiId.`,
14943
15804
  ["field.duplicateApiId"]: (kind, parent, apiId) => `${upperFirst(kind)} "${parent}" declares more than one field with the apiId "${apiId}".`,
14944
15805
  ["field.duplicateDisplayName"]: (kind, parent, displayName) => `${upperFirst(kind)} "${parent}" has more than one field called "${displayName}".`,
@@ -14978,6 +15839,19 @@ const messages = {
14978
15839
  ["field.requiredOnList"]: (field) => `Field "${field}" is a list and cannot be required.`,
14979
15840
  ["field.enumerationMissing"]: (field, enumeration) => `Field "${field}" uses enumeration "${enumeration}", which is not in the environment.`,
14980
15841
  ["field.enumerationValueInvalid"]: (field, attribute, value) => `Field "${field}" has ${JSON.stringify(value)} in its ${attribute}, which is not a value of its enumeration.`,
15842
+ ["field.remoteSourceMissing"]: (field, prefix) => `Field "${field}" uses remote source "${prefix}", which is not in the environment.`,
15843
+ ["field.remoteRenameUnsupported"]: (field) => `Field "${field}" is a remote field with renamedFrom, which Hygraph cannot rename.`,
15844
+ ["field.remoteOnComponent"]: (field) => `Field "${field}" is a remote field on a component, which Hygraph does not take.`,
15845
+ ["field.remoteQueryMissing"]: (field, prefix) => `Field "${field}" is on GraphQL remote source "${prefix}" but has no query.`,
15846
+ ["field.remoteQueryOnRest"]: (field, prefix) => `Field "${field}" has a query, but remote source "${prefix}" is a REST source.`,
15847
+ ["field.remotePathOnGraphQL"]: (field, prefix) => `Field "${field}" has a path, but remote source "${prefix}" is a GraphQL source.`,
15848
+ ["field.remoteCacheTTLInvalid"]: (field, ttl) => `Field "${field}" caches for ${ttl} seconds, which Hygraph does not take.`,
15849
+ ["field.remoteHeaderMissing"]: (field, header) => `Field "${field}" has no value for the header ${header}.`,
15850
+ ["field.remoteArgDuplicate"]: (field, arg) => `Field "${field}" declares the argument "${arg}" more than once.`,
15851
+ ["field.remotePlaceholderField"]: (field, placeholder) => `Field "${field}" uses {{${placeholder}}}, but its model has no field by that apiId.`,
15852
+ ["field.remotePlaceholderDocOnQuery"]: (field, placeholder) => `Field "${field}" on Query uses {{${placeholder}}}, but Query has no entry to read it from.`,
15853
+ ["field.remotePlaceholderArg"]: (field, placeholder) => `Field "${field}" uses {{${placeholder}}}, but it declares no argument by that apiId.`,
15854
+ ["field.remoteTypeUnknown"]: (field, type, prefix) => `Field "${field}" uses the type "${type}", which REST remote source "${prefix}" does not declare.`,
14981
15855
  ["field.taxonomyMissing"]: (field, taxonomy) => `Field "${field}" uses taxonomy "${taxonomy}", which is not in the environment.`,
14982
15856
  ["field.taxonomyNodeInvalid"]: (field, attribute, value) => `Field "${field}" has ${JSON.stringify(value)} in its ${attribute}, which is not a node of its taxonomy.`,
14983
15857
  ["field.componentMissing"]: (field, component) => `Field "${field}" uses component "${component}", which is not in the environment.`,
@@ -15007,10 +15881,21 @@ const messages = {
15007
15881
  ["field.richTextEmbedComponent"]: (field, component) => `Field "${field}" embeds component "${component}". Rich text embeds entries of a model.`,
15008
15882
  ["field.richTextUniqueEmbeds"]: (field) => `Field "${field}" is unique and has embeds, which Hygraph refuses on a model.`,
15009
15883
  ["field.richTextRequiredList"]: (field) => `Field "${field}" is a required list, which Hygraph refuses on rich text.`,
15884
+ ["field.assetReverseFieldMissing"]: (parent, field) => `Asset field "${field}" on ${parent} does not name its field back on Asset.`,
15885
+ ["field.assetReverseFieldOnComponent"]: (parent, field) => `Asset field "${field}" on component ${parent} names a field back. A component's field back is hidden, and the CLI names it.`,
15886
+ ["field.assetSystemAssetMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} has its field back "${back}" on Asset, and models does not list system.asset.`,
15887
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Asset field "${field}" on ${parent} names its field back "${back}", which system.asset does not list.`,
15888
+ ["field.assetFieldBackPartner"]: (back, partner, problem) => `Field back "${back}" on Asset names ${partner}, which ${problem}.`,
15889
+ ["field.assetReverseFieldNotOnAsset"]: (parent, field) => `Field "${field}" on ${parent} is an assetReverseField. A field back is on Asset only.`,
15890
+ ["field.assetReverseFieldChanged"]: (parent, field, from, to) => `Asset field "${field}" on ${parent} has the field back "${from}" on Asset, and the config names "${to}".`,
15010
15891
  ["change.modelMissing"]: (action, apiId) => `Cannot ${action} model "${apiId}": it does not exist at that point of the migration.`,
15011
15892
  ["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.`,
15012
15893
  ["change.componentMissing"]: (action, apiId) => `Cannot ${action} component "${apiId}": it does not exist at that point of the migration.`,
15013
15894
  ["change.enumerationMissing"]: (action, apiId) => `Cannot ${action} enumeration "${apiId}": it does not exist at that point of the migration.`,
15895
+ ["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.`,
15896
+ ["change.remoteSourceRotateSecret"]: (prefix, reason) => `--rotate-secret names remote source "${prefix}", which ${reason}.`,
15897
+ ["change.remoteSourceOAuthRemoved"]: (prefix) => `Remote source "${prefix}" signs in with OAuth in Hygraph, and the config leaves oAuth out. Hygraph keeps OAuth on a source until it is deleted.`,
15898
+ ["change.remoteSourceIntrospectionUrl"]: (prefix) => `Remote source "${prefix}" changes its introspection URL, which Hygraph cannot change on a source that exists.`,
15014
15899
  ["change.taxonomyMissing"]: (action, apiId) => `Cannot ${action} taxonomy "${apiId}": it does not exist at that point of the migration.`,
15015
15900
  ["change.taxonomyRootReplaced"]: (taxonomy, liveRoot, root) => `The root of taxonomy "${taxonomy}" is "${liveRoot}" in Hygraph and cannot be replaced by "${root}".`,
15016
15901
  ["change.renameSourceMissing"]: (renamedFrom, apiId) => `Cannot rename model "${renamedFrom}" to "${apiId}": neither apiId exists in the environment.`,
@@ -15052,6 +15937,12 @@ const fixes = {
15052
15937
  ["model.invalidRenamedFrom"]: "Use the apiId the model has in Hygraph right now: an uppercase letter, then letters, digits and underscores only, up to 64 characters.",
15053
15938
  ["model.renamedFromMatchesApiId"]: "Set renamedFrom to the apiId the model has in Hygraph right now, or remove it.",
15054
15939
  ["model.noTitleField"]: "Set title: true on the field Studio should show entries by, such as a name or a heading.",
15940
+ ["model.apiIdReserved"]: "Use another apiId. To add fields to Asset or Query, put system.asset({ fields }) or system.query({ fields }) in models.",
15941
+ ["systemModel.duplicate"]: "List it once, with all your fields on it.",
15942
+ ["systemModel.fieldRequired"]: "Set required: false.",
15943
+ ["systemModel.fieldUnion"]: "Use a component field, or put the union on a model of yours.",
15944
+ ["systemModel.fieldReferenceTwoWay"]: "Use define.field.assetReverseField with the same apiId, displayName, to and reverse, and no list or rules.",
15945
+ ["systemModel.fieldNotRemote"]: "Use define.field.remote, or put the field on a model of yours.",
15055
15946
  ["model.duplicateApiId"]: "Rename one of them. A model apiId is unique per environment.",
15056
15947
  ["model.duplicateDisplayName"]: "Rename one of them. A displayName is unique per environment.",
15057
15948
  ["component.invalidApiId"]: "Start with an uppercase letter, then use letters, digits and underscores only, up to 64 characters.",
@@ -15076,6 +15967,17 @@ const fixes = {
15076
15967
  ["taxonomyNode.invalidRenamedFrom"]: "Use the apiId the node has in Hygraph right now: an uppercase letter, then letters, digits and underscores only, up to 64 characters.",
15077
15968
  ["taxonomyNode.renamedFromMatchesApiId"]: "Set renamedFrom to the apiId the node has in Hygraph right now, or remove it.",
15078
15969
  ["taxonomyNode.duplicateRenamedFrom"]: "Keep renamedFrom on the node that continues it. The other nodes are created new.",
15970
+ ["remoteSource.invalidPrefix"]: "Start with an uppercase letter, then use letters, digits and underscores only, up to 64 characters, and do not end with an underscore.",
15971
+ ["remoteSource.duplicatePrefix"]: "Rename one of them. A prefix is unique per environment.",
15972
+ ["remoteSource.invalidUrl"]: "Use an absolute https URL, such as https://api.example.com/graphql.",
15973
+ ["remoteSource.headerMissing"]: "Set the environment variable the config reads it from, or write the value in the config.",
15974
+ ["remoteSource.oAuthOnCustom"]: "Set kind to \"CommerceTools\" or \"CommerceLayer\", or remove oAuth and sign in with headers.",
15975
+ ["remoteSource.oAuthClientIdMissing"]: "Set oAuth.clientId to the API client's id.",
15976
+ ["remoteSource.oAuthScopeInvalid"]: "Write one scope per entry, each once and without spaces, such as [\"manage_project:shop\", \"view_orders:shop\"].",
15977
+ ["remoteSource.oAuthSecretMissing"]: "Set the environment variable the config reads oAuth.clientSecret from, then plan again.",
15978
+ ["remoteSource.invalidTypeDefinitions"]: "Write GraphQL SDL with type, input, enum, interface, scalar and union definitions only, without the prefix.",
15979
+ ["remoteSource.duplicateTypeDefinition"]: "Keep one definition of the type.",
15980
+ ["remoteSource.typeDefinitionNotInput"]: "Declare only input types, for remote field arguments. The remote API's own types come from introspection.",
15079
15981
  ["enumeration.invalidRenamedFrom"]: "Use the apiId the enumeration has in Hygraph right now: an uppercase letter, then letters, digits and underscores only, up to 64 characters.",
15080
15982
  ["enumeration.renamedFromMatchesApiId"]: "Set renamedFrom to the apiId the enumeration has in Hygraph right now, or remove it.",
15081
15983
  ["enumerationValue.invalidRenamedFrom"]: "Use the apiId the value has in Hygraph right now: a letter, then letters, digits and underscores only, up to 191 characters.",
@@ -15139,6 +16041,19 @@ const fixes = {
15139
16041
  ["field.requiredOnList"]: "Remove required, or make the field hold one value.",
15140
16042
  ["field.enumerationMissing"]: "Add the enumeration to enumerations in define.environment.",
15141
16043
  ["field.enumerationValueInvalid"]: "Use a value apiId of the field's enumeration, or add the value to it.",
16044
+ ["field.remoteSourceMissing"]: "Add the source to remoteSources in define.environment.",
16045
+ ["field.remoteRenameUnsupported"]: "Remove renamedFrom and keep the new apiId: the plan deletes the field and creates it again, which loses nothing.",
16046
+ ["field.remoteOnComponent"]: "Move the remote field to a model.",
16047
+ ["field.remoteQueryMissing"]: "Write the query sent to the source: a named operation that spreads ...EntryPoint where returnType is.",
16048
+ ["field.remoteQueryOnRest"]: "Give a REST source's field a path, or use a GraphQL source.",
16049
+ ["field.remotePathOnGraphQL"]: "Give a GraphQL source's field a query, or use a REST source.",
16050
+ ["field.remoteCacheTTLInvalid"]: "Use 0 for no cache, or a whole number of seconds from 60 up.",
16051
+ ["field.remoteHeaderMissing"]: "Set the environment variable the config reads it from, or write the value in the config.",
16052
+ ["field.remoteArgDuplicate"]: "Keep one argument by that apiId.",
16053
+ ["field.remotePlaceholderField"]: "Name a field of the same model after doc., or add the field.",
16054
+ ["field.remotePlaceholderDocOnQuery"]: "Take the value as an argument and use {{args.<apiId>}}.",
16055
+ ["field.remotePlaceholderArg"]: "Name one of the field's args after args., or add the argument.",
16056
+ ["field.remoteTypeUnknown"]: "Use a scalar, or declare the type in the source's remoteTypeDefinitions.",
15142
16057
  ["field.taxonomyMissing"]: "Add the taxonomy to taxonomies in define.environment.",
15143
16058
  ["field.taxonomyNodeInvalid"]: "Use a node apiId of the field's taxonomy, or add the node to it.",
15144
16059
  ["field.componentMissing"]: "Add the component to components in define.environment.",
@@ -15168,10 +16083,21 @@ const fixes = {
15168
16083
  ["field.richTextEmbedComponent"]: "List only models in embeds. To hold a component, use define.field.component.",
15169
16084
  ["field.richTextUniqueEmbeds"]: "Remove unique, or remove embeds.",
15170
16085
  ["field.richTextRequiredList"]: "Remove required, or set list: false.",
16086
+ ["field.assetReverseFieldMissing"]: (parent, field, back) => `Set reverse: "${back}" on the field, and add its field back to system.asset's fields: ${fieldBack(parent, field, back)}.`,
16087
+ ["field.assetReverseFieldOnComponent"]: "Remove reverse.",
16088
+ ["field.assetSystemAssetMissing"]: (parent, field, back) => `Add const Asset = system.asset({ fields: [${fieldBack(parent, field, back)}] }) to models.`,
16089
+ ["field.assetFieldBackMissing"]: (parent, field, back) => `Add ${fieldBack(parent, field, back)} to system.asset's fields, at the end for a new field.`,
16090
+ ["field.assetFieldBackPartner"]: "Point it at the asset field that names it in reverse: to is that field's model, and reverse is its apiId.",
16091
+ ["field.assetReverseFieldNotOnAsset"]: "Move it to system.asset's fields, or use define.field.referenceTwoWay on a model.",
16092
+ ["field.assetReverseFieldChanged"]: (_parent, _field, from) => `To rename the field back, set renamedFrom: "${from}" on it in system.asset. Otherwise set reverse back to "${from}".`,
15171
16093
  ["change.modelMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a model from one place only.",
15172
16094
  ["change.embedsReplaced"]: "Create the new models in one apply. Then change embeds and delete the old models in the next.",
15173
16095
  ["change.componentMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a component from one place only.",
15174
16096
  ["change.enumerationMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename an enumeration from one place only.",
16097
+ ["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.",
16098
+ ["change.remoteSourceRotateSecret"]: "Name a source of the config that signs in with OAuth, with the new secret in the variable its oAuth.clientSecret reads.",
16099
+ ["change.remoteSourceOAuthRemoved"]: "Keep oAuth on the source. To drop it, remove the source and its remote fields from the config and apply, then add them back without it and apply again.",
16100
+ ["change.remoteSourceIntrospectionUrl"]: "Keep the introspection URL 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 URL and apply again.",
15175
16101
  ["change.taxonomyMissing"]: "An earlier change deletes or renames it. Plan against the current environment, and rename a taxonomy from one place only.",
15176
16102
  ["change.taxonomyRootReplaced"]: (_taxonomy, liveRoot) => `Rename the root instead: give it renamedFrom: "${liveRoot}", or keep "${liveRoot}" as its apiId.`,
15177
16103
  ["change.renameSourceMissing"]: "Set renamedFrom to the apiId the model has in Hygraph right now, or remove it to create the model.",
@@ -15205,6 +16131,136 @@ const fixes = {
15205
16131
  function upperFirst(text) {
15206
16132
  return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
15207
16133
  }
16134
+ /** The field back of an asset field, as the config declares it on Asset. */
16135
+ function fieldBack(parent, field, back) {
16136
+ return `define.field.assetReverseField({ apiId: "${back}", displayName: "${back}", to: () => ${parent}, reverse: "${field}" })`;
16137
+ }
16138
+ //#endregion
16139
+ //#region src/plan/secrets.ts
16140
+ function oAuthSecrets(environment) {
16141
+ return new Map(environment.remoteSources.flatMap((source) => source.oAuth === null ? [] : [[source.prefix, {
16142
+ kind: source.kind,
16143
+ secret: source.oAuth.clientSecret
16144
+ }]]));
16145
+ }
16146
+ /**
16147
+ * The changes with the config's OAuth secret on each that needs one: a
16148
+ * create with OAuth, an update that adds OAuth, and one that changes
16149
+ * `clientId`, as the stored secret belongs to the old client. Hygraph
16150
+ * keeps the secret it has on any other change. A CommerceTools source
16151
+ * without its secret gets `clientSecret: null`, which apply refuses, and a
16152
+ * warning now; a CommerceLayer one may sign in without a secret.
16153
+ */
16154
+ function attachOAuthSecrets(changes, secrets) {
16155
+ const warnings = [];
16156
+ return {
16157
+ changes: changes.map((change) => {
16158
+ if (change.resource !== "remoteSource" || change.action === "delete" || !needsSecret(change)) return change;
16159
+ const prefix = remoteSourcePrefixOf(change);
16160
+ const source = secrets.get(prefix);
16161
+ if (source === void 0) return change;
16162
+ if (source.secret !== null) return {
16163
+ ...change,
16164
+ clientSecret: source.secret
16165
+ };
16166
+ if (source.kind !== "CommerceTools") return change;
16167
+ const code = "remoteSource.oAuthSecretMissing";
16168
+ warnings.push({
16169
+ code,
16170
+ severity: "warning",
16171
+ path: [
16172
+ "remoteSources",
16173
+ prefix,
16174
+ "oAuth",
16175
+ "clientSecret"
16176
+ ],
16177
+ message: messages[code](prefix),
16178
+ fix: fixes[code]
16179
+ });
16180
+ return {
16181
+ ...change,
16182
+ clientSecret: null
16183
+ };
16184
+ }),
16185
+ warnings
16186
+ };
16187
+ }
16188
+ function needsSecret(change) {
16189
+ if (change.action === "create") return change.remoteSource.oAuth !== null;
16190
+ const oAuth = change.changes.oAuth;
16191
+ return oAuth !== void 0 && oAuth.to !== null && (oAuth.from === null || oAuth.from.clientId !== oAuth.to.clientId);
16192
+ }
16193
+ /**
16194
+ * The changes with each source `rotate` names sending its secret, which
16195
+ * Hygraph cannot tell changed: live never returns one. A source the plan
16196
+ * does not change otherwise gets an update with no changes. Refuses a
16197
+ * prefix the config does not have, a source without OAuth, and one whose
16198
+ * secret is empty: there is nothing to send.
16199
+ */
16200
+ function rotateOAuthSecrets(changes, desired, secrets, rotate) {
16201
+ const refusals = [];
16202
+ let rotated = changes;
16203
+ for (const prefix of new Set(rotate)) {
16204
+ const source = desired.remoteSources.find((each) => each.prefix === prefix);
16205
+ const secret = secrets.get(prefix)?.secret ?? null;
16206
+ const refuse = (reason) => {
16207
+ const code = "change.remoteSourceRotateSecret";
16208
+ refusals.push({
16209
+ code,
16210
+ severity: "error",
16211
+ path: [
16212
+ "remoteSources",
16213
+ prefix,
16214
+ "oAuth",
16215
+ "clientSecret"
16216
+ ],
16217
+ message: messages[code](prefix, reason),
16218
+ fix: fixes[code]
16219
+ });
16220
+ };
16221
+ if (source === void 0) {
16222
+ refuse("the config does not have");
16223
+ continue;
16224
+ }
16225
+ if (source.oAuth === null) {
16226
+ refuse("does not sign in with OAuth");
16227
+ continue;
16228
+ }
16229
+ if (secret === null) {
16230
+ refuse("has no secret to send: its oAuth.clientSecret is empty");
16231
+ continue;
16232
+ }
16233
+ const index = rotated.findIndex((change) => change.resource === "remoteSource" && change.action !== "delete" && remoteSourcePrefixOf(change) === prefix);
16234
+ const existing = rotated[index];
16235
+ if (existing?.resource === "remoteSource" && existing.action !== "delete") {
16236
+ rotated = rotated.with(index, {
16237
+ ...existing,
16238
+ clientSecret: secret
16239
+ });
16240
+ continue;
16241
+ }
16242
+ rotated = [...rotated, {
16243
+ action: "update",
16244
+ resource: "remoteSource",
16245
+ prefix,
16246
+ type: source.type,
16247
+ displayName: source.displayName,
16248
+ headers: source.headers,
16249
+ introspectionHeaders: source.type === "GRAPHQL" ? source.introspectionHeaders : null,
16250
+ oAuth: source.oAuth,
16251
+ changes: {},
16252
+ clientSecret: secret
16253
+ }];
16254
+ }
16255
+ return {
16256
+ changes: rotated,
16257
+ refusals
16258
+ };
16259
+ }
16260
+ /** The sources a plan sends a secret for, which apply plans again with `--rotate-secret`. */
16261
+ function sentOAuthSecrets(changes) {
16262
+ return changes.flatMap((change) => change.resource === "remoteSource" && change.action !== "delete" && typeof change.clientSecret === "string" ? [remoteSourcePrefixOf(change)] : []);
16263
+ }
15208
16264
  //#endregion
15209
16265
  //#region src/define/fields/validation.shared.ts
15210
16266
  /**
@@ -15306,6 +16362,47 @@ function validateListOptions(parent, field) {
15306
16362
  return validations;
15307
16363
  }
15308
16364
  //#endregion
16365
+ //#region src/define/fields/assetReverseField.validation.ts
16366
+ /**
16367
+ * A field back is on Asset, and its partner is an asset field on `to`
16368
+ * whose `reverse` names it back. Hygraph makes the field back with its
16369
+ * asset field, so one that names no asset field has nothing to make.
16370
+ * `parents` are the models and Asset: an asset field on Asset has its
16371
+ * field back there too. A `to` the environment does not have is
16372
+ * `field.referenceModelMissing`.
16373
+ */
16374
+ function validateAssetReverseFields(parent, fields, parents) {
16375
+ const validations = [];
16376
+ const report = (code, apiId, attribute, message) => {
16377
+ validations.push({
16378
+ code,
16379
+ severity: "error",
16380
+ path: fieldPath(parent, apiId, attribute),
16381
+ message,
16382
+ fix: fixes[code]
16383
+ });
16384
+ };
16385
+ for (const field of fields) {
16386
+ if (field.__typename !== "AssetReverseField") continue;
16387
+ if (parent.apiId !== "Asset") {
16388
+ const code = "field.assetReverseFieldNotOnAsset";
16389
+ report(code, field.apiId, "to", messages[code](parent.apiId, field.apiId));
16390
+ continue;
16391
+ }
16392
+ const to = field.to().apiId;
16393
+ const model = parents.get(to);
16394
+ if (model === void 0) continue;
16395
+ const partnerName = `${to}.${field.reverse}`;
16396
+ const partner = model.fields.find(({ apiId }) => apiId === field.reverse);
16397
+ const problem = partner === void 0 ? "does not exist" : partner.__typename !== "AssetField" ? "is not an asset field" : partner.reverse !== field.apiId ? `names Asset.${partner.reverse ?? "(none)"} as its field back` : null;
16398
+ if (problem !== null) {
16399
+ const code = "field.assetFieldBackPartner";
16400
+ report(code, field.apiId, "reverse", messages[code](field.apiId, partnerName, problem));
16401
+ }
16402
+ }
16403
+ return validations;
16404
+ }
16405
+ //#endregion
15309
16406
  //#region src/define/fields/component.validation.ts
15310
16407
  /**
15311
16408
  * Every component a component or union field uses must be in the
@@ -15426,15 +16523,17 @@ function validateReferenceField(parent, field) {
15426
16523
  /**
15427
16524
  * Every model a reference uses must be in the environment's `models`, or
15428
16525
  * the plan would reference a model it never creates. A component is
15429
- * refused on its own: only the types keep it out of `to`.
16526
+ * refused on its own: only the types keep it out of `to`. A field back
16527
+ * may name Asset, for an asset field on Asset: it is on Asset, so Asset
16528
+ * is listed.
15430
16529
  */
15431
16530
  function validateReferenceModelReferences(parent, fields, models) {
15432
16531
  return fields.flatMap((field) => {
15433
- if (field.__typename !== "ReferenceOneWayField" && field.__typename !== "ReferenceTwoWayField" && field.__typename !== "ReferenceUnionField" && field.__typename !== "ReferenceUnionMemberField") return [];
16532
+ if (field.__typename !== "ReferenceOneWayField" && field.__typename !== "ReferenceTwoWayField" && field.__typename !== "ReferenceUnionField" && field.__typename !== "ReferenceUnionMemberField" && field.__typename !== "AssetReverseField") return [];
15434
16533
  const targets = field.__typename === "ReferenceUnionField" ? field.to.map((model) => model()) : [field.to()];
15435
16534
  const path = fieldPath(parent, field.apiId, "to");
15436
16535
  return [...new Map(targets.map((target) => [target.apiId, target])).values()].flatMap(({ __typename, apiId }) => {
15437
- const code = __typename === "Component" ? "field.referenceToComponent" : models.has(apiId) ? null : "field.referenceModelMissing";
16536
+ const code = __typename === "Component" ? "field.referenceToComponent" : models.has(apiId) || field.__typename === "AssetReverseField" && __typename === "SystemAsset" ? null : "field.referenceModelMissing";
15438
16537
  return code === null ? [] : [{
15439
16538
  code,
15440
16539
  severity: "error",
@@ -15467,6 +16566,7 @@ function validateReferenceTwoWayPartners(parent, fields, models) {
15467
16566
  };
15468
16567
  for (const field of fields) {
15469
16568
  if (field.__typename !== "ReferenceTwoWayField") continue;
16569
+ if (parent.apiId === "Asset") continue;
15470
16570
  if (parent.kind === "component") {
15471
16571
  const code = "field.referenceTwoWayOnComponent";
15472
16572
  report(code, field.apiId, "to", messages[code](field.apiId));
@@ -15598,6 +16698,296 @@ function validateReferenceUnionMembers(parent, fields, models) {
15598
16698
  return validations;
15599
16699
  }
15600
16700
  //#endregion
16701
+ //#region src/define/resources/remoteSource.validation.ts
16702
+ var import_GraphQLError = require_GraphQLError();
16703
+ var import_kinds = require_kinds();
16704
+ var import_parser = require_parser();
16705
+ /**
16706
+ * Hygraph's rule for a prefix, which Studio also caps at 64 characters. The
16707
+ * server strips a trailing underscore, so a prefix ending in one would
16708
+ * never match what live reads back.
16709
+ */
16710
+ const PREFIX = /^[A-Z][A-Za-z0-9_]{0,63}$/;
16711
+ /**
16712
+ * What a remote source can tell about itself. Whether its prefix collides
16713
+ * with another source's belongs to the environment. Every check runs,
16714
+ * whatever the ones before it found. A CommerceTools source without its
16715
+ * OAuth secret is not refused here: the secret is sent only when a plan
16716
+ * needs it, and plan warns then.
16717
+ */
16718
+ function validateRemoteSource(source) {
16719
+ const validations = [];
16720
+ if (!PREFIX.test(source.prefix) || source.prefix.endsWith("_")) validations.push({
16721
+ code: "remoteSource.invalidPrefix",
16722
+ severity: "error",
16723
+ path: remoteSourcePath(source.prefix, "prefix"),
16724
+ message: messages["remoteSource.invalidPrefix"](source.prefix),
16725
+ fix: fixes["remoteSource.invalidPrefix"]
16726
+ });
16727
+ const urls = [
16728
+ ["url", source.url],
16729
+ ["introspectionUrl", source.__typename === "GraphQLRemoteSource" ? source.introspectionUrl : null],
16730
+ ["oAuth.authorizationUrl", source.oAuth?.authorizationUrl ?? null]
16731
+ ];
16732
+ for (const [attribute, url] of urls) if (url !== null && !isHttpsUrl(url)) validations.push({
16733
+ code: "remoteSource.invalidUrl",
16734
+ severity: "error",
16735
+ path: remoteSourcePath(source.prefix, ...attribute.split(".")),
16736
+ message: messages["remoteSource.invalidUrl"](source.prefix, attribute, url),
16737
+ fix: fixes["remoteSource.invalidUrl"]
16738
+ });
16739
+ const headers = [["headers", source.headers], ["introspectionHeaders", source.__typename === "GraphQLRemoteSource" ? source.introspectionHeaders : {}]];
16740
+ for (const [attribute, each] of headers) for (const [name, value] of Object.entries(each)) if (hasNoValue(value)) validations.push({
16741
+ code: "remoteSource.headerMissing",
16742
+ severity: "error",
16743
+ path: [...remoteSourcePath(source.prefix, attribute), name],
16744
+ message: messages["remoteSource.headerMissing"](source.prefix, name),
16745
+ fix: fixes["remoteSource.headerMissing"]
16746
+ });
16747
+ if (source.oAuth !== null && source.kind === "Custom") {
16748
+ const code = "remoteSource.oAuthOnCustom";
16749
+ validations.push({
16750
+ code,
16751
+ severity: "error",
16752
+ path: remoteSourcePath(source.prefix, "oAuth"),
16753
+ message: messages[code](source.prefix),
16754
+ fix: fixes[code]
16755
+ });
16756
+ }
16757
+ if (source.oAuth !== null && isEmpty(source.oAuth.clientId)) {
16758
+ const code = "remoteSource.oAuthClientIdMissing";
16759
+ validations.push({
16760
+ code,
16761
+ severity: "error",
16762
+ path: remoteSourcePath(source.prefix, "oAuth", "clientId"),
16763
+ message: messages[code](source.prefix),
16764
+ fix: fixes[code]
16765
+ });
16766
+ }
16767
+ if (source.oAuth !== null) validations.push(...validateScopes(source.prefix, source.oAuth.scopes));
16768
+ if (source.remoteTypeDefinitions !== null) validations.push(...validateTypeDefinitions(source, source.remoteTypeDefinitions));
16769
+ return validations;
16770
+ }
16771
+ /** `["remoteSources", "Shop", "url"]`, or deeper: `"oAuth", "clientId"`. */
16772
+ function remoteSourcePath(prefix, ...attributes) {
16773
+ return [
16774
+ "remoteSources",
16775
+ prefix,
16776
+ ...attributes
16777
+ ];
16778
+ }
16779
+ /**
16780
+ * The SDL parses, holds type definitions only, each once, and on a GraphQL
16781
+ * source only input types: Hygraph refuses any other there.
16782
+ */
16783
+ function validateTypeDefinitions(source, sdl) {
16784
+ const path = remoteSourcePath(source.prefix, "remoteTypeDefinitions");
16785
+ const invalid = (reason) => ({
16786
+ code: "remoteSource.invalidTypeDefinitions",
16787
+ severity: "error",
16788
+ path,
16789
+ message: messages["remoteSource.invalidTypeDefinitions"](source.prefix, reason),
16790
+ fix: fixes["remoteSource.invalidTypeDefinitions"]
16791
+ });
16792
+ let document;
16793
+ try {
16794
+ document = (0, import_parser.parse)(sdl);
16795
+ } catch (error) {
16796
+ return [invalid(error instanceof import_GraphQLError.GraphQLError ? error.message : `${error}`)];
16797
+ }
16798
+ const validations = [];
16799
+ const names = /* @__PURE__ */ new Set();
16800
+ for (const definition of document.definitions) {
16801
+ const name = typeDefinitionName(definition);
16802
+ if (name === null) {
16803
+ validations.push(invalid(`it holds a ${definition.kind} definition.`));
16804
+ continue;
16805
+ }
16806
+ if (names.has(name)) validations.push({
16807
+ code: "remoteSource.duplicateTypeDefinition",
16808
+ severity: "error",
16809
+ path,
16810
+ message: messages["remoteSource.duplicateTypeDefinition"](source.prefix, name),
16811
+ fix: fixes["remoteSource.duplicateTypeDefinition"]
16812
+ });
16813
+ names.add(name);
16814
+ if (source.__typename === "GraphQLRemoteSource" && definition.kind !== import_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION) validations.push({
16815
+ code: "remoteSource.typeDefinitionNotInput",
16816
+ severity: "error",
16817
+ path,
16818
+ message: messages["remoteSource.typeDefinitionNotInput"](source.prefix, name),
16819
+ fix: fixes["remoteSource.typeDefinitionNotInput"]
16820
+ });
16821
+ }
16822
+ return validations;
16823
+ }
16824
+ /**
16825
+ * Studio refuses an empty scope and one listed twice. Hygraph keeps the
16826
+ * scopes as one string joined with spaces and live splits it again, so a
16827
+ * scope with whitespace would read back as two and plan a change forever.
16828
+ */
16829
+ function validateScopes(prefix, scopes) {
16830
+ const code = "remoteSource.oAuthScopeInvalid";
16831
+ const seen = /* @__PURE__ */ new Set();
16832
+ return scopes.flatMap((scope) => {
16833
+ const reason = scope.trim() === "" ? "is empty" : /\s/.test(scope) ? "holds whitespace: Hygraph keeps the scopes as one string joined with spaces" : seen.has(scope) ? "is listed more than once" : null;
16834
+ seen.add(scope);
16835
+ return reason === null ? [] : [{
16836
+ code,
16837
+ severity: "error",
16838
+ path: remoteSourcePath(prefix, "oAuth", "scopes"),
16839
+ message: messages[code](prefix, scope, reason),
16840
+ fix: fixes[code]
16841
+ }];
16842
+ });
16843
+ }
16844
+ /**
16845
+ * A header Hygraph would get empty: a variable that is not set, or is set
16846
+ * to `""`, a list without values, or a list holding one of those.
16847
+ */
16848
+ function hasNoValue(value) {
16849
+ if (typeof value === "string" || value === void 0) return isEmpty(value);
16850
+ return value.length === 0 || value.some((each) => isEmpty(each));
16851
+ }
16852
+ /** Studio takes https URLs only on a remote source, so requests and credentials never go out in the clear. */
16853
+ function isHttpsUrl(value) {
16854
+ return URL.canParse(value) && new URL(value).protocol === "https:";
16855
+ }
16856
+ //#endregion
16857
+ //#region src/define/fields/remote.validation.ts
16858
+ /**
16859
+ * GraphQL's scalars and the ones Hygraph adds to a REST source, which a
16860
+ * REST source's field can return or take without declaring them.
16861
+ */
16862
+ const REST_SCALARS = /* @__PURE__ */ new Set([
16863
+ "String",
16864
+ "Int",
16865
+ "Float",
16866
+ "Boolean",
16867
+ "ID",
16868
+ "Date",
16869
+ "DateTime",
16870
+ "Json"
16871
+ ]);
16872
+ /** `{{doc.city}}`, `{{args.lookup.id}}`: the kind and the first name after it. */
16873
+ const PLACEHOLDER = /\{\{\s*(doc|args)\.([A-Za-z0-9_]+)[^}]*\}\}/g;
16874
+ /**
16875
+ * What a remote field can tell about itself: Hygraph takes it on a model
16876
+ * only, cannot rename it, sends a GraphQL source a query, which it needs,
16877
+ * and calls a REST one at a path, caches for 0 or at least 60 seconds, and sends no header
16878
+ * empty. Each argument is declared once, and every `{{args.x}}` names one.
16879
+ */
16880
+ function validateRemoteField(parent, field) {
16881
+ const validations = [];
16882
+ const report = (code, attribute, message) => validations.push({
16883
+ code,
16884
+ severity: "error",
16885
+ path: fieldPath(parent, field.apiId, attribute),
16886
+ message,
16887
+ fix: fixes[code]
16888
+ });
16889
+ if (parent.kind === "component") report("field.remoteOnComponent", "source", messages["field.remoteOnComponent"](field.apiId));
16890
+ if (field.renamedFrom !== null) report("field.remoteRenameUnsupported", "renamedFrom", messages["field.remoteRenameUnsupported"](field.apiId));
16891
+ const graphql = field.source.__typename === "GraphQLRemoteSource";
16892
+ if (!graphql && field.query !== null) report("field.remoteQueryOnRest", "query", messages["field.remoteQueryOnRest"](field.apiId, field.source.prefix));
16893
+ if (graphql && field.query === null) report("field.remoteQueryMissing", "query", messages["field.remoteQueryMissing"](field.apiId, field.source.prefix));
16894
+ if (graphql && field.path !== null) report("field.remotePathOnGraphQL", "path", messages["field.remotePathOnGraphQL"](field.apiId, field.source.prefix));
16895
+ const ttl = field.cacheTTLSeconds;
16896
+ if (!Number.isInteger(ttl) || ttl !== 0 && ttl < 60) report("field.remoteCacheTTLInvalid", "cacheTTLSeconds", messages["field.remoteCacheTTLInvalid"](field.apiId, String(ttl)));
16897
+ for (const [name, value] of Object.entries(field.headers)) if (hasNoValue(value)) validations.push({
16898
+ code: "field.remoteHeaderMissing",
16899
+ severity: "error",
16900
+ path: [...fieldPath(parent, field.apiId, "headers"), name],
16901
+ message: messages["field.remoteHeaderMissing"](field.apiId, name),
16902
+ fix: fixes["field.remoteHeaderMissing"]
16903
+ });
16904
+ const args = /* @__PURE__ */ new Set();
16905
+ for (const arg of field.args) {
16906
+ if (args.has(arg.apiId)) report("field.remoteArgDuplicate", "args", messages["field.remoteArgDuplicate"](field.apiId, arg.apiId));
16907
+ args.add(arg.apiId);
16908
+ }
16909
+ for (const [attribute, placeholder] of placeholders(field, "args")) if (!args.has(placeholder)) report("field.remotePlaceholderArg", attribute, messages["field.remotePlaceholderArg"](field.apiId, `args.${placeholder}`));
16910
+ return validations;
16911
+ }
16912
+ /**
16913
+ * What a remote field needs from the environment: its source in
16914
+ * `remoteSources`, for every `{{doc.x}}` the entry's `id` or a field of the
16915
+ * same parent that is not a remote field, the names Studio offers, and on
16916
+ * a REST source, whose types are all in the config, a declared or scalar
16917
+ * type for `returnType` and each argument. A GraphQL source's types come
16918
+ * from introspection, which the config does not hold; the server checks
16919
+ * those on apply. A parent without entries, Query, takes no `{{doc.x}}`.
16920
+ */
16921
+ function validateRemoteFieldReferences(parent, fields, sources, { entries = true } = {}) {
16922
+ const documentFields = /* @__PURE__ */ new Set(["id", ...fields.filter((field) => field.__typename !== "RemoteField").map((field) => field.apiId)]);
16923
+ return fields.flatMap((field) => {
16924
+ if (field.__typename !== "RemoteField") return [];
16925
+ const source = sources.get(field.source.prefix);
16926
+ if (source === void 0) {
16927
+ const code = "field.remoteSourceMissing";
16928
+ return [{
16929
+ code,
16930
+ severity: "error",
16931
+ path: fieldPath(parent, field.apiId, "source"),
16932
+ message: messages[code](field.apiId, field.source.prefix),
16933
+ fix: fixes[code]
16934
+ }];
16935
+ }
16936
+ const validations = [];
16937
+ for (const [attribute, placeholder] of placeholders(field, "doc")) if (!entries) {
16938
+ const code = "field.remotePlaceholderDocOnQuery";
16939
+ validations.push({
16940
+ code,
16941
+ severity: "error",
16942
+ path: fieldPath(parent, field.apiId, attribute),
16943
+ message: messages[code](field.apiId, `doc.${placeholder}`),
16944
+ fix: fixes[code]
16945
+ });
16946
+ } else if (!documentFields.has(placeholder)) {
16947
+ const code = "field.remotePlaceholderField";
16948
+ validations.push({
16949
+ code,
16950
+ severity: "error",
16951
+ path: fieldPath(parent, field.apiId, attribute),
16952
+ message: messages[code](field.apiId, `doc.${placeholder}`),
16953
+ fix: fixes[code]
16954
+ });
16955
+ }
16956
+ if (source.__typename === "RESTRemoteSource") {
16957
+ const declared = declaredTypes(source);
16958
+ const used = [["returnType", field.returnType], ...field.args.map((arg) => ["args", arg.type])];
16959
+ for (const [attribute, type] of used) if (!REST_SCALARS.has(type) && !declared.has(type)) {
16960
+ const code = "field.remoteTypeUnknown";
16961
+ validations.push({
16962
+ code,
16963
+ severity: "error",
16964
+ path: fieldPath(parent, field.apiId, attribute),
16965
+ message: messages[code](field.apiId, type, source.prefix),
16966
+ fix: fixes[code]
16967
+ });
16968
+ }
16969
+ }
16970
+ return validations;
16971
+ });
16972
+ }
16973
+ /** Every `{{doc.x}}` or `{{args.x}}` in the query, the path and the headers, by attribute. */
16974
+ function placeholders(field, kind) {
16975
+ return [
16976
+ ["query", field.query ?? ""],
16977
+ ["path", field.path ?? ""],
16978
+ ...Object.values(field.headers).flatMap((value) => (Array.isArray(value) ? value : [value]).map((each) => ["headers", each ?? ""]))
16979
+ ].flatMap(([attribute, text]) => [...text.matchAll(PLACEHOLDER)].filter((match) => match[1] === kind).map((match) => [attribute, match[2] ?? ""]));
16980
+ }
16981
+ /** The type names a source's SDL declares, none when it does not parse; its own check reports that. */
16982
+ function declaredTypes(source) {
16983
+ if (source.remoteTypeDefinitions === null) return /* @__PURE__ */ new Set();
16984
+ try {
16985
+ return new Set(splitTypeDefinitions(source.remoteTypeDefinitions).map((type) => type.apiId));
16986
+ } catch {
16987
+ return /* @__PURE__ */ new Set();
16988
+ }
16989
+ }
16990
+ //#endregion
15601
16991
  //#region src/define/fields/richText.validation.ts
15602
16992
  /**
15603
16993
  * What only rich text checks, from the server's rules and Studio's form:
@@ -15741,19 +17131,44 @@ function isValidStageApiId(value) {
15741
17131
  //#endregion
15742
17132
  //#region src/define/fields/asset.validation.ts
15743
17133
  /**
15744
- * What only asset fields check. The other side on Asset is named after the
15745
- * field and its parent, and must be a valid field apiId, up to 64
15746
- * characters: the server refuses any other, failing the whole migration.
17134
+ * What only asset fields check. On a model, `reverse` names the other
17135
+ * side on Asset; on a component it is left out, and the CLI names the
17136
+ * hidden one after the field and the component. Either way it must be a
17137
+ * valid field apiId, up to 64 characters: the server refuses any other,
17138
+ * failing the whole migration.
15747
17139
  */
15748
17140
  function validateAssetField(parent, field) {
15749
17141
  const validations = [];
15750
- const reverse = assetReverseApiId(field.apiId, parent.apiId);
17142
+ if (parent.kind === "model" && field.reverse === null) {
17143
+ const code = "field.assetReverseFieldMissing";
17144
+ const suggested = assetReverseApiId(field.apiId, parent.apiId);
17145
+ validations.push({
17146
+ code,
17147
+ severity: "error",
17148
+ path: fieldPath(parent, field.apiId, "reverse"),
17149
+ message: messages[code](parent.apiId, field.apiId),
17150
+ fix: fixes[code](parent.apiId, field.apiId, suggested)
17151
+ });
17152
+ return validations;
17153
+ }
17154
+ if (parent.kind === "component" && field.reverse !== null) {
17155
+ const code = "field.assetReverseFieldOnComponent";
17156
+ validations.push({
17157
+ code,
17158
+ severity: "error",
17159
+ path: fieldPath(parent, field.apiId, "reverse"),
17160
+ message: messages[code](parent.apiId, field.apiId),
17161
+ fix: fixes[code]
17162
+ });
17163
+ return validations;
17164
+ }
17165
+ const reverse = field.reverse ?? assetReverseApiId(field.apiId, parent.apiId);
15751
17166
  if (!isValidFieldApiId(reverse)) {
15752
17167
  const code = "field.assetReverseInvalid";
15753
17168
  validations.push({
15754
17169
  code,
15755
17170
  severity: "error",
15756
- path: fieldPath(parent, field.apiId, "apiId"),
17171
+ path: fieldPath(parent, field.apiId, field.reverse === null ? "apiId" : "reverse"),
15757
17172
  message: messages[code](field.apiId, reverse),
15758
17173
  fix: fixes[code]
15759
17174
  });
@@ -16016,10 +17431,12 @@ function validateTypeOptions(parent, field) {
16016
17431
  case "ReferenceUnionField": return [...validateReferenceUnionField(parent, field), ...validateReferenceField(parent, field)];
16017
17432
  case "ReferenceUnionMemberField": return [];
16018
17433
  case "AssetField": return validateAssetField(parent, field);
17434
+ case "AssetReverseField": return [];
16019
17435
  case "RichTextField": return validateRichTextField(parent, field);
16020
17436
  case "ColorField": return validateColorField(parent, field);
16021
17437
  case "EnumerationField": return validateEnumerationField(parent, field);
16022
17438
  case "TaxonomyField": return validateTaxonomyField(parent, field);
17439
+ case "RemoteField": return validateRemoteField(parent, field);
16023
17440
  case "IntField":
16024
17441
  case "FloatField": return validateNumberField(parent, field);
16025
17442
  case "SingleLineField":
@@ -16145,6 +17562,80 @@ function validateOptions(parent, field) {
16145
17562
  return validations;
16146
17563
  }
16147
17564
  //#endregion
17565
+ //#region src/define/system/asset.validation.ts
17566
+ /**
17567
+ * What Asset can tell about itself: its fields, as a model's are checked,
17568
+ * and what Hygraph refuses on a model it provides. A required field and a
17569
+ * component union fail the whole migration. A two-way reference on Asset
17570
+ * is a field back, which `assetReverseField` declares. There is no title
17571
+ * check: Studio shows assets by their file.
17572
+ */
17573
+ function validateSystemAsset(asset) {
17574
+ const parent = {
17575
+ kind: "model",
17576
+ apiId: asset.apiId
17577
+ };
17578
+ const validations = validateFields(parent, asset.fields);
17579
+ for (const field of asset.fields) if (field.__typename === "ComponentUnionField") {
17580
+ const code = "systemModel.fieldUnion";
17581
+ validations.push({
17582
+ code,
17583
+ severity: "error",
17584
+ path: fieldPath(parent, field.apiId, "components"),
17585
+ message: messages[code](asset.apiId, field.apiId),
17586
+ fix: fixes[code]
17587
+ });
17588
+ } else if (field.__typename === "ReferenceTwoWayField") {
17589
+ const code = "systemModel.fieldReferenceTwoWay";
17590
+ validations.push({
17591
+ code,
17592
+ severity: "error",
17593
+ path: fieldPath(parent, field.apiId, "to"),
17594
+ message: messages[code](asset.apiId, field.apiId),
17595
+ fix: fixes[code]
17596
+ });
17597
+ } else if (field.__typename !== "UnsupportedField" && field.required) {
17598
+ const code = "systemModel.fieldRequired";
17599
+ validations.push({
17600
+ code,
17601
+ severity: "error",
17602
+ path: fieldPath(parent, field.apiId, "required"),
17603
+ message: messages[code](asset.apiId, field.apiId),
17604
+ fix: fixes[code]
17605
+ });
17606
+ }
17607
+ return validations;
17608
+ }
17609
+ //#endregion
17610
+ //#region src/define/system/query.validation.ts
17611
+ /**
17612
+ * What Query can tell about itself: its fields, as a model's are checked,
17613
+ * and that each is a remote field, the only type Hygraph takes there. An
17614
+ * unsupported field is one the CLI cannot read yet, a remote field too.
17615
+ */
17616
+ function validateSystemQuery(query) {
17617
+ const validations = validateFields({
17618
+ kind: "model",
17619
+ apiId: query.apiId
17620
+ }, query.fields);
17621
+ for (const field of query.fields) if (field.__typename !== "RemoteField" && field.__typename !== "UnsupportedField") {
17622
+ const code = "systemModel.fieldNotRemote";
17623
+ validations.push({
17624
+ code,
17625
+ severity: "error",
17626
+ path: [
17627
+ "models",
17628
+ query.apiId,
17629
+ "fields",
17630
+ field.apiId
17631
+ ],
17632
+ message: messages[code](field.apiId),
17633
+ fix: fixes[code]
17634
+ });
17635
+ }
17636
+ return validations;
17637
+ }
17638
+ //#endregion
16148
17639
  //#region src/define/resources/component.validation.ts
16149
17640
  /**
16150
17641
  * What a component can tell about itself, its fields included. Whether its
@@ -16694,13 +18185,23 @@ function nodePath(taxonomy, node) {
16694
18185
  }
16695
18186
  //#endregion
16696
18187
  //#region src/define/resources/environment.validation.ts
18188
+ /** The call that lists each model Hygraph provides, as the config writes it. */
18189
+ const SYSTEM_MODEL_CALLS = {
18190
+ SystemAsset: "system.asset()",
18191
+ SystemQuery: "system.query()"
18192
+ };
16697
18193
  /**
16698
18194
  * What only the whole environment can tell: whether two resources collide,
16699
18195
  * whether exactly one locale is the default, whether a stage takes Draft's
16700
18196
  * or Published's names, and whether every enumeration, taxonomy, component
16701
- * and model a field uses is in it. Models, components, enumerations and
18197
+ * and model a field uses is in it. Remote sources have their own namespace,
18198
+ * by prefix. Models, components, enumerations and
16702
18199
  * taxonomies share one apiId namespace; locales and stages each have their
16703
- * own. Display names are unique per kind.
18200
+ * own. Display names are unique per kind. `Asset`, `QueryModel` and
18201
+ * `Query` are Hygraph's: a model of yours cannot take any of them, and
18202
+ * `system.asset` and `system.query` are listed once each. An asset field
18203
+ * on a model or on Asset names its field back on Asset, which
18204
+ * `system.asset` lists as an `assetReverseField`.
16704
18205
  *
16705
18206
  * Runs over the models as declared, before conversion, so every report
16706
18207
  * points at the config the user wrote.
@@ -16711,8 +18212,37 @@ function validateEnvironment(environment) {
16711
18212
  const displayNames = /* @__PURE__ */ new Set();
16712
18213
  validations.push(...validateLocales(environment.locales));
16713
18214
  validations.push(...validateStages(environment.stages));
18215
+ const systemApiIds = /* @__PURE__ */ new Set();
18216
+ for (const model of environment.systemModels) {
18217
+ validations.push(...model.__typename === "SystemAsset" ? validateSystemAsset(model) : validateSystemQuery(model));
18218
+ if (systemApiIds.has(model.apiId)) {
18219
+ const code = "systemModel.duplicate";
18220
+ validations.push({
18221
+ code,
18222
+ severity: "error",
18223
+ path: ["models", model.apiId],
18224
+ message: messages[code](SYSTEM_MODEL_CALLS[model.__typename]),
18225
+ fix: fixes[code]
18226
+ });
18227
+ }
18228
+ systemApiIds.add(model.apiId);
18229
+ }
16714
18230
  for (const model of environment.models) {
16715
18231
  validations.push(...validateModel(model));
18232
+ if ([
18233
+ "Asset",
18234
+ "QueryModel",
18235
+ "Query"
18236
+ ].includes(model.apiId)) {
18237
+ const code = "model.apiIdReserved";
18238
+ validations.push({
18239
+ code,
18240
+ severity: "error",
18241
+ path: modelPath(model.apiId, "apiId"),
18242
+ message: messages[code](model.apiId),
18243
+ fix: fixes[code]
18244
+ });
18245
+ }
16716
18246
  if (apiIds.has(model.apiId)) validations.push({
16717
18247
  code: "model.duplicateApiId",
16718
18248
  severity: "error",
@@ -16730,6 +18260,41 @@ function validateEnvironment(environment) {
16730
18260
  });
16731
18261
  displayNames.add(model.displayName);
16732
18262
  }
18263
+ const asset = environment.systemModels.find((model) => model.__typename === "SystemAsset");
18264
+ const fieldsBack = new Set(asset?.fields.filter((field) => field.__typename === "AssetReverseField").map((field) => field.apiId));
18265
+ for (const parent of [...environment.models, ...asset ? [asset] : []]) for (const field of parent.fields) {
18266
+ if (field.__typename !== "AssetField" || field.reverse === null) continue;
18267
+ if (!asset) {
18268
+ const code = "field.assetSystemAssetMissing";
18269
+ validations.push({
18270
+ code,
18271
+ severity: "error",
18272
+ path: [
18273
+ "models",
18274
+ parent.apiId,
18275
+ "fields",
18276
+ field.apiId
18277
+ ],
18278
+ message: messages[code](parent.apiId, field.apiId, field.reverse),
18279
+ fix: fixes[code](parent.apiId, field.apiId, field.reverse)
18280
+ });
18281
+ } else if (!fieldsBack.has(field.reverse)) {
18282
+ const code = "field.assetFieldBackMissing";
18283
+ validations.push({
18284
+ code,
18285
+ severity: "error",
18286
+ path: [
18287
+ "models",
18288
+ parent.apiId,
18289
+ "fields",
18290
+ field.apiId,
18291
+ "reverse"
18292
+ ],
18293
+ message: messages[code](parent.apiId, field.apiId, field.reverse),
18294
+ fix: fixes[code](parent.apiId, field.apiId, field.reverse)
18295
+ });
18296
+ }
18297
+ }
16733
18298
  const componentDisplayNames = /* @__PURE__ */ new Set();
16734
18299
  for (const component of environment.components) {
16735
18300
  validations.push(...validateComponent(component));
@@ -16790,23 +18355,44 @@ function validateEnvironment(environment) {
16790
18355
  });
16791
18356
  taxonomyDisplayNames.add(taxonomy.displayName);
16792
18357
  }
18358
+ const prefixes = /* @__PURE__ */ new Set();
18359
+ for (const source of environment.remoteSources) {
18360
+ validations.push(...validateRemoteSource(source));
18361
+ if (prefixes.has(source.prefix)) validations.push({
18362
+ code: "remoteSource.duplicatePrefix",
18363
+ severity: "error",
18364
+ path: remoteSourcePath(source.prefix, "prefix"),
18365
+ message: messages["remoteSource.duplicatePrefix"](source.prefix),
18366
+ fix: fixes["remoteSource.duplicatePrefix"]
18367
+ });
18368
+ prefixes.add(source.prefix);
18369
+ }
16793
18370
  const enumerations = new Map(environment.enumerations.map((enumeration) => [enumeration.apiId, enumeration]));
16794
- const parents = [...environment.models.map((model) => ({
16795
- kind: "model",
16796
- ...model
16797
- })), ...environment.components.map((component) => ({
16798
- kind: "component",
16799
- ...component
16800
- }))];
18371
+ const parents = [
18372
+ ...environment.models.map((model) => ({
18373
+ kind: "model",
18374
+ ...model
18375
+ })),
18376
+ ...environment.systemModels.map((model) => ({
18377
+ kind: "model",
18378
+ ...model
18379
+ })),
18380
+ ...environment.components.map((component) => ({
18381
+ kind: "component",
18382
+ ...component
18383
+ }))
18384
+ ];
16801
18385
  const components = new Set(environment.components.map((component) => component.apiId));
16802
18386
  const models = new Map(environment.models.map((model) => [model.apiId, model]));
18387
+ const withAsset = new Map([...models, ...asset ? [[asset.apiId, asset]] : []]);
16803
18388
  const taxonomies = new Map(environment.taxonomies.map((taxonomy) => [taxonomy.apiId, taxonomy]));
18389
+ const sources = new Map(environment.remoteSources.map((source) => [source.prefix, source]));
16804
18390
  for (const parent of parents) {
16805
18391
  const fieldParent = {
16806
18392
  kind: parent.kind,
16807
18393
  apiId: parent.apiId
16808
18394
  };
16809
- validations.push(...validateEnumerationFieldReferences(fieldParent, parent.fields, enumerations), ...validateComponentFieldReferences(fieldParent, parent.fields, components), ...validateReferenceModelReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceTwoWayPartners(fieldParent, parent.fields, models), ...validateRichTextEmbedReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceUnionMembers(fieldParent, parent.fields, models), ...validateTaxonomyFieldReferences(fieldParent, parent.fields, taxonomies));
18395
+ validations.push(...validateEnumerationFieldReferences(fieldParent, parent.fields, enumerations), ...validateComponentFieldReferences(fieldParent, parent.fields, components), ...validateReferenceModelReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceTwoWayPartners(fieldParent, parent.fields, models), ...validateAssetReverseFields(fieldParent, parent.fields, withAsset), ...validateRichTextEmbedReferences(fieldParent, parent.fields, new Set(models.keys())), ...validateReferenceUnionMembers(fieldParent, parent.fields, models), ...validateTaxonomyFieldReferences(fieldParent, parent.fields, taxonomies), ...validateRemoteFieldReferences(fieldParent, parent.fields, sources, { entries: parent.__typename !== "SystemQuery" }));
16810
18396
  }
16811
18397
  return validations;
16812
18398
  }
@@ -16944,7 +18530,8 @@ function pairTwoWayReferences(from, to, unsupportedPairs = []) {
16944
18530
  const livePartner = twoWay(fromModels, field.to, field.reverse);
16945
18531
  if (live?.to === field.to && live.reverse === field.reverse && live.list === field.list && partner !== void 0 && livePartner?.list === partner.list) inPlace.add(sideKey(parent, field.apiId));
16946
18532
  }
16947
- const deletes = ({ parent, apiId }) => toModels.has(parent) && !inPlace.has(sideKey(parent, apiId)) && toModels.get(parent)?.fields[apiId]?.kind !== "unsupported";
18533
+ const toParents = new Map(fieldParents(to).map((parent) => [parent.apiId, parent]));
18534
+ const deletes = ({ parent, apiId }) => toParents.has(parent) && !inPlace.has(sideKey(parent, apiId)) && toParents.get(parent)?.fields[apiId]?.kind !== "unsupported";
16948
18535
  const livePairs = [...sides(from.models).map(({ parent, field }) => [{
16949
18536
  parent,
16950
18537
  apiId: field.apiId
@@ -17416,6 +19003,7 @@ function changesInPlace(from, to) {
17416
19003
  if (from.kind === "unsupported" || to.kind === "unsupported") return from.kind === "unsupported" && to.kind === "unsupported" && from.type === to.type;
17417
19004
  if (from.kind === "enumeration" && to.kind === "enumeration") return from.list === to.list && from.enumeration === to.enumeration && from.localized === to.localized;
17418
19005
  if (from.kind === "taxonomy" && to.kind === "taxonomy") return from.list === to.list && from.taxonomy === to.taxonomy;
19006
+ if (from.kind === "remote" && to.kind === "remote") return from.list === to.list && from.type === to.type;
17419
19007
  if (from.kind === "component" && to.kind === "component") return from.list === to.list && from.component === to.component;
17420
19008
  if (from.kind === "componentUnion" && to.kind === "componentUnion") return from.list === to.list && from.visibility === to.visibility;
17421
19009
  if (from.kind === "referenceOneWay" && to.kind === "referenceOneWay") return from.list === to.list && from.to === to.to;
@@ -17499,12 +19087,54 @@ function diffField(from, to) {
17499
19087
  from: from.initialValue,
17500
19088
  to: to.initialValue
17501
19089
  };
19090
+ if (from.kind === "remote" && to.kind === "remote") Object.assign(changes, diffRemoteField(from, to));
17502
19091
  if (from.position !== to.position) changes.position = {
17503
19092
  from: from.position,
17504
19093
  to: to.position
17505
19094
  };
17506
19095
  return changes;
17507
19096
  }
19097
+ /** A remote field's own attributes. Headers and arguments are sorted, so equal ones hash the same. */
19098
+ function diffRemoteField(from, to) {
19099
+ const changes = {};
19100
+ if (from.source !== to.source) changes.source = {
19101
+ from: from.source,
19102
+ to: to.source
19103
+ };
19104
+ if (from.returnType !== to.returnType) changes.returnType = {
19105
+ from: from.returnType,
19106
+ to: to.returnType
19107
+ };
19108
+ if (from.method !== to.method) changes.method = {
19109
+ from: from.method,
19110
+ to: to.method
19111
+ };
19112
+ if (from.query !== to.query) changes.query = {
19113
+ from: from.query,
19114
+ to: to.query
19115
+ };
19116
+ if (from.path !== to.path) changes.path = {
19117
+ from: from.path,
19118
+ to: to.path
19119
+ };
19120
+ if (hashJSON(from.headers) !== hashJSON(to.headers)) changes.headers = {
19121
+ from: from.headers,
19122
+ to: to.headers
19123
+ };
19124
+ if (from.forwardClientHeaders !== to.forwardClientHeaders) changes.forwardClientHeaders = {
19125
+ from: from.forwardClientHeaders,
19126
+ to: to.forwardClientHeaders
19127
+ };
19128
+ if (from.cacheTTLSeconds !== to.cacheTTLSeconds) changes.cacheTTLSeconds = {
19129
+ from: from.cacheTTLSeconds,
19130
+ to: to.cacheTTLSeconds
19131
+ };
19132
+ if (hashJSON(from.args) !== hashJSON(to.args)) changes.args = {
19133
+ from: from.args,
19134
+ to: to.args
19135
+ };
19136
+ return changes;
19137
+ }
17508
19138
  /** Values are sorted in the IR, so equal conditions hash the same. */
17509
19139
  function sameCondition(a, b) {
17510
19140
  return hashJSON(a) === hashJSON(b);
@@ -17612,6 +19242,65 @@ function diffModel(from, to) {
17612
19242
  return changes;
17613
19243
  }
17614
19244
  //#endregion
19245
+ //#region src/diff/resources/remoteSource.ts
19246
+ /**
19247
+ * Whether `to` cannot be reached from `from` in place: Hygraph does not
19248
+ * change a source's type. The source is deleted and created again, and so
19249
+ * are its fields, whose type changes with it. A new introspection URL, a
19250
+ * new kind and OAuth taken away are refused before the diff
19251
+ * (`validateRemoteSourceChanges`).
19252
+ */
19253
+ function recreatesRemoteSource(from, to) {
19254
+ return from.type !== to.type;
19255
+ }
19256
+ /**
19257
+ * The attributes of `to` that differ from `from`, each with both values.
19258
+ * Empty when the two agree. Only called on two sources of one type that
19259
+ * `recreatesRemoteSource` keeps.
19260
+ */
19261
+ function diffRemoteSource(from, to) {
19262
+ const changes = {};
19263
+ if (from.displayName !== to.displayName) changes.displayName = {
19264
+ from: from.displayName,
19265
+ to: to.displayName
19266
+ };
19267
+ if (from.description !== to.description) changes.description = {
19268
+ from: from.description,
19269
+ to: to.description
19270
+ };
19271
+ if (from.url !== to.url) changes.url = {
19272
+ from: from.url,
19273
+ to: to.url
19274
+ };
19275
+ if (hashJSON(from.headers) !== hashJSON(to.headers)) changes.headers = {
19276
+ from: from.headers,
19277
+ to: to.headers
19278
+ };
19279
+ if (from.debugEnabled !== to.debugEnabled) changes.debugEnabled = {
19280
+ from: from.debugEnabled,
19281
+ to: to.debugEnabled
19282
+ };
19283
+ if (hashJSON(from.oAuth) !== hashJSON(to.oAuth)) changes.oAuth = {
19284
+ from: from.oAuth,
19285
+ to: to.oAuth
19286
+ };
19287
+ if (hashJSON(from.typeDefinitions) !== hashJSON(to.typeDefinitions)) changes.typeDefinitions = {
19288
+ from: from.typeDefinitions,
19289
+ to: to.typeDefinitions
19290
+ };
19291
+ if (from.type === "GRAPHQL" && to.type === "GRAPHQL") {
19292
+ if (from.introspectionMethod !== to.introspectionMethod) changes.introspectionMethod = {
19293
+ from: from.introspectionMethod,
19294
+ to: to.introspectionMethod
19295
+ };
19296
+ if (hashJSON(from.introspectionHeaders) !== hashJSON(to.introspectionHeaders)) changes.introspectionHeaders = {
19297
+ from: from.introspectionHeaders,
19298
+ to: to.introspectionHeaders
19299
+ };
19300
+ }
19301
+ return changes;
19302
+ }
19303
+ //#endregion
17615
19304
  //#region src/diff/resources/stage.ts
17616
19305
  /**
17617
19306
  * The attributes of `to` that differ from `from`, each with both values.
@@ -17818,11 +19507,12 @@ function parentsFirst(nodes) {
17818
19507
  * so that everything after them uses the new names;
17819
19508
  * 2. field deletes, the updates of rich text that drops a model the plan
17820
19509
  * deletes (see `orderEmbeds`), model deletes, value deletes, enumeration
17821
- * deletes, taxonomy deletes, locale deletes, then stage deletes, which
17822
- * free the names a create may claim. A two-way pair has one delete, from the side
17823
- * on the lower model, so the side it takes along is gone before that
17824
- * model's own deletes renumber it. A union's delete, which takes its
17825
- * members along, comes before every other field delete for the same
19510
+ * deletes, taxonomy deletes, the deletes of remote sources created
19511
+ * again, locale deletes, then stage deletes, which free the names a
19512
+ * create may claim. A two-way pair has one delete, from the side on the
19513
+ * lower model, so the side it takes along is gone before that model's
19514
+ * own deletes renumber it. A union's delete, which takes its members
19515
+ * along, comes before every other field delete for the same
17826
19516
  * reason, and is sent even when its model goes, if a member's model
17827
19517
  * stays. The union updates that drop models follow the field deletes:
17828
19518
  * the server deletes the dropped members, which renumbers their models
@@ -17838,13 +19528,16 @@ function parentsFirst(nodes) {
17838
19528
  * that put the stages in order;
17839
19529
  * 4. enumeration updates, enumeration creates, value updates and value
17840
19530
  * creates, then taxonomy updates, taxonomy creates, node creates, node
17841
- * updates and node deletes, so that every value and node exists before
17842
- * the models and fields. A node is created before the nodes under it,
17843
- * and moves away from a node before that node is deleted;
19531
+ * updates and node deletes, then remote source updates and creates, so
19532
+ * that every value, node and source exists before the models and
19533
+ * fields. A node is created before the nodes under it, and moves away
19534
+ * from a node before that node is deleted. A source whose type or
19535
+ * introspection URL changes is deleted in step 2 and created here;
17844
19536
  * 5. component updates, component creates, model updates, then field
17845
- * updates, carrying only what differs. A component update frees the
17846
- * names a create may claim, and a union update finds the components it
17847
- * adds;
19537
+ * updates, carrying only what differs, then remote source deletes. A
19538
+ * component update frees the names a create may claim, and a union
19539
+ * update finds the components it adds. A field update may move a remote
19540
+ * field off a source, which Hygraph cannot delete while a field uses it;
17848
19541
  * 6. component deletes. Hygraph refuses to delete a component while a
17849
19542
  * field uses it, so they wait for the field deletes and for the union
17850
19543
  * updates that drop them;
@@ -17856,9 +19549,17 @@ function parentsFirst(nodes) {
17856
19549
  * updates of rich text that embeds a model created in step 7.
17857
19550
  *
17858
19551
  * Locales, stages, enumerations, taxonomies, components and models follow
17859
- * apiId order within each step, but stage creates and moves follow the
19552
+ * apiId order within each step, remote sources prefix order, but stage creates and moves follow the
17860
19553
  * config's order; values and fields follow apiId order within their
17861
- * parent. Fields of models come before fields of components.
19554
+ * parent. Fields of models come before fields of Asset, and those before
19555
+ * fields of components.
19556
+ *
19557
+ * Asset is Hygraph's: only its fields change, never Asset itself, and only
19558
+ * when the config lists it. Leaving it out of the config keeps its fields.
19559
+ * A field back on Asset goes with its asset field: a new asset field takes
19560
+ * its field back's slot from the config, and a deleted one's field back is
19561
+ * not deleted on its own. The server numbers Asset's fields again only
19562
+ * when the asset field was on Asset itself.
17862
19563
  */
17863
19564
  function diffEnvironment({ from, to, intents = {
17864
19565
  renames: [],
@@ -17894,8 +19595,8 @@ function diffEnvironment({ from, to, intents = {
17894
19595
  const memberDrops = [];
17895
19596
  const memberAdds = [];
17896
19597
  const fieldConditions = [];
17897
- const pushFields = (fromParent, parent) => {
17898
- const fields = diffFields(fromParent, parent, new Map(intents.migrationValues.filter((migration) => migration.parent === parent.apiId).map((migration) => [migration.apiId, migration.value])), pairs, unions);
19598
+ const pushFields = (fromParent, parent, parentPairs = pairs) => {
19599
+ const fields = diffFields(fromParent, parent, new Map(intents.migrationValues.filter((migration) => migration.parent === parent.apiId).map((migration) => [migration.apiId, migration.value])), parentPairs, unions);
17899
19600
  for (const fieldDelete of fields.deletes) (fieldDelete.members ? unionDeletes : fieldDeletes).push(fieldDelete);
17900
19601
  fieldUpdates.push(...fields.updates);
17901
19602
  fieldCreates.push(...fields.creates);
@@ -17924,6 +19625,18 @@ function diffEnvironment({ from, to, intents = {
17924
19625
  changes
17925
19626
  });
17926
19627
  }
19628
+ if (to.asset) {
19629
+ const gone = fieldsBackDeletedWith(renamed, [...fieldDeletes, ...modelDeletes]);
19630
+ pushFields(renamed.asset ? {
19631
+ ...renamed.asset,
19632
+ fields: Object.fromEntries(Object.entries(renamed.asset.fields).filter(([apiId]) => !gone.has(apiId)))
19633
+ } : null, to.asset, {
19634
+ ...pairFieldsBack(renamed, to),
19635
+ cascaded: pairs.cascaded,
19636
+ deletedPartners: pairs.deletedPartners
19637
+ });
19638
+ }
19639
+ if (to.query) pushFields(renamed.query ?? null, to.query);
17927
19640
  const fromComponents = new Map(renamed.components.map((component) => [component.apiId, component]));
17928
19641
  const toComponentApiIds = new Set(to.components.map((component) => component.apiId));
17929
19642
  const deletedComponents = renamed.components.filter((component) => !toComponentApiIds.has(component.apiId));
@@ -17958,17 +19671,20 @@ function diffEnvironment({ from, to, intents = {
17958
19671
  const stages = diffStages(renamed.stages, to.stages);
17959
19672
  const enumerations = diffEnumerations(renamed, to);
17960
19673
  const taxonomies = diffTaxonomies(renamed, to);
19674
+ const goneWithTheirField = fieldsBackDeletedWith(renamed, fieldDeletes);
19675
+ const remoteSources = diffRemoteSources(renamed, to);
17961
19676
  const embeds = orderEmbeds(fieldUpdates, new Set(modelDeletes.flatMap((change) => change.resource === "model" && change.action === "delete" ? [change.apiId] : [])), new Set(to.models.filter((model) => !fromModels.has(model.apiId)).map((model) => model.apiId)));
17962
19677
  return [
17963
19678
  ...renames,
17964
19679
  ...unionDeletes,
17965
- ...fieldDeletes,
19680
+ ...fieldDeletes.filter((change) => !(change.action === "delete" && change.resource === "field" && change.parent === "Asset" && goneWithTheirField.has(change.apiId))),
17966
19681
  ...memberDrops,
17967
19682
  ...embeds.beforeModelDeletes,
17968
19683
  ...modelDeletes,
17969
19684
  ...enumerations.valueDeletes,
17970
19685
  ...enumerations.deletes,
17971
19686
  ...taxonomies.deletes,
19687
+ ...remoteSources.recreates,
17972
19688
  ...locales.deletes,
17973
19689
  ...stages.deletes,
17974
19690
  ...locales.updates,
@@ -17986,13 +19702,16 @@ function diffEnvironment({ from, to, intents = {
17986
19702
  ...taxonomies.nodeCreates,
17987
19703
  ...taxonomies.nodeUpdates,
17988
19704
  ...taxonomies.nodeDeletes,
19705
+ ...remoteSources.updates,
19706
+ ...remoteSources.creates,
17989
19707
  ...componentUpdates,
17990
19708
  ...componentCreates,
17991
19709
  ...modelUpdates,
17992
19710
  ...embeds.updates,
19711
+ ...remoteSources.deletes,
17993
19712
  ...componentDeletes,
17994
19713
  ...modelCreates,
17995
- ...fieldCreates,
19714
+ ...fieldCreates.map((change) => withFieldBack(change, to)),
17996
19715
  ...memberAdds,
17997
19716
  ...fieldConditions,
17998
19717
  ...embeds.afterModelCreates
@@ -18029,6 +19748,60 @@ function orderEmbeds(changes, deleted, created) {
18029
19748
  return order;
18030
19749
  }
18031
19750
  /**
19751
+ * The fields back on Asset whose asset field the changes delete, on its
19752
+ * own or with its model, as `from` names them after the renames.
19753
+ */
19754
+ function fieldsBackDeletedWith(renamed, deletes) {
19755
+ const parents = new Map(fieldParents(renamed).map((parent) => [parent.apiId, parent]));
19756
+ const backs = /* @__PURE__ */ new Set();
19757
+ for (const change of deletes) {
19758
+ const fields = change.action !== "delete" ? [] : change.resource === "model" ? Object.values(parents.get(change.apiId)?.fields ?? {}) : change.resource === "field" ? [parents.get(change.parent)?.fields[change.apiId]] : [];
19759
+ for (const field of fields) if (field?.kind === "asset" && field.reverse !== void 0) backs.add(field.reverse);
19760
+ }
19761
+ return backs;
19762
+ }
19763
+ /**
19764
+ * An asset field create, with its field back on Asset as the partner the
19765
+ * same create makes, when the config lists it.
19766
+ */
19767
+ function withFieldBack(change, to) {
19768
+ if (change.action !== "create" || change.resource !== "field" || change.field.kind !== "asset" || change.field.reverse === void 0) return change;
19769
+ const back = to.asset?.fields[change.field.reverse];
19770
+ return back?.kind === "referenceTwoWay" ? {
19771
+ ...change,
19772
+ partner: back
19773
+ } : change;
19774
+ }
19775
+ /**
19776
+ * What the Asset diff does with each field back, by `sideKey`. A field
19777
+ * back goes with its asset field: it changes in place while that field
19778
+ * stays, with the same `list`, and the live field back is there under the
19779
+ * apiId the config gives it (renames applied), with the same `to` and
19780
+ * `reverse`. Otherwise the asset field's create makes it. Its deletes go
19781
+ * with the asset field too, which `fieldsBackDeletedWith` takes out of
19782
+ * live.
19783
+ */
19784
+ function pairFieldsBack(renamed, to) {
19785
+ const inPlace = /* @__PURE__ */ new Set();
19786
+ const createdWithPartner = /* @__PURE__ */ new Set();
19787
+ const liveParents = new Map(fieldParents(renamed).map((parent) => [parent.apiId, parent]));
19788
+ for (const parent of fieldParents(to)) for (const field of Object.values(parent.fields)) {
19789
+ if (field.kind !== "asset" || field.reverse === void 0) continue;
19790
+ const back = to.asset?.fields[field.reverse];
19791
+ if (back?.kind !== "referenceTwoWay") continue;
19792
+ const live = liveParents.get(parent.apiId)?.fields[field.apiId];
19793
+ const liveBack = renamed.asset?.fields[field.reverse];
19794
+ const key = sideKey("Asset", field.reverse);
19795
+ if (live?.kind === "asset" && live.list === field.list && live.reverse === field.reverse && liveBack?.kind === "referenceTwoWay" && liveBack.to === back.to && liveBack.reverse === back.reverse) inPlace.add(key);
19796
+ else createdWithPartner.add(key);
19797
+ }
19798
+ return {
19799
+ ...NO_PAIRS,
19800
+ inPlace,
19801
+ createdWithPartner
19802
+ };
19803
+ }
19804
+ /**
18032
19805
  * `from` with every rename intent applied, and the renames as changes:
18033
19806
  * locales, enumerations, their values, taxonomies, their nodes,
18034
19807
  * components, models, then fields. Values, nodes and fields find their
@@ -18283,7 +20056,7 @@ function applyEnumerationValueRenames(from, intents) {
18283
20056
  renames
18284
20057
  };
18285
20058
  }
18286
- /** Every model and component with `map` applied to each of its fields. */
20059
+ /** Every model, component and Asset with `map` applied to each of its fields. */
18287
20060
  function mapFields(from, map) {
18288
20061
  const mapParent = (parent) => ({
18289
20062
  ...parent,
@@ -18291,7 +20064,8 @@ function mapFields(from, map) {
18291
20064
  });
18292
20065
  return {
18293
20066
  models: from.models.map(mapParent),
18294
- components: from.components.map(mapParent)
20067
+ components: from.components.map(mapParent),
20068
+ ...from.asset && { asset: mapParent(from.asset) }
18295
20069
  };
18296
20070
  }
18297
20071
  /**
@@ -18331,7 +20105,7 @@ function applyComponentRenames(from, intents) {
18331
20105
  return {
18332
20106
  renamed: {
18333
20107
  ...from,
18334
- models: parents.models,
20108
+ ...parents,
18335
20109
  components
18336
20110
  },
18337
20111
  renames
@@ -18388,7 +20162,7 @@ function applyModelRenames(from, intents) {
18388
20162
  return {
18389
20163
  renamed: {
18390
20164
  ...from,
18391
- components: parents.components,
20165
+ ...parents,
18392
20166
  models
18393
20167
  },
18394
20168
  renames
@@ -18451,7 +20225,8 @@ function applyFieldRenames(from, intents) {
18451
20225
  const renamed = {
18452
20226
  ...from,
18453
20227
  models: from.models.map(renameFields),
18454
- components: from.components.map(renameFields)
20228
+ components: from.components.map(renameFields),
20229
+ ...from.asset && { asset: renameFields(from.asset) }
18455
20230
  };
18456
20231
  const parents = mapFields(renamed, (field) => {
18457
20232
  switch (field.kind) {
@@ -18471,6 +20246,14 @@ function applyFieldRenames(from, intents) {
18471
20246
  reverse: apiId
18472
20247
  } : field;
18473
20248
  }
20249
+ case "asset": {
20250
+ if (field.reverse === void 0) return field;
20251
+ const apiId = renamedSides.get(sideKey("Asset", field.reverse));
20252
+ return apiId ? {
20253
+ ...field,
20254
+ reverse: apiId
20255
+ } : field;
20256
+ }
18474
20257
  default: return field;
18475
20258
  }
18476
20259
  });
@@ -18586,6 +20369,57 @@ function diffTaxonomies(from, to) {
18586
20369
  return changes;
18587
20370
  }
18588
20371
  /**
20372
+ * Sources are matched by prefix, which never changes: a source `to` names
20373
+ * by another prefix is another source. `recreates` are the deletes of the
20374
+ * sources created again with another type or introspection URL, which run
20375
+ * before their creates; their fields are created again too. The other
20376
+ * deletes wait for the field updates, which may move a field off the
20377
+ * source first.
20378
+ */
20379
+ function diffRemoteSources(from, to) {
20380
+ const fromSources = new Map(from.remoteSources.map((source) => [source.prefix, source]));
20381
+ const toPrefixes = new Set(to.remoteSources.map((source) => source.prefix));
20382
+ const changes = {
20383
+ deletes: from.remoteSources.filter((source) => !toPrefixes.has(source.prefix)).map((source) => ({
20384
+ action: "delete",
20385
+ resource: "remoteSource",
20386
+ prefix: source.prefix
20387
+ })),
20388
+ recreates: [],
20389
+ updates: [],
20390
+ creates: []
20391
+ };
20392
+ for (const source of to.remoteSources) {
20393
+ const fromSource = fromSources.get(source.prefix);
20394
+ if (fromSource && recreatesRemoteSource(fromSource, source)) changes.recreates.push({
20395
+ action: "delete",
20396
+ resource: "remoteSource",
20397
+ prefix: source.prefix
20398
+ });
20399
+ if (!fromSource || recreatesRemoteSource(fromSource, source)) {
20400
+ changes.creates.push({
20401
+ action: "create",
20402
+ resource: "remoteSource",
20403
+ remoteSource: source
20404
+ });
20405
+ continue;
20406
+ }
20407
+ const attributes = diffRemoteSource(fromSource, source);
20408
+ if (Object.keys(attributes).length > 0) changes.updates.push({
20409
+ action: "update",
20410
+ resource: "remoteSource",
20411
+ prefix: source.prefix,
20412
+ type: source.type,
20413
+ displayName: source.displayName,
20414
+ headers: source.headers,
20415
+ introspectionHeaders: source.type === "GRAPHQL" ? source.introspectionHeaders : null,
20416
+ oAuth: source.oAuth,
20417
+ changes: attributes
20418
+ });
20419
+ }
20420
+ return changes;
20421
+ }
20422
+ /**
18589
20423
  * The fields of deleted components that use another deleted component. A
18590
20424
  * component delete takes its own fields with it, but Hygraph refuses it
18591
20425
  * while a field elsewhere uses the component; deleting these first lets
@@ -18820,6 +20654,39 @@ function validateTaxonomyIntents(from, intents) {
18820
20654
  return validations;
18821
20655
  }
18822
20656
  /**
20657
+ * What a source `from` has keeps, as Studio keeps it: its kind, its OAuth,
20658
+ * and on a GraphQL source its introspection URL. The server refuses a new
20659
+ * introspection URL on `updateGraphQLRemoteSource` ("Switching
20660
+ * Introspection URLs is not implemented yet!"); a kind and OAuth it would
20661
+ * change, but Studio locks the kind once the source exists and has no way
20662
+ * to remove OAuth, and a source without its OAuth fails every request.
20663
+ * Deleting the source first fails while a remote field uses it. A source
20664
+ * whose type changes is created again, so none of this applies to it.
20665
+ */
20666
+ function validateRemoteSourceChanges({ from, to }) {
20667
+ const live = new Map(from.remoteSources.map((source) => [source.prefix, source]));
20668
+ return to.remoteSources.flatMap((source) => {
20669
+ const old = live.get(source.prefix);
20670
+ if (old?.type !== source.type) return [];
20671
+ const refuse = (code, attribute, message) => ({
20672
+ code,
20673
+ severity: "error",
20674
+ path: [
20675
+ "remoteSources",
20676
+ source.prefix,
20677
+ attribute
20678
+ ],
20679
+ message,
20680
+ fix: fixes[code]
20681
+ });
20682
+ const validations = [];
20683
+ if (old.kind !== source.kind) validations.push(refuse("change.remoteSourceKindChanged", "kind", messages["change.remoteSourceKindChanged"](source.prefix, old.kind, source.kind)));
20684
+ if (old.oAuth !== null && source.oAuth === null) validations.push(refuse("change.remoteSourceOAuthRemoved", "oAuth", messages["change.remoteSourceOAuthRemoved"](source.prefix)));
20685
+ if (old.type === "GRAPHQL" && source.type === "GRAPHQL" && old.introspectionUrl !== source.introspectionUrl) validations.push(refuse("change.remoteSourceIntrospectionUrl", "introspectionUrl", messages["change.remoteSourceIntrospectionUrl"](source.prefix)));
20686
+ return validations;
20687
+ });
20688
+ }
20689
+ /**
18823
20690
  * Whether every unsupported field in the config is live with the same
18824
20691
  * type. The plan cannot create one, and one of another type is another
18825
20692
  * field, so either stops the plan. A side of an unsupported two-way pair
@@ -18829,13 +20696,24 @@ function validateTaxonomyIntents(from, intents) {
18829
20696
  */
18830
20697
  function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], unsupportedUnions = [] }) {
18831
20698
  const validations = [];
18832
- const parents = [...to.models.map((parent) => ({
18833
- kind: "model",
18834
- parent
18835
- })), ...to.components.map((parent) => ({
18836
- kind: "component",
18837
- parent
18838
- }))];
20699
+ const parents = [
20700
+ ...to.models.map((parent) => ({
20701
+ kind: "model",
20702
+ parent
20703
+ })),
20704
+ ...to.asset ? [{
20705
+ kind: "model",
20706
+ parent: to.asset
20707
+ }] : [],
20708
+ ...to.query ? [{
20709
+ kind: "model",
20710
+ parent: to.query
20711
+ }] : [],
20712
+ ...to.components.map((parent) => ({
20713
+ kind: "component",
20714
+ parent
20715
+ }))
20716
+ ];
18839
20717
  for (const { kind, parent } of parents) {
18840
20718
  const fields = liveParent(from, intents, parent.apiId)?.fields ?? {};
18841
20719
  for (const field of Object.values(parent.fields).toSorted(byApiId$1)) {
@@ -18871,10 +20749,11 @@ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], u
18871
20749
  const renameParent = followModelRenames(from, intents);
18872
20750
  const kept = (side) => {
18873
20751
  const { parent: model, apiId } = renameParent(side);
20752
+ const parent = model === "Asset" ? to.asset : to.models.find((each) => each.apiId === model);
18874
20753
  return {
18875
20754
  model,
18876
20755
  apiId,
18877
- unsupported: to.models.find((each) => each.apiId === model)?.fields[apiId]?.kind === "unsupported"
20756
+ unsupported: model === "Asset" && to.asset === void 0 || parent?.fields[apiId]?.kind === "unsupported"
18878
20757
  };
18879
20758
  };
18880
20759
  for (const [a, b] of unsupportedPairs) for (const [side, partner] of [[kept(a), kept(b)], [kept(b), kept(a)]]) if (side.unsupported && !partner.unsupported) {
@@ -18929,6 +20808,59 @@ function validateUnsupportedFields({ from, to, intents, unsupportedPairs = [], u
18929
20808
  return validations;
18930
20809
  }
18931
20810
  /**
20811
+ * Whether each asset field that is live keeps the field back live has for
20812
+ * it. The config pairs them already: the field back on Asset is a two-way
20813
+ * reference to its asset field. A field back cannot be deleted on its own,
20814
+ * as that deletes the relation, so naming another one is refused, unless
20815
+ * the field back is renamed to it with `renamedFrom`.
20816
+ */
20817
+ function validateAssetFieldsBack({ from, to, intents }) {
20818
+ if (!to.asset) return [];
20819
+ const validations = [];
20820
+ for (const { parent, field, reverse, live } of pairAssetFields(from, to, intents)) {
20821
+ const renamed = intents.fieldRenames.some((rename) => rename.parent === "Asset" && rename.apiId === reverse && rename.renamedFrom === live);
20822
+ if (live === void 0 || live === reverse || renamed) continue;
20823
+ const code = "field.assetReverseFieldChanged";
20824
+ validations.push({
20825
+ code,
20826
+ severity: "error",
20827
+ path: [
20828
+ "models",
20829
+ parent,
20830
+ "fields",
20831
+ field,
20832
+ "reverse"
20833
+ ],
20834
+ message: messages[code](parent, field, live, reverse),
20835
+ fix: fixes[code](parent, field, live)
20836
+ });
20837
+ }
20838
+ return validations;
20839
+ }
20840
+ /**
20841
+ * Each asset field on a model or on Asset in the config, with the field
20842
+ * back it names and the one live names for it, if it is live.
20843
+ */
20844
+ function pairAssetFields(from, to, intents) {
20845
+ const pairs = [];
20846
+ for (const parent of fieldParents(to)) {
20847
+ const liveFields = liveParent(from, intents, parent.apiId)?.fields ?? {};
20848
+ for (const field of Object.values(parent.fields).toSorted(byApiId$1)) {
20849
+ if (field.kind !== "asset" || field.reverse === void 0) continue;
20850
+ const rename = intents.fieldRenames.find((each) => each.parent === parent.apiId && each.apiId === field.apiId);
20851
+ const liveField = liveFields[field.apiId] ?? (rename ? liveFields[rename.renamedFrom] : void 0);
20852
+ const live = liveField?.kind === "asset" ? liveField.reverse : void 0;
20853
+ pairs.push({
20854
+ parent: parent.apiId,
20855
+ field: field.apiId,
20856
+ reverse: field.reverse,
20857
+ live
20858
+ });
20859
+ }
20860
+ }
20861
+ return pairs;
20862
+ }
20863
+ /**
18932
20864
  * The live enumeration for a config apiId. If live has no enumeration under
18933
20865
  * that apiId and the config renames it, returns the one under its old apiId.
18934
20866
  */
@@ -18939,12 +20871,23 @@ function liveEnumeration(from, intents, enumeration) {
18939
20871
  return enumerations.get(enumeration);
18940
20872
  }
18941
20873
  /**
18942
- * The live model or component for a config apiId; the two share their
18943
- * apiIds. If live has none under that apiId and the config renames it,
20874
+ * The live model, component, Asset or Query for a config apiId; they share
20875
+ * their apiIds. Asset and Query are always live, with no fields of yours
20876
+ * when `from` leaves them out. If live has none under that apiId and the config renames it,
18944
20877
  * returns the one under its old apiId.
18945
20878
  */
18946
20879
  function liveParent(from, intents, parent) {
18947
- const parents = new Map([...from.models, ...from.components].map((each) => [each.apiId, each]));
20880
+ const parents = new Map([
20881
+ ...[...from.models, ...from.components].map((each) => [each.apiId, each]),
20882
+ ["Asset", from.asset ?? {
20883
+ apiId: "Asset",
20884
+ fields: {}
20885
+ }],
20886
+ ["QueryModel", from.query ?? {
20887
+ apiId: "QueryModel",
20888
+ fields: {}
20889
+ }]
20890
+ ]);
18948
20891
  const rename = intents.renames.find((each) => (each.resource === "model" || each.resource === "component") && each.apiId === parent);
18949
20892
  if (rename && !parents.has(parent)) return parents.get(rename.renamedFrom);
18950
20893
  return parents.get(parent);
@@ -19061,7 +21004,7 @@ function validateChangeSet({ from, changes }) {
19061
21004
  validateComponentsUsed(change);
19062
21005
  validateModelReferenced(change);
19063
21006
  validateModelsEmbedded(change);
19064
- if (models.has(change.parent) || components.has(change.parent)) break;
21007
+ if (change.parent === "Asset" || change.parent === "QueryModel" || models.has(change.parent) || components.has(change.parent)) break;
19065
21008
  const onComponent = componentApiIds.has(change.parent);
19066
21009
  report(onComponent ? "change.componentMissing" : "change.modelMissing", [
19067
21010
  onComponent ? "components" : "models",
@@ -19363,6 +21306,22 @@ const assetFieldSchema = strictObject({
19363
21306
  required: boolean(),
19364
21307
  visibility: fieldVisibilitySchema,
19365
21308
  visibilityCondition: visibilityConditionSchema.nullable(),
21309
+ reverse: string$1().nullable(),
21310
+ renamedFrom: string$1().nullable()
21311
+ });
21312
+ //#endregion
21313
+ //#region src/define/fields/assetReverseField.zod.ts
21314
+ const assetReverseFieldSchema = strictObject({
21315
+ __typename: literal("AssetReverseField"),
21316
+ apiId: string$1(),
21317
+ displayName: string$1(),
21318
+ description: string$1().nullable(),
21319
+ to: custom((value) => typeof value === "function"),
21320
+ reverse: string$1(),
21321
+ list: literal(true),
21322
+ required: literal(false),
21323
+ visibility: fieldVisibilitySchema,
21324
+ visibilityCondition: _null(),
19366
21325
  renamedFrom: string$1().nullable()
19367
21326
  });
19368
21327
  //#endregion
@@ -19605,6 +21564,75 @@ const referenceUnionMemberFieldSchema = strictObject({
19605
21564
  renamedFrom: string$1().nullable()
19606
21565
  });
19607
21566
  //#endregion
21567
+ //#region src/define/resources/remoteSource.zod.ts
21568
+ const headersSchema$1 = record(string$1(), union([
21569
+ string$1(),
21570
+ array(union([string$1(), _undefined()])),
21571
+ _undefined()
21572
+ ]));
21573
+ const attributes = {
21574
+ prefix: string$1(),
21575
+ displayName: string$1(),
21576
+ description: string$1().nullable(),
21577
+ url: string$1(),
21578
+ headers: headersSchema$1,
21579
+ debugEnabled: boolean(),
21580
+ kind: _enum([
21581
+ "CommerceLayer",
21582
+ "CommerceTools",
21583
+ "Custom"
21584
+ ]),
21585
+ oAuth: strictObject({
21586
+ clientId: string$1(),
21587
+ clientSecret: string$1().nullable(),
21588
+ scopes: array(string$1()),
21589
+ authorizationUrl: string$1()
21590
+ }).nullable(),
21591
+ remoteTypeDefinitions: string$1().nullable()
21592
+ };
21593
+ const remoteSourceSchema = discriminatedUnion("__typename", [strictObject({
21594
+ __typename: literal("GraphQLRemoteSource"),
21595
+ ...attributes,
21596
+ introspectionMethod: _enum(["GET", "POST"]),
21597
+ introspectionUrl: string$1().nullable(),
21598
+ introspectionHeaders: headersSchema$1
21599
+ }), strictObject({
21600
+ __typename: literal("RESTRemoteSource"),
21601
+ ...attributes
21602
+ })]);
21603
+ //#endregion
21604
+ //#region src/define/fields/remote.zod.ts
21605
+ const headersSchema = record(string$1(), union([
21606
+ string$1(),
21607
+ array(union([string$1(), _undefined()])),
21608
+ _undefined()
21609
+ ]));
21610
+ const remoteFieldSchema = strictObject({
21611
+ __typename: literal("RemoteField"),
21612
+ apiId: string$1(),
21613
+ displayName: string$1(),
21614
+ description: string$1().nullable(),
21615
+ source: remoteSourceSchema,
21616
+ returnType: string$1(),
21617
+ method: _enum(["GET", "POST"]),
21618
+ query: string$1().nullable(),
21619
+ path: string$1().nullable(),
21620
+ args: array(strictObject({
21621
+ apiId: string$1(),
21622
+ type: string$1(),
21623
+ required: boolean(),
21624
+ list: boolean()
21625
+ })),
21626
+ headers: headersSchema,
21627
+ forwardClientHeaders: boolean(),
21628
+ cacheTTLSeconds: number(),
21629
+ list: boolean(),
21630
+ required: boolean(),
21631
+ visibility: fieldVisibilitySchema,
21632
+ visibilityCondition: _null(),
21633
+ renamedFrom: string$1().nullable()
21634
+ });
21635
+ //#endregion
19608
21636
  //#region src/define/fields/string.zod.ts
19609
21637
  const regexRuleSchema = strictObject({
19610
21638
  regex: string$1(),
@@ -19707,6 +21735,7 @@ const fieldSchema = discriminatedUnion("__typename", [
19707
21735
  migrationValue: taxonomyValueSchema,
19708
21736
  renamedFrom: string$1().nullable()
19709
21737
  }),
21738
+ remoteFieldSchema,
19710
21739
  jsonFieldSchema,
19711
21740
  richTextFieldSchema,
19712
21741
  colorFieldSchema,
@@ -19722,9 +21751,24 @@ const fieldSchema = discriminatedUnion("__typename", [
19722
21751
  referenceTwoWayFieldSchema,
19723
21752
  referenceUnionFieldSchema,
19724
21753
  referenceUnionMemberFieldSchema,
19725
- assetFieldSchema
21754
+ assetFieldSchema,
21755
+ assetReverseFieldSchema
19726
21756
  ]);
19727
21757
  //#endregion
21758
+ //#region src/define/system/asset.zod.ts
21759
+ const systemAssetSchema = strictObject({
21760
+ __typename: literal("SystemAsset"),
21761
+ apiId: literal("Asset"),
21762
+ fields: array(fieldSchema)
21763
+ });
21764
+ //#endregion
21765
+ //#region src/define/system/query.zod.ts
21766
+ const systemQuerySchema = strictObject({
21767
+ __typename: literal("SystemQuery"),
21768
+ apiId: literal("QueryModel"),
21769
+ fields: array(fieldSchema)
21770
+ });
21771
+ //#endregion
19728
21772
  //#region src/define/resources/component.zod.ts
19729
21773
  const componentSchema = strictObject({
19730
21774
  __typename: literal("Component"),
@@ -19764,8 +21808,10 @@ const environmentSchema = strictObject({
19764
21808
  stages: array(union([stageSchema, systemStageSchema])),
19765
21809
  enumerations: array(enumerationSchema),
19766
21810
  taxonomies: array(taxonomySchema),
21811
+ remoteSources: array(remoteSourceSchema),
19767
21812
  components: array(componentSchema),
19768
- models: array(modelSchema)
21813
+ models: array(modelSchema),
21814
+ systemModels: array(union([systemAssetSchema, systemQuerySchema]))
19769
21815
  });
19770
21816
  //#endregion
19771
21817
  //#region src/define/resources/target.zod.ts
@@ -19893,7 +21939,7 @@ function selectTargets(targets, names) {
19893
21939
  /** What only plan can find out is wrong. The command prints it and exits 1. */
19894
21940
  var PlanFailure = class extends Failure {};
19895
21941
  function registerPlan(program) {
19896
- program.command("plan").description("show what would change against the target environments").argument("[config]", "path to the config", "hygraph.config.ts").option("-t, --target <name>", "plan only this target (repeatable, default: every target)", collect, []).option("--out <file>", `write the plan artifact to a file (${TARGET_PLACEHOLDER} stands for the target name)`).option("--no-color", "print without colours").action(async function(config, options) {
21942
+ program.command("plan").description("show what would change against the target environments").argument("[config]", "path to the config", "hygraph.config.ts").option("-t, --target <name>", "plan only this target (repeatable, default: every target)", collect, []).option("--out <file>", `write the plan artifact to a file (${TARGET_PLACEHOLDER} stands for the target name)`).option("--rotate-secret <prefix>", "send the remote source's OAuth secret again, after it changed (repeatable)", collect, []).option("--no-color", "print without colours").action(async function(config, options) {
19897
21943
  const output = this.configureOutput();
19898
21944
  const write = (text) => output.writeOut?.(text);
19899
21945
  const writeErr = (text) => output.writeErr?.(text);
@@ -19910,6 +21956,7 @@ function registerPlan(program) {
19910
21956
  ["hygraph plan", "see what would change on every target"],
19911
21957
  ["hygraph plan --target uk", "plan one target of several"],
19912
21958
  ["hygraph plan --out plan.json", "save the plan so it can be reviewed"],
21959
+ ["hygraph plan --rotate-secret Shop", "send Shop's new OAuth secret, which Hygraph cannot tell changed"],
19913
21960
  [`hygraph plan --out plans/${TARGET_PLACEHOLDER}.json`, "one artifact per target"],
19914
21961
  ["hygraph plan brands/kaffa.ts", "use a config other than the default"],
19915
21962
  ["hygraph plan --no-color", "prints plan without text colors"]
@@ -19924,11 +21971,13 @@ async function plan(config, options, write, writeErr) {
19924
21971
  const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported);
19925
21972
  const targets = await loadTargets(config, options.target, PlanFailure);
19926
21973
  const out = options.out === void 0 ? void 0 : pathsForTargets(options.out, targets, PlanFailure);
21974
+ const rotateSecrets = options.rotateSecret;
19927
21975
  if (targets.length === 1) {
19928
21976
  await planTarget(targets[0], {
19929
21977
  config,
19930
21978
  colors,
19931
21979
  out,
21980
+ rotateSecrets,
19932
21981
  write
19933
21982
  });
19934
21983
  return;
@@ -19941,6 +21990,7 @@ async function plan(config, options, write, writeErr) {
19941
21990
  config,
19942
21991
  colors,
19943
21992
  out,
21993
+ rotateSecrets,
19944
21994
  write
19945
21995
  });
19946
21996
  outcomes.push({
@@ -19962,8 +22012,8 @@ async function plan(config, options, write, writeErr) {
19962
22012
  const failed = outcomes.filter(({ ok }) => !ok).length;
19963
22013
  if (failed > 0) throw new PlanFailure(`${failed} of ${targets.length} targets could not be planned`);
19964
22014
  }
19965
- async function planTarget(target, { config, colors, out, write }) {
19966
- const { plan, warnings } = await computePlan(target);
22015
+ async function planTarget(target, { config, colors, out, rotateSecrets, write }) {
22016
+ const { plan, warnings } = await computePlan(target, void 0, { rotateSecrets });
19967
22017
  write(renderPlan(plan, {
19968
22018
  name: target.name,
19969
22019
  config,
@@ -19982,14 +22032,20 @@ async function planTarget(target, { config, colors, out, write }) {
19982
22032
  * the renames and the unsupported fields against it, diff the two, validate the change set, build the
19983
22033
  * plan. Stops at the first phase with errors and reports every error of that
19984
22034
  * phase. Warnings do not stop it; they come back beside the plan. The environment id comes along for `apply`, which addresses the
19985
- * batch by it.
22035
+ * batch by it, and so do the config's header values and OAuth secrets,
22036
+ * which the plan holds as hashes. `rotateSecrets` names the sources whose
22037
+ * secret it sends although nothing else asks for it.
19986
22038
  */
19987
- async function computePlan(target, fetch) {
22039
+ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
19988
22040
  const configValidations = validateEnvironment(target.apply);
19989
22041
  maybeRefuse(configValidations, "the config has");
19990
22042
  const desired = convertEnvironmentToIR(target.apply);
19991
22043
  const intents = collectIntents(target.apply);
19992
22044
  const { environmentId, environment: live, unsupportedPairs, unsupportedUnions } = await readLiveEnvironment(target, fetch);
22045
+ maybeRefuse(validateRemoteSourceChanges({
22046
+ from: live,
22047
+ to: desired
22048
+ }), `the remote sources cannot be planned against ${target.environment},`);
19993
22049
  maybeRefuse(validateIntents({
19994
22050
  from: live,
19995
22051
  to: desired,
@@ -20002,7 +22058,12 @@ async function computePlan(target, fetch) {
20002
22058
  unsupportedPairs,
20003
22059
  unsupportedUnions
20004
22060
  }), `the unsupported fields do not match ${target.environment},`);
20005
- const changes = diffEnvironment({
22061
+ maybeRefuse(validateAssetFieldsBack({
22062
+ from: live,
22063
+ to: desired,
22064
+ intents
22065
+ }), `the fields back on Asset do not match the asset fields,`);
22066
+ const diffed = diffEnvironment({
20006
22067
  from: live,
20007
22068
  to: desired,
20008
22069
  intents,
@@ -20011,8 +22072,13 @@ async function computePlan(target, fetch) {
20011
22072
  });
20012
22073
  maybeRefuse(validateChangeSet({
20013
22074
  from: live,
20014
- changes
22075
+ changes: diffed
20015
22076
  }), `the changes cannot be applied to ${target.environment},`);
22077
+ const secrets = oAuthSecrets(target.apply);
22078
+ const attached = attachOAuthSecrets(diffed, secrets);
22079
+ const { changes, refusals } = rotateOAuthSecrets(attached.changes, desired, secrets, rotateSecrets);
22080
+ maybeRefuse(refusals, "the secrets cannot be rotated,");
22081
+ const { warnings } = attached;
20016
22082
  return {
20017
22083
  plan: buildPlan({
20018
22084
  target,
@@ -20022,7 +22088,8 @@ async function computePlan(target, fetch) {
20022
22088
  changes
20023
22089
  }),
20024
22090
  environmentId,
20025
- warnings: configValidations.filter((validation) => validation.severity === "warning")
22091
+ secretValues: secretValues(desired, secrets),
22092
+ warnings: [...configValidations.filter((validation) => validation.severity === "warning"), ...warnings]
20026
22093
  };
20027
22094
  }
20028
22095
  /** Below the plan: what is worth a look but does not stop it. */
@@ -20052,7 +22119,7 @@ var ApplyFailure = class extends Failure {};
20052
22119
  /** A refusal already rendered for the terminal. Printed as is, exit 1. */
20053
22120
  var ApplyRefusal = class extends Failure {};
20054
22121
  function registerApply(program) {
20055
- program.command("apply").description("execute the plan as one migration per target").argument("[config]", "path to the config", "hygraph.config.ts").option("-t, --target <name>", "apply only this target (repeatable, default: every target)", collect, []).option("--plan <file>", `apply exactly this plan artifact (${TARGET_PLACEHOLDER} stands for the target name)`).option("--prune", "acknowledge that this plan destroys data").option("-y, --yes", "apply without asking for confirmation").option("--no-color", "print without colours").action(async function(config, options) {
22122
+ program.command("apply").description("execute the plan as one migration per target").argument("[config]", "path to the config", "hygraph.config.ts").option("-t, --target <name>", "apply only this target (repeatable, default: every target)", collect, []).option("--plan <file>", `apply exactly this plan artifact (${TARGET_PLACEHOLDER} stands for the target name)`).option("--rotate-secret <prefix>", "send the remote source's OAuth secret again, after it changed (repeatable; not with --plan)", collect, []).option("--prune", "acknowledge that this plan destroys data").option("-y, --yes", "apply without asking for confirmation").option("--no-color", "print without colours").action(async function(config, options) {
20056
22123
  const output = this.configureOutput();
20057
22124
  const write = (text) => output.writeOut?.(text);
20058
22125
  const writeErr = (text) => output.writeErr?.(text);
@@ -20075,7 +22142,8 @@ function registerApply(program) {
20075
22142
  ["hygraph apply", "re-plan and apply every target in one step"],
20076
22143
  ["hygraph apply --target uk --target de", "apply two targets of several"],
20077
22144
  [`hygraph apply --plan plans/${TARGET_PLACEHOLDER}.json`, "apply each target's reviewed artifact"],
20078
- ["hygraph apply --yes", "do not ask for confirmation"]
22145
+ ["hygraph apply --yes", "do not ask for confirmation"],
22146
+ ["hygraph apply --rotate-secret Shop", "send Shop's new OAuth secret, which Hygraph cannot tell changed"]
20079
22147
  ]));
20080
22148
  }
20081
22149
  /**
@@ -20086,6 +22154,7 @@ function registerApply(program) {
20086
22154
  * at the end.
20087
22155
  */
20088
22156
  async function apply(config, options, write, writeErr) {
22157
+ if (options.plan !== void 0 && options.rotateSecret.length > 0) throw new ApplyFailure("--rotate-secret goes with plan, not with --plan: a reviewed plan.json already says which secrets it sends. Plan again with --rotate-secret, then apply that plan.");
20089
22158
  const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported);
20090
22159
  const targets = await loadTargets(config, options.target, ApplyFailure);
20091
22160
  const context = {
@@ -20162,11 +22231,12 @@ async function apply(config, options, write, writeErr) {
20162
22231
  * plan. Hands back nothing when there is nothing to change.
20163
22232
  */
20164
22233
  async function prepare(target, { config, options, colors, planFiles, write }) {
20165
- const { plan: fresh, environmentId } = await computePlan(target);
22234
+ const file = planFiles?.get(target.name);
22235
+ const artifact = file === void 0 ? void 0 : readPlanFile(file);
22236
+ if (artifact !== void 0) refuseUnsendableOAuthSecrets(unmaskSecrets(artifact.changes, oAuthSecretValues(oAuthSecrets(target.apply))));
22237
+ const { plan: fresh, environmentId, secretValues } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
20166
22238
  let plan = fresh;
20167
- if (planFiles !== void 0) {
20168
- const file = planFiles.get(target.name);
20169
- const artifact = readPlanFile(file);
22239
+ if (file !== void 0 && artifact !== void 0) {
20170
22240
  const refusals = verifyPlan(artifact, fresh);
20171
22241
  if (refusals.length > 0) throw new ApplyFailure(renderRefusals(file, refusals));
20172
22242
  plan = artifact;
@@ -20182,13 +22252,25 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
20182
22252
  }));
20183
22253
  if (plan.changes.length === 0) return;
20184
22254
  if (plan.summary.destructive > 0 && options.prune !== true) throw new ApplyRefusal(renderDestructiveRefusal(plan.summary, colors));
22255
+ refuseUnsendableOAuthSecrets(unmaskSecrets(plan.changes, secretValues));
20185
22256
  return {
20186
22257
  target,
20187
22258
  plan,
20188
- environmentId
22259
+ environmentId,
22260
+ secretValues
20189
22261
  };
20190
22262
  }
20191
22263
  /**
22264
+ * A plan that needs an OAuth secret the config did not have, or had
22265
+ * another one when it was planned, would send nothing or a hash. Hygraph
22266
+ * would fail to sign in, so apply stops before it submits.
22267
+ */
22268
+ function refuseUnsendableOAuthSecrets(changes) {
22269
+ const unsendable = unsendableOAuthSecrets(changes);
22270
+ if (unsendable.length === 0) return;
22271
+ throw new ApplyFailure(unsendable.map(({ prefix, reason }) => reason === "missing" ? `Remote source "${prefix}" needs its OAuth secret, and the config had none when this was planned. Set the environment variable the config reads oAuth.clientSecret from, then plan again.` : `The OAuth secret of remote source "${prefix}" changed after this was planned. Plan again to send the new one.`).join("\n"));
22272
+ }
22273
+ /**
20192
22274
  * Reads the target's live schema again just before its submit. With
20193
22275
  * several targets, the earlier migrations run between planning and here.
20194
22276
  */
@@ -20198,14 +22280,17 @@ async function verifyLiveUnchanged({ target, plan }, { colors, write }) {
20198
22280
  write(renderCheck("liveFingerprint matches", "environment unchanged since planning", colors));
20199
22281
  }
20200
22282
  /** Submits one target's migration and follows it to its end. */
20201
- async function execute({ target, plan, environmentId }, { colors, write }) {
22283
+ async function execute({ target, plan, environmentId, secretValues }, { colors, write }) {
20202
22284
  const client = createManagementClient({
20203
22285
  endpoint: target.endpoint,
20204
22286
  token: target.token
20205
22287
  });
20206
22288
  const name = migrationName(plan.planHash, /* @__PURE__ */ new Date());
20207
22289
  const started = Date.now();
20208
- const { id } = await submitMigration(client, target, toBatchMigrationInput(plan, {
22290
+ const { id } = await submitMigration(client, target, toBatchMigrationInput({
22291
+ ...plan,
22292
+ changes: unmaskSecrets(plan.changes, secretValues)
22293
+ }, {
20209
22294
  environmentId,
20210
22295
  name
20211
22296
  }));
@@ -20275,6 +22360,10 @@ async function formatSource(source) {
20275
22360
  function string(value) {
20276
22361
  return JSON.stringify(value);
20277
22362
  }
22363
+ /** A template literal, for text that spans lines. Nothing in it is interpolated. */
22364
+ function template(value) {
22365
+ return `\`${value.replaceAll(/[\\`]|\$\{/g, (match) => `\\${match}`)}\``;
22366
+ }
20278
22367
  /**
20279
22368
  * An object literal of code values. It opens with a newline, so oxfmt keeps
20280
22369
  * it expanded, one attribute per line. Entries without a value are left out.
@@ -20283,16 +22372,124 @@ function object(entries) {
20283
22372
  return `{\n${entries.flatMap(([key, code]) => code === void 0 ? [] : [`${key}: ${code},`]).join("\n")}\n}`;
20284
22373
  }
20285
22374
  //#endregion
22375
+ //#region src/export/resources/remoteSource.ts
22376
+ /**
22377
+ * `const <prefix>RemoteSource = define.graphqlRemoteSource({...});` or
22378
+ * `define.restRemoteSource`. A prefix may be a model's apiId too, so the
22379
+ * const takes a suffix. Attributes at their default are left out; the types
22380
+ * print as one SDL document. Every header is read from the environment,
22381
+ * `process.env.SHOP_AUTHORIZATION`, so a token never reaches the
22382
+ * repository, and so is the OAuth secret, which Hygraph never returns.
22383
+ */
22384
+ function printRemoteSource(source) {
22385
+ const builder = source.type === "GRAPHQL" ? "graphqlRemoteSource" : "restRemoteSource";
22386
+ return `const ${remoteSourceConstName(source)} = define.${builder}(${object([
22387
+ ["prefix", string(source.prefix)],
22388
+ ["displayName", string(source.displayName)],
22389
+ ["description", source.description === null ? void 0 : string(source.description)],
22390
+ ["url", string(source.url)],
22391
+ ["kind", source.kind === "Custom" ? void 0 : string(source.kind)],
22392
+ ["oAuth", source.oAuth === null ? void 0 : printOAuth(source.prefix, source.oAuth)],
22393
+ ["debugEnabled", source.debugEnabled ? "true" : void 0],
22394
+ ["headers", printHeaders(source.prefix, "", source.headers)],
22395
+ ...source.type === "GRAPHQL" ? [
22396
+ ["introspectionMethod", string(source.introspectionMethod)],
22397
+ ["introspectionUrl", source.introspectionUrl === null ? void 0 : string(source.introspectionUrl)],
22398
+ ["introspectionHeaders", printHeaders(source.prefix, "INTROSPECTION_", source.introspectionHeaders)]
22399
+ ] : [],
22400
+ ["remoteTypeDefinitions", source.typeDefinitions.length === 0 ? void 0 : template(source.typeDefinitions.map((type) => type.sdl).join("\n\n"))]
22401
+ ])});`;
22402
+ }
22403
+ /**
22404
+ * The secret is read from `oAuthSecretEnvName`'s variable. Live cannot tell
22405
+ * whether a CommerceLayer source has one, so it is read for both kinds; an
22406
+ * unset variable sends none.
22407
+ */
22408
+ function printOAuth(prefix, oAuth) {
22409
+ return object([
22410
+ ["clientId", string(oAuth.clientId)],
22411
+ ["clientSecret", `process.env.${oAuthSecretEnvName(prefix)}`],
22412
+ ["scopes", oAuth.scopes.length === 0 ? void 0 : `[${oAuth.scopes.map(string).join(", ")}]`],
22413
+ ["authorizationUrl", string(oAuth.authorizationUrl)]
22414
+ ]);
22415
+ }
22416
+ /** The variables the printed config reads the OAuth secrets from, in print order. */
22417
+ function oAuthSecretEnvNames(environment) {
22418
+ return environment.remoteSources.filter((source) => source.oAuth !== null).map((source) => oAuthSecretEnvName(source.prefix));
22419
+ }
22420
+ /** The variable the printed config reads a source's OAuth secret from: `SHOP_OAUTH_CLIENT_SECRET`. */
22421
+ function oAuthSecretEnvName(prefix) {
22422
+ return `${prefix}_OAUTH_CLIENT_SECRET`.replaceAll(/[^A-Za-z0-9]+/g, "_").toUpperCase();
22423
+ }
22424
+ /** The name of the const `printRemoteSource` declares. */
22425
+ function remoteSourceConstName(source) {
22426
+ return `${source.prefix}RemoteSource`;
22427
+ }
22428
+ /**
22429
+ * Every header value is a read of the variable `headerEnvNames` names,
22430
+ * never the value: export cannot tell a token from any other value. A
22431
+ * header with one value reads one variable, as the config takes it.
22432
+ */
22433
+ function printHeaders(prefix, scope, headers) {
22434
+ if (headers === null) return;
22435
+ return object(Object.entries(headers).map(([name, values]) => {
22436
+ const reads = headerEnvNames(prefix, scope, name, values).map((env) => `process.env.${env}`);
22437
+ return [string(name), reads.length === 1 ? reads[0] : `[${reads.join(", ")}]`];
22438
+ }));
22439
+ }
22440
+ /**
22441
+ * The environment variables a header's values are read from, one per
22442
+ * value, numbered when there are more: `SHOP_AUTHORIZATION`,
22443
+ * `SHOP_X_API_KEY_1`.
22444
+ */
22445
+ function headerEnvNames(prefix, scope, header, values) {
22446
+ const base = `${prefix}_${scope}${header}`.replaceAll(/[^A-Za-z0-9]+/g, "_").toUpperCase();
22447
+ return values.length === 1 ? [base] : values.map((_value, index) => `${base}_${index + 1}`);
22448
+ }
22449
+ /**
22450
+ * Every variable the printed config reads a header from, in print order:
22451
+ * the sources', then the remote fields' on the models and components, then
22452
+ * on Asset and Query. Each parent goes by the name export prints its
22453
+ * fields under: Query, not its apiId QueryModel.
22454
+ */
22455
+ function remoteHeaderEnvNames(environment) {
22456
+ const sources = environment.remoteSources.flatMap((source) => [["", source.headers], ["INTROSPECTION_", source.type === "GRAPHQL" ? source.introspectionHeaders : null]].flatMap(([scope, headers]) => Object.entries(headers ?? {}).flatMap(([name, values]) => headerEnvNames(source.prefix, scope, name, values))));
22457
+ const fields = [
22458
+ ...[...environment.models, ...environment.components].map((parent) => [parent.apiId, parent]),
22459
+ ["Asset", environment.asset],
22460
+ ["Query", environment.query]
22461
+ ].flatMap(([name, parent]) => Object.values(parent?.fields ?? {}).toSorted((a, b) => a.position - b.position || byApiId$1(a, b)).flatMap((field) => field.kind === "remote" ? Object.entries(field.headers ?? {}).flatMap(([header, values]) => headerEnvNames(name, `${field.apiId}_`, header, values)) : []));
22462
+ return [...sources, ...fields];
22463
+ }
22464
+ //#endregion
20286
22465
  //#region src/export/resources/field.ts
20287
22466
  /**
20288
22467
  * A model's fields as the `fields` array, in position order: the order the
20289
22468
  * config gives them is the order they will have. A tie keeps apiId order,
20290
22469
  * so the same schema prints the same.
20291
22470
  */
20292
- function printFields(fields) {
20293
- return `[${Object.values(fields).toSorted((a, b) => a.position - b.position || byApiId$1(a, b)).map(printField).join(", ")}]`;
22471
+ function printFields(parent, fields, print = (field) => printField(parent, field)) {
22472
+ return `[${Object.values(fields).toSorted((a, b) => a.position - b.position || byApiId$1(a, b)).map(print).join(", ")}]`;
22473
+ }
22474
+ /**
22475
+ * A field on Asset. A two-way reference there is the field back of an
22476
+ * asset field, which the config declares with `assetReverseField`: always
22477
+ * a list with no rules and no condition. `visibility` is left out at
22478
+ * `API_ONLY`, where Studio makes it.
22479
+ */
22480
+ function printAssetModelField(field) {
22481
+ if (field.kind !== "referenceTwoWay") return printField("Asset", field);
22482
+ return printBuilder("assetReverseField", [
22483
+ ["apiId", string(field.apiId)],
22484
+ ["displayName", string(field.displayName)],
22485
+ ["to", `() => ${field.to}`],
22486
+ ["reverse", string(field.reverse)],
22487
+ ["description", field.description === null ? void 0 : string(field.description)],
22488
+ ["visibility", field.visibility === "API_ONLY" ? void 0 : string(field.visibility)]
22489
+ ]);
20294
22490
  }
20295
- function printField(field) {
22491
+ /** `parent` is the model's or component's apiId, which names a remote field's header variables. */
22492
+ function printField(parent, field) {
20296
22493
  switch (field.kind) {
20297
22494
  case "unsupported": return printBuilder("unsupported", [["apiId", string(field.apiId)], ["type", string(field.type)]]);
20298
22495
  case "boolean": return printBuilder("boolean", fieldOptions(field, FIELD_DEFAULTS));
@@ -20332,7 +22529,7 @@ function printField(field) {
20332
22529
  }
20333
22530
  case "component": return printBuilder("component", referenceOptions(field, ["component", `() => ${field.component}`]));
20334
22531
  case "componentUnion": return printBuilder("componentUnion", referenceOptions(field, ["components", `[${field.components.map((apiId) => `() => ${apiId}`).join(", ")}]`]));
20335
- case "asset": return printBuilder("asset", referenceOptions(field));
22532
+ case "asset": return printBuilder("asset", referenceOptions(field, ["reverse", field.reverse === void 0 ? void 0 : string(field.reverse)]));
20336
22533
  case "referenceOneWay": return printBuilder("referenceOneWay", [...referenceOptions(field, ["to", `() => ${field.to}`]), ["rules", printRules(field.rules)]]);
20337
22534
  case "referenceTwoWay": {
20338
22535
  const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
@@ -20366,8 +22563,43 @@ function printField(field) {
20366
22563
  ...options
20367
22564
  ]);
20368
22565
  }
22566
+ case "remote": return printBuilder("remote", remoteOptions(parent, field));
20369
22567
  }
20370
22568
  }
22569
+ /**
22570
+ * The source's const, which export prints ahead of the models. Headers are
22571
+ * read from the environment, like a source's, under the parent's and the
22572
+ * field's apiId: `STORE_FORECAST_AUTHORIZATION`. Attributes at their
22573
+ * default are left out.
22574
+ */
22575
+ function remoteOptions(parent, field) {
22576
+ return [
22577
+ ["apiId", string(field.apiId)],
22578
+ ["displayName", string(field.displayName)],
22579
+ ["description", field.description === null ? void 0 : string(field.description)],
22580
+ ["source", remoteSourceConstName({ prefix: field.source })],
22581
+ ["returnType", string(field.returnType)],
22582
+ ["method", string(field.method)],
22583
+ ["query", field.query === null ? void 0 : template(field.query)],
22584
+ ["path", field.path === null ? void 0 : string(field.path)],
22585
+ ["args", field.args.length === 0 ? void 0 : `[${field.args.map(printRemoteFieldArg).join(", ")}]`],
22586
+ ["headers", printHeaders(parent, `${field.apiId}_`, field.headers)],
22587
+ ["forwardClientHeaders", field.forwardClientHeaders === REMOTE_DEFAULTS.forwardClientHeaders ? void 0 : String(field.forwardClientHeaders)],
22588
+ ["cacheTTLSeconds", field.cacheTTLSeconds === REMOTE_DEFAULTS.cacheTTLSeconds ? void 0 : String(field.cacheTTLSeconds)],
22589
+ ["list", field.list === REMOTE_DEFAULTS.list ? void 0 : String(field.list)],
22590
+ ["required", field.required === REMOTE_DEFAULTS.required ? void 0 : String(field.required)],
22591
+ ["visibility", field.visibility === REMOTE_DEFAULTS.visibility ? void 0 : string(field.visibility)]
22592
+ ];
22593
+ }
22594
+ /** On one line, `required` and `list` only when set. */
22595
+ function printRemoteFieldArg(arg) {
22596
+ return `{ ${[
22597
+ `apiId: ${string(arg.apiId)}`,
22598
+ `type: ${string(arg.type)}`,
22599
+ ...arg.required ? ["required: true"] : [],
22600
+ ...arg.list ? ["list: true"] : []
22601
+ ].join(", ")} }`;
22602
+ }
20371
22603
  /** The builder that makes each text form renderer, with its defaults. */
20372
22604
  const BUILDERS = {
20373
22605
  GCMS_SINGLE_LINE: ["singleLine", FIELD_DEFAULTS],
@@ -20491,7 +22723,7 @@ function printComponent(component) {
20491
22723
  ["apiIdPlural", string(component.apiIdPlural)],
20492
22724
  ["displayName", string(component.displayName)],
20493
22725
  ["description", component.description === null ? void 0 : string(component.description)],
20494
- ["fields", printFields(component.fields)]
22726
+ ["fields", printFields(component.apiId, component.fields)]
20495
22727
  ])});`;
20496
22728
  }
20497
22729
  //#endregion
@@ -20540,7 +22772,7 @@ function printModel(model) {
20540
22772
  ["apiIdPlural", string(model.apiIdPlural)],
20541
22773
  ["displayName", string(model.displayName)],
20542
22774
  ["description", model.description === null ? void 0 : string(model.description)],
20543
- ["fields", printFields(model.fields)]
22775
+ ["fields", printFields(model.apiId, model.fields)]
20544
22776
  ])});`;
20545
22777
  }
20546
22778
  //#endregion
@@ -20566,6 +22798,19 @@ function printStage(stage) {
20566
22798
  ])})`;
20567
22799
  }
20568
22800
  //#endregion
22801
+ //#region src/export/resources/system.ts
22802
+ /** `const Asset = system.asset({ fields: [...] });`, your fields only. */
22803
+ function printSystemAsset(asset) {
22804
+ return `const Asset = system.asset(${object([["fields", printFields(asset.apiId, asset.fields, printAssetModelField)]])});`;
22805
+ }
22806
+ /**
22807
+ * `const Query = system.query({ fields: [...] });`. Its remote fields read
22808
+ * their headers as `QUERY_<FIELD>_<HEADER>`, after the name Studio shows.
22809
+ */
22810
+ function printSystemQuery(query) {
22811
+ return `const Query = system.query(${object([["fields", printFields("Query", query.fields)]])});`;
22812
+ }
22813
+ //#endregion
20569
22814
  //#region src/export/resources/taxonomy.ts
20570
22815
  /**
20571
22816
  * `const <apiId> = define.taxonomy({...});`, the tree from the root down,
@@ -20596,20 +22841,35 @@ function printTaxonomy(taxonomy) {
20596
22841
  }
20597
22842
  //#endregion
20598
22843
  //#region src/export/config.ts
22844
+ /** Asset as the IR has it when live has no fields of yours on it. */
22845
+ const NO_ASSET_FIELDS = {
22846
+ apiId: "Asset",
22847
+ fields: {}
22848
+ };
22849
+ /** Query as the IR has it when live has no fields of yours on it. */
22850
+ const NO_QUERY_FIELDS = {
22851
+ apiId: "QueryModel",
22852
+ fields: {}
22853
+ };
20599
22854
  /**
20600
22855
  * The config a user commits: one const per enumeration, then per
20601
- * taxonomy, per component and per model, in IR order, the environment
20602
- * that lists them with every locale and stage written inline, and the
20603
- * target as the default export. The token is read from HYGRAPH_TOKEN when
20604
- * the config loads, never written.
22856
+ * taxonomy, per remote source, per component and per model, in IR
22857
+ * order, then Asset and Query, also with no fields of yours, so the first
22858
+ * asset field only adds its field back there. Then the environment that
22859
+ * lists them with every locale and stage written inline, and the target as
22860
+ * the default export. The token is read from HYGRAPH_TOKEN when the config
22861
+ * loads, never written.
20605
22862
  */
20606
22863
  async function printConfig(target, environment) {
20607
22864
  return formatSource([
20608
22865
  `import { define, system } from "@hygraph/cli/define";`,
20609
22866
  ...environment.enumerations.map(printEnumeration),
20610
22867
  ...environment.taxonomies.map(printTaxonomy),
22868
+ ...environment.remoteSources.map(printRemoteSource),
20611
22869
  ...environment.components.map(printComponent),
20612
22870
  ...environment.models.map(printModel),
22871
+ printSystemAsset(environment.asset ?? NO_ASSET_FIELDS),
22872
+ printSystemQuery(environment.query ?? NO_QUERY_FIELDS),
20613
22873
  printEnvironment(environment),
20614
22874
  printTarget(target)
20615
22875
  ].join("\n\n"));
@@ -20618,18 +22878,23 @@ async function printConfig(target, environment) {
20618
22878
  * `locales` lists every locale, the default one included. `stages` lists
20619
22879
  * every stage in its live order, also when Draft and Published are the only
20620
22880
  * ones, so the config shows where a new stage goes. `enumerations`,
20621
- * `taxonomies` and `components` are left out when there are none, their
20622
- * default.
22881
+ * `taxonomies`, `remoteSources` and `components` are left out when there
22882
+ * are none, their default. `models` ends with Asset and Query.
20623
22883
  */
20624
- function printEnvironment({ locales, stages, enumerations, taxonomies, components, models }) {
22884
+ function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset }) {
20625
22885
  const list = (resources) => `[${resources.map((resource) => resource.apiId).join(", ")}]`;
20626
22886
  return `const environment = define.environment({ ${[
20627
22887
  `locales: [${locales.map(printLocale).join(", ")}]`,
20628
22888
  `stages: [${stages.toSorted((a, b) => a.position - b.position).map(printStage).join(", ")}]`,
20629
22889
  ...enumerations.length > 0 ? [`enumerations: ${list(enumerations)}`] : [],
20630
22890
  ...taxonomies.length > 0 ? [`taxonomies: ${list(taxonomies)}`] : [],
22891
+ ...remoteSources.length > 0 ? [`remoteSources: [${remoteSources.map(remoteSourceConstName).join(", ")}]`] : [],
20631
22892
  ...components.length > 0 ? [`components: ${list(components)}`] : [],
20632
- `models: ${list(models)}`
22893
+ `models: ${list([
22894
+ ...models,
22895
+ asset ?? NO_ASSET_FIELDS,
22896
+ { apiId: "Query" }
22897
+ ])}`
20633
22898
  ].join(", ")} });`;
20634
22899
  }
20635
22900
  function printTarget(target) {
@@ -20649,15 +22914,19 @@ var ExportFailure = class extends Failure {};
20649
22914
  function registerExport(program) {
20650
22915
  program.command("export").description("write a live environment out as TypeScript").requiredOption("--project <id>", "project to export").requiredOption("--endpoint <url>", "the project's management API endpoint").option("--environment <name>", "environment to export", "master").option("--name <name>", "target name in the config (default: the environment)").option("--out <file>", "write to a file instead of stdout").option("--no-color", "print without colours").action(async function(options) {
20651
22916
  const write = (text) => this.configureOutput().writeOut?.(text);
22917
+ const writeErr = (text) => this.configureOutput().writeErr?.(text);
20652
22918
  try {
20653
22919
  const { config, environment } = await exportEnvironment(options);
22920
+ const headers = renderHeaderNote(remoteHeaderEnvNames(environment)) + renderSecretNote(oAuthSecretEnvNames(environment));
20654
22921
  if (options.out === void 0) {
20655
22922
  write(config);
22923
+ writeErr(headers);
20656
22924
  return;
20657
22925
  }
20658
22926
  writeConfigFile(config, options.out);
20659
22927
  const colors = import_picocolors.default.createColors(options.color && import_picocolors.default.isColorSupported);
20660
22928
  write(renderCheck(`wrote ${options.out}`, count(environment), colors));
22929
+ write(headers);
20661
22930
  write(`\nRun \`hygraph plan ${options.out}\` next. It should show no changes.\n`);
20662
22931
  } catch (error) {
20663
22932
  if (error instanceof Failure) this.error(`error: ${error.message}`, {
@@ -20693,6 +22962,24 @@ async function exportEnvironment(options) {
20693
22962
  environment: environment$1
20694
22963
  };
20695
22964
  }
22965
+ /**
22966
+ * The variables the config reads remote source headers from, which the
22967
+ * user sets before plan, or empty when there are none. Export leaves the
22968
+ * values out; Studio shows them in the source's settings.
22969
+ */
22970
+ function renderHeaderNote(names) {
22971
+ if (names.length === 0) return "";
22972
+ return `\nThe config reads remote source headers from ${names.join(", ")}. Set them to the values the headers have in Hygraph, which Studio shows in each source's settings, or replace a read with the value where it is not a secret, such as Accept: "application/json".\n`;
22973
+ }
22974
+ /**
22975
+ * The variables the config reads OAuth secrets from, or empty when there
22976
+ * are none. Hygraph never shows a secret, and apply sends one only when a
22977
+ * plan needs it, such as on a create.
22978
+ */
22979
+ function renderSecretNote(names) {
22980
+ if (names.length === 0) return "";
22981
+ return `\nThe config reads OAuth secrets from ${names.join(", ")}. Set each to its API client's secret before a plan that sends it, such as one that creates the source. Hygraph keeps the secrets and never shows them.\n`;
22982
+ }
20696
22983
  /** Replaces a file that is already there: the config is meant to live in git. */
20697
22984
  function writeConfigFile(config, path) {
20698
22985
  try {
@@ -20721,7 +23008,7 @@ function pull(command) {
20721
23008
  //#endregion
20722
23009
  //#region src/commands/validate.ts
20723
23010
  function registerValidate(program) {
20724
- program.command("validate").description("dry-run the migration on the server against real data").requiredOption("--plan <file>", "the plan artifact to validate").action(function() {
23011
+ program.command("validate", { hidden: true }).description("dry-run the migration on the server against real data").requiredOption("--plan <file>", "the plan artifact to validate").action(function() {
20725
23012
  validate(this);
20726
23013
  }).addHelpText("after", examples([["hygraph validate --plan plan.json", "ask the server to dry-run it"]]));
20727
23014
  }