@firestartr/cli 2.11.0-snapshot-org-secrets-00 → 2.11.0-snapshot-patch-claims-4

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.
Files changed (30) hide show
  1. package/build/index.js +1475 -1881
  2. package/build/packages/cdk8s_renderer/imports/firestartr.dev.d.ts +0 -491
  3. package/build/packages/cdk8s_renderer/src/charts/github/index.d.ts +0 -1
  4. package/build/packages/cdk8s_renderer/src/charts/index.d.ts +1 -2
  5. package/build/packages/cdk8s_renderer/src/claims/base/schemas/index.d.ts +0 -89
  6. package/build/packages/cdk8s_renderer/src/claims/github/index.d.ts +0 -89
  7. package/build/packages/cdk8s_renderer/src/claims/github/orgSettings.d.ts +0 -20
  8. package/build/packages/cdk8s_renderer/src/claims/github/orgsettings.schema.d.ts +0 -24
  9. package/build/packages/cdk8s_renderer/src/claims/stitching/errors.d.ts +14 -0
  10. package/build/packages/cdk8s_renderer/src/claims/stitching/protectedPaths.d.ts +3 -0
  11. package/build/packages/cdk8s_renderer/src/claims/stitching/stitching.d.ts +20 -0
  12. package/build/packages/cdk8s_renderer/src/claims/stitching/validateFeatureDescriptors.d.ts +1 -0
  13. package/build/packages/cdk8s_renderer/src/overriders/featureOverride.d.ts +2 -11
  14. package/build/packages/cdk8s_renderer/src/renderer/claims-render.d.ts +1 -1
  15. package/build/packages/features_preparer/index.d.ts +3 -0
  16. package/build/packages/features_preparer/src/index.d.ts +5 -2
  17. package/build/packages/features_preparer/src/installer.d.ts +2 -0
  18. package/build/packages/features_preparer/src/renderer.d.ts +2 -0
  19. package/build/packages/features_renderer/index.d.ts +4 -1
  20. package/build/packages/features_renderer/src/auxiliar.d.ts +6 -3
  21. package/build/packages/features_renderer/src/render.d.ts +2 -1
  22. package/build/packages/features_renderer/src/schema.d.ts +7 -1
  23. package/build/packages/github/index.d.ts +1 -7
  24. package/package.json +1 -1
  25. package/build/packages/cdk8s_renderer/src/charts/github/orgSecretSectionChart.d.ts +0 -8
  26. package/build/packages/cdk8s_renderer/src/claims/github/orgSecrets.schema.d.ts +0 -67
  27. package/build/packages/cdk8s_renderer/src/validations/githubOrgSecretSection.d.ts +0 -4
  28. package/build/packages/gh_provisioner/src/entities/ghorgsecretsection/index.d.ts +0 -7
  29. package/build/packages/gh_provisioner/src/entities/ghorgsecretsection/secrets.d.ts +0 -16
  30. package/build/packages/github/src/orgSecrets.d.ts +0 -10
package/build/index.js CHANGED
@@ -128395,7 +128395,7 @@ function trasformLeg(leg) {
128395
128395
 
128396
128396
 
128397
128397
  function getFeatureRenderedPathForEntity(entity, featureName, basePath = '/tmp') {
128398
- const entityFolderName = `${entity.metadata.name}`.toLowerCase();
128398
+ const entityFolderName = `${entity.metadata?.name ?? entity.name}`.toLowerCase();
128399
128399
  return external_path_default().join(basePath, entityFolderName, featureName);
128400
128400
  }
128401
128401
  function getFeatureRenderedConfigForComponent(entity, featureName, basePath = '/tmp/features') {
@@ -128727,7 +128727,7 @@ function getCronNextInterval(cronLine, tz) {
128727
128727
 
128728
128728
  /***/ }),
128729
128729
 
128730
- /***/ 3342:
128730
+ /***/ 99029:
128731
128731
  /***/ ((__unused_webpack_module, __webpack_exports__, __nccwpck_require__) => {
128732
128732
 
128733
128733
  // ESM COMPAT FLAG
@@ -134407,66 +134407,6 @@ async function encryptRepoSecret(owner, repo, section, plaintextValue, octokit)
134407
134407
  }
134408
134408
  }
134409
134409
 
134410
- ;// CONCATENATED MODULE: ../github/src/orgSecrets.ts
134411
-
134412
-
134413
-
134414
- async function getOrgPublicKey(org, section, octokit) {
134415
- logger.info(`Retrieving org public key for ${org} (${section})`);
134416
- try {
134417
- if (!octokit) {
134418
- octokit = await getOctokitForOrg(org);
134419
- }
134420
- const { data } = await octokit.rest[`${section}`].getOrgPublicKey({
134421
- org,
134422
- });
134423
- return data;
134424
- }
134425
- catch (error) {
134426
- logger.error(`Error retrieving org public key (${section}) for ${org}: ${error}`);
134427
- throw error;
134428
- }
134429
- }
134430
- async function encryptOrgSecret(org, section, plaintextValue, preFetchedKey, octokit) {
134431
- try {
134432
- const { key_id, key } = preFetchedKey
134433
- ? preFetchedKey
134434
- : await getOrgPublicKey(org, section, octokit);
134435
- await libsodium_wrappers.ready;
134436
- const publicKey = libsodium_wrappers.from_base64(key, libsodium_wrappers.base64_variants.ORIGINAL);
134437
- const secretBytes = libsodium_wrappers.from_string(plaintextValue);
134438
- const encryptedBytes = libsodium_wrappers.crypto_box_seal(secretBytes, publicKey);
134439
- const encryptedValue = libsodium_wrappers.to_base64(encryptedBytes, libsodium_wrappers.base64_variants.ORIGINAL);
134440
- return {
134441
- key_id,
134442
- encrypted_value: encryptedValue,
134443
- };
134444
- }
134445
- catch (err) {
134446
- logger.error(`Error encrypting org secret (${section}) for ${org}: ${err}`);
134447
- throw err;
134448
- }
134449
- }
134450
- async function getOrgSecret(org, section, name, octokit) {
134451
- logger.info(`Checking org secret ${name} (${section}) for ${org}`);
134452
- try {
134453
- if (!octokit) {
134454
- octokit = await getOctokitForOrg(org);
134455
- }
134456
- const response = await octokit.rest[`${section}`].getOrgSecret({
134457
- org,
134458
- secret_name: name,
134459
- });
134460
- return response.data;
134461
- }
134462
- catch (err) {
134463
- if (err && err.status === 404) {
134464
- return null;
134465
- }
134466
- throw err;
134467
- }
134468
- }
134469
-
134470
134410
  ;// CONCATENATED MODULE: ../github/src/profile.ts
134471
134411
  // Profile definitions and store for github package (immutable and ambient profiles)
134472
134412
  const profileStore = new Map();
@@ -134901,7 +134841,6 @@ function withProfile(profileName) {
134901
134841
 
134902
134842
 
134903
134843
 
134904
-
134905
134844
  /* harmony default export */ const github = ({
134906
134845
  org: organization,
134907
134846
  repo: repository,
@@ -134924,9 +134863,6 @@ function withProfile(profileName) {
134924
134863
  encryption: {
134925
134864
  encryptRepoSecret: encryptRepoSecret,
134926
134865
  getRepoPublicKey: getRepoPublicKey,
134927
- getOrgPublicKey: getOrgPublicKey,
134928
- encryptOrgSecret: encryptOrgSecret,
134929
- getOrgSecret: getOrgSecret,
134930
134866
  },
134931
134867
  withProfile: withProfile,
134932
134868
  createProfile: createProfile,
@@ -159704,8 +159640,8 @@ var dist = __nccwpck_require__(44516);
159704
159640
  var dist_default = /*#__PURE__*/__nccwpck_require__.n(dist);
159705
159641
  // EXTERNAL MODULE: ../catalog_common/index.ts + 44 modules
159706
159642
  var catalog_common = __nccwpck_require__(78542);
159707
- // EXTERNAL MODULE: ../github/index.ts + 38 modules
159708
- var github = __nccwpck_require__(3342);
159643
+ // EXTERNAL MODULE: ../github/index.ts + 37 modules
159644
+ var github = __nccwpck_require__(99029);
159709
159645
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/patches/base.ts
159710
159646
  class BasePatches {
159711
159647
  constructor() { }
@@ -162566,31 +162502,6 @@ function extractAllRefs(claimData) {
162566
162502
  }
162567
162503
  }
162568
162504
  }
162569
- const orgSecrets = parsedClaim.providers?.github?.org_secrets;
162570
- if (orgSecrets && typeof orgSecrets === 'object') {
162571
- const secretRefRegex = /^ref:secretsclaim:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)$/;
162572
- for (const section of ['actions', 'codespaces', 'dependabot']) {
162573
- const secrets = orgSecrets[section];
162574
- if (!Array.isArray(secrets))
162575
- continue;
162576
- for (const secret of secrets) {
162577
- if (secret.value) {
162578
- const match = secret.value.match(secretRefRegex);
162579
- if (match) {
162580
- refs.push(`SecretsClaim-${match[1]}`);
162581
- }
162582
- }
162583
- if (Array.isArray(secret.selected_repositories)) {
162584
- for (const repoRef of secret.selected_repositories) {
162585
- const compMatch = repoRef.match(/^component:(.+)$/);
162586
- if (compMatch) {
162587
- refs.push(`ComponentClaim-${compMatch[1]}`);
162588
- }
162589
- }
162590
- }
162591
- }
162592
- }
162593
- }
162594
162505
  break;
162595
162506
  }
162596
162507
  }
@@ -163749,30 +163660,6 @@ const organizationSettingsProperties = {
163749
163660
  ],
163750
163661
  },
163751
163662
  },
163752
- org_secrets: {
163753
- type: 'object',
163754
- properties: {
163755
- actions: {
163756
- type: 'array',
163757
- items: {
163758
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
163759
- },
163760
- },
163761
- codespaces: {
163762
- type: 'array',
163763
- items: {
163764
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
163765
- },
163766
- },
163767
- dependabot: {
163768
- type: 'array',
163769
- items: {
163770
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
163771
- },
163772
- },
163773
- },
163774
- additionalProperties: false,
163775
- },
163776
163663
  };
163777
163664
  /* harmony default export */ const github_orgsettings_schema = ({
163778
163665
  $schema: SCHEMA,
@@ -163997,75 +163884,6 @@ const organizationSettingsProperties = {
163997
163884
  },
163998
163885
  });
163999
163886
 
164000
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/github/orgSecrets.schema.ts
164001
-
164002
- /* harmony default export */ const orgSecrets_schema = ({
164003
- $schema: SCHEMA,
164004
- $id: 'GithubOrgClaimSecrets',
164005
- definitions: {
164006
- GithubOrgClaimSecrets: {
164007
- $id: 'firestartr.dev://github/GithubOrgClaimSecrets',
164008
- type: 'object',
164009
- description: 'Organization-level GitHub Actions secrets',
164010
- properties: {
164011
- actions: {
164012
- type: 'array',
164013
- items: {
164014
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
164015
- },
164016
- },
164017
- codespaces: {
164018
- type: 'array',
164019
- items: {
164020
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
164021
- },
164022
- },
164023
- dependabot: {
164024
- type: 'array',
164025
- items: {
164026
- $ref: 'firestartr.dev://github/GithubOrgClaimSecret',
164027
- },
164028
- },
164029
- },
164030
- additionalProperties: false,
164031
- },
164032
- GithubOrgClaimSecretRef: {
164033
- $id: 'firestartr.dev://github/GithubOrgClaimSecretRef',
164034
- type: 'string',
164035
- description: 'the reference of the secret',
164036
- pattern: '^ref:secretsclaim:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)$',
164037
- },
164038
- GithubOrgClaimSecret: {
164039
- $id: 'firestartr.dev://github/GithubOrgClaimSecret',
164040
- type: 'object',
164041
- description: 'An organization-level secret for GitHub Actions',
164042
- properties: {
164043
- name: {
164044
- type: 'string',
164045
- description: 'the name of the secret',
164046
- },
164047
- value: {
164048
- $ref: 'firestartr.dev://github/GithubOrgClaimSecretRef',
164049
- },
164050
- visibility: {
164051
- type: 'string',
164052
- enum: ['all', 'selected', 'private'],
164053
- description: 'which repositories can access the secret',
164054
- },
164055
- selected_repositories: {
164056
- type: 'array',
164057
- items: {
164058
- type: 'string',
164059
- },
164060
- description: 'list of repository refs when visibility is selected',
164061
- },
164062
- },
164063
- required: ['name', 'value'],
164064
- additionalProperties: false,
164065
- },
164066
- },
164067
- });
164068
-
164069
163887
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/github/index.ts
164070
163888
 
164071
163889
 
@@ -164076,7 +163894,6 @@ const organizationSettingsProperties = {
164076
163894
 
164077
163895
 
164078
163896
 
164079
-
164080
163897
  const GithubSchemas = [
164081
163898
  github_group_schema,
164082
163899
  github_user_schema,
@@ -164087,7 +163904,6 @@ const GithubSchemas = [
164087
163904
  component_secrets_vars_schema,
164088
163905
  component_labels_schema,
164089
163906
  pages_schema,
164090
- orgSecrets_schema,
164091
163907
  ];
164092
163908
 
164093
163909
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/tfworkspaces/terraform.schema.ts
@@ -164734,771 +164550,6 @@ const base_secrets_schema = 'firestartr.dev://common/SecretsClaim';
164734
164550
  SecretsClaimSchema: base_secrets_schema,
164735
164551
  });
164736
164552
 
