@hygraph/cli 0.0.15 → 0.0.17

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/README.md CHANGED
@@ -144,7 +144,7 @@ npx hygraph apply --prune
144
144
  `apply` does not ask for confirmation when `CI` or `TF_BUILD` is set, which
145
145
  most CI providers do. Elsewhere, pass `--yes`.
146
146
 
147
- To apply exactly the plan someone reviewed, save it and pass it to `apply`:
147
+ To apply the plan someone reviewed, save it and pass it to `apply`:
148
148
 
149
149
  ```bash
150
150
  npx hygraph plan --out plan.json
@@ -154,6 +154,12 @@ npx hygraph apply --plan plan.json
154
154
  `apply` refuses the saved plan if the config or the live schema has changed
155
155
  since. Run `plan` again in that case.
156
156
 
157
+ The saved plan holds an HMAC of each remote source header value and OAuth
158
+ secret, never the value. The HMAC uses a key that Hygraph keeps for your
159
+ project, so the plan alone does not let anyone test a guessed value.
160
+ `apply` refuses the saved plan when one of these values changed after
161
+ `plan`, or when the project's key changed. Run `plan` again in that case.
162
+
157
163
  ## What's supported
158
164
 
159
165
  - **Schema:** models, components, enumerations, taxonomies, locales and
package/dist/cli.js CHANGED
@@ -8,7 +8,7 @@ import fs, { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
8
8
  import process$1 from "node:process";
9
9
  import { isDeepStrictEqual, stripVTControlCharacters } from "node:util";
10
10
  import { createInterface } from "node:readline/promises";
11
- import { createHash } from "node:crypto";
11
+ import { createHash, createHmac } from "node:crypto";
12
12
  import { createJiti } from "jiti";
13
13
  import { Writable } from "node:stream";
14
14
  import { structuredPatch } from "diff";
@@ -3448,6 +3448,11 @@ const SchemaDefinitionDocument = new TypedDocumentString(`
3448
3448
  }
3449
3449
  __typename
3450
3450
  }
3451
+ schemaHashKey {
3452
+ id
3453
+ key
3454
+ __typename
3455
+ }
3451
3456
  __typename
3452
3457
  }
3453
3458
  __typename
