@transcend-io/cli 10.25.4 → 10.26.0

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 (222) hide show
  1. package/README.md +264 -1
  2. package/dist/{app-CLOsNNoj.mjs → app-CZX6ZV6X.mjs} +38 -21
  3. package/dist/app-CZX6ZV6X.mjs.map +1 -0
  4. package/dist/{approvePrivacyRequests-BfULMmiN.mjs → approvePrivacyRequests-D1S2AYud.mjs} +2 -2
  5. package/dist/{approvePrivacyRequests-BfULMmiN.mjs.map → approvePrivacyRequests-D1S2AYud.mjs.map} +1 -1
  6. package/dist/bin/bash-complete.mjs +1 -1
  7. package/dist/bin/cli.mjs +1 -1
  8. package/dist/bin/deprecated-command.mjs +1 -1
  9. package/dist/{buildExamples-CHogOpC8.mjs → buildExamples-CnfZJ8MD.mjs} +2 -2
  10. package/dist/{buildExamples-CHogOpC8.mjs.map → buildExamples-CnfZJ8MD.mjs.map} +1 -1
  11. package/dist/{buildXdiSyncEndpoint-BR7zCF05.mjs → buildXdiSyncEndpoint-B4l998cU.mjs} +2 -2
  12. package/dist/{buildXdiSyncEndpoint-BR7zCF05.mjs.map → buildXdiSyncEndpoint-B4l998cU.mjs.map} +1 -1
  13. package/dist/{bulkRestartRequests-D3NnqSRA.mjs → bulkRestartRequests-NAASQwvP.mjs} +2 -2
  14. package/dist/{bulkRestartRequests-D3NnqSRA.mjs.map → bulkRestartRequests-NAASQwvP.mjs.map} +1 -1
  15. package/dist/{bulkRetryEnrichers-Blydm41j.mjs → bulkRetryEnrichers-BEEVKtCH.mjs} +2 -2
  16. package/dist/{bulkRetryEnrichers-Blydm41j.mjs.map → bulkRetryEnrichers-BEEVKtCH.mjs.map} +1 -1
  17. package/dist/{cancelPrivacyRequests-Da7_hfc7.mjs → cancelPrivacyRequests-DM3Zamqd.mjs} +2 -2
  18. package/dist/{cancelPrivacyRequests-Da7_hfc7.mjs.map → cancelPrivacyRequests-DM3Zamqd.mjs.map} +1 -1
  19. package/dist/codecs-DJFlZLGT.mjs +2 -0
  20. package/dist/codecs-DJFlZLGT.mjs.map +1 -0
  21. package/dist/{collectCsvFilesOrExit-C8-Pr9Hr.mjs → collectCsvFilesOrExit-BPo8Mjy7.mjs} +1 -1
  22. package/dist/{collectCsvFilesOrExit-C8-Pr9Hr.mjs.map → collectCsvFilesOrExit-BPo8Mjy7.mjs.map} +1 -1
  23. package/dist/{collectParquetFilesOrExit-DyZISY9X.mjs → collectParquetFilesOrExit-DVS9_OSv.mjs} +1 -1
  24. package/dist/{collectParquetFilesOrExit-DyZISY9X.mjs.map → collectParquetFilesOrExit-DVS9_OSv.mjs.map} +1 -1
  25. package/dist/{command-Dpvt1BIt.mjs → command-30CgpFvx.mjs} +2 -2
  26. package/dist/{command-Dpvt1BIt.mjs.map → command-30CgpFvx.mjs.map} +1 -1
  27. package/dist/commands/admin/parquet-to-csv/worker.mjs +1 -1
  28. package/dist/{consentManagersToBusinessEntities-DGzryQ3W.mjs → consentManagersToBusinessEntities-rf8_xu71.mjs} +1 -1
  29. package/dist/{consentManagersToBusinessEntities-DGzryQ3W.mjs.map → consentManagersToBusinessEntities-rf8_xu71.mjs.map} +1 -1
  30. package/dist/{constants-DNF09zFX.mjs → constants-BgCEW975.mjs} +2 -2
  31. package/dist/{constants-DNF09zFX.mjs.map → constants-BgCEW975.mjs.map} +1 -1
  32. package/dist/{constants-BjwEFOS4.mjs → constants-CAOyAsNX.mjs} +2 -2
  33. package/dist/{constants-BjwEFOS4.mjs.map → constants-CAOyAsNX.mjs.map} +1 -1
  34. package/dist/{createExtraKeyHandler-Cg1VRPqF.mjs → createExtraKeyHandler-DbWzaD4c.mjs} +2 -2
  35. package/dist/{createExtraKeyHandler-Cg1VRPqF.mjs.map → createExtraKeyHandler-DbWzaD4c.mjs.map} +1 -1
  36. package/dist/{dataFlowsToDataSilos-DRGrUosf.mjs → dataFlowsToDataSilos-DRuAfwIn.mjs} +1 -1
  37. package/dist/{dataFlowsToDataSilos-DRGrUosf.mjs.map → dataFlowsToDataSilos-DRuAfwIn.mjs.map} +1 -1
  38. package/dist/{done-input-validation-uqIgnJcw.mjs → done-input-validation-DL31vk7g.mjs} +1 -1
  39. package/dist/{done-input-validation-uqIgnJcw.mjs.map → done-input-validation-DL31vk7g.mjs.map} +1 -1
  40. package/dist/{downloadPrivacyRequestFiles-CAGrriEp.mjs → downloadPrivacyRequestFiles-DSOTFVU6.mjs} +2 -2
  41. package/dist/{downloadPrivacyRequestFiles-CAGrriEp.mjs.map → downloadPrivacyRequestFiles-DSOTFVU6.mjs.map} +1 -1
  42. package/dist/{generateCrossAccountApiKeys-Cu35vcXs.mjs → generateCrossAccountApiKeys-C3mCgp6X.mjs} +2 -2
  43. package/dist/{generateCrossAccountApiKeys-Cu35vcXs.mjs.map → generateCrossAccountApiKeys-C3mCgp6X.mjs.map} +1 -1
  44. package/dist/{impl-DBFiULuD2.mjs → impl-1ueiw_XV2.mjs} +2 -2
  45. package/dist/{impl-DBFiULuD2.mjs.map → impl-1ueiw_XV2.mjs.map} +1 -1
  46. package/dist/{impl-Ce4Ua3nx.mjs → impl-7pxeoDZg.mjs} +2 -2
  47. package/dist/{impl-Ce4Ua3nx.mjs.map → impl-7pxeoDZg.mjs.map} +1 -1
  48. package/dist/impl-8zmHCdih.mjs +2 -0
  49. package/dist/{impl-C6jaX52V.mjs.map → impl-8zmHCdih.mjs.map} +1 -1
  50. package/dist/{impl-UEjhKO47.mjs → impl-B0fzc-Pd.mjs} +2 -2
  51. package/dist/{impl-UEjhKO47.mjs.map → impl-B0fzc-Pd.mjs.map} +1 -1
  52. package/dist/{impl-DdjTOXMv.mjs → impl-B2eZGemA.mjs} +2 -2
  53. package/dist/{impl-DdjTOXMv.mjs.map → impl-B2eZGemA.mjs.map} +1 -1
  54. package/dist/{impl-CmvkC9BB2.mjs → impl-B2yCuG6f2.mjs} +2 -2
  55. package/dist/{impl-CmvkC9BB2.mjs.map → impl-B2yCuG6f2.mjs.map} +1 -1
  56. package/dist/{impl-CvmW0u62.mjs → impl-B6_4iGM2.mjs} +2 -2
  57. package/dist/{impl-CvmW0u62.mjs.map → impl-B6_4iGM2.mjs.map} +1 -1
  58. package/dist/{impl-BGVWpusE.mjs → impl-B_1LPpGy.mjs} +2 -2
  59. package/dist/{impl-BGVWpusE.mjs.map → impl-B_1LPpGy.mjs.map} +1 -1
  60. package/dist/{impl-D8h6Rxgo2.mjs → impl-Bbtnhcy02.mjs} +2 -2
  61. package/dist/{impl-D8h6Rxgo2.mjs.map → impl-Bbtnhcy02.mjs.map} +1 -1
  62. package/dist/{impl-C5kS4BNc.mjs → impl-BdG67mkj.mjs} +2 -2
  63. package/dist/{impl-C5kS4BNc.mjs.map → impl-BdG67mkj.mjs.map} +1 -1
  64. package/dist/{impl-BpPDz_Yz.mjs → impl-BdTWl0Xm.mjs} +2 -2
  65. package/dist/{impl-BpPDz_Yz.mjs.map → impl-BdTWl0Xm.mjs.map} +1 -1
  66. package/dist/{impl-C7Xp0Txd.mjs → impl-BmQR1Pae.mjs} +2 -2
  67. package/dist/{impl-C7Xp0Txd.mjs.map → impl-BmQR1Pae.mjs.map} +1 -1
  68. package/dist/{impl-BX76WSDL.mjs → impl-BnzPrDmM.mjs} +2 -2
  69. package/dist/{impl-BX76WSDL.mjs.map → impl-BnzPrDmM.mjs.map} +1 -1
  70. package/dist/{impl-Dp8o3Xpr.mjs → impl-BohgbWOH.mjs} +2 -2
  71. package/dist/{impl-Dp8o3Xpr.mjs.map → impl-BohgbWOH.mjs.map} +1 -1
  72. package/dist/{impl-w2J6bGfU.mjs → impl-BsPgb_kT.mjs} +2 -2
  73. package/dist/{impl-w2J6bGfU.mjs.map → impl-BsPgb_kT.mjs.map} +1 -1
  74. package/dist/{impl-BvLjryD7.mjs → impl-Bur_bNXN.mjs} +2 -2
  75. package/dist/{impl-BvLjryD7.mjs.map → impl-Bur_bNXN.mjs.map} +1 -1
  76. package/dist/{impl-NUMkBg7d.mjs → impl-BwuWn3TM.mjs} +2 -2
  77. package/dist/{impl-NUMkBg7d.mjs.map → impl-BwuWn3TM.mjs.map} +1 -1
  78. package/dist/{impl-B0AKcSoy.mjs → impl-BxQE7dL92.mjs} +2 -2
  79. package/dist/impl-BxQE7dL92.mjs.map +1 -0
  80. package/dist/impl-C2DDZ1EB2.mjs +2 -0
  81. package/dist/{impl-fkYix-LF2.mjs.map → impl-C2DDZ1EB2.mjs.map} +1 -1
  82. package/dist/{impl-BF9Ekyjn.mjs → impl-C3f_H_77.mjs} +2 -2
  83. package/dist/{impl-BF9Ekyjn.mjs.map → impl-C3f_H_77.mjs.map} +1 -1
  84. package/dist/{impl-BlI9fIP5.mjs → impl-C9KCLG7s2.mjs} +2 -2
  85. package/dist/impl-C9KCLG7s2.mjs.map +1 -0
  86. package/dist/{impl-D22mHixx.mjs → impl-CWVX0Xnv.mjs} +2 -2
  87. package/dist/{impl-D22mHixx.mjs.map → impl-CWVX0Xnv.mjs.map} +1 -1
  88. package/dist/impl-CWqtBcmr.mjs +2 -0
  89. package/dist/{impl-CR_UvQXr.mjs.map → impl-CWqtBcmr.mjs.map} +1 -1
  90. package/dist/{impl-BCEw1fsj.mjs → impl-CZG9gzzR.mjs} +2 -2
  91. package/dist/{impl-BCEw1fsj.mjs.map → impl-CZG9gzzR.mjs.map} +1 -1
  92. package/dist/{impl-CiaTPxwK.mjs → impl-Ca064LmU.mjs} +2 -2
  93. package/dist/{impl-CiaTPxwK.mjs.map → impl-Ca064LmU.mjs.map} +1 -1
  94. package/dist/{impl-Bgf0a6fL2.mjs → impl-CdOwXtLY2.mjs} +2 -2
  95. package/dist/{impl-Bgf0a6fL2.mjs.map → impl-CdOwXtLY2.mjs.map} +1 -1
  96. package/dist/{impl-B_4_7a-i.mjs → impl-Chska4J8.mjs} +2 -2
  97. package/dist/{impl-B_4_7a-i.mjs.map → impl-Chska4J8.mjs.map} +1 -1
  98. package/dist/{impl-Bgg6AZQS.mjs → impl-CkoQHhc8.mjs} +2 -2
  99. package/dist/{impl-Bgg6AZQS.mjs.map → impl-CkoQHhc8.mjs.map} +1 -1
  100. package/dist/impl-Cl3hf0Pd.mjs +2 -0
  101. package/dist/impl-Cl3hf0Pd.mjs.map +1 -0
  102. package/dist/{impl-D6rMK5Us.mjs → impl-CnrK11Gr2.mjs} +2 -2
  103. package/dist/impl-CnrK11Gr2.mjs.map +1 -0
  104. package/dist/{impl-Zjvt9J28.mjs → impl-D0-ioxpZ.mjs} +2 -2
  105. package/dist/{impl-Zjvt9J28.mjs.map → impl-D0-ioxpZ.mjs.map} +1 -1
  106. package/dist/impl-D5fmpaDf2.mjs +2 -0
  107. package/dist/{impl-DdomTpuS2.mjs.map → impl-D5fmpaDf2.mjs.map} +1 -1
  108. package/dist/impl-DBK5c6d0.mjs +2 -0
  109. package/dist/impl-DBK5c6d0.mjs.map +1 -0
  110. package/dist/{impl-7obvc16D2.mjs → impl-DJHPOIQn2.mjs} +2 -2
  111. package/dist/{impl-7obvc16D2.mjs.map → impl-DJHPOIQn2.mjs.map} +1 -1
  112. package/dist/{impl-DGQW5mVR.mjs → impl-DLWhxaMi.mjs} +2 -2
  113. package/dist/{impl-DGQW5mVR.mjs.map → impl-DLWhxaMi.mjs.map} +1 -1
  114. package/dist/{impl-Cjb617E32.mjs → impl-DLypyDZV2.mjs} +2 -2
  115. package/dist/{impl-Cjb617E32.mjs.map → impl-DLypyDZV2.mjs.map} +1 -1
  116. package/dist/{impl-BBSKkDDW.mjs → impl-DNtaoKI9.mjs} +2 -2
  117. package/dist/{impl-BBSKkDDW.mjs.map → impl-DNtaoKI9.mjs.map} +1 -1
  118. package/dist/{impl-Bxhh44Tv.mjs → impl-DOQk-mfA.mjs} +2 -2
  119. package/dist/{impl-Bxhh44Tv.mjs.map → impl-DOQk-mfA.mjs.map} +1 -1
  120. package/dist/{impl-9RgMs7Ud.mjs → impl-DPC_ktM2.mjs} +2 -2
  121. package/dist/{impl-9RgMs7Ud.mjs.map → impl-DPC_ktM2.mjs.map} +1 -1
  122. package/dist/{impl-BgspL0zl2.mjs → impl-DPmitBXR2.mjs} +2 -2
  123. package/dist/{impl-BgspL0zl2.mjs.map → impl-DPmitBXR2.mjs.map} +1 -1
  124. package/dist/{impl-D8iCRZpR2.mjs → impl-DRjvMMeU2.mjs} +2 -2
  125. package/dist/{impl-D8iCRZpR2.mjs.map → impl-DRjvMMeU2.mjs.map} +1 -1
  126. package/dist/{impl-BUou3FAX2.mjs → impl-DSCuy4GU2.mjs} +2 -2
  127. package/dist/{impl-BUou3FAX2.mjs.map → impl-DSCuy4GU2.mjs.map} +1 -1
  128. package/dist/{impl-Bl714Q2W2.mjs → impl-D__B55Iu2.mjs} +2 -2
  129. package/dist/{impl-Bl714Q2W2.mjs.map → impl-D__B55Iu2.mjs.map} +1 -1
  130. package/dist/{impl-DAvX3-2i2.mjs → impl-Da1sv_hX2.mjs} +2 -2
  131. package/dist/{impl-DAvX3-2i2.mjs.map → impl-Da1sv_hX2.mjs.map} +1 -1
  132. package/dist/{impl-fiK_rZ7c.mjs → impl-DmODS2cY.mjs} +2 -2
  133. package/dist/{impl-fiK_rZ7c.mjs.map → impl-DmODS2cY.mjs.map} +1 -1
  134. package/dist/{impl-D4_KLWT_2.mjs → impl-DmbT1vXM2.mjs} +2 -2
  135. package/dist/{impl-D4_KLWT_2.mjs.map → impl-DmbT1vXM2.mjs.map} +1 -1
  136. package/dist/{impl-D-JYZ74k.mjs → impl-DvSnW_IA.mjs} +2 -2
  137. package/dist/{impl-D-JYZ74k.mjs.map → impl-DvSnW_IA.mjs.map} +1 -1
  138. package/dist/{impl-x1AgpyRL.mjs → impl-GeXGMn5G.mjs} +2 -2
  139. package/dist/{impl-x1AgpyRL.mjs.map → impl-GeXGMn5G.mjs.map} +1 -1
  140. package/dist/{impl-DI0UIHyf2.mjs → impl-YeYfan582.mjs} +2 -2
  141. package/dist/{impl-DI0UIHyf2.mjs.map → impl-YeYfan582.mjs.map} +1 -1
  142. package/dist/{impl-DC9vrPYR.mjs → impl-_BPSoSwJ.mjs} +2 -2
  143. package/dist/{impl-DC9vrPYR.mjs.map → impl-_BPSoSwJ.mjs.map} +1 -1
  144. package/dist/{impl-BqvuxZBQ2.mjs → impl-_nJfGV8K2.mjs} +2 -2
  145. package/dist/{impl-BqvuxZBQ2.mjs.map → impl-_nJfGV8K2.mjs.map} +1 -1
  146. package/dist/{impl-D3qD4wsS.mjs → impl-xIb20rTt.mjs} +2 -2
  147. package/dist/{impl-D3qD4wsS.mjs.map → impl-xIb20rTt.mjs.map} +1 -1
  148. package/dist/{impl-Dj92X5ey.mjs → impl-y01BtY2r.mjs} +2 -2
  149. package/dist/{impl-Dj92X5ey.mjs.map → impl-y01BtY2r.mjs.map} +1 -1
  150. package/dist/{impl-1ia0Gtfj.mjs → impl-yVmEK84l.mjs} +2 -2
  151. package/dist/{impl-1ia0Gtfj.mjs.map → impl-yVmEK84l.mjs.map} +1 -1
  152. package/dist/{impl-CDm8c6Cr2.mjs → impl-z5TV6Spz2.mjs} +2 -2
  153. package/dist/{impl-CDm8c6Cr2.mjs.map → impl-z5TV6Spz2.mjs.map} +1 -1
  154. package/dist/index.d.mts +129 -3
  155. package/dist/index.d.mts.map +1 -1
  156. package/dist/index.mjs +3 -3
  157. package/dist/index.mjs.map +1 -1
  158. package/dist/{listFiles-BPx3iDV6.mjs → listFiles-C5kubvdN.mjs} +1 -1
  159. package/dist/{listFiles-BPx3iDV6.mjs.map → listFiles-C5kubvdN.mjs.map} +1 -1
  160. package/dist/{markRequestDataSiloIdsCompleted-Bw_krZSS.mjs → markRequestDataSiloIdsCompleted-CDV0Ppv2.mjs} +2 -2
  161. package/dist/{markRequestDataSiloIdsCompleted-Bw_krZSS.mjs.map → markRequestDataSiloIdsCompleted-CDV0Ppv2.mjs.map} +1 -1
  162. package/dist/{markSilentPrivacyRequests-CitXF4qq.mjs → markSilentPrivacyRequests-DXLiS2jH.mjs} +2 -2
  163. package/dist/{markSilentPrivacyRequests-CitXF4qq.mjs.map → markSilentPrivacyRequests-DXLiS2jH.mjs.map} +1 -1
  164. package/dist/mergeTranscendInputs-DjPe49yR.mjs +3 -0
  165. package/dist/mergeTranscendInputs-DjPe49yR.mjs.map +1 -0
  166. package/dist/{notifyPrivacyRequestsAdditionalTime-mpYqqBxR.mjs → notifyPrivacyRequestsAdditionalTime-DPp0MyfT.mjs} +2 -2
  167. package/dist/{notifyPrivacyRequestsAdditionalTime-mpYqqBxR.mjs.map → notifyPrivacyRequestsAdditionalTime-DPp0MyfT.mjs.map} +1 -1
  168. package/dist/{parquetToCsvOneFile-13GirFzy.mjs → parquetToCsvOneFile-0O4iLz0t.mjs} +1 -1
  169. package/dist/{parquetToCsvOneFile-13GirFzy.mjs.map → parquetToCsvOneFile-0O4iLz0t.mjs.map} +1 -1
  170. package/dist/parseVariablesFromString-B4TUkJRF.mjs +2 -0
  171. package/dist/parseVariablesFromString-B4TUkJRF.mjs.map +1 -0
  172. package/dist/{pullAllDatapoints-Bvv9KRR5.mjs → pullAllDatapoints-DJno8LkB.mjs} +1 -1
  173. package/dist/{pullAllDatapoints-Bvv9KRR5.mjs.map → pullAllDatapoints-DJno8LkB.mjs.map} +1 -1
  174. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-CQTfWHbv.mjs → pullChunkedCustomSiloOutstandingIdentifiers-rKefgKKC.mjs} +2 -2
  175. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-CQTfWHbv.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-rKefgKKC.mjs.map} +1 -1
  176. package/dist/{pullConsentManagerMetrics-CR4WwUt6.mjs → pullConsentManagerMetrics-C41UhU8u.mjs} +1 -1
  177. package/dist/{pullConsentManagerMetrics-CR4WwUt6.mjs.map → pullConsentManagerMetrics-C41UhU8u.mjs.map} +1 -1
  178. package/dist/{pullManualEnrichmentIdentifiersToCsv-B0DLb0h9.mjs → pullManualEnrichmentIdentifiersToCsv-Cbk-7ztw.mjs} +2 -2
  179. package/dist/{pullManualEnrichmentIdentifiersToCsv-B0DLb0h9.mjs.map → pullManualEnrichmentIdentifiersToCsv-Cbk-7ztw.mjs.map} +1 -1
  180. package/dist/{pushCronIdentifiersFromCsv-7s9hak_0.mjs → pushCronIdentifiersFromCsv-Dj-KEFpQ.mjs} +2 -2
  181. package/dist/{pushCronIdentifiersFromCsv-7s9hak_0.mjs.map → pushCronIdentifiersFromCsv-Dj-KEFpQ.mjs.map} +1 -1
  182. package/dist/{pushManualEnrichmentIdentifiersFromCsv-h4gafAHj.mjs → pushManualEnrichmentIdentifiersFromCsv-CY4d1jQy.mjs} +2 -2
  183. package/dist/{pushManualEnrichmentIdentifiersFromCsv-h4gafAHj.mjs.map → pushManualEnrichmentIdentifiersFromCsv-CY4d1jQy.mjs.map} +1 -1
  184. package/dist/{readTranscendYaml-ceJQNB1O.mjs → readTranscendYaml-bL1qFPqv.mjs} +2 -2
  185. package/dist/{readTranscendYaml-ceJQNB1O.mjs.map → readTranscendYaml-bL1qFPqv.mjs.map} +1 -1
  186. package/dist/{removeUnverifiedRequestIdentifiers-CjgP5O-2.mjs → removeUnverifiedRequestIdentifiers-BUJZoJD9.mjs} +2 -2
  187. package/dist/{removeUnverifiedRequestIdentifiers-CjgP5O-2.mjs.map → removeUnverifiedRequestIdentifiers-BUJZoJD9.mjs.map} +1 -1
  188. package/dist/{retryRequestDataSilos-DAY3Fu3J.mjs → retryRequestDataSilos-DATDTDin.mjs} +2 -2
  189. package/dist/{retryRequestDataSilos-DAY3Fu3J.mjs.map → retryRequestDataSilos-DATDTDin.mjs.map} +1 -1
  190. package/dist/{skipPreflightJobs-D09CE-vp.mjs → skipPreflightJobs-C1go-m8K.mjs} +2 -2
  191. package/dist/{skipPreflightJobs-D09CE-vp.mjs.map → skipPreflightJobs-C1go-m8K.mjs.map} +1 -1
  192. package/dist/{skipRequestDataSilos-CDMBQH8Z.mjs → skipRequestDataSilos-1ksexte3.mjs} +2 -2
  193. package/dist/{skipRequestDataSilos-CDMBQH8Z.mjs.map → skipRequestDataSilos-1ksexte3.mjs.map} +1 -1
  194. package/dist/{streamPrivacyRequestsToCsv-C_UcaZGl.mjs → streamPrivacyRequestsToCsv-7S52MmdS.mjs} +2 -2
  195. package/dist/{streamPrivacyRequestsToCsv-C_UcaZGl.mjs.map → streamPrivacyRequestsToCsv-7S52MmdS.mjs.map} +1 -1
  196. package/dist/{updateConsentManagerVersionToLatest-B4uTgkJS.mjs → updateConsentManagerVersionToLatest-CYGRh2Mf.mjs} +2 -2
  197. package/dist/{updateConsentManagerVersionToLatest-B4uTgkJS.mjs.map → updateConsentManagerVersionToLatest-CYGRh2Mf.mjs.map} +1 -1
  198. package/dist/{uploadConsents-mr1TLN64.mjs → uploadConsents-DxzUYFP_.mjs} +2 -2
  199. package/dist/{uploadConsents-mr1TLN64.mjs.map → uploadConsents-DxzUYFP_.mjs.map} +1 -1
  200. package/dist/{uploadCookiesFromCsv-ZG1M6Lmc.mjs → uploadCookiesFromCsv-D33lINd-.mjs} +2 -2
  201. package/dist/{uploadCookiesFromCsv-ZG1M6Lmc.mjs.map → uploadCookiesFromCsv-D33lINd-.mjs.map} +1 -1
  202. package/dist/{uploadDataFlowsFromCsv-BTyYYQQR.mjs → uploadDataFlowsFromCsv-0oDEouPJ.mjs} +2 -2
  203. package/dist/{uploadDataFlowsFromCsv-BTyYYQQR.mjs.map → uploadDataFlowsFromCsv-0oDEouPJ.mjs.map} +1 -1
  204. package/dist/{uploadPrivacyRequestsFromCsv-O6_80ZLH.mjs → uploadPrivacyRequestsFromCsv-CX7JRYjH.mjs} +2 -2
  205. package/dist/{uploadPrivacyRequestsFromCsv-O6_80ZLH.mjs.map → uploadPrivacyRequestsFromCsv-CX7JRYjH.mjs.map} +1 -1
  206. package/dist/{validateTranscendAuth-Dl8UUCAQ.mjs → validateTranscendAuth-CAO5ktnu.mjs} +2 -2
  207. package/dist/{validateTranscendAuth-Dl8UUCAQ.mjs.map → validateTranscendAuth-CAO5ktnu.mjs.map} +1 -1
  208. package/dist/{writeCsv-BMVkiMHM.mjs → writeCsv-DMw5OmWp.mjs} +1 -1
  209. package/dist/{writeCsv-BMVkiMHM.mjs.map → writeCsv-DMw5OmWp.mjs.map} +1 -1
  210. package/package.json +5 -4
  211. package/dist/app-CLOsNNoj.mjs.map +0 -1
  212. package/dist/codecs-DRBjmo_R.mjs +0 -2
  213. package/dist/codecs-DRBjmo_R.mjs.map +0 -1
  214. package/dist/impl-B0AKcSoy.mjs.map +0 -1
  215. package/dist/impl-BlI9fIP5.mjs.map +0 -1
  216. package/dist/impl-C6jaX52V.mjs +0 -2
  217. package/dist/impl-CR_UvQXr.mjs +0 -2
  218. package/dist/impl-D6rMK5Us.mjs.map +0 -1
  219. package/dist/impl-DdomTpuS2.mjs +0 -2
  220. package/dist/impl-fkYix-LF2.mjs +0 -2
  221. package/dist/parseVariablesFromString-B2TB86Fo.mjs +0 -3
  222. package/dist/parseVariablesFromString-B2TB86Fo.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import{r as e}from"./policyEngineCliError-BnBghLd1.mjs";import{i as t,n,t as r}from"./printResult-oXnpZu_9.mjs";import{t as i}from"./renderTable-DKXvortp.mjs";import{n as a}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as o}from"./logger-Ckep4QXn.mjs";import{t as s}from"./done-input-validation-uqIgnJcw.mjs";import c from"colors";async function l({"bundle-name":l,auth:u,"transcend-url":d,limit:f,after:p,json:m,debug:h=!1}){s(this.process.exit),e(h);let g=t(d,u),_=await a(g,l);if(!_)throw Error(`Policy bundle "${l}" was not found for this organization.`);o.info(c.green(`Listing versions for bundle "${l}"...`));let v={limit:f};p&&(v.after=p);let y=await n(g.get(`v1/policy-engine/policy-bundles/${_}/versions`,{searchParams:v}).json());r(this.process.stdout,{json:m,data:y,renderTable:()=>{if(y.nodes.length===0)return p?`No more versions for bundle "${l}" (end of results).`:`No versions found for bundle "${l}".`;let e=i([`id`,`version`,`createdAt`,`activatedAt`,`deactivatedAt`],y.nodes.map(e=>[e.id,e.version,e.createdAt,e.activatedAt??`-`,e.deactivatedAt??`-`]));return y.pageInfo.endCursor&&(e+=`\n\nafter: ${y.pageInfo.endCursor}`),e}})}export{l as versions};