164737
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/lazy_loader.ts
164738
-
164739
-
164740
-
164741
-
164742
-
164743
-
164744
-
164745
-
164746
-
164747
-
164748
-
164749
-
164750
-
164751
-
164752
-
164753
-
164754
- // We need to ensure the grep command is a gnu version
164755
- let IS_GNU_GREP = false;
164756
- let GREP_ON_CHECK = false;
164757
- // this loop is for avoid race conditions
164758
- // once a check is running no more checks
164759
- async function waitForCheck() {
164760
- const f_wait = () => new Promise((timeOut) => setTimeout(timeOut, 10));
164761
- do {
164762
- await f_wait();
164763
- } while (GREP_ON_CHECK);
164764
- }
164765
- function checkGrep() {
164766
- return new Promise((ok, ko) => {
164767
- // idempotency: already checked
164768
- if (IS_GNU_GREP)
164769
- return ok();
164770
- // a check is already running no new checks
164771
- if (GREP_ON_CHECK)
164772
- return waitForCheck();
164773
- logger.info('Checking the grep command');
164774
- GREP_ON_CHECK = true;
164775
- const handler = (0,external_node_child_process_namespaceObject.spawn)('grep', ['--version']);
164776
- handler.on('close', (code) => {
164777
- GREP_ON_CHECK = false;
164778
- if (code === 0) {
164779
- logger.debug('Grep is a gnu grep');
164780
- IS_GNU_GREP = true;
164781
- ok();
164782
- }
164783
- else {
164784
- ko('Lazy evaluation needs a gnu-grep command');
164785
- }
164786
- });
164787
- });
164788
- }
164789
- async function loadClaim(claimRef, org, defaults = loadClaimDefaults(), patchClaim = loader_patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, existingRefs = {}, postValidations = new Map()) {
164790
- await checkGrep();
164791
- let result = existingRefs;
164792
- logger.info(`Load reference ${claimRef}`);
164793
- initVirtualClaims(org);
164794
- logger.info(`Load reference (parts) ${claimRef.split(/-/)[0]} ${claimRef.replace(/^[^-]+-/, '')}`);
164795
- // cargas datos con grep
164796
- try {
164797
- const claimData = await lazyGetClaim(claimRef.split(/-/)[0], claimRef.replace(/^[^-]+-/, ''), org, cwd);
164798
- const claim = patchClaim(catalog_common/* default.io.fromYaml */.Z.io.fromYaml(claimData), defaults);
164799
- let variants = [];
164800
- if (claim.kind === 'TFWorkspaceClaim' &&
164801
- claim.providers?.terraform?.variants) {
164802
- variants = claim.providers.terraform.variants;
164803
- delete claim.providers.terraform.variants;
164804
- }
164805
- logger.silly(`Patched claim is:
164806
- ---
164807
- ${catalog_common/* default.io.toYaml */.Z.io.toYaml(claim)}`);
164808
- try {
164809
- validateClaim(claim, base[`${claim.kind}Schema`]);
164810
- await optionalValidation(claim);
164811
- }
164812
- catch (error) {
164813
- let errorMsg = '';
164814
- if (Array.isArray(error)) {
164815
- for (const data of error) {
164816
- errorMsg = `${errorMsg}
164817
- - ${data.instancePath}: ${data.message}`;
164818
- }
164819
- }
164820
- else {
164821
- errorMsg = error instanceof Error ? error.message : String(error);
164822
- }
164823
- throw new Error(`Error when validating claim ${claimRef}: ${errorMsg}`);
164824
- }
164825
- result[claimRef] = {};
164826
- result[claimRef]['claim'] = claim;
164827
- result[claimRef]['claimPath'] = VisitedClaims[claimRef];
164828
- if (VisitedClaims[claimRef] === 'virtual') {
164829
- result = await setVirtualClaimAdditionalData(result, claim, claimRef);
164830
- }
164831
- else {
164832
- result = await setNonVirtualClaimAdditionalData(result, claim, claimRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers);
164833
- }
164834
- const claimKind = claim.kind;
164835
- const references = extractAllRefs(catalog_common/* default.io.toYaml */.Z.io.toYaml(claim));
164836
- for (const ref of references) {
164837
- if (!result[ref]) {
164838
- const [resolvedReferences] = await loadClaim(ref, org, defaults, patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, result, postValidations);
164839
- result = lodash_default().merge(result, resolvedReferences);
164840
- }
164841
- }
164842
- if (variants.length > 0) {
164843
- const parentClaimPath = VisitedClaims[claimRef];
164844
- for (const variant of variants) {
164845
- if (!variant.name || !variant.overrides) {
164846
- throw new Error(`Variant in claim ${claimRef} is missing required field 'name' or 'overrides'`);
164847
- }
164848
- const prohibitedOverrideFields = ['source', 'module', 'name'];
164849
- for (const field of prohibitedOverrideFields) {
164850
- if (field in variant.overrides) {
164851
- throw new Error(`Variant '${variant.name}' in claim ${claimRef} cannot override '${field}'`);
164852
- }
164853
- }
164854
- const composedName = claim.providers.terraform.name + '-' + variant.name;
164855
- const variantClaim = lodash_default().cloneDeep(claim);
164856
- variantClaim._parentClaimName = claim.name;
164857
- variantClaim.name = composedName;
164858
- variantClaim.providers.terraform = lodash_default().merge({}, claim.providers.terraform, variant.overrides);
164859
- variantClaim.providers.terraform.name = composedName;
164860
- if (!variantClaim.annotations) {
164861
- variantClaim.annotations = {};
164862
- }
164863
- variantClaim.annotations['firestartr.dev/variant-of'] =
164864
- claim.providers.terraform.name;
164865
- const variantRef = `TFWorkspaceClaim-${composedName}`;
164866
- if (result[variantRef]) {
164867
- throw new Error(`Variant name '${variant.name}' (composed: '${composedName}') from claim '${claimRef}' conflicts with existing claim '${variantRef}'`);
164868
- }
164869
- logger.info(`Creating synthetic variant claim ${variantRef}`);
164870
- result[variantRef] = {};
164871
- result[variantRef]['claim'] = variantClaim;
164872
- result[variantRef]['claimPath'] = parentClaimPath;
164873
- result = await setNonVirtualClaimAdditionalData(result, variantClaim, variantRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers);
164874
- const variantReferences = extractAllRefs(catalog_common/* default.io.toYaml */.Z.io.toYaml(variantClaim));
164875
- for (const ref of variantReferences) {
164876
- if (!result[ref]) {
164877
- const [resolvedReferences] = await loadClaim(ref, org, defaults, patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, result, postValidations);
164878
- result = lodash_default().merge(result, resolvedReferences);
164879
- }
164880
- }
164881
- }
164882
- }
164883
- }
164884
- catch (err) {
164885
- throw `Lazy Loading: ${err}`;
164886
- }
164887
- return [result, postValidations];
164888
- }
164889
- let LoadedClaims = {};
164890
- let VisitedClaims = {};
164891
- let DuplicatedClaims = {};
164892
- function resetLazyLoader() {
164893
- LoadedClaims = {};
164894
- VisitedClaims = {};
164895
- DuplicatedClaims = {};
164896
- }
164897
- async function lazyGetClaim(kind, name, org, cwd) {
164898
- const indice = `${kind}-${name}`;
164899
- logger.info(`Lazy loading ${kind}-${name} with index ${indice}`);
164900
- if (indice in LoadedClaims)
164901
- return LoadedClaims[indice];
164902
- if (isVirtualClaim(kind, name)) {
164903
- await loadVirtualClaim(kind, name, org);
164904
- }
164905
- else {
164906
- await getClaimsByName(name, cwd);
164907
- }
164908
- if (indice in LoadedClaims) {
164909
- return LoadedClaims[indice];
164910
- }
164911
- else {
164912
- throw new Error(`Error: ${kind}-${name} not found`);
164913
- }
164914
- }
164915
- async function getClaimsByName(name, cwd = '.') {
164916
- return new Promise((ok, ko) => {
164917
- const handler = (0,external_node_child_process_namespaceObject.spawn)('grep', ['-r', '-l', '--include=*', '-E', `name: "?${name}"?`, '.'], {
164918
- cwd: cwd,
164919
- });
164920
- logger.info(`Running ${['grep', '-r', '-l', '--include', '-E', 'name: "' + name + '"?', '.'].join(' ')}`);
164921
- const entradas = [];
164922
- const chunks = [];
164923
- handler.stdout.on('data', (data) => {
164924
- chunks.push(data.toString('utf-8'));
164925
- });
164926
- handler.on('close', () => {
164927
- const dataFinal = chunks.join('');
164928
- const fileNameList = dataFinal.split(/\n/).filter((line) => line !== '');
164929
- for (const fileName of fileNameList) {
164930
- // only yaml files
164931
- if (!fileName.match(/\.yml$|\.yaml$/)) {
164932
- continue;
164933
- }
164934
- // only entries not already visited
164935
- if (Object.values(VisitedClaims).includes(fileName)) {
164936
- continue;
164937
- }
164938
- entradas.push(external_path_.join(cwd, fileName));
164939
- }
164940
- return Promise.all(entradas.map((entrada) => {
164941
- return loadRawClaim(entrada);
164942
- }))
164943
- .then(() => {
164944
- ok();
164945
- })
164946
- .catch((err) => {
164947
- ko(err);
164948
- });
164949
- });
164950
- });
164951
- }
164952
- async function loadRawClaim(entry) {
164953
- return new Promise((ok, ko) => {
164954
- external_fs_.readFile(entry, 'utf-8', (error, data) => {
164955
- if (error)
164956
- return ko(`Reading ${entry}: ${error}`);
164957
- const claim = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
164958
- if (!('kind' in claim && 'name' in claim)) {
164959
- logger.warn(`Invalid claim file ${entry}`);
164960
- }
164961
- else {
164962
- const claimKey = `${claim.kind}-${claim.name}`;
164963
- if (Object.keys(DuplicatedClaims).includes(claimKey) &&
164964
- DuplicatedClaims[claimKey] !== entry) {
164965
- return ko(`Duplicated claim ${claimKey} found files: ${DuplicatedClaims[claimKey]} and ${entry}`);
164966
- }
164967
- LoadedClaims[claimKey] = data;
164968
- VisitedClaims[claimKey] = entry;
164969
- DuplicatedClaims[claimKey] = entry;
164970
- ok();
164971
- }
164972
- });
164973
- });
164974
- }
164975
- async function setVirtualClaimAdditionalData(renderedData, claim, claimRef) {
164976
- const virtualClaim = getVirtualClaim(claim.kind, claim.name);
164977
- renderedData[claimRef]['initializers'] = [
164978
- new UUIDInitializer(claim),
164979
- new InitializerClaimRef(),
164980
- new InitializerDefault(virtualClaim.getDefaultConfig()),
164981
- ];
164982
- renderedData[claimRef]['globals'] = [];
164983
- renderedData[claimRef]['overrides'] = [];
164984
- renderedData[claimRef]['normalizers'] = [new NameNormalizer()];
164985
- return renderedData;
164986
- }
164987
- async function setNonVirtualClaimAdditionalData(renderedData, claim, claimRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers) {
164988
- renderedData[claimRef]['initializers'] = await loadInitializers(claim, renderedData[claimRef]['claimPath']);
164989
- renderedData[claimRef]['globals'] = await loadGlobals(claim);
164990
- renderedData[claimRef]['overrides'] = loadOverrides(claim);
164991
- renderedData[claimRef]['normalizers'] = await loadNormalizers(claim, renderedData[claimRef]['claimPath']);
164992
- return renderedData;
164993
- }
164994
- async function loadVirtualClaim(kind, name, org) {
164995
- const virtualClaim = getVirtualClaim(kind, name);
164996
- const expandedClaim = await virtualClaim.expand({ org });
164997
- logger.info(`Loading virtual claim ${kind} ${name} ${org}`);
164998
- LoadedClaims[`${kind}-${name}`] = catalog_common/* default.io.toYaml */.Z.io.toYaml(expandedClaim);
164999
- VisitedClaims[`${kind}-${name}`] = 'virtual';
165000
- }
165001
-
165002
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/claimsDefaulter.ts
165003
-
165004
-
165005
-
165006
- /*
165007
- * Default blocks are objects that cannot be merged but applied as a whole. Meaning:
165008
- * - If the object is defined at the claim-level it is maintained *AS IT IS* (no merge)
165009
- * - If the block is missing at the claim-level, the default block is applied
165010
- */
165011
- const defaultBlocksPaths = ['/providers/terraform/sync'];
165012
- function applyBlockAwareDefaults(claim, defaultClaim) {
165013
- // we always work with a clone of the original
165014
- const claimClone = JSON.parse(JSON.stringify(claim));
165015
- // if the block is claim-level defined we store it here
165016
- const defaultBlocks = new Map();
165017
- // we remove the blocks entirely of the claim
165018
- // to achieve an add copy
165019
- for (const defaultBlockPath of defaultBlocksPaths) {
165020
- if (claimsDefaulter_hasDeepPath(claimClone, defaultBlockPath) !== true)
165021
- continue;
165022
- const originalValue = fast_json_patch_default().getValueByPointer(claimClone, defaultBlockPath);
165023
- if (originalValue) {
165024
- logger.silly(`${claim.kind}/${claim.name}: has an original ${defaultBlockPath}: preserving`);
165025
- defaultBlocks.set(defaultBlockPath, originalValue);
165026
- fast_json_patch_default().applyPatch(claimClone, [{ op: 'remove', path: defaultBlockPath }]);
165027
- }
165028
- }
165029
- // if the patch has the same path of a block
165030
- // and the block was defined at claim-level
165031
- // we interchange the value with the original value
165032
- // otherwise we use the default
165033
- const jsonPatchOps = fast_json_patch_default().compare(claimClone, defaultClaim)
165034
- .filter((jp) => jp.op === 'add')
165035
- .map((jp) => {
165036
- if (defaultBlocks.has(jp.path)) {
165037
- return {
165038
- ...jp,
165039
- value: defaultBlocks.get(jp.path),
165040
- };
165041
- }
165042
- else {
165043
- return jp;
165044
- }
165045
- });
165046
- return fast_json_patch_default().applyPatch(claimClone, jsonPatchOps).newDocument;
165047
- }
165048
- function claimsDefaulter_hasDeepPath(data, deepPath) {
165049
- return lodash_default().has(data, deepPath.replace(/\//g, '.').replace(/^\./, ''));
165050
- }
165051
-
165052
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/loader.ts
165053
-
165054
-
165055
-
165056
-
165057
-
165058
-
165059
-
165060
-
165061
-
165062
-
165063
-
165064
-
165065
-
165066
-
165067
-
165068
- const isYamlFile = new RegExp(/\.(yaml|yml)$/);
165069
- /**
165070
- *
165071
- * @returns Virtual Claims
165072
- */
165073
- const virtualClaims = [new FirestartrAllClaim()];
165074
- /*
165075
- * Loads all applicable globals for a given claim and stores them into a list.
165076
- *
165077
- * Input:
165078
- * - claim: our custom claim object, with which we check if the global is applicable
165079
- *
165080
- * Returns:
165081
- * - A GlobalSection array promise, containing all the globals loaded for this claim
165082
- *
165083
- */
165084
- async function loadGlobals(claim) {
165085
- const result = [];
165086
- await crawl(getPath('globals'), (entry) => {
165087
- return isYamlFile.test(entry);
165088
- }, async (entry, data) => {
165089
- const globalData = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
165090
- const ext = external_path_.extname(entry);
165091
- const name = external_path_.basename(entry, ext);
165092
- if (name in SECTIONS_BY_FILE_NAME) {
165093
- const section = new SECTIONS_BY_FILE_NAME[name](globalData);
165094
- if (!(await section.validate(SCHEMAS_BY_SECTION_NAME[name] || {}))) {
165095
- throw new Error(`Invalid ${name} global file`);
165096
- }
165097
- if (globalData.kind === claim.kind) {
165098
- result.push(section);
165099
- }
165100
- else {
165101
- logger.debug(`Skipping global ${name} because it is not applicable to ${claim.kind}`);
165102
- }
165103
- }
165104
- });
165105
- logger.info(`Loaded globals ${result}`);
165106
- return result;
165107
- }
165108
- /*
165109
- * If the input claim is a GithubRepositoryClaim, it loads all it's applicable
165110
- * overrides and stores them into a list. Otherwise, it returns an empty list.
165111
- *
165112
- * Input:
165113
- * - claim: our custom claim object, which should be a GithubRepositoryClaim
165114
- *
165115
- * Returns:
165116
- * - An Overrider array, with a GithubRepositoryOverrider if the claim
165117
- * was a GithubRepositoryClaim, or empty if it was not.
165118
- *
165119
- */
165120
- function loadOverrides(claim) {
165121
- const overrides = [];
165122
- if (claim.kind === 'ComponentClaim' && claim.providers.github.overrides) {
165123
- overrides.push(new GithubRepositoryOverrider());
165124
- }
165125
- return overrides;
165126
- }
165127
- /**
165128
- * Load all normalizers and stores them into a list.
165129
- * @param claim
165130
- * @returns
165131
- */
165132
- async function loadNormalizers(_claim, path) {
165133
- const result = [];
165134
- for (const normalizer of NORMALIZERS) {
165135
- result.push(new normalizer({ path: path }));
165136
- }
165137
- return result;
165138
- }
165139
- /*
165140
- * Loads all applicable initializers for a given claim and stores them into a list.
165141
- *
165142
- * Input:
165143
- * - claim: our custom claim object, with which we check if the initializer is applicable
165144
- *
165145
- * Returns:
165146
- * - An Initializer array promise, containing all the initializers loaded for this claim
165147
- *
165148
- */
165149
- let loadedInitializers = false;
165150
- async function loadInitializers(claim, claimPath, initializersPath = getPath('initializers')) {
165151
- const result = [];
165152
- await crawl(initializersPath, (entry) => {
165153
- return isYamlFile.test(entry);
165154
- }, async (entry, data) => {
165155
- const initializerData = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
165156
- const ext = external_path_.extname(entry);
165157
- const name = external_path_.basename(entry, ext);
165158
- if (name in INITIALIZERS_BY_FILE_NAME) {
165159
- const initializerBfN = new INITIALIZERS_BY_FILE_NAME[name](initializerData);
165160
- if (!(await initializerBfN.validate(SCHEMAS_BY_INITIALIZER_NAME[name] || {}))) {
165161
- throw new Error(`Invalid ${name} initializer file`);
165162
- }
165163
- if (initializerData.kind === claim.kind) {
165164
- result.push(initializerBfN);
165165
- }
165166
- else {
165167
- logger.debug(`Skipping initializer ${name} because it is not applicable to ${claim.kind}`);
165168
- }
165169
- }
165170
- });
165171
- for (const initializer of INITIALIZERS) {
165172
- if (initializer.applicableKinds.includes(claim.kind)) {
165173
- result.push(new initializer({ path: claimPath }));
165174
- }
165175
- }
165176
- logger.info(`Loaded initializers ${JSON.stringify(result)}`);
165177
- loadedInitializers = result;
165178
- return loadedInitializers;
165179
- }
165180
- function loadClaimDefaults() {
165181
- try {
165182
- return catalog_common/* default.io.fromYaml */.Z.io.fromYaml(external_fs_.readFileSync(`${getPath('claimsDefaults')}/claims_defaults.yaml`, 'utf-8'));
165183
- }
165184
- catch (error) {
165185
- const errMsg = `Could not read claims defaults file in path ${getPath('claimsDefaults')}/claims_defaults.yaml: ${error}`;
165186
- logger.error(errMsg);
165187
- throw new Error(errMsg);
165188
- }
165189
- }
165190
- /*
165191
- * Using fast-json-patch, compares a claim to its kind's defaults, then patches it.
165192
- *
165193
- * Input:
165194
- * - claim: our custom claim object, which we want to patch
165195
- * - defaultsClaims: an object, containing the defaults for each claim kind,
165196
- * with the same structure that we use for the actual claims
165197
- *
165198
- * Returns:
165199
- * - The patched claim
165200
- *
165201
- */
165202
- function loader_patchClaim(claim, defaultsClaims) {
165203
- if (defaultsClaims[claim.kind]) {
165204
- claim = applyBlockAwareDefaults(claim, defaultsClaims[claim.kind]);
165205
- }
165206
- return claim;
165207
- }
165208
- async function loadCRsWithFullSet(crsPath = getPath('crs'), excludedPaths = [getPath('globals'), getPath('initializers')], allowedClaimReferences = []) {
165209
- const result = {};
165210
- const fullResult = {};
165211
- await crawlWithExclusions(crsPath, (entry) => {
165212
- return isYamlFile.test(entry);
165213
- }, async (entry, data) => {
165214
- const yamlData = stripKnownRelations(catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data));
165215
- const metadata = yamlData?.metadata;
165216
- if (!(yamlData &&
165217
- typeof yamlData === 'object' &&
165218
- 'kind' in yamlData &&
165219
- metadata &&
165220
- typeof metadata === 'object' &&
165221
- 'name' in metadata)) {
165222
- logger.warn(`Invalid CR file ${entry}`);
165223
- }
165224
- else {
165225
- const crKey = `${yamlData.kind}-${metadata.name}`;
165226
- if (fullResult[crKey]) {
165227
- logger.error(`Duplicate CR ${crKey}`);
165228
- }
165229
- // Keep the complete CR set for validations that need repository-wide context.
165230
- fullResult[crKey] = yamlData;
165231
- // Keep the filtered CR set for previous-CR lookup during claim rendering.
165232
- if (allowedClaimReferences.length === 0 ||
165233
- allowedClaimReferences.includes(yamlData.metadata?.annotations?.[catalog_common/* default.generic.getFirestartrAnnotation */.Z.generic.getFirestartrAnnotation('claim-ref')])) {
165234
- result[crKey] = yamlData;
165235
- }
165236
- }
165237
- }, excludedPaths.concat(getAdditionalPaths()));
165238
- return { crs: result, fullCrs: fullResult };
165239
- }
165240
- async function loadCRs(crsPath = getPath('crs'), excludedPaths = [getPath('globals'), getPath('initializers')], allowedClaimReferences = []) {
165241
- const { crs } = await loadCRsWithFullSet(crsPath, excludedPaths, allowedClaimReferences);
165242
- return crs;
165243
- }
165244
- /*
165245
- * Description: Get the renamed using claimRef annotation
165246
- * Input: claims: any, crs: any
165247
- * Output: renames: IRenameResult[]
165248
- */
165249
- async function loadRenames(claims, crs) {
165250
- /*
165251
- * If checkRenames is false, we don't need to check for renames
165252
- */
165253
- const renamesEnabled = getRenamesEnabled();
165254
- if (!renamesEnabled)
165255
- return [];
165256
- const result = [];
165257
- /**
165258
- * For each CR, look for a claim that does not match the name with CR's firestartr.dev/claim-ref annotation
165259
- */
165260
- for (const cr of Object.values(crs)) {
165261
- const anyCr = cr;
165262
- if (!anyCr?.metadata?.annotations)
165263
- continue;
165264
- // if the annotation is a claimRef
165265
- const annotationName = common.generic.getFirestartrAnnotation('claim-ref');
165266
- const annotations = anyCr?.metadata?.annotations || {};
165267
- if (annotationName in annotations) {
165268
- const claimRef = anyCr.metadata.annotations[annotationName];
165269
- // split the annotation into kind and name
165270
- const [kind, name] = claimRef.split('/');
165271
- // if the claim exists, check if the name is different for the given provider
165272
- const referencedClaim = claims[`${kind}-${name}`].claim;
165273
- const oldName = anyCr.metadata.name;
165274
- const newName = referencedClaim.providers[getConfiguredProvider()].name;
165275
- if (oldName !== newName) {
165276
- result.push({
165277
- kind: referencedClaim.kind,
165278
- claimPath: claims[`${kind}-${name}`].claimPath,
165279
- claimName: referencedClaim.name,
165280
- oldName,
165281
- newName,
165282
- });
165283
- }
165284
- }
165285
- }
165286
- return result;
165287
- }
165288
- async function loadClaimsList(claimRefList, claimsPath = getPath('claims')) {
165289
- const data = {
165290
- renderClaims: {},
165291
- crs: {},
165292
- fullCrs: {},
165293
- };
165294
- const defaults = loadClaimDefaults();
165295
- for await (const claimRef of claimRefList) {
165296
- const [renderedClaimData] = await loadClaim(claimRef, getOrg(), defaults, loader_patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, claimsPath);
165297
- data.renderClaims = lodash_default().merge(data.renderClaims, renderedClaimData);
165298
- }
165299
- const crClaimReferences = [];
165300
- for (const ref of Object.keys(data.renderClaims)) {
165301
- // Replaces only the first instance of '-'
165302
- crClaimReferences.push(ref.replace('-', '/'));
165303
- }
165304
- const loadedCrs = await loadCRsWithFullSet(getPath('crs'), [getPath('globals'), getPath('initializers')], crClaimReferences);
165305
- data['crs'] = loadedCrs.crs;
165306
- data['fullCrs'] = loadedCrs.fullCrs;
165307
- return data;
165308
- }
165309
- function getOrg() {
165310
- const groupOrg = catalog_common/* default.environment.getFromEnvironmentWithDefault */.Z.environment.getFromEnvironmentWithDefault(catalog_common/* default.types.envVars.org */.Z.types.envVars.org, '');
165311
- return groupOrg;
165312
- }
165313
-
165314
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/references.ts
165315
- function validateTfStateKeyUniqueness(crs) {
165316
- const tfStateKeys = {};
165317
- for (const crKey of Object.keys(crs)) {
165318
- const cr = crs[crKey];
165319
- if (!isTerraformWorkspace(cr))
165320
- continue;
165321
- const tfKey = cr.spec.firestartr.tfStateKey;
165322
- if (tfStateKeys[tfKey]) {
165323
- throw new Error(`❗❗ ❌ RENDER ERROR ❌ ❗❗
165324
-
165325
- The tfStateKey ${tfKey} is not unique,
165326
-
165327
- It is being used by the following CRs:
165328
-
165329
- - ${tfStateKeys[tfKey].kind} ${tfStateKeys[tfKey].metadata.name}
165330
-
165331
- - ${cr.kind} ${cr.metadata.name}
165332
-
165333
- Check the following Claims to ensure that the tfStateKey is unique:
165334
-
165335
- - ${tfStateKeys[tfKey].metadata.annotations['firestartr.dev/claim-ref']}
165336
-
165337
- - ${cr.metadata.annotations['firestartr.dev/claim-ref']}
165338
- `);
165339
- }
165340
- tfStateKeys[cr.spec.firestartr.tfStateKey] = cr;
165341
- }
165342
- }
165343
- function references_isCatalogEntity(cr) {
165344
- return [
165345
- 'Component',
165346
- 'Domain',
165347
- 'System',
165348
- 'User',
165349
- 'Group',
165350
- 'Resource',
165351
- ].includes(cr.kind);
165352
- }
165353
- function isTerraformWorkspace(cr) {
165354
- return cr.kind === 'FirestartrTerraformWorkspace';
165355
- }
165356
-
165357
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/crSize.ts
165358
-
165359
- const K8S_OBJECT_SIZE_LIMIT = 1572864; // 1.5 MiB in bytes, etcd recommended limit: https://etcd.io/docs/latest/dev-guide/limit/
165360
- function validateCrSizes(crs) {
165361
- for (const key of Object.keys(crs)) {
165362
- const cr = crs[key];
165363
- const serialized = catalog_common/* default.io.toYaml */.Z.io.toYaml(cr);
165364
- const size = Buffer.byteLength(serialized, 'utf8');
165365
- if (size > K8S_OBJECT_SIZE_LIMIT) {
165366
- throw new Error(`CR "${cr.kind}-${cr.metadata.name}" exceeds the Kubernetes object size limit by ${size - K8S_OBJECT_SIZE_LIMIT} bytes. Maximum allowed is ${K8S_OBJECT_SIZE_LIMIT} bytes (1.5MiB).`);
165367
- }
165368
- }
165369
- }
165370
-
165371
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/permissions.ts
165372
-
165373
- function validatePermissionsUniqueness(crs) {
165374
- for (const crkey in crs) {
165375
- const cr = crs[crkey];
165376
- if (cr.kind === 'FirestartrGithubRepository') {
165377
- const permissions = cr.spec.permissions;
165378
- logger.debug(`Validating Permissions Uniqueness of ${crkey}`);
165379
- if (permissions) {
165380
- const rolesByIdentifier = new Map();
165381
- for (const perm of permissions) {
165382
- const identifier = perm.collaborator
165383
- ? perm.collaborator
165384
- : `ref:${perm.ref.kind}:${perm.ref.name}`;
165385
- const role = perm.role;
165386
- const prevRole = rolesByIdentifier.get(identifier);
165387
- if (prevRole === undefined) {
165388
- rolesByIdentifier.set(identifier, role);
165389
- }
165390
- else if (prevRole !== role) {
165391
- throw new Error(`Conflicting permission role in FirestartrGithubRepository ${crkey}: ${identifier} has roles "${prevRole}" and "${role}".\nFull CR: ${JSON.stringify(cr, null, 2)}`);
165392
- }
165393
- }
165394
- }
165395
- }
165396
- }
165397
- }
165398
-
165399
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/backstageAnnotations.ts
165400
- const backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX = 'firestartr.backstage.dev/';
165401
- const CATALOG_KINDS = new Set([
165402
- 'User',
165403
- 'Group',
165404
- 'Component',
165405
- 'System',
165406
- 'Domain',
165407
- 'API',
165408
- 'Resource',
165409
- 'CatalogKubernetesResource',
165410
- 'CatalogTerraformWorkspace',
165411
- 'CatalogArgoDeploy',
165412
- 'CatalogOrgWebhook',
165413
- 'CatalogSecrets',
165414
- ]);
165415
- function validateNoBackstageAnnotationsInK8sCrs(crs) {
165416
- for (const crKey in crs) {
165417
- const cr = crs[crKey];
165418
- if (CATALOG_KINDS.has(cr.kind))
165419
- continue;
165420
- if (cr.metadata?.annotations) {
165421
- const backstageKeys = Object.keys(cr.metadata.annotations).filter((k) => k.startsWith(backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX));
165422
- if (backstageKeys.length > 0) {
165423
- throw new Error(`K8s CR ${crKey} contains Backstage-only annotations (${backstageKeys.join(', ')}). ` +
165424
- `Annotations with prefix ${backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX} must only appear on Backstage catalog entities, not on Kubernetes CRs.`);
165425
- }
165426
- }
165427
- }
165428
- }
165429
-
165430
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/refsSorter/refsSorter.ts
165431
-
165432
- /**
165433
- * @param renderClaims renderClaims to sort
165434
- * @param kinds kinds to get from renderClaims
165435
- * @returns renderClaims with only the kinds specified
165436
- */
165437
- function sortRenderClaimsByKind(renderClaims, kinds) {
165438
- let result = {};
165439
- for (const kind of kinds) {
165440
- for (const key in renderClaims) {
165441
- if (renderClaims[key].claim.kind === kind) {
165442
- result[key] = renderClaims[key];
165443
- }
165444
- }
165445
- result = sortSelfKindRefs(result, kind);
165446
- }
165447
- return result;
165448
- }
165449
- function sortSelfKindRefs(renderClaims, kind) {
165450
- if (!hasSelfRefs(kind)) {
165451
- return renderClaims;
165452
- }
165453
- const newRenderClaims = {};
165454
- const data = extractRefs(renderClaims, kind);
165455
- const ordered = [];
165456
- const visiting = [];
165457
- const visited = [];
165458
- for (const key of Object.keys(data)) {
165459
- if (!visited.find((obj) => obj.name === key)) {
165460
- sortRefs(data, data[key], ordered, visiting, visited);
165461
- }
165462
- }
165463
- for (const cr of ordered) {
165464
- newRenderClaims[cr.name] = renderClaims[cr.name];
165465
- }
165466
- return newRenderClaims;
165467
- }
165468
- function sortRefs(data, claim, ordered = [], visiting = [], visited = []) {
165469
- if (visiting.find((obj) => obj.name === claim.name)) {
165470
- throw new Error(`Circular dependency detected for '${claim.name}'`);
165471
- }
165472
- if (!visited.find((obj) => obj.name === claim.name)) {
165473
- visiting.push(claim);
165474
- if (claim.refs) {
165475
- for (const ref of claim.refs) {
165476
- const referencedObject = data[ref];
165477
- if (!referencedObject) {
165478
- throw new Error(`Reference '${ref}' does not exist for '${claim.name}'`);
165479
- }
165480
- sortRefs(data, referencedObject, ordered, visiting, visited);
165481
- }
165482
- }
165483
- visited.push(visiting.pop());
165484
- ordered.push(claim);
165485
- }
165486
- }
165487
- function hasSelfRefs(kind) {
165488
- return ['TFWorkspaceClaim', 'GroupClaim'].includes(kind);
165489
- }
165490
-
165491
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/renderer/claims-sorter.ts
165492
-
165493
- function sortKinds(orderedKinds, claims) {
165494
- const result = [];
165495
- for (const kind of orderedKinds) {
165496
- const kindRenderClaims = sortRenderClaimsByKind(claims, [kind]);
165497
- result.push(kindRenderClaims);
165498
- }
165499
- return result;
165500
- }
165501
-
165502
164553
  ;// CONCATENATED MODULE: ../features_renderer/src/common.ts
165503
164554
 
165504
164555
  function isDirectory(path) {
@@ -165538,6 +164589,16 @@ var ajv_default = /*#__PURE__*/__nccwpck_require__.n(dist_ajv);
165538
164589
  $ref: '#/definitions/File',
165539
164590
  },
165540
164591
  },