@@ -3711,171 +3716,140 @@ function hashIR(ir) {
3711
3716
  //#region src/plan/masking.ts
3712
3717
  /**
3713
3718
  * Remote source header values hold tokens, and OAuth secrets are secrets,
3714
- * so the plan carries a hash of each in their place: `plan.json` is kept as
3715
- * a CI artifact and printed in job logs. A change still shows, as the hash
3716
- * moves with the value. Apply puts the values back from the config it
3717
- * plans again from.
3718
- */
3719
- const MASK = "sha256:";
3720
- /** Every header value and OAuth secret in the changes, the live ones included, as its hash. */
3721
- function maskSecrets(changes) {
3722
- const hash = (value) => `${MASK}${hashJSON(value)}`;
3723
- return mapSecrets(mapHeaders(changes, (headers) => mapValues(headers, hash)), hash);
3724
- }
3725
- /**
3726
- * Every header value of the config's sources and remote fields, and every
3727
- * OAuth secret, which the IR leaves out, by the hash `maskSecrets`
3728
- * puts in its place.
3729
- */
3730
- function secretValues(desired, secrets = /* @__PURE__ */ new Map()) {
3731
- const headers = [...desired.remoteSources.flatMap((source) => [source.headers, source.type === "GRAPHQL" ? source.introspectionHeaders : null]), ...[
3732
- ...desired.models,
3733
- ...desired.components,
3734
- ...desired.asset ? [desired.asset] : [],
3735
- ...desired.query ? [desired.query] : []
3736
- ].flatMap((parent) => Object.values(parent.fields).map((field) => field.kind === "remote" ? field.headers : null))];
3737
- return new Map([...byHash(headers.flatMap((each) => Object.values(each ?? {}).flat())), ...oAuthSecretValues(secrets)]);
3738
- }
3739
- /**
3740
- * The OAuth secrets alone, by hash: what apply needs to check a plan's
3741
- * secrets before the config is validated and converted.
3742
- */
3743
- function oAuthSecretValues(secrets) {
3744
- return byHash([...secrets.values()].flatMap(({ secret }) => secret === null ? [] : [secret]));
3745
- }
3746
- function byHash(values) {
3747
- return new Map(values.map((value) => [`${MASK}${hashJSON(value)}`, value]));
3748
- }
3749
- /**
3750
- * The changes with the config's header values back in place of their
3751
- * hashes, for the batch. Only the values a change sends need to be found:
3752
- * those of `to`, which is the config. A hash the config does not have
3753
- * stays as it is; apply refuses a plan whose config moved before it gets
3754
- * here.
3755
- */
3756
- function unmaskSecrets(changes, values) {
3757
- const unmask = (value) => values.get(value) ?? value;
3758
- return mapSecrets(mapHeaders(changes, (headers) => mapValues(headers, unmask)), unmask);
3759
- }
3760
- function unsendableOAuthSecrets(changes) {
3761
- return changes.flatMap((change) => {
3762
- if (change.resource !== "remoteSource" || change.action === "delete") return [];
3763
- const prefix = remoteSourcePrefixOf(change);
3764
- if (change.clientSecret === null) return [{
3765
- prefix,
3766
- reason: "missing"
3767
- }];
3768
- if (change.clientSecret?.startsWith(MASK)) return [{
3769
- prefix,
3770
- reason: "changed"
3771
- }];
3772
- return [];
3773
- });
3774
- }
3775
- /** Every OAuth secret a remote source change sends, passed through `map`. */
3776
- function mapSecrets(changes, map) {
3777
- return changes.map((change) => {
3778
- if (change.resource !== "remoteSource" || change.action === "delete" || typeof change.clientSecret !== "string") return change;
3779
- return {
3780
- ...change,
3781
- clientSecret: map(change.clientSecret)
3782
- };
3783
- });
3784
- }
3785
- function mapValues(headers, map) {
3786
- return Object.fromEntries(Object.entries(headers).map(([name, values]) => [name, values.map(map)]));
3719
+ * while `plan.json` is kept as a CI artifact and printed in job logs, so
3720
+ * the plan holds the value's HMAC-SHA256 under the project's hash key,
3721
+ * `hmac-sha256:<hex>`, in place of each value: the plan pins the value,
3722
+ * and a reader without the key cannot test a guess. Apply sends the values
3723
+ * of the changes it plans again.
3724
+ */
3725
+ const HMAC = "hmac-sha256:";
3726
+ function redaction(key) {
3727
+ const bytes = Buffer.from(key.key, "hex");
3728
+ const hmac = (value) => `${HMAC}${createHmac("sha256", bytes).update(value).digest("hex")}`;
3729
+ const headers = (each) => mapValues(each, hmac);
3730
+ return {
3731
+ headers,
3732
+ change: ({ from, to }) => ({
3733
+ from: headers(from),
3734
+ to: headers(to)
3735
+ }),
3736
+ secret: hmac
3737
+ };
3787
3738
  }
3788
- /**
3789
- * Every set of headers a remote source change or a remote field change
3790
- * holds, passed through `map`.
3791
- */
3792
- function mapHeaders(changes, map) {
3793
- const each = (headers) => headers === null ? null : map(headers);
3739
+ /** Every header value and OAuth secret in the changes, the live ones included, as its hash. */
3740
+ function redactSecrets(changes, key) {
3741
+ const redact = redaction(key);
3794
3742
  return changes.map((change) => {
3795
3743
  if (change.resource === "field") {
3796
3744
  if (change.action === "create" && change.field.kind === "remote") return {
3797
3745
  ...change,
3798
3746
  field: {
3799
3747
  ...change.field,
3800
- headers: each(change.field.headers)
3801
- }
3802
- };
3803
- if (change.action === "update" && change.kind === "remote" && change.changes.headers) {
3804
- const { headers } = change.changes;
3805
- return {
3806
- ...change,
3807
- changes: {
3808
- ...change.changes,
3809
- headers: {
3810
- from: each(headers.from),
3811
- to: each(headers.to)
3812
- }
3813
- }
3814
- };
3815
- }
3816
- return change;
3817
- }
3818
- if (change.resource !== "remoteSource") return change;
3819
- if (change.action === "create") {
3820
- const source = change.remoteSource;
3821
- return {
3822
- ...change,
3823
- remoteSource: source.type === "GRAPHQL" ? {
3824
- ...source,
3825
- headers: each(source.headers),
3826
- introspectionHeaders: each(source.introspectionHeaders)
3827
- } : {
3828
- ...source,
3829
- headers: each(source.headers)
3748
+ headers: redact.headers(change.field.headers)
3830
3749
  }
3831
3750
  };
3832
- }
3833
- if (change.action === "update") {
3834
- const { headers, introspectionHeaders } = change.changes;
3835
- return {
3751
+ if (change.action === "update" && change.kind === "remote" && change.changes.headers) return {
3836
3752
  ...change,
3837
- headers: each(change.headers),
3838
- introspectionHeaders: each(change.introspectionHeaders),
3839
3753
  changes: {
3840
3754
  ...change.changes,
3841
- ...headers && { headers: {
3842
- from: each(headers.from),
3843
- to: each(headers.to)
3844
- } },
3845
- ...introspectionHeaders && { introspectionHeaders: {
3846
- from: each(introspectionHeaders.from),
3847
- to: each(introspectionHeaders.to)
3848
- } }
3755
+ headers: redact.change(change.changes.headers)
3849
3756
  }
3850
3757
  };
3758
+ return change;
3851
3759
  }
3852
- return change;
3760
+ if (change.resource !== "remoteSource" || change.action === "delete") return change;
3761
+ const clientSecret = typeof change.clientSecret === "string" ? { clientSecret: redact.secret(change.clientSecret) } : void 0;
3762
+ if (change.action === "create") return {
3763
+ ...change,
3764
+ remoteSource: redactSource(change.remoteSource, redact),
3765
+ ...clientSecret
3766
+ };
3767
+ const { headers, introspectionHeaders } = change.changes;
3768
+ return {
3769
+ ...change,
3770
+ headers: redact.headers(change.headers),
3771
+ introspectionHeaders: redact.headers(change.introspectionHeaders),
3772
+ changes: {
3773
+ ...change.changes,
3774
+ ...headers && { headers: redact.change(headers) },
3775
+ ...introspectionHeaders && { introspectionHeaders: redact.change(introspectionHeaders) }
3776
+ },
3777
+ ...clientSecret
3778
+ };
3853
3779
  });
3854
3780
  }
3855
- /** The changes hold a hash of each remote source header value, not the value. */
3856
- function buildPlan({ target, desired, intents, live, changes }) {
3781
+ /** The IR with every header value as its hash, for the fingerprints. */
3782
+ function redactEnvironment(environment, key) {
3783
+ const redact = redaction(key);
3784
+ const fields = (parent) => redactFields(parent, redact);
3785
+ const { asset, query, segment } = environment;
3786
+ return {
3787
+ ...environment,
3788
+ remoteSources: environment.remoteSources.map((source) => redactSource(source, redact)),
3789
+ models: environment.models.map(fields),
3790
+ components: environment.components.map(fields),
3791
+ ...asset && { asset: fields(asset) },
3792
+ ...query && { query: fields(query) },
3793
+ ...segment && { segment: fields(segment) }
3794
+ };
3795
+ }
3796
+ function redactSource(source, redact) {
3797
+ return source.type === "GRAPHQL" ? {
3798
+ ...source,
3799
+ headers: redact.headers(source.headers),
3800
+ introspectionHeaders: redact.headers(source.introspectionHeaders)
3801
+ } : {
3802
+ ...source,
3803
+ headers: redact.headers(source.headers)
3804
+ };
3805
+ }
3806
+ function redactFields(parent, redact) {
3807
+ return {
3808
+ ...parent,
3809
+ fields: Object.fromEntries(Object.entries(parent.fields).map(([apiId, field]) => [apiId, field.kind === "remote" ? {
3810
+ ...field,
3811
+ headers: redact.headers(field.headers)
3812
+ } : field]))
3813
+ };
3814
+ }
3815
+ function mapValues(headers, map) {
3816
+ return headers === null ? null : Object.fromEntries(Object.entries(headers).map(([name, values]) => [name, values.map(map)]));
3817
+ }
3818
+ /**
3819
+ * The changes hold a hash under `hashKey` in place of each header value
3820
+ * and OAuth secret, and the fingerprints in place of each header value.
3821
+ */
3822
+ function buildPlan({ target, desired, intents, live, changes, hashKey }) {
3857
3823
  const planTarget = {
3858
3824
  project: target.project,
3859
3825
  environment: target.environment
3860
3826
  };
3861
- const masked = maskSecrets(changes);
3827
+ const redacted = redactSecrets(changes, hashKey);
3862
3828
  return {
3863
3829
  formatVersion: 1,
3864
3830
  target: planTarget,
3865
- desiredFingerprint: desiredFingerprint(desired, intents),
3866
- liveFingerprint: hashIR(live),
3867
- planHash: planHash(planTarget, masked),
3868
- summary: summarise(masked),
3869
- changes: masked
3831
+ hashKeyId: hashKey.id,
3832
+ desiredFingerprint: desiredFingerprint(desired, intents, hashKey),
3833
+ liveFingerprint: liveFingerprint(live, hashKey),
3834
+ planHash: planHash(planTarget, redacted),
3835
+ summary: summarise(redacted),
3836
+ changes: redacted
3870
3837
  };
3871
3838
  }
3872
- /** The config as written: its canonical IR and the renames it declares. */
3873
- function desiredFingerprint(desired, intents) {
3839
+ /**
3840
+ * The config as written: its canonical IR and the renames it declares.
3841
+ * Header values are hashes, as in the changes.
3842
+ */
3843
+ function desiredFingerprint(desired, intents, hashKey) {
3874
3844
  return hashJSON({
3875
- environment: desired,
3845
+ environment: redactEnvironment(desired, hashKey),
3876
3846
  intents
3877
3847
  });
3878
3848
  }
3849
+ /** The live schema's canonical IR, header values as hashes. */
3850
+ function liveFingerprint(live, hashKey) {
3851
+ return hashIR(redactEnvironment(live, hashKey));
3852
+ }
3879
3853
  /** Change order is part of the plan: the migration runs in this order. */
3880
3854
  function planHash(target, changes) {
3881
3855
  return hashJSON({
@@ -11904,12 +11878,11 @@ function createComponentUnionField({ parent }, field) {
11904
11878
  }
11905
11879
  /**
11906
11880
  * Only the attributes that change are sent. A rename is `newApiId`; the
11907
- * members are sent whole and replace the old ones. `list` and the
11908
- * visibility cannot change: the diff deletes and creates the field
11909
- * instead.
11881
+ * members are sent whole and replace the old ones. `list` cannot change:
11882
+ * the diff deletes and creates the field instead.
11910
11883
  */
11911
11884
  function updateComponentUnionField(change) {
11912
- const { apiId, displayName, description, components, visibilityCondition, variantEnabled, position } = change.changes;
11885
+ const { apiId, displayName, description, components, visibility, visibilityCondition, variantEnabled, position } = change.changes;
11913
11886
  const input = {
11914
11887
  apiId: change.apiId,
11915
11888
  parentApiId: change.parent
@@ -11918,6 +11891,7 @@ function updateComponentUnionField(change) {
11918
11891
  if (displayName) input.displayName = displayName.to;
11919
11892
  if (description) input.description = description.to;
11920
11893
  if (components) input.componentApiIds = components.to;
11894
+ if (visibility) input.visibility = visibility.to;
11921
11895
  if (visibilityCondition) input.visibilityCondition = visibilityCondition.to;
11922
11896
  if (variantEnabled) input.isVariantEnabled = variantEnabled.to;
11923
11897
  if (position) input.position = position.to;
@@ -12755,7 +12729,7 @@ function renderRemoteSourceChange(change, width, colors) {
12755
12729
  case "delete": return [` ${colors.red(`- ${op}`)} ${change.prefix} ${colors.yellow(`⚠ deletes the remote source`)}`];
12756
12730
  }
12757
12731
  }
12758
- /** Whether the change sends the OAuth secret, never its value or hash. */
12732
+ /** Whether the change sends the OAuth secret, never its value. */
12759
12733
  function secretRow(clientSecret) {
12760
12734
  if (clientSecret === void 0) return [];
12761
12735
  return [{
@@ -14085,6 +14059,7 @@ const planSchema = strictObject({
14085
14059
  project: string$1(),
14086
14060
  environment: string$1()
14087
14061
  }),
14062
+ hashKeyId: string$1(),
14088
14063
  desiredFingerprint: string$1(),
14089
14064
  liveFingerprint: string$1(),
14090
14065
  planHash: string$1(),
@@ -14140,7 +14115,10 @@ function readPlanFile(file) {
14140
14115
  * and holding the changes this CLI plans from those. Every mismatch is
14141
14116
  * returned, so one run shows all of them. The last check only runs when
14142
14117
  * the others hold; otherwise the plan hash differs for a reason already
14143
- * given.
14118
+ * given. The fingerprints hold header values as hashes under the project's
14119
+ * hash key, and the plan hash holds header values and OAuth secrets, so a
14120
+ * changed value moves one of them. They compare only under the same key;
14121
+ * with another key, the fingerprints are not compared.
14144
14122
  */
14145
14123
  function verifyPlan(artifact, current) {
14146
14124
  const refusals = [];
@@ -14166,23 +14144,30 @@ function verifyPlan(artifact, current) {
14166
14144
  current: currentTarget,
14167
14145
  hint: "Point the config at that environment, or plan again for this one."
14168
14146
  });
14169
- if (artifact.desiredFingerprint !== current.desiredFingerprint) refusals.push({
14147
+ const keyMoved = artifact.hashKeyId !== current.hashKeyId;
14148
+ if (keyMoved) refusals.push({
14149
+ reason: "hashKeyId mismatch — the plan hashes its secret values with another key than the project has now",
14150
+ planned: artifact.hashKeyId,
14151
+ current: current.hashKeyId,
14152
+ hint: "The project's key changed. Plan again."
14153
+ });
14154
+ if (!keyMoved && artifact.desiredFingerprint !== current.desiredFingerprint) refusals.push({
14170
14155
  reason: "desiredFingerprint mismatch — the config changed after this plan was made",
14171
14156
  planned: artifact.desiredFingerprint,
14172
14157
  current: current.desiredFingerprint,
14173
14158
  hint: "Plan again and get the new artifact reviewed."
14174
14159
  });
14175
- if (artifact.liveFingerprint !== current.liveFingerprint) refusals.push({
14160
+ if (!keyMoved && artifact.liveFingerprint !== current.liveFingerprint) refusals.push({
14176
14161
  reason: "liveFingerprint mismatch — the live schema changed after this plan was made",
14177
14162
  planned: artifact.liveFingerprint,
14178
14163
  current: current.liveFingerprint,
14179
14164
  hint: "Run plan to see it; a Studio edit is the usual cause."
14180
14165
  });
14181
14166
  if (refusals.length === 0 && artifact.planHash !== current.planHash) refusals.push({
14182
- reason: "planHash mismatch — this CLI plans other changes from the same config and schema",
14167
+ reason: "planHash mismatch — planning again gives other changes with the same fingerprints",
14183
14168
  planned: artifact.planHash,
14184
14169
  current: current.planHash,
14185
- hint: "The artifact came from another CLI version. Plan again with this one."
14170
+ hint: "An OAuth secret or a header value changed, or the artifact came from another CLI version. Plan again."
14186
14171
  });
14187
14172
  return refusals;
14188
14173
  }
@@ -16271,7 +16256,7 @@ var LiveSchemaFailure = class extends Failure {};
16271
16256
  * two-way relation's other side without its rules and condition, and a
16272
16257
  * union's members with the first one's settings, so they come from its
16273
16258
  * `models`, as every model's sidebar does. Whether Segment exists comes
16274
- * from its system models.
16259
+ * from its system models. The project's hash key comes with it.
16275
16260
  */
16276
16261
  async function readLiveEnvironment(target, fetch) {
16277
16262
  if (isEmpty(target.token)) throw new LiveSchemaFailure(`target "${target.name}" has no token. An exported config reads it from HYGRAPH_TOKEN.`);
@@ -16294,6 +16279,10 @@ async function readLiveEnvironment(target, fetch) {
16294
16279
  const sidebars = new Map(environment.contentModel.models.map((model) => [model.apiId, convertSidebarToIR(model.apiId, model.sidebarElements)]));
16295
16280
  return {
16296
16281
  environmentId: environment.id,
16282
+ hashKey: {
16283
+ id: environment.schemaHashKey.id,
16284
+ key: environment.schemaHashKey.key
16285
+ },
16297
16286
  unsupportedPairs: findUnsupportedPairs(environment.schemaDefinition, live),
16298
16287
  unsupportedUnions: findUnsupportedUnions(environment.schemaDefinition, live, unions),
16299
16288
  apps: environment.appInstallations.map(({ app }) => ({
@@ -17315,6 +17304,10 @@ function rotateOAuthSecrets(changes, desired, secrets, rotate) {
17315
17304
  function sentOAuthSecrets(changes) {
17316
17305
  return changes.flatMap((change) => change.resource === "remoteSource" && change.action !== "delete" && typeof change.clientSecret === "string" ? [remoteSourcePrefixOf(change)] : []);
17317
17306
  }
17307
+ /** The sources a plan needs a secret for that the config did not have, which apply refuses. */
17308
+ function missingOAuthSecrets(changes) {
17309
+ return changes.flatMap((change) => change.resource === "remoteSource" && change.action !== "delete" && change.clientSecret === null ? [remoteSourcePrefixOf(change)] : []);
17310
+ }
17318
17311
  //#endregion
17319
17312
  //#region src/define/fields/validation.shared.ts
17320
17313
  /**
@@ -20360,9 +20353,9 @@ function basesFirst(creates) {
20360
20353
  /**
20361
20354
  * Hygraph cannot change a field's type or its `list` once it exists, nor an
20362
20355
  * enumeration field's enumeration or `localized`, a taxonomy field's
20363
- * taxonomy, a component field's component, a union's visibility or the
20364
- * model a reference references, nor turn a rich text's embeds off. A
20365
- * two-way pair is decided as a whole, in `pairTwoWayReferences`.
20356
+ * taxonomy, a component field's component or the model a reference
20357
+ * references, nor turn a rich text's embeds off. A two-way pair is decided
20358
+ * as a whole, in `pairTwoWayReferences`.
20366
20359
  */
20367
20360
  function changesInPlace(from, to) {
20368
20361
  if (from.kind === "unsupported" || to.kind === "unsupported") return from.kind === "unsupported" && to.kind === "unsupported" && from.type === to.type;
@@ -20370,7 +20363,6 @@ function changesInPlace(from, to) {
20370
20363
  if (from.kind === "taxonomy" && to.kind === "taxonomy") return from.list === to.list && from.taxonomy === to.taxonomy;
20371
20364
  if (from.kind === "remote" && to.kind === "remote") return from.list === to.list && from.type === to.type;
20372
20365
  if (from.kind === "component" && to.kind === "component") return from.list === to.list && from.component === to.component;
20373
- if (from.kind === "componentUnion" && to.kind === "componentUnion") return from.list === to.list && from.visibility === to.visibility;
20374
20366
  if (from.kind === "referenceOneWay" && to.kind === "referenceOneWay") return from.list === to.list && from.to === to.to;
20375
20367
  if (from.kind === "richText" && to.kind === "richText") return from.list === to.list && (from.embeds === null || to.embeds !== null);
20376
20368
  return from.kind === to.kind && from.list === to.list;
@@ -23862,16 +23854,16 @@ async function planTarget(target, { config, colors, out, rotateSecrets, write })
23862
23854
  * the renames and the unsupported fields against it, diff the two, validate the change set, build the
23863
23855
  * plan. Stops at the first phase with errors and reports every error of that
23864
23856
  * phase. Warnings do not stop it; they come back beside the plan. The environment id comes along for `apply`, which addresses the
23865
- * batch by it, and so do the config's header values and OAuth secrets,
23866
- * which the plan holds as hashes. `rotateSecrets` names the sources whose
23867
- * secret it sends although nothing else asks for it.
23857
+ * batch by it, and so do the changes with their header values and OAuth
23858
+ * secrets, which the plan holds as hashes. `rotateSecrets` names the
23859
+ * sources whose secret it sends although nothing else asks for it.
23868
23860
  */
23869
23861
  async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
23870
23862
  const configValidations = validateEnvironment(target.apply);
23871
23863
  maybeRefuse(configValidations, "the config has");
23872
23864
  const desired = convertEnvironmentToIR(target.apply);
23873
23865
  const intents = collectIntents(target.apply);
23874
- const { environmentId, environment: live, unsupportedPairs, unsupportedUnions, apps, fieldsBackOnAsset, newModelSidebar, oldSidebarTitles, modelsWithUnsupportedSidebarElements } = await readLiveEnvironment(target, fetch);
23866
+ const { environmentId, environment: live, unsupportedPairs, unsupportedUnions, apps, fieldsBackOnAsset, newModelSidebar, oldSidebarTitles, modelsWithUnsupportedSidebarElements, hashKey } = await readLiveEnvironment(target, fetch);
23875
23867
  maybeRefuse(validateRemoteSourceChanges({
23876
23868
  from: live,
23877
23869
  to: desired
@@ -23932,10 +23924,11 @@ async function computePlan(target, fetch, { rotateSecrets = [] } = {}) {
23932
23924
  desired,
23933
23925
  intents,
23934
23926
  live,
23935
- changes
23927
+ changes,
23928
+ hashKey
23936
23929
  }),
23930
+ changes,
23937
23931
  environmentId,
23938
- secretValues: secretValues(desired, secrets),
23939
23932
  warnings: [
23940
23933
  ...[...configValidations, ...segmentValidations].filter((validation) => validation.severity === "warning"),
23941
23934
  ...validateVariantComponents({
@@ -23997,7 +23990,7 @@ function registerApply(program) {
23997
23990
  throw error;
23998
23991
  }
23999
23992
  }).addHelpText("after", examples([
24000
- ["hygraph apply --plan plan.json", "apply exactly that plan"],
23993
+ ["hygraph apply --plan plan.json", "apply the reviewed plan"],
24001
23994
  ["hygraph apply --plan plan.json --prune", "allow it to delete data"],
24002
23995
  ["hygraph apply", "re-plan and apply every target in one step"],
24003
23996
  ["hygraph apply --target uk --target de", "apply two targets of several"],
@@ -24093,13 +24086,11 @@ async function apply(config, options, write, writeErr) {
24093
24086
  async function prepare(target, { config, options, colors, planFiles, write }) {
24094
24087
  const file = planFiles?.get(target.name);
24095
24088
  const artifact = file === void 0 ? void 0 : readPlanFile(file);
24096
- if (artifact !== void 0) refuseUnsendableOAuthSecrets(unmaskSecrets(artifact.changes, oAuthSecretValues(oAuthSecrets(target.apply))));
24097
- const { plan: fresh, environmentId, secretValues, warnings } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
24098
- let plan = fresh;
24089
+ if (artifact !== void 0) refuseMissingOAuthSecrets(artifact.changes);
24090
+ const { plan, changes, environmentId, warnings } = await computePlan(target, void 0, { rotateSecrets: artifact ? sentOAuthSecrets(artifact.changes) : options.rotateSecret });
24099
24091
  if (file !== void 0 && artifact !== void 0) {
24100
- const refusals = verifyPlan(artifact, fresh);
24092
+ const refusals = verifyPlan(artifact, plan);
24101
24093
  if (refusals.length > 0) throw new ApplyFailure(renderRefusals(file, refusals));
24102
- plan = artifact;
24103
24094
  write(renderCheck("plan loaded", `${file} (planHash ${plan.planHash.slice(0, 12)})`, colors));
24104
24095
  write(renderCheck("desiredFingerprint matches", "config unchanged since planning", colors));
24105
24096
  write(renderCheck("liveFingerprint matches", "environment unchanged since planning", colors));
@@ -24113,35 +24104,34 @@ async function prepare(target, { config, options, colors, planFiles, write }) {
24113
24104
  if (warnings.length > 0) write(renderWarnings(warnings, colors));
24114
24105
  if (plan.changes.length === 0) return;
24115
24106
  if (plan.summary.destructive > 0 && options.prune !== true) throw new ApplyRefusal(renderDestructiveRefusal(plan.summary, colors));
24116
- refuseUnsendableOAuthSecrets(unmaskSecrets(plan.changes, secretValues));
24107
+ refuseMissingOAuthSecrets(changes);
24117
24108
  return {
24118
24109
  target,
24119
24110
  plan,
24120
- environmentId,
24121
- secretValues
24111
+ changes,
24112
+ environmentId
24122
24113
  };
24123
24114
  }
24124
24115
  /**
24125
- * A plan that needs an OAuth secret the config did not have, or had
24126
- * another one when it was planned, would send nothing or a hash. Hygraph
24127
- * would fail to sign in, so apply stops before it submits.
24116
+ * A plan that needs an OAuth secret the config did not have would send
24117
+ * nothing. Hygraph would fail to sign in, so apply stops before it submits.
24128
24118
  */
24129
- function refuseUnsendableOAuthSecrets(changes) {
24130
- const unsendable = unsendableOAuthSecrets(changes);
24131
- if (unsendable.length === 0) return;
24132
- 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"));
24119
+ function refuseMissingOAuthSecrets(changes) {
24120
+ const missing = missingOAuthSecrets(changes);
24121
+ if (missing.length === 0) return;
24122
+ throw new ApplyFailure(missing.map((prefix) => `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.`).join("\n"));
24133
24123
  }
24134
24124
  /**
24135
24125
  * Reads the target's live schema again just before its submit. With
24136
24126
  * several targets, the earlier migrations run between planning and here.
24137
24127
  */
24138
24128
  async function verifyLiveUnchanged({ target, plan }, { colors, write }) {
24139
- const { environment } = await readLiveEnvironment(target);
24140
- if (hashIR(environment) !== plan.liveFingerprint) throw new ApplyFailure(`${target.environment} changed after it was planned, so its migration was not submitted. Run apply again to plan it from its current schema.`);
24129
+ const { environment, hashKey } = await readLiveEnvironment(target);
24130
+ if (liveFingerprint(environment, hashKey) !== plan.liveFingerprint) throw new ApplyFailure(`${target.environment} changed after it was planned, so its migration was not submitted. Run apply again to plan it from its current schema.`);
24141
24131
  write(renderCheck("liveFingerprint matches", "environment unchanged since planning", colors));
24142
24132
  }
24143
24133
  /** Submits one target's migration and follows it to its end. */
24144
- async function execute({ target, plan, environmentId, secretValues }, { colors, write }) {
24134
+ async function execute({ target, plan, changes, environmentId }, { colors, write }) {
24145
24135
  const client = createManagementClient({
24146
24136
  endpoint: target.endpoint,
24147
24137
  token: target.token
@@ -24150,7 +24140,7 @@ async function execute({ target, plan, environmentId, secretValues }, { colors,
24150
24140
  const started = Date.now();
24151
24141
  const { id } = await submitMigration(client, target, toBatchMigrationInput({
24152
24142
  ...plan,
24153
- changes: unmaskSecrets(plan.changes, secretValues)
24143
+ changes
24154
24144
  }, {
24155
24145
  environmentId,
24156
24146
  name
@@ -24221,6 +24211,17 @@ async function formatSource(source) {
24221
24211
  function string(value) {
24222
24212
  return JSON.stringify(value);
24223
24213
  }
24214
+ /** The characters of Hygraph's apiId rule, without its length limit. */
24215
+ const NAME = /^[A-Z][A-Za-z0-9_]*$/;
24216
+ /**
24217
+ * A name in code, such as a const. Only an apiId made of the characters of
24218
+ * Hygraph's rule is written as one; anything else could be code, so it is
24219
+ * refused. `kind` names the value in the error.
24220
+ */
24221
+ function identifier(name, kind = "apiId") {
24222
+ if (!NAME.test(name)) throw new Failure(`${string(name)} is not a valid ${kind}, so it cannot name a const in the config.`);
24223
+ return name;
24224
+ }
24224
24225
  /** A template literal, for text that spans lines. Nothing in it is interpolated. */
24225
24226
  function template(value) {
24226
24227
  return `\`${value.replaceAll(/[\\`]|\$\{/g, (match) => `\\${match}`)}\``;
@@ -24284,7 +24285,7 @@ function oAuthSecretEnvName(prefix) {
24284
24285
  }
24285
24286
  /** The name of the const `printRemoteSource` declares. */
24286
24287
  function remoteSourceConstName(source) {
24287
- return `${source.prefix}RemoteSource`;
24288
+ return `${identifier(source.prefix, "remote source prefix")}RemoteSource`;
24288
24289
  }
24289
24290
  /**
24290
24291
  * Every header value is a read of the variable `headerEnvNames` names,
@@ -24343,7 +24344,7 @@ function printAssetModelField(field) {
24343
24344
  return printBuilder("assetReverseField", [
24344
24345
  ["apiId", string(field.apiId)],
24345
24346
  ["displayName", string(field.displayName)],
24346
- ["to", `() => ${field.to}`],
24347
+ ["to", `() => ${identifier(field.to)}`],
24347
24348
  ["reverse", string(field.reverse)],
24348
24349
  ["description", field.description === null ? void 0 : string(field.description)],
24349
24350
  ["visibility", field.visibility === "API_ONLY" ? void 0 : string(field.visibility)]
@@ -24364,7 +24365,7 @@ function printField(parent, field) {
24364
24365
  return printBuilder("enumeration", [
24365
24366
  apiId,
24366
24367
  displayName,
24367
- ["enumeration", field.enumeration],
24368
+ ["enumeration", identifier(field.enumeration)],
24368
24369
  ...options
24369
24370
  ]);
24370
24371
  }
@@ -24373,13 +24374,13 @@ function printField(parent, field) {
24373
24374
  return printBuilder("taxonomy", [
24374
24375
  apiId,
24375
24376
  displayName,
24376
- ["taxonomy", field.taxonomy],
24377
+ ["taxonomy", identifier(field.taxonomy)],
24377
24378
  ...options
24378
24379
  ]);
24379
24380
  }
24380
24381
  case "richText": return printBuilder(customOf("richText", field.formRenderer), [
24381
24382
  ...fieldOptions(field, FIELD_DEFAULTS),
24382
- ["embeds", field.embeds === null ? void 0 : `[${field.embeds.map((apiId) => `() => ${apiId}`).join(", ")}]`],
24383
+ ["embeds", field.embeds === null ? void 0 : `[${field.embeds.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`],
24383
24384
  ["actions", field.actions === null ? void 0 : `[${field.actions.map(string).join(", ")}]`],
24384
24385
  rendererOption(field.formRenderer)
24385
24386
  ]);
@@ -24399,16 +24400,16 @@ function printField(parent, field) {
24399
24400
  const [builder, defaults] = BUILDERS[formRenderer];
24400
24401
  return printBuilder(builder, [...fieldOptions(field, defaults), ...stringOptions(field)]);
24401
24402
  }
24402
- case "component": return printBuilder("component", referenceOptions(field, ["component", `() => ${field.component}`]));
24403
- case "componentUnion": return printBuilder("componentUnion", referenceOptions(field, ["components", `[${field.components.map((apiId) => `() => ${apiId}`).join(", ")}]`]));
24403
+ case "component": return printBuilder("component", referenceOptions(field, ["component", `() => ${identifier(field.component)}`]));
24404
+ case "componentUnion": return printBuilder("componentUnion", referenceOptions(field, ["components", `[${field.components.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`]));
24404
24405
  case "asset": return printBuilder(customOf("asset", field.formRenderer), [...referenceOptions(field, ["reverse", field.reverse === void 0 ? void 0 : string(field.reverse)]), rendererOption(field.formRenderer)]);
24405
24406
  case "referenceOneWay": return printBuilder(customOf("referenceOneWay", field.formRenderer), [
24406
- ...referenceOptions(field, ["to", `() => ${field.to}`]),
24407
+ ...referenceOptions(field, ["to", `() => ${identifier(field.to)}`]),
24407
24408
  ["rules", printRules(field.rules)],
24408
24409
  rendererOption(field.formRenderer)
24409
24410
  ]);
24410
24411
  case "referenceTwoWay": {
24411
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
24412
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${identifier(field.to)}`]);
24412
24413
  return printBuilder(customOf("referenceTwoWay", field.formRenderer), [
24413
24414
  apiId,
24414
24415
  displayName,
@@ -24420,7 +24421,7 @@ function printField(parent, field) {
24420
24421
  ]);
24421
24422
  }
24422
24423
  case "referenceUnion": {
24423
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `[${field.to.map((apiId) => `() => ${apiId}`).join(", ")}]`]);
24424
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `[${field.to.map((apiId) => `() => ${identifier(apiId)}`).join(", ")}]`]);
24424
24425
  return printBuilder("referenceUnion", [
24425
24426
  apiId,
24426
24427
  displayName,
@@ -24431,7 +24432,7 @@ function printField(parent, field) {
24431
24432
  ]);
24432
24433
  }
24433
24434
  case "referenceUnionMember": {
24434
- const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${field.to}`]);
24435
+ const [apiId, displayName, to, ...options] = referenceOptions(field, ["to", `() => ${identifier(field.to)}`]);
24435
24436
  return printBuilder("referenceUnionMember", [
24436
24437
  apiId,
24437
24438
  displayName,
@@ -24614,7 +24615,7 @@ function printRegex(regex) {
24614
24615
  * const. Attributes at their default are left out.
24615
24616
  */
24616
24617
  function printComponent(component) {
24617
- return `const ${component.apiId} = define.component(${object([
24618
+ return `const ${identifier(component.apiId)} = define.component(${object([
24618
24619
  ["apiId", string(component.apiId)],
24619
24620
  ["apiIdPlural", string(component.apiIdPlural)],
24620
24621
  ["displayName", string(component.displayName)],
@@ -24632,7 +24633,7 @@ function printComponent(component) {
24632
24633
  */
24633
24634
  function printEnumeration(enumeration) {
24634
24635
  const values = enumeration.values.map((value) => `{ apiId: ${string(value.apiId)}, displayName: ${string(value.displayName)} }`);
24635
- return `const ${enumeration.apiId} = define.enumeration(${object([
24636
+ return `const ${identifier(enumeration.apiId)} = define.enumeration(${object([
24636
24637
  ["apiId", string(enumeration.apiId)],
24637
24638
  ["displayName", string(enumeration.displayName)],
24638
24639
  ["description", enumeration.description === null ? void 0 : string(enumeration.description)],
@@ -24695,7 +24696,7 @@ function printPreviewUrls(urls) {
24695
24696
  * out, as is a sidebar the IR leaves to Hygraph.
24696
24697
  */
24697
24698
  function printModel(model) {
24698
- return `const ${model.apiId} = define.model(${object([
24699
+ return `const ${identifier(model.apiId)} = define.model(${object([
24699
24700
  ["apiId", string(model.apiId)],
24700
24701
  ["apiIdPlural", string(model.apiIdPlural)],
24701
24702
  ["displayName", string(model.displayName)],
@@ -24777,7 +24778,7 @@ function printTaxonomy(taxonomy) {
24777
24778
  ["children", `[${below.map(printNode).join(", ")}]`]
24778
24779
  ]);
24779
24780
  };
24780
- return `const ${taxonomy.apiId} = define.taxonomy(${object([
24781
+ return `const ${identifier(taxonomy.apiId)} = define.taxonomy(${object([
24781
24782
  ["apiId", string(taxonomy.apiId)],
24782
24783
  ["displayName", string(taxonomy.displayName)],
24783
24784
  ["description", taxonomy.description === null ? void 0 : string(taxonomy.description)],
@@ -24867,7 +24868,7 @@ async function printConfig(target, environment) {
24867
24868
  * when live has it.
24868
24869
  */
24869
24870
  function printEnvironment({ locales, stages, enumerations, taxonomies, remoteSources, components, models, asset, segment }) {
24870
- const list = (resources) => `[${resources.map((resource) => resource.apiId).join(", ")}]`;
24871
+ const list = (resources) => `[${resources.map((resource) => identifier(resource.apiId)).join(", ")}]`;
24871
24872
  return `const environment = define.environment({ ${[
24872
24873
  `locales: [${locales.map(printLocale).join(", ")}]`,
24873
24874
  `stages: [${stages.toSorted((a, b) => a.position - b.position).map(printStage).join(", ")}]`,
@@ -25454,7 +25455,7 @@ function createProgram() {
25454
25455
  program.addHelpText("after", examples([
25455
25456
  ["hygraph plan", "see what would change"],
25456
25457
  ["hygraph plan --out plan.json", "save the plan for review"],
25457
- ["hygraph apply --plan plan.json", "apply exactly that plan"],
25458
+ ["hygraph apply --plan plan.json", "apply the reviewed plan"],
25458
25459
  ["hygraph export --project <id> --endpoint <url>", "write a live environment to code"]
25459
25460
  ]));
25460
25461
  program.addHelpText("after", "\nRun `hygraph <command> --help` for options on a single command.");
package/dist/define.d.ts CHANGED
@@ -567,7 +567,7 @@ declare function component$1(input: ComponentInput): Component;
567
567
  * The options `componentUnion` takes. Hygraph stores a union as never
568
568
  * required, so it takes no `required`.
569
569
  */
570
- type ComponentUnionFieldInput = Omit<FieldInput, "required" | "visibility"> & {
570
+ type ComponentUnionFieldInput = Omit<FieldInput, "required"> & {
571
571
  /**
572
572
  * The components editors choose from, as `define.component` returns them,
573
573
  * each behind a function: `[() => Hero, () => Banner]`. At least one, and
@@ -582,12 +582,6 @@ type ComponentUnionFieldInput = Omit<FieldInput, "required" | "visibility"> & {
582
582
  * @default false
583
583
  */
584
584
  list?: boolean;
585
- /**
586
- * Cannot change once the field exists: changing it deletes the field and
587
- * its content.
588
- * @default "READ_WRITE"
589
- */
590
- visibility?: FieldVisibility;
591
585
  };
592
586
  /**
593
587
  * What `define.field.componentUnion` hands back: the input with every
package/dist/version.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region src/version.ts
2
- const VERSION = "0.0.15";
2
+ const VERSION = "0.0.17";
3
3
  //#endregion
4
4
  export { VERSION as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hygraph/cli",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "description": "Manage your Hygraph schema as code",
5
5
  "license": "MIT",
6
6
  "author": "Hygraph GmbH",