2
- //# sourceMappingURL=impl-B0AKcSoy.mjs.map
1
+ import{r as e}from"./policyEngineCliError-BnBghLd1.mjs";import{i as t,n,t as r}from"./printResult-oXnpZu_9.mjs";import{t as i}from"./renderTable-DKXvortp.mjs";import{n as a}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as o}from"./logger-Ckep4QXn.mjs";import{t as s}from"./done-input-validation-DL31vk7g.mjs";import c from"colors";async function l({"bundle-name":l,auth:u,"transcend-url":d,limit:f,after:p,json:m,debug:h=!1}){s(this.process.exit),e(h);let g=t(d,u),_=await a(g,l);if(!_)throw Error(`Policy bundle "${l}" was not found for this organization.`);o.info(c.green(`Listing versions for bundle "${l}"...`));let v={limit:f};p&&(v.after=p);let y=await n(g.get(`v1/policy-engine/policy-bundles/${_}/versions`,{searchParams:v}).json());r(this.process.stdout,{json:m,data:y,renderTable:()=>{if(y.nodes.length===0)return p?`No more versions for bundle "${l}" (end of results).`:`No versions found for bundle "${l}".`;let e=i([`id`,`version`,`createdAt`,`activatedAt`,`deactivatedAt`],y.nodes.map(e=>[e.id,e.version,e.createdAt,e.activatedAt??`-`,e.deactivatedAt??`-`]));return y.pageInfo.endCursor&&(e+=`\n\nafter: ${y.pageInfo.endCursor}`),e}})}export{l as versions};
2
+ //# sourceMappingURL=impl-BxQE7dL92.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"impl-BxQE7dL92.mjs","names":[],"sources":["../src/commands/policy/versions/impl.ts"],"sourcesContent":["import colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { logger } from '../../../logger.js';\nimport { EMPTY_CELL } from '../constants.js';\nimport {\n buildPolicyEngineClient,\n policyEngineRequest,\n printResult,\n renderTable,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { PolicyBundleVersionListResponse } from '../types.js';\n\n/** CLI flags for `transcend policy versions`. */\nexport interface VersionsCommandFlags {\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Page size */\n limit: number;\n /** Cursor from a previous page's pageInfo.endCursor */\n after?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * List versions for a policy bundle.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function versions(\n this: LocalContext,\n {\n 'bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n limit,\n after,\n json,\n debug = false,\n }: VersionsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n setPolicyEngineCliDebug(debug);\n\n const client = buildPolicyEngineClient(transcendUrl, auth);\n const bundleId = await resolveBundleIdByName(client, bundleName);\n\n if (!bundleId) {\n throw new Error(`Policy bundle \"${bundleName}\" was not found for this organization.`);\n }\n\n logger.info(colors.green(`Listing versions for bundle \"${bundleName}\"...`));\n\n const searchParams: Record<string, string | number> = { limit };\n if (after) {\n searchParams.after = after;\n }\n\n const body = await policyEngineRequest(\n client\n .get(`v1/policy-engine/policy-bundles/${bundleId}/versions`, {\n searchParams,\n })\n .json<PolicyBundleVersionListResponse>(),\n );\n\n printResult(this.process.stdout, {\n json,\n data: body,\n renderTable: () => {\n if (body.nodes.length === 0) {\n // Distinguish \"this page is empty because you paginated past the end\"\n // from \"the bundle genuinely has no versions\" — the latter is already\n // surfaced during version resolution upstream.\n return after\n ? `No more versions for bundle \"${bundleName}\" (end of results).`\n : `No versions found for bundle \"${bundleName}\".`;\n }\n\n const rows = body.nodes.map((version) => [\n version.id,\n version.version,\n version.createdAt,\n version.activatedAt ?? EMPTY_CELL,\n version.deactivatedAt ?? EMPTY_CELL,\n ]);\n\n let table = renderTable(['id', 'version', 'createdAt', 'activatedAt', 'deactivatedAt'], rows);\n if (body.pageInfo.endCursor) {\n table += `\\n\\nafter: ${body.pageInfo.endCursor}`;\n }\n return table;\n },\n });\n}\n"],"mappings":"iVAwCA,eAAsB,EAEpB,CACE,cAAe,EACf,OACA,gBAAiB,EACjB,QACA,QACA,OACA,QAAQ,IAEK,CACf,EAAoB,KAAK,QAAQ,KAAK,CACtC,EAAwB,EAAM,CAE9B,IAAM,EAAS,EAAwB,EAAc,EAAK,CACpD,EAAW,MAAM,EAAsB,EAAQ,EAAW,CAEhE,GAAI,CAAC,EACH,MAAU,MAAM,kBAAkB,EAAW,wCAAwC,CAGvF,EAAO,KAAK,EAAO,MAAM,gCAAgC,EAAW,MAAM,CAAC,CAE3E,IAAM,EAAgD,CAAE,QAAO,CAC3D,IACF,EAAa,MAAQ,GAGvB,IAAM,EAAO,MAAM,EACjB,EACG,IAAI,mCAAmC,EAAS,WAAY,CAC3D,eACD,CAAC,CACD,MAAuC,CAC3C,CAED,EAAY,KAAK,QAAQ,OAAQ,CAC/B,OACA,KAAM,EACN,gBAAmB,CACjB,GAAI,EAAK,MAAM,SAAW,EAIxB,OAAO,EACH,gCAAgC,EAAW,qBAC3C,iCAAiC,EAAW,IAWlD,IAAI,EAAQ,EAAY,CAAC,KAAM,UAAW,YAAa,cAAe,gBAAgB,CARzE,EAAK,MAAM,IAAK,GAAY,CACvC,EAAQ,GACR,EAAQ,QACR,EAAQ,UACR,EAAQ,aAAA,IACR,EAAQ,eAAA,IACT,CAE2F,CAAC,CAI7F,OAHI,EAAK,SAAS,YAChB,GAAS,cAAc,EAAK,SAAS,aAEhC,GAEV,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./skipPreflightJobs-C1go-m8K.mjs";import{t}from"./done-input-validation-DL31vk7g.mjs";async function n({auth:n,transcendUrl:r,enricherIds:i}){t(this.process.exit),await e({transcendUrl:r,auth:n,enricherIds:i})}export{n as skipPreflightJobs};
2
+ //# sourceMappingURL=impl-C2DDZ1EB2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-fkYix-LF2.mjs","names":["skipPreflightJobsHelper"],"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests/index.js';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"yGAUA,eAAsB,EAEpB,CAAE,OAAM,eAAc,eACP,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAAwB,CAC5B,eACA,OACA,cACD,CAAC"}
1
+ {"version":3,"file":"impl-C2DDZ1EB2.mjs","names":["skipPreflightJobsHelper"],"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests/index.js';\n\nexport interface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"yGAUA,eAAsB,EAEpB,CAAE,OAAM,eAAc,eACP,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAMA,EAAwB,CAC5B,eACA,OACA,cACD,CAAC"}
@@ -1,3 +1,3 @@
1
- import{n as e,r as t,t as n}from"./runOpa-D511z37u.mjs";import{t as r}from"./logger-Ckep4QXn.mjs";import{n as i}from"./inquirer-B0OF_nRe.mjs";import{t as a}from"./done-input-validation-uqIgnJcw.mjs";import o from"node:path";import s from"colors";async function c({dir:c}){a(this.process.exit),t();let l=o.resolve(c);r.info(s.green(`Linting policy bundle in ${l}...`));let u=await e([`check`,`--strict`,l]);u!==0&&this.process.exit(u);let{stdout:d}=await n([`fmt`,`--list`,l]),f=d.trim().split(`
1
+ import{n as e,r as t,t as n}from"./runOpa-D511z37u.mjs";import{t as r}from"./logger-Ckep4QXn.mjs";import{n as i}from"./inquirer-B0OF_nRe.mjs";import{t as a}from"./done-input-validation-DL31vk7g.mjs";import o from"node:path";import s from"colors";async function c({dir:c}){a(this.process.exit),t();let l=o.resolve(c);r.info(s.green(`Linting policy bundle in ${l}...`));let u=await e([`check`,`--strict`,l]);u!==0&&this.process.exit(u);let{stdout:d}=await n([`fmt`,`--list`,l]),f=d.trim().split(`
2
2
  `).filter(e=>e.length>0);if(f.length>0){r.error(s.red(`Policy files are not formatted:`)),f.forEach(e=>{r.error(s.red(` - ${e}`))}),r.error(``),await e([`fmt`,`--diff`,l]),this.process.stdin.isTTY||(r.error(s.red(`Cannot format policy files in a non-interactive environment.`)),this.process.exit(1)),await i({message:`Format the unformatted policy files listed above?`})||this.process.exit(1);let t=await e([`fmt`,`-w`,l]);t!==0&&this.process.exit(t),r.info(s.green(`Policy files formatted.`)),r.info(s.green(`Policy lint passed.`));return}r.info(s.green(`Policy lint passed.`))}export{c as lint};
3
- //# sourceMappingURL=impl-BF9Ekyjn.mjs.map
3
+ //# sourceMappingURL=impl-C3f_H_77.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BF9Ekyjn.mjs","names":[],"sources":["../src/commands/policy/lint/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport { logger } from '../../../logger.js';\nimport { assertOpaInstalled, runOpa, runOPACapture } from '../helpers/index.js';\n\n/** CLI flags for `transcend policy lint`. */\nexport interface LintCommandFlags {\n /** Directory containing Rego policy files */\n dir: string;\n}\n\n/**\n * Local Rego lint via `opa check` and optional interactive formatting via `opa fmt`.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function lint(this: LocalContext, { dir }: LintCommandFlags): Promise<void> {\n doneInputValidation(this.process.exit);\n\n assertOpaInstalled();\n const resolvedDir = path.resolve(dir);\n\n logger.info(colors.green(`Linting policy bundle in ${resolvedDir}...`));\n\n const checkCode = await runOpa(['check', '--strict', resolvedDir]);\n if (checkCode !== 0) {\n this.process.exit(checkCode);\n }\n\n const { stdout } = await runOPACapture(['fmt', '--list', resolvedDir]);\n const unformattedFiles = stdout\n .trim()\n .split('\\n')\n .filter((file) => file.length > 0);\n\n if (unformattedFiles.length > 0) {\n logger.error(colors.red('Policy files are not formatted:'));\n unformattedFiles.forEach((file) => {\n logger.error(colors.red(` - ${file}`));\n });\n logger.error('');\n await runOpa(['fmt', '--diff', resolvedDir]);\n\n if (!this.process.stdin.isTTY) {\n logger.error(colors.red('Cannot format policy files in a non-interactive environment.'));\n this.process.exit(1);\n }\n\n const shouldFormat = await inquirerConfirmBoolean({\n message: 'Format the unformatted policy files listed above?',\n });\n if (!shouldFormat) {\n this.process.exit(1);\n }\n\n const fmtWriteCode = await runOpa(['fmt', '-w', resolvedDir]);\n if (fmtWriteCode !== 0) {\n this.process.exit(fmtWriteCode);\n }\n\n logger.info(colors.green('Policy files formatted.'));\n logger.info(colors.green('Policy lint passed.'));\n return;\n }\n\n logger.info(colors.green('Policy lint passed.'));\n}\n"],"mappings":"sPAsBA,eAAsB,EAAyB,CAAE,OAAwC,CACvF,EAAoB,KAAK,QAAQ,KAAK,CAEtC,GAAoB,CACpB,IAAM,EAAc,EAAK,QAAQ,EAAI,CAErC,EAAO,KAAK,EAAO,MAAM,4BAA4B,EAAY,KAAK,CAAC,CAEvE,IAAM,EAAY,MAAM,EAAO,CAAC,QAAS,WAAY,EAAY,CAAC,CAC9D,IAAc,GAChB,KAAK,QAAQ,KAAK,EAAU,CAG9B,GAAM,CAAE,UAAW,MAAM,EAAc,CAAC,MAAO,SAAU,EAAY,CAAC,CAChE,EAAmB,EACtB,MAAM,CACN,MAAM;EAAK,CACX,OAAQ,GAAS,EAAK,OAAS,EAAE,CAEpC,GAAI,EAAiB,OAAS,EAAG,CAC/B,EAAO,MAAM,EAAO,IAAI,kCAAkC,CAAC,CAC3D,EAAiB,QAAS,GAAS,CACjC,EAAO,MAAM,EAAO,IAAI,OAAO,IAAO,CAAC,EACvC,CACF,EAAO,MAAM,GAAG,CAChB,MAAM,EAAO,CAAC,MAAO,SAAU,EAAY,CAAC,CAEvC,KAAK,QAAQ,MAAM,QACtB,EAAO,MAAM,EAAO,IAAI,+DAA+D,CAAC,CACxF,KAAK,QAAQ,KAAK,EAAE,EAMjB,MAHsB,EAAuB,CAChD,QAAS,oDACV,CAAC,EAEA,KAAK,QAAQ,KAAK,EAAE,CAGtB,IAAM,EAAe,MAAM,EAAO,CAAC,MAAO,KAAM,EAAY,CAAC,CACzD,IAAiB,GACnB,KAAK,QAAQ,KAAK,EAAa,CAGjC,EAAO,KAAK,EAAO,MAAM,0BAA0B,CAAC,CACpD,EAAO,KAAK,EAAO,MAAM,sBAAsB,CAAC,CAChD,OAGF,EAAO,KAAK,EAAO,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"impl-C3f_H_77.mjs","names":[],"sources":["../src/commands/policy/lint/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport { logger } from '../../../logger.js';\nimport { assertOpaInstalled, runOpa, runOPACapture } from '../helpers/index.js';\n\n/** CLI flags for `transcend policy lint`. */\nexport interface LintCommandFlags {\n /** Directory containing Rego policy files */\n dir: string;\n}\n\n/**\n * Local Rego lint via `opa check` and optional interactive formatting via `opa fmt`.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function lint(this: LocalContext, { dir }: LintCommandFlags): Promise<void> {\n doneInputValidation(this.process.exit);\n\n assertOpaInstalled();\n const resolvedDir = path.resolve(dir);\n\n logger.info(colors.green(`Linting policy bundle in ${resolvedDir}...`));\n\n const checkCode = await runOpa(['check', '--strict', resolvedDir]);\n if (checkCode !== 0) {\n this.process.exit(checkCode);\n }\n\n const { stdout } = await runOPACapture(['fmt', '--list', resolvedDir]);\n const unformattedFiles = stdout\n .trim()\n .split('\\n')\n .filter((file) => file.length > 0);\n\n if (unformattedFiles.length > 0) {\n logger.error(colors.red('Policy files are not formatted:'));\n unformattedFiles.forEach((file) => {\n logger.error(colors.red(` - ${file}`));\n });\n logger.error('');\n await runOpa(['fmt', '--diff', resolvedDir]);\n\n if (!this.process.stdin.isTTY) {\n logger.error(colors.red('Cannot format policy files in a non-interactive environment.'));\n this.process.exit(1);\n }\n\n const shouldFormat = await inquirerConfirmBoolean({\n message: 'Format the unformatted policy files listed above?',\n });\n if (!shouldFormat) {\n this.process.exit(1);\n }\n\n const fmtWriteCode = await runOpa(['fmt', '-w', resolvedDir]);\n if (fmtWriteCode !== 0) {\n this.process.exit(fmtWriteCode);\n }\n\n logger.info(colors.green('Policy files formatted.'));\n logger.info(colors.green('Policy lint passed.'));\n return;\n }\n\n logger.info(colors.green('Policy lint passed.'));\n}\n"],"mappings":"sPAsBA,eAAsB,EAAyB,CAAE,OAAwC,CACvF,EAAoB,KAAK,QAAQ,KAAK,CAEtC,GAAoB,CACpB,IAAM,EAAc,EAAK,QAAQ,EAAI,CAErC,EAAO,KAAK,EAAO,MAAM,4BAA4B,EAAY,KAAK,CAAC,CAEvE,IAAM,EAAY,MAAM,EAAO,CAAC,QAAS,WAAY,EAAY,CAAC,CAC9D,IAAc,GAChB,KAAK,QAAQ,KAAK,EAAU,CAG9B,GAAM,CAAE,UAAW,MAAM,EAAc,CAAC,MAAO,SAAU,EAAY,CAAC,CAChE,EAAmB,EACtB,MAAM,CACN,MAAM;EAAK,CACX,OAAQ,GAAS,EAAK,OAAS,EAAE,CAEpC,GAAI,EAAiB,OAAS,EAAG,CAC/B,EAAO,MAAM,EAAO,IAAI,kCAAkC,CAAC,CAC3D,EAAiB,QAAS,GAAS,CACjC,EAAO,MAAM,EAAO,IAAI,OAAO,IAAO,CAAC,EACvC,CACF,EAAO,MAAM,GAAG,CAChB,MAAM,EAAO,CAAC,MAAO,SAAU,EAAY,CAAC,CAEvC,KAAK,QAAQ,MAAM,QACtB,EAAO,MAAM,EAAO,IAAI,+DAA+D,CAAC,CACxF,KAAK,QAAQ,KAAK,EAAE,EAMjB,MAHsB,EAAuB,CAChD,QAAS,oDACV,CAAC,EAEA,KAAK,QAAQ,KAAK,EAAE,CAGtB,IAAM,EAAe,MAAM,EAAO,CAAC,MAAO,KAAM,EAAY,CAAC,CACzD,IAAiB,GACnB,KAAK,QAAQ,KAAK,EAAa,CAGjC,EAAO,KAAK,EAAO,MAAM,0BAA0B,CAAC,CACpD,EAAO,KAAK,EAAO,MAAM,sBAAsB,CAAC,CAChD,OAGF,EAAO,KAAK,EAAO,MAAM,sBAAsB,CAAC"}
@@ -1,3 +1,3 @@
1
- import{t as e}from"./buildExamples-CHogOpC8.mjs";import{r as t}from"./policyEngineCliError-BnBghLd1.mjs";import{n,t as r}from"./constants-FbK2iR--.mjs";import{r as i,t as a}from"./runOpa-D511z37u.mjs";import{i as o,n as s,t as c}from"./printResult-oXnpZu_9.mjs";import{t as l}from"./formatPolicyBundleVersionSummary-Bo7DYxoy.mjs";import{n as u}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as d}from"./logger-Ckep4QXn.mjs";import{n as f}from"./inquirer-B0OF_nRe.mjs";import{t as p}from"./done-input-validation-uqIgnJcw.mjs";import{spawnSync as m}from"node:child_process";import h from"node:fs";import g from"node:os";import _ from"node:path";import{gunzipSync as v}from"node:zlib";import y from"fast-glob";import b from"colors";function x(e){return e.endsWith(`.rego`)&&!e.endsWith(`_test.rego`)}function S(e){let t=_.join(e,`manifest.json`);if(!h.existsSync(t))throw Error(`Policy bundle directory must contain a manifest.json file.`);let n=h.readFileSync(t,`utf8`),r;try{r=JSON.parse(n)}catch(e){throw Error(`manifest.json is not valid JSON: ${e instanceof Error?e.message:String(e)}`,{cause:e})}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`manifest.json must contain a JSON object.`);let i=r.roots;if(!Array.isArray(i)||i.length===0)throw Error(`manifest.json must declare "roots" as a non-empty array of strings (e.g. {"roots":["policy_engine"]}).`);if(!i.every(e=>typeof e==`string`&&e.length>0))throw Error(`manifest.json "roots" must be an array of non-empty strings.`);return{roots:i}}function C(e){let t=S(e),n=y.sync(`**/*.rego`,{cwd:e,onlyFiles:!0,dot:!1}).filter(x);if(n.length===0)throw Error(`Policy bundle directory must contain at least one .rego policy file.`);return{entries:[`manifest.json`,...n.sort()],manifest:t}}const w=/^\s*package\s+([A-Za-z_][\w.]*)/m;function T(e){return e.replace(/\//g,`.`)}function E(e){let t=h.readFileSync(e,`utf8`);return w.exec(t)?.[1]}function D(e,t,n){let r=n.map(T),i=[];for(let a of t){let t=E(_.join(e,a));t&&(r.some(e=>t===e||t.startsWith(`${e}.`))||i.push(` - ${a} (package ${t}) is not covered by roots [${n.join(`, `)}]`))}if(i.length>0)throw Error([`manifest.json "roots" do not cover all Rego packages in the bundle; uncovered packages will fail-closed at decide time. Either broaden "roots" or move the policy under a covered package:`,...i].join(`
1
+ import{t as e}from"./buildExamples-CnfZJ8MD.mjs";import{r as t}from"./policyEngineCliError-BnBghLd1.mjs";import{n,t as r}from"./constants-FbK2iR--.mjs";import{r as i,t as a}from"./runOpa-D511z37u.mjs";import{i as o,n as s,t as c}from"./printResult-oXnpZu_9.mjs";import{t as l}from"./formatPolicyBundleVersionSummary-Bo7DYxoy.mjs";import{n as u}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as d}from"./logger-Ckep4QXn.mjs";import{n as f}from"./inquirer-B0OF_nRe.mjs";import{t as p}from"./done-input-validation-DL31vk7g.mjs";import{spawnSync as m}from"node:child_process";import h from"node:fs";import g from"node:os";import _ from"node:path";import{gunzipSync as v}from"node:zlib";import y from"fast-glob";import b from"colors";function x(e){return e.endsWith(`.rego`)&&!e.endsWith(`_test.rego`)}function S(e){let t=_.join(e,`manifest.json`);if(!h.existsSync(t))throw Error(`Policy bundle directory must contain a manifest.json file.`);let n=h.readFileSync(t,`utf8`),r;try{r=JSON.parse(n)}catch(e){throw Error(`manifest.json is not valid JSON: ${e instanceof Error?e.message:String(e)}`,{cause:e})}if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`manifest.json must contain a JSON object.`);let i=r.roots;if(!Array.isArray(i)||i.length===0)throw Error(`manifest.json must declare "roots" as a non-empty array of strings (e.g. {"roots":["policy_engine"]}).`);if(!i.every(e=>typeof e==`string`&&e.length>0))throw Error(`manifest.json "roots" must be an array of non-empty strings.`);return{roots:i}}function C(e){let t=S(e),n=y.sync(`**/*.rego`,{cwd:e,onlyFiles:!0,dot:!1}).filter(x);if(n.length===0)throw Error(`Policy bundle directory must contain at least one .rego policy file.`);return{entries:[`manifest.json`,...n.sort()],manifest:t}}const w=/^\s*package\s+([A-Za-z_][\w.]*)/m;function T(e){return e.replace(/\//g,`.`)}function E(e){let t=h.readFileSync(e,`utf8`);return w.exec(t)?.[1]}function D(e,t,n){let r=n.map(T),i=[];for(let a of t){let t=E(_.join(e,a));t&&(r.some(e=>t===e||t.startsWith(`${e}.`))||i.push(` - ${a} (package ${t}) is not covered by roots [${n.join(`, `)}]`))}if(i.length>0)throw Error([`manifest.json "roots" do not cover all Rego packages in the bundle; uncovered packages will fail-closed at decide time. Either broaden "roots" or move the policy under a covered package:`,...i].join(`
2
2
  `))}async function O(e){let t=_.join(g.tmpdir(),`transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`);try{let{code:n,stderr:r}=await a([`build`,`--v0-compatible`,`--ignore`,`*_test.rego`,`-o`,t,`.`],{cwd:e});if(n!==0)throw Error(r.trim()||`opa build failed with exit code ${n}`)}finally{h.existsSync(t)&&h.unlinkSync(t)}}function k(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t%1==0?t.toFixed(0):t.toFixed(1)} KiB`;let n=t/1024;return`${n%1==0?n.toFixed(0):n.toFixed(1)} MiB`}async function A(e){i();let t=_.resolve(e);if(!h.existsSync(t)||!h.statSync(t).isDirectory())throw Error(`Policy directory does not exist or is not a directory: ${t}`);let{entries:o,manifest:s}=C(t);D(t,o.filter(e=>e!==`manifest.json`),s.roots);let{code:c,stderr:l}=await a([`check`,`--strict`,`--v0-compatible`,t]);if(c!==0)throw Error(l.trim()||`opa check failed with exit code ${c}`);await O(t);let u=_.join(g.tmpdir(),`transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`),d=m(`tar`,[`-czf`,u,`-C`,t,...o],{env:{...process.env,COPYFILE_DISABLE:`1`},encoding:`utf8`});if(d.status!==0)throw Error(`Failed to create policy bundle archive: ${d.stderr.trim()||`tar failed`}`);let f=h.readFileSync(u);if(f.byteLength>5120)throw h.unlinkSync(u),Error(`Policy bundle exceeds the ${k(r)} compressed upload limit (bundle is ${k(f.byteLength)}). The server also rejects decompressed bundles larger than ${k(n)}.`);let p=v(f);if(p.byteLength>51200)throw h.unlinkSync(u),Error(`Policy bundle exceeds the ${k(n)} decompressed upload limit (bundle is ${k(p.byteLength)} decompressed).`);return u}function j(e){let t=h.readFileSync(e.bundlePath),n=new FormData;return n.append(`bundle`,new Blob([t],{type:`application/gzip`}),_.basename(e.bundlePath)),n.append(`version`,e.version),e.description&&n.append(`description`,e.description),e.bundleName&&n.append(`bundleName`,e.bundleName),n}function M(e){return e.toISOString().slice(0,19).replace(/[T:]/g,`-`)}function N(e,t=new Date){return`${e}-${M(t)}`}async function P({dir:n,"bundle-name":r,auth:i,"transcend-url":a,version:m,description:g,json:v,yes:y,debug:x=!1}){p(this.process.exit),t(x);let S=_.resolve(n),C=m??N(r),w=o(a,i),T;try{d.info(b.green(`Building policy bundle from ${S}...`)),T=await A(S);let t=await u(w,r),n;if(t){d.info(b.green(`Uploading new version for bundle "${r}"...`));let e=j({bundlePath:T,version:C,description:g});n=await s(w.post(`v1/policy-engine/policy-bundles/${t}/versions`,{body:e}).json())}else{if(!this.process.stdin.isTTY&&!y){d.error(b.red(`Cannot create a new bundle in a non-interactive environment; pass --yes to confirm.`)),this.process.exit(1);return}if(!y&&(d.warn(b.yellow(`No policy bundle named "${r}" exists for this organization.`)),!await f({message:`No policy bundle named "${r}" exists. Create a new bundle and upload its first version?`}))){d.info(b.yellow(`Publish cancelled.`));return}d.info(b.green(`Creating bundle "${r}" and uploading first version...`));let e=j({bundlePath:T,version:C,description:g,bundleName:r});n=await s(w.post(`v1/policy-engine/policy-bundles`,{body:e}).json())}c(this.process.stdout,{json:v,data:n,renderTable:()=>l(n.version)}),d.info(b.green(`Policy bundle version uploaded successfully.`));let i=e([`policy`,`activate`],{version:n.version.version,"bundle-name":r});d.info(b.yellow(`Publishing a policy does not activate it. To activate this version, run:\n ${i}`))}finally{T&&h.existsSync(T)&&h.unlinkSync(T)}}export{P as publish};
3
- //# sourceMappingURL=impl-BlI9fIP5.mjs.map
3
+ //# sourceMappingURL=impl-C9KCLG7s2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"impl-C9KCLG7s2.mjs","names":["fg"],"sources":["../src/commands/policy/helpers/buildOpaBundleTarball.ts","../src/commands/policy/helpers/buildPolicyBundleFormData.ts","../src/commands/policy/helpers/defaultPolicyVersionLabel.ts","../src/commands/policy/publish/impl.ts"],"sourcesContent":["import { spawnSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { gunzipSync } from 'node:zlib';\n\nimport fg from 'fast-glob';\n\nimport { MAX_BUNDLE_COMPRESSED_BYTES, MAX_BUNDLE_DECOMPRESSED_BYTES } from '../constants.js';\nimport { assertOpaInstalled } from './assertOpaInstalled.js';\nimport { runOPACapture } from './runOpa.js';\n\n/**\n * Returns whether a relative path is a publishable Rego policy file.\n *\n * OPA test files (`*_test.rego`) are excluded because they are for local\n * validation only and are not part of the upload contract.\n *\n * @param relativePath - Path relative to the bundle directory\n * @returns Whether the file should be included in the upload archive\n */\nfunction isPublishableRegoFile(relativePath: string): boolean {\n return relativePath.endsWith('.rego') && !relativePath.endsWith('_test.rego');\n}\n\n/** Shape of the OPA bundle `manifest.json` as accepted by the Policy Engine. */\ninterface PolicyBundleManifest {\n /** Roots of the bundle, e.g. `[\"policy_engine\"]` or `[\"policy_engine/transcend\"]` */\n roots: string[];\n}\n\n/**\n * Reads and validates `manifest.json` from a policy bundle directory.\n *\n * The Policy Engine requires `manifest.json` to declare `roots` as an array of\n * strings. OPA's own tooling does not always enforce this against the Rego\n * packages on upload, so we validate the shape client-side to surface a clear,\n * actionable error instead of an opaque server `400` or a decide-time\n * fail-closed footgun.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns The parsed manifest\n */\nfunction readPolicyBundleManifest(dir: string): PolicyBundleManifest {\n const manifestPath = path.join(dir, 'manifest.json');\n if (!fs.existsSync(manifestPath)) {\n throw new Error('Policy bundle directory must contain a manifest.json file.');\n }\n\n const raw = fs.readFileSync(manifestPath, 'utf8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `manifest.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('manifest.json must contain a JSON object.');\n }\n\n const roots = (parsed as { roots?: unknown }).roots;\n if (!Array.isArray(roots) || roots.length === 0) {\n throw new Error(\n 'manifest.json must declare \"roots\" as a non-empty array of strings (e.g. {\"roots\":[\"policy_engine\"]}).',\n );\n }\n\n if (!roots.every((root) => typeof root === 'string' && root.length > 0)) {\n throw new Error('manifest.json \"roots\" must be an array of non-empty strings.');\n }\n\n return { roots };\n}\n\n/** Result of collecting publishable entries from a policy bundle directory. */\ninterface PolicyBundleArchiveContents {\n /** Relative paths to include in the upload tarball (manifest first, then rego) */\n entries: string[];\n /** Parsed manifest */\n manifest: PolicyBundleManifest;\n}\n\n/**\n * Collects `manifest.json` and publishable `.rego` files from a policy directory.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @returns Archive entries and the parsed manifest\n */\nfunction collectPolicyBundleArchiveEntries(dir: string): PolicyBundleArchiveContents {\n const manifest = readPolicyBundleManifest(dir);\n\n const regoFiles = fg\n .sync('**/*.rego', {\n cwd: dir,\n onlyFiles: true,\n dot: false,\n })\n .filter(isPublishableRegoFile);\n\n if (regoFiles.length === 0) {\n throw new Error('Policy bundle directory must contain at least one .rego policy file.');\n }\n\n return { entries: ['manifest.json', ...regoFiles.sort()], manifest };\n}\n\n/** Matches a Rego `package <path>` declaration. */\nconst PACKAGE_DECLARATION_PATTERN = /^\\s*package\\s+([A-Za-z_][\\w.]*)/m;\n\n/**\n * Normalizes an OPA manifest root to a dotted package prefix.\n *\n * Roots use `/` as the path separator (e.g. `policy_engine/transcend`); Rego\n * package paths use `.` (e.g. `policy_engine.transcend`).\n *\n * @param root - A manifest root string\n * @returns The root in dotted form\n */\nfunction normalizeRootToPackagePrefix(root: string): string {\n return root.replace(/\\//g, '.');\n}\n\n/**\n * Reads the Rego package path declared in a `.rego` file.\n *\n * @param filePath - Absolute path to the `.rego` file\n * @returns The dotted package path, or `undefined` if no `package` declaration\n */\nfunction readRegoPackagePath(filePath: string): string | undefined {\n const contents = fs.readFileSync(filePath, 'utf8');\n const match = PACKAGE_DECLARATION_PATTERN.exec(contents);\n return match?.[1];\n}\n\n/**\n * Verifies that every publishable `.rego` package is covered by a manifest root.\n *\n * A bundle whose `roots` do not cover its Rego packages will upload cleanly but\n * fail-closed at decide time — the customer only discovers the mismatch via\n * denied decisions. This surfaces the mismatch at upload with a clear message.\n *\n * @param dir - Absolute path to the policy bundle directory\n * @param regoFiles - Relative paths to publishable `.rego` files\n * @param roots - Manifest roots\n */\nfunction assertRootsCoverPackages(dir: string, regoFiles: string[], roots: string[]): void {\n const rootPrefixes = roots.map(normalizeRootToPackagePrefix);\n\n const uncovered: string[] = [];\n for (const relativeRego of regoFiles) {\n const pkg = readRegoPackagePath(path.join(dir, relativeRego));\n if (!pkg) {\n continue;\n }\n const covered = rootPrefixes.some((prefix) => pkg === prefix || pkg.startsWith(`${prefix}.`));\n if (!covered) {\n uncovered.push(\n ` - ${relativeRego} (package ${pkg}) is not covered by roots [${roots.join(', ')}]`,\n );\n }\n }\n\n if (uncovered.length > 0) {\n throw new Error(\n [\n 'manifest.json \"roots\" do not cover all Rego packages in the bundle; ' +\n 'uncovered packages will fail-closed at decide time. Either broaden \"roots\" or move the policy under a covered package:',\n ...uncovered,\n ].join('\\n'),\n );\n }\n}\n\n/**\n * Verifies that a policy directory compiles end-to-end with `opa build`.\n *\n * The compiled output is discarded — the server receives the `manifest.json` +\n * `.rego` archive produced by {@link buildOpaBundleTarball}, not the OPA bundle\n * — but a successful build guarantees the policies compile and link, surfacing\n * errors (syntax, missing imports, undefined references, etc.) before upload.\n *\n * @param dir - Absolute path to the policy bundle directory\n */\nasync function assertBundleCompiles(dir: string): Promise<void> {\n const buildOutputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-build-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n try {\n // Run with `cwd` set to the bundle directory and pass `.` so `opa build`\n // resolves the bundle root correctly. `*_test.rego` files are local-only.\n const { code, stderr } = await runOPACapture(\n ['build', '--v0-compatible', '--ignore', '*_test.rego', '-o', buildOutputPath, '.'],\n { cwd: dir },\n );\n if (code !== 0) {\n throw new Error(stderr.trim() || `opa build failed with exit code ${code}`);\n }\n } finally {\n if (fs.existsSync(buildOutputPath)) {\n fs.unlinkSync(buildOutputPath);\n }\n }\n}\n\n/**\n * Formats a byte count as a human-readable size with binary units.\n *\n * @param bytes - Number of bytes\n * @returns Human-readable size, e.g. `14 MiB` or `4 KiB`\n */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n const kib = bytes / 1024;\n if (kib < 1024) {\n return `${kib % 1 === 0 ? kib.toFixed(0) : kib.toFixed(1)} KiB`;\n }\n const mib = kib / 1024;\n return `${mib % 1 === 0 ? mib.toFixed(0) : mib.toFixed(1)} MiB`;\n}\n\n/**\n * Builds a gzip-compressed policy bundle tarball for upload to Transcend.\n *\n * The Policy Engine API expects a plain archive containing `manifest.json` and\n * one or more `.rego` files. This differs from `opa build` output, which embeds\n * `.manifest`, `data.json`, and other OPA bundle metadata that the server\n * rejects. Before packaging, the manifest is validated (shape + root coverage)\n * and the bundle is validated with `opa check` (strict Rego linting) and\n * `opa build` (full compilation) so failures surface client-side rather than\n * after upload.\n *\n * @param dir - Directory containing `manifest.json` and `.rego` policy files\n * @returns Absolute path to the generated `.tar.gz` bundle\n */\nexport async function buildOpaBundleTarball(dir: string): Promise<string> {\n assertOpaInstalled();\n\n const resolvedDir = path.resolve(dir);\n if (!fs.existsSync(resolvedDir) || !fs.statSync(resolvedDir).isDirectory()) {\n throw new Error(`Policy directory does not exist or is not a directory: ${resolvedDir}`);\n }\n\n // Validate the manifest shape and that roots cover every Rego package before\n // invoking OPA, so invalid manifests surface a clear error instead of an\n // opaque `opa build failed with exit code 1`.\n const { entries: archiveEntries, manifest } = collectPolicyBundleArchiveEntries(resolvedDir);\n const regoFiles = archiveEntries.filter((entry) => entry !== 'manifest.json');\n assertRootsCoverPackages(resolvedDir, regoFiles, manifest.roots);\n\n // Match the Rego v1 validation the Policy Engine API runs on upload.\n const { code: checkCode, stderr: checkStderr } = await runOPACapture([\n 'check',\n '--strict',\n '--v0-compatible',\n resolvedDir,\n ]);\n if (checkCode !== 0) {\n throw new Error(checkStderr.trim() || `opa check failed with exit code ${checkCode}`);\n }\n\n // Ensure the bundle compiles end-to-end before packaging for upload.\n await assertBundleCompiles(resolvedDir);\n\n const outputPath = path.join(\n os.tmpdir(),\n `transcend-policy-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.tar.gz`,\n );\n\n const tarResult = spawnSync('tar', ['-czf', outputPath, '-C', resolvedDir, ...archiveEntries], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n encoding: 'utf8',\n });\n if (tarResult.status !== 0) {\n throw new Error(\n `Failed to create policy bundle archive: ${tarResult.stderr.trim() || 'tar failed'}`,\n );\n }\n\n const compressedBytes = fs.readFileSync(outputPath);\n if (compressedBytes.byteLength > MAX_BUNDLE_COMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_COMPRESSED_BYTES)} compressed upload limit ` +\n `(bundle is ${formatBytes(compressedBytes.byteLength)}). ` +\n `The server also rejects decompressed bundles larger than ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)}.`,\n );\n }\n\n const decompressedBytes = gunzipSync(compressedBytes);\n if (decompressedBytes.byteLength > MAX_BUNDLE_DECOMPRESSED_BYTES) {\n fs.unlinkSync(outputPath);\n throw new Error(\n `Policy bundle exceeds the ${formatBytes(MAX_BUNDLE_DECOMPRESSED_BYTES)} decompressed upload limit ` +\n `(bundle is ${formatBytes(decompressedBytes.byteLength)} decompressed).`,\n );\n }\n\n return outputPath;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\n/** Fields for building a policy bundle upload form. */\nexport interface BuildPolicyBundleFormDataOptions {\n /** Absolute path to the bundle tarball */\n bundlePath: string;\n /** Version label */\n version: string;\n /** Optional description */\n description?: string;\n /** Bundle name (only for create) */\n bundleName?: string;\n}\n\n/**\n * Builds multipart form data for a policy bundle upload.\n *\n * @param options - Upload fields\n * @returns FormData ready for POST\n */\nexport function buildPolicyBundleFormData(options: BuildPolicyBundleFormDataOptions): FormData {\n const bundleBytes = fs.readFileSync(options.bundlePath);\n const form = new FormData();\n form.append(\n 'bundle',\n new Blob([bundleBytes], { type: 'application/gzip' }),\n path.basename(options.bundlePath),\n );\n form.append('version', options.version);\n if (options.description) {\n form.append('description', options.description);\n }\n if (options.bundleName) {\n form.append('bundleName', options.bundleName);\n }\n return form;\n}\n","/**\n * Formats a date as `yyyy-mm-dd-hh-mm-ss` in UTC.\n *\n * @param date - Date to format\n * @returns Timestamp label\n */\nfunction formatPolicyVersionTimestamp(date: Date): string {\n return date.toISOString().slice(0, 19).replace(/[T:]/g, '-');\n}\n\n/**\n * Returns a default version label from the bundle name and current UTC timestamp.\n *\n * @param bundleName - Tenant-unique policy bundle name\n * @param now - Current time (for testing)\n * @returns Version label in `{bundleName}-yyyy-mm-dd-hh-mm-ss` form\n */\nexport function defaultPolicyVersionLabel(bundleName: string, now: Date = new Date()): string {\n return `${bundleName}-${formatPolicyVersionTimestamp(now)}`;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildExampleCommand } from '../../../lib/docgen/buildExamples.js';\nimport { inquirerConfirmBoolean } from '../../../lib/helpers/inquirer.js';\nimport { logger } from '../../../logger.js';\nimport type { ActivateCommandFlags } from '../activate/impl.js';\nimport {\n buildPolicyBundleFormData,\n buildPolicyEngineClient,\n buildOpaBundleTarball,\n defaultPolicyVersionLabel,\n formatPolicyBundleVersionSummary,\n policyEngineRequest,\n printResult,\n resolveBundleIdByName,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { CreatePolicyBundleResponse, CreatePolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy publish`. */\nexport interface PublishCommandFlags {\n /** Directory containing Rego policy files */\n dir: string;\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Version label (defaults to `{bundleName}-yyyy-mm-dd-hh-mm-ss`) */\n version?: string;\n /** Optional version description */\n description?: string;\n /** Print raw JSON response */\n json: boolean;\n /** Skip the \"create new bundle\" confirmation */\n yes: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Build and upload a new immutable policy bundle version.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function publish(\n this: LocalContext,\n {\n dir,\n 'bundle-name': bundleName,\n auth,\n 'transcend-url': transcendUrl,\n version,\n description,\n json,\n yes,\n debug = false,\n }: PublishCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n setPolicyEngineCliDebug(debug);\n\n const resolvedDir = path.resolve(dir);\n const versionLabel = version ?? defaultPolicyVersionLabel(bundleName);\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n let bundlePath: string | undefined;\n try {\n logger.info(colors.green(`Building policy bundle from ${resolvedDir}...`));\n bundlePath = await buildOpaBundleTarball(resolvedDir);\n\n const existingBundleId = await resolveBundleIdByName(client, bundleName);\n\n let responseBody: CreatePolicyBundleResponse | CreatePolicyBundleVersionResponse;\n\n if (existingBundleId) {\n logger.info(colors.green(`Uploading new version for bundle \"${bundleName}\"...`));\n const form = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n });\n responseBody = await policyEngineRequest(\n client\n .post(`v1/policy-engine/policy-bundles/${existingBundleId}/versions`, { body: form })\n .json<CreatePolicyBundleVersionResponse>(),\n );\n } else {\n if (!this.process.stdin.isTTY && !yes) {\n logger.error(\n colors.red(\n 'Cannot create a new bundle in a non-interactive environment; pass --yes to confirm.',\n ),\n );\n this.process.exit(1);\n return;\n }\n\n if (!yes) {\n logger.warn(\n colors.yellow(`No policy bundle named \"${bundleName}\" exists for this organization.`),\n );\n const shouldCreate = await inquirerConfirmBoolean({\n message: `No policy bundle named \"${bundleName}\" exists. Create a new bundle and upload its first version?`,\n });\n if (!shouldCreate) {\n logger.info(colors.yellow('Publish cancelled.'));\n return;\n }\n }\n\n logger.info(colors.green(`Creating bundle \"${bundleName}\" and uploading first version...`));\n const createForm = buildPolicyBundleFormData({\n bundlePath,\n version: versionLabel,\n description,\n bundleName,\n });\n responseBody = await policyEngineRequest(\n client\n .post('v1/policy-engine/policy-bundles', {\n body: createForm,\n })\n .json<CreatePolicyBundleResponse>(),\n );\n }\n\n printResult(this.process.stdout, {\n json,\n data: responseBody,\n renderTable: () => formatPolicyBundleVersionSummary(responseBody.version),\n });\n\n logger.info(colors.green('Policy bundle version uploaded successfully.'));\n\n const activateCommand = buildExampleCommand<ActivateCommandFlags>(['policy', 'activate'], {\n version: responseBody.version.version,\n 'bundle-name': bundleName,\n });\n logger.info(\n colors.yellow(\n `Publishing a policy does not activate it. To activate this version, run:\\n ${activateCommand}`,\n ),\n );\n } finally {\n if (bundlePath && fs.existsSync(bundlePath)) {\n fs.unlinkSync(bundlePath);\n }\n }\n}\n"],"mappings":"8tBAqBA,SAAS,EAAsB,EAA+B,CAC5D,OAAO,EAAa,SAAS,QAAQ,EAAI,CAAC,EAAa,SAAS,aAAa,CAqB/E,SAAS,EAAyB,EAAmC,CACnE,IAAM,EAAe,EAAK,KAAK,EAAK,gBAAgB,CACpD,GAAI,CAAC,EAAG,WAAW,EAAa,CAC9B,MAAU,MAAM,6DAA6D,CAG/E,IAAM,EAAM,EAAG,aAAa,EAAc,OAAO,CAC7C,EACJ,GAAI,CACF,EAAS,KAAK,MAAM,EAAI,OACjB,EAAK,CACZ,MAAU,MACR,oCAAoC,aAAe,MAAQ,EAAI,QAAU,OAAO,EAAI,GACpF,CAAE,MAAO,EAAK,CACf,CAGH,GAAI,CAAC,GAAU,OAAO,GAAW,UAAY,MAAM,QAAQ,EAAO,CAChE,MAAU,MAAM,4CAA4C,CAG9D,IAAM,EAAS,EAA+B,MAC9C,GAAI,CAAC,MAAM,QAAQ,EAAM,EAAI,EAAM,SAAW,EAC5C,MAAU,MACR,yGACD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W,CAAE,CACxF,QAAS,EAAa,QAAQ,QAC9B,cAAe,EAChB,CAAC,CACF,EAAO,KACL,EAAO,OACL,+EAA+E,IAChF,CACF,QACO,CACJ,GAAc,EAAG,WAAW,EAAW,EACzC,EAAG,WAAW,EAAW"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./bulkRetryEnrichers-Blydm41j.mjs";import{t}from"./done-input-validation-uqIgnJcw.mjs";async function n({auth:n,enricherId:r,actions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d,transcendUrl:f}){t(this.process.exit),await e({auth:n,enricherId:r,requestActions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s?new Date(s):void 0,createdAtAfter:c?new Date(c):void 0,updatedAtBefore:l?new Date(l):void 0,updatedAtAfter:u?new Date(u):void 0,concurrency:d,transcendUrl:f})}export{n as enricherRestart};
2
- //# sourceMappingURL=impl-D22mHixx.mjs.map
1
+ import{t as e}from"./bulkRetryEnrichers-BEEVKtCH.mjs";import{t}from"./done-input-validation-DL31vk7g.mjs";async function n({auth:n,enricherId:r,actions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d,transcendUrl:f}){t(this.process.exit),await e({auth:n,enricherId:r,requestActions:i,requestEnricherStatuses:a,requestIds:o,createdAtBefore:s?new Date(s):void 0,createdAtAfter:c?new Date(c):void 0,updatedAtBefore:l?new Date(l):void 0,updatedAtAfter:u?new Date(u):void 0,concurrency:d,transcendUrl:f})}export{n as enricherRestart};
2
+ //# sourceMappingURL=impl-CWVX0Xnv.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-D22mHixx.mjs","names":[],"sources":["../src/commands/request/enricher-restart/impl.ts"],"sourcesContent":["import type { RequestAction, RequestEnricherStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { bulkRetryEnrichers } from '../../../lib/requests/index.js';\n\nexport interface EnricherRestartCommandFlags {\n auth: string;\n enricherId: string;\n actions?: RequestAction[];\n requestEnricherStatuses?: RequestEnricherStatus[];\n transcendUrl: string;\n concurrency: number;\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n}\n\nexport async function enricherRestart(\n this: LocalContext,\n {\n auth,\n enricherId,\n actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n }: EnricherRestartCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await bulkRetryEnrichers({\n auth,\n enricherId,\n requestActions: actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore: createdAtBefore ? new Date(createdAtBefore) : undefined,\n createdAtAfter: createdAtAfter ? new Date(createdAtAfter) : undefined,\n updatedAtBefore: updatedAtBefore ? new Date(updatedAtBefore) : undefined,\n updatedAtAfter: updatedAtAfter ? new Date(updatedAtAfter) : undefined,\n concurrency,\n transcendUrl,\n });\n}\n"],"mappings":"0GAoBA,eAAsB,EAEpB,CACE,OACA,aACA,UACA,0BACA,aACA,kBACA,iBACA,kBACA,iBACA,cACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAmB,CACvB,OACA,aACA,eAAgB,EAChB,0BACA,aACA,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,cACA,eACD,CAAC"}
1
+ {"version":3,"file":"impl-CWVX0Xnv.mjs","names":[],"sources":["../src/commands/request/enricher-restart/impl.ts"],"sourcesContent":["import type { RequestAction, RequestEnricherStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { bulkRetryEnrichers } from '../../../lib/requests/index.js';\n\nexport interface EnricherRestartCommandFlags {\n auth: string;\n enricherId: string;\n actions?: RequestAction[];\n requestEnricherStatuses?: RequestEnricherStatus[];\n transcendUrl: string;\n concurrency: number;\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n}\n\nexport async function enricherRestart(\n this: LocalContext,\n {\n auth,\n enricherId,\n actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n transcendUrl,\n }: EnricherRestartCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await bulkRetryEnrichers({\n auth,\n enricherId,\n requestActions: actions,\n requestEnricherStatuses,\n requestIds,\n createdAtBefore: createdAtBefore ? new Date(createdAtBefore) : undefined,\n createdAtAfter: createdAtAfter ? new Date(createdAtAfter) : undefined,\n updatedAtBefore: updatedAtBefore ? new Date(updatedAtBefore) : undefined,\n updatedAtAfter: updatedAtAfter ? new Date(updatedAtAfter) : undefined,\n concurrency,\n transcendUrl,\n });\n}\n"],"mappings":"0GAoBA,eAAsB,EAEpB,CACE,OACA,aACA,UACA,0BACA,aACA,kBACA,iBACA,kBACA,iBACA,cACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAAmB,CACvB,OACA,aACA,eAAgB,EAChB,0BACA,aACA,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,gBAAiB,EAAkB,IAAI,KAAK,EAAgB,CAAG,IAAA,GAC/D,eAAgB,EAAiB,IAAI,KAAK,EAAe,CAAG,IAAA,GAC5D,cACA,eACD,CAAC"}
@@ -0,0 +1,2 @@
1
+ import{r as e}from"./constants-CAOyAsNX.mjs";import{t}from"./logger-Ckep4QXn.mjs";import{r as n}from"./readTranscendYaml-bL1qFPqv.mjs";import{n as r,t as i}from"./mergeTranscendInputs-DjPe49yR.mjs";import{t as a}from"./parseVariablesFromString-B4TUkJRF.mjs";import{t as o}from"./validateTranscendAuth-CAO5ktnu.mjs";import{t as s}from"./listFiles-C5kubvdN.mjs";import{t as c}from"./done-input-validation-DL31vk7g.mjs";import{existsSync as l,lstatSync as u}from"node:fs";import{join as d}from"node:path";import f from"colors";import{buildTranscendGraphQLClient as p}from"@transcend-io/sdk";import{mapSeries as m}from"@transcend-io/utils";async function h({transcendUrl:e,auth:n,pageSize:i,publishToPrivacyCenter:a,contents:o,deleteExtraAttributeValues:s=!1,classifyService:c=!1}){let l=p(e,n);try{let e=await r(o,l,{pageSize:i,publishToPrivacyCenter:a,classifyService:c,deleteExtraAttributeValues:s,logger:t});return e.success||e.errors.forEach(({resource:e,item:n,message:r})=>{t.error(f.red(`Failed to sync ${e}${n?` "${n}"`:``}: ${r}`))}),e.success}catch(e){return t.error(f.red(`An unexpected error occurred syncing the schema: ${e.message}`)),!1}}async function g({file:r=`./transcend.yml`,transcendUrl:p,auth:g,variables:_,pageSize:v,publishToPrivacyCenter:y,classifyService:b,deleteExtraAttributeValues:x}){c(this.process.exit);let S=await o(g),C=a(_),w;if(w=Array.isArray(S)&&u(r).isDirectory()?s(r).map(e=>d(r,e)):r.split(`,`),w.length<1)throw Error(`No file specified!`);let T=w.map(e=>{l(e)?t.info(f.magenta(`Reading file "${e}"...`)):(t.error(f.red(`The file path does not exist on disk: ${e}. You can specify the filepath using --file=./examples/transcend.yml`)),this.process.exit(1));try{let r=n(e,C);return t.info(f.green(`Successfully read in "${e}"`)),{content:r,name:e.split(`/`).pop().replace(`.yml`,``)}}catch(e){t.error(f.red(`The shape of your yaml file is invalid with the following errors: ${e.message}`)),this.process.exit(1)}});if(typeof S==`string`){let[n,...r]=T.map(({content:e})=>e);await h({transcendUrl:p,auth:S,contents:i(n,...r),publishToPrivacyCenter:y,deleteExtraAttributeValues:x,pageSize:v,classifyService:!!b})||(t.info(f.red(`Sync encountered errors. View output above for more information, or check out ${e}`)),this.process.exit(1))}else{if(T.length!==1&&T.length!==S.length)throw Error(`Expected list of yml files to be equal to the list of API keys.Got ${T.length} YML file${T.length===1?``:`s`} and ${S.length} API key${S.length===1?``:`s`}`);let n=[];await m(S,async(e,r)=>{let i=`[${r+1}/${S.length}][${e.organizationName}] `;t.info(f.magenta(`~~~\n\n${i}Attempting to push configuration...\n\n~~~`));let a=T.length===1?T[0].content:T.find(t=>t.name===e.organizationName)?.content;if(!a){t.error(f.red(`${i}Failed to find transcend.yml file for organization: "${e.organizationName}".`)),n.push(e.organizationName);return}await h({transcendUrl:p,auth:e.apiKey,contents:a,pageSize:v,publishToPrivacyCenter:y,deleteExtraAttributeValues:x,classifyService:b})?t.info(f.green(`${i}Successfully pushed configuration!`)):(t.error(f.red(`${i}Failed to sync configuration.`)),n.push(e.organizationName))}),n.length>0&&(t.info(f.red(`Sync encountered errors for "${n.join(`,`)}". View output above for more information, or check out ${e}`)),this.process.exit(1))}t.info(f.green(`Successfully synced yaml file to Transcend! View at ${e}`))}export{g as push};
2
+ //# sourceMappingURL=impl-CWqtBcmr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-CR_UvQXr.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const result = await syncConfigurationToTranscend(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n logger,\n });\n if (!result.success) {\n result.errors.forEach(({ resource, item, message }) => {\n logger.error(\n colors.red(`Failed to sync ${resource}${item ? ` \"${item}\"` : ''}: ${message}`),\n );\n });\n }\n return result.success;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Parse out the variables\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && lstatSync(file).isDirectory()) {\n fileList = listFiles(file).map((filePath) => join(file, filePath));\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!existsSync(filePath)) {\n logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = readTranscendYaml(filePath, vars);\n logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n });\n\n // exist with error code\n if (!success) {\n logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n logger.info(colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`));\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n });\n\n if (success) {\n logger.info(colors.green(`${prefix}Successfully pushed configuration!`));\n } else {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n logger.info(\n colors.green(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"2kBAwBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,IAgBC,CACnB,IAAM,EAAS,EAA4B,EAAc,EAAK,CAG9D,GAAI,CACF,IAAM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EAAkB,KAChD,IACD,CAAC,0DAA0D,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,EAAO,KACL,EAAO,MAAM,uDAAuD,IAA0B,CAC/F"}
1
+ {"version":3,"file":"impl-CWqtBcmr.mjs","names":[],"sources":["../src/commands/inventory/push/impl.ts"],"sourcesContent":["import { existsSync, lstatSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport { TranscendInput } from '../../../codecs.js';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth, listFiles } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { syncConfigurationToTranscend } from '../../../lib/graphql/index.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { mergeTranscendInputs } from '../../../lib/mergeTranscendInputs.js';\nimport { readTranscendYaml } from '../../../lib/readTranscendYaml.js';\nimport { logger } from '../../../logger.js';\n\n/**\n * Sync configuration to Transcend\n *\n * @param options - Options\n * @returns True if synced successfully, false if error occurs\n */\nasync function syncConfiguration({\n transcendUrl,\n auth,\n pageSize,\n publishToPrivacyCenter,\n contents,\n deleteExtraAttributeValues = false,\n classifyService = false,\n}: {\n /** Transcend YAML */\n contents: TranscendInput;\n /** Transcend URL */\n transcendUrl: string;\n /** API key */\n auth: string;\n /** Page size */\n pageSize: number;\n /** Skip privacy center publish step */\n publishToPrivacyCenter: boolean;\n /** classify data flow service if missing */\n classifyService?: boolean;\n /** Delete attributes when syncing */\n deleteExtraAttributeValues?: boolean;\n}): Promise<boolean> {\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Sync to Transcend\n try {\n const result = await syncConfigurationToTranscend(contents, client, {\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n logger,\n });\n if (!result.success) {\n result.errors.forEach(({ resource, item, message }) => {\n logger.error(\n colors.red(`Failed to sync ${resource}${item ? ` \"${item}\"` : ''}: ${message}`),\n );\n });\n }\n return result.success;\n } catch (err) {\n logger.error(colors.red(`An unexpected error occurred syncing the schema: ${err.message}`));\n return false;\n }\n}\n\nexport interface PushCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n pageSize: number;\n variables: string;\n publishToPrivacyCenter: boolean;\n classifyService: boolean;\n deleteExtraAttributeValues: boolean;\n}\n\nexport async function push(\n this: LocalContext,\n {\n file = './transcend.yml',\n transcendUrl,\n auth,\n variables,\n pageSize,\n publishToPrivacyCenter,\n classifyService,\n deleteExtraAttributeValues,\n }: PushCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Parse out the variables\n const vars = parseVariablesFromString(variables);\n\n // check if we are being passed a list of API keys and a list of files\n let fileList: string[];\n if (Array.isArray(apiKeyOrList) && lstatSync(file).isDirectory()) {\n fileList = listFiles(file).map((filePath) => join(file, filePath));\n } else {\n fileList = file.split(',');\n }\n\n // Ensure at least one file is parsed\n if (fileList.length < 1) {\n throw new Error('No file specified!');\n }\n\n // eslint-disable-next-line array-callback-return,consistent-return\n const transcendInputs = fileList.map((filePath) => {\n // Ensure yaml file exists on disk\n if (!existsSync(filePath)) {\n logger.error(\n colors.red(\n `The file path does not exist on disk: ${filePath}. You can specify the filepath using --file=./examples/transcend.yml`,\n ),\n );\n this.process.exit(1);\n } else {\n logger.info(colors.magenta(`Reading file \"${filePath}\"...`));\n }\n\n try {\n // Read in the yaml file and validate it's shape\n const newContents = readTranscendYaml(filePath, vars);\n logger.info(colors.green(`Successfully read in \"${filePath}\"`));\n return {\n content: newContents,\n name: filePath.split('/').pop()!.replace('.yml', ''),\n };\n } catch (err) {\n logger.error(\n colors.red(\n `The shape of your yaml file is invalid with the following errors: ${err.message}`,\n ),\n );\n this.process.exit(1);\n }\n });\n\n // process a single API key\n if (typeof apiKeyOrList === 'string') {\n // if passed multiple inputs, merge them together\n const [base, ...rest] = transcendInputs.map(({ content }) => content);\n const contents = mergeTranscendInputs(base, ...rest);\n\n // sync the configuration\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKeyOrList,\n contents,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n pageSize,\n classifyService: !!classifyService,\n });\n\n // exist with error code\n if (!success) {\n logger.info(\n colors.red(\n `Sync encountered errors. View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n } else {\n // if passed multiple inputs, expect them to be one per instance\n if (transcendInputs.length !== 1 && transcendInputs.length !== apiKeyOrList.length) {\n throw new Error(\n 'Expected list of yml files to be equal to the list of API keys.' +\n `Got ${transcendInputs.length} YML file${\n transcendInputs.length === 1 ? '' : 's'\n } and ${apiKeyOrList.length} API key${apiKeyOrList.length === 1 ? '' : 's'}`,\n );\n }\n\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${apiKey.organizationName}] `;\n logger.info(colors.magenta(`~~~\\n\\n${prefix}Attempting to push configuration...\\n\\n~~~`));\n\n // use the merged contents if 1 yml passed, else use the contents that map to that organization\n const useContents =\n transcendInputs.length === 1\n ? transcendInputs[0].content\n : transcendInputs.find((input) => input.name === apiKey.organizationName)?.content;\n\n // Throw error if cannot find a yml file matching that organization name\n if (!useContents) {\n logger.error(\n colors.red(\n `${prefix}Failed to find transcend.yml file for organization: \"${apiKey.organizationName}\".`,\n ),\n );\n encounteredErrors.push(apiKey.organizationName);\n return;\n }\n\n const success = await syncConfiguration({\n transcendUrl,\n auth: apiKey.apiKey,\n contents: useContents,\n pageSize,\n publishToPrivacyCenter,\n deleteExtraAttributeValues,\n classifyService,\n });\n\n if (success) {\n logger.info(colors.green(`${prefix}Successfully pushed configuration!`));\n } else {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n this.process.exit(1);\n }\n }\n\n // Indicate success\n logger.info(\n colors.green(`Successfully synced yaml file to Transcend! View at ${ADMIN_DASH_INTEGRATIONS}`),\n );\n}\n"],"mappings":"4nBAwBA,eAAe,EAAkB,CAC/B,eACA,OACA,WACA,yBACA,WACA,6BAA6B,GAC7B,kBAAkB,IAgBC,CACnB,IAAM,EAAS,EAA4B,EAAc,EAAK,CAG9D,GAAI,CACF,IAAM,EAAS,MAAM,EAA6B,EAAU,EAAQ,CAClE,WACA,yBACA,kBACA,6BACA,SACD,CAAC,CAQF,OAPK,EAAO,SACV,EAAO,OAAO,SAAS,CAAE,WAAU,OAAM,aAAc,CACrD,EAAO,MACL,EAAO,IAAI,kBAAkB,IAAW,EAAO,KAAK,EAAK,GAAK,GAAG,IAAI,IAAU,CAChF,EACD,CAEG,EAAO,cACP,EAAK,CAEZ,OADA,EAAO,MAAM,EAAO,IAAI,oDAAoD,EAAI,UAAU,CAAC,CACpF,IAeX,eAAsB,EAEpB,CACE,OAAO,kBACP,eACA,OACA,YACA,WACA,yBACA,kBACA,8BAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAGtC,IAAM,EAAe,MAAM,EAAsB,EAAK,CAGhD,EAAO,EAAyB,EAAU,CAG5C,EAQJ,GAPA,AAGE,EAHE,MAAM,QAAQ,EAAa,EAAI,EAAU,EAAK,CAAC,aAAa,CACnD,EAAU,EAAK,CAAC,IAAK,GAAa,EAAK,EAAM,EAAS,CAAC,CAEvD,EAAK,MAAM,IAAI,CAIxB,EAAS,OAAS,EACpB,MAAU,MAAM,qBAAqB,CAIvC,IAAM,EAAkB,EAAS,IAAK,G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AgB,KAAM,GAAU,EAAM,OAAS,EAAO,iBAAiB,EAAE,QAG/E,GAAI,CAAC,EAAa,CAChB,EAAO,MACL,EAAO,IACL,GAAG,EAAO,uDAAuD,EAAO,iBAAiB,IAC1F,CACF,CACD,EAAkB,KAAK,EAAO,iBAAiB,CAC/C,OAaE,MAVkB,EAAkB,CACtC,eACA,KAAM,EAAO,OACb,SAAU,EACV,WACA,yBACA,6BACA,kBACD,CAAC,CAGA,EAAO,KAAK,EAAO,MAAM,GAAG,EAAO,oCAAoC,CAAC,EAExE,EAAO,MAAM,EAAO,IAAI,GAAG,EAAO,+BAA+B,CAAC,CAClE,EAAkB,KAAK,EAAO,iBAAiB,GAEjD,CAEE,EAAkB,OAAS,IAC7B,EAAO,KACL,EAAO,IACL,gCAAgC,EAAkB,KAChD,IACD,CAAC,0DAA0D,IAC7D,CACF,CAED,KAAK,QAAQ,KAAK,EAAE,EAKxB,EAAO,KACL,EAAO,MAAM,uDAAuD,IAA0B,CAC/F"}
@@ -1,3 +1,3 @@
1
- import{r as e}from"./policyEngineCliError-BnBghLd1.mjs";import{i as t,n,t as r}from"./printResult-oXnpZu_9.mjs";import{t as i}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as a}from"./resolvePolicyBundleVersion-DO7IvEwb.mjs";import{t as o}from"./logger-Ckep4QXn.mjs";import{t as s}from"./done-input-validation-uqIgnJcw.mjs";import c from"node:fs";import l from"node:path";import u from"got";import d from"colors";function f(e,t){return`${e}-${t}.tar.gz`}function p(e,t){return[`bundleName ${e.bundleName}`,`version ${e.version}`,`output ${t}`,`sha256 ${e.sha256}`,`sizeBytes ${e.sizeBytes}`,`uploadedAt ${e.uploadedAt}`,`activatedAt ${e.activatedAt??`-`}`].join(`
1
+ import{r as e}from"./policyEngineCliError-BnBghLd1.mjs";import{i as t,n,t as r}from"./printResult-oXnpZu_9.mjs";import{t as i}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as a}from"./resolvePolicyBundleVersion-DO7IvEwb.mjs";import{t as o}from"./logger-Ckep4QXn.mjs";import{t as s}from"./done-input-validation-DL31vk7g.mjs";import c from"node:fs";import l from"node:path";import u from"got";import d from"colors";function f(e,t){return`${e}-${t}.tar.gz`}function p(e,t){return[`bundleName ${e.bundleName}`,`version ${e.version}`,`output ${t}`,`sha256 ${e.sha256}`,`sizeBytes ${e.sizeBytes}`,`uploadedAt ${e.uploadedAt}`,`activatedAt ${e.activatedAt??`-`}`].join(`
2
2
  `)}async function m({"bundle-name":m,version:h,output:g,auth:_,"transcend-url":v,json:y,debug:b=!1}){s(this.process.exit),e(b);let x=t(v,_),S=await i(x,m);if(!S)throw Error(`Policy bundle "${m}" was not found for this organization.`);let C;if(h)C=(await a(x,S.id,{version:h})).id;else{if(!S.activeVersionId)throw Error(`Policy bundle "${m}" has no active version.`);C=S.activeVersionId}o.info(d.green(h?`Fetching download URL for bundle "${m}" version "${h}"...`:`Fetching download URL for active version of bundle "${m}"...`));let w=await n(x.get(`v1/policy-engine/policy-bundles/${S.id}/versions/${C}`).json());if(y){r(this.process.stdout,{json:!0,data:w});return}let T=l.resolve(g??f(m,w.version));o.info(d.green(`Downloading policy bundle to ${T}...`));let E;try{E=await u(w.downloadUrl).buffer()}catch(e){throw Error(`Failed to download policy bundle from the presigned URL: ${e instanceof Error?e.message:String(e)}`,{cause:e})}let D=l.dirname(T);c.mkdirSync(D,{recursive:!0}),c.writeFileSync(T,E),r(this.process.stdout,{json:!1,data:w,renderTable:()=>p(w,T)}),o.info(d.green(`Policy bundle downloaded successfully.`))}export{m as download};
3
- //# sourceMappingURL=impl-BCEw1fsj.mjs.map
3
+ //# sourceMappingURL=impl-CZG9gzzR.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BCEw1fsj.mjs","names":[],"sources":["../src/commands/policy/download/impl.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport colors from 'colors';\nimport got from 'got';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { logger } from '../../../logger.js';\nimport { EMPTY_CELL } from '../constants.js';\nimport {\n buildPolicyEngineClient,\n policyEngineRequest,\n printResult,\n resolveBundleByName,\n resolvePolicyBundleVersion,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { GetPolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy download`. */\nexport interface DownloadCommandFlags {\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /**\n * Caller-supplied version label to download.\n * When omitted, downloads the bundle's currently active version.\n */\n version?: string;\n /** Destination file path; defaults to `{bundleName}-{version}.tar.gz` */\n output?: string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Print metadata + presigned URL as JSON without writing a file */\n json: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Builds the default output path for a downloaded policy bundle.\n *\n * @param bundleName - Tenant-unique bundle name\n * @param version - Caller-supplied version label\n * @returns Relative path `{bundleName}-{version}.tar.gz`\n */\nexport function defaultPolicyDownloadOutputPath(bundleName: string, version: string): string {\n return `${bundleName}-${version}.tar.gz`;\n}\n\n/**\n * Formats download metadata for human-readable CLI output.\n *\n * @param body - Version metadata from the Policy Engine API\n * @param outputPath - Destination path written (or that would be written)\n * @returns Summary lines\n */\nfunction formatDownloadSummary(body: GetPolicyBundleVersionResponse, outputPath: string): string {\n return [\n `bundleName ${body.bundleName}`,\n `version ${body.version}`,\n `output ${outputPath}`,\n `sha256 ${body.sha256}`,\n `sizeBytes ${body.sizeBytes}`,\n `uploadedAt ${body.uploadedAt}`,\n `activatedAt ${body.activatedAt ?? EMPTY_CELL}`,\n ].join('\\n');\n}\n\n/**\n * Download a compiled policy bundle version to disk.\n *\n * Resolves `--bundle-name` and an optional `--version` to IDs, fetches a\n * short-lived presigned S3 URL from the monolith, then downloads the `.tar.gz`\n * bytes directly from S3 (the monolith does not proxy the artifact).\n *\n * When `--version` is omitted, downloads the bundle's currently active version.\n * If the bundle has no active version, exits with an error.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function download(\n this: LocalContext,\n {\n 'bundle-name': bundleName,\n version,\n output,\n auth,\n 'transcend-url': transcendUrl,\n json,\n debug = false,\n }: DownloadCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n setPolicyEngineCliDebug(debug);\n\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n const bundle = await resolveBundleByName(client, bundleName);\n if (!bundle) {\n throw new Error(`Policy bundle \"${bundleName}\" was not found for this organization.`);\n }\n\n let versionId: string;\n if (version) {\n const resolvedVersion = await resolvePolicyBundleVersion(client, bundle.id, { version });\n versionId = resolvedVersion.id;\n } else {\n if (!bundle.activeVersionId) {\n throw new Error(`Policy bundle \"${bundleName}\" has no active version.`);\n }\n versionId = bundle.activeVersionId;\n }\n\n logger.info(\n colors.green(\n version\n ? `Fetching download URL for bundle \"${bundleName}\" version \"${version}\"...`\n : `Fetching download URL for active version of bundle \"${bundleName}\"...`,\n ),\n );\n\n const body = await policyEngineRequest(\n client\n .get(`v1/policy-engine/policy-bundles/${bundle.id}/versions/${versionId}`)\n .json<GetPolicyBundleVersionResponse>(),\n );\n\n if (json) {\n printResult(this.process.stdout, {\n json: true,\n data: body,\n });\n return;\n }\n\n const outputPath = path.resolve(\n output ?? defaultPolicyDownloadOutputPath(bundleName, body.version),\n );\n\n logger.info(colors.green(`Downloading policy bundle to ${outputPath}...`));\n\n let bundleBytes: Uint8Array;\n try {\n bundleBytes = await got(body.downloadUrl).buffer();\n } catch (err) {\n throw new Error(\n `Failed to download policy bundle from the presigned URL: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n\n const outputDir = path.dirname(outputPath);\n fs.mkdirSync(outputDir, { recursive: true });\n fs.writeFileSync(outputPath, bundleBytes);\n\n printResult(this.process.stdout, {\n json: false,\n data: body,\n renderTable: () => formatDownloadSummary(body, outputPath),\n });\n\n logger.info(colors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AQ,OAC3C,EAAK,CACZ,MAAU,MACR,4DACE,aAAe,MAAQ,EAAI,QAAU,OAAO,EAAI,GAElD,CAAE,MAAO,EAAK,CACf,CAGH,IAAM,EAAY,EAAK,QAAQ,EAAW,CAC1C,EAAG,UAAU,EAAW,CAAE,UAAW,GAAM,CAAC,CAC5C,EAAG,cAAc,EAAY,EAAY,CAEzC,EAAY,KAAK,QAAQ,OAAQ,CAC/B,KAAM,GACN,KAAM,EACN,gBAAmB,EAAsB,EAAM,EAAW,CAC3D,CAAC,CAEF,EAAO,KAAK,EAAO,MAAM,yCAAyC,CAAC"}
1
+ {"version":3,"file":"impl-CZG9gzzR.mjs","names":[],"sources":["../src/commands/policy/download/impl.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport colors from 'colors';\nimport got from 'got';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { logger } from '../../../logger.js';\nimport { EMPTY_CELL } from '../constants.js';\nimport {\n buildPolicyEngineClient,\n policyEngineRequest,\n printResult,\n resolveBundleByName,\n resolvePolicyBundleVersion,\n setPolicyEngineCliDebug,\n} from '../helpers/index.js';\nimport type { GetPolicyBundleVersionResponse } from '../types.js';\n\n/** CLI flags for `transcend policy download`. */\nexport interface DownloadCommandFlags {\n /** Tenant-unique bundle name */\n 'bundle-name': string;\n /**\n * Caller-supplied version label to download.\n * When omitted, downloads the bundle's currently active version.\n */\n version?: string;\n /** Destination file path; defaults to `{bundleName}-{version}.tar.gz` */\n output?: string;\n /** Transcend API key */\n auth: string;\n /** Transcend API URL */\n 'transcend-url': string;\n /** Print metadata + presigned URL as JSON without writing a file */\n json: boolean;\n /** Include technical error details when a command fails */\n debug?: boolean;\n}\n\n/**\n * Builds the default output path for a downloaded policy bundle.\n *\n * @param bundleName - Tenant-unique bundle name\n * @param version - Caller-supplied version label\n * @returns Relative path `{bundleName}-{version}.tar.gz`\n */\nexport function defaultPolicyDownloadOutputPath(bundleName: string, version: string): string {\n return `${bundleName}-${version}.tar.gz`;\n}\n\n/**\n * Formats download metadata for human-readable CLI output.\n *\n * @param body - Version metadata from the Policy Engine API\n * @param outputPath - Destination path written (or that would be written)\n * @returns Summary lines\n */\nfunction formatDownloadSummary(body: GetPolicyBundleVersionResponse, outputPath: string): string {\n return [\n `bundleName ${body.bundleName}`,\n `version ${body.version}`,\n `output ${outputPath}`,\n `sha256 ${body.sha256}`,\n `sizeBytes ${body.sizeBytes}`,\n `uploadedAt ${body.uploadedAt}`,\n `activatedAt ${body.activatedAt ?? EMPTY_CELL}`,\n ].join('\\n');\n}\n\n/**\n * Download a compiled policy bundle version to disk.\n *\n * Resolves `--bundle-name` and an optional `--version` to IDs, fetches a\n * short-lived presigned S3 URL from the monolith, then downloads the `.tar.gz`\n * bytes directly from S3 (the monolith does not proxy the artifact).\n *\n * When `--version` is omitted, downloads the bundle's currently active version.\n * If the bundle has no active version, exits with an error.\n *\n * @param this - CLI context\n * @param flags - Command flags\n */\nexport async function download(\n this: LocalContext,\n {\n 'bundle-name': bundleName,\n version,\n output,\n auth,\n 'transcend-url': transcendUrl,\n json,\n debug = false,\n }: DownloadCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n setPolicyEngineCliDebug(debug);\n\n const client = buildPolicyEngineClient(transcendUrl, auth);\n\n const bundle = await resolveBundleByName(client, bundleName);\n if (!bundle) {\n throw new Error(`Policy bundle \"${bundleName}\" was not found for this organization.`);\n }\n\n let versionId: string;\n if (version) {\n const resolvedVersion = await resolvePolicyBundleVersion(client, bundle.id, { version });\n versionId = resolvedVersion.id;\n } else {\n if (!bundle.activeVersionId) {\n throw new Error(`Policy bundle \"${bundleName}\" has no active version.`);\n }\n versionId = bundle.activeVersionId;\n }\n\n logger.info(\n colors.green(\n version\n ? `Fetching download URL for bundle \"${bundleName}\" version \"${version}\"...`\n : `Fetching download URL for active version of bundle \"${bundleName}\"...`,\n ),\n );\n\n const body = await policyEngineRequest(\n client\n .get(`v1/policy-engine/policy-bundles/${bundle.id}/versions/${versionId}`)\n .json<GetPolicyBundleVersionResponse>(),\n );\n\n if (json) {\n printResult(this.process.stdout, {\n json: true,\n data: body,\n });\n return;\n }\n\n const outputPath = path.resolve(\n output ?? defaultPolicyDownloadOutputPath(bundleName, body.version),\n );\n\n logger.info(colors.green(`Downloading policy bundle to ${outputPath}...`));\n\n let bundleBytes: Uint8Array;\n try {\n bundleBytes = await got(body.downloadUrl).buffer();\n } catch (err) {\n throw new Error(\n `Failed to download policy bundle from the presigned URL: ${\n err instanceof Error ? err.message : String(err)\n }`,\n { cause: err },\n );\n }\n\n const outputDir = path.dirname(outputPath);\n fs.mkdirSync(outputDir, { recursive: true });\n fs.writeFileSync(outputPath, bundleBytes);\n\n printResult(this.process.stdout, {\n json: false,\n data: body,\n renderTable: () => formatDownloadSummary(body, outputPath),\n });\n\n logger.info(colors.green('Policy bundle downloaded successfully.'));\n}\n"],"mappings":"maAgDA,SAAgB,EAAgC,EAAoB,EAAyB,CAC3F,MAAO,GAAG,EAAW,GAAG,EAAQ,SAUlC,SAAS,EAAsB,EAAsC,EAA4B,CAC/F,MAAO,CACL,eAAe,EAAK,aACpB,eAAe,EAAK,UACpB,eAAe,IACf,eAAe,EAAK,SACpB,eAAe,EAAK,YACpB,eAAe,EAAK,aACpB,eAAe,EAAK,aAAA,MACrB,CAAC,KAAK;EAAK,CAgBd,eAAsB,EAEpB,CACE,cAAe,EACf,UACA,SACA,OACA,gBAAiB,EACjB,OACA,QAAQ,IAEK,CACf,EAAoB,KAAK,QAAQ,KAAK,CACtC,EAAwB,EAAM,CAE9B,IAAM,EAAS,EAAwB,EAAc,EAAK,CAEpD,EAAS,MAAM,EAAoB,EAAQ,EAAW,CAC5D,GAAI,CAAC,EACH,MAAU,MAAM,kBAAkB,EAAW,wCAAwC,CAGvF,IAAI,EACJ,GAAI,EAEF,GAAY,MADkB,EAA2B,EAAQ,EAAO,GAAI,CAAE,UAAS,CAAC,EAC5D,OACvB,CACL,GAAI,CAAC,EAAO,gBACV,MAAU,MAAM,kBAAkB,EAAW,0BAA0B,CAEzE,EAAY,EAAO,gBAGrB,EAAO,KACL,EAAO,MACL,EACI,qCAAqC,EAAW,aAAa,EAAQ,MACrE,uDAAuD,EAAW,MACvE,CACF,CAED,IAAM,EAAO,MAAM,EACjB,EACG,IAAI,mCAAmC,EAAO,GAAG,YAAY,IAAY,CACzE,MAAsC,CAC1C,CAED,GAAI,EAAM,CACR,EAAY,KAAK,QAAQ,OAAQ,CAC/B,KAAM,GACN,KAAM,EACP,CAAC,CACF,OAGF,IAAM,EAAa,EAAK,QACtB,GAAU,EAAgC,EAAY,EAAK,QAAQ,CACpE,CAED,EAAO,KAAK,EAAO,MAAM,gCAAgC,EAAW,KAAK,CAAC,CAE1E,IAAI,EACJ,GAAI,CACF,EAAc,MAAM,EAAI,EAAK,YAAY,CAAC,QAAQ,OAC3C,EAAK,CACZ,MAAU,MACR,4DACE,aAAe,MAAQ,EAAI,QAAU,OAAO,EAAI,GAElD,CAAE,MAAO,EAAK,CACf,CAGH,IAAM,EAAY,EAAK,QAAQ,EAAW,CAC1C,EAAG,UAAU,EAAW,CAAE,UAAW,GAAM,CAAC,CAC5C,EAAG,cAAc,EAAY,EAAY,CAEzC,EAAY,KAAK,QAAQ,OAAQ,CAC/B,KAAM,GACN,KAAM,EACN,gBAAmB,EAAsB,EAAM,EAAW,CAC3D,CAAC,CAEF,EAAO,KAAK,EAAO,MAAM,yCAAyC,CAAC"}
@@ -1,4 +1,4 @@
1
- import"./enums-OiLcZ26O.mjs";import{t as e}from"./logger-Ckep4QXn.mjs";import{t}from"./done-input-validation-uqIgnJcw.mjs";import{OneTrustEnrichedAssessment as n,OneTrustGetAssessmentResponse as r,OneTrustGetListOfAssessmentsResponse as i,OneTrustGetRiskResponse as a,OneTrustGetUserResponse as o}from"@transcend-io/privacy-types";import{keyBy as s,uniq as c}from"lodash-es";import l,{createReadStream as u}from"node:fs";import d from"got";import f from"colors";import{decodeCodec as p}from"@transcend-io/type-utils";import{IMPORT_ONE_TRUST_ASSESSMENT_FORMS as m,buildTranscendGraphQLClient as h,makeGraphQLRequest as g}from"@transcend-io/sdk";import{map as _,mapSeries as v}from"@transcend-io/utils";import y from"JSONStream";const b=({assessment:e,index:t,total:n,wrap:r=!0})=>{let i=``;(t===0||r)&&(i=`[
1
+ import"./enums-OiLcZ26O.mjs";import{t as e}from"./logger-Ckep4QXn.mjs";import{t}from"./done-input-validation-DL31vk7g.mjs";import{OneTrustEnrichedAssessment as n,OneTrustGetAssessmentResponse as r,OneTrustGetListOfAssessmentsResponse as i,OneTrustGetRiskResponse as a,OneTrustGetUserResponse as o}from"@transcend-io/privacy-types";import{keyBy as s,uniq as c}from"lodash-es";import l,{createReadStream as u}from"node:fs";import d from"got";import f from"colors";import{decodeCodec as p}from"@transcend-io/type-utils";import{IMPORT_ONE_TRUST_ASSESSMENT_FORMS as m,buildTranscendGraphQLClient as h,makeGraphQLRequest as g}from"@transcend-io/sdk";import{map as _,mapSeries as v}from"@transcend-io/utils";import y from"JSONStream";const b=({assessment:e,index:t,total:n,wrap:r=!0})=>{let i=``;(t===0||r)&&(i=`[
2
2
  `);let a=JSON.stringify(e),o=n&&t<n-1&&!r?`,`:``;return i=`${i+a+o}\n`,(n&&t===n-1||r)&&(i+=`
3
3
  ]`),i},x=({file:t,assessment:n,index:r,total:i})=>{e.info(f.magenta(`Writing enriched assessment ${r+1} of ${i} to file "${t}"...`)),r===0?l.writeFileSync(t,b({assessment:n,index:r,total:i,wrap:!1})):l.appendFileSync(t,b({assessment:n,index:r,total:i,wrap:!1}))},S=async({oneTrust:t})=>{let n=0,r=1,a=0,o=[];for(;n<r;){let{body:s}=await t.get(`api/assessment/v2/assessments?page=${n}&size=2000`),{page:c,content:l}=p(i,s);o.push(...l??[]),n===0&&(r=c?.totalPages??0,a=c?.totalElements??0),n+=1,e.info(`Fetched ${o.length} of ${a} assessments.`)}return o},C=async({oneTrust:e,assessmentId:t})=>{let{body:n}=await e.get(`api/assessment/v2/assessments/${t}/export?ExcludeSkippedQuestions=false`);return p(r,n)},w=async({oneTrust:e,riskId:t})=>{let{body:n}=await e.get(`api/risk/v2/risks/${t}`);return p(a,n)},T=async({oneTrust:e,userId:t})=>{let{body:n}=await e.get(`api/scim/v2/Users/${t}`);return p(o,n)},E=({assessment:e,assessmentDetails:t,riskDetails:n,creatorDetails:r,approversDetails:i,respondentsDetails:a})=>{let o=s(n,`id`),{sections:c,createdBy:l,...u}=t,d=c.map(e=>{let{questions:t,...n}=e,r=t.map(e=>{let{risks:t,...n}=e,r=(t??[]).map(e=>{let t=o[e.riskId];return{...e,...t,level:e.level,impactLevel:e.impactLevel??0}});return{...n,risks:r}});return{...n,questions:r}}),f={...l,active:r?.active??!1,userType:r?.userType??`Internal`,emails:r?.emails??[],title:r?.title??null,givenName:r?.name.givenName??null,familyName:r?.name.familyName??null},p=s(i,`id`),m=t.approvers.flatMap(e=>p[e.id]?[{...e,approver:{...e.approver,active:p[e.id].active,userType:p[e.id].userType,emails:p[e.id].emails,title:p[e.id].title,givenName:p[e.id].name.givenName??null,familyName:p[e.id].name.familyName??null}}]:[]),h=s(a,`id`),g=t.respondents.filter(e=>!e.name.includes(`@`)).flatMap(e=>h[e.id]?[{...e,active:h[e.id].active,userType:h[e.id].userType,emails:h[e.id].emails,title:h[e.id].title,givenName:h[e.id].name.givenName??null,familyName:h[e.id].name.familyName??null}]:[]);return{...e,...u,approvers:m,respondents:g,createdBy:f,sections:d}},D=async({transcend:t,assessment:n,total:r,index:i})=>{e.info(f.magenta(`Writing enriched assessment ${i+1} ${r?`of ${r} `:` `}to Transcend...`));let a={json:b({assessment:n,index:i,total:r})};try{await g(t,m,{variables:{input:a},logger:e})}catch(t){e.error(f.red(`Failed to sync assessment ${i+1} ${r?`of ${r} `:` `}to Transcend.\n\tAssessment Title: ${n.name}. Template Title: ${n.template.name}\n`),t)}},O=async({oneTrust:t,file:n,dryRun:r,transcend:i})=>{e.info(`Getting list of all assessments from OneTrust...`);let a=await S({oneTrust:t}),o={};await v(Array.from({length:Math.ceil(a.length/5)},(e,t)=>a.slice(t*5,(t+1)*5)),async(s,l)=>{let u=[];await _(s,async(n,r)=>{let i=5*l+r+1;e.info(`[assessment ${i} of ${a.length}]: fetching details...`);let{templateName:s,assessmentId:d}=n,p=await C({oneTrust:t,assessmentId:d}),m=p.createdBy.id,h=o[m];if(!h){e.info(`[assessment ${i} of ${a.length}]: fetching creator...`);try{h=await T({oneTrust:t,userId:m}),o[m]=h}catch(t){e.warn(f.yellow(`[assessment ${i} of ${a.length}]: failed to fetch form creator.\tcreatorId: ${m}. Assessment Title: ${n.name}. Template Title: ${s}`),t)}}let{approvers:g}=p,v=[];g.length>0&&(e.info(`[assessment ${i} of ${a.length}]: fetching approvers...`),v=await _(g.map(({id:e})=>e),async r=>{try{let e=o[r];return e||(e=await T({oneTrust:t,userId:r}),o[r]=e),[e]}catch(t){return e.warn(f.yellow(`[assessment ${i} of ${a.length}]: failed to fetch a form approver.\tapproverId: ${r}. Assessment Title: ${n.name}. Template Title: ${s}`),t),[]}},{concurrency:5}));let{respondents:y}=p,b=y.filter(e=>!e.name.includes(`@`)),x=[];b.length>0&&(e.info(`[assessment ${i} of ${a.length}]: fetching respondents...`),x=await _(b.map(({id:e})=>e),async r=>{try{let e=o[r];return e||(e=await T({oneTrust:t,userId:r}),o[r]=e),[e]}catch(t){return e.warn(f.yellow(`[assessment ${i} of ${a.length}]: failed to fetch a respondent.\trespondentId: ${r}. Assessment Title: ${n.name}. Template Title: ${s}`),t),[]}},{concurrency:5}));let S=[],D=c(p.sections.flatMap(e=>e.questions.flatMap(e=>(e.risks??[]).flatMap(e=>e.riskId))));D.length>0&&(e.info(`[assessment ${i} of ${a.length}]: fetching risks...`),S=await _(D,e=>w({oneTrust:t,riskId:e}),{concurrency:5}));let O=E({assessment:n,assessmentDetails:p,riskDetails:S,creatorDetails:h,approversDetails:v.flat(),respondentsDetails:x.flat()});u.push(O)},{concurrency:5}),await v(u,async(e,t)=>{let o=l*5+t;r&&n?x({assessment:e,index:o,total:a.length,file:n}):i&&await D({assessment:e,transcend:i,total:a.length,index:o})})})},k=({transcend:t,file:r})=>(e.info(`Getting list of all assessments from file ${r}...`),new Promise((i,a)=>{let o=u(r,{encoding:`utf-8`,highWaterMark:64*1024}),s=y.parse(`*`),c=0;o.pipe(s),s.on(`data`,async i=>{try{s.pause(),await D({assessment:p(n,i),transcend:t,index:c}),c+=1,s.resume()}catch(t){e.error(f.red(`Failed to parse the assessment ${c} from file '${r}': ${t.message}.`))}}),s.on(`end`,()=>{e.info(`Finished processing ${c} assessments from file ${r}`),i()}),s.on(`error`,t=>{e.error(f.red(`Error parsing file '${r}': ${t.message}`)),a(t)}),o.on(`error`,t=>{e.error(f.red(`Error reading file '${r}': ${t.message}`)),a(t)})})),A=({hostname:e,auth:t})=>d.extend({prefixUrl:`https://${e}`,headers:{accept:`application/json`,"content-type":`application/json`,authorization:`Bearer ${t}`}});async function j({hostname:n,oneTrustAuth:r,source:i,transcendAuth:a,transcendUrl:o,resource:s,file:c,dryRun:l,debug:u}){if(!l&&!a)throw Error('Must specify a "transcendAuth" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}');if(l&&!c)throw Error(`Must set a "file" parameter when "dryRun" is "true". e.g. --file=./oneTrustAssessments.json`);if(c){let e=c.split(`.`);if(e.length<2)throw Error(`The "file" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.`);if(e.at(-1)!==`json`)throw Error(`Expected the format of the "file" parameters '${c}' to be 'json', but got '${e.at(-1)}'.`)}if(i===`oneTrust`){if(!n)throw Error(`Missing required parameter "hostname". e.g. --hostname=customer.my.onetrust.com`);if(!r)throw Error(`Missing required parameter "oneTrustAuth". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN`)}else{if(!c)throw Error(`Must specify a "file" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json`);if(l)throw Error(`Cannot read and write to a file simultaneously. Emit the "source" parameter or set it to oneTrust if "dryRun" is enabled.`)}t(this.process.exit);let d=n&&r?A({hostname:n,auth:r}):void 0,p=o&&a?h(o,a):void 0;try{s===`assessments`&&(i===`oneTrust`&&d?await O({oneTrust:d,file:c,dryRun:l,...p&&{transcend:p}}):i===`file`&&c&&p&&await k({file:c,transcend:p}))}catch(e){throw Error(`An error occurred syncing the resource ${s} from OneTrust: ${u?e.stack:e.message}`)}e.info(f.green(`Successfully synced OneTrust ${s} to ${l?`disk at "${c}"`:`Transcend`}!`))}export{j as syncOt};
4
- //# sourceMappingURL=impl-CiaTPxwK.mjs.map
4
+ //# sourceMappingURL=impl-Ca064LmU.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-CiaTPxwK.mjs","names":[],"sources":["../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToDisk.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/endpoints/getOneTrustAssessment.ts","../src/lib/oneTrust/endpoints/getOneTrustRisk.ts","../src/lib/oneTrust/endpoints/getOneTrustUser.ts","../src/lib/oneTrust/helpers/enrichOneTrustAssessment.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromFile.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/commands/migration/sync-ot/impl.ts"],"sourcesContent":["import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Converts the assessment into a json entry.\n *\n * @param param - information about the assessment and amount of entries\n * @returns a stringified json entry ready to be appended to a file\n */\nexport const oneTrustAssessmentToJson = ({\n assessment,\n index,\n total,\n wrap = true,\n}: {\n /** The assessment to convert */\n assessment: OneTrustEnrichedAssessment;\n /** The position of the assessment in the final Json object */\n index: number;\n /** The total amount of the assessments in the final Json object */\n total?: number;\n /** Whether to wrap every entry in brackets */\n wrap?: boolean;\n}): string => {\n let jsonEntry = '';\n // start with an opening bracket\n if (index === 0 || wrap) {\n jsonEntry = '[\\n';\n }\n\n const stringifiedAssessment = JSON.stringify(assessment);\n\n // Add comma for all items except the last one\n const comma = total && index < total - 1 && !wrap ? ',' : '';\n\n // write to file\n jsonEntry = `${jsonEntry + stringifiedAssessment + comma}\\n`;\n\n // end with closing bracket\n if ((total && index === total - 1) || wrap) {\n jsonEntry += '\\n]';\n }\n\n return jsonEntry;\n};\n","import fs from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\n/**\n * Write the assessment to disk at the specified file path.\n *\n *\n * @param param - information about the assessment to write\n */\nexport const syncOneTrustAssessmentToDisk = ({\n file,\n assessment,\n index,\n total,\n}: {\n /** The file path to write the assessment to */\n file: string;\n /** The basic assessment */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total: number;\n}): void => {\n logger.info(\n colors.magenta(`Writing enriched assessment ${index + 1} of ${total} to file \"${file}\"...`),\n );\n\n if (index === 0) {\n fs.writeFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n } else {\n fs.appendFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n }\n};\n","import {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\nimport { logger } from '../../../logger.js';\n\n/**\n * Fetch a list of all assessments from the OneTrust client.\n * ref: https://developer.onetrust.com/onetrust/reference/getallassessmentbasicdetailsusingget\n *\n * @param param - the information about the OneTrust client\n * @returns a list of OneTrustAssessment\n */\nexport const getListOfOneTrustAssessments = async ({\n oneTrust,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n}): Promise<OneTrustAssessment[]> => {\n let currentPage = 0;\n let totalPages = 1;\n let totalElements = 0;\n\n const allAssessments: OneTrustAssessment[] = [];\n\n while (currentPage < totalPages) {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments?page=${currentPage}&size=2000`,\n );\n\n const { page, content } = decodeCodec(OneTrustGetListOfAssessmentsResponse, body);\n allAssessments.push(...(content ?? []));\n if (currentPage === 0) {\n totalPages = page?.totalPages ?? 0;\n totalElements = page?.totalElements ?? 0;\n }\n currentPage += 1;\n\n // log progress\n logger.info(`Fetched ${allAssessments.length} of ${totalElements} assessments.`);\n }\n\n return allAssessments;\n};\n","import { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular assessment.\n * ref: https://developer.onetrust.com/onetrust/reference/exportassessmentusingget\n *\n * @param param - the information about the OneTrust client and assessment to retrieve\n * @returns details about the assessment\n */\nexport const getOneTrustAssessment = async ({\n oneTrust,\n assessmentId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the assessment to retrieve */\n assessmentId: string;\n}): Promise<OneTrustGetAssessmentResponse> => {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments/${assessmentId}/export?ExcludeSkippedQuestions=false`,\n );\n\n return decodeCodec(OneTrustGetAssessmentResponse, body);\n};\n","import { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular risk.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustRisk = async ({\n oneTrust,\n riskId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust risk to retrieve */\n riskId: string;\n}): Promise<OneTrustGetRiskResponse> => {\n const { body } = await oneTrust.get(`api/risk/v2/risks/${riskId}`);\n\n return decodeCodec(OneTrustGetRiskResponse, body);\n};\n","import { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular user.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustUser = async ({\n oneTrust,\n userId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust user to retrieve */\n userId: string;\n}): Promise<OneTrustGetUserResponse> => {\n const { body } = await oneTrust.get(`api/scim/v2/Users/${userId}`);\n\n return decodeCodec(OneTrustGetUserResponse, body);\n};\n","import {\n OneTrustAssessment,\n OneTrustEnrichedAssessment,\n OneTrustGetAssessmentResponse,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { keyBy } from 'lodash-es';\n\n/**\n * Merge the assessment, assessmentDetails, and riskDetails into one object.\n *\n * @param param - the assessment and risk information\n * @returns the assessment enriched with details and risk information\n */\nexport const enrichOneTrustAssessment = ({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails,\n approversDetails,\n respondentsDetails,\n}: {\n /** The OneTrust risk details */\n riskDetails: OneTrustGetRiskResponse[];\n /** The OneTrust assessment as returned from Get List of Assessments endpoint */\n assessment: OneTrustAssessment;\n /** The OneTrust assessment details */\n assessmentDetails: OneTrustGetAssessmentResponse;\n /** The OneTrust assessment creator details */\n creatorDetails: OneTrustGetUserResponse;\n /** The OneTrust assessment approvers details */\n approversDetails: OneTrustGetUserResponse[];\n /** The OneTrust assessment internal respondents details */\n respondentsDetails: OneTrustGetUserResponse[];\n}): OneTrustEnrichedAssessment => {\n const riskDetailsById = keyBy(riskDetails, 'id');\n const { sections, createdBy, ...restAssessmentDetails } = assessmentDetails;\n const sectionsWithEnrichedRisk = sections.map((section) => {\n const { questions, ...restSection } = section;\n const enrichedQuestions = questions.map((question) => {\n const { risks, ...restQuestion } = question;\n const enrichedRisks = (risks ?? []).map((risk) => {\n const details = riskDetailsById[risk.riskId];\n return {\n ...risk,\n ...details,\n level: risk.level,\n impactLevel: risk.impactLevel ?? 0,\n };\n });\n return {\n ...restQuestion,\n risks: enrichedRisks,\n };\n });\n return {\n ...restSection,\n questions: enrichedQuestions,\n };\n });\n\n // grab creator details\n const enrichedCreatedBy = {\n ...createdBy,\n active: creatorDetails?.active ?? false,\n userType: creatorDetails?.userType ?? 'Internal',\n emails: creatorDetails?.emails ?? [],\n title: creatorDetails?.title ?? null,\n givenName: creatorDetails?.name.givenName ?? null,\n familyName: creatorDetails?.name.familyName ?? null,\n };\n\n // grab approvers details\n const approverDetailsById = keyBy(approversDetails, 'id');\n const enrichedApprovers = assessmentDetails.approvers.flatMap((originalApprover) =>\n approverDetailsById[originalApprover.id]\n ? [\n {\n ...originalApprover,\n approver: {\n ...originalApprover.approver,\n active: approverDetailsById[originalApprover.id].active,\n userType: approverDetailsById[originalApprover.id].userType,\n emails: approverDetailsById[originalApprover.id].emails,\n title: approverDetailsById[originalApprover.id].title,\n givenName: approverDetailsById[originalApprover.id].name.givenName ?? null,\n familyName: approverDetailsById[originalApprover.id].name.familyName ?? null,\n },\n },\n ]\n : [],\n );\n\n // grab respondents details\n const respondentsDetailsById = keyBy(respondentsDetails, 'id');\n const enrichedRespondents = assessmentDetails.respondents\n .filter((r) => !r.name.includes('@')) // search only internal respondents\n .flatMap((respondent) =>\n respondentsDetailsById[respondent.id]\n ? [\n {\n ...respondent,\n active: respondentsDetailsById[respondent.id].active,\n userType: respondentsDetailsById[respondent.id].userType,\n emails: respondentsDetailsById[respondent.id].emails,\n title: respondentsDetailsById[respondent.id].title,\n givenName: respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName: respondentsDetailsById[respondent.id].name.familyName ?? null,\n },\n ]\n : [],\n );\n\n // combine everything into a single enriched assessment\n return {\n ...assessment,\n ...restAssessmentDetails,\n approvers: enrichedApprovers,\n respondents: enrichedRespondents,\n createdBy: enrichedCreatedBy,\n sections: sectionsWithEnrichedRisk,\n };\n};\n","import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { makeGraphQLRequest, IMPORT_ONE_TRUST_ASSESSMENT_FORMS } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\n\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs.js';\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Write the assessment to a Transcend instance.\n *\n *\n * @param param - information about the assessment and Transcend instance to write to\n */\nexport const syncOneTrustAssessmentToTranscend = async ({\n transcend,\n assessment,\n total,\n index,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** the assessment to sync to Transcend */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total?: number;\n}): Promise<void> => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend...`,\n ),\n );\n\n // convert the OneTrust assessment object into a json record\n const json = oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n });\n\n // transform the json record into a valid input to the mutation\n const input: ImportOnetrustAssessmentsInput = {\n json,\n };\n\n try {\n await makeGraphQLRequest<{\n /** the importOneTrustAssessmentForms mutation */\n importOneTrustAssessmentForms: {\n /** Created Assessment Forms */\n assessmentForms: AssessmentForm[];\n };\n }>(transcend, IMPORT_ONE_TRUST_ASSESSMENT_FORMS, {\n variables: { input },\n logger,\n });\n } catch (error) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n error,\n );\n }\n};\n","import {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { mapSeries, map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { GraphQLClient } from 'graphql-request';\nimport { uniq } from 'lodash-es';\n\nimport { logger } from '../../../logger.js';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints/index.js';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment.js';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Reads all the assessments from a OneTrust instance and syncs them to Transcend or to Disk.\n *\n * @param param - the information about the assessment, its OneTrust source, and destination (disk or Transcend)\n */\nexport const syncOneTrustAssessmentsFromOneTrust = async ({\n oneTrust,\n file,\n dryRun,\n transcend,\n}: {\n /** the OneTrust client instance */\n oneTrust: Got;\n /** the Transcend client instance */\n transcend?: GraphQLClient;\n /** Whether to write to file instead of syncing to Transcend */\n dryRun: boolean;\n /** the path to the file in case dryRun is true */\n file?: string;\n}): Promise<void> => {\n // fetch the list of all assessments in the OneTrust organization\n logger.info('Getting list of all assessments from OneTrust...');\n const assessments = await getListOfOneTrustAssessments({ oneTrust });\n\n // a cache of OneTrust users so we avoid requesting already fetched users\n const oneTrustCachedUsers: Record<string, OneTrustGetUserResponse> = {};\n\n // split all assessments in batches, so we can process some of steps in parallel\n const BATCH_SIZE = 5;\n const assessmentBatches = Array.from(\n {\n length: Math.ceil(assessments.length / BATCH_SIZE),\n },\n (_, i) => assessments.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),\n );\n\n // process each batch and sync the batch right away so it's garbage collected and we don't run out of memory\n await mapSeries(assessmentBatches, async (assessmentBatch, batch) => {\n const batchEnrichedAssessments: OneTrustEnrichedAssessment[] = [];\n\n // fetch assessment details from OneTrust in parallel\n await map(\n assessmentBatch,\n async (assessment, index) => {\n const assessmentNumber = BATCH_SIZE * batch + index + 1;\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching details...`,\n );\n const { templateName, assessmentId } = assessment;\n const assessmentDetails = await getOneTrustAssessment({\n oneTrust,\n assessmentId,\n });\n // fetch assessment's creator information\n const creatorId = assessmentDetails.createdBy.id;\n let creator = oneTrustCachedUsers[creatorId];\n if (!creator) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching creator...`,\n );\n try {\n creator = await getOneTrustUser({\n oneTrust,\n userId: creatorId,\n });\n oneTrustCachedUsers[creatorId] = creator;\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch form creator.` +\n `\\tcreatorId: ${creatorId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n }\n }\n\n // fetch assessment approvers information\n const { approvers } = assessmentDetails;\n let approversDetails: OneTrustGetUserResponse[][] = [];\n if (approvers.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching approvers...`,\n );\n approversDetails = await map(\n approvers.map(({ id }) => id),\n async (userId) => {\n try {\n let approver = oneTrustCachedUsers[userId];\n if (!approver) {\n approver = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = approver;\n }\n return [approver];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a form approver.` +\n `\\tapproverId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment internal respondents information\n const { respondents } = assessmentDetails;\n // if a user is an internal respondents, their 'name' field can't be an email.\n const internalRespondents = respondents.filter((r) => !r.name.includes('@'));\n let respondentsDetails: OneTrustGetUserResponse[][] = [];\n if (internalRespondents.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching respondents...`,\n );\n respondentsDetails = await map(\n internalRespondents.map(({ id }) => id),\n async (userId) => {\n try {\n let respondent = oneTrustCachedUsers[userId];\n if (!respondent) {\n respondent = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = respondent;\n }\n return [respondent];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a respondent.` +\n `\\trespondentId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment risk information\n let riskDetails: OneTrustGetRiskResponse[] = [];\n const riskIds = uniq(\n assessmentDetails.sections.flatMap((s: OneTrustAssessmentSection) =>\n s.questions.flatMap((q: OneTrustAssessmentQuestion) =>\n (q.risks ?? []).flatMap((r) => r.riskId),\n ),\n ),\n );\n if (riskIds.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching risks...`,\n );\n riskDetails = await map(\n riskIds,\n (riskId) => getOneTrustRisk({ oneTrust, riskId: riskId as string }),\n {\n concurrency: 5,\n },\n );\n }\n\n // enrich the assessments with user and risk details\n const enrichedAssessment = enrichOneTrustAssessment({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails: creator,\n approversDetails: approversDetails.flat(),\n respondentsDetails: respondentsDetails.flat(),\n });\n\n batchEnrichedAssessments.push(enrichedAssessment);\n },\n { concurrency: BATCH_SIZE },\n );\n\n // sync assessments in series to avoid concurrency bugs\n await mapSeries(batchEnrichedAssessments, async (enrichedAssessment, index) => {\n // the assessment's global index takes its batch into consideration\n const globalIndex = batch * BATCH_SIZE + index;\n\n if (dryRun && file) {\n // sync to file\n syncOneTrustAssessmentToDisk({\n assessment: enrichedAssessment,\n index: globalIndex,\n total: assessments.length,\n file,\n });\n } else if (transcend) {\n // sync to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: enrichedAssessment,\n transcend,\n total: assessments.length,\n index: globalIndex,\n });\n }\n });\n });\n};\n","import { createReadStream } from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport JSONStream from 'JSONStream';\n\nimport { logger } from '../../../logger.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\n/**\n * Reads assessments from a file and syncs them to Transcend.\n *\n * @param param - the information about the source file and Transcend instance to write them to.\n */\nexport const syncOneTrustAssessmentsFromFile = ({\n transcend,\n file,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** The name of the file from which to read the OneTrust assessments */\n file: string;\n}): Promise<void> => {\n logger.info(`Getting list of all assessments from file ${file}...`);\n\n return new Promise((resolve, reject) => {\n // Create a readable stream from the file\n const fileStream = createReadStream(file, {\n encoding: 'utf-8',\n highWaterMark: 64 * 1024, // 64KB chunks\n });\n\n // Create a JSONStream parser to parse the array of OneTrust assessments from the file\n const parser = JSONStream.parse('*'); // '*' matches each element in the root array\n\n let index = 0;\n\n // Pipe the file stream into the JSON parser\n fileStream.pipe(parser);\n\n // Handle each parsed assessment object\n parser.on('data', async (assessment) => {\n try {\n // Pause the stream while processing to avoid overwhelming memory\n parser.pause();\n\n // Decode and validate the assessment\n const parsedAssessment = decodeCodec(OneTrustEnrichedAssessment, assessment);\n\n // Sync the assessment to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: parsedAssessment,\n transcend,\n index,\n });\n\n index += 1;\n\n // Resume the stream after processing\n parser.resume();\n } catch (e) {\n // if failed to parse a line, report error and continue\n logger.error(\n colors.red(`Failed to parse the assessment ${index} from file '${file}': ${e.message}.`),\n );\n }\n });\n\n // Handle completion\n parser.on('end', () => {\n logger.info(`Finished processing ${index} assessments from file ${file}`);\n resolve();\n });\n\n // Handle stream or parsing errors\n parser.on('error', (error) => {\n logger.error(colors.red(`Error parsing file '${file}': ${error.message}`));\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(colors.red(`Error reading file '${file}': ${error.message}`));\n reject(error);\n });\n });\n};\n","import got, { Got } from 'got';\n\n/**\n * Instantiate an instance of got that is capable of making requests to OneTrust\n *\n * @param param - information about the OneTrust URL\n * @returns The instance of got that is capable of making requests to the customer ingress\n */\nexport const createOneTrustGotInstance = ({\n hostname,\n auth,\n}: {\n /** Hostname of the OneTrust API */\n hostname: string;\n /** The OAuth access token */\n auth: string;\n}): Got =>\n got.extend({\n prefixUrl: `https://${hostname}`,\n headers: {\n accept: 'application/json',\n 'content-type': 'application/json',\n authorization: `Bearer ${auth}`,\n },\n });\n","import { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { OneTrustFileFormat, OneTrustPullResource, OneTrustPullSource } from '../../../enums.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers/index.js';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust/index.js';\nimport { logger } from '../../../logger.js';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${dryRun ? `disk at \"${file}\"` : 'Transcend'}!`,\n ),\n );\n}\n"],"mappings":"utBAQA,MAAa,GAA4B,CACvC,aACA,QACA,QACA,OAAO,MAUK,CACZ,IAAI,EAAY,IAEZ,IAAU,GAAK,KACjB,EAAY;GAGd,IAAM,EAAwB,KAAK,UAAU,EAAW,CAGlD,EAAQ,GAAS,EAAQ,EAAQ,GAAK,CAAC,EAAO,IAAM,GAU1D,MAPA,GAAY,GAAG,EAAY,EAAwB,EAAM,KAGpD,GAAS,IAAU,EAAQ,GAAM,KACpC,GAAa;IAGR,GC5BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QAAQ,+BAA+B,EAAQ,EAAE,MAAM,EAAM,YAAY,EAAK,MAAM,CAC5F,CAEG,IAAU,EACZ,EAAG,cACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,CAED,EAAG,eACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,ECpCQ,EAA+B,MAAO,CACjD,cAImC,CACnC,IAAI,EAAc,EACd,EAAa,EACb,EAAg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,GACvD,MAAM,EAAgC,CAAE,OAAM,YAAW,CAAC,QAGvD,EAAK,CACZ,MAAU,MACR,0CAA0C,EAAS,kBACjD,EAAQ,EAAI,MAAQ,EAAI,UAE3B,CAIH,EAAO,KACL,EAAO,MACL,gCAAgC,EAAS,MAAM,EAAS,YAAY,EAAK,GAAK,YAAY,GAC3F,CACF"}
1
+ {"version":3,"file":"impl-Ca064LmU.mjs","names":[],"sources":["../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToDisk.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/endpoints/getOneTrustAssessment.ts","../src/lib/oneTrust/endpoints/getOneTrustRisk.ts","../src/lib/oneTrust/endpoints/getOneTrustUser.ts","../src/lib/oneTrust/helpers/enrichOneTrustAssessment.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromFile.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/commands/migration/sync-ot/impl.ts"],"sourcesContent":["import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Converts the assessment into a json entry.\n *\n * @param param - information about the assessment and amount of entries\n * @returns a stringified json entry ready to be appended to a file\n */\nexport const oneTrustAssessmentToJson = ({\n assessment,\n index,\n total,\n wrap = true,\n}: {\n /** The assessment to convert */\n assessment: OneTrustEnrichedAssessment;\n /** The position of the assessment in the final Json object */\n index: number;\n /** The total amount of the assessments in the final Json object */\n total?: number;\n /** Whether to wrap every entry in brackets */\n wrap?: boolean;\n}): string => {\n let jsonEntry = '';\n // start with an opening bracket\n if (index === 0 || wrap) {\n jsonEntry = '[\\n';\n }\n\n const stringifiedAssessment = JSON.stringify(assessment);\n\n // Add comma for all items except the last one\n const comma = total && index < total - 1 && !wrap ? ',' : '';\n\n // write to file\n jsonEntry = `${jsonEntry + stringifiedAssessment + comma}\\n`;\n\n // end with closing bracket\n if ((total && index === total - 1) || wrap) {\n jsonEntry += '\\n]';\n }\n\n return jsonEntry;\n};\n","import fs from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\n/**\n * Write the assessment to disk at the specified file path.\n *\n *\n * @param param - information about the assessment to write\n */\nexport const syncOneTrustAssessmentToDisk = ({\n file,\n assessment,\n index,\n total,\n}: {\n /** The file path to write the assessment to */\n file: string;\n /** The basic assessment */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total: number;\n}): void => {\n logger.info(\n colors.magenta(`Writing enriched assessment ${index + 1} of ${total} to file \"${file}\"...`),\n );\n\n if (index === 0) {\n fs.writeFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n } else {\n fs.appendFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n }\n};\n","import {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\nimport { logger } from '../../../logger.js';\n\n/**\n * Fetch a list of all assessments from the OneTrust client.\n * ref: https://developer.onetrust.com/onetrust/reference/getallassessmentbasicdetailsusingget\n *\n * @param param - the information about the OneTrust client\n * @returns a list of OneTrustAssessment\n */\nexport const getListOfOneTrustAssessments = async ({\n oneTrust,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n}): Promise<OneTrustAssessment[]> => {\n let currentPage = 0;\n let totalPages = 1;\n let totalElements = 0;\n\n const allAssessments: OneTrustAssessment[] = [];\n\n while (currentPage < totalPages) {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments?page=${currentPage}&size=2000`,\n );\n\n const { page, content } = decodeCodec(OneTrustGetListOfAssessmentsResponse, body);\n allAssessments.push(...(content ?? []));\n if (currentPage === 0) {\n totalPages = page?.totalPages ?? 0;\n totalElements = page?.totalElements ?? 0;\n }\n currentPage += 1;\n\n // log progress\n logger.info(`Fetched ${allAssessments.length} of ${totalElements} assessments.`);\n }\n\n return allAssessments;\n};\n","import { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular assessment.\n * ref: https://developer.onetrust.com/onetrust/reference/exportassessmentusingget\n *\n * @param param - the information about the OneTrust client and assessment to retrieve\n * @returns details about the assessment\n */\nexport const getOneTrustAssessment = async ({\n oneTrust,\n assessmentId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the assessment to retrieve */\n assessmentId: string;\n}): Promise<OneTrustGetAssessmentResponse> => {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments/${assessmentId}/export?ExcludeSkippedQuestions=false`,\n );\n\n return decodeCodec(OneTrustGetAssessmentResponse, body);\n};\n","import { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular risk.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustRisk = async ({\n oneTrust,\n riskId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust risk to retrieve */\n riskId: string;\n}): Promise<OneTrustGetRiskResponse> => {\n const { body } = await oneTrust.get(`api/risk/v2/risks/${riskId}`);\n\n return decodeCodec(OneTrustGetRiskResponse, body);\n};\n","import { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { Got } from 'got';\n\n/**\n * Retrieve details about a particular user.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustUser = async ({\n oneTrust,\n userId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust user to retrieve */\n userId: string;\n}): Promise<OneTrustGetUserResponse> => {\n const { body } = await oneTrust.get(`api/scim/v2/Users/${userId}`);\n\n return decodeCodec(OneTrustGetUserResponse, body);\n};\n","import {\n OneTrustAssessment,\n OneTrustEnrichedAssessment,\n OneTrustGetAssessmentResponse,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { keyBy } from 'lodash-es';\n\n/**\n * Merge the assessment, assessmentDetails, and riskDetails into one object.\n *\n * @param param - the assessment and risk information\n * @returns the assessment enriched with details and risk information\n */\nexport const enrichOneTrustAssessment = ({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails,\n approversDetails,\n respondentsDetails,\n}: {\n /** The OneTrust risk details */\n riskDetails: OneTrustGetRiskResponse[];\n /** The OneTrust assessment as returned from Get List of Assessments endpoint */\n assessment: OneTrustAssessment;\n /** The OneTrust assessment details */\n assessmentDetails: OneTrustGetAssessmentResponse;\n /** The OneTrust assessment creator details */\n creatorDetails: OneTrustGetUserResponse;\n /** The OneTrust assessment approvers details */\n approversDetails: OneTrustGetUserResponse[];\n /** The OneTrust assessment internal respondents details */\n respondentsDetails: OneTrustGetUserResponse[];\n}): OneTrustEnrichedAssessment => {\n const riskDetailsById = keyBy(riskDetails, 'id');\n const { sections, createdBy, ...restAssessmentDetails } = assessmentDetails;\n const sectionsWithEnrichedRisk = sections.map((section) => {\n const { questions, ...restSection } = section;\n const enrichedQuestions = questions.map((question) => {\n const { risks, ...restQuestion } = question;\n const enrichedRisks = (risks ?? []).map((risk) => {\n const details = riskDetailsById[risk.riskId];\n return {\n ...risk,\n ...details,\n level: risk.level,\n impactLevel: risk.impactLevel ?? 0,\n };\n });\n return {\n ...restQuestion,\n risks: enrichedRisks,\n };\n });\n return {\n ...restSection,\n questions: enrichedQuestions,\n };\n });\n\n // grab creator details\n const enrichedCreatedBy = {\n ...createdBy,\n active: creatorDetails?.active ?? false,\n userType: creatorDetails?.userType ?? 'Internal',\n emails: creatorDetails?.emails ?? [],\n title: creatorDetails?.title ?? null,\n givenName: creatorDetails?.name.givenName ?? null,\n familyName: creatorDetails?.name.familyName ?? null,\n };\n\n // grab approvers details\n const approverDetailsById = keyBy(approversDetails, 'id');\n const enrichedApprovers = assessmentDetails.approvers.flatMap((originalApprover) =>\n approverDetailsById[originalApprover.id]\n ? [\n {\n ...originalApprover,\n approver: {\n ...originalApprover.approver,\n active: approverDetailsById[originalApprover.id].active,\n userType: approverDetailsById[originalApprover.id].userType,\n emails: approverDetailsById[originalApprover.id].emails,\n title: approverDetailsById[originalApprover.id].title,\n givenName: approverDetailsById[originalApprover.id].name.givenName ?? null,\n familyName: approverDetailsById[originalApprover.id].name.familyName ?? null,\n },\n },\n ]\n : [],\n );\n\n // grab respondents details\n const respondentsDetailsById = keyBy(respondentsDetails, 'id');\n const enrichedRespondents = assessmentDetails.respondents\n .filter((r) => !r.name.includes('@')) // search only internal respondents\n .flatMap((respondent) =>\n respondentsDetailsById[respondent.id]\n ? [\n {\n ...respondent,\n active: respondentsDetailsById[respondent.id].active,\n userType: respondentsDetailsById[respondent.id].userType,\n emails: respondentsDetailsById[respondent.id].emails,\n title: respondentsDetailsById[respondent.id].title,\n givenName: respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName: respondentsDetailsById[respondent.id].name.familyName ?? null,\n },\n ]\n : [],\n );\n\n // combine everything into a single enriched assessment\n return {\n ...assessment,\n ...restAssessmentDetails,\n approvers: enrichedApprovers,\n respondents: enrichedRespondents,\n createdBy: enrichedCreatedBy,\n sections: sectionsWithEnrichedRisk,\n };\n};\n","import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { makeGraphQLRequest, IMPORT_ONE_TRUST_ASSESSMENT_FORMS } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\n\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs.js';\nimport { logger } from '../../../logger.js';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Write the assessment to a Transcend instance.\n *\n *\n * @param param - information about the assessment and Transcend instance to write to\n */\nexport const syncOneTrustAssessmentToTranscend = async ({\n transcend,\n assessment,\n total,\n index,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** the assessment to sync to Transcend */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total?: number;\n}): Promise<void> => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend...`,\n ),\n );\n\n // convert the OneTrust assessment object into a json record\n const json = oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n });\n\n // transform the json record into a valid input to the mutation\n const input: ImportOnetrustAssessmentsInput = {\n json,\n };\n\n try {\n await makeGraphQLRequest<{\n /** the importOneTrustAssessmentForms mutation */\n importOneTrustAssessmentForms: {\n /** Created Assessment Forms */\n assessmentForms: AssessmentForm[];\n };\n }>(transcend, IMPORT_ONE_TRUST_ASSESSMENT_FORMS, {\n variables: { input },\n logger,\n });\n } catch (error) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${total ? `of ${total} ` : ' '}to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n error,\n );\n }\n};\n","import {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { mapSeries, map } from '@transcend-io/utils';\nimport colors from 'colors';\nimport type { Got } from 'got';\nimport { GraphQLClient } from 'graphql-request';\nimport { uniq } from 'lodash-es';\n\nimport { logger } from '../../../logger.js';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints/index.js';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment.js';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Reads all the assessments from a OneTrust instance and syncs them to Transcend or to Disk.\n *\n * @param param - the information about the assessment, its OneTrust source, and destination (disk or Transcend)\n */\nexport const syncOneTrustAssessmentsFromOneTrust = async ({\n oneTrust,\n file,\n dryRun,\n transcend,\n}: {\n /** the OneTrust client instance */\n oneTrust: Got;\n /** the Transcend client instance */\n transcend?: GraphQLClient;\n /** Whether to write to file instead of syncing to Transcend */\n dryRun: boolean;\n /** the path to the file in case dryRun is true */\n file?: string;\n}): Promise<void> => {\n // fetch the list of all assessments in the OneTrust organization\n logger.info('Getting list of all assessments from OneTrust...');\n const assessments = await getListOfOneTrustAssessments({ oneTrust });\n\n // a cache of OneTrust users so we avoid requesting already fetched users\n const oneTrustCachedUsers: Record<string, OneTrustGetUserResponse> = {};\n\n // split all assessments in batches, so we can process some of steps in parallel\n const BATCH_SIZE = 5;\n const assessmentBatches = Array.from(\n {\n length: Math.ceil(assessments.length / BATCH_SIZE),\n },\n (_, i) => assessments.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),\n );\n\n // process each batch and sync the batch right away so it's garbage collected and we don't run out of memory\n await mapSeries(assessmentBatches, async (assessmentBatch, batch) => {\n const batchEnrichedAssessments: OneTrustEnrichedAssessment[] = [];\n\n // fetch assessment details from OneTrust in parallel\n await map(\n assessmentBatch,\n async (assessment, index) => {\n const assessmentNumber = BATCH_SIZE * batch + index + 1;\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching details...`,\n );\n const { templateName, assessmentId } = assessment;\n const assessmentDetails = await getOneTrustAssessment({\n oneTrust,\n assessmentId,\n });\n // fetch assessment's creator information\n const creatorId = assessmentDetails.createdBy.id;\n let creator = oneTrustCachedUsers[creatorId];\n if (!creator) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching creator...`,\n );\n try {\n creator = await getOneTrustUser({\n oneTrust,\n userId: creatorId,\n });\n oneTrustCachedUsers[creatorId] = creator;\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch form creator.` +\n `\\tcreatorId: ${creatorId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n }\n }\n\n // fetch assessment approvers information\n const { approvers } = assessmentDetails;\n let approversDetails: OneTrustGetUserResponse[][] = [];\n if (approvers.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching approvers...`,\n );\n approversDetails = await map(\n approvers.map(({ id }) => id),\n async (userId) => {\n try {\n let approver = oneTrustCachedUsers[userId];\n if (!approver) {\n approver = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = approver;\n }\n return [approver];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a form approver.` +\n `\\tapproverId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment internal respondents information\n const { respondents } = assessmentDetails;\n // if a user is an internal respondents, their 'name' field can't be an email.\n const internalRespondents = respondents.filter((r) => !r.name.includes('@'));\n let respondentsDetails: OneTrustGetUserResponse[][] = [];\n if (internalRespondents.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching respondents...`,\n );\n respondentsDetails = await map(\n internalRespondents.map(({ id }) => id),\n async (userId) => {\n try {\n let respondent = oneTrustCachedUsers[userId];\n if (!respondent) {\n respondent = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = respondent;\n }\n return [respondent];\n } catch (error) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a respondent.` +\n `\\trespondentId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n error,\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment risk information\n let riskDetails: OneTrustGetRiskResponse[] = [];\n const riskIds = uniq(\n assessmentDetails.sections.flatMap((s: OneTrustAssessmentSection) =>\n s.questions.flatMap((q: OneTrustAssessmentQuestion) =>\n (q.risks ?? []).flatMap((r) => r.riskId),\n ),\n ),\n );\n if (riskIds.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching risks...`,\n );\n riskDetails = await map(\n riskIds,\n (riskId) => getOneTrustRisk({ oneTrust, riskId: riskId as string }),\n {\n concurrency: 5,\n },\n );\n }\n\n // enrich the assessments with user and risk details\n const enrichedAssessment = enrichOneTrustAssessment({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails: creator,\n approversDetails: approversDetails.flat(),\n respondentsDetails: respondentsDetails.flat(),\n });\n\n batchEnrichedAssessments.push(enrichedAssessment);\n },\n { concurrency: BATCH_SIZE },\n );\n\n // sync assessments in series to avoid concurrency bugs\n await mapSeries(batchEnrichedAssessments, async (enrichedAssessment, index) => {\n // the assessment's global index takes its batch into consideration\n const globalIndex = batch * BATCH_SIZE + index;\n\n if (dryRun && file) {\n // sync to file\n syncOneTrustAssessmentToDisk({\n assessment: enrichedAssessment,\n index: globalIndex,\n total: assessments.length,\n file,\n });\n } else if (transcend) {\n // sync to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: enrichedAssessment,\n transcend,\n total: assessments.length,\n index: globalIndex,\n });\n }\n });\n });\n};\n","import { createReadStream } from 'node:fs';\n\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport JSONStream from 'JSONStream';\n\nimport { logger } from '../../../logger.js';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend.js';\n\n/**\n * Reads assessments from a file and syncs them to Transcend.\n *\n * @param param - the information about the source file and Transcend instance to write them to.\n */\nexport const syncOneTrustAssessmentsFromFile = ({\n transcend,\n file,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** The name of the file from which to read the OneTrust assessments */\n file: string;\n}): Promise<void> => {\n logger.info(`Getting list of all assessments from file ${file}...`);\n\n return new Promise((resolve, reject) => {\n // Create a readable stream from the file\n const fileStream = createReadStream(file, {\n encoding: 'utf-8',\n highWaterMark: 64 * 1024, // 64KB chunks\n });\n\n // Create a JSONStream parser to parse the array of OneTrust assessments from the file\n const parser = JSONStream.parse('*'); // '*' matches each element in the root array\n\n let index = 0;\n\n // Pipe the file stream into the JSON parser\n fileStream.pipe(parser);\n\n // Handle each parsed assessment object\n parser.on('data', async (assessment) => {\n try {\n // Pause the stream while processing to avoid overwhelming memory\n parser.pause();\n\n // Decode and validate the assessment\n const parsedAssessment = decodeCodec(OneTrustEnrichedAssessment, assessment);\n\n // Sync the assessment to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: parsedAssessment,\n transcend,\n index,\n });\n\n index += 1;\n\n // Resume the stream after processing\n parser.resume();\n } catch (e) {\n // if failed to parse a line, report error and continue\n logger.error(\n colors.red(`Failed to parse the assessment ${index} from file '${file}': ${e.message}.`),\n );\n }\n });\n\n // Handle completion\n parser.on('end', () => {\n logger.info(`Finished processing ${index} assessments from file ${file}`);\n resolve();\n });\n\n // Handle stream or parsing errors\n parser.on('error', (error) => {\n logger.error(colors.red(`Error parsing file '${file}': ${error.message}`));\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(colors.red(`Error reading file '${file}': ${error.message}`));\n reject(error);\n });\n });\n};\n","import got, { Got } from 'got';\n\n/**\n * Instantiate an instance of got that is capable of making requests to OneTrust\n *\n * @param param - information about the OneTrust URL\n * @returns The instance of got that is capable of making requests to the customer ingress\n */\nexport const createOneTrustGotInstance = ({\n hostname,\n auth,\n}: {\n /** Hostname of the OneTrust API */\n hostname: string;\n /** The OAuth access token */\n auth: string;\n}): Got =>\n got.extend({\n prefixUrl: `https://${hostname}`,\n headers: {\n accept: 'application/json',\n 'content-type': 'application/json',\n authorization: `Bearer ${auth}`,\n },\n });\n","import { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { OneTrustFileFormat, OneTrustPullResource, OneTrustPullSource } from '../../../enums.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers/index.js';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust/index.js';\nimport { logger } from '../../../logger.js';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${dryRun ? `disk at \"${file}\"` : 'Transcend'}!`,\n ),\n );\n}\n"],"mappings":"utBAQA,MAAa,GAA4B,CACvC,aACA,QACA,QACA,OAAO,MAUK,CACZ,IAAI,EAAY,IAEZ,IAAU,GAAK,KACjB,EAAY;GAGd,IAAM,EAAwB,KAAK,UAAU,EAAW,CAGlD,EAAQ,GAAS,EAAQ,EAAQ,GAAK,CAAC,EAAO,IAAM,GAU1D,MAPA,GAAY,GAAG,EAAY,EAAwB,EAAM,KAGpD,GAAS,IAAU,EAAQ,GAAM,KACpC,GAAa;IAGR,GC5BI,GAAgC,CAC3C,OACA,aACA,QACA,WAUU,CACV,EAAO,KACL,EAAO,QAAQ,+BAA+B,EAAQ,EAAE,MAAM,EAAM,YAAY,EAAK,MAAM,CAC5F,CAEG,IAAU,EACZ,EAAG,cACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,CAED,EAAG,eACD,EACA,EAAyB,CACvB,aACA,QACA,QACA,KAAM,GACP,CAAC,CACH,ECpCQ,EAA+B,MAAO,CACjD,cAImC,CACnC,IAAI,EAAc,EACd,EAAa,EACb,EAAgB,EAEd,EAAuC,EAAE,CAE/C,KAAO,EAAc,GAAY,CAC/B,GAAM,CAAE,QAAS,MAAM,EAAS,IAC9B,sCAAsC,EAAY,YACnD,CAEK,CAAE,OAAM,WAAY,EAAY,EAAsC,EAAK,CACjF,EAAe,KAAK,GAAI,GAAW,EAAE,CAAE,CACnC,IAAgB,IAClB,EAAa,G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@ -1,2 +1,2 @@
1
- import{t as e}from"./downloadPrivacyRequestFiles-CAGrriEp.mjs";import{t}from"./done-input-validation-uqIgnJcw.mjs";import{RequestStatus as n}from"@transcend-io/privacy-types";async function r({auth:r,transcendUrl:i,folderPath:a,requestIds:o,statuses:s=[n.Approving,n.Downloadable],concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p}){t(this.process.exit),await e({transcendUrl:i,auth:r,folderPath:a,requestIds:o,statuses:s,concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p})}export{r as downloadFiles};
2
- //# sourceMappingURL=impl-Bgf0a6fL2.mjs.map
1
+ import{t as e}from"./downloadPrivacyRequestFiles-DSOTFVU6.mjs";import{t}from"./done-input-validation-DL31vk7g.mjs";import{RequestStatus as n}from"@transcend-io/privacy-types";async function r({auth:r,transcendUrl:i,folderPath:a,requestIds:o,statuses:s=[n.Approving,n.Downloadable],concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p}){t(this.process.exit),await e({transcendUrl:i,auth:r,folderPath:a,requestIds:o,statuses:s,concurrency:c,createdAtBefore:l,createdAtAfter:u,updatedAtBefore:d,updatedAtAfter:f,approveAfterDownload:p})}export{r as downloadFiles};
2
+ //# sourceMappingURL=impl-CdOwXtLY2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-Bgf0a6fL2.mjs","names":[],"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import { RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests/index.js';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"+KAqBA,eAAsB,EAEpB,CACE,OACA,eACA,aACA,aACA,WAAW,CAAC,EAAc,UAAW,EAAc,aAAa,CAChE,cACA,kBACA,iBACA,kBACA,iBACA,wBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAA4B,CAChC,eACA,OACA,aACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACA,uBACD,CAAC"}
1
+ {"version":3,"file":"impl-CdOwXtLY2.mjs","names":[],"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import { RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests/index.js';\n\nexport interface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"+KAqBA,eAAsB,EAEpB,CACE,OACA,eACA,aACA,aACA,WAAW,CAAC,EAAc,UAAW,EAAc,aAAa,CAChE,cACA,kBACA,iBACA,kBACA,iBACA,wBAEa,CACf,EAAoB,KAAK,QAAQ,KAAK,CAEtC,MAAM,EAA4B,CAChC,eACA,OACA,aACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACA,uBACD,CAAC"}
@@ -1,3 +1,3 @@
1
- import{r as e,t}from"./policyEngineCliError-BnBghLd1.mjs";import{i as n,n as r,t as i}from"./printResult-oXnpZu_9.mjs";import{t as a}from"./formatPolicyBundleVersionSummary-Bo7DYxoy.mjs";import{n as o}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as s}from"./resolvePolicyBundleVersion-DO7IvEwb.mjs";import{t as c}from"./logger-Ckep4QXn.mjs";import{t as l}from"./done-input-validation-uqIgnJcw.mjs";import u from"colors";async function d({"bundle-name":d,version:f,auth:p,"transcend-url":m,"dry-run":h,json:g,debug:_=!1}){l(this.process.exit),e(_);let v=n(m,p),y=await o(v,d);if(!y)throw Error(`Policy bundle "${d}" was not found for this organization.`);let b=await s(v,y,{version:f});c.info(u.green(h?`Validating activation for version "${b.version}"...`:`Activating version "${b.version}"...`));let x;try{x=await r(v.post(`v1/policy-engine/policy-bundles/${y}/versions/${b.id}/activate`,{json:h?{dryRun:!0}:{}}).json())}catch(e){throw(e instanceof t?e.cause:void 0)?.response?.statusCode===409?new t(`Version "${b.version}" of policy bundle "${d}" is already the active version.`,{cause:e}):e}i(this.process.stdout,{json:g,data:x,renderTable:()=>[`bundleId ${x.bundle.id}`,`bundleName ${x.bundle.bundleName}`,a(x.version)].join(`
1
+ import{r as e,t}from"./policyEngineCliError-BnBghLd1.mjs";import{i as n,n as r,t as i}from"./printResult-oXnpZu_9.mjs";import{t as a}from"./formatPolicyBundleVersionSummary-Bo7DYxoy.mjs";import{n as o}from"./resolveBundleIdByName-By5Vl8Iz.mjs";import{t as s}from"./resolvePolicyBundleVersion-DO7IvEwb.mjs";import{t as c}from"./logger-Ckep4QXn.mjs";import{t as l}from"./done-input-validation-DL31vk7g.mjs";import u from"colors";async function d({"bundle-name":d,version:f,auth:p,"transcend-url":m,"dry-run":h,json:g,debug:_=!1}){l(this.process.exit),e(_);let v=n(m,p),y=await o(v,d);if(!y)throw Error(`Policy bundle "${d}" was not found for this organization.`);let b=await s(v,y,{version:f});c.info(u.green(h?`Validating activation for version "${b.version}"...`:`Activating version "${b.version}"...`));let x;try{x=await r(v.post(`v1/policy-engine/policy-bundles/${y}/versions/${b.id}/activate`,{json:h?{dryRun:!0}:{}}).json())}catch(e){throw(e instanceof t?e.cause:void 0)?.response?.statusCode===409?new t(`Version "${b.version}" of policy bundle "${d}" is already the active version.`,{cause:e}):e}i(this.process.stdout,{json:g,data:x,renderTable:()=>[`bundleId ${x.bundle.id}`,`bundleName ${x.bundle.bundleName}`,a(x.version)].join(`
2
2
  `)}),c.info(u.green(h?`Activation validation succeeded.`:`Policy bundle version activated.`))}export{d as activate};
3
- //# sourceMappingURL=impl-B_4_7a-i.mjs.map
3
+ //# sourceMappingURL=impl-Chska4J8.mjs.map