164592
+ claimPatches: {
164593
+ type: 'array',
164594
+ items: {
164595
+ $ref: '#/definitions/Patch',
164596
+ },
164597
+ },
164598
+ // Legacy field kept for backward compatibility. Real feature packages
164599
+ // (prefapp/features) ship `patches` in the provider-keyed object
164600
+ // shape. The renderer ignores it for claim-level behaviour; claim-level
164601
+ // patches must come from `claimPatches`.
165541
164602
  patches: {
165542
164603
  type: 'object',
165543
164604
  patternProperties: {
@@ -165569,7 +164630,7 @@ var ajv_default = /*#__PURE__*/__nccwpck_require__.n(dist_ajv);
165569
164630
  },
165570
164631
  },
165571
164632
  },
165572
- required: ['args', 'feature_name', 'files', 'patches'],
164633
+ required: ['args', 'feature_name', 'files'],
165573
164634
  title: 'root',
165574
164635
  },
165575
164636
  Args: {
@@ -165649,10 +164710,10 @@ var ajv_default = /*#__PURE__*/__nccwpck_require__.n(dist_ajv);
165649
164710
  type: 'string',
165650
164711
  },
165651
164712
  value: {
165652
- type: 'string',
164713
+ type: ['string', 'object', 'array', 'number', 'boolean', 'null'],
165653
164714
  },
165654
164715
  },
165655
- required: ['name', 'op', 'path'],
164716
+ required: ['op', 'path'],
165656
164717
  title: 'Patch',
165657
164718
  },
165658
164719
  },
@@ -165674,10 +164735,10 @@ function validate(featurePath) {
165674
164735
  }
165675
164736
  function __validateDirStructure(featurePath) {
165676
164737
  if (!isDirectory(featurePath)) {
165677
- throw `Feature: ${featurePath} not a directory`;
164738
+ throw new Error(`Feature: ${featurePath} not a directory`);
165678
164739
  }
165679
164740
  if (!isFile(external_path_.join(featurePath, 'config.yaml'))) {
165680
- throw `Feature: ${featurePath}/config.yaml not found or not a file`;
164741
+ throw new Error(`Feature: ${featurePath}/config.yaml not found or not a file`);
165681
164742
  }
165682
164743
  }
165683
164744
  function __validateFeatureConfig(featurePath) {
@@ -165687,10 +164748,16 @@ function __validateFeatureConfig(featurePath) {
165687
164748
  return configData;
165688
164749
  }
165689
164750
  catch (error) {
165690
- throw `Feature: loading config.yaml: ${error}`;
164751
+ throw new Error(`Feature: loading config.yaml: ${error}`);
165691
164752
  }
165692
164753
  }
165693
164754
  function __validateFeatureConfigData(configData) {
164755
+ // Detect old provider-keyed claimPatches shape for migration hint.
164756
+ if (configData.claimPatches &&
164757
+ !Array.isArray(configData.claimPatches) &&
164758
+ typeof configData.claimPatches === 'object') {
164759
+ throw new Error(`Feature: config.yaml invalid claimPatches: expected flat array of claimPatches (claim-relative pointers like /annotations/backstage.io~1techdocs-ref), but got provider-keyed object ${JSON.stringify(Object.keys(configData.claimPatches))}. Migrate: claimPatches: { catalog: [...] } → claimPatches: [{ op, path: /annotations/backstage.io~1techdocs-ref, value }]. $ref paths also migrate: [spec, org] → [providers, github, org], [metadata, annotations, firestartr.dev/external-name] → [providers, github, name]`);
164760
+ }
165694
164761
  const ajv = new (ajv_default())({
165695
164762
  allowUnionTypes: true,
165696
164763
  });
@@ -165701,7 +164768,7 @@ function __validateFeatureConfigData(configData) {
165701
164768
  const validate = ajv.compile(activeSchema);
165702
164769
  const valid = validate(configData);
165703
164770
  if (!valid) {
165704
- throw `Feature: config.yaml invalid ${JSON.stringify(validate.errors)}`;
164771
+ throw new Error(`Feature: config.yaml invalid ${JSON.stringify(validate.errors)}`);
165705
164772
  }
165706
164773
  }
165707
164774
  function stripAnchoringConstraints(schemaDef) {
@@ -165712,12 +164779,26 @@ function stripAnchoringConstraints(schemaDef) {
165712
164779
  return clone;
165713
164780
  }
165714
164781
  function __validateJsonPatches(configData) {
165715
- const keys = Object.keys(configData.patches);
165716
- for (const key of keys) {
165717
- if (configData.patches[key]) {
165718
- if (fast_json_patch_default().validate(configData.patches[key])) {
165719
- const errors = JSON.stringify(fast_json_patch_default().validate(configData.patches[key]).message);
165720
- throw `Feature: config.yaml -> patches: invalid patches ${errors}`;
164782
+ const patches = configData.claimPatches;
164783
+ if (!Array.isArray(patches))
164784
+ return;
164785
+ const err = fast_json_patch_default().validate(patches);
164786
+ if (err) {
164787
+ throw new Error(`Feature: config.yaml -> claimPatches: invalid claimPatches ${JSON.stringify(err.message ?? err)}`);
164788
+ }
164789
+ // Legacy provider-keyed `patches` field is accepted for backward
164790
+ // compatibility. Its values are per-provider arrays of the same Patch
164791
+ // shape, so validate each of them too.
164792
+ const legacyPatches = configData.patches;
164793
+ if (legacyPatches && typeof legacyPatches === 'object') {
164794
+ for (const key of Object.keys(legacyPatches)) {
164795
+ const arr = legacyPatches[key];
164796
+ if (!Array.isArray(arr)) {
164797
+ throw new Error(`Feature: config.yaml -> patches.${key}: expected an array of patches, got ${typeof arr}`);
164798
+ }
164799
+ const legacyErr = fast_json_patch_default().validate(arr);
164800
+ if (legacyErr) {
164801
+ throw new Error(`Feature: config.yaml -> patches.${key}: invalid patch ${JSON.stringify(legacyErr.message ?? legacyErr)}`);
165721
164802
  }
165722
164803
  }
165723
164804
  }
@@ -166564,10 +165645,12 @@ const renderTestsSchema = {
166564
165645
  items: {
166565
165646
  type: 'object',
166566
165647
  additionalProperties: false,
166567
- required: ['name', 'cr'],
165648
+ required: ['name'],
165649
+ anyOf: [{ required: ['cr'] }, { required: ['claim'] }],
166568
165650
  properties: {
166569
165651
  name: { type: 'string', minLength: 1 },
166570
165652
  cr: { type: 'string', minLength: 1 },
165653
+ claim: { type: 'string', minLength: 1 },
166571
165654
  args: { type: 'object' },
166572
165655
  },
166573
165656
  },
@@ -166622,6 +165705,9 @@ function resolveCrPath(featurePath, crRelPath) {
166622
165705
  }
166623
165706
  return resolved;
166624
165707
  }
165708
+ function resolveClaimPath(featurePath, claimRelPath) {
165709
+ return resolveCrPath(featurePath, claimRelPath);
165710
+ }
166625
165711
  function listYamlFiles(dir) {
166626
165712
  if (!fs.existsSync(dir))
166627
165713
  return [];
@@ -166685,7 +165771,7 @@ function buildExpectedOutput(config, renderDir) {
166685
165771
  }));
166686
165772
  return {
166687
165773
  files,
166688
- patches: config.patches || [],
165774
+ claimPatches: config.claimPatches || [],
166689
165775
  traceability: {},
166690
165776
  };
166691
165777
  }
@@ -166740,6 +165826,7 @@ async function createRenderContext(prefix = 'feature-render-') {
166740
165826
  buildExpectedOutput,
166741
165827
  loadAndValidateRenderTests,
166742
165828
  resolveCrPath,
165829
+ resolveClaimPath,
166743
165830
  });
166744
165831
 
166745
165832
  ;// CONCATENATED MODULE: ../features_renderer/src/featureArgsValidation.ts
@@ -166832,7 +165919,7 @@ function render(featurePath, featureRenderPath, entity, firestartrConfig = {}, f
166832
165919
  resolveInside(featureRenderPath, dest, 'file dest', 'render target directory');
166833
165920
  }
166834
165921
  }
166835
- const output = { files: [] };
165922
+ const output = { files: [], claimPatches: [] };
166836
165923
  context.config.files.forEach((file) => {
166837
165924
  const { src, dest } = file;
166838
165925
  // For now let's keep upgradable flag for backward compatibility
@@ -166853,30 +165940,125 @@ function render(featurePath, featureRenderPath, entity, firestartrConfig = {}, f
166853
165940
  userManaged: userManaged,
166854
165941
  targetBranch,
166855
165942
  });
166856
- output.patches = context.config.patches;
166857
- // Not used anymore
166858
- // output.unpatches = context.config.unpatches
166859
165943
  });
165944
+ // claimPatches are applied to the claim during claim stitching. Present in
165945
+ // the output even when empty or when the feature renders no files. The
165946
+ // legacy `patches` field is deliberately not copied: it is accepted in
165947
+ // config.yaml for backward compatibility but ignored for claim-level
165948
+ // behaviour.
165949
+ output.claimPatches = context.config.claimPatches || [];
166860
165950
  output.traceability = context.traceability;
165951
+ external_fs_default().mkdirSync(featureRenderPath, { recursive: true });
166861
165952
  external_fs_default().writeFileSync(external_path_default().join(featureRenderPath, 'config.json'), JSON.stringify(context.config));
166862
165953
  // write the output file
166863
165954
  const configFile = external_path_default().join(featureRenderPath, 'output.json');
166864
165955
  external_fs_default().writeFileSync(configFile, JSON.stringify(output));
166865
165956
  return output;
166866
165957
  }
166867
- function buildContext(entity, args, firestartrConfig, featureArgs) {
165958
+ function getClaimPatches(featurePath, entity, firestartrConfig = {}, featureArgs = {}) {
165959
+ const configData = validate(featurePath);
165960
+ validateFeatureArgs(featurePath, featureArgs);
165961
+ const context = buildContext(entity, configData.args, firestartrConfig, featureArgs);
165962
+ const rendered = JSON.parse(renderContent(JSON.stringify(configData), context));
165963
+ return rendered.claimPatches ?? [];
165964
+ }
165965
+ function buildContext(stitchedClaim, args, firestartrConfig, featureArgs) {
166868
165966
  const context = {};
165967
+ const resolveRef = (doc, ref) => {
165968
+ const v = lodash_default().get(doc, ref);
165969
+ if (v !== undefined)
165970
+ return v;
165971
+ // Fallback for transition: try CR-shaped alternatives when stitchedClaim is CR-shaped
165972
+ // and vice versa. Covers the ADR 0006 table plus legacy feature_a provisioner paths.
165973
+ const altTable = {
165974
+ 'providers,github,org': [
165975
+ ['spec', 'org'],
165976
+ ['spec', 'provisioner', 'org'],
165977
+ ],
165978
+ 'providers,github,branchStrategy,defaultBranch': [
165979
+ ['spec', 'repo', 'defaultBranch'],
165980
+ ['spec', 'provisioner', 'repo', 'defaultBranch'],
165981
+ ],
165982
+ 'providers,github,name': [
165983
+ ['metadata', 'annotations', 'firestartr.dev/external-name'],
165984
+ ['metadata', 'name'],
165985
+ ],
165986
+ 'providers,github,technology,stack': [
165987
+ ['spec', 'firestartr', 'technology', 'stack'],
165988
+ ['spec', 'provisioner', 'technology', 'stack'],
165989
+ ],
165990
+ name: [['metadata', 'name']],
165991
+ 'annotations,firestartr.dev/dest-annotation': [
165992
+ ['metadata', 'annotations', 'firestartr.dev/dest-annotation'],
165993
+ ],
165994
+ };
165995
+ const key = ref.join(',');
165996
+ const alts = altTable[key];
165997
+ if (alts) {
165998
+ for (const alt of alts) {
165999
+ const av = lodash_default().get(doc, alt);
166000
+ if (av !== undefined)
166001
+ return av;
166002
+ }
166003
+ }
166004
+ // Reverse fallback: if ref is CR-shaped, try claim-shaped
166005
+ const reverseTable = {
166006
+ 'spec,org': ['providers', 'github', 'org'],
166007
+ 'spec,provisioner,technology,stack': [
166008
+ 'providers',
166009
+ 'github',
166010
+ 'technology',
166011
+ 'stack',
166012
+ ],
166013
+ 'spec,firestartr,technology,stack': [
166014
+ 'providers',
166015
+ 'github',
166016
+ 'technology',
166017
+ 'stack',
166018
+ ],
166019
+ 'metadata,name': ['name'],
166020
+ 'metadata,annotations,firestartr.dev/dest-annotation': [
166021
+ 'annotations',
166022
+ 'firestartr.dev/dest-annotation',
166023
+ ],
166024
+ 'spec,provisioner,org': ['providers', 'github', 'org'],
166025
+ 'spec,provisioner,repo,defaultBranch': [
166026
+ 'providers',
166027
+ 'github',
166028
+ 'branchStrategy',
166029
+ 'defaultBranch',
166030
+ ],
166031
+ 'spec,repo,defaultBranch': [
166032
+ 'providers',
166033
+ 'github',
166034
+ 'branchStrategy',
166035
+ 'defaultBranch',
166036
+ ],
166037
+ 'metadata,annotations,firestartr.dev/external-name': [
166038
+ 'providers',
166039
+ 'github',
166040
+ 'name',
166041
+ ],
166042
+ };
166043
+ const rev = reverseTable[ref.join(',')];
166044
+ if (rev) {
166045
+ const rv = lodash_default().get(doc, rev);
166046
+ if (rv !== undefined)
166047
+ return rv;
166048
+ }
166049
+ return v;
166050
+ };
166869
166051
  Object.entries(args).forEach(([key, arg]) => {
166870
166052
  if ('$default' in arg) {
166871
166053
  if (Array.isArray(arg['$default'])) {
166872
- context[key] = lodash_default().get(entity, arg['$default']);
166054
+ context[key] = resolveRef(stitchedClaim, arg['$default']);
166873
166055
  }
166874
166056
  else {
166875
166057
  context[key] = arg['$default'];
166876
166058
  }
166877
166059
  }
166878
166060
  if ('$ref' in arg) {
166879
- const refValue = lodash_default().get(entity, arg['$ref']);
166061
+ const refValue = resolveRef(stitchedClaim, arg['$ref']);
166880
166062
  context[key] = refValue;
166881
166063
  }
166882
166064
  else if ('$lit' in arg) {
@@ -167006,6 +166188,7 @@ function updateFileContent(featureRenderPath, filePath, content) {
167006
166188
 
167007
166189
 
167008
166190
 
166191
+
167009
166192
  /* harmony default export */ const features_renderer = ({
167010
166193
  validate: validate,
167011
166194
  render: render,
@@ -167015,6 +166198,7 @@ function updateFileContent(featureRenderPath, filePath, content) {
167015
166198
  renderContent: renderContent,
167016
166199
  expandFiles: expandFiles,
167017
166200
  validateFeatureArgs: validateFeatureArgs,
166201
+ getClaimPatches: getClaimPatches,
167018
166202
  });
167019
166203
 
167020
166204
  ;// CONCATENATED MODULE: ../features_preparer/src/logger.ts
@@ -167039,6 +166223,13 @@ function renderFeature(featureName, version, owner, repo, featureOwner, renderPa
167039
166223
  function renderFeatureFromPath(extractPath, renderedPath, featureOwner, featureArgs = {}) {
167040
166224
  return features_renderer.render(extractPath, renderedPath, featureOwner, {}, featureArgs);
167041
166225
  }
166226
+ function getFeatureClaimPatches(featureName, version, owner, repo, featureOwner, featureArgs = {}) {
166227
+ const extractPath = external_path_default().join(catalog_common/* default.features.tarballs.getFeaturesExtractPath */.Z.features.tarballs.getFeaturesExtractPath(featureName, version, owner, repo), 'packages', featureName);
166228
+ return getClaimPatches(extractPath, featureOwner, {}, featureArgs);
166229
+ }
166230
+ function getFeatureClaimPatchesFromPath(extractPath, featureOwner, featureArgs = {}) {
166231
+ return getClaimPatches(extractPath, featureOwner, {}, featureArgs);
166232
+ }
167042
166233
 
167043
166234
  // EXTERNAL MODULE: ../../node_modules/adm-zip/adm-zip.js
167044
166235
  var adm_zip = __nccwpck_require__(7993);
@@ -167089,6 +166280,7 @@ featureArgs = {}, repo = 'features', owner = 'prefapp') {
167089
166280
  async function processFeature(featureName, reference, featureOwner, // -> cr
167090
166281
  featureArgs = {}, repo = 'features', owner = 'prefapp') {
167091
166282
  await downloadFeatureZip(repo, featureName, reference, owner);
166283
+ featureArgs = { ...(featureArgs ?? {}) };
167092
166284
  const commitInfo = await resolveFeatureCommit(owner, repo, reference);
167093
166285
  featureArgs['traceability'] = {
167094
166286
  version: reference,
@@ -167102,6 +166294,27 @@ featureArgs = {}, repo = 'features', owner = 'prefapp') {
167102
166294
  };
167103
166295
  return renderFeature(featureName, reference, owner, repo, featureOwner, '/tmp', featureArgs);
167104
166296
  }
166297
+ async function installer_getFeatureClaimPatches(featureName, version, featureOwner, featureArgs = {}, repo = 'features', owner = 'prefapp') {
166298
+ const reference = `${featureName}-v${version}`;
166299
+ return processFeatureClaimPatches(featureName, reference, featureOwner, featureArgs, repo, owner);
166300
+ }
166301
+ async function getFeatureClaimPatchesFromRef(featureName, featureRef, featureOwner, featureArgs = {}, repo = 'features', owner = 'prefapp') {
166302
+ const reference = `${featureRef}`;
166303
+ return processFeatureClaimPatches(featureName, reference, featureOwner, featureArgs, repo, owner);
166304
+ }
166305
+ async function processFeatureClaimPatches(featureName, reference, featureOwner, featureArgs = {}, repo = 'features', owner = 'prefapp') {
166306
+ await downloadFeatureZip(repo, featureName, reference, owner);
166307
+ featureArgs = { ...(featureArgs ?? {}) };
166308
+ featureArgs['traceability'] = {
166309
+ version: reference,
166310
+ owner,
166311
+ repo,
166312
+ name: featureName,
166313
+ ref: reference,
166314
+ url: `https://github.com/${owner}/${repo}/tree/${reference}/packages/${featureName}`,
166315
+ };
166316
+ return getFeatureClaimPatches(featureName, reference, owner, repo, featureOwner, featureArgs);
166317
+ }
167105
166318
  async function resolveFeatureCommit(owner, repo, reference) {
167106
166319
  try {
167107
166320
  const octokit = await github["default"].getOctokitForOrg(owner, true);
@@ -167189,6 +166402,9 @@ async function downloadFeatureZip(repo, featureName, reference, owner = 'prefapp
167189
166402
  /* harmony default export */ const src = ({
167190
166403
  renderFeature: renderFeature,
167191
166404
  renderFeatureFromPath: renderFeatureFromPath,
166405
+ getFeatureClaimPatches: installer_getFeatureClaimPatches,
166406
+ getFeatureClaimPatchesFromRef: getFeatureClaimPatchesFromRef,
166407
+ getFeatureClaimPatchesFromPath: getFeatureClaimPatchesFromPath,
167192
166408
  getFeatureConfigFromRef: getFeatureConfigFromRef,
167193
166409
  getFeatureConfig: getFeatureConfig,
167194
166410
  prepareFeature: prepareFeature,
@@ -167203,8 +166419,1266 @@ async function downloadFeatureZip(repo, featureName, reference, owner = 'prefapp
167203
166419
  renderFeatureFromPath: src.renderFeatureFromPath,
167204
166420
  getFeatureConfig: src.getFeatureConfig,
167205
166421
  getFeatureConfigFromRef: src.getFeatureConfigFromRef,
166422
+ getFeatureClaimPatches: src.getFeatureClaimPatches,
166423
+ getFeatureClaimPatchesFromRef: src.getFeatureClaimPatchesFromRef,
166424
+ getFeatureClaimPatchesFromPath: src.getFeatureClaimPatchesFromPath,
167206
166425
  });
167207
166426
 
166427
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/stitching/protectedPaths.ts
166428
+ // Platform-curated protected claim paths — features may not write to these.
166429
+ // Stored as JSON Pointers (RFC 6901). Supports wildcard `*` for a single segment.
166430
+ // Example: /providers/STAR/org matches /providers/github/org where STAR is *.
166431
+ const PROTECTED_CLAIM_PATHS = [
166432
+ '/kind',
166433
+ '/name',
166434
+ '/providers/*/org',
166435
+ '/providers/github/org',
166436
+ '/providers/github/name',
166437
+ '/providers/*/features',
166438
+ '/metadata/name',
166439
+ '/metadata/namespace',
166440
+ ];
166441
+ function isProtectedPath(patchPath) {
166442
+ const normalizedPatch = normalizePointer(patchPath);
166443
+ for (const protectedPath of PROTECTED_CLAIM_PATHS) {
166444
+ if (matchesProtected(protectedPath, normalizedPatch)) {
166445
+ return true;
166446
+ }
166447
+ }
166448
+ return false;
166449
+ }
166450
+ function normalizePointer(pointer) {
166451
+ // '' is RFC 6901's whole-document (root) pointer. Replacing the root touches
166452
+ // every protected field, so it must keep its identity for classification
166453
+ // instead of being rewritten to '/' (the "" empty-string member).
166454
+ if (pointer === '')
166455
+ return pointer;
166456
+ if (!pointer.startsWith('/')) {
166457
+ return '/' + pointer;
166458
+ }
166459
+ return pointer;
166460
+ }
166461
+ function matchesProtected(protectedPointer, patchPointer) {
166462
+ const protectedSegments = protectedPointer
166463
+ .split('/')
166464
+ .slice(1)
166465
+ .map(unescapePointer);
166466
+ const patchSegments = patchPointer.split('/').slice(1).map(unescapePointer);
166467
+ // Treat ancestor/descendant as protected: a patch to a parent (e.g. /metadata)
166468
+ // would replace the protected child (/metadata/name), and a patch to a child
166469
+ // (e.g. /metadata/name/extra) is also under the protected tree. Match when
166470
+ // the shorter prefix equals the longer prefix (with wildcard support).
166471
+ const minLen = Math.min(protectedSegments.length, patchSegments.length);
166472
+ for (let i = 0; i < minLen; i++) {
166473
+ if (protectedSegments[i] === '*')
166474
+ continue;
166475
+ if (protectedSegments[i] !== patchSegments[i])
166476
+ return false;
166477
+ }
166478
+ return true;
166479
+ }
166480
+ function unescapePointer(segment) {
166481
+ return segment.replace(/~1/g, '/').replace(/~0/g, '~');
166482
+ }
166483
+
166484
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/stitching/errors.ts
166485
+ class StitchingError extends Error {
166486
+ constructor(violations) {
166487
+ const lines = violations.map((v) => ` - ${v.message}`).join('\n');
166488
+ super(`Claim stitching failed with ${violations.length} violation(s):\n${lines}`);
166489
+ this.name = 'StitchingError';
166490
+ this.violations = violations;
166491
+ }
166492
+ }
166493
+ function formatStitchingError(error) {
166494
+ return error.message;
166495
+ }
166496
+
166497
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/stitching/validateFeatureDescriptors.ts
166498
+
166499
+
166500
+ let validateFeatureDescriptors_validate;
166501
+ let validateFeatureDescriptors_ajv;
166502
+ function getValidate() {
166503
+ if (!validateFeatureDescriptors_validate) {
166504
+ validateFeatureDescriptors_ajv = new (_2020_default())();
166505
+ validateFeatureDescriptors_ajv.addSchema(feature_schema.definitions.GithubComponentFeatureClaim);
166506
+ validateFeatureDescriptors_validate = validateFeatureDescriptors_ajv.compile({
166507
+ type: 'array',
166508
+ items: { $ref: 'firestartr.dev://github/GithubComponentFeatureClaim' },
166509
+ });
166510
+ }
166511
+ return validateFeatureDescriptors_validate;
166512
+ }
166513
+ // Validates the `providers.github.features` descriptor array against the same
166514
+ // GithubComponentFeatureClaim schema used by claim-kind AJV validation. This
166515
+ // runs BEFORE any feature preparer (auth/network) is invoked, so malformed or
166516
+ // unauthorized `repo`/`ref`/`version` values are rejected without triggering
166517
+ // GitHub downloads. Full AJV validation of the stitched claim is still applied
166518
+ // after stitching.
166519
+ function validateFeatureDescriptors(claim) {
166520
+ const typedClaim = claim;
166521
+ const features = typedClaim.providers?.github?.features;
166522
+ if (!Array.isArray(features))
166523
+ return;
166524
+ const v = getValidate();
166525
+ if (v(features))
166526
+ return;
166527
+ const details = (v.errors ?? [])
166528
+ .map((e) => {
166529
+ const formatted = `${e.instancePath || '/'} ${e.message}`;
166530
+ return ` - ${formatted}`;
166531
+ })
166532
+ .join('\n');
166533
+ throw new Error(`Invalid feature descriptor(s):\n${details}\nFix the claim before stitching or rendering.`);
166534
+ }
166535
+
166536
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/claims/stitching/stitching.ts
166537
+
166538
+
166539
+
166540
+
166541
+
166542
+ let MOCK_FEATURES_FN;
166543
+ function MOCK_STITCHING_FEATURES(mock) {
166544
+ MOCK_FEATURES_FN = mock;
166545
+ }
166546
+ // Non-enumerable stamp marking a claim as already stitched. Lets stitching be
166547
+ // once-only at each entry point (e.g. renderFromImports) without re-running
166548
+ // feature downloads or re-applying gates on the same claim object.
166549
+ const STITCHED_CLAIM = Symbol('firestartr.stitchedClaim');
166550
+ function stitching_unescapePointer(segment) {
166551
+ return segment.replace(/~1/g, '/').replace(/~0/g, '~');
166552
+ }
166553
+ function pointerExists(doc, pointer) {
166554
+ const segments = pointer.split('/').slice(1).map(stitching_unescapePointer);
166555
+ let cur = doc;
166556
+ for (const seg of segments) {
166557
+ if (cur === null || cur === undefined || typeof cur !== 'object')
166558
+ return false;
166559
+ if (!Object.prototype.hasOwnProperty.call(cur, seg))
166560
+ return false;
166561
+ cur = cur[seg];
166562
+ }
166563
+ return true;
166564
+ }
166565
+ function isAppendPointer(pointer) {
166566
+ return pointer.endsWith('/-');
166567
+ }
166568
+ function isRecord(value) {
166569
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
166570
+ }
166571
+ // Deduplication identity for a feature patch (Phase 1 silent dedup). Two
166572
+ // patches are only considered identical intent when the operation, the
166573
+ // normalized pointer, and — for array appends (`add ... /-`) — the appended
166574
+ // element's `name` all match, e.g. two features adding the same label. The
166575
+ // operation is part of the identity so an `add` and a `replace` on the same
166576
+ // pointer are never deduplicated against each other.
166577
+ function dedupIdentity(patch) {
166578
+ const path = normalizePointer(patch.path);
166579
+ if (patch.op === 'add' &&
166580
+ isAppendPointer(path) &&
166581
+ isRecord(patch.value) &&
166582
+ typeof patch.value.name === 'string') {
166583
+ return `${patch.op} ${path}#${patch.value.name}`;
166584
+ }
166585
+ return `${patch.op} ${path}`;
166586
+ }
166587
+ // Write region for a feature patch — the claim locations the patch occupies.
166588
+ // For a regular op it is the unescaped pointer segments; for an array append
166589
+ // (`add ... /-`) carrying a `name` it is the array parent plus the element
166590
+ // `name`, so two appends of distinct names stay sibling writes while an append
166591
+ // and a whole-array write overlap.
166592
+ function writeRegion(patch) {
166593
+ const path = normalizePointer(patch.path);
166594
+ const segments = path.split('/').slice(1).map(stitching_unescapePointer);
166595
+ if (patch.op === 'add' &&
166596
+ isAppendPointer(path) &&
166597
+ isRecord(patch.value) &&
166598
+ typeof patch.value.name === 'string') {
166599
+ return [...segments.slice(0, -1), patch.value.name];
166600
+ }
166601
+ return segments;
166602
+ }
166603
+ // Ancestor/descendant (or identical) regions conflict: under JSON Patch
166604
+ // semantics a parent write replaces its whole subtree, so the composed result
166605
+ // would depend on feature order. Distinct-name appends yield sibling regions
166606
+ // and stay composable.
166607
+ function regionsOverlap(a, b) {
166608
+ const minLen = Math.min(a.length, b.length);
166609
+ for (let i = 0; i < minLen; i++) {
166610
+ if (a[i] !== b[i])
166611
+ return false;
166612
+ }
166613
+ return true;
166614
+ }
166615
+ function isStitchedClaim(claim) {
166616
+ return (isRecord(claim) &&
166617
+ claim[STITCHED_CLAIM] === true);
166618
+ }
166619
+ function markStitched(claim) {
166620
+ if (isRecord(claim)) {
166621
+ Object.defineProperty(claim, STITCHED_CLAIM, {
166622
+ value: true,
166623
+ enumerable: false,
166624
+ writable: false,
166625
+ configurable: true,
166626
+ });
166627
+ }
166628
+ return claim;
166629
+ }
166630
+ // Check whether an array at `appendPath`'s parent already contains an element
166631
+ // whose `name` matches `value.name`. Used for the "claim wins" gate: when a
166632
+ // feature tries to append an array element that already exists in the claim,
166633
+ // the patch is silently dropped.
166634
+ function arrayElementExists(doc, appendPath, value) {
166635
+ if (!isRecord(value) || typeof value.name !== 'string')
166636
+ return false;
166637
+ const parentPath = appendPath.slice(0, -2); // strip trailing /-
166638
+ const segments = parentPath.split('/').slice(1).map(stitching_unescapePointer);
166639
+ let cur = doc;
166640
+ for (const seg of segments) {
166641
+ if (cur === null || cur === undefined || typeof cur !== 'object')
166642
+ return false;
166643
+ if (!Object.prototype.hasOwnProperty.call(cur, seg))
166644
+ return false;
166645
+ cur = cur[seg];
166646
+ }
166647
+ if (!Array.isArray(cur))
166648
+ return false;
166649
+ return cur.some((el) => isRecord(el) && el.name === value.name);
166650
+ }
166651
+ // fast-json-patch does not create intermediate containers for `add`, and
166652
+ // appending to an array requires the array to already exist. Ensure every
166653
+ // ancestor segment exists before applying an `add`: missing containers are
166654
+ // created as objects, except the immediate parent of a `/-` append, which is
166655
+ // created as an array. Existing (user/default-declared) values are never
166656
+ // overwritten.
166657
+ function ensureAddParents(doc, patch) {
166658
+ const segments = patch.path.split('/').slice(1);
166659
+ let prefix = '';
166660
+ for (let i = 0; i < segments.length - 1; i++) {
166661
+ prefix += '/' + segments[i];
166662
+ if (pointerExists(doc, prefix))
166663
+ continue;
166664
+ const isArrayParent = isAppendPointer(patch.path) && i === segments.length - 2;
166665
+ const value = isArrayParent ? [] : {};
166666
+ try {
166667
+ doc = fast_json_patch.applyPatch(doc, [{ op: 'add', path: prefix, value }], false, false).newDocument;
166668
+ }
166669
+ catch {
166670
+ // Concurrent structural conflict — let the actual patch surface the error.
166671
+ }
166672
+ }
166673
+ return doc;
166674
+ }
166675
+ async function stitchClaim(claimAfterDefaults, preCollectedEnvelopes, originalClaim) {
166676
+ if (isStitchedClaim(claimAfterDefaults)) {
166677
+ return claimAfterDefaults;
166678
+ }
166679
+ const envelopes = preCollectedEnvelopes ?? (await collectFeaturePatches(claimAfterDefaults));
166680
+ if (envelopes.length === 0) {
166681
+ return markStitched(claimAfterDefaults);
166682
+ }
166683
+ // Normalize all patches once so every gate and the apply phase use the same pointers.
166684
+ const normalizedEnvelopes = envelopes.map((env) => ({
166685
+ feature: env.feature,
166686
+ patches: env.patches.map((p) => ({
166687
+ ...p,
166688
+ path: normalizePointer(p.path),
166689
+ _raw: p.path,
166690
+ })),
166691
+ }));
166692
+ // ── Phase 1: silently drop patches that should not be applied ──────────
166693
+ // • Array append whose element already exists in the claim → claim wins
166694
+ // (never for protected claim paths, which are rejected in Phase 2)
166695
+ // • Duplicate identity with identical value across features → silent dedup
166696
+ // (a feature's own ordered patches are always retained verbatim)
166697
+ const dropped = new Set(); // "envelopeIdx:patchIdx"
166698
+ const seenIdentities = new Map();
166699
+ for (let ei = 0; ei < normalizedEnvelopes.length; ei++) {
166700
+ const envelope = normalizedEnvelopes[ei];
166701
+ for (let pi = 0; pi < envelope.patches.length; pi++) {
166702
+ const patch = envelope.patches[pi];
166703
+ const key = `${ei}:${pi}`;
166704
+ // Array claim-wins: element already in claim → drop (protected paths
166705
+ // are exempt so every attempt on them is rejected in Phase 2)
166706
+ if (patch.op === 'add' &&
166707
+ isAppendPointer(patch.path) &&
166708
+ !isProtectedPath(patch.path)) {
166709
+ if (arrayElementExists(claimAfterDefaults, patch.path, patch.value)) {
166710
+ dropped.add(key);
166711
+ continue;
166712
+ }
166713
+ }
166714
+ // Silent dedup across features only: same op + destination + value from
166715
+ // a DIFFERENT feature → drop. A feature's own ordered patches (e.g. a
166716
+ // repeated append, or a scalar written twice) are always retained.
166717
+ const identity = dedupIdentity(patch);
166718
+ const existing = seenIdentities.get(identity);
166719
+ if (existing && existing.feature !== envelope.feature) {
166720
+ if (JSON.stringify(existing.value) === JSON.stringify(patch.value)) {
166721
+ dropped.add(key);
166722
+ continue;
166723
+ }
166724
+ // Different value — kept here, caught as a violation in Phase 2.
166725
+ }
166726
+ // Refresh the recorded writer/value so later features compare against
166727
+ // the latest write by this feature.
166728
+ seenIdentities.set(identity, {
166729
+ feature: envelope.feature,
166730
+ value: patch.value,
166731
+ });
166732
+ }
166733
+ }
166734
+ // ── Phase 2: collect violations on non-dropped patches ─────────────────
166735
+ const violations = [];
166736
+ // Writers observed so far (write region + feature). Gate 2 compares every new
166737
+ // patch's region against prior writers from OTHER features, covering both
166738
+ // identical destinations and ancestor/descendant destinations.
166739
+ const priorWrites = [];
166740
+ for (let ei = 0; ei < normalizedEnvelopes.length; ei++) {
166741
+ const envelope = normalizedEnvelopes[ei];
166742
+ // Per-feature shadow document: tracks mutations within this envelope so that
166743
+ // ordered sequences like add → replace within one feature resolve correctly.
166744
+ let shadow = JSON.parse(JSON.stringify(claimAfterDefaults));
166745
+ for (let pi = 0; pi < envelope.patches.length; pi++) {
166746
+ if (dropped.has(`${ei}:${pi}`))
166747
+ continue;
166748
+ const patch = envelope.patches[pi];
166749
+ const path = patch.path;
166750
+ const raw = patch._raw ?? path;
166751
+ // Gate 1: protected path
166752
+ if (isProtectedPath(path)) {
166753
+ violations.push({
166754
+ feature: envelope.feature,
166755
+ op: patch.op,
166756
+ path,
166757
+ reason: 'protected-path',
166758
+ message: `Feature '${envelope.feature}' patch ${patch.op} ${raw} (normalized ${path}) targets protected claim path`,
166759
+ });
166760
+ }
166761
+ // Gate 2: conflicting write from a DIFFERENT feature to the same
166762
+ // destination or an ancestor/descendant of it (region-based, op-agnostic
166763
+ // — see writeRegion). A feature's own ordered patches never self-conflict.
166764
+ const region = writeRegion(patch);
166765
+ const overlapping = priorWrites.find((w) => w.feature !== envelope.feature && regionsOverlap(w.region, region));
166766
+ if (overlapping) {
166767
+ violations.push({
166768
+ feature: envelope.feature,
166769
+ op: patch.op,
166770
+ path,
166771
+ reason: 'duplicate-path',
166772
+ conflictingFeature: overlapping.feature,
166773
+ message: `Feature '${envelope.feature}' and '${overlapping.feature}' both write overlapping paths (${raw} overlaps ${overlapping.path}); compose them in one feature instead`,
166774
+ });
166775
+ }
166776
+ priorWrites.push({ region, feature: envelope.feature, path });
166777
+ // Gate 3: replace / remove to a path absent from this feature's mutation
166778
+ // sequence (tracked via shadow), not the static claimAfterDefaults.
166779
+ if (['replace', 'remove'].includes(patch.op)) {
166780
+ if (!pointerExists(shadow, path)) {
166781
+ violations.push({
166782
+ feature: envelope.feature,
166783
+ op: patch.op,
166784
+ path,
166785
+ reason: 'overwrite-protected',
166786
+ message: `Feature '${envelope.feature}' patch ${patch.op} ${raw} (normalized ${path}) targets absent path (replace/remove requires existing value)`,
166787
+ });
166788
+ }
166789
+ }
166790
+ // Gate 4: non-append ops must not overwrite a user-declared field
166791
+ // (overwrite protection). The user's own claim wins over any feature.
166792
+ // Only the patch's target field itself is protected: adding a sibling
166793
+ // field under a user-declared parent (e.g. a new field in
166794
+ // /providers/github) is allowed. Array appends (`add ... /-`) are
166795
+ // exempt: the appended element is deduplicated against the claim in
166796
+ // Phase 1, preserving original values, while distinct elements from
166797
+ // multiple features may be added.
166798
+ if (originalClaim && !isAppendPointer(path)) {
166799
+ if (pointerExists(originalClaim, path)) {
166800
+ violations.push({
166801
+ feature: envelope.feature,
166802
+ op: patch.op,
166803
+ path,
166804
+ reason: 'user-declared-path',
166805
+ message: `Feature '${envelope.feature}' patch ${patch.op} ${raw} (normalized ${path}) targets a field declared by the user (overwrite protection)`,
166806
+ });
166807
+ }
166808
+ }
166809
+ // Update shadow for subsequent patches within this feature
166810
+ try {
166811
+ if (patch.op === 'add')
166812
+ shadow = ensureAddParents(shadow, patch);
166813
+ shadow = fast_json_patch.applyPatch(shadow, [patch], false, false).newDocument;
166814
+ }
166815
+ catch {
166816
+ /* leave shadow unchanged — Gate 3 stays conservative */
166817
+ }
166818
+ }
166819
+ }
166820
+ if (violations.length > 0) {
166821
+ throw new StitchingError(violations);
166822
+ }
166823
+ // ── Phase 3: apply remaining patches ───────────────────────────────────
166824
+ let stitched = JSON.parse(JSON.stringify(claimAfterDefaults));
166825
+ for (let ei = 0; ei < normalizedEnvelopes.length; ei++) {
166826
+ const envelope = normalizedEnvelopes[ei];
166827
+ const patchesToApply = envelope.patches.filter((_, pi) => !dropped.has(`${ei}:${pi}`));
166828
+ if (patchesToApply.length === 0)
166829
+ continue;
166830
+ // ── Apply each patch in order, creating parents for adds as needed ───
166831
+ for (const patch of patchesToApply) {
166832
+ if (patch.op === 'add') {
166833
+ stitched = ensureAddParents(stitched, patch);
166834
+ }
166835
+ const result = fast_json_patch.applyPatch(stitched, [patch], false, false);
166836
+ stitched = result.newDocument;
166837
+ }
166838
+ }
166839
+ return markStitched(stitched);
166840
+ }
166841
+ async function collectFeaturePatches(claim) {
166842
+ if (MOCK_FEATURES_FN) {
166843
+ return MOCK_FEATURES_FN(claim);
166844
+ }
166845
+ const typedClaim = claim;
166846
+ const features = typedClaim.providers?.github?.features;
166847
+ if (features === undefined)
166848
+ return [];
166849
+ if (!Array.isArray(features)) {
166850
+ throw new Error('Invalid feature descriptor(s): /providers/github/features must be an array');
166851
+ }
166852
+ if (features.length === 0)
166853
+ return [];
166854
+ // Gate 0: reject malformed feature descriptors (repo/ref/version shape)
166855
+ // BEFORE any preparer call, so no auth/network work is triggered by data
166856
+ // that claim-kind AJV validation would reject.
166857
+ validateFeatureDescriptors(claim);
166858
+ const envelopes = [];
166859
+ for (const feature of features) {
166860
+ const featureName = feature.name;
166861
+ const versionOrRef = feature.ref ?? feature.version ?? '';
166862
+ const repo = feature.repo
166863
+ ? (feature.repo.split('/')[1] ?? 'features')
166864
+ : 'features';
166865
+ const owner = feature.repo
166866
+ ? (feature.repo.split('/')[0] ?? 'prefapp')
166867
+ : 'prefapp';
166868
+ const args = feature.args ?? {};
166869
+ try {
166870
+ let patchesOrRendered;
166871
+ const preparerAny = features_preparer;
166872
+ if (feature.ref) {
166873
+ if (typeof preparerAny.getFeatureClaimPatchesFromRef === 'function') {
166874
+ patchesOrRendered = await preparerAny.getFeatureClaimPatchesFromRef(featureName, versionOrRef, claim, args, repo, owner);
166875
+ }
166876
+ else {
166877
+ patchesOrRendered = await preparerAny.getFeatureConfigFromRef(featureName, versionOrRef, claim, args, repo, owner);
166878
+ }
166879
+ }
166880
+ else {
166881
+ if (typeof preparerAny.getFeatureClaimPatches === 'function') {
166882
+ patchesOrRendered = await preparerAny.getFeatureClaimPatches(featureName, versionOrRef, claim, args, repo, owner);
166883
+ }
166884
+ else {
166885
+ patchesOrRendered = await preparerAny.getFeatureConfig(featureName, versionOrRef, claim, args, repo, owner);
166886
+ }
166887
+ }
166888
+ const patches = Array.isArray(patchesOrRendered)
166889
+ ? patchesOrRendered
166890
+ : extractClaimPatches(patchesOrRendered);
166891
+ envelopes.push({ feature: featureName, patches });
166892
+ }
166893
+ catch (err) {
166894
+ throw new Error(`Failed to collect claimPatches for feature '${featureName}': ${err instanceof Error ? err.message : String(err)}`);
166895
+ }
166896
+ }
166897
+ return envelopes;
166898
+ }
166899
+ function extractClaimPatches(rendered) {
166900
+ const patches = rendered.claimPatches;
166901
+ if (!patches)
166902
+ return [];
166903
+ if (Array.isArray(patches))
166904
+ return patches;
166905
+ throw new Error(`Feature claimPatches must be a flat array (claim-relative pointers like /annotations/...), got ${typeof patches}: ${JSON.stringify(patches).slice(0, 200)}`);
166906
+ }
166907
+
166908
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/lazy_loader.ts
166909
+
166910
+
166911
+
166912
+
166913
+
166914
+
166915
+
166916
+
166917
+
166918
+
166919
+
166920
+
166921
+
166922
+
166923
+
166924
+
166925
+
166926
+ // We need to ensure the grep command is a gnu version
166927
+ let IS_GNU_GREP = false;
166928
+ let GREP_ON_CHECK = false;
166929
+ // this loop is for avoid race conditions
166930
+ // once a check is running no more checks
166931
+ async function waitForCheck() {
166932
+ const f_wait = () => new Promise((timeOut) => setTimeout(timeOut, 10));
166933
+ do {
166934
+ await f_wait();
166935
+ } while (GREP_ON_CHECK);
166936
+ }
166937
+ function checkGrep() {
166938
+ return new Promise((ok, ko) => {
166939
+ // idempotency: already checked
166940
+ if (IS_GNU_GREP)
166941
+ return ok();
166942
+ // a check is already running no new checks
166943
+ if (GREP_ON_CHECK)
166944
+ return waitForCheck();
166945
+ logger.info('Checking the grep command');
166946
+ GREP_ON_CHECK = true;
166947
+ const handler = (0,external_node_child_process_namespaceObject.spawn)('grep', ['--version']);
166948
+ handler.on('close', (code) => {
166949
+ GREP_ON_CHECK = false;
166950
+ if (code === 0) {
166951
+ logger.debug('Grep is a gnu grep');
166952
+ IS_GNU_GREP = true;
166953
+ ok();
166954
+ }
166955
+ else {
166956
+ ko('Lazy evaluation needs a gnu-grep command');
166957
+ }
166958
+ });
166959
+ });
166960
+ }
166961
+ async function loadClaim(claimRef, org, defaults = loadClaimDefaults(), patchClaim = loader_patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, existingRefs = {}, postValidations = new Map()) {
166962
+ await checkGrep();
166963
+ let result = existingRefs;
166964
+ logger.info(`Load reference ${claimRef}`);
166965
+ initVirtualClaims(org);
166966
+ logger.info(`Load reference (parts) ${claimRef.split(/-/)[0]} ${claimRef.replace(/^[^-]+-/, '')}`);
166967
+ // cargas datos con grep
166968
+ try {
166969
+ const claimData = await lazyGetClaim(claimRef.split(/-/)[0], claimRef.replace(/^[^-]+-/, ''), org, cwd);
166970
+ const rawClaim = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(claimData);
166971
+ let claim = patchClaim(rawClaim, defaults);
166972
+ // Claim stitching: feature claim-patches with gates before AJV
166973
+ try {
166974
+ claim = await stitchClaim(claim, undefined, rawClaim);
166975
+ }
166976
+ catch (e) {
166977
+ throw new Error(`Error when stitching claim ${claimRef}: ${e instanceof Error ? e.message : String(e)}`);
166978
+ }
166979
+ let variants = [];
166980
+ if (claim.kind === 'TFWorkspaceClaim' &&
166981
+ claim.providers?.terraform?.variants) {
166982
+ variants = claim.providers.terraform.variants;
166983
+ delete claim.providers.terraform.variants;
166984
+ }
166985
+ logger.silly(`Patched claim is:
166986
+ ---
166987
+ ${catalog_common/* default.io.toYaml */.Z.io.toYaml(claim)}`);
166988
+ try {
166989
+ validateClaim(claim, base[`${claim.kind}Schema`]);
166990
+ await optionalValidation(claim);
166991
+ }
166992
+ catch (error) {
166993
+ let errorMsg = '';
166994
+ if (Array.isArray(error)) {
166995
+ for (const data of error) {
166996
+ errorMsg = `${errorMsg}
166997
+ - ${data.instancePath}: ${data.message}`;
166998
+ }
166999
+ }
167000
+ else {
167001
+ errorMsg = error instanceof Error ? error.message : String(error);
167002
+ }
167003
+ throw new Error(`Error when validating claim ${claimRef}: ${errorMsg}`);
167004
+ }
167005
+ result[claimRef] = {};
167006
+ result[claimRef]['claim'] = claim;
167007
+ result[claimRef]['claimPath'] = VisitedClaims[claimRef];
167008
+ if (VisitedClaims[claimRef] === 'virtual') {
167009
+ result = await setVirtualClaimAdditionalData(result, claim, claimRef);
167010
+ }
167011
+ else {
167012
+ result = await setNonVirtualClaimAdditionalData(result, claim, claimRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers);
167013
+ }
167014
+ const claimKind = claim.kind;
167015
+ const references = extractAllRefs(catalog_common/* default.io.toYaml */.Z.io.toYaml(claim));
167016
+ for (const ref of references) {
167017
+ if (!result[ref]) {
167018
+ const [resolvedReferences] = await loadClaim(ref, org, defaults, patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, result, postValidations);
167019
+ result = lodash_default().merge(result, resolvedReferences);
167020
+ }
167021
+ }
167022
+ if (variants.length > 0) {
167023
+ const parentClaimPath = VisitedClaims[claimRef];
167024
+ for (const variant of variants) {
167025
+ if (!variant.name || !variant.overrides) {
167026
+ throw new Error(`Variant in claim ${claimRef} is missing required field 'name' or 'overrides'`);
167027
+ }
167028
+ const prohibitedOverrideFields = ['source', 'module', 'name'];
167029
+ for (const field of prohibitedOverrideFields) {
167030
+ if (field in variant.overrides) {
167031
+ throw new Error(`Variant '${variant.name}' in claim ${claimRef} cannot override '${field}'`);
167032
+ }
167033
+ }
167034
+ const composedName = claim.providers.terraform.name + '-' + variant.name;
167035
+ const variantClaim = lodash_default().cloneDeep(claim);
167036
+ variantClaim._parentClaimName = claim.name;
167037
+ variantClaim.name = composedName;
167038
+ variantClaim.providers.terraform = lodash_default().merge({}, claim.providers.terraform, variant.overrides);
167039
+ variantClaim.providers.terraform.name = composedName;
167040
+ if (!variantClaim.annotations) {
167041
+ variantClaim.annotations = {};
167042
+ }
167043
+ variantClaim.annotations['firestartr.dev/variant-of'] =
167044
+ claim.providers.terraform.name;
167045
+ const variantRef = `TFWorkspaceClaim-${composedName}`;
167046
+ if (result[variantRef]) {
167047
+ throw new Error(`Variant name '${variant.name}' (composed: '${composedName}') from claim '${claimRef}' conflicts with existing claim '${variantRef}'`);
167048
+ }
167049
+ logger.info(`Creating synthetic variant claim ${variantRef}`);
167050
+ result[variantRef] = {};
167051
+ result[variantRef]['claim'] = variantClaim;
167052
+ result[variantRef]['claimPath'] = parentClaimPath;
167053
+ result = await setNonVirtualClaimAdditionalData(result, variantClaim, variantRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers);
167054
+ const variantReferences = extractAllRefs(catalog_common/* default.io.toYaml */.Z.io.toYaml(variantClaim));
167055
+ for (const ref of variantReferences) {
167056
+ if (!result[ref]) {
167057
+ const [resolvedReferences] = await loadClaim(ref, org, defaults, patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, cwd, result, postValidations);
167058
+ result = lodash_default().merge(result, resolvedReferences);
167059
+ }
167060
+ }
167061
+ }
167062
+ }
167063
+ }
167064
+ catch (err) {
167065
+ throw `Lazy Loading: ${err}`;
167066
+ }
167067
+ return [result, postValidations];
167068
+ }
167069
+ let LoadedClaims = {};
167070
+ let VisitedClaims = {};
167071
+ let DuplicatedClaims = {};
167072
+ function resetLazyLoader() {
167073
+ LoadedClaims = {};
167074
+ VisitedClaims = {};
167075
+ DuplicatedClaims = {};
167076
+ }
167077
+ async function lazyGetClaim(kind, name, org, cwd) {
167078
+ const indice = `${kind}-${name}`;
167079
+ logger.info(`Lazy loading ${kind}-${name} with index ${indice}`);
167080
+ if (indice in LoadedClaims)
167081
+ return LoadedClaims[indice];
167082
+ if (isVirtualClaim(kind, name)) {
167083
+ await loadVirtualClaim(kind, name, org);
167084
+ }
167085
+ else {
167086
+ await getClaimsByName(name, cwd);
167087
+ }
167088
+ if (indice in LoadedClaims) {
167089
+ return LoadedClaims[indice];
167090
+ }
167091
+ else {
167092
+ throw new Error(`Error: ${kind}-${name} not found`);
167093
+ }
167094
+ }
167095
+ async function getClaimsByName(name, cwd = '.') {
167096
+ return new Promise((ok, ko) => {
167097
+ const handler = (0,external_node_child_process_namespaceObject.spawn)('grep', ['-r', '-l', '--include=*', '-E', `name: "?${name}"?`, '.'], {
167098
+ cwd: cwd,
167099
+ });
167100
+ logger.info(`Running ${['grep', '-r', '-l', '--include', '-E', 'name: "' + name + '"?', '.'].join(' ')}`);
167101
+ const entradas = [];
167102
+ const chunks = [];
167103
+ handler.stdout.on('data', (data) => {
167104
+ chunks.push(data.toString('utf-8'));
167105
+ });
167106
+ handler.on('close', () => {
167107
+ const dataFinal = chunks.join('');
167108
+ const fileNameList = dataFinal.split(/\n/).filter((line) => line !== '');
167109
+ for (const fileName of fileNameList) {
167110
+ // only yaml files
167111
+ if (!fileName.match(/\.yml$|\.yaml$/)) {
167112
+ continue;
167113
+ }
167114
+ // only entries not already visited
167115
+ if (Object.values(VisitedClaims).includes(fileName)) {
167116
+ continue;
167117
+ }
167118
+ entradas.push(external_path_.join(cwd, fileName));
167119
+ }
167120
+ return Promise.all(entradas.map((entrada) => {
167121
+ return loadRawClaim(entrada);
167122
+ }))
167123
+ .then(() => {
167124
+ ok();
167125
+ })
167126
+ .catch((err) => {
167127
+ ko(err);
167128
+ });
167129
+ });
167130
+ });
167131
+ }
167132
+ async function loadRawClaim(entry) {
167133
+ return new Promise((ok, ko) => {
167134
+ external_fs_.readFile(entry, 'utf-8', (error, data) => {
167135
+ if (error)
167136
+ return ko(`Reading ${entry}: ${error}`);
167137
+ const claim = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
167138
+ if (!('kind' in claim && 'name' in claim)) {
167139
+ logger.warn(`Invalid claim file ${entry}`);
167140
+ }
167141
+ else {
167142
+ const claimKey = `${claim.kind}-${claim.name}`;
167143
+ if (Object.keys(DuplicatedClaims).includes(claimKey) &&
167144
+ DuplicatedClaims[claimKey] !== entry) {
167145
+ return ko(`Duplicated claim ${claimKey} found files: ${DuplicatedClaims[claimKey]} and ${entry}`);
167146
+ }
167147
+ LoadedClaims[claimKey] = data;
167148
+ VisitedClaims[claimKey] = entry;
167149
+ DuplicatedClaims[claimKey] = entry;
167150
+ ok();
167151
+ }
167152
+ });
167153
+ });
167154
+ }
167155
+ async function setVirtualClaimAdditionalData(renderedData, claim, claimRef) {
167156
+ const virtualClaim = getVirtualClaim(claim.kind, claim.name);
167157
+ renderedData[claimRef]['initializers'] = [
167158
+ new UUIDInitializer(claim),
167159
+ new InitializerClaimRef(),
167160
+ new InitializerDefault(virtualClaim.getDefaultConfig()),
167161
+ ];
167162
+ renderedData[claimRef]['globals'] = [];
167163
+ renderedData[claimRef]['overrides'] = [];
167164
+ renderedData[claimRef]['normalizers'] = [new NameNormalizer()];
167165
+ return renderedData;
167166
+ }
167167
+ async function setNonVirtualClaimAdditionalData(renderedData, claim, claimRef, loadInitializers, loadGlobals, loadOverrides, loadNormalizers) {
167168
+ renderedData[claimRef]['initializers'] = await loadInitializers(claim, renderedData[claimRef]['claimPath']);
167169
+ renderedData[claimRef]['globals'] = await loadGlobals(claim);
167170
+ renderedData[claimRef]['overrides'] = loadOverrides(claim);
167171
+ renderedData[claimRef]['normalizers'] = await loadNormalizers(claim, renderedData[claimRef]['claimPath']);
167172
+ return renderedData;
167173
+ }
167174
+ async function loadVirtualClaim(kind, name, org) {
167175
+ const virtualClaim = getVirtualClaim(kind, name);
167176
+ const expandedClaim = await virtualClaim.expand({ org });
167177
+ logger.info(`Loading virtual claim ${kind} ${name} ${org}`);
167178
+ LoadedClaims[`${kind}-${name}`] = catalog_common/* default.io.toYaml */.Z.io.toYaml(expandedClaim);
167179
+ VisitedClaims[`${kind}-${name}`] = 'virtual';
167180
+ }
167181
+
167182
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/claimsDefaulter.ts
167183
+
167184
+
167185
+
167186
+ /*
167187
+ * Default blocks are objects that cannot be merged but applied as a whole. Meaning:
167188
+ * - If the object is defined at the claim-level it is maintained *AS IT IS* (no merge)
167189
+ * - If the block is missing at the claim-level, the default block is applied
167190
+ */
167191
+ const defaultBlocksPaths = ['/providers/terraform/sync'];
167192
+ function applyBlockAwareDefaults(claim, defaultClaim) {
167193
+ // we always work with a clone of the original
167194
+ const claimClone = JSON.parse(JSON.stringify(claim));
167195
+ // if the block is claim-level defined we store it here
167196
+ const defaultBlocks = new Map();
167197
+ // we remove the blocks entirely of the claim
167198
+ // to achieve an add copy
167199
+ for (const defaultBlockPath of defaultBlocksPaths) {
167200
+ if (claimsDefaulter_hasDeepPath(claimClone, defaultBlockPath) !== true)
167201
+ continue;
167202
+ const originalValue = fast_json_patch_default().getValueByPointer(claimClone, defaultBlockPath);
167203
+ if (originalValue) {
167204
+ logger.silly(`${claim.kind}/${claim.name}: has an original ${defaultBlockPath}: preserving`);
167205
+ defaultBlocks.set(defaultBlockPath, originalValue);
167206
+ fast_json_patch_default().applyPatch(claimClone, [{ op: 'remove', path: defaultBlockPath }]);
167207
+ }
167208
+ }
167209
+ // if the patch has the same path of a block
167210
+ // and the block was defined at claim-level
167211
+ // we interchange the value with the original value
167212
+ // otherwise we use the default
167213
+ const jsonPatchOps = fast_json_patch_default().compare(claimClone, defaultClaim)
167214
+ .filter((jp) => jp.op === 'add')
167215
+ .map((jp) => {
167216
+ if (defaultBlocks.has(jp.path)) {
167217
+ return {
167218
+ ...jp,
167219
+ value: defaultBlocks.get(jp.path),
167220
+ };
167221
+ }
167222
+ else {
167223
+ return jp;
167224
+ }
167225
+ });
167226
+ return fast_json_patch_default().applyPatch(claimClone, jsonPatchOps).newDocument;
167227
+ }
167228
+ function claimsDefaulter_hasDeepPath(data, deepPath) {
167229
+ return lodash_default().has(data, deepPath.replace(/\//g, '.').replace(/^\./, ''));
167230
+ }
167231
+
167232
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/loader/loader.ts
167233
+
167234
+
167235
+
167236
+
167237
+
167238
+
167239
+
167240
+
167241
+
167242
+
167243
+
167244
+
167245
+
167246
+
167247
+
167248
+ const isYamlFile = new RegExp(/\.(yaml|yml)$/);
167249
+ /**
167250
+ *
167251
+ * @returns Virtual Claims
167252
+ */
167253
+ const virtualClaims = [new FirestartrAllClaim()];
167254
+ /*
167255
+ * Loads all applicable globals for a given claim and stores them into a list.
167256
+ *
167257
+ * Input:
167258
+ * - claim: our custom claim object, with which we check if the global is applicable
167259
+ *
167260
+ * Returns:
167261
+ * - A GlobalSection array promise, containing all the globals loaded for this claim
167262
+ *
167263
+ */
167264
+ async function loadGlobals(claim) {
167265
+ const result = [];
167266
+ await crawl(getPath('globals'), (entry) => {
167267
+ return isYamlFile.test(entry);
167268
+ }, async (entry, data) => {
167269
+ const globalData = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
167270
+ const ext = external_path_.extname(entry);
167271
+ const name = external_path_.basename(entry, ext);
167272
+ if (name in SECTIONS_BY_FILE_NAME) {
167273
+ const section = new SECTIONS_BY_FILE_NAME[name](globalData);
167274
+ if (!(await section.validate(SCHEMAS_BY_SECTION_NAME[name] || {}))) {
167275
+ throw new Error(`Invalid ${name} global file`);
167276
+ }
167277
+ if (globalData.kind === claim.kind) {
167278
+ result.push(section);
167279
+ }
167280
+ else {
167281
+ logger.debug(`Skipping global ${name} because it is not applicable to ${claim.kind}`);
167282
+ }
167283
+ }
167284
+ });
167285
+ logger.info(`Loaded globals ${result}`);
167286
+ return result;
167287
+ }
167288
+ /*
167289
+ * If the input claim is a GithubRepositoryClaim, it loads all it's applicable
167290
+ * overrides and stores them into a list. Otherwise, it returns an empty list.
167291
+ *
167292
+ * Input:
167293
+ * - claim: our custom claim object, which should be a GithubRepositoryClaim
167294
+ *
167295
+ * Returns:
167296
+ * - An Overrider array, with a GithubRepositoryOverrider if the claim
167297
+ * was a GithubRepositoryClaim, or empty if it was not.
167298
+ *
167299
+ */
167300
+ function loadOverrides(claim) {
167301
+ const overrides = [];
167302
+ if (claim.kind === 'ComponentClaim' && claim.providers.github.overrides) {
167303
+ overrides.push(new GithubRepositoryOverrider());
167304
+ }
167305
+ return overrides;
167306
+ }
167307
+ /**
167308
+ * Load all normalizers and stores them into a list.
167309
+ * @param claim
167310
+ * @returns
167311
+ */
167312
+ async function loadNormalizers(_claim, path) {
167313
+ const result = [];
167314
+ for (const normalizer of NORMALIZERS) {
167315
+ result.push(new normalizer({ path: path }));
167316
+ }
167317
+ return result;
167318
+ }
167319
+ /*
167320
+ * Loads all applicable initializers for a given claim and stores them into a list.
167321
+ *
167322
+ * Input:
167323
+ * - claim: our custom claim object, with which we check if the initializer is applicable
167324
+ *
167325
+ * Returns:
167326
+ * - An Initializer array promise, containing all the initializers loaded for this claim
167327
+ *
167328
+ */
167329
+ let loadedInitializers = false;
167330
+ async function loadInitializers(claim, claimPath, initializersPath = getPath('initializers')) {
167331
+ const result = [];
167332
+ await crawl(initializersPath, (entry) => {
167333
+ return isYamlFile.test(entry);
167334
+ }, async (entry, data) => {
167335
+ const initializerData = catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data);
167336
+ const ext = external_path_.extname(entry);
167337
+ const name = external_path_.basename(entry, ext);
167338
+ if (name in INITIALIZERS_BY_FILE_NAME) {
167339
+ const initializerBfN = new INITIALIZERS_BY_FILE_NAME[name](initializerData);
167340
+ if (!(await initializerBfN.validate(SCHEMAS_BY_INITIALIZER_NAME[name] || {}))) {
167341
+ throw new Error(`Invalid ${name} initializer file`);
167342
+ }
167343
+ if (initializerData.kind === claim.kind) {
167344
+ result.push(initializerBfN);
167345
+ }
167346
+ else {
167347
+ logger.debug(`Skipping initializer ${name} because it is not applicable to ${claim.kind}`);
167348
+ }
167349
+ }
167350
+ });
167351
+ for (const initializer of INITIALIZERS) {
167352
+ if (initializer.applicableKinds.includes(claim.kind)) {
167353
+ result.push(new initializer({ path: claimPath }));
167354
+ }
167355
+ }
167356
+ logger.info(`Loaded initializers ${JSON.stringify(result)}`);
167357
+ loadedInitializers = result;
167358
+ return loadedInitializers;
167359
+ }
167360
+ function loadClaimDefaults() {
167361
+ try {
167362
+ return catalog_common/* default.io.fromYaml */.Z.io.fromYaml(external_fs_.readFileSync(`${getPath('claimsDefaults')}/claims_defaults.yaml`, 'utf-8'));
167363
+ }
167364
+ catch (error) {
167365
+ const errMsg = `Could not read claims defaults file in path ${getPath('claimsDefaults')}/claims_defaults.yaml: ${error}`;
167366
+ logger.error(errMsg);
167367
+ throw new Error(errMsg);
167368
+ }
167369
+ }
167370
+ /*
167371
+ * Using fast-json-patch, compares a claim to its kind's defaults, then patches it.
167372
+ *
167373
+ * Input:
167374
+ * - claim: our custom claim object, which we want to patch
167375
+ * - defaultsClaims: an object, containing the defaults for each claim kind,
167376
+ * with the same structure that we use for the actual claims
167377
+ *
167378
+ * Returns:
167379
+ * - The patched claim
167380
+ *
167381
+ */
167382
+ function loader_patchClaim(claim, defaultsClaims) {
167383
+ if (defaultsClaims[claim.kind]) {
167384
+ claim = applyBlockAwareDefaults(claim, defaultsClaims[claim.kind]);
167385
+ }
167386
+ return claim;
167387
+ }
167388
+ async function loadCRsWithFullSet(crsPath = getPath('crs'), excludedPaths = [getPath('globals'), getPath('initializers')], allowedClaimReferences = []) {
167389
+ const result = {};
167390
+ const fullResult = {};
167391
+ await crawlWithExclusions(crsPath, (entry) => {
167392
+ return isYamlFile.test(entry);
167393
+ }, async (entry, data) => {
167394
+ const yamlData = stripKnownRelations(catalog_common/* default.io.fromYaml */.Z.io.fromYaml(data));
167395
+ const metadata = yamlData?.metadata;
167396
+ if (!(yamlData &&
167397
+ typeof yamlData === 'object' &&
167398
+ 'kind' in yamlData &&
167399
+ metadata &&
167400
+ typeof metadata === 'object' &&
167401
+ 'name' in metadata)) {
167402
+ logger.warn(`Invalid CR file ${entry}`);
167403
+ }
167404
+ else {
167405
+ const crKey = `${yamlData.kind}-${metadata.name}`;
167406
+ if (fullResult[crKey]) {
167407
+ logger.error(`Duplicate CR ${crKey}`);
167408
+ }
167409
+ // Keep the complete CR set for validations that need repository-wide context.
167410
+ fullResult[crKey] = yamlData;
167411
+ // Keep the filtered CR set for previous-CR lookup during claim rendering.
167412
+ if (allowedClaimReferences.length === 0 ||
167413
+ allowedClaimReferences.includes(yamlData.metadata?.annotations?.[catalog_common/* default.generic.getFirestartrAnnotation */.Z.generic.getFirestartrAnnotation('claim-ref')])) {
167414
+ result[crKey] = yamlData;
167415
+ }
167416
+ }
167417
+ }, excludedPaths.concat(getAdditionalPaths()));
167418
+ return { crs: result, fullCrs: fullResult };
167419
+ }
167420
+ async function loadCRs(crsPath = getPath('crs'), excludedPaths = [getPath('globals'), getPath('initializers')], allowedClaimReferences = []) {
167421
+ const { crs } = await loadCRsWithFullSet(crsPath, excludedPaths, allowedClaimReferences);
167422
+ return crs;
167423
+ }
167424
+ /*
167425
+ * Description: Get the renamed using claimRef annotation
167426
+ * Input: claims: any, crs: any
167427
+ * Output: renames: IRenameResult[]
167428
+ */
167429
+ async function loadRenames(claims, crs) {
167430
+ /*
167431
+ * If checkRenames is false, we don't need to check for renames
167432
+ */
167433
+ const renamesEnabled = getRenamesEnabled();
167434
+ if (!renamesEnabled)
167435
+ return [];
167436
+ const result = [];
167437
+ /**
167438
+ * For each CR, look for a claim that does not match the name with CR's firestartr.dev/claim-ref annotation
167439
+ */
167440
+ for (const cr of Object.values(crs)) {
167441
+ const anyCr = cr;
167442
+ if (!anyCr?.metadata?.annotations)
167443
+ continue;
167444
+ // if the annotation is a claimRef
167445
+ const annotationName = common.generic.getFirestartrAnnotation('claim-ref');
167446
+ const annotations = anyCr?.metadata?.annotations || {};
167447
+ if (annotationName in annotations) {
167448
+ const claimRef = anyCr.metadata.annotations[annotationName];
167449
+ // split the annotation into kind and name
167450
+ const [kind, name] = claimRef.split('/');
167451
+ // if the claim exists, check if the name is different for the given provider
167452
+ const referencedClaim = claims[`${kind}-${name}`].claim;
167453
+ const oldName = anyCr.metadata.name;
167454
+ const newName = referencedClaim.providers[getConfiguredProvider()].name;
167455
+ if (oldName !== newName) {
167456
+ result.push({
167457
+ kind: referencedClaim.kind,
167458
+ claimPath: claims[`${kind}-${name}`].claimPath,
167459
+ claimName: referencedClaim.name,
167460
+ oldName,
167461
+ newName,
167462
+ });
167463
+ }
167464
+ }
167465
+ }
167466
+ return result;
167467
+ }
167468
+ async function loadClaimsList(claimRefList, claimsPath = getPath('claims')) {
167469
+ const data = {
167470
+ renderClaims: {},
167471
+ crs: {},
167472
+ fullCrs: {},
167473
+ };
167474
+ const defaults = loadClaimDefaults();
167475
+ for await (const claimRef of claimRefList) {
167476
+ const [renderedClaimData] = await loadClaim(claimRef, getOrg(), defaults, loader_patchClaim, loadInitializers, loadGlobals, loadOverrides, loadNormalizers, claimsPath);
167477
+ data.renderClaims = lodash_default().merge(data.renderClaims, renderedClaimData);
167478
+ }
167479
+ const crClaimReferences = [];
167480
+ for (const ref of Object.keys(data.renderClaims)) {
167481
+ // Replaces only the first instance of '-'
167482
+ crClaimReferences.push(ref.replace('-', '/'));
167483
+ }
167484
+ const loadedCrs = await loadCRsWithFullSet(getPath('crs'), [getPath('globals'), getPath('initializers')], crClaimReferences);
167485
+ data['crs'] = loadedCrs.crs;
167486
+ data['fullCrs'] = loadedCrs.fullCrs;
167487
+ return data;
167488
+ }
167489
+ function getOrg() {
167490
+ const groupOrg = catalog_common/* default.environment.getFromEnvironmentWithDefault */.Z.environment.getFromEnvironmentWithDefault(catalog_common/* default.types.envVars.org */.Z.types.envVars.org, '');
167491
+ return groupOrg;
167492
+ }
167493
+
167494
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/references.ts
167495
+ function validateTfStateKeyUniqueness(crs) {
167496
+ const tfStateKeys = {};
167497
+ for (const crKey of Object.keys(crs)) {
167498
+ const cr = crs[crKey];
167499
+ if (!isTerraformWorkspace(cr))
167500
+ continue;
167501
+ const tfKey = cr.spec.firestartr.tfStateKey;
167502
+ if (tfStateKeys[tfKey]) {
167503
+ throw new Error(`❗❗ ❌ RENDER ERROR ❌ ❗❗
167504
+
167505
+ The tfStateKey ${tfKey} is not unique,
167506
+
167507
+ It is being used by the following CRs:
167508
+
167509
+ - ${tfStateKeys[tfKey].kind} ${tfStateKeys[tfKey].metadata.name}
167510
+
167511
+ - ${cr.kind} ${cr.metadata.name}
167512
+
167513
+ Check the following Claims to ensure that the tfStateKey is unique:
167514
+
167515
+ - ${tfStateKeys[tfKey].metadata.annotations['firestartr.dev/claim-ref']}
167516
+
167517
+ - ${cr.metadata.annotations['firestartr.dev/claim-ref']}
167518
+ `);
167519
+ }
167520
+ tfStateKeys[cr.spec.firestartr.tfStateKey] = cr;
167521
+ }
167522
+ }
167523
+ function references_isCatalogEntity(cr) {
167524
+ return [
167525
+ 'Component',
167526
+ 'Domain',
167527
+ 'System',
167528
+ 'User',
167529
+ 'Group',
167530
+ 'Resource',
167531
+ ].includes(cr.kind);
167532
+ }
167533
+ function isTerraformWorkspace(cr) {
167534
+ return cr.kind === 'FirestartrTerraformWorkspace';
167535
+ }
167536
+
167537
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/crSize.ts
167538
+
167539
+ const K8S_OBJECT_SIZE_LIMIT = 1572864; // 1.5 MiB in bytes, etcd recommended limit: https://etcd.io/docs/latest/dev-guide/limit/
167540
+ function validateCrSizes(crs) {
167541
+ for (const key of Object.keys(crs)) {
167542
+ const cr = crs[key];
167543
+ const serialized = catalog_common/* default.io.toYaml */.Z.io.toYaml(cr);
167544
+ const size = Buffer.byteLength(serialized, 'utf8');
167545
+ if (size > K8S_OBJECT_SIZE_LIMIT) {
167546
+ throw new Error(`CR "${cr.kind}-${cr.metadata.name}" exceeds the Kubernetes object size limit by ${size - K8S_OBJECT_SIZE_LIMIT} bytes. Maximum allowed is ${K8S_OBJECT_SIZE_LIMIT} bytes (1.5MiB).`);
167547
+ }
167548
+ }
167549
+ }
167550
+
167551
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/permissions.ts
167552
+
167553
+ function validatePermissionsUniqueness(crs) {
167554
+ for (const crkey in crs) {
167555
+ const cr = crs[crkey];
167556
+ if (cr.kind === 'FirestartrGithubRepository') {
167557
+ const permissions = cr.spec.permissions;
167558
+ logger.debug(`Validating Permissions Uniqueness of ${crkey}`);
167559
+ if (permissions) {
167560
+ const rolesByIdentifier = new Map();
167561
+ for (const perm of permissions) {
167562
+ const identifier = perm.collaborator
167563
+ ? perm.collaborator
167564
+ : `ref:${perm.ref.kind}:${perm.ref.name}`;
167565
+ const role = perm.role;
167566
+ const prevRole = rolesByIdentifier.get(identifier);
167567
+ if (prevRole === undefined) {
167568
+ rolesByIdentifier.set(identifier, role);
167569
+ }
167570
+ else if (prevRole !== role) {
167571
+ throw new Error(`Conflicting permission role in FirestartrGithubRepository ${crkey}: ${identifier} has roles "${prevRole}" and "${role}".\nFull CR: ${JSON.stringify(cr, null, 2)}`);
167572
+ }
167573
+ }
167574
+ }
167575
+ }
167576
+ }
167577
+ }
167578
+
167579
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/backstageAnnotations.ts
167580
+ const backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX = 'firestartr.backstage.dev/';
167581
+ const CATALOG_KINDS = new Set([
167582
+ 'User',
167583
+ 'Group',
167584
+ 'Component',
167585
+ 'System',
167586
+ 'Domain',
167587
+ 'API',
167588
+ 'Resource',
167589
+ 'CatalogKubernetesResource',
167590
+ 'CatalogTerraformWorkspace',
167591
+ 'CatalogArgoDeploy',
167592
+ 'CatalogOrgWebhook',
167593
+ 'CatalogSecrets',
167594
+ ]);
167595
+ function validateNoBackstageAnnotationsInK8sCrs(crs) {
167596
+ for (const crKey in crs) {
167597
+ const cr = crs[crKey];
167598
+ if (CATALOG_KINDS.has(cr.kind))
167599
+ continue;
167600
+ if (cr.metadata?.annotations) {
167601
+ const backstageKeys = Object.keys(cr.metadata.annotations).filter((k) => k.startsWith(backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX));
167602
+ if (backstageKeys.length > 0) {
167603
+ throw new Error(`K8s CR ${crKey} contains Backstage-only annotations (${backstageKeys.join(', ')}). ` +
167604
+ `Annotations with prefix ${backstageAnnotations_BACKSTAGE_ANNOTATION_PREFIX} must only appear on Backstage catalog entities, not on Kubernetes CRs.`);
167605
+ }
167606
+ }
167607
+ }
167608
+ }
167609
+
167610
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/refsSorter/refsSorter.ts
167611
+
167612
+ /**
167613
+ * @param renderClaims renderClaims to sort
167614
+ * @param kinds kinds to get from renderClaims
167615
+ * @returns renderClaims with only the kinds specified
167616
+ */
167617
+ function sortRenderClaimsByKind(renderClaims, kinds) {
167618
+ let result = {};
167619
+ for (const kind of kinds) {
167620
+ for (const key in renderClaims) {
167621
+ if (renderClaims[key].claim.kind === kind) {
167622
+ result[key] = renderClaims[key];
167623
+ }
167624
+ }
167625
+ result = sortSelfKindRefs(result, kind);
167626
+ }
167627
+ return result;
167628
+ }
167629
+ function sortSelfKindRefs(renderClaims, kind) {
167630
+ if (!hasSelfRefs(kind)) {
167631
+ return renderClaims;
167632
+ }
167633
+ const newRenderClaims = {};
167634
+ const data = extractRefs(renderClaims, kind);
167635
+ const ordered = [];
167636
+ const visiting = [];
167637
+ const visited = [];
167638
+ for (const key of Object.keys(data)) {
167639
+ if (!visited.find((obj) => obj.name === key)) {
167640
+ sortRefs(data, data[key], ordered, visiting, visited);
167641
+ }
167642
+ }
167643
+ for (const cr of ordered) {
167644
+ newRenderClaims[cr.name] = renderClaims[cr.name];
167645
+ }
167646
+ return newRenderClaims;
167647
+ }
167648
+ function sortRefs(data, claim, ordered = [], visiting = [], visited = []) {
167649
+ if (visiting.find((obj) => obj.name === claim.name)) {
167650
+ throw new Error(`Circular dependency detected for '${claim.name}'`);
167651
+ }
167652
+ if (!visited.find((obj) => obj.name === claim.name)) {
167653
+ visiting.push(claim);
167654
+ if (claim.refs) {
167655
+ for (const ref of claim.refs) {
167656
+ const referencedObject = data[ref];
167657
+ if (!referencedObject) {
167658
+ throw new Error(`Reference '${ref}' does not exist for '${claim.name}'`);
167659
+ }
167660
+ sortRefs(data, referencedObject, ordered, visiting, visited);
167661
+ }
167662
+ }
167663
+ visited.push(visiting.pop());
167664
+ ordered.push(claim);
167665
+ }
167666
+ }
167667
+ function hasSelfRefs(kind) {
167668
+ return ['TFWorkspaceClaim', 'GroupClaim'].includes(kind);
167669
+ }
167670
+
167671
+ ;// CONCATENATED MODULE: ../cdk8s_renderer/src/renderer/claims-sorter.ts
167672
+
167673
+ function sortKinds(orderedKinds, claims) {
167674
+ const result = [];
167675
+ for (const kind of orderedKinds) {
167676
+ const kindRenderClaims = sortRenderClaimsByKind(claims, [kind]);
167677
+ result.push(kindRenderClaims);
167678
+ }
167679
+ return result;
167680
+ }
167681
+
167208
167682
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/overriders/utils.ts
167209
167683
 
167210
167684
 
@@ -167255,14 +167729,12 @@ async function utils_renderFeature(featureName, featureVersion, featureOutputObj
167255
167729
 
167256
167730
 
167257
167731
 
167258
-
167259
-
167260
167732
  // this is the only way currently to make
167261
167733
  // work the system and inject our code
167262
167734
  // without having to download a feature
167263
- let MOCK_FEATURES_FN;
167735
+ let featureOverride_MOCK_FEATURES_FN;
167264
167736
  function MOCK_FEATURES(mock) {
167265
- MOCK_FEATURES_FN = mock;
167737
+ featureOverride_MOCK_FEATURES_FN = mock;
167266
167738
  if (mock) {
167267
167739
  log.warn('⚠️ Warning features system downloader has been mocked, it should only happen in unit testing');
167268
167740
  }
@@ -167293,8 +167765,8 @@ class FeaturesOverrider extends OverriderPatches {
167293
167765
  let owner = 'prefapp';
167294
167766
  let versionOrRef = this.featureVersion;
167295
167767
  let renderer = 'getFeatureConfig';
167296
- if (MOCK_FEATURES_FN) {
167297
- return MOCK_FEATURES_FN();
167768
+ if (featureOverride_MOCK_FEATURES_FN) {
167769
+ return featureOverride_MOCK_FEATURES_FN();
167298
167770
  }
167299
167771
  if (this.featureRepo) {
167300
167772
  [owner, repo] = this.featureRepo.split(/\//);
@@ -167312,8 +167784,8 @@ class FeaturesOverrider extends OverriderPatches {
167312
167784
  const featureName = this.featureName;
167313
167785
  const featureVersion = this.featureVersion || this.featureRef;
167314
167786
  const featureArgs = this.featureArgs;
167315
- const fSetUpAndRunRenderer = function (cr) {
167316
- return this.setUpAndRunRenderer(cr);
167787
+ const fSetUpAndRunRenderer = function (target) {
167788
+ return this.setUpAndRunRenderer(target);
167317
167789
  }.bind(this);
167318
167790
  let renderedFeatureConfig = null;
167319
167791
  return [
@@ -167322,7 +167794,7 @@ class FeaturesOverrider extends OverriderPatches {
167322
167794
  return true;
167323
167795
  },
167324
167796
  async apply(cr) {
167325
- renderedFeatureConfig = await fSetUpAndRunRenderer(cr);
167797
+ renderedFeatureConfig = await fSetUpAndRunRenderer(claim);
167326
167798
  return cr;
167327
167799
  },
167328
167800
  identify() {
@@ -167335,28 +167807,6 @@ class FeaturesOverrider extends OverriderPatches {
167335
167807
  return utils_renderFeature(featureName, featureVersion, renderedFeatureConfig, cr, claim.name);
167336
167808
  },
167337
167809
  },
167338
- {
167339
- isPostPatch: true,
167340
- validate() {
167341
- return true;
167342
- },
167343
- async apply(cr) {
167344
- if (!renderedFeatureConfig) {
167345
- logger.warn(`Feature ${featureName}: renderedFeatureConfig is null, skipping post-patch`);
167346
- return cr;
167347
- }
167348
- const provider = helperCTX(this).provider;
167349
- const jsonPatches = renderedFeatureConfig.patches?.[provider] || [];
167350
- fast_json_patch_default().applyPatch(cr, jsonPatches);
167351
- return cr;
167352
- },
167353
- identify() {
167354
- return `feature-json-patch/${featureName}`;
167355
- },
167356
- applicable() {
167357
- return { applicableProviders: ['catalog', 'github'] };
167358
- },
167359
- },
167360
167810
  ];
167361
167811
  }
167362
167812
  }
@@ -168184,412 +168634,6 @@ var FirestartrGithubMembershipSpecContextProviderRefKind;
168184
168634
  /** FirestartrProviderConfig */
168185
168635
  FirestartrGithubMembershipSpecContextProviderRefKind["FIRESTARTR_PROVIDER_CONFIG"] = "FirestartrProviderConfig";
168186
168636
  })(FirestartrGithubMembershipSpecContextProviderRefKind || (FirestartrGithubMembershipSpecContextProviderRefKind = {}));
168187
- /**
168188
- * A resource to handle GitHub Organization Actions Secrets.
168189
- *
168190
- * @schema FirestartrGithubOrganizationSecretSection
168191
- */
168192
- class FirestartrGithubOrganizationSecretSection extends lib.ApiObject {
168193
- /**
168194
- * Renders a Kubernetes manifest for "FirestartrGithubOrganizationSecretSection".
168195
- *
168196
- * This can be used to inline resource manifests inside other objects (e.g. as templates).
168197
- *
168198
- * @param props initialization props
168199
- */
168200
- static manifest(props) {
168201
- return {
168202
- ...FirestartrGithubOrganizationSecretSection.GVK,
168203
- ...toJson_FirestartrGithubOrganizationSecretSectionProps(props),
168204
- };
168205
- }
168206
- /**
168207
- * Defines a "FirestartrGithubOrganizationSecretSection" API object
168208
- * @param scope the scope in which to define this object
168209
- * @param id a scope-local name for the object
168210
- * @param props initialization props
168211
- */
168212
- constructor(scope, id, props) {
168213
- super(scope, id, {
168214
- ...FirestartrGithubOrganizationSecretSection.GVK,
168215
- ...props,
168216
- });
168217
- }
168218
- /**
168219
- * Renders the object to Kubernetes JSON.
168220
- */
168221
- toJson() {
168222
- const resolved = super.toJson();
168223
- return {
168224
- ...FirestartrGithubOrganizationSecretSection.GVK,
168225
- ...toJson_FirestartrGithubOrganizationSecretSectionProps(resolved),
168226
- };
168227
- }
168228
- }
168229
- /**
168230
- * Returns the apiVersion and kind for "FirestartrGithubOrganizationSecretSection"
168231
- */
168232
- FirestartrGithubOrganizationSecretSection.GVK = {
168233
- apiVersion: 'firestartr.dev/v1',
168234
- kind: 'FirestartrGithubOrganizationSecretSection',
168235
- };
168236
-
168237
- /**
168238
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionProps' to JSON representation.
168239
- */
168240
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168241
- function toJson_FirestartrGithubOrganizationSecretSectionProps(obj) {
168242
- if (obj === undefined) {
168243
- return undefined;
168244
- }
168245
- const result = {
168246
- 'metadata': obj.metadata,
168247
- 'spec': toJson_FirestartrGithubOrganizationSecretSectionSpec(obj.spec),
168248
- };
168249
- // filter undefined values
168250
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168251
- }
168252
- /**
168253
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpec' to JSON representation.
168254
- */
168255
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168256
- function toJson_FirestartrGithubOrganizationSecretSectionSpec(obj) {
168257
- if (obj === undefined) {
168258
- return undefined;
168259
- }
168260
- const result = {
168261
- 'org': obj.org,
168262
- 'secrets': toJson_FirestartrGithubOrganizationSecretSectionSpecSecrets(obj.secrets),
168263
- 'context': toJson_FirestartrGithubOrganizationSecretSectionSpecContext(obj.context),
168264
- 'firestartr': toJson_FirestartrGithubOrganizationSecretSectionSpecFirestartr(obj.firestartr),
168265
- 'writeConnectionSecretToRef': toJson_FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRef(obj.writeConnectionSecretToRef),
168266
- };
168267
- // filter undefined values
168268
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168269
- }
168270
- /**
168271
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecrets' to JSON representation.
168272
- */
168273
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168274
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecrets(obj) {
168275
- if (obj === undefined) {
168276
- return undefined;
168277
- }
168278
- const result = {
168279
- 'actions': obj.actions?.map(y => toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsActions(y)),
168280
- 'codespaces': obj.codespaces?.map(y => toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsCodespaces(y)),
168281
- 'dependabot': obj.dependabot?.map(y => toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsDependabot(y)),
168282
- };
168283
- // filter undefined values
168284
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168285
- }
168286
- /**
168287
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecContext' to JSON representation.
168288
- */
168289
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168290
- function toJson_FirestartrGithubOrganizationSecretSectionSpecContext(obj) {
168291
- if (obj === undefined) {
168292
- return undefined;
168293
- }
168294
- const result = {
168295
- 'backend': toJson_FirestartrGithubOrganizationSecretSectionSpecContextBackend(obj.backend),
168296
- 'provider': toJson_FirestartrGithubOrganizationSecretSectionSpecContextProvider(obj.provider),
168297
- };
168298
- // filter undefined values
168299
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168300
- }
168301
- /**
168302
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecFirestartr' to JSON representation.
168303
- */
168304
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168305
- function toJson_FirestartrGithubOrganizationSecretSectionSpecFirestartr(obj) {
168306
- if (obj === undefined) {
168307
- return undefined;
168308
- }
168309
- const result = {
168310
- 'tfStateKey': obj.tfStateKey,
168311
- };
168312
- // filter undefined values
168313
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168314
- }
168315
- /**
168316
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRef' to JSON representation.
168317
- */
168318
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168319
- function toJson_FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRef(obj) {
168320
- if (obj === undefined) {
168321
- return undefined;
168322
- }
168323
- const result = {
168324
- 'name': obj.name,
168325
- 'outputs': obj.outputs?.map(y => toJson_FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRefOutputs(y)),
168326
- };
168327
- // filter undefined values
168328
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168329
- }
168330
- /**
168331
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsActions' to JSON representation.
168332
- */
168333
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168334
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsActions(obj) {
168335
- if (obj === undefined) {
168336
- return undefined;
168337
- }
168338
- const result = {
168339
- 'name': obj.name,
168340
- 'ref': toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRef(obj.ref),
168341
- 'visibility': obj.visibility,
168342
- 'selectedRepositories': obj.selectedRepositories?.map(y => y),
168343
- };
168344
- // filter undefined values
168345
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168346
- }
168347
- /**
168348
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsCodespaces' to JSON representation.
168349
- */
168350
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168351
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsCodespaces(obj) {
168352
- if (obj === undefined) {
168353
- return undefined;
168354
- }
168355
- const result = {
168356
- 'name': obj.name,
168357
- 'ref': toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRef(obj.ref),
168358
- 'visibility': obj.visibility,
168359
- 'selectedRepositories': obj.selectedRepositories?.map(y => y),
168360
- };
168361
- // filter undefined values
168362
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168363
- }
168364
- /**
168365
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsDependabot' to JSON representation.
168366
- */
168367
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168368
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsDependabot(obj) {
168369
- if (obj === undefined) {
168370
- return undefined;
168371
- }
168372
- const result = {
168373
- 'name': obj.name,
168374
- 'ref': toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRef(obj.ref),
168375
- 'visibility': obj.visibility,
168376
- 'selectedRepositories': obj.selectedRepositories?.map(y => y),
168377
- };
168378
- // filter undefined values
168379
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168380
- }
168381
- /**
168382
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecContextBackend' to JSON representation.
168383
- */
168384
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168385
- function toJson_FirestartrGithubOrganizationSecretSectionSpecContextBackend(obj) {
168386
- if (obj === undefined) {
168387
- return undefined;
168388
- }
168389
- const result = {
168390
- 'ref': toJson_FirestartrGithubOrganizationSecretSectionSpecContextBackendRef(obj.ref),
168391
- };
168392
- // filter undefined values
168393
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168394
- }
168395
- /**
168396
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecContextProvider' to JSON representation.
168397
- */
168398
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168399
- function toJson_FirestartrGithubOrganizationSecretSectionSpecContextProvider(obj) {
168400
- if (obj === undefined) {
168401
- return undefined;
168402
- }
168403
- const result = {
168404
- 'ref': toJson_FirestartrGithubOrganizationSecretSectionSpecContextProviderRef(obj.ref),
168405
- };
168406
- // filter undefined values
168407
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168408
- }
168409
- /**
168410
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRefOutputs' to JSON representation.
168411
- */
168412
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168413
- function toJson_FirestartrGithubOrganizationSecretSectionSpecWriteConnectionSecretToRefOutputs(obj) {
168414
- if (obj === undefined) {
168415
- return undefined;
168416
- }
168417
- const result = {
168418
- 'key': obj.key,
168419
- };
168420
- // filter undefined values
168421
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168422
- }
168423
- /**
168424
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRef' to JSON representation.
168425
- */
168426
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168427
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRef(obj) {
168428
- if (obj === undefined) {
168429
- return undefined;
168430
- }
168431
- const result = {
168432
- 'kind': obj.kind,
168433
- 'name': obj.name,
168434
- 'key': obj.key,
168435
- };
168436
- // filter undefined values
168437
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168438
- }
168439
- /* eslint-enable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168440
- /**
168441
- * Which repositories can access the secret.
168442
- *
168443
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility
168444
- */
168445
- var FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility;
168446
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility) {
168447
- /** all */
168448
- FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility["ALL"] = "all";
168449
- /** selected */
168450
- FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility["SELECTED"] = "selected";
168451
- /** private */
168452
- FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility["PRIVATE"] = "private";
168453
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility || (FirestartrGithubOrganizationSecretSectionSpecSecretsActionsVisibility = {}));
168454
- /**
168455
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRef' to JSON representation.
168456
- */
168457
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168458
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRef(obj) {
168459
- if (obj === undefined) {
168460
- return undefined;
168461
- }
168462
- const result = {
168463
- 'kind': obj.kind,
168464
- 'name': obj.name,
168465
- 'key': obj.key,
168466
- };
168467
- // filter undefined values
168468
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168469
- }
168470
- /* eslint-enable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168471
- /**
168472
- * Which repositories can access the secret.
168473
- *
168474
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility
168475
- */
168476
- var FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility;
168477
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility) {
168478
- /** all */
168479
- FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility["ALL"] = "all";
168480
- /** selected */
168481
- FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility["SELECTED"] = "selected";
168482
- /** private */
168483
- FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility["PRIVATE"] = "private";
168484
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility || (FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesVisibility = {}));
168485
- /**
168486
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRef' to JSON representation.
168487
- */
168488
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168489
- function toJson_FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRef(obj) {
168490
- if (obj === undefined) {
168491
- return undefined;
168492
- }
168493
- const result = {
168494
- 'kind': obj.kind,
168495
- 'name': obj.name,
168496
- 'key': obj.key,
168497
- };
168498
- // filter undefined values
168499
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168500
- }
168501
- /* eslint-enable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168502
- /**
168503
- * Which repositories can access the secret.
168504
- *
168505
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility
168506
- */
168507
- var FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility;
168508
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility) {
168509
- /** all */
168510
- FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility["ALL"] = "all";
168511
- /** selected */
168512
- FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility["SELECTED"] = "selected";
168513
- /** private */
168514
- FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility["PRIVATE"] = "private";
168515
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility || (FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotVisibility = {}));
168516
- /**
168517
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecContextBackendRef' to JSON representation.
168518
- */
168519
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168520
- function toJson_FirestartrGithubOrganizationSecretSectionSpecContextBackendRef(obj) {
168521
- if (obj === undefined) {
168522
- return undefined;
168523
- }
168524
- const result = {
168525
- 'kind': obj.kind,
168526
- 'name': obj.name,
168527
- };
168528
- // filter undefined values
168529
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168530
- }
168531
- /**
168532
- * Converts an object of type 'FirestartrGithubOrganizationSecretSectionSpecContextProviderRef' to JSON representation.
168533
- */
168534
- /* eslint-disable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168535
- function toJson_FirestartrGithubOrganizationSecretSectionSpecContextProviderRef(obj) {
168536
- if (obj === undefined) {
168537
- return undefined;
168538
- }
168539
- const result = {
168540
- 'kind': obj.kind,
168541
- 'name': obj.name,
168542
- };
168543
- // filter undefined values
168544
- return Object.entries(result).reduce((r, i) => (i[1] === undefined) ? r : ({ ...r, [i[0]]: i[1] }), {});
168545
- }
168546
- /* eslint-enable max-len, @stylistic/max-len, quote-props, @stylistic/quote-props */
168547
- /**
168548
- * The type of Kubernetes resource to reference.
168549
- *
168550
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind
168551
- */
168552
- var FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind;
168553
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind) {
168554
- /** Secret */
168555
- FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind["SECRET"] = "Secret";
168556
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind || (FirestartrGithubOrganizationSecretSectionSpecSecretsActionsRefKind = {}));
168557
- /**
168558
- * The type of Kubernetes resource to reference.
168559
- *
168560
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind
168561
- */
168562
- var FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind;
168563
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind) {
168564
- /** Secret */
168565
- FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind["SECRET"] = "Secret";
168566
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind || (FirestartrGithubOrganizationSecretSectionSpecSecretsCodespacesRefKind = {}));
168567
- /**
168568
- * The type of Kubernetes resource to reference.
168569
- *
168570
- * @schema FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind
168571
- */
168572
- var FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind;
168573
- (function (FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind) {
168574
- /** Secret */
168575
- FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind["SECRET"] = "Secret";
168576
- })(FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind || (FirestartrGithubOrganizationSecretSectionSpecSecretsDependabotRefKind = {}));
168577
- /**
168578
- * @schema FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind
168579
- */
168580
- var FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind;
168581
- (function (FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind) {
168582
- /** FirestartrProviderConfig */
168583
- FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind["FIRESTARTR_PROVIDER_CONFIG"] = "FirestartrProviderConfig";
168584
- })(FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind || (FirestartrGithubOrganizationSecretSectionSpecContextBackendRefKind = {}));
168585
- /**
168586
- * @schema FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind
168587
- */
168588
- var FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind;
168589
- (function (FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind) {
168590
- /** FirestartrProviderConfig */
168591
- FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind["FIRESTARTR_PROVIDER_CONFIG"] = "FirestartrProviderConfig";
168592
- })(FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind || (FirestartrGithubOrganizationSecretSectionSpecContextProviderRefKind = {}));
168593
168637
  /**
168594
168638
  * A resource to handle GitHub Organization Settings.
168595
168639
  *
@@ -172045,78 +172089,6 @@ class GithubOrgVariableSectionChart extends BaseGithubChart {
172045
172089
  }
172046
172090
  }
172047
172091
 
172048
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/charts/github/orgSecretSectionChart.ts
172049
-
172050
-
172051
-
172052
- class GithubOrgSecretSectionChart extends BaseGithubChart {
172053
- template() {
172054
- const claim = this.get('claim');
172055
- const firestartrId = this.get('firestartrId');
172056
- const githubProvider = claim.providers.github;
172057
- const orgSecrets = githubProvider.org_secrets || {};
172058
- const renderSecrets = (section) => {
172059
- const secrets = orgSecrets[section];
172060
- if (!Array.isArray(secrets))
172061
- return [];
172062
- return secrets.map((secret) => {
172063
- const parts = secret.value.split(':');
172064
- const selectedRepositories = (secret.selected_repositories || []).map((ref) => {
172065
- const match = ref.match(/^component:(.+)$/);
172066
- if (!match) {
172067
- throw new ChartRenderError('OrgSettingsClaim', claim.name, `Invalid component ref "${ref}" in selected_repositories. Expected format: component:<name>`);
172068
- }
172069
- const componentName = match[1];
172070
- const resolvedCr = this.refResolver('ComponentClaim', componentName);
172071
- const org = resolvedCr?.spec?.org;
172072
- const repoName = resolvedCr?.metadata?.annotations?.['firestartr.dev/external-name'] || resolvedCr?.metadata?.name?.replace(/-[0-9a-f-]{36}$/, '');
172073
- if (!org || !repoName) {
172074
- throw new ChartRenderError('OrgSettingsClaim', claim.name, `Referenced component "${componentName}" has no GitHub provider configured`);
172075
- }
172076
- return `${org}/${repoName}`;
172077
- });
172078
- return {
172079
- name: secret.name,
172080
- ref: {
172081
- kind: 'Secret',
172082
- name: parts[2],
172083
- key: parts[3],
172084
- },
172085
- visibility: secret.visibility || 'all',
172086
- selectedRepositories,
172087
- };
172088
- });
172089
- };
172090
- const template = {
172091
- metadata: {
172092
- name: githubProvider.name,
172093
- },
172094
- spec: {
172095
- org: githubProvider.org,
172096
- secrets: {
172097
- actions: renderSecrets('actions'),
172098
- codespaces: renderSecrets('codespaces'),
172099
- dependabot: renderSecrets('dependabot'),
172100
- },
172101
- firestartr: {
172102
- tfStateKey: firestartrId,
172103
- },
172104
- writeConnectionSecretToRef: {
172105
- name: `firestartrgithuborganizationsecretsection-${githubProvider.name}-secrets-outputs`.toLowerCase(),
172106
- outputs: [{ key: 'managed_secrets' }, { key: 'secret_ids' }],
172107
- },
172108
- },
172109
- };
172110
- return JSON.parse(JSON.stringify(template));
172111
- }
172112
- gvk() {
172113
- return FirestartrGithubOrganizationSecretSection.GVK;
172114
- }
172115
- instanceApiObject(template) {
172116
- return new FirestartrGithubOrganizationSecretSection(this, template.metadata.name, template);
172117
- }
172118
- }
172119
-
172120
172092
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/charts/github/index.ts
172121
172093
 
172122
172094
 
@@ -172125,7 +172097,6 @@ class GithubOrgSecretSectionChart extends BaseGithubChart {
172125
172097
 
172126
172098
 
172127
172099
 
172128
-
172129
172100
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/charts/catalog/base.ts
172130
172101
 
172131
172102
  class BaseCatalogChart extends BaseChart {
@@ -172888,7 +172859,6 @@ class SecretsChart extends BaseSecretsChart {
172888
172859
  GithubOrgWebhookChart: GithubOrgWebhookChart,
172889
172860
  GithubOrgSettingsChart: GithubOrgSettingsChart,
172890
172861
  GithubOrgVariableSectionChart: GithubOrgVariableSectionChart,
172891
- GithubOrgSecretSectionChart: GithubOrgSecretSectionChart,
172892
172862
  });
172893
172863
 
172894
172864
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/renderer/claims-render.ts
@@ -172940,21 +172910,16 @@ async function renderClaims(catalogScope, firestartrScope, data) {
172940
172910
  const variableSectionPreviousCR = claim.kind === 'OrgSettingsClaim'
172941
172911
  ? getPreviousCRfromClaim(claim, crs, 'FirestartrGithubOrganizationVariableSection')
172942
172912
  : false;
172943
- const secretSectionPreviousCR = claim.kind === 'OrgSettingsClaim'
172944
- ? getPreviousCRfromClaim({ kind: claim.kind, name: `${claim.name}-secret-section` }, crs, 'FirestartrGithubOrganizationSecretSection')
172945
- : false;
172946
172913
  const patches = await extractPatches(renderClaims[claimKey], previousCR, crs);
172947
172914
  let variableSectionPatches = undefined;
172948
- let secretSectionPatches = undefined;
172949
172915
  if (claim.kind === 'OrgSettingsClaim') {
172950
172916
  variableSectionPatches = await extractPatches(renderClaims[claimKey], variableSectionPreviousCR, crs);
172951
- secretSectionPatches = await extractPatches(renderClaims[claimKey], secretSectionPreviousCR);
172952
172917
  }
172953
172918
  if (!previousCR) {
172954
172919
  logger.debug(`No CR found for claim ${claimKey}, it will be rendered from scratch`);
172955
172920
  }
172956
172921
  const claimPath = renderClaims[claimKey].claimPath;
172957
- const { firestartrEntity, extraCharts, catalogEntity } = await renderClaim(catalogScope, firestartrScope, claim, patches, previousCR, claimPath, variableSectionPreviousCR, variableSectionPatches, crs, secretSectionPreviousCR, secretSectionPatches);
172922
+ const { firestartrEntity, extraCharts, catalogEntity } = await renderClaim(catalogScope, firestartrScope, claim, patches, previousCR, claimPath, variableSectionPreviousCR, variableSectionPatches, crs);
172958
172923
  if (catalogEntity) {
172959
172924
  result[`${catalogEntity.kind}-${catalogEntity.metadata.name}`] =
172960
172925
  catalogEntity.toJson();
@@ -172983,7 +172948,7 @@ async function renderClaims(catalogScope, firestartrScope, data) {
172983
172948
  }
172984
172949
  return result;
172985
172950
  }
172986
- async function renderClaim(catalogScope, firestartrScope, claim, patches, previousCR = null, claimPath, variableSectionPreviousCR = false, variableSectionPatches, crs, secretSectionPreviousCR = false, secretSectionPatches) {
172951
+ async function renderClaim(catalogScope, firestartrScope, claim, patches, previousCR = null, claimPath, variableSectionPreviousCR = false, variableSectionPatches, crs) {
172987
172952
  let catalogEntity = undefined;
172988
172953
  let firestartrEntity = undefined;
172989
172954
  const extraCharts = [];
@@ -173153,27 +173118,6 @@ async function renderClaim(catalogScope, firestartrScope, claim, patches, previo
173153
173118
  },
173154
173119
  chart: variableSectionObject,
173155
173120
  });
173156
- const secretSectionFirestartrId = secretSectionPreviousCR
173157
- ? secretSectionPreviousCR.spec?.firestartr?.tfStateKey
173158
- : firestartrId
173159
- ? `${firestartrId}-secrets`
173160
- : null;
173161
- const ssRenderPatches = secretSectionPatches
173162
- ? secretSectionPatches.filter((patch) => !patch.isPostPatch)
173163
- : renderPatches;
173164
- const ssPostPatches = secretSectionPatches
173165
- ? secretSectionPatches.filter((patch) => patch.isPostPatch)
173166
- : postPatches;
173167
- const secretSectionChart = new charts.GithubOrgSecretSectionChart(firestartrScope, `github-secrets-${chartId}`, secretSectionFirestartrId, claim, ssRenderPatches);
173168
- await secretSectionChart.render();
173169
- const secretSectionObject = await secretSectionChart.postRenderer(ssPostPatches);
173170
- extraCharts.push({
173171
- claim: {
173172
- kind: claim.kind,
173173
- name: `${claim.name}-secret-section`,
173174
- },
173175
- chart: secretSectionObject,
173176
- });
173177
173121
  }
173178
173122
  break;
173179
173123
  default:
@@ -173296,33 +173240,8 @@ function searchSecretKey(secretClaim, key) {
173296
173240
  }
173297
173241
  function validateOrgSettingsComponentRefs(ref, renderClaims) {
173298
173242
  const claim = renderClaims[ref].claim;
173299
- validateOrgSecretsSelectedRepositories(claim, renderClaims);
173300
173243
  validateActionsVariablesSelectedRepositories(claim, renderClaims);
173301
173244
  }
173302
- function validateOrgSecretsSelectedRepositories(claim, renderClaims) {
173303
- const orgSecrets = claim?.providers?.github?.org_secrets;
173304
- if (!orgSecrets || typeof orgSecrets !== 'object')
173305
- return;
173306
- for (const section of ['actions', 'codespaces', 'dependabot']) {
173307
- const secrets = orgSecrets[section];
173308
- if (!Array.isArray(secrets))
173309
- continue;
173310
- for (const secret of secrets) {
173311
- if (!secret.selected_repositories)
173312
- continue;
173313
- for (const repoRef of secret.selected_repositories) {
173314
- const match = repoRef.match(COMPONENT_REF_PATTERN);
173315
- if (!match)
173316
- continue;
173317
- const [, componentName] = match;
173318
- const expectedKey = `ComponentClaim-${componentName}`;
173319
- if (!renderClaims[expectedKey]) {
173320
- throw new Error(`CrossReference error: OrgSettingsClaim/${claim.name} references a non-existent component "${componentName}" in org_secrets.${section}.${secret.name}.selected_repositories`);
173321
- }
173322
- }
173323
- }
173324
- }
173325
- }
173326
173245
  function validateActionsVariablesSelectedRepositories(claim, renderClaims) {
173327
173246
  const actionsVariables = claim?.providers?.github?.actions_variables;
173328
173247
  if (!Array.isArray(actionsVariables))
@@ -173453,116 +173372,6 @@ function validateActionsVariablesUniqueness(crs) {
173453
173372
  }
173454
173373
  }
173455
173374
 
173456
- ;// CONCATENATED MODULE: ../cdk8s_renderer/src/validations/githubOrgSecretSection.ts
173457
- const GITHUB_ORG_SECRET_SECTION_KIND = 'FirestartrGithubOrganizationSecretSection';
173458
- const githubOrgSecretSection_FIRESTARTR_CLAIM_REF_ANNOTATION = 'firestartr.dev/claim-ref';
173459
- const githubOrgSecretSection_CLAIM_REF_LABEL = 'claim-ref';
173460
- const SECRETS_CLAIM_REF_PATTERN = /^ref:secretsclaim:([a-zA-Z0-9_-]+):([a-zA-Z0-9_-]+)$/;
173461
- function githubOrgSecretSection_formatResourceRef(name, claimRef) {
173462
- return claimRef ? `${name} (claim: ${claimRef})` : name;
173463
- }
173464
- function validateGithubOrgSecretSectionSingleton(crs) {
173465
- const refsByOrg = new Map();
173466
- const seenClaimRefs = new Map();
173467
- for (const crKey of Object.keys(crs)) {
173468
- const cr = crs[crKey];
173469
- if (cr.kind !== GITHUB_ORG_SECRET_SECTION_KIND)
173470
- continue;
173471
- const org = cr.spec?.org;
173472
- if (typeof org !== 'string' || !org)
173473
- continue;
173474
- const name = cr.metadata?.name || crKey;
173475
- const claimRef = cr.metadata?.annotations?.[githubOrgSecretSection_FIRESTARTR_CLAIM_REF_ANNOTATION] ||
173476
- cr.metadata?.labels?.[githubOrgSecretSection_CLAIM_REF_LABEL];
173477
- const normalizedOrg = org.toLowerCase();
173478
- if (claimRef) {
173479
- const seen = seenClaimRefs.get(normalizedOrg) || new Set();
173480
- if (seen.has(claimRef))
173481
- continue;
173482
- seen.add(claimRef);
173483
- seenClaimRefs.set(normalizedOrg, seen);
173484
- }
173485
- const refs = refsByOrg.get(normalizedOrg) || [];
173486
- refs.push(githubOrgSecretSection_formatResourceRef(name, claimRef));
173487
- refsByOrg.set(normalizedOrg, refs);
173488
- }
173489
- for (const [org, refs] of refsByOrg.entries()) {
173490
- if (refs.length < 2)
173491
- continue;
173492
- throw new Error(`Duplicate ${GITHUB_ORG_SECRET_SECTION_KIND} resources found for GitHub organization "${org}": ${refs.join(', ')}`);
173493
- }
173494
- }
173495
- function validateSecretNamesUniqueness(crs) {
173496
- for (const crKey of Object.keys(crs)) {
173497
- const cr = crs[crKey];
173498
- if (cr.kind !== GITHUB_ORG_SECRET_SECTION_KIND)
173499
- continue;
173500
- const secrets = cr.spec?.secrets;
173501
- if (!secrets || typeof secrets !== 'object')
173502
- continue;
173503
- for (const section of ['actions', 'codespaces', 'dependabot']) {
173504
- const sectionSecrets = secrets[section];
173505
- if (!Array.isArray(sectionSecrets))
173506
- continue;
173507
- const names = new Set();
173508
- for (const secret of sectionSecrets) {
173509
- const secretName = secret?.name;
173510
- if (!secretName)
173511
- continue;
173512
- if (names.has(secretName)) {
173513
- const org = cr.spec?.org || 'unknown';
173514
- throw new Error(`Duplicate secret name "${secretName}" found in ${section} section of ${GITHUB_ORG_SECRET_SECTION_KIND} for organization "${org}"`);
173515
- }
173516
- names.add(secretName);
173517
- }
173518
- }
173519
- }
173520
- }
173521
- function validateOrgSecretsCrossReferences(renderClaims) {
173522
- for (const claimKey of Object.keys(renderClaims)) {
173523
- if (!claimKey.startsWith('OrgSettingsClaim-'))
173524
- continue;
173525
- const claimData = renderClaims[claimKey];
173526
- const claim = claimData?.claim;
173527
- const orgSecrets = claim?.providers?.github?.org_secrets;
173528
- if (!orgSecrets || typeof orgSecrets !== 'object')
173529
- continue;
173530
- for (const section of ['actions', 'codespaces', 'dependabot']) {
173531
- const secrets = orgSecrets[section];
173532
- if (!Array.isArray(secrets))
173533
- continue;
173534
- for (const secret of secrets) {
173535
- if (!secret.value)
173536
- continue;
173537
- const match = secret.value.match(SECRETS_CLAIM_REF_PATTERN);
173538
- if (!match)
173539
- continue;
173540
- const [, secretClaimName, secretKey] = match;
173541
- const expectedKey = `SecretsClaim-${secretClaimName}`;
173542
- if (!renderClaims[expectedKey])
173543
- continue;
173544
- const secretClaim = renderClaims[expectedKey]?.claim;
173545
- const externalSecrets = secretClaim?.providers?.external_secrets?.externalSecrets?.secrets;
173546
- const pushSecrets = secretClaim?.providers?.external_secrets?.pushSecrets;
173547
- let keyFound = false;
173548
- if (Array.isArray(pushSecrets)) {
173549
- keyFound =
173550
- pushSecrets.find((s) => s.secretName === secretKey) !==
173551
- undefined;
173552
- }
173553
- if (!keyFound && Array.isArray(externalSecrets)) {
173554
- keyFound =
173555
- externalSecrets.find((s) => s.secretName === secretKey) !==
173556
- undefined;
173557
- }
173558
- if (!keyFound) {
173559
- throw new Error(`CrossReference error: OrgSettingsClaim/${claim.name} references a non-existent secret key "${secretKey}" in SecretsClaim/${secretClaimName} via org_secrets.${section}.${secret.name}`);
173560
- }
173561
- }
173562
- }
173563
- }
173564
- }
173565
-
173566
173375
  ;// CONCATENATED MODULE: ../cdk8s_renderer/src/renderer/renderer.ts
173567
173376
 
173568
173377
 
@@ -173575,7 +173384,6 @@ function validateOrgSecretsCrossReferences(renderClaims) {
173575
173384
 
173576
173385
 
173577
173386
 
173578
-
173579
173387
  /*
173580
173388
  * Function called when rendering but not importing
173581
173389
  *
@@ -173597,13 +173405,10 @@ async function renderer_render(catalogScope, firestartrScope, claimList) {
173597
173405
  try {
173598
173406
  validateSubReferences(data.renderClaims);
173599
173407
  validateComponentPagesPath(data.renderClaims);
173600
- validateOrgSecretsCrossReferences(data.renderClaims);
173601
173408
  validateTfStateKeyUniqueness(result);
173602
173409
  validateGithubOrgSettingsSingleton(fullCrSet);
173603
173410
  validateGithubOrgVariableSectionSingleton(fullCrSet);
173604
173411
  validateActionsVariablesUniqueness(result);
173605
- validateGithubOrgSecretSectionSingleton(fullCrSet);
173606
- validateSecretNamesUniqueness(result);
173607
173412
  validateCrSizes(result);
173608
173413
  validatePermissionsUniqueness(result);
173609
173414
  validateNoBackstageAnnotationsInK8sCrs(result);
@@ -173916,6 +173721,7 @@ function walkArray(arr, symbolsToResolve, renderClaim) {
173916
173721
 
173917
173722
 
173918
173723
 
173724
+
173919
173725
  /*
173920
173726
  * Function called when rendering from the importer class.
173921
173727
  *
@@ -173958,11 +173764,19 @@ async function renderFromImports(rClaims, crs = {}, catalogOutputDir = '/tmp/.ca
173958
173764
  // after resolving imported refs, preventing setRenderedClaim() from throwing
173959
173765
  // 'already rendered' for claims that were previously seeded
173960
173766
  emptyRenderedClaims();
173961
- // after resolving the imported-refs, we need to validate the claims again, and apply the defaults if needed
173767
+ // After resolving the imported-refs, each claim goes through the same
173768
+ // defaults → stitching → AJV pipeline as loadClaim so feature claim-patches
173769
+ // are applied and validated at the import boundary too. Stitching is
173770
+ // once-only: already stitched claims are left untouched (no feature
173771
+ // re-download, no gates re-applied).
173962
173772
  for (const renderClaim of Object.values(rClaims)) {
173963
- if (defaults) {
173964
- renderClaim.claim = loader_patchClaim(renderClaim.claim, defaults);
173773
+ if (renderClaim.claim && renderClaim.claim[STITCHED_CLAIM]) {
173774
+ validateClaim(renderClaim.claim, `firestartr.dev://common/${renderClaim.claim.kind}`);
173775
+ continue;
173965
173776
  }
173777
+ const rawClaim = renderClaim.claim;
173778
+ const claim = defaults ? loader_patchClaim(rawClaim, defaults) : rawClaim;
173779
+ renderClaim.claim = await stitchClaim(claim, undefined, rawClaim);
173966
173780
  validateClaim(renderClaim.claim, `firestartr.dev://common/${renderClaim.claim.kind}`);
173967
173781
  }
173968
173782
  const catalogScope = new lib.App({
@@ -357883,7 +357697,6 @@ const kindPluralMap = {
357883
357697
  githuborgwebhooks: 'FirestartrGithubOrgWebhook',
357884
357698
  githuborganizationsettings: 'FirestartrGithubOrganizationSettings',
357885
357699
  githuborganizationvariablesections: 'FirestartrGithubOrganizationVariableSection',
357886
- githuborganizationsecretsections: 'FirestartrGithubOrganizationSecretSection',
357887
357700
  terraformworkspaces: 'FirestartrTerraformWorkspace',
357888
357701
  terraformworkspaceplans: 'FirestartrTerraformWorkspacePlan',
357889
357702
  providerconfigs: 'FirestartrProviderConfig',
@@ -360284,7 +360097,6 @@ const kindsWithFinalizer = [
360284
360097
  'FirestartrGithubOrgWebhook',
360285
360098
  'FirestartrGithubOrganizationSettings',
360286
360099
  'FirestartrGithubOrganizationVariableSection',
360287
- 'FirestartrGithubOrganizationSecretSection',
360288
360100
  'FirestartrGithubRepositorySecretsSection',
360289
360101
  ];
360290
360102
  const kindsWithDependants = [
@@ -363323,7 +363135,7 @@ async function configGit() {
363323
363135
  }
363324
363136
  // Import github dynamically to avoid Jest ESM issues when not specifically running this function
363325
363137
  // (see CONSTITUTION and RULES: must not change test machinery)
363326
- const githubModule = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 3342));
363138
+ const githubModule = await Promise.resolve(/* import() */).then(__nccwpck_require__.bind(__nccwpck_require__, 99029));
363327
363139
  const github = githubModule.default || githubModule;
363328
363140
  if (external_fs_.existsSync(gitconfigPath)) {
363329
363141
  external_fs_.rmSync(gitconfigPath);
@@ -365028,7 +364840,7 @@ function helperCreateCheckRunName(cmd, item) {
365028
364840
 
365029
364841
  ;// CONCATENATED MODULE: ../operator/src/utils/index.ts
365030
364842
  const secretRegex = /\$\{\{ secrets\.(.*?) \}\}/g;
365031
- function isRecord(value) {
364843
+ function utils_isRecord(value) {
365032
364844
  return typeof value === 'object' && value !== null;
365033
364845
  }
365034
364846
  function getFirstNonEmptyString(...values) {
@@ -365066,7 +364878,7 @@ function replaceInlineSecrets(inline, secrets) {
365066
364878
  return result;
365067
364879
  }
365068
364880
  function extractErrorDetails(error) {
365069
- const exitCode = isRecord(error) && typeof error.exitCode === 'number'
364881
+ const exitCode = utils_isRecord(error) && typeof error.exitCode === 'number'
365070
364882
  ? error.exitCode
365071
364883
  : undefined;
365072
364884
  if (typeof error === 'string') {
@@ -365077,7 +364889,7 @@ function extractErrorDetails(error) {
365077
364889
  const output = getFirstNonEmptyString(errorWithOutput.output, error.message);
365078
364890
  return { output: output ?? String(error), exitCode };
365079
364891
  }
365080
- if (isRecord(error)) {
364892
+ if (utils_isRecord(error)) {
365081
364893
  const output = getFirstNonEmptyString(error.output, error.message, error.error);
365082
364894
  if (output !== undefined) {
365083
364895
  return { output, exitCode };
@@ -367169,11 +366981,6 @@ const MODULES = {
367169
366981
  // github-org-variables-section-v0.1.0
367170
366982
  ref: 'fb9c01d0a1e03e5134479da13d0faf55891dfedf',
367171
366983
  },
367172
- FirestartrGithubOrganizationSecretSection: {
367173
- module: 'git::https://github.com/prefapp/tfm.git//modules/github-org-secrets-section',
367174
- // feat/1364-feat-add-github-org-secrets-section-module
367175
- ref: '170e6cf',
367176
- },
367177
366984
  };
367178
366985
  function getFirestartrDefaultTFM(kind) {
367179
366986
  if (kind in MODULES) {
@@ -369086,215 +368893,6 @@ class EntityGHOrgVarsSection extends base_Entity {
369086
368893
  async loadAddressesToImport() { }
369087
368894
  }
369088
368895
 
369089
- ;// CONCATENATED MODULE: ../gh_provisioner/src/entities/ghorgsecretsection/secrets.ts
369090
-
369091
-
369092
-
369093
-
369094
- const secrets_SECTIONS = ['actions', 'codespaces', 'dependabot'];
369095
-
369096
- async function provisionOrgSecrets(entity, secrets) {
369097
- gh_provisioner_src_logger.info(`[gh-provisioner] ${entity.k8sId} provisioning org secrets`);
369098
- for (const section of secrets_SECTIONS) {
369099
- const sectionSecrets = secrets[section] || [];
369100
- if (sectionSecrets.length === 0)
369101
- continue;
369102
- let preFetchedKey;
369103
- try {
369104
- preFetchedKey = await fetchOrgPublicKey(entity, section);
369105
- }
369106
- catch (err) {
369107
- const message = err instanceof Error ? err.message : String(err);
369108
- throw new Error(`[gh-provisioner] ${entity.k8sId} failed to fetch ${section} org public key: ${message}`);
369109
- }
369110
- for (const secret of sectionSecrets) {
369111
- await provisionOrgSecret(entity, section, secret, preFetchedKey);
369112
- }
369113
- }
369114
- }
369115
- async function fetchOrgPublicKey(entity, section) {
369116
- return (await entity.runWithGithubProvider(async () => {
369117
- return await github["default"].encryption.getOrgPublicKey(entity.cr.spec.org, section);
369118
- }));
369119
- }
369120
- async function provisionOrgSecret(entity, section, secret, preFetchedKey) {
369121
- gh_provisioner_src_logger.info(`[gh-provisioner] provisioning org secret ${entity.k8sId}/${section}/${secret.name}`);
369122
- if (process.env['AVOID_PROVIDER_SECRET_ENCRYPTION']) {
369123
- await secrets_createUnencryptedSecret(entity, section, secret);
369124
- }
369125
- else {
369126
- await secrets_createEncryptedSecret(entity, section, secret, preFetchedKey);
369127
- }
369128
- gh_provisioner_src_logger.info(`[gh-provisioner] org secret provisioned ${section}/${secret.name}`);
369129
- }
369130
- async function secrets_createEncryptedSecret(entity, section, secret, preFetchedKey) {
369131
- const plainSecret = base_Entity.refResolver(secret.ref);
369132
- if (!plainSecret) {
369133
- throw new Error(`[gh-provisioner] ${entity.k8sId} cannot resolve secret ref: ${secret.ref.kind}/${secret.ref.name}:${secret.ref.key} — ensure the referenced resource is available as a dependency`);
369134
- }
369135
- const plainTextSecret = plainSecret.getOutput(secret.ref.key);
369136
- const plaintextSha256 = external_crypto_default().createHash('sha256')
369137
- .update(plainTextSecret)
369138
- .digest('hex');
369139
- const { encrypted_value } = (await entity.runWithGithubProvider(async () => {
369140
- return await github["default"].encryption.encryptOrgSecret(entity.cr.spec.org, section, plainTextSecret, preFetchedKey);
369141
- }));
369142
- entity.patchData({
369143
- op: PatchOperations.add,
369144
- path: `/config/${section}/${secret.name}`,
369145
- value: {
369146
- value: encrypted_value,
369147
- visibility: secret.visibility || 'all',
369148
- ...(secret.selectedRepositories && secret.selectedRepositories.length > 0
369149
- ? { selected_repositories: secret.selectedRepositories }
369150
- : {}),
369151
- },
369152
- });
369153
- entity.patchData({
369154
- op: PatchOperations.add,
369155
- path: `/config/${section}_sha256/${secret.name}`,
369156
- value: plaintextSha256,
369157
- });
369158
- }
369159
- async function secrets_createUnencryptedSecret(entity, section, secret) {
369160
- const plainSecret = base_Entity.refResolver(secret.ref);
369161
- const plainTextSecret = plainSecret.getOutput(secret.ref.key);
369162
- const plaintextSha256 = external_crypto_default().createHash('sha256')
369163
- .update(plainTextSecret)
369164
- .digest('hex');
369165
- entity.patchData({
369166
- op: PatchOperations.add,
369167
- path: `/config/${section}/${secret.name}`,
369168
- value: {
369169
- value: plainTextSecret,
369170
- visibility: secret.visibility || 'all',
369171
- ...(secret.selectedRepositories && secret.selectedRepositories.length > 0
369172
- ? { selected_repositories: secret.selectedRepositories }
369173
- : {}),
369174
- },
369175
- });
369176
- entity.patchData({
369177
- op: PatchOperations.add,
369178
- path: `/config/${section}_sha256/${secret.name}`,
369179
- value: plaintextSha256,
369180
- });
369181
- }
369182
- async function adoptSecretsIfNeeded(entity, secrets) {
369183
- const managedSecrets = entity.cr.fResolveSelfOutputs('managed_secrets') || [];
369184
- for (const section of secrets_SECTIONS) {
369185
- const sectionSecrets = secrets[section] || [];
369186
- if (sectionSecrets.length === 0)
369187
- continue;
369188
- const declaredNames = sectionSecrets.map((s) => s.name);
369189
- const newToModule = declaredNames.filter((name) => !managedSecrets.includes(name));
369190
- if (newToModule.length === 0) {
369191
- gh_provisioner_src_logger.debug(`[gh-provisioner] ${entity.k8sId} all declared ${section} secrets are already managed`);
369192
- continue;
369193
- }
369194
- if (managedSecrets.length === 0) {
369195
- gh_provisioner_src_logger.info(`[gh-provisioner] ${entity.k8sId} no managed_secrets output — first reconciliation, treating all ${newToModule.length} ${section} secret(s) as new to module`);
369196
- }
369197
- for (const secretName of newToModule) {
369198
- try {
369199
- const existing = (await entity.runWithGithubProvider(async () => {
369200
- return await github["default"].encryption.getOrgSecret(entity.cr.spec.org, section, secretName);
369201
- }));
369202
- if (existing) {
369203
- gh_provisioner_src_logger.info(`[gh-provisioner] ${entity.k8sId} adopting pre-existing ${section} secret '${secretName}' on GitHub org '${entity.cr.spec.org}'`);
369204
- const resourceType = `github_${section}_organization_secret`;
369205
- entity.patchImportData({
369206
- op: PatchOperations.add,
369207
- path: '/imports/-',
369208
- value: {
369209
- to: `${resourceType}.this["${secretName}"]`,
369210
- id: secretName,
369211
- },
369212
- });
369213
- const secretEntry = sectionSecrets.find((s) => s.name === secretName);
369214
- if (secretEntry &&
369215
- secretEntry.visibility === 'selected' &&
369216
- (section === 'actions' || section === 'dependabot')) {
369217
- const bindingType = `github_${section}_organization_secret_repositories`;
369218
- entity.patchImportData({
369219
- op: PatchOperations.add,
369220
- path: '/imports/-',
369221
- value: {
369222
- to: `${bindingType}.this["${secretName}"]`,
369223
- id: secretName,
369224
- },
369225
- });
369226
- }
369227
- }
369228
- }
369229
- catch (err) {
369230
- if (err && err.status === 404) {
369231
- gh_provisioner_src_logger.info(`[gh-provisioner] ${entity.k8sId} ${section} secret '${secretName}' not found on GitHub org '${entity.cr.spec.org}' — will be created by TFM`);
369232
- }
369233
- else if (err && (err.status === 401 || err.status === 403)) {
369234
- gh_provisioner_src_logger.warn(`[gh-provisioner] ${entity.k8sId} token lacks scope to check ${section} secret '${secretName}' on org '${entity.cr.spec.org}' — skipping adoption gracefully`);
369235
- }
369236
- else {
369237
- gh_provisioner_src_logger.warn(`[gh-provisioner] ${entity.k8sId} unexpected error checking ${section} secret '${secretName}' on org '${entity.cr.spec.org}': ${err instanceof Error ? err.message : String(err)}`);
369238
- }
369239
- }
369240
- }
369241
- }
369242
- }
369243
-
369244
- ;// CONCATENATED MODULE: ../gh_provisioner/src/entities/ghorgsecretsection/index.ts
369245
-
369246
-
369247
-
369248
- class EntityGHOrgSecretSection extends base_Entity {
369249
- constructor(artifact) {
369250
- super(artifact, {
369251
- config: {
369252
- org: '',
369253
- actions: {},
369254
- codespaces: {},
369255
- dependabot: {},
369256
- actions_sha256: {},
369257
- codespaces_sha256: {},
369258
- dependabot_sha256: {},
369259
- },
369260
- });
369261
- }
369262
- async loadResources(tfOp) {
369263
- gh_provisioner_src_logger.info(`[gh-provisioner] running ${tfOp} on ${this.k8sId}`);
369264
- try {
369265
- const cr = this.cr;
369266
- const org = cr.spec.org;
369267
- const secrets = cr.spec.secrets || {};
369268
- this.patchData({
369269
- op: PatchOperations.replace,
369270
- path: '/config/org',
369271
- value: org,
369272
- });
369273
- await provisionOrgSecrets(this, secrets);
369274
- const redactedDoc = JSON.parse(JSON.stringify(this._document, (key, value) => {
369275
- if (key === 'value' && typeof value === 'string')
369276
- return '[REDACTED]';
369277
- return typeof value === 'string' && value.length > 50
369278
- ? '[REDACTED]'
369279
- : value;
369280
- }));
369281
- this.synthMessage(`[gh-provisioner] ${this.k8sId} config:\n${JSON.stringify(redactedDoc, null, 2)}`);
369282
- this.synthEnd(`[gh-provisioner] ${this.k8sId} loaded its data`);
369283
- if (tfOp === 'apply') {
369284
- await adoptSecretsIfNeeded(this, secrets);
369285
- }
369286
- gh_provisioner_src_logger.debug(`[gh-provisioner] ${this.k8sId} loaded its data`);
369287
- }
369288
- catch (err) {
369289
- const message = err instanceof Error ? err.message : String(err);
369290
- gh_provisioner_src_logger.error(`[gh-provisioner] ${this.k8sId} error loading resources: ${message}`);
369291
- throw new Error(`[gh-provisioner] ${this.k8sId} error loading resources: ${message}`);
369292
- }
369293
- }
369294
- async postProvision(_tfOp) { }
369295
- async loadAddressesToImport() { }
369296
- }
369297
-
369298
368896
  ;// CONCATENATED MODULE: ../gh_provisioner/src/entities/ghorgwebhook/index.ts
369299
368897
 
369300
368898
 
@@ -369372,7 +368970,6 @@ class EntityGHOrgWebHook extends base_Entity {
369372
368970
 
369373
368971
 
369374
368972
 
369375
-
369376
368973
  function entities_getEntity(cr) {
369377
368974
  const entityClass = getEntityClass(cr.kind);
369378
368975
  return new entityClass(cr);
@@ -369395,8 +368992,6 @@ function getEntityClass(kind) {
369395
368992
  return EntityGHOrgSettings;
369396
368993
  case 'FirestartrGithubOrganizationVariableSection':
369397
368994
  return EntityGHOrgVarsSection;
369398
- case 'FirestartrGithubOrganizationSecretSection':
369399
- return EntityGHOrgSecretSection;
369400
368995
  default:
369401
368996
  throw new Error(`kind ${kind} has no entity associated`);
369402
368997
  }
@@ -371224,7 +370819,6 @@ const provisionImplementations = {
371224
370819
  githuborgwebhooks: process_operation_processOperation,
371225
370820
  githuborganizationsettings: process_operation_processOperation,
371226
370821
  githuborganizationvariablesections: process_operation_processOperation,
371227
- githuborganizationsecretsections: process_operation_processOperation,
371228
370822
  fsdummiesa: processFirestartrDummies,
371229
370823
  fsdummiesb: processFirestartrDummies,
371230
370824
  fsdummiesc: processFirestartrDummies,
@@ -715677,7 +715271,7 @@ const crsStatusSubcommand = {
715677
715271
  };
715678
715272
 
715679
715273
  ;// CONCATENATED MODULE: ./package.json
715680
- const package_namespaceObject = JSON.parse('{"i8":"2.11.0-snapshot-org-secrets-00"}');
715274
+ const package_namespaceObject = JSON.parse('{"i8":"2.11.0-snapshot-patch-claims-4"}');
715681
715275
  ;// CONCATENATED MODULE: ../../package.json
715682
715276
  const package_namespaceObject_1 = {"i8":"2.10.0"};
715683
715277
  // EXTERNAL MODULE: ../../node_modules/semver/index.js