@transcend-io/cli 12.1.5 → 13.0.2

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 (215) hide show
  1. package/README.md +64 -14
  2. package/dist/{app-BMLQABJX.mjs → app-CCGKgPiC.mjs} +19 -19
  3. package/dist/app-CCGKgPiC.mjs.map +1 -0
  4. package/dist/{approvePrivacyRequests-CY6rQT4J.mjs → approvePrivacyRequests-BBcqydVb.mjs} +2 -2
  5. package/dist/{approvePrivacyRequests-CY6rQT4J.mjs.map → approvePrivacyRequests-BBcqydVb.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-BNGtj-DW.mjs → buildExamples-DRU0o6EK.mjs} +2 -2
  10. package/dist/{buildExamples-BNGtj-DW.mjs.map → buildExamples-DRU0o6EK.mjs.map} +1 -1
  11. package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs → buildXdiSyncEndpoint-CSjQKSn3.mjs} +2 -2
  12. package/dist/{buildXdiSyncEndpoint-BNCfOc-g.mjs.map → buildXdiSyncEndpoint-CSjQKSn3.mjs.map} +1 -1
  13. package/dist/{bulkRestartRequests-CGvODu3r.mjs → bulkRestartRequests-Cx5LfpdX.mjs} +2 -2
  14. package/dist/{bulkRestartRequests-CGvODu3r.mjs.map → bulkRestartRequests-Cx5LfpdX.mjs.map} +1 -1
  15. package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs → bulkRetryEnrichers-BSJtvqJD.mjs} +2 -2
  16. package/dist/{bulkRetryEnrichers-BgDd4GWH.mjs.map → bulkRetryEnrichers-BSJtvqJD.mjs.map} +1 -1
  17. package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs → cancelPrivacyRequests-Cy48R4tJ.mjs} +2 -2
  18. package/dist/{cancelPrivacyRequests-Ccsiwrnu.mjs.map → cancelPrivacyRequests-Cy48R4tJ.mjs.map} +1 -1
  19. package/dist/codecs-8T8Jhxsr.mjs +2 -0
  20. package/dist/codecs-8T8Jhxsr.mjs.map +1 -0
  21. package/dist/{command-BjzdoKgJ.mjs → command-Gip5wB8W.mjs} +2 -2
  22. package/dist/{command-BjzdoKgJ.mjs.map → command-Gip5wB8W.mjs.map} +1 -1
  23. package/dist/constants-D6y_AX3P.mjs +2 -0
  24. package/dist/constants-D6y_AX3P.mjs.map +1 -0
  25. package/dist/{constants-FDjw7bPS.mjs → constants-DAx9VK1C.mjs} +2 -2
  26. package/dist/{constants-FDjw7bPS.mjs.map → constants-DAx9VK1C.mjs.map} +1 -1
  27. package/dist/{createPoolingCommandUi-BdtnLBBM.mjs → createPoolingCommandUi-DZx16Cn8.mjs} +2 -2
  28. package/dist/{createPoolingCommandUi-BdtnLBBM.mjs.map → createPoolingCommandUi-DZx16Cn8.mjs.map} +1 -1
  29. package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs → downloadPrivacyRequestFiles-DBeuW9b3.mjs} +2 -2
  30. package/dist/{downloadPrivacyRequestFiles-C9-xSCpt.mjs.map → downloadPrivacyRequestFiles-DBeuW9b3.mjs.map} +1 -1
  31. package/dist/fetchAllRequests-BV9K0wXv.mjs +2 -0
  32. package/dist/fetchAllRequests-BV9K0wXv.mjs.map +1 -0
  33. package/dist/{fuzzyMatchColumns-D18n9Beu.mjs → fuzzyMatchColumns-Djl3a7lV.mjs} +2 -2
  34. package/dist/{fuzzyMatchColumns-D18n9Beu.mjs.map → fuzzyMatchColumns-Djl3a7lV.mjs.map} +1 -1
  35. package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs → generateCrossAccountApiKeys-CjmSyfwm.mjs} +2 -2
  36. package/dist/{generateCrossAccountApiKeys-FtWwlf_L.mjs.map → generateCrossAccountApiKeys-CjmSyfwm.mjs.map} +1 -1
  37. package/dist/{impl-Dg7XSQdO2.mjs → impl-7qTKg-YP2.mjs} +2 -2
  38. package/dist/{impl-Dg7XSQdO2.mjs.map → impl-7qTKg-YP2.mjs.map} +1 -1
  39. package/dist/{impl-D58JUOdA.mjs → impl-9W0QG6fB.mjs} +2 -2
  40. package/dist/{impl-D58JUOdA.mjs.map → impl-9W0QG6fB.mjs.map} +1 -1
  41. package/dist/{impl-B94dMG4x2.mjs → impl-B-BkGfqq2.mjs} +2 -2
  42. package/dist/{impl-B94dMG4x2.mjs.map → impl-B-BkGfqq2.mjs.map} +1 -1
  43. package/dist/{impl-yIVxAhCG2.mjs → impl-B8DsKzNn2.mjs} +2 -2
  44. package/dist/{impl-yIVxAhCG2.mjs.map → impl-B8DsKzNn2.mjs.map} +1 -1
  45. package/dist/impl-B9jwlKCX2.mjs +2 -0
  46. package/dist/impl-B9jwlKCX2.mjs.map +1 -0
  47. package/dist/{impl-C3vTm9zQ.mjs → impl-BIhXJ0Nw.mjs} +2 -2
  48. package/dist/{impl-C3vTm9zQ.mjs.map → impl-BIhXJ0Nw.mjs.map} +1 -1
  49. package/dist/{impl-B_N_fOq0.mjs → impl-BLM6rMBq.mjs} +2 -2
  50. package/dist/{impl-B_N_fOq0.mjs.map → impl-BLM6rMBq.mjs.map} +1 -1
  51. package/dist/{impl-Hj5CgbWd.mjs → impl-BPmzcgpy.mjs} +2 -2
  52. package/dist/{impl-Hj5CgbWd.mjs.map → impl-BPmzcgpy.mjs.map} +1 -1
  53. package/dist/{impl-COqlYiiw.mjs → impl-BUKV7sYp.mjs} +2 -2
  54. package/dist/{impl-COqlYiiw.mjs.map → impl-BUKV7sYp.mjs.map} +1 -1
  55. package/dist/{impl-DFnWzZyY.mjs → impl-BahDGEJJ.mjs} +2 -2
  56. package/dist/{impl-DFnWzZyY.mjs.map → impl-BahDGEJJ.mjs.map} +1 -1
  57. package/dist/{impl-qNF5eqX-.mjs → impl-BfU0GFmW.mjs} +1 -1
  58. package/dist/{impl-qNF5eqX-.mjs.map → impl-BfU0GFmW.mjs.map} +1 -1
  59. package/dist/{impl-DDVhG8Gf.mjs → impl-Bh1CkZhV.mjs} +2 -2
  60. package/dist/{impl-DDVhG8Gf.mjs.map → impl-Bh1CkZhV.mjs.map} +1 -1
  61. package/dist/{impl-BvwRiPSG.mjs → impl-BkQryDNq.mjs} +2 -2
  62. package/dist/{impl-BvwRiPSG.mjs.map → impl-BkQryDNq.mjs.map} +1 -1
  63. package/dist/{impl-bl6NF3Lr.mjs → impl-BsdneZZP.mjs} +2 -2
  64. package/dist/{impl-bl6NF3Lr.mjs.map → impl-BsdneZZP.mjs.map} +1 -1
  65. package/dist/{impl-D6rMLiNB2.mjs → impl-BuOc87b6.mjs} +2 -2
  66. package/dist/impl-BuOc87b6.mjs.map +1 -0
  67. package/dist/{impl-DUYRVzMo.mjs → impl-BzzkiK_b.mjs} +1 -1
  68. package/dist/{impl-DUYRVzMo.mjs.map → impl-BzzkiK_b.mjs.map} +1 -1
  69. package/dist/{impl-ClT3G845.mjs → impl-C2BYhujB.mjs} +2 -2
  70. package/dist/{impl-ClT3G845.mjs.map → impl-C2BYhujB.mjs.map} +1 -1
  71. package/dist/{impl-DnDM9zcu.mjs → impl-C5qif_gE.mjs} +2 -2
  72. package/dist/{impl-DnDM9zcu.mjs.map → impl-C5qif_gE.mjs.map} +1 -1
  73. package/dist/{impl-BLtOfbtk.mjs → impl-C8auyA7u.mjs} +2 -2
  74. package/dist/{impl-BLtOfbtk.mjs.map → impl-C8auyA7u.mjs.map} +1 -1
  75. package/dist/{impl-BEiCEzl_2.mjs → impl-CHoglMch.mjs} +1 -1
  76. package/dist/impl-CHoglMch.mjs.map +1 -0
  77. package/dist/{impl-QD3_9HTk.mjs → impl-CJ4oVuXN.mjs} +2 -2
  78. package/dist/{impl-QD3_9HTk.mjs.map → impl-CJ4oVuXN.mjs.map} +1 -1
  79. package/dist/{impl-DhXzxQDN2.mjs → impl-CRif3TpB2.mjs} +2 -2
  80. package/dist/{impl-DhXzxQDN2.mjs.map → impl-CRif3TpB2.mjs.map} +1 -1
  81. package/dist/{impl-Cvyc-iTI2.mjs → impl-CWINXCFq2.mjs} +2 -2
  82. package/dist/{impl-Cvyc-iTI2.mjs.map → impl-CWINXCFq2.mjs.map} +1 -1
  83. package/dist/{impl-Dd39KsYO.mjs → impl-C_lIkMLn2.mjs} +2 -2
  84. package/dist/impl-C_lIkMLn2.mjs.map +1 -0
  85. package/dist/{impl-EDwngLc7.mjs → impl-CcPwm8a4.mjs} +2 -2
  86. package/dist/{impl-EDwngLc7.mjs.map → impl-CcPwm8a4.mjs.map} +1 -1
  87. package/dist/{impl-DGtCNANL.mjs → impl-CjjiXsMh.mjs} +2 -2
  88. package/dist/{impl-DGtCNANL.mjs.map → impl-CjjiXsMh.mjs.map} +1 -1
  89. package/dist/{impl-BLOhoP-b2.mjs → impl-CzFfjx8n2.mjs} +2 -2
  90. package/dist/{impl-BLOhoP-b2.mjs.map → impl-CzFfjx8n2.mjs.map} +1 -1
  91. package/dist/{impl-BXGpJz21.mjs → impl-D6e2LNBm.mjs} +2 -2
  92. package/dist/{impl-BXGpJz21.mjs.map → impl-D6e2LNBm.mjs.map} +1 -1
  93. package/dist/{impl-SOebshza.mjs → impl-D8yF0jw9.mjs} +2 -2
  94. package/dist/{impl-SOebshza.mjs.map → impl-D8yF0jw9.mjs.map} +1 -1
  95. package/dist/{impl-DeCRXfAh2.mjs → impl-DEF-meSg2.mjs} +2 -2
  96. package/dist/{impl-DeCRXfAh2.mjs.map → impl-DEF-meSg2.mjs.map} +1 -1
  97. package/dist/{impl-DZoTWLfw2.mjs → impl-DEPuP4Oy2.mjs} +2 -2
  98. package/dist/{impl-DZoTWLfw2.mjs.map → impl-DEPuP4Oy2.mjs.map} +1 -1
  99. package/dist/impl-DGLrKNNs2.mjs +2 -0
  100. package/dist/impl-DGLrKNNs2.mjs.map +1 -0
  101. package/dist/{impl-XxYQHKO5.mjs → impl-DPq1O87s.mjs} +2 -2
  102. package/dist/{impl-XxYQHKO5.mjs.map → impl-DPq1O87s.mjs.map} +1 -1
  103. package/dist/{impl-ChQAmyBN.mjs → impl-DiaD11OP.mjs} +2 -2
  104. package/dist/{impl-ChQAmyBN.mjs.map → impl-DiaD11OP.mjs.map} +1 -1
  105. package/dist/{impl-0-_oxvck.mjs → impl-DioQW8jR.mjs} +2 -2
  106. package/dist/{impl-0-_oxvck.mjs.map → impl-DioQW8jR.mjs.map} +1 -1
  107. package/dist/{impl-D6frX-PK.mjs → impl-DjBbx05w.mjs} +2 -2
  108. package/dist/{impl-D6frX-PK.mjs.map → impl-DjBbx05w.mjs.map} +1 -1
  109. package/dist/{impl-BCKUj-ko.mjs → impl-DnBmd-wi.mjs} +2 -2
  110. package/dist/{impl-BCKUj-ko.mjs.map → impl-DnBmd-wi.mjs.map} +1 -1
  111. package/dist/{impl-Cp5o0Q2g.mjs → impl-Do3hnGHt.mjs} +2 -2
  112. package/dist/{impl-Cp5o0Q2g.mjs.map → impl-Do3hnGHt.mjs.map} +1 -1
  113. package/dist/{impl-VSo8bO-J.mjs → impl-DqbJ33ve.mjs} +2 -2
  114. package/dist/{impl-VSo8bO-J.mjs.map → impl-DqbJ33ve.mjs.map} +1 -1
  115. package/dist/{impl-Cb-7C1Ml2.mjs → impl-DvHiVaGW.mjs} +12 -105
  116. package/dist/impl-DvHiVaGW.mjs.map +1 -0
  117. package/dist/{impl-CTOgxZFi.mjs → impl-Dx8BYv7U.mjs} +2 -2
  118. package/dist/{impl-CTOgxZFi.mjs.map → impl-Dx8BYv7U.mjs.map} +1 -1
  119. package/dist/{impl-Bz1wZxa-.mjs → impl-GphhprmF.mjs} +2 -2
  120. package/dist/{impl-Bz1wZxa-.mjs.map → impl-GphhprmF.mjs.map} +1 -1
  121. package/dist/{impl-agm4lpyq.mjs → impl-HsRwcfRu.mjs} +2 -2
  122. package/dist/{impl-agm4lpyq.mjs.map → impl-HsRwcfRu.mjs.map} +1 -1
  123. package/dist/{impl-BHEAKFX02.mjs → impl-LT1FBKID2.mjs} +2 -2
  124. package/dist/{impl-BHEAKFX02.mjs.map → impl-LT1FBKID2.mjs.map} +1 -1
  125. package/dist/{impl-xY_5o78i.mjs → impl-Nwbb2xaH.mjs} +2 -2
  126. package/dist/{impl-xY_5o78i.mjs.map → impl-Nwbb2xaH.mjs.map} +1 -1
  127. package/dist/{impl-CSnBFv5P.mjs → impl-SKxxByoN.mjs} +2 -2
  128. package/dist/{impl-CSnBFv5P.mjs.map → impl-SKxxByoN.mjs.map} +1 -1
  129. package/dist/{impl-ojAnhhbi.mjs → impl-bUltX0u3.mjs} +2 -2
  130. package/dist/{impl-ojAnhhbi.mjs.map → impl-bUltX0u3.mjs.map} +1 -1
  131. package/dist/{impl-Bs2pNgMK.mjs → impl-cU3bjY3P.mjs} +2 -2
  132. package/dist/{impl-Bs2pNgMK.mjs.map → impl-cU3bjY3P.mjs.map} +1 -1
  133. package/dist/{impl-xVmMN-Vt.mjs → impl-h0z8OSQY.mjs} +2 -2
  134. package/dist/{impl-xVmMN-Vt.mjs.map → impl-h0z8OSQY.mjs.map} +1 -1
  135. package/dist/{impl-Ay6JeH-7.mjs → impl-kuuX5KaC.mjs} +2 -2
  136. package/dist/{impl-Ay6JeH-7.mjs.map → impl-kuuX5KaC.mjs.map} +1 -1
  137. package/dist/{impl-Ar7VAh0Z.mjs → impl-nYlbrsD7.mjs} +2 -2
  138. package/dist/{impl-Ar7VAh0Z.mjs.map → impl-nYlbrsD7.mjs.map} +1 -1
  139. package/dist/{impl-zZd6fuXS.mjs → impl-nte7qanu.mjs} +2 -2
  140. package/dist/{impl-zZd6fuXS.mjs.map → impl-nte7qanu.mjs.map} +1 -1
  141. package/dist/{impl-ApZGIx6l.mjs → impl-o66EB2o7.mjs} +2 -2
  142. package/dist/{impl-ApZGIx6l.mjs.map → impl-o66EB2o7.mjs.map} +1 -1
  143. package/dist/{impl-BpVe6fMe.mjs → impl-yxR3rwGm.mjs} +2 -2
  144. package/dist/{impl-BpVe6fMe.mjs.map → impl-yxR3rwGm.mjs.map} +1 -1
  145. package/dist/index.d.mts +36 -26
  146. package/dist/index.d.mts.map +1 -1
  147. package/dist/index.mjs +1 -1
  148. package/dist/{inquirer-jzIQWAvq.mjs → inquirer-DK1JbPA0.mjs} +2 -2
  149. package/dist/{inquirer-jzIQWAvq.mjs.map → inquirer-DK1JbPA0.mjs.map} +1 -1
  150. package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs → markRequestDataSiloIdsCompleted-loC-xyyW.mjs} +2 -2
  151. package/dist/{markRequestDataSiloIdsCompleted-JGJf33yp.mjs.map → markRequestDataSiloIdsCompleted-loC-xyyW.mjs.map} +1 -1
  152. package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs → markSilentPrivacyRequests-D7ncAg8k.mjs} +2 -2
  153. package/dist/{markSilentPrivacyRequests-BTI3rH-V.mjs.map → markSilentPrivacyRequests-D7ncAg8k.mjs.map} +1 -1
  154. package/dist/{mergeTranscendInputs-B7WjxYMN.mjs → mergeTranscendInputs-9kQ3t5VY.mjs} +2 -2
  155. package/dist/{mergeTranscendInputs-B7WjxYMN.mjs.map → mergeTranscendInputs-9kQ3t5VY.mjs.map} +1 -1
  156. package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs → notifyPrivacyRequestsAdditionalTime-DpCfIR_O.mjs} +2 -2
  157. package/dist/{notifyPrivacyRequestsAdditionalTime-n5fvOJaA.mjs.map → notifyPrivacyRequestsAdditionalTime-DpCfIR_O.mjs.map} +1 -1
  158. package/dist/{policy-bundle-manifest-DbbTXe0u.mjs → policy-bundle-manifest-DW3Wilp8.mjs} +2 -2
  159. package/dist/{policy-bundle-manifest-DbbTXe0u.mjs.map → policy-bundle-manifest-DW3Wilp8.mjs.map} +1 -1
  160. package/dist/{policy-project-discovery-DTSl0Gfl.mjs → policy-project-discovery-CND7N2HI.mjs} +4 -4
  161. package/dist/policy-project-discovery-CND7N2HI.mjs.map +1 -0
  162. package/dist/{policy-scaffold-config-RpxwwZ2H.mjs → policy-scaffold-config-CwY0QZC0.mjs} +8 -8
  163. package/dist/policy-scaffold-config-CwY0QZC0.mjs.map +1 -0
  164. package/dist/{project-discovery-BkHpTXDx.mjs → project-discovery-g29vd44a.mjs} +2 -2
  165. package/dist/{project-discovery-BkHpTXDx.mjs.map → project-discovery-g29vd44a.mjs.map} +1 -1
  166. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs → pullChunkedCustomSiloOutstandingIdentifiers-7qvaMN58.mjs} +2 -2
  167. package/dist/{pullChunkedCustomSiloOutstandingIdentifiers-DbybCU2T.mjs.map → pullChunkedCustomSiloOutstandingIdentifiers-7qvaMN58.mjs.map} +1 -1
  168. package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs → pullManualEnrichmentIdentifiersToCsv-CWPs7VeX.mjs} +2 -2
  169. package/dist/{pullManualEnrichmentIdentifiersToCsv-CxTPUfpV.mjs.map → pullManualEnrichmentIdentifiersToCsv-CWPs7VeX.mjs.map} +1 -1
  170. package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs → pushCronIdentifiersFromCsv-DQoliMdQ.mjs} +2 -2
  171. package/dist/{pushCronIdentifiersFromCsv-CeRVlbFE.mjs.map → pushCronIdentifiersFromCsv-DQoliMdQ.mjs.map} +1 -1
  172. package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs → pushManualEnrichmentIdentifiersFromCsv-R9BXYuFk.mjs} +2 -2
  173. package/dist/{pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs.map → pushManualEnrichmentIdentifiersFromCsv-R9BXYuFk.mjs.map} +1 -1
  174. package/dist/{readTranscendYaml-BfqQbPiT.mjs → readTranscendYaml-D576bvzR.mjs} +2 -2
  175. package/dist/{readTranscendYaml-BfqQbPiT.mjs.map → readTranscendYaml-D576bvzR.mjs.map} +1 -1
  176. package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs → removeUnverifiedRequestIdentifiers-CgnfHdbc.mjs} +2 -2
  177. package/dist/{removeUnverifiedRequestIdentifiers-CV6JGgt_.mjs.map → removeUnverifiedRequestIdentifiers-CgnfHdbc.mjs.map} +1 -1
  178. package/dist/{retryRequestDataSilos-_OThvVwU.mjs → retryRequestDataSilos-BrLLNQqT.mjs} +2 -2
  179. package/dist/{retryRequestDataSilos-_OThvVwU.mjs.map → retryRequestDataSilos-BrLLNQqT.mjs.map} +1 -1
  180. package/dist/runRegalLintStep-DPaMm7Gg.mjs +3 -0
  181. package/dist/runRegalLintStep-DPaMm7Gg.mjs.map +1 -0
  182. package/dist/{scaffold-planning-BrX-pcz6.mjs → scaffold-planning-Bp_yqZWx.mjs} +2 -2
  183. package/dist/{scaffold-planning-BrX-pcz6.mjs.map → scaffold-planning-Bp_yqZWx.mjs.map} +1 -1
  184. package/dist/{skipPreflightJobs-D8og5pKe.mjs → skipPreflightJobs-CqjpB7ug.mjs} +2 -2
  185. package/dist/{skipPreflightJobs-D8og5pKe.mjs.map → skipPreflightJobs-CqjpB7ug.mjs.map} +1 -1
  186. package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs → skipRequestDataSilos-DPi6-XVr.mjs} +2 -2
  187. package/dist/{skipRequestDataSilos-DUQ6AD_O.mjs.map → skipRequestDataSilos-DPi6-XVr.mjs.map} +1 -1
  188. package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs → streamPrivacyRequestsToCsv-DVPQ860_.mjs} +2 -2
  189. package/dist/{streamPrivacyRequestsToCsv-BApu4dvI.mjs.map → streamPrivacyRequestsToCsv-DVPQ860_.mjs.map} +1 -1
  190. package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs → updateConsentManagerVersionToLatest-gJMWny-i.mjs} +2 -2
  191. package/dist/{updateConsentManagerVersionToLatest-BrgPZ5hX.mjs.map → updateConsentManagerVersionToLatest-gJMWny-i.mjs.map} +1 -1
  192. package/dist/{uploadConsents-DRlDHQak.mjs → uploadConsents-5HlMj7EK.mjs} +2 -2
  193. package/dist/{uploadConsents-DRlDHQak.mjs.map → uploadConsents-5HlMj7EK.mjs.map} +1 -1
  194. package/dist/uploadPrivacyRequestsFromCsv-Dh8KEW3n.mjs +2 -0
  195. package/dist/uploadPrivacyRequestsFromCsv-Dh8KEW3n.mjs.map +1 -0
  196. package/dist/{validateTranscendAuth-D-dDINof.mjs → validateTranscendAuth-BrVGfq6X.mjs} +2 -2
  197. package/dist/{validateTranscendAuth-D-dDINof.mjs.map → validateTranscendAuth-BrVGfq6X.mjs.map} +1 -1
  198. package/package.json +22 -22
  199. package/dist/app-BMLQABJX.mjs.map +0 -1
  200. package/dist/codecs-CfcaFoZR.mjs +0 -2
  201. package/dist/codecs-CfcaFoZR.mjs.map +0 -1
  202. package/dist/constants-DlH2vWm_.mjs +0 -2
  203. package/dist/constants-DlH2vWm_.mjs.map +0 -1
  204. package/dist/fetchAllRequests-BI0tFl_a.mjs +0 -2
  205. package/dist/fetchAllRequests-BI0tFl_a.mjs.map +0 -1
  206. package/dist/impl-BEiCEzl_2.mjs.map +0 -1
  207. package/dist/impl-Cb-7C1Ml2.mjs.map +0 -1
  208. package/dist/impl-D6rMLiNB2.mjs.map +0 -1
  209. package/dist/impl-DNOgBcsu.mjs +0 -3
  210. package/dist/impl-DNOgBcsu.mjs.map +0 -1
  211. package/dist/impl-Dd39KsYO.mjs.map +0 -1
  212. package/dist/policy-project-discovery-DTSl0Gfl.mjs.map +0 -1
  213. package/dist/policy-scaffold-config-RpxwwZ2H.mjs.map +0 -1
  214. package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs +0 -2
  215. package/dist/uploadPrivacyRequestsFromCsv-FAGllBdd.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import{o as e}from"./project-discovery-CWRjlFnC.mjs";import{t}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{t as r}from"./missing-manifest-D8y1VL4p.mjs";import{a as i,l as a,n as o,o as s,t as c}from"./project-discovery-BkHpTXDx.mjs";import{n as l,t as u}from"./prompts-BhXfYD6g.mjs";import{t as d}from"./run-captured-process-BjaSDWXG.mjs";import{r as f,t as p}from"./deno-runtime-CB2HBach.mjs";import{t as m}from"./module-graph-CAT8_JCG.mjs";import{CustomFunctionPayloadType as h,CustomFunctionType as g}from"@transcend-io/privacy-types";import{join as _}from"node:path";import v from"colors";import{tmpdir as y}from"node:os";import{Buffer as b}from"node:buffer";import{DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as x,DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as S,GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as C}from"@transcend-io/custom-function-types";import w from"ajv";import{stripVTControlCharacters as T}from"node:util";const E=3e4,D=1024*1024,O=_(y(),`transcend-custom-functions-deno`),k=new w({allErrors:!0,strict:!1}),A={general:k.compile(C),datapoint:k.compile(x),enricher:k.compile(S)};function j(e,t,n){let r=t,i=r.extras??{},a=i.profile,o=e.type??g.General,s=o===g.Dsr&&n!==h.RequestEnricher&&a?.identifier===`{{identifier}}`?{...a,identifier:`example-identifier`}:a,c=i.dataSilo,l=o===g.Dsr?{...i,...s?{profile:s}:{},dataSilo:{title:e.name,description:``,link:``,...c,id:e.dataSiloId??c?.id??`00000000-0000-4000-8000-000000000000`}}:s?{...i,profile:s}:i;return{...r,...Object.keys(l).length>0?{extras:l}:{},coreIdentifier:r.coreIdentifier??{value:`example-identifier`}}}function M(e,t){let n=(e.type??g.General)===g.Dsr?t.payloadType===h.RequestEnricher?A.enricher:A.datapoint:A.general;if(!n(t.payload)){let t=(n.errors??[]).map(e=>`${e.instancePath||`/`} ${e.message??`is invalid`}`).join(`; `);throw Error(`Invalid test payload for "${e.name}": ${t}`)}}function N(e,t,n={}){M(e,t);let r=e.env??{},i=Object.keys(r),o=e.allowedHosts??[];a(e);let s=n.allowNetwork?o.length===0?[`--allow-net=localhost`]:o[0]===`*`?[`--allow-net`]:[`--allow-net=${o.join(`,`)}`]:[],c=(e.type??g.General)===g.Dsr&&t.payloadType===h.RequestEnricher?`enricher`:`default`,l=`data:application/javascript;base64,${b.from(`
1
+ import{o as e}from"./project-discovery-CWRjlFnC.mjs";import{t}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{t as r}from"./missing-manifest-D8y1VL4p.mjs";import{a as i,l as a,n as o,o as s,t as c}from"./project-discovery-g29vd44a.mjs";import{n as l,t as u}from"./prompts-BhXfYD6g.mjs";import{t as d}from"./run-captured-process-BjaSDWXG.mjs";import{r as f,t as p}from"./deno-runtime-CB2HBach.mjs";import{t as m}from"./module-graph-CAT8_JCG.mjs";import{CustomFunctionPayloadType as h,CustomFunctionType as g}from"@transcend-io/privacy-types";import{join as _}from"node:path";import v from"colors";import{tmpdir as y}from"node:os";import{Buffer as b}from"node:buffer";import{DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as x,DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as S,GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA as C}from"@transcend-io/custom-function-types";import w from"ajv";import{stripVTControlCharacters as T}from"node:util";const E=3e4,D=1024*1024,O=_(y(),`transcend-custom-functions-deno`),k=new w({allErrors:!0,strict:!1}),A={general:k.compile(C),datapoint:k.compile(x),enricher:k.compile(S)};function j(e,t,n){let r=t,i=r.extras??{},a=i.profile,o=e.type??g.General,s=o===g.Dsr&&n!==h.RequestEnricher&&a?.identifier===`{{identifier}}`?{...a,identifier:`example-identifier`}:a,c=i.dataSilo,l=o===g.Dsr?{...i,...s?{profile:s}:{},dataSilo:{title:e.name,description:``,link:``,...c,id:e.dataSiloId??c?.id??`00000000-0000-4000-8000-000000000000`}}:s?{...i,profile:s}:i;return{...r,...Object.keys(l).length>0?{extras:l}:{},coreIdentifier:r.coreIdentifier??{value:`example-identifier`}}}function M(e,t){let n=(e.type??g.General)===g.Dsr?t.payloadType===h.RequestEnricher?A.enricher:A.datapoint:A.general;if(!n(t.payload)){let t=(n.errors??[]).map(e=>`${e.instancePath||`/`} ${e.message??`is invalid`}`).join(`; `);throw Error(`Invalid test payload for "${e.name}": ${t}`)}}function N(e,t,n={}){M(e,t);let r=e.env??{},i=Object.keys(r),o=e.allowedHosts??[];a(e);let s=n.allowNetwork?o.length===0?[`--allow-net=localhost`]:o[0]===`*`?[`--allow-net`]:[`--allow-net=${o.join(`,`)}`]:[],c=(e.type??g.General)===g.Dsr&&t.payloadType===h.RequestEnricher?`enricher`:`default`,l=`data:application/javascript;base64,${b.from(`
2
2
  const input = JSON.parse(await new Response(Deno.stdin.readable).text());
3
3
  for (const [name, value] of Object.entries(input.functionArgs.environment)) {
4
4
  Deno.env.set(name, value);
@@ -88,4 +88,4 @@ try {
88
88
  `)).filter(e=>{let t=e.codePointAt(0);return t===9||t===10||t>=32&&t!==127&&!(t>=128&&t<=159)}).join(``)}function F(e,t={},n=!1){let r=Object.values(t).filter(e=>e.length>0).map(P).sort((e,t)=>t.length-e.length),i=P(e);if(n){let e=Math.max(0,...r.map(e=>{let t=Math.min(e.length-1,i.length);for(let n=t;n>0;--n)if(i.endsWith(e.slice(0,n)))return n;return 0}));e>0&&(i=i.slice(0,-e))}return r.reduce((e,t)=>e.split(t).join(`[REDACTED]`),i)}function I(e,t=D){let n=b.from(e);if(n.length<=t)return{output:e,truncated:!1};let r=t;for(;r>0&&(n[r]&192)==128;)--r;return{output:n.subarray(0,r).toString(`utf8`),truncated:!0}}function L(e,t){if(!t)return e.length===1?e[0]:void 0;let n=e.filter(e=>e.name===t||e.id===t);if(n.length===0)throw Error(`Custom Function "${t}" was not found in the manifest.`);if(n.length>1)throw Error(`Custom Function selector "${t}" is ambiguous. Pass its manifest ID instead.`);return n[0]}async function R(a,h){n(this.process);try{let n=o(this,{...h?{directory:h}:{},...a.manifest?{manifest:a.manifest}:{}});if(!this.fs.existsSync(n.manifestPath)){let e=this.process.cwd();throw Error(r({cwd:e,manifestPath:n.manifestPath,discoveredManifestPaths:c(this,e),command:`run`}))}let u=i(this.fs.readFileSync(n.manifestPath,`utf8`));if(u.functions.length===0)throw Error(`The Custom Function manifest does not define any functions.`);let g=!a.noInteractive&&!!(this.process.stdin.isTTY&&this.process.stderr.isTTY),_=L(u.functions,a.function);if(!_&&g){let e=await new l(this).select(`Custom Function to run:`,u.functions.map((e,t)=>({name:e.id?`${e.name} (${e.id})`:e.name,value:String(t)})),`0`);_=u.functions[Number(e)]}if(!_)throw Error(`Select a Custom Function with --function in a non-interactive invocation.`);let{config:y,sourcePath:x}=s(n.manifestPath,_,t(a.variables),t=>e(this,n.manifestDirectory,t));if(!y.testPayloads||y.testPayloads.length===0)throw Error(`Custom Function "${y.name}" has no test payloads. Add test-payload or test-payloads to its manifest entry.`);let S=this.fs.existsSync(n.denoConfigPath)?{denoConfigPath:n.denoConfigPath}:{},C=y.testPayloads.map(e=>({testPayload:e,invocation:N(y,e,{...S,allowNetwork:a.allowNetwork})})),w=await d(`deno`,[`--version`],{cwd:n.manifestDirectory},this);if(w.error?.code===`ENOENT`)throw Error(`Deno 2.x is required. Install it from ${p}`);if(w.code!==0)throw Error(`Deno was found, but its version could not be determined.`);let T=f(w.stdout);if(T.level===`error`)throw Error(T.message);T.level===`warning`&&this.logger.warn(T.message);let E=await d(`deno`,[`info`,`--json`,...S.denoConfigPath?[`--config=${S.denoConfigPath}`]:[`--no-config`],x],{cwd:n.manifestDirectory},this);if(E.code!==0)throw Error(`Could not inspect Custom Function runtime imports: ${E.stderr.trim()||`Deno exited with code ${E.code}`}`);let O=m(E.stdout);if(O.length>0)throw Error(`Custom Functions must be self-contained. Local or import-map runtime dependencies are not deployed: ${O.join(`, `)}`);this.logger.warn(v.yellow(`Local simulator: sdk.fetch calls are logged and return HTTP 200 without sending a request; KV state starts empty for each payload.`)),a.allowNetwork?this.logger.warn(v.yellow(`Network enabled: native fetch can make real requests to ${y.allowedHosts?.length?y.allowedHosts.join(`, `):`localhost`}.`)):y.allowedHosts?.length&&this.logger.warn(v.yellow(`Native network access is disabled. Pass --allowNetwork to permit calls to allowed-hosts.`));let k=!1;for(let[e,{invocation:t,testPayload:r}]of C.entries()){let i=r.payloadType??`payload ${e+1}`;this.logger.info(`\n${v.bold(`Running "${y.name}" (${i})`)}`);let a=await d(`deno`,t.args,{cwd:n.manifestDirectory,input:t.input,env:t.env,timeoutMs:t.timeoutMs,maxOutputBytes:D+Math.max(0,...Object.values(y.env??{}).map(e=>b.byteLength(e)))},this),o=y.env??{},s=I(F(a.stdout,o,a.stdoutTruncated)),c=I(F(a.stderr,o,a.stderrTruncated));if(s.output&&this.process.stdout.write(s.output.endsWith(`
89
89
  `)?s.output:`${s.output}\n`),c.output&&this.process.stderr.write(c.output.endsWith(`
90
90
  `)?c.output:`${c.output}\n`),(a.outputTruncated||s.truncated||c.truncated)&&this.logger.warn(v.yellow(`Simulator output was truncated after ${D} bytes per stream.`)),a.code===0)this.logger.info(v.green(`Passed "${y.name}" (${i})`));else{k=!0;let e=a.timedOut?`timed out after ${t.timeoutMs}ms`:a.inputError?`could not send the fixture to Deno: ${a.inputError.message}`:a.error?`could not start Deno: ${a.error.message}`:a.signal?`was terminated with ${a.signal}`:`exited with code ${a.code}`;this.logger.error(v.red(`Failed "${y.name}" (${i}): ${e}`))}}k&&(this.process.exitCode=1)}catch(e){throw e instanceof u&&this.process.exit(130),e}}export{R as run};
91
- //# sourceMappingURL=impl-DhXzxQDN2.mjs.map
91
+ //# sourceMappingURL=impl-CRif3TpB2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DhXzxQDN2.mjs","names":[],"sources":["../src/lib/custom-functions/local-simulator.ts","../src/commands/custom-functions/run/impl.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport {\n DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n} from '@transcend-io/custom-function-types';\nimport { CustomFunctionPayloadType, CustomFunctionType } from '@transcend-io/privacy-types';\nimport Ajv from 'ajv';\n\nimport { validateCustomFunctionExecutionContext } from './execution-context.js';\nimport type { CustomFunctionManifestConfig } from './manifest.js';\n\n/** Value injected when production-only identifiers are absent from a fixture. */\nexport const LOCAL_SIMULATOR_IDENTIFIER = 'example-identifier';\n\n/** Synthetic data silo used by local DSR simulations. */\nexport const LOCAL_SIMULATOR_DATA_SILO_ID = '00000000-0000-4000-8000-000000000000';\n\n/** Default local execution timeout. */\nexport const LOCAL_SIMULATOR_TIMEOUT_MS = 30_000;\n\n/** Maximum stdout and stderr retained from one local invocation. */\nexport const LOCAL_SIMULATOR_MAX_OUTPUT_BYTES = 1024 * 1024;\n\n/** Isolated dependency cache readable by simulated functions. */\nexport const LOCAL_SIMULATOR_DENO_DIR = join(tmpdir(), 'transcend-custom-functions-deno');\n\nconst ajv = new Ajv({ allErrors: true, strict: false });\nconst payloadValidators = {\n general: ajv.compile(GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n datapoint: ajv.compile(DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n enricher: ajv.compile(DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n};\n\n/** Complete local Deno process invocation. */\nexport interface LocalSimulatorInvocation {\n /** Deno CLI arguments. */\n args: string[];\n /** JSON sent privately over stdin. */\n input: string;\n /** Minimal environment exposed to the process. */\n env: NodeJS.ProcessEnv;\n /** Maximum execution time. */\n timeoutMs: number;\n}\n\n/**\n * Runtime wrapper modeled after Sombra's Deno executor.\n *\n * The local SDK intentionally simulates customer-ingress calls rather than\n * sending authenticated requests. Native fetch remains governed by Deno's\n * allow-net permissions.\n */\nconst LOCAL_SIMULATOR_SOURCE = `\nconst input = JSON.parse(await new Response(Deno.stdin.readable).text());\nfor (const [name, value] of Object.entries(input.functionArgs.environment)) {\n Deno.env.set(name, value);\n}\n\nclass KV {\n constructor() {\n this.store = {};\n }\n\n get(key) {\n return Promise.resolve(key in this.store ? this.store[key] : null);\n }\n\n async set(key, value) {\n if (typeof value !== 'string') throw new Error('Value must be of type string');\n if (value.length > 2048) throw new Error('Cannot store value greater than 2048 bytes');\n if (key.length > 128) throw new Error('Key length cannot be greater than 128 bytes');\n if (!(key in this.store) && Object.keys(this.store).length >= 128) {\n throw new Error('Maximum number of keys allowed is 128');\n }\n this.store[key] = value;\n }\n\n keys() {\n return Promise.resolve(Object.keys(this.store));\n }\n\n has(key) {\n return Promise.resolve(key in this.store);\n }\n\n async del(key) {\n if (!(key in this.store)) return false;\n delete this.store[key];\n return true;\n }\n}\n\nclass SDK {\n constructor(nonce) {\n this.transcendNonce = nonce;\n this.customerIngressBaseUrl = 'local://customer-ingress';\n }\n\n nonce() {\n return this.transcendNonce;\n }\n\n setCustomerIngressUrl(newUrl) {\n this.customerIngressBaseUrl = newUrl;\n }\n\n async ping() {\n await this.fetch('/test', { method: 'GET' });\n }\n\n fetch(path, options = {}) {\n const method = options.method ?? 'GET';\n console.warn(\n \\`[simulator] sdk.fetch \\${method} \\${path} -> HTTP 200 (request not sent)\\`,\n );\n return Promise.resolve(new Response(null, { status: 200, statusText: 'OK' }));\n }\n}\n\ntry {\n const custom = await import(\n \\`data:application/typescript;base64,\\${input.base64Function}\\`\n );\n if (!(input.functionToRun in custom)) {\n throw new Error(\n \\`Custom Function does not export \"\\${input.functionToRun}\" for this payload\\`,\n );\n }\n await custom[input.functionToRun]({\n ...input.functionArgs,\n sdk: new SDK(input.functionArgs.nonce),\n kv: new KV(),\n });\n Deno.exit(0);\n} catch (error) {\n console.error(error);\n Deno.exit(1);\n}\n`;\n\n/**\n * Add values that Sombra normally injects into test payloads.\n *\n * @param config - Selected manifest function\n * @param payload - Parsed test fixture\n * @param payloadType - Optional DSR export selector\n * @returns Prepared local handler payload\n */\nexport function prepareLocalSimulatorPayload(\n config: Pick<CustomFunctionManifestConfig, 'dataSiloId' | 'name' | 'type'>,\n payload: object,\n payloadType?: CustomFunctionPayloadType,\n): object {\n const record = payload as {\n /** Runtime core identifier. */\n coreIdentifier?: { value: string };\n /** DSR metadata. */\n extras?: Record<string, unknown>;\n };\n const extras = record.extras ?? {};\n const profile = extras['profile'] as { identifier?: unknown } | undefined;\n const type = config.type ?? CustomFunctionType.General;\n const isDataPoint =\n type === CustomFunctionType.Dsr && payloadType !== CustomFunctionPayloadType.RequestEnricher;\n const preparedProfile =\n isDataPoint && profile?.identifier === '{{identifier}}'\n ? { ...profile, identifier: LOCAL_SIMULATOR_IDENTIFIER }\n : profile;\n const dataSilo = extras['dataSilo'] as Record<string, unknown> | undefined;\n const preparedExtras =\n type === CustomFunctionType.Dsr\n ? {\n ...extras,\n ...(preparedProfile ? { profile: preparedProfile } : {}),\n dataSilo: {\n title: config.name,\n description: '',\n link: '',\n ...dataSilo,\n id: config.dataSiloId ?? dataSilo?.['id'] ?? LOCAL_SIMULATOR_DATA_SILO_ID,\n },\n }\n : preparedProfile\n ? { ...extras, profile: preparedProfile }\n : extras;\n return {\n ...record,\n ...(Object.keys(preparedExtras).length > 0 ? { extras: preparedExtras } : {}),\n coreIdentifier: record.coreIdentifier ?? { value: LOCAL_SIMULATOR_IDENTIFIER },\n };\n}\n\n/**\n * Validate a fixture with the same published schemas used by `check`.\n *\n * @param config - Selected manifest function\n * @param testPayload - Fixture and optional DSR export selector\n */\nfunction validateLocalSimulatorPayload(\n config: CustomFunctionManifestConfig,\n testPayload: NonNullable<CustomFunctionManifestConfig['testPayloads']>[number],\n): void {\n const type = config.type ?? CustomFunctionType.General;\n const validate =\n type !== CustomFunctionType.Dsr\n ? payloadValidators.general\n : testPayload.payloadType === CustomFunctionPayloadType.RequestEnricher\n ? payloadValidators.enricher\n : payloadValidators.datapoint;\n if (!validate(testPayload.payload)) {\n const details = (validate.errors ?? [])\n .map((error) => `${error.instancePath || '/'} ${error.message ?? 'is invalid'}`)\n .join('; ');\n throw new Error(`Invalid test payload for \"${config.name}\": ${details}`);\n }\n}\n\n/**\n * Build one constrained Deno invocation for a test fixture.\n *\n * @param config - Selected manifest function\n * @param testPayload - Fixture and optional DSR export selector\n * @param options - Discovered Deno configuration\n * @returns Process arguments, input, environment, and timeout\n */\nexport function buildLocalSimulatorInvocation(\n config: CustomFunctionManifestConfig,\n testPayload: NonNullable<CustomFunctionManifestConfig['testPayloads']>[number],\n options: {\n /** Existing deno.json or deno.jsonc path. */\n denoConfigPath?: string;\n /** Permit real native fetch calls to manifest allowed hosts. */\n allowNetwork?: boolean;\n } = {},\n): LocalSimulatorInvocation {\n validateLocalSimulatorPayload(config, testPayload);\n const environment = config.env ?? {};\n const envNames = Object.keys(environment);\n const allowedHosts = config.allowedHosts ?? [];\n validateCustomFunctionExecutionContext(config);\n const allowNetArgs = options.allowNetwork\n ? allowedHosts.length === 0\n ? ['--allow-net=localhost']\n : allowedHosts[0] === '*'\n ? ['--allow-net']\n : [`--allow-net=${allowedHosts.join(',')}`]\n : [];\n const type = config.type ?? CustomFunctionType.General;\n const functionToRun =\n type === CustomFunctionType.Dsr &&\n testPayload.payloadType === CustomFunctionPayloadType.RequestEnricher\n ? 'enricher'\n : 'default';\n const runnerUrl = `data:application/javascript;base64,${Buffer.from(\n LOCAL_SIMULATOR_SOURCE,\n ).toString('base64')}`;\n const args = [\n 'run',\n '--no-check',\n '--no-prompt',\n '--no-lock',\n '--node-modules-dir=none',\n '--vendor=false',\n `--allow-read=${LOCAL_SIMULATOR_DENO_DIR}`,\n ...(envNames.length > 0 ? [`--allow-env=${envNames.join(',')}`] : []),\n ...(options.denoConfigPath ? [`--config=${options.denoConfigPath}`] : ['--no-config']),\n ...allowNetArgs,\n ...(config.allowThirdPartyImports ? [] : ['--no-remote', '--no-npm']),\n runnerUrl,\n ];\n return {\n args,\n input: JSON.stringify({\n base64Function: Buffer.from(config.code).toString('base64'),\n functionToRun,\n functionArgs: {\n environment,\n payload: prepareLocalSimulatorPayload(config, testPayload.payload, testPayload.payloadType),\n nonce: 'local-simulator',\n },\n }),\n env: {\n ...environment,\n DENO_DIR: LOCAL_SIMULATOR_DENO_DIR,\n DENO_TLS_CA_STORE: 'system',\n NO_COLOR: '1',\n },\n timeoutMs:\n config.timeoutMs && config.timeoutMs > 0\n ? Math.min(config.timeoutMs, LOCAL_SIMULATOR_TIMEOUT_MS)\n : LOCAL_SIMULATOR_TIMEOUT_MS,\n };\n}\n\n/**\n * Remove terminal controls and opaque data URLs from local output.\n *\n * @param value - Untrusted terminal text\n * @returns Plain printable text\n */\nfunction sanitizeLocalSimulatorText(value: string): string {\n return Array.from(\n stripVTControlCharacters(\n value.replace(\n /data:application\\/(?:javascript|typescript);base64,[A-Za-z\\d+/=]+/gu,\n '<local-module>',\n ),\n ).replace(/\\r(?!\\n)/gu, '\\n'),\n )\n .filter((character) => {\n const code = character.codePointAt(0)!;\n return (\n code === 9 || code === 10 || (code >= 32 && code !== 127 && !(code >= 128 && code <= 159))\n );\n })\n .join('');\n}\n\n/**\n * Redact configured environment values from captured local output.\n *\n * @param output - Captured stdout or stderr\n * @param environment - User-defined environment\n * @param sourceTruncated - Whether capture stopped before the stream ended\n * @returns Redacted output\n */\nexport function redactLocalSimulatorOutput(\n output: string,\n environment: Record<string, string> = {},\n sourceTruncated = false,\n): string {\n const values = Object.values(environment)\n .filter((value) => value.length > 0)\n .map(sanitizeLocalSimulatorText)\n .sort((left, right) => right.length - left.length);\n let sanitized = sanitizeLocalSimulatorText(output);\n if (sourceTruncated) {\n const trailingFragmentLength = Math.max(\n 0,\n ...values.map((value) => {\n const maximum = Math.min(value.length - 1, sanitized.length);\n for (let length = maximum; length > 0; length -= 1) {\n if (sanitized.endsWith(value.slice(0, length))) {\n return length;\n }\n }\n return 0;\n }),\n );\n if (trailingFragmentLength > 0) {\n sanitized = sanitized.slice(0, -trailingFragmentLength);\n }\n }\n return values.reduce((redacted, value) => redacted.split(value).join('[REDACTED]'), sanitized);\n}\n\n/**\n * Truncate sanitized output without splitting a UTF-8 code point.\n *\n * @param output - Sanitized and redacted output\n * @param maxBytes - Maximum output size\n * @returns Bounded output and whether truncation occurred\n */\nexport function truncateLocalSimulatorOutput(\n output: string,\n maxBytes = LOCAL_SIMULATOR_MAX_OUTPUT_BYTES,\n): { output: string; truncated: boolean } {\n const bytes = Buffer.from(output);\n if (bytes.length <= maxBytes) {\n return { output, truncated: false };\n }\n let end = maxBytes;\n while (end > 0 && (bytes[end]! & 0b1100_0000) === 0b1000_0000) {\n end -= 1;\n }\n return {\n output: bytes.subarray(0, end).toString('utf8'),\n truncated: true,\n };\n}\n","import { Buffer } from 'node:buffer';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { runCapturedProcess } from '../../../lib/cli/run-captured-process.js';\nimport {\n DENO_INSTALL_URL,\n getDenoRuntimeCompatibility,\n SUPPORTED_DENO_MAJOR_VERSION,\n} from '../../../lib/custom-functions/deno-runtime.js';\nimport {\n buildLocalSimulatorInvocation,\n LOCAL_SIMULATOR_MAX_OUTPUT_BYTES,\n redactLocalSimulatorOutput,\n truncateLocalSimulatorOutput,\n} from '../../../lib/custom-functions/local-simulator.js';\nimport {\n parseCustomFunctionsManifest,\n readCustomFunctionManifestEntry,\n type CustomFunctionManifestEntry,\n} from '../../../lib/custom-functions/manifest.js';\nimport { formatMissingManifestMessage } from '../../../lib/custom-functions/missing-manifest.js';\nimport { findNonSelfContainedRuntimeImports } from '../../../lib/custom-functions/module-graph.js';\nimport {\n discoverCustomFunctionManifests,\n discoverCustomFunctionProject,\n} from '../../../lib/custom-functions/project-discovery.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { assertPathPhysicallyContained } from '../../../lib/scaffolding/path-safety.js';\nimport { PromptCancelledError, ScaffoldPrompts } from '../../../lib/scaffolding/prompts.js';\n\n/** Flags accepted by `transcend custom-functions run`. */\nexport interface CustomFunctionRunFlags {\n /** Explicit manifest path. */\n manifest?: string;\n /** Exact function name. */\n function?: string;\n /** Manifest variable substitutions. */\n variables: string;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Permit native network calls to allowed hosts. */\n allowNetwork: boolean;\n}\n\n/**\n * Select one function by exact name or ID.\n *\n * @param configs - Hydrated manifest functions\n * @param selector - Optional exact name or ID\n * @returns Selected function, or undefined when interactive selection is needed\n */\nfunction selectNamedFunction<Config extends Pick<CustomFunctionManifestEntry, 'id' | 'name'>>(\n configs: readonly Config[],\n selector: string | undefined,\n): Config | undefined {\n if (!selector) {\n return configs.length === 1 ? configs[0] : undefined;\n }\n const matches = configs.filter((config) => config.name === selector || config.id === selector);\n if (matches.length === 0) {\n throw new Error(`Custom Function \"${selector}\" was not found in the manifest.`);\n }\n if (matches.length > 1) {\n throw new Error(\n `Custom Function selector \"${selector}\" is ambiguous. Pass its manifest ID instead.`,\n );\n }\n return matches[0];\n}\n\n/**\n * Run one manifest function in the credential-free local Deno simulator.\n *\n * @param this - CLI context\n * @param flags - Selection and manifest flags\n * @param directory - Optional project directory\n */\nexport async function run(\n this: LocalContext,\n flags: CustomFunctionRunFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const state = discoverCustomFunctionProject(this, {\n ...(directory ? { directory } : {}),\n ...(flags.manifest ? { manifest: flags.manifest } : {}),\n });\n if (!this.fs.existsSync(state.manifestPath)) {\n const cwd = this.process.cwd();\n throw new Error(\n formatMissingManifestMessage({\n cwd,\n manifestPath: state.manifestPath,\n discoveredManifestPaths: discoverCustomFunctionManifests(this, cwd),\n command: 'run',\n }),\n );\n }\n\n const parsedManifest = parseCustomFunctionsManifest(\n this.fs.readFileSync(state.manifestPath, 'utf8'),\n );\n if (parsedManifest.functions.length === 0) {\n throw new Error('The Custom Function manifest does not define any functions.');\n }\n const interactive =\n !flags.noInteractive && Boolean(this.process.stdin.isTTY && this.process.stderr.isTTY);\n let selectedEntry = selectNamedFunction(parsedManifest.functions, flags.function);\n if (!selectedEntry && interactive) {\n const prompts = new ScaffoldPrompts(this);\n const selectedIndex = await prompts.select(\n 'Custom Function to run:',\n parsedManifest.functions.map((entry, index) => ({\n name: entry.id ? `${entry.name} (${entry.id})` : entry.name,\n value: String(index),\n })),\n '0',\n );\n selectedEntry = parsedManifest.functions[Number(selectedIndex)];\n }\n if (!selectedEntry) {\n throw new Error('Select a Custom Function with --function in a non-interactive invocation.');\n }\n const { config: selected, sourcePath } = readCustomFunctionManifestEntry(\n state.manifestPath,\n selectedEntry,\n parseVariablesFromString(flags.variables),\n (path) => assertPathPhysicallyContained(this, state.manifestDirectory, path),\n );\n if (!selected.testPayloads || selected.testPayloads.length === 0) {\n throw new Error(\n `Custom Function \"${selected.name}\" has no test payloads. Add test-payload or test-payloads to its manifest entry.`,\n );\n }\n const denoConfig = this.fs.existsSync(state.denoConfigPath)\n ? { denoConfigPath: state.denoConfigPath }\n : {};\n const simulations = selected.testPayloads.map((testPayload) => ({\n testPayload,\n invocation: buildLocalSimulatorInvocation(selected, testPayload, {\n ...denoConfig,\n allowNetwork: flags.allowNetwork,\n }),\n }));\n\n const denoVersion = await runCapturedProcess(\n 'deno',\n ['--version'],\n { cwd: state.manifestDirectory },\n this,\n );\n if (denoVersion.error?.code === 'ENOENT') {\n throw new Error(\n `Deno ${SUPPORTED_DENO_MAJOR_VERSION}.x is required. Install it from ${DENO_INSTALL_URL}`,\n );\n }\n if (denoVersion.code !== 0) {\n throw new Error('Deno was found, but its version could not be determined.');\n }\n const compatibility = getDenoRuntimeCompatibility(denoVersion.stdout);\n if (compatibility.level === 'error') {\n throw new Error(compatibility.message);\n }\n if (compatibility.level === 'warning') {\n this.logger.warn(compatibility.message);\n }\n const moduleGraph = await runCapturedProcess(\n 'deno',\n [\n 'info',\n '--json',\n ...(denoConfig.denoConfigPath\n ? [`--config=${denoConfig.denoConfigPath}`]\n : ['--no-config']),\n sourcePath,\n ],\n { cwd: state.manifestDirectory },\n this,\n );\n if (moduleGraph.code !== 0) {\n throw new Error(\n `Could not inspect Custom Function runtime imports: ${\n moduleGraph.stderr.trim() || `Deno exited with code ${moduleGraph.code}`\n }`,\n );\n }\n const unsupportedImports = findNonSelfContainedRuntimeImports(moduleGraph.stdout);\n if (unsupportedImports.length > 0) {\n throw new Error(\n `Custom Functions must be self-contained. Local or import-map runtime dependencies are not deployed: ${unsupportedImports.join(\n ', ',\n )}`,\n );\n }\n\n this.logger.warn(\n colors.yellow(\n 'Local simulator: sdk.fetch calls are logged and return HTTP 200 without sending a request; KV state starts empty for each payload.',\n ),\n );\n if (flags.allowNetwork) {\n this.logger.warn(\n colors.yellow(\n `Network enabled: native fetch can make real requests to ${\n selected.allowedHosts?.length ? selected.allowedHosts.join(', ') : 'localhost'\n }.`,\n ),\n );\n } else if (selected.allowedHosts?.length) {\n this.logger.warn(\n colors.yellow(\n 'Native network access is disabled. Pass --allowNetwork to permit calls to allowed-hosts.',\n ),\n );\n }\n let failed = false;\n for (const [index, { invocation, testPayload }] of simulations.entries()) {\n const label = testPayload.payloadType ?? `payload ${index + 1}`;\n this.logger.info(`\\n${colors.bold(`Running \"${selected.name}\" (${label})`)}`);\n const result = await runCapturedProcess(\n 'deno',\n invocation.args,\n {\n cwd: state.manifestDirectory,\n input: invocation.input,\n env: invocation.env,\n timeoutMs: invocation.timeoutMs,\n maxOutputBytes:\n LOCAL_SIMULATOR_MAX_OUTPUT_BYTES +\n Math.max(\n 0,\n ...Object.values(selected.env ?? {}).map((value) => Buffer.byteLength(value)),\n ),\n },\n this,\n );\n const environment = selected.env ?? {};\n const stdout = truncateLocalSimulatorOutput(\n redactLocalSimulatorOutput(result.stdout, environment, result.stdoutTruncated),\n );\n const stderr = truncateLocalSimulatorOutput(\n redactLocalSimulatorOutput(result.stderr, environment, result.stderrTruncated),\n );\n if (stdout.output) {\n this.process.stdout.write(\n stdout.output.endsWith('\\n') ? stdout.output : `${stdout.output}\\n`,\n );\n }\n if (stderr.output) {\n this.process.stderr.write(\n stderr.output.endsWith('\\n') ? stderr.output : `${stderr.output}\\n`,\n );\n }\n if (result.outputTruncated || stdout.truncated || stderr.truncated) {\n this.logger.warn(\n colors.yellow(\n `Simulator output was truncated after ${LOCAL_SIMULATOR_MAX_OUTPUT_BYTES} bytes per stream.`,\n ),\n );\n }\n if (result.code === 0) {\n this.logger.info(colors.green(`Passed \"${selected.name}\" (${label})`));\n } else {\n failed = true;\n const detail = result.timedOut\n ? `timed out after ${invocation.timeoutMs}ms`\n : result.inputError\n ? `could not send the fixture to Deno: ${result.inputError.message}`\n : result.error\n ? `could not start Deno: ${result.error.message}`\n : result.signal\n ? `was terminated with ${result.signal}`\n : `exited with code ${result.code}`;\n this.logger.error(colors.red(`Failed \"${selected.name}\" (${label}): ${detail}`));\n }\n }\n if (failed) {\n this.process.exitCode = 1;\n }\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"w+BAiBA,MAMa,EAA6B,IAG7B,EAAmC,KAAO,KAG1C,EAA2B,EAAK,GAAQ,CAAE,kCAAkC,CAEnF,EAAM,IAAI,EAAI,CAAE,UAAW,GAAM,OAAQ,GAAO,CAAC,CACjD,EAAoB,CACxB,QAAS,EAAI,QAAQ,EAAuC,CAC5D,UAAW,EAAI,QAAQ,EAA6C,CACpE,SAAU,EAAI,QAAQ,EAAoD,CAC3E,CAqHD,SAAgB,EACd,EACA,EACA,EACQ,CACR,IAAM,EAAS,EAMT,EAAS,EAAO,QAAU,EAAE,CAC5B,EAAU,EAAO,QACjB,EAAO,EAAO,MAAQ,EAAmB,QAGzC,EADJ,IAAS,EAAmB,KAAO,IAAgB,EAA0B,iBAE9D,GAAS,aAAe,iBACnC,CAAE,GAAG,EAAS,WAAY,qBAA4B,CACtD,EACA,EAAW,EAAO,SAClB,EACJ,IAAS,EAAmB,IACxB,CACE,GAAG,EACH,GAAI,EAAkB,CAAE,QAAS,EAAiB,CAAG,EAAE,CACvD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,GAAG,OAAO,OAAO,EAAS,KAAO,EAAE,CAAC,CAAC,IAAK,GAAU,EAAO,WAAW,EAAM,CAAC,CAC9E,CACJ,CACD,KACD,CACK,EAAc,EAAS,KAAO,EAAE,CAChC,EAAS,EACb,EAA2B,EAAO,OAAQ,EAAa,EAAO,gBAAgB,CAC/E,CACK,EAAS,EACb,EAA2B,EAAO,OAAQ,EAAa,EAAO,gBAAgB,CAC/E,CAkBD,GAjBI,EAAO,QACT,KAAK,QAAQ,OAAO,MAClB,EAAO,OAAO,SAAS;EAAK,CAAG,EAAO,OAAS,GAAG,EAAO,OAAO,IACjE,CAEC,EAAO,QACT,KAAK,QAAQ,OAAO,MAClB,EAAO,OAAO,SAAS;EAAK,CAAG,EAAO,OAAS,GAAG,EAAO,OAAO,IACjE,EAEC,EAAO,iBAAmB,EAAO,WAAa,EAAO,YACvD,KAAK,OAAO,KACV,EAAO,OACL,wCAAwC,EAAiC,oBAC1E,CACF,CAEC,EAAO,OAAS,EAClB,KAAK,OAAO,KAAK,EAAO,MAAM,WAAW,EAAS,KAAK,KAAK,EAAM,GAAG,CAAC,KACjE,CACL,EAAS,GACT,IAAM,EAAS,EAAO,SAClB,mBAAmB,EAAW,UAAU,IACxC,EAAO,WACL,uCAAuC,EAAO,WAAW,UACzD,EAAO,MACL,yBAAyB,EAAO,MAAM,UACtC,EAAO,OACL,uBAAuB,EAAO,SAC9B,oBAAoB,EAAO,OACrC,KAAK,OAAO,MAAM,EAAO,IAAI,WAAW,EAAS,KAAK,KAAK,EAAM,KAAK,IAAS,CAAC,EAGhF,IACF,KAAK,QAAQ,SAAW,SAEnB,EAAO,CAId,MAHI,aAAiB,GACnB,KAAK,QAAQ,KAAK,IAAI,CAElB"}
1
+ {"version":3,"file":"impl-CRif3TpB2.mjs","names":[],"sources":["../src/lib/custom-functions/local-simulator.ts","../src/commands/custom-functions/run/impl.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport {\n DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA,\n} from '@transcend-io/custom-function-types';\nimport { CustomFunctionPayloadType, CustomFunctionType } from '@transcend-io/privacy-types';\nimport Ajv from 'ajv';\n\nimport { validateCustomFunctionExecutionContext } from './execution-context.js';\nimport type { CustomFunctionManifestConfig } from './manifest.js';\n\n/** Value injected when production-only identifiers are absent from a fixture. */\nexport const LOCAL_SIMULATOR_IDENTIFIER = 'example-identifier';\n\n/** Synthetic data silo used by local DSR simulations. */\nexport const LOCAL_SIMULATOR_DATA_SILO_ID = '00000000-0000-4000-8000-000000000000';\n\n/** Default local execution timeout. */\nexport const LOCAL_SIMULATOR_TIMEOUT_MS = 30_000;\n\n/** Maximum stdout and stderr retained from one local invocation. */\nexport const LOCAL_SIMULATOR_MAX_OUTPUT_BYTES = 1024 * 1024;\n\n/** Isolated dependency cache readable by simulated functions. */\nexport const LOCAL_SIMULATOR_DENO_DIR = join(tmpdir(), 'transcend-custom-functions-deno');\n\nconst ajv = new Ajv({ allErrors: true, strict: false });\nconst payloadValidators = {\n general: ajv.compile(GENERAL_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n datapoint: ajv.compile(DSR_DATAPOINT_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n enricher: ajv.compile(DSR_REQUEST_ENRICHER_CUSTOM_FUNCTION_PAYLOAD_SCHEMA),\n};\n\n/** Complete local Deno process invocation. */\nexport interface LocalSimulatorInvocation {\n /** Deno CLI arguments. */\n args: string[];\n /** JSON sent privately over stdin. */\n input: string;\n /** Minimal environment exposed to the process. */\n env: NodeJS.ProcessEnv;\n /** Maximum execution time. */\n timeoutMs: number;\n}\n\n/**\n * Runtime wrapper modeled after Sombra's Deno executor.\n *\n * The local SDK intentionally simulates customer-ingress calls rather than\n * sending authenticated requests. Native fetch remains governed by Deno's\n * allow-net permissions.\n */\nconst LOCAL_SIMULATOR_SOURCE = `\nconst input = JSON.parse(await new Response(Deno.stdin.readable).text());\nfor (const [name, value] of Object.entries(input.functionArgs.environment)) {\n Deno.env.set(name, value);\n}\n\nclass KV {\n constructor() {\n this.store = {};\n }\n\n get(key) {\n return Promise.resolve(key in this.store ? this.store[key] : null);\n }\n\n async set(key, value) {\n if (typeof value !== 'string') throw new Error('Value must be of type string');\n if (value.length > 2048) throw new Error('Cannot store value greater than 2048 bytes');\n if (key.length > 128) throw new Error('Key length cannot be greater than 128 bytes');\n if (!(key in this.store) && Object.keys(this.store).length >= 128) {\n throw new Error('Maximum number of keys allowed is 128');\n }\n this.store[key] = value;\n }\n\n keys() {\n return Promise.resolve(Object.keys(this.store));\n }\n\n has(key) {\n return Promise.resolve(key in this.store);\n }\n\n async del(key) {\n if (!(key in this.store)) return false;\n delete this.store[key];\n return true;\n }\n}\n\nclass SDK {\n constructor(nonce) {\n this.transcendNonce = nonce;\n this.customerIngressBaseUrl = 'local://customer-ingress';\n }\n\n nonce() {\n return this.transcendNonce;\n }\n\n setCustomerIngressUrl(newUrl) {\n this.customerIngressBaseUrl = newUrl;\n }\n\n async ping() {\n await this.fetch('/test', { method: 'GET' });\n }\n\n fetch(path, options = {}) {\n const method = options.method ?? 'GET';\n console.warn(\n \\`[simulator] sdk.fetch \\${method} \\${path} -> HTTP 200 (request not sent)\\`,\n );\n return Promise.resolve(new Response(null, { status: 200, statusText: 'OK' }));\n }\n}\n\ntry {\n const custom = await import(\n \\`data:application/typescript;base64,\\${input.base64Function}\\`\n );\n if (!(input.functionToRun in custom)) {\n throw new Error(\n \\`Custom Function does not export \"\\${input.functionToRun}\" for this payload\\`,\n );\n }\n await custom[input.functionToRun]({\n ...input.functionArgs,\n sdk: new SDK(input.functionArgs.nonce),\n kv: new KV(),\n });\n Deno.exit(0);\n} catch (error) {\n console.error(error);\n Deno.exit(1);\n}\n`;\n\n/**\n * Add values that Sombra normally injects into test payloads.\n *\n * @param config - Selected manifest function\n * @param payload - Parsed test fixture\n * @param payloadType - Optional DSR export selector\n * @returns Prepared local handler payload\n */\nexport function prepareLocalSimulatorPayload(\n config: Pick<CustomFunctionManifestConfig, 'dataSiloId' | 'name' | 'type'>,\n payload: object,\n payloadType?: CustomFunctionPayloadType,\n): object {\n const record = payload as {\n /** Runtime core identifier. */\n coreIdentifier?: { value: string };\n /** DSR metadata. */\n extras?: Record<string, unknown>;\n };\n const extras = record.extras ?? {};\n const profile = extras['profile'] as { identifier?: unknown } | undefined;\n const type = config.type ?? CustomFunctionType.General;\n const isDataPoint =\n type === CustomFunctionType.Dsr && payloadType !== CustomFunctionPayloadType.RequestEnricher;\n const preparedProfile =\n isDataPoint && profile?.identifier === '{{identifier}}'\n ? { ...profile, identifier: LOCAL_SIMULATOR_IDENTIFIER }\n : profile;\n const dataSilo = extras['dataSilo'] as Record<string, unknown> | undefined;\n const preparedExtras =\n type === CustomFunctionType.Dsr\n ? {\n ...extras,\n ...(preparedProfile ? { profile: preparedProfile } : {}),\n dataSilo: {\n title: config.name,\n description: '',\n link: '',\n ...dataSilo,\n id: config.dataSiloId ?? dataSilo?.['id'] ?? LOCAL_SIMULATOR_DATA_SILO_ID,\n },\n }\n : preparedProfile\n ? { ...extras, profile: preparedProfile }\n : extras;\n return {\n ...record,\n ...(Object.keys(preparedExtras).length > 0 ? { extras: preparedExtras } : {}),\n coreIdentifier: record.coreIdentifier ?? { value: LOCAL_SIMULATOR_IDENTIFIER },\n };\n}\n\n/**\n * Validate a fixture with the same published schemas used by `check`.\n *\n * @param config - Selected manifest function\n * @param testPayload - Fixture and optional DSR export selector\n */\nfunction validateLocalSimulatorPayload(\n config: CustomFunctionManifestConfig,\n testPayload: NonNullable<CustomFunctionManifestConfig['testPayloads']>[number],\n): void {\n const type = config.type ?? CustomFunctionType.General;\n const validate =\n type !== CustomFunctionType.Dsr\n ? payloadValidators.general\n : testPayload.payloadType === CustomFunctionPayloadType.RequestEnricher\n ? payloadValidators.enricher\n : payloadValidators.datapoint;\n if (!validate(testPayload.payload)) {\n const details = (validate.errors ?? [])\n .map((error) => `${error.instancePath || '/'} ${error.message ?? 'is invalid'}`)\n .join('; ');\n throw new Error(`Invalid test payload for \"${config.name}\": ${details}`);\n }\n}\n\n/**\n * Build one constrained Deno invocation for a test fixture.\n *\n * @param config - Selected manifest function\n * @param testPayload - Fixture and optional DSR export selector\n * @param options - Discovered Deno configuration\n * @returns Process arguments, input, environment, and timeout\n */\nexport function buildLocalSimulatorInvocation(\n config: CustomFunctionManifestConfig,\n testPayload: NonNullable<CustomFunctionManifestConfig['testPayloads']>[number],\n options: {\n /** Existing deno.json or deno.jsonc path. */\n denoConfigPath?: string;\n /** Permit real native fetch calls to manifest allowed hosts. */\n allowNetwork?: boolean;\n } = {},\n): LocalSimulatorInvocation {\n validateLocalSimulatorPayload(config, testPayload);\n const environment = config.env ?? {};\n const envNames = Object.keys(environment);\n const allowedHosts = config.allowedHosts ?? [];\n validateCustomFunctionExecutionContext(config);\n const allowNetArgs = options.allowNetwork\n ? allowedHosts.length === 0\n ? ['--allow-net=localhost']\n : allowedHosts[0] === '*'\n ? ['--allow-net']\n : [`--allow-net=${allowedHosts.join(',')}`]\n : [];\n const type = config.type ?? CustomFunctionType.General;\n const functionToRun =\n type === CustomFunctionType.Dsr &&\n testPayload.payloadType === CustomFunctionPayloadType.RequestEnricher\n ? 'enricher'\n : 'default';\n const runnerUrl = `data:application/javascript;base64,${Buffer.from(\n LOCAL_SIMULATOR_SOURCE,\n ).toString('base64')}`;\n const args = [\n 'run',\n '--no-check',\n '--no-prompt',\n '--no-lock',\n '--node-modules-dir=none',\n '--vendor=false',\n `--allow-read=${LOCAL_SIMULATOR_DENO_DIR}`,\n ...(envNames.length > 0 ? [`--allow-env=${envNames.join(',')}`] : []),\n ...(options.denoConfigPath ? [`--config=${options.denoConfigPath}`] : ['--no-config']),\n ...allowNetArgs,\n ...(config.allowThirdPartyImports ? [] : ['--no-remote', '--no-npm']),\n runnerUrl,\n ];\n return {\n args,\n input: JSON.stringify({\n base64Function: Buffer.from(config.code).toString('base64'),\n functionToRun,\n functionArgs: {\n environment,\n payload: prepareLocalSimulatorPayload(config, testPayload.payload, testPayload.payloadType),\n nonce: 'local-simulator',\n },\n }),\n env: {\n ...environment,\n DENO_DIR: LOCAL_SIMULATOR_DENO_DIR,\n DENO_TLS_CA_STORE: 'system',\n NO_COLOR: '1',\n },\n timeoutMs:\n config.timeoutMs && config.timeoutMs > 0\n ? Math.min(config.timeoutMs, LOCAL_SIMULATOR_TIMEOUT_MS)\n : LOCAL_SIMULATOR_TIMEOUT_MS,\n };\n}\n\n/**\n * Remove terminal controls and opaque data URLs from local output.\n *\n * @param value - Untrusted terminal text\n * @returns Plain printable text\n */\nfunction sanitizeLocalSimulatorText(value: string): string {\n return Array.from(\n stripVTControlCharacters(\n value.replace(\n /data:application\\/(?:javascript|typescript);base64,[A-Za-z\\d+/=]+/gu,\n '<local-module>',\n ),\n ).replace(/\\r(?!\\n)/gu, '\\n'),\n )\n .filter((character) => {\n const code = character.codePointAt(0)!;\n return (\n code === 9 || code === 10 || (code >= 32 && code !== 127 && !(code >= 128 && code <= 159))\n );\n })\n .join('');\n}\n\n/**\n * Redact configured environment values from captured local output.\n *\n * @param output - Captured stdout or stderr\n * @param environment - User-defined environment\n * @param sourceTruncated - Whether capture stopped before the stream ended\n * @returns Redacted output\n */\nexport function redactLocalSimulatorOutput(\n output: string,\n environment: Record<string, string> = {},\n sourceTruncated = false,\n): string {\n const values = Object.values(environment)\n .filter((value) => value.length > 0)\n .map(sanitizeLocalSimulatorText)\n .sort((left, right) => right.length - left.length);\n let sanitized = sanitizeLocalSimulatorText(output);\n if (sourceTruncated) {\n const trailingFragmentLength = Math.max(\n 0,\n ...values.map((value) => {\n const maximum = Math.min(value.length - 1, sanitized.length);\n for (let length = maximum; length > 0; length -= 1) {\n if (sanitized.endsWith(value.slice(0, length))) {\n return length;\n }\n }\n return 0;\n }),\n );\n if (trailingFragmentLength > 0) {\n sanitized = sanitized.slice(0, -trailingFragmentLength);\n }\n }\n return values.reduce((redacted, value) => redacted.split(value).join('[REDACTED]'), sanitized);\n}\n\n/**\n * Truncate sanitized output without splitting a UTF-8 code point.\n *\n * @param output - Sanitized and redacted output\n * @param maxBytes - Maximum output size\n * @returns Bounded output and whether truncation occurred\n */\nexport function truncateLocalSimulatorOutput(\n output: string,\n maxBytes = LOCAL_SIMULATOR_MAX_OUTPUT_BYTES,\n): { output: string; truncated: boolean } {\n const bytes = Buffer.from(output);\n if (bytes.length <= maxBytes) {\n return { output, truncated: false };\n }\n let end = maxBytes;\n while (end > 0 && (bytes[end]! & 0b1100_0000) === 0b1000_0000) {\n end -= 1;\n }\n return {\n output: bytes.subarray(0, end).toString('utf8'),\n truncated: true,\n };\n}\n","import { Buffer } from 'node:buffer';\n\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { runCapturedProcess } from '../../../lib/cli/run-captured-process.js';\nimport {\n DENO_INSTALL_URL,\n getDenoRuntimeCompatibility,\n SUPPORTED_DENO_MAJOR_VERSION,\n} from '../../../lib/custom-functions/deno-runtime.js';\nimport {\n buildLocalSimulatorInvocation,\n LOCAL_SIMULATOR_MAX_OUTPUT_BYTES,\n redactLocalSimulatorOutput,\n truncateLocalSimulatorOutput,\n} from '../../../lib/custom-functions/local-simulator.js';\nimport {\n parseCustomFunctionsManifest,\n readCustomFunctionManifestEntry,\n type CustomFunctionManifestEntry,\n} from '../../../lib/custom-functions/manifest.js';\nimport { formatMissingManifestMessage } from '../../../lib/custom-functions/missing-manifest.js';\nimport { findNonSelfContainedRuntimeImports } from '../../../lib/custom-functions/module-graph.js';\nimport {\n discoverCustomFunctionManifests,\n discoverCustomFunctionProject,\n} from '../../../lib/custom-functions/project-discovery.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { assertPathPhysicallyContained } from '../../../lib/scaffolding/path-safety.js';\nimport { PromptCancelledError, ScaffoldPrompts } from '../../../lib/scaffolding/prompts.js';\n\n/** Flags accepted by `transcend custom-functions run`. */\nexport interface CustomFunctionRunFlags {\n /** Explicit manifest path. */\n manifest?: string;\n /** Exact function name. */\n function?: string;\n /** Manifest variable substitutions. */\n variables: string;\n /** Disable prompts. */\n noInteractive: boolean;\n /** Permit native network calls to allowed hosts. */\n allowNetwork: boolean;\n}\n\n/**\n * Select one function by exact name or ID.\n *\n * @param configs - Hydrated manifest functions\n * @param selector - Optional exact name or ID\n * @returns Selected function, or undefined when interactive selection is needed\n */\nfunction selectNamedFunction<Config extends Pick<CustomFunctionManifestEntry, 'id' | 'name'>>(\n configs: readonly Config[],\n selector: string | undefined,\n): Config | undefined {\n if (!selector) {\n return configs.length === 1 ? configs[0] : undefined;\n }\n const matches = configs.filter((config) => config.name === selector || config.id === selector);\n if (matches.length === 0) {\n throw new Error(`Custom Function \"${selector}\" was not found in the manifest.`);\n }\n if (matches.length > 1) {\n throw new Error(\n `Custom Function selector \"${selector}\" is ambiguous. Pass its manifest ID instead.`,\n );\n }\n return matches[0];\n}\n\n/**\n * Run one manifest function in the credential-free local Deno simulator.\n *\n * @param this - CLI context\n * @param flags - Selection and manifest flags\n * @param directory - Optional project directory\n */\nexport async function run(\n this: LocalContext,\n flags: CustomFunctionRunFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n try {\n const state = discoverCustomFunctionProject(this, {\n ...(directory ? { directory } : {}),\n ...(flags.manifest ? { manifest: flags.manifest } : {}),\n });\n if (!this.fs.existsSync(state.manifestPath)) {\n const cwd = this.process.cwd();\n throw new Error(\n formatMissingManifestMessage({\n cwd,\n manifestPath: state.manifestPath,\n discoveredManifestPaths: discoverCustomFunctionManifests(this, cwd),\n command: 'run',\n }),\n );\n }\n\n const parsedManifest = parseCustomFunctionsManifest(\n this.fs.readFileSync(state.manifestPath, 'utf8'),\n );\n if (parsedManifest.functions.length === 0) {\n throw new Error('The Custom Function manifest does not define any functions.');\n }\n const interactive =\n !flags.noInteractive && Boolean(this.process.stdin.isTTY && this.process.stderr.isTTY);\n let selectedEntry = selectNamedFunction(parsedManifest.functions, flags.function);\n if (!selectedEntry && interactive) {\n const prompts = new ScaffoldPrompts(this);\n const selectedIndex = await prompts.select(\n 'Custom Function to run:',\n parsedManifest.functions.map((entry, index) => ({\n name: entry.id ? `${entry.name} (${entry.id})` : entry.name,\n value: String(index),\n })),\n '0',\n );\n selectedEntry = parsedManifest.functions[Number(selectedIndex)];\n }\n if (!selectedEntry) {\n throw new Error('Select a Custom Function with --function in a non-interactive invocation.');\n }\n const { config: selected, sourcePath } = readCustomFunctionManifestEntry(\n state.manifestPath,\n selectedEntry,\n parseVariablesFromString(flags.variables),\n (path) => assertPathPhysicallyContained(this, state.manifestDirectory, path),\n );\n if (!selected.testPayloads || selected.testPayloads.length === 0) {\n throw new Error(\n `Custom Function \"${selected.name}\" has no test payloads. Add test-payload or test-payloads to its manifest entry.`,\n );\n }\n const denoConfig = this.fs.existsSync(state.denoConfigPath)\n ? { denoConfigPath: state.denoConfigPath }\n : {};\n const simulations = selected.testPayloads.map((testPayload) => ({\n testPayload,\n invocation: buildLocalSimulatorInvocation(selected, testPayload, {\n ...denoConfig,\n allowNetwork: flags.allowNetwork,\n }),\n }));\n\n const denoVersion = await runCapturedProcess(\n 'deno',\n ['--version'],\n { cwd: state.manifestDirectory },\n this,\n );\n if (denoVersion.error?.code === 'ENOENT') {\n throw new Error(\n `Deno ${SUPPORTED_DENO_MAJOR_VERSION}.x is required. Install it from ${DENO_INSTALL_URL}`,\n );\n }\n if (denoVersion.code !== 0) {\n throw new Error('Deno was found, but its version could not be determined.');\n }\n const compatibility = getDenoRuntimeCompatibility(denoVersion.stdout);\n if (compatibility.level === 'error') {\n throw new Error(compatibility.message);\n }\n if (compatibility.level === 'warning') {\n this.logger.warn(compatibility.message);\n }\n const moduleGraph = await runCapturedProcess(\n 'deno',\n [\n 'info',\n '--json',\n ...(denoConfig.denoConfigPath\n ? [`--config=${denoConfig.denoConfigPath}`]\n : ['--no-config']),\n sourcePath,\n ],\n { cwd: state.manifestDirectory },\n this,\n );\n if (moduleGraph.code !== 0) {\n throw new Error(\n `Could not inspect Custom Function runtime imports: ${\n moduleGraph.stderr.trim() || `Deno exited with code ${moduleGraph.code}`\n }`,\n );\n }\n const unsupportedImports = findNonSelfContainedRuntimeImports(moduleGraph.stdout);\n if (unsupportedImports.length > 0) {\n throw new Error(\n `Custom Functions must be self-contained. Local or import-map runtime dependencies are not deployed: ${unsupportedImports.join(\n ', ',\n )}`,\n );\n }\n\n this.logger.warn(\n colors.yellow(\n 'Local simulator: sdk.fetch calls are logged and return HTTP 200 without sending a request; KV state starts empty for each payload.',\n ),\n );\n if (flags.allowNetwork) {\n this.logger.warn(\n colors.yellow(\n `Network enabled: native fetch can make real requests to ${\n selected.allowedHosts?.length ? selected.allowedHosts.join(', ') : 'localhost'\n }.`,\n ),\n );\n } else if (selected.allowedHosts?.length) {\n this.logger.warn(\n colors.yellow(\n 'Native network access is disabled. Pass --allowNetwork to permit calls to allowed-hosts.',\n ),\n );\n }\n let failed = false;\n for (const [index, { invocation, testPayload }] of simulations.entries()) {\n const label = testPayload.payloadType ?? `payload ${index + 1}`;\n this.logger.info(`\\n${colors.bold(`Running \"${selected.name}\" (${label})`)}`);\n const result = await runCapturedProcess(\n 'deno',\n invocation.args,\n {\n cwd: state.manifestDirectory,\n input: invocation.input,\n env: invocation.env,\n timeoutMs: invocation.timeoutMs,\n maxOutputBytes:\n LOCAL_SIMULATOR_MAX_OUTPUT_BYTES +\n Math.max(\n 0,\n ...Object.values(selected.env ?? {}).map((value) => Buffer.byteLength(value)),\n ),\n },\n this,\n );\n const environment = selected.env ?? {};\n const stdout = truncateLocalSimulatorOutput(\n redactLocalSimulatorOutput(result.stdout, environment, result.stdoutTruncated),\n );\n const stderr = truncateLocalSimulatorOutput(\n redactLocalSimulatorOutput(result.stderr, environment, result.stderrTruncated),\n );\n if (stdout.output) {\n this.process.stdout.write(\n stdout.output.endsWith('\\n') ? stdout.output : `${stdout.output}\\n`,\n );\n }\n if (stderr.output) {\n this.process.stderr.write(\n stderr.output.endsWith('\\n') ? stderr.output : `${stderr.output}\\n`,\n );\n }\n if (result.outputTruncated || stdout.truncated || stderr.truncated) {\n this.logger.warn(\n colors.yellow(\n `Simulator output was truncated after ${LOCAL_SIMULATOR_MAX_OUTPUT_BYTES} bytes per stream.`,\n ),\n );\n }\n if (result.code === 0) {\n this.logger.info(colors.green(`Passed \"${selected.name}\" (${label})`));\n } else {\n failed = true;\n const detail = result.timedOut\n ? `timed out after ${invocation.timeoutMs}ms`\n : result.inputError\n ? `could not send the fixture to Deno: ${result.inputError.message}`\n : result.error\n ? `could not start Deno: ${result.error.message}`\n : result.signal\n ? `was terminated with ${result.signal}`\n : `exited with code ${result.code}`;\n this.logger.error(colors.red(`Failed \"${selected.name}\" (${label}): ${detail}`));\n }\n }\n if (failed) {\n this.process.exitCode = 1;\n }\n } catch (error) {\n if (error instanceof PromptCancelledError) {\n this.process.exit(130);\n }\n throw error;\n }\n}\n"],"mappings":"w+BAiBA,MAMa,EAA6B,IAG7B,EAAmC,KAAO,KAG1C,EAA2B,EAAK,GAAQ,CAAE,kCAAkC,CAEnF,EAAM,IAAI,EAAI,CAAE,UAAW,GAAM,OAAQ,GAAO,CAAC,CACjD,EAAoB,CACxB,QAAS,EAAI,QAAQ,EAAuC,CAC5D,UAAW,EAAI,QAAQ,EAA6C,CACpE,SAAU,EAAI,QAAQ,EAAoD,CAC3E,CAqHD,SAAgB,EACd,EACA,EACA,EACQ,CACR,IAAM,EAAS,EAMT,EAAS,EAAO,QAAU,EAAE,CAC5B,EAAU,EAAO,QACjB,EAAO,EAAO,MAAQ,EAAmB,QAGzC,EADJ,IAAS,EAAmB,KAAO,IAAgB,EAA0B,iBAE9D,GAAS,aAAe,iBACnC,CAAE,G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1
- import{i as e}from"./paths-J5KScOaQ.mjs";import{o as t}from"./project-discovery-CWRjlFnC.mjs";import{t as n}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as r}from"./validateTranscendAuth-D-dDINof.mjs";import{t as i}from"./done-input-validation-LiTaCEzF.mjs";import{t as a}from"./missing-manifest-D8y1VL4p.mjs";import{c as o,s,t as c}from"./project-discovery-BkHpTXDx.mjs";import{t as l}from"./command-output-BJcDRXNr.mjs";import{n as u}from"./command-output-BRfF3YFv.mjs";import{CustomFunctionPayloadType as d,CustomFunctionType as f}from"@transcend-io/privacy-types";import p from"colors";import{mapSeries as m}from"@transcend-io/utils";import{buildTranscendGraphQLClient as h,createSombraGotInstance as g,fetchAllCustomFunctions as _,resolveEffectiveSombraId as v,resolveExistingCustomFunction as y,syncCustomFunction as b}from"@transcend-io/sdk";async function x({auth:x,sombraAuth:S,transcendUrl:C,manifest:w,variables:T,dryRun:E,json:D,promote:O,force:k,skipTests:A,updateManifest:j,sombraId:M},N){i(this.process);let P=this.process.cwd(),{manifestDirectory:F,manifestPath:I}=e(P,{...N?{directory:N}:{},...w?{manifest:w}:{}});if(!this.fs.existsSync(I)){let e=a({cwd:P,manifestPath:I,discoveredManifestPaths:c(this,P),command:`push`});this.logger.error(p.red(e)),this.process.exit(1)}let L=r(x,this);Array.isArray(L)&&(this.logger.error(p.red(`transcend custom-functions push does not support a list of API keys — pass a single API key.`)),this.process.exit(1));let R=L,z=l(this.logger,D),B=n(T);z.info(p.magenta(`Reading manifest "${I}"...`));let V=s(I,B,e=>t(this,F,e));z.info(p.green(`Found ${V.length} custom function(s) in "${I}"`));let H=h(C,R),U=await _(H,{logger:z}),W=new Map,G=async(e,t)=>{let n=`${e??``}\u0000${t??``}`,r=W.get(n);if(r)return r;z.info(p.magenta(`Connecting to the ${e?`Sombra gateway "${e}"`:`primary Sombra gateway`} to sign code...`));let i=await g(C,R,{logger:z,sombraApiKey:t,...e?{sombraId:e}:{}});return W.set(n,i),i},K=e=>{if(!e.sombraAuthEnv)return S;let t=this.process.env[e.sombraAuthEnv];if(!t)throw Error(`Custom function "${e.name}" sets sombra-auth-env: ${e.sombraAuthEnv}, but that environment variable is not set. Export it (e.g. from a CI secret) before pushing.`);return t},q=[];if(await m(V,async e=>{try{let t=v(e,y(U,e),M),n=await b(H,{input:e,sombra:E?void 0:await G(t,K(e)),defaultSombraId:M,existing:U,promote:O,dryRun:E,force:k,...!A&&e.testPayloads!==void 0?{testPayloads:e.testPayloads}:{},logger:z});q.push({name:e.name,result:n});let r=n.versionNumber?` (version ${n.versionNumber})`:``,i=n.changedFields.length>0?` [${n.changedFields.join(`, `)}]`:``;switch(n.outcome){case`created`:n.createdDataSilo&&n.dataSiloId&&z.info(p.green(`Created DSR integration (data silo ${n.dataSiloId}) for "${e.name}"`)),z.info(p.green(`Created custom function "${e.name}"${r}`));break;case`updated`:z.info(p.green(`Pushed new revision to "${e.name}"${r}${i}${n.promoted?` and promoted to active`:` as a draft`}`));break;case`metadata-updated`:z.info(p.green(`Updated metadata for "${e.name}"${i} — code unchanged, no new revision`));break;case`skipped`:z.info(p.yellow(`Skipped "${e.name}" — no changes detected (env variable values cannot be diffed; use --force if only values changed)`));break;case`would-create`:z.info(p.cyan(`[dry run] Would create custom function "${e.name}"${e.type===f.Dsr&&!e.dataSiloId?` and its DSR integration (data silo)`:``}`));break;case`would-update`:z.info(p.cyan(`[dry run] Would push a new revision to "${e.name}"${i}`));break;case`test-failed`:{let t=(n.testResults??[]).filter(({passed:e})=>!e);z.error(p.red(`Rejected "${e.name}" — ${t.length} of ${n.testResults?.length??0} test run(s) failed`)),t.forEach(({payloadType:e,result:t})=>{let n=e?`[${e}] `:``;z.error(p.red(` ${n}${t.error?t.error.message:`failed with exit code ${t.exitCode}`}`)),t.logs.forEach(({file:e,message:t})=>{z.error(p.red(` [${e}] ${t}`))})}),n.createdDataSilo&&z.error(p.red(` The DSR integration (data silo) created for "${e.name}" was rolled back.`));break}}if(!A&&(e.testPayloads===void 0||e.testPayloads.length===0)&&(n.outcome===`created`||n.outcome===`updated`)&&z.warn(p.yellow(`Custom function "${e.name}" was pushed without a test run — add a test-payload to its manifest entry to enable test-before-promote.`)),!A&&e.type===f.Dsr&&e.testPayloads!==void 0&&e.testPayloads.length>0&&(n.outcome===`created`||n.outcome===`updated`)){let t=new Set(e.testPayloads.map(({payloadType:e})=>e??d.DataPoint));if(t.size===1){let[n]=t,r=n===d.DataPoint?d.RequestEnricher:d.DataPoint;z.warn(p.yellow(`DSR custom function "${e.name}" only tests its ${n} export — if it also implements the ${r} export, add a test payload with payload-type: ${r} so both entry points are tested on every push.`))}}}catch(t){q.push({name:e.name,error:t}),z.error(p.red(`Failed to sync custom function "${e.name}": ${t.message}`))}}),j&&!E){let e=o(I,V.map((e,t)=>{let n=q[t]?.result;if(!n)return;let r={...!e.id&&n.customFunctionId?{id:n.customFunctionId}:{},...!e.dataSiloId&&n.dataSiloId?{dataSiloId:n.dataSiloId}:{}};return Object.keys(r).length>0?r:void 0}));e>0&&z.info(p.green(`Wrote assigned id(s) back to ${e} manifest entr(ies) in "${I}" — commit this change so future pushes match by ID.`))}let J=u(I,E,q);if(D)this.process.stdout.write(`${JSON.stringify(J)}\n`);else{let{summary:e}=J;z.info(p.magenta(`Custom function sync complete: ${e.created} created, ${e.updated} updated, ${e.metadataUpdated} metadata-only, ${e.skipped} skipped, ${e.rejected} rejected (test failed), ${e.failed} failed${E?` (dry run)`:``}`))}J.status===`failed`&&this.process.exit(1)}export{x as push};
2
- //# sourceMappingURL=impl-Cvyc-iTI2.mjs.map
1
+ import{i as e}from"./paths-J5KScOaQ.mjs";import{o as t}from"./project-discovery-CWRjlFnC.mjs";import{t as n}from"./parseVariablesFromString-6TYW65LF.mjs";import{t as r}from"./validateTranscendAuth-BrVGfq6X.mjs";import{t as i}from"./done-input-validation-LiTaCEzF.mjs";import{t as a}from"./missing-manifest-D8y1VL4p.mjs";import{c as o,s,t as c}from"./project-discovery-g29vd44a.mjs";import{t as l}from"./command-output-BJcDRXNr.mjs";import{n as u}from"./command-output-BRfF3YFv.mjs";import{CustomFunctionPayloadType as d,CustomFunctionType as f}from"@transcend-io/privacy-types";import p from"colors";import{mapSeries as m}from"@transcend-io/utils";import{buildTranscendGraphQLClient as h,createSombraGotInstance as g,fetchAllCustomFunctions as _,resolveEffectiveSombraId as v,resolveExistingCustomFunction as y,syncCustomFunction as b}from"@transcend-io/sdk";async function x({auth:x,sombraAuth:S,transcendUrl:C,manifest:w,variables:T,dryRun:E,json:D,promote:O,force:k,skipTests:A,updateManifest:j,sombraId:M},N){i(this.process);let P=this.process.cwd(),{manifestDirectory:F,manifestPath:I}=e(P,{...N?{directory:N}:{},...w?{manifest:w}:{}});if(!this.fs.existsSync(I)){let e=a({cwd:P,manifestPath:I,discoveredManifestPaths:c(this,P),command:`push`});this.logger.error(p.red(e)),this.process.exit(1)}let L=r(x,this);Array.isArray(L)&&(this.logger.error(p.red(`transcend custom-functions push does not support a list of API keys — pass a single API key.`)),this.process.exit(1));let R=L,z=l(this.logger,D),B=n(T);z.info(p.magenta(`Reading manifest "${I}"...`));let V=s(I,B,e=>t(this,F,e));z.info(p.green(`Found ${V.length} custom function(s) in "${I}"`));let H=h(C,R),U=await _(H,{logger:z}),W=new Map,G=async(e,t)=>{let n=`${e??``}\u0000${t??``}`,r=W.get(n);if(r)return r;z.info(p.magenta(`Connecting to the ${e?`Sombra gateway "${e}"`:`primary Sombra gateway`} to sign code...`));let i=await g(C,R,{logger:z,sombraApiKey:t,...e?{sombraId:e}:{}});return W.set(n,i),i},K=e=>{if(!e.sombraAuthEnv)return S;let t=this.process.env[e.sombraAuthEnv];if(!t)throw Error(`Custom function "${e.name}" sets sombra-auth-env: ${e.sombraAuthEnv}, but that environment variable is not set. Export it (e.g. from a CI secret) before pushing.`);return t},q=[];if(await m(V,async e=>{try{let t=v(e,y(U,e),M),n=await b(H,{input:e,sombra:E?void 0:await G(t,K(e)),defaultSombraId:M,existing:U,promote:O,dryRun:E,force:k,...!A&&e.testPayloads!==void 0?{testPayloads:e.testPayloads}:{},logger:z});q.push({name:e.name,result:n});let r=n.versionNumber?` (version ${n.versionNumber})`:``,i=n.changedFields.length>0?` [${n.changedFields.join(`, `)}]`:``;switch(n.outcome){case`created`:n.createdDataSilo&&n.dataSiloId&&z.info(p.green(`Created DSR integration (data silo ${n.dataSiloId}) for "${e.name}"`)),z.info(p.green(`Created custom function "${e.name}"${r}`));break;case`updated`:z.info(p.green(`Pushed new revision to "${e.name}"${r}${i}${n.promoted?` and promoted to active`:` as a draft`}`));break;case`metadata-updated`:z.info(p.green(`Updated metadata for "${e.name}"${i} — code unchanged, no new revision`));break;case`skipped`:z.info(p.yellow(`Skipped "${e.name}" — no changes detected (env variable values cannot be diffed; use --force if only values changed)`));break;case`would-create`:z.info(p.cyan(`[dry run] Would create custom function "${e.name}"${e.type===f.Dsr&&!e.dataSiloId?` and its DSR integration (data silo)`:``}`));break;case`would-update`:z.info(p.cyan(`[dry run] Would push a new revision to "${e.name}"${i}`));break;case`test-failed`:{let t=(n.testResults??[]).filter(({passed:e})=>!e);z.error(p.red(`Rejected "${e.name}" — ${t.length} of ${n.testResults?.length??0} test run(s) failed`)),t.forEach(({payloadType:e,result:t})=>{let n=e?`[${e}] `:``;z.error(p.red(` ${n}${t.error?t.error.message:`failed with exit code ${t.exitCode}`}`)),t.logs.forEach(({file:e,message:t})=>{z.error(p.red(` [${e}] ${t}`))})}),n.createdDataSilo&&z.error(p.red(` The DSR integration (data silo) created for "${e.name}" was rolled back.`));break}}if(!A&&(e.testPayloads===void 0||e.testPayloads.length===0)&&(n.outcome===`created`||n.outcome===`updated`)&&z.warn(p.yellow(`Custom function "${e.name}" was pushed without a test run — add a test-payload to its manifest entry to enable test-before-promote.`)),!A&&e.type===f.Dsr&&e.testPayloads!==void 0&&e.testPayloads.length>0&&(n.outcome===`created`||n.outcome===`updated`)){let t=new Set(e.testPayloads.map(({payloadType:e})=>e??d.DataPoint));if(t.size===1){let[n]=t,r=n===d.DataPoint?d.RequestEnricher:d.DataPoint;z.warn(p.yellow(`DSR custom function "${e.name}" only tests its ${n} export — if it also implements the ${r} export, add a test payload with payload-type: ${r} so both entry points are tested on every push.`))}}}catch(t){q.push({name:e.name,error:t}),z.error(p.red(`Failed to sync custom function "${e.name}": ${t.message}`))}}),j&&!E){let e=o(I,V.map((e,t)=>{let n=q[t]?.result;if(!n)return;let r={...!e.id&&n.customFunctionId?{id:n.customFunctionId}:{},...!e.dataSiloId&&n.dataSiloId?{dataSiloId:n.dataSiloId}:{}};return Object.keys(r).length>0?r:void 0}));e>0&&z.info(p.green(`Wrote assigned id(s) back to ${e} manifest entr(ies) in "${I}" — commit this change so future pushes match by ID.`))}let J=u(I,E,q);if(D)this.process.stdout.write(`${JSON.stringify(J)}\n`);else{let{summary:e}=J;z.info(p.magenta(`Custom function sync complete: ${e.created} created, ${e.updated} updated, ${e.metadataUpdated} metadata-only, ${e.skipped} skipped, ${e.rejected} rejected (test failed), ${e.failed} failed${E?` (dry run)`:``}`))}J.status===`failed`&&this.process.exit(1)}export{x as push};
2
+ //# sourceMappingURL=impl-CWINXCFq2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-Cvyc-iTI2.mjs","names":[],"sources":["../src/commands/custom-functions/push/impl.ts"],"sourcesContent":["import { CustomFunctionPayloadType, CustomFunctionType } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllCustomFunctions,\n resolveEffectiveSombraId,\n resolveExistingCustomFunction,\n syncCustomFunction,\n type CustomFunctionSyncResult,\n} from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { selectCommandLogger } from '../../../lib/cli/command-output.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildCustomFunctionPushJsonResult } from '../../../lib/custom-functions/command-output.js';\nimport {\n readCustomFunctionsManifest,\n writeCustomFunctionIdsToManifest,\n} from '../../../lib/custom-functions/manifest.js';\nimport { formatMissingManifestMessage } from '../../../lib/custom-functions/missing-manifest.js';\nimport { resolveCustomFunctionProjectPaths } from '../../../lib/custom-functions/paths.js';\nimport { discoverCustomFunctionManifests } from '../../../lib/custom-functions/project-discovery.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { assertPathPhysicallyContained } from '../../../lib/scaffolding/path-safety.js';\n\nexport interface CustomFunctionsPushCommandFlags {\n /** Transcend API key. */\n auth: string;\n /** Optional Sombra internal key. */\n sombraAuth?: string;\n /** Transcend backend URL. */\n transcendUrl: string;\n /** Explicit manifest path. */\n manifest?: string;\n /** Manifest variable substitutions. */\n variables: string;\n /** Preview remote changes without applying them. */\n dryRun: boolean;\n /** Emit stable JSON output. */\n json: boolean;\n /** Promote new revisions to active. */\n promote: boolean;\n /** Push even when no changes can be detected. */\n force: boolean;\n /** Skip test payload execution. */\n skipTests: boolean;\n /** Write assigned IDs back to the manifest. */\n updateManifest: boolean;\n /** Default Sombra gateway ID. */\n sombraId?: string;\n}\n\nexport async function push(\n this: LocalContext,\n {\n auth,\n sombraAuth,\n transcendUrl,\n manifest,\n variables,\n dryRun,\n json,\n promote,\n force,\n skipTests,\n updateManifest,\n sombraId,\n }: CustomFunctionsPushCommandFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const cwd = this.process.cwd();\n const { manifestDirectory, manifestPath } = resolveCustomFunctionProjectPaths(cwd, {\n ...(directory ? { directory } : {}),\n ...(manifest ? { manifest } : {}),\n });\n\n // Read and validate the manifest before performing auth or network setup.\n if (!this.fs.existsSync(manifestPath)) {\n const message = formatMissingManifestMessage({\n cwd,\n manifestPath,\n discoveredManifestPaths: discoverCustomFunctionManifests(this, cwd),\n command: 'push',\n });\n this.logger.error(colors.red(message));\n this.process.exit(1);\n }\n\n // This command operates on a single Transcend instance\n const apiKeyOrList = validateTranscendAuth(auth, this);\n if (Array.isArray(apiKeyOrList)) {\n this.logger.error(\n colors.red(\n 'transcend custom-functions push does not support a list of API keys — pass a single API key.',\n ),\n );\n this.process.exit(1);\n }\n const apiKey = apiKeyOrList as string;\n const commandLogger = selectCommandLogger(this.logger, json);\n\n const vars = parseVariablesFromString(variables);\n commandLogger.info(colors.magenta(`Reading manifest \"${manifestPath}\"...`));\n const configs = readCustomFunctionsManifest(manifestPath, vars, (path) =>\n assertPathPhysicallyContained(this, manifestDirectory, path),\n );\n commandLogger.info(\n colors.green(`Found ${configs.length} custom function(s) in \"${manifestPath}\"`),\n );\n\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey);\n\n // Fetch existing functions once to diff against\n const existing = await fetchAllCustomFunctions(client, { logger: commandLogger });\n\n // Each custom function belongs to a single Sombra gateway whose keys sign\n // its code, so code must be signed against that specific gateway's customer\n // ingress. Cache one connection per distinct gateway + internal key across\n // the run.\n type SombraGot = Awaited<ReturnType<typeof createSombraGotInstance>>;\n const sombraByGateway = new Map<string, SombraGot>();\n const getSombraForGateway = async (\n gatewaySombraId: string | undefined,\n sombraApiKey: string | undefined,\n ): Promise<SombraGot> => {\n const key = `${gatewaySombraId ?? ''}\\u0000${sombraApiKey ?? ''}`;\n const cached = sombraByGateway.get(key);\n if (cached) {\n return cached;\n }\n commandLogger.info(\n colors.magenta(\n `Connecting to the ${\n gatewaySombraId ? `Sombra gateway \"${gatewaySombraId}\"` : 'primary Sombra gateway'\n } to sign code...`,\n ),\n );\n const sombra = await createSombraGotInstance(transcendUrl, apiKey, {\n logger: commandLogger,\n sombraApiKey,\n ...(gatewaySombraId ? { sombraId: gatewaySombraId } : {}),\n });\n sombraByGateway.set(key, sombra);\n return sombra;\n };\n\n /**\n * Resolve the Sombra internal key for a manifest entry: the env variable\n * named by `sombra-auth-env` when set (which must be exported), else the\n * `--sombraAuth` flag.\n *\n * @param input - The manifest entry\n * @returns The internal key to authenticate with, if any\n */\n const resolveEntrySombraAuth = (input: {\n /** Function name, for error messages */\n name: string;\n /** Env variable name holding the gateway's internal key */\n sombraAuthEnv?: string;\n }): string | undefined => {\n if (!input.sombraAuthEnv) {\n return sombraAuth;\n }\n const value = this.process.env[input.sombraAuthEnv];\n if (!value) {\n throw new Error(\n `Custom function \"${input.name}\" sets sombra-auth-env: ${input.sombraAuthEnv}, ` +\n 'but that environment variable is not set. Export it (e.g. from a CI secret) ' +\n 'before pushing.',\n );\n }\n return value;\n };\n\n // Sync each function in order\n const results: { name: string; result?: CustomFunctionSyncResult; error?: Error }[] = [];\n await mapSeries(configs, async (input) => {\n try {\n // Resolve the gateway this function belongs to: manifest sombra-id,\n // else the existing function's gateway, else --sombraId, else primary.\n // Also validates manifest-vs-existing gateway mismatches.\n const effectiveSombraId = resolveEffectiveSombraId(\n input,\n resolveExistingCustomFunction(existing, input),\n sombraId,\n );\n const result = await syncCustomFunction(client, {\n input,\n sombra: dryRun\n ? undefined\n : await getSombraForGateway(effectiveSombraId, resolveEntrySombraAuth(input)),\n defaultSombraId: sombraId,\n existing,\n promote,\n dryRun,\n force,\n // Test the freshly signed code before pushing; every payload must\n // pass or the function is rejected. Dry runs never sign, so nothing\n // is tested either.\n ...(!skipTests && input.testPayloads !== undefined\n ? { testPayloads: input.testPayloads }\n : {}),\n logger: commandLogger,\n });\n results.push({ name: input.name, result });\n\n const suffix = result.versionNumber ? ` (version ${result.versionNumber})` : '';\n const changes =\n result.changedFields.length > 0 ? ` [${result.changedFields.join(', ')}]` : '';\n switch (result.outcome) {\n case 'created':\n if (result.createdDataSilo && result.dataSiloId) {\n commandLogger.info(\n colors.green(\n `Created DSR integration (data silo ${result.dataSiloId}) for \"${input.name}\"`,\n ),\n );\n }\n commandLogger.info(colors.green(`Created custom function \"${input.name}\"${suffix}`));\n break;\n case 'updated':\n commandLogger.info(\n colors.green(\n `Pushed new revision to \"${input.name}\"${suffix}${changes}${\n result.promoted ? ' and promoted to active' : ' as a draft'\n }`,\n ),\n );\n break;\n case 'metadata-updated':\n commandLogger.info(\n colors.green(\n `Updated metadata for \"${input.name}\"${changes} — code unchanged, no new revision`,\n ),\n );\n break;\n case 'skipped':\n commandLogger.info(\n colors.yellow(\n `Skipped \"${input.name}\" — no changes detected ` +\n '(env variable values cannot be diffed; use --force if only values changed)',\n ),\n );\n break;\n case 'would-create':\n commandLogger.info(\n colors.cyan(\n `[dry run] Would create custom function \"${input.name}\"${\n input.type === CustomFunctionType.Dsr && !input.dataSiloId\n ? ' and its DSR integration (data silo)'\n : ''\n }`,\n ),\n );\n break;\n case 'would-update':\n commandLogger.info(\n colors.cyan(`[dry run] Would push a new revision to \"${input.name}\"${changes}`),\n );\n break;\n case 'test-failed': {\n const failed = (result.testResults ?? []).filter(({ passed }) => !passed);\n commandLogger.error(\n colors.red(\n `Rejected \"${input.name}\" — ${failed.length} of ${\n result.testResults?.length ?? 0\n } test run(s) failed`,\n ),\n );\n failed.forEach(({ payloadType, result: execution }) => {\n const label = payloadType ? `[${payloadType}] ` : '';\n commandLogger.error(\n colors.red(\n ` ${label}${\n execution.error\n ? execution.error.message\n : `failed with exit code ${execution.exitCode}`\n }`,\n ),\n );\n execution.logs.forEach(({ file: logFile, message }) => {\n commandLogger.error(colors.red(` [${logFile}] ${message}`));\n });\n });\n if (result.createdDataSilo) {\n commandLogger.error(\n colors.red(\n ` The DSR integration (data silo) created for \"${input.name}\" was rolled back.`,\n ),\n );\n }\n break;\n }\n }\n\n // Anything that reached the push path without a test payload was\n // promoted untested — call it out so payloads get added over time\n if (\n !skipTests &&\n (input.testPayloads === undefined || input.testPayloads.length === 0) &&\n (result.outcome === 'created' || result.outcome === 'updated')\n ) {\n commandLogger.warn(\n colors.yellow(\n `Custom function \"${input.name}\" was pushed without a test run — add a ` +\n 'test-payload to its manifest entry to enable test-before-promote.',\n ),\n );\n }\n\n // DSR functions have two entry points (default export = DATA_POINT,\n // enricher export = REQUEST_ENRICHER); nudge toward covering both\n if (\n !skipTests &&\n input.type === CustomFunctionType.Dsr &&\n input.testPayloads !== undefined &&\n input.testPayloads.length > 0 &&\n (result.outcome === 'created' || result.outcome === 'updated')\n ) {\n const coveredTypes = new Set(\n input.testPayloads.map(\n ({ payloadType }) => payloadType ?? CustomFunctionPayloadType.DataPoint,\n ),\n );\n if (coveredTypes.size === 1) {\n const [covered] = coveredTypes;\n const uncovered =\n covered === CustomFunctionPayloadType.DataPoint\n ? CustomFunctionPayloadType.RequestEnricher\n : CustomFunctionPayloadType.DataPoint;\n commandLogger.warn(\n colors.yellow(\n `DSR custom function \"${input.name}\" only tests its ${covered} export — if it ` +\n `also implements the ${uncovered} export, add a test payload with ` +\n `payload-type: ${uncovered} so both entry points are tested on every push.`,\n ),\n );\n }\n }\n } catch (err) {\n results.push({ name: input.name, error: err as Error });\n commandLogger.error(\n colors.red(`Failed to sync custom function \"${input.name}\": ${(err as Error).message}`),\n );\n }\n });\n\n // Write assigned IDs back into the manifest so future pushes match by ID\n // instead of by (potentially non-unique) name, and DSR entries keep\n // pointing at their (possibly auto-created) integration\n if (updateManifest && !dryRun) {\n const idsByIndex = configs.map((input, index) => {\n const result = results[index]?.result;\n if (!result) {\n return undefined;\n }\n const ids = {\n ...(!input.id && result.customFunctionId ? { id: result.customFunctionId } : {}),\n ...(!input.dataSiloId && result.dataSiloId ? { dataSiloId: result.dataSiloId } : {}),\n };\n return Object.keys(ids).length > 0 ? ids : undefined;\n });\n const updatedCount = writeCustomFunctionIdsToManifest(manifestPath, idsByIndex);\n if (updatedCount > 0) {\n commandLogger.info(\n colors.green(\n `Wrote assigned id(s) back to ${updatedCount} manifest entr(ies) in \"${manifestPath}\" — ` +\n 'commit this change so future pushes match by ID.',\n ),\n );\n }\n }\n\n const output = buildCustomFunctionPushJsonResult(manifestPath, dryRun, results);\n if (json) {\n this.process.stdout.write(`${JSON.stringify(output)}\\n`);\n } else {\n const { summary } = output;\n commandLogger.info(\n colors.magenta(\n `Custom function sync complete: ${summary.created} created, ${summary.updated} updated, ` +\n `${summary.metadataUpdated} metadata-only, ${summary.skipped} skipped, ` +\n `${summary.rejected} rejected (test failed), ${summary.failed} failed${\n dryRun ? ' (dry run)' : ''\n }`,\n ),\n );\n }\n\n if (output.status === 'failed') {\n this.process.exit(1);\n }\n}\n"],"mappings":"21BAuDA,eAAsB,EAEpB,CACE,OACA,aACA,eACA,WACA,YACA,SACA,OACA,UACA,QACA,YACA,iBACA,YAEF,EACe,CACf,EAAoB,KAAK,QAAQ,CAEjC,IAAM,EAAM,KAAK,QAAQ,KAAK,CACxB,CAAE,oBAAmB,gBAAiB,EAAkC,EAAK,CACjF,GAAI,EAAY,CAAE,YAAW,CAAG,EAAE,CAClC,GAAI,EAAW,CAAE,WAAU,CAAG,EAAE,CACjC,CAAC,CAGF,GAAI,CAAC,KAAK,GAAG,WAAW,EAAa,CAAE,CACrC,IAAM,EAAU,EAA6B,CAC3C,MACA,eACA,wBAAyB,EAAgC,KAAM,EAAI,CACnE,QAAS,OACV,CAAC,CACF,KAAK,OAAO,MAAM,EAAO,IAAI,EAAQ,CAAC,CACtC,KAAK,QAAQ,KAAK,EAAE,CAItB,IAAM,EAAe,EAAsB,EAAM,KAAK,CAClD,MAAM,QAAQ,EAAa,GAC7B,KAAK,OAAO,MACV,EAAO,IACL,+FACD,CACF,CACD,KAAK,QAAQ,KAAK,EAAE,EAEtB,IAAM,EAAS,EACT,EAAgB,EAAoB,KAAK,OAAQ,EAAK,CAEtD,EAAO,EAAyB,EAAU,CAChD,EAAc,KAAK,EAAO,QAAQ,qBAAqB,EAAa,MAAM,CAAC,CAC3E,IAAM,EAAU,EAA4B,EAAc,EAAO,GAC/D,EAA8B,KAAM,EAAmB,EAAK,CAC7D,CACD,EAAc,KACZ,EAAO,MAAM,SAAS,EAAQ,OAAO,0BAA0B,EAAa,GAAG,CAChF,CAED,IAAM,EAAS,EAA4B,EAAc,EAAO,CAG1D,EAAW,MAAM,EAAwB,EAAQ,CAAE,OAAQ,EAAe,CAAC,CAO3E,EAAkB,IAAI,IACtB,EAAsB,MAC1B,E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,EAAQ,CAC/E,GAAI,EACF,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,EAAO,CAAC,IAAI,KACnD,CACL,GAAM,CAAE,WAAY,EACpB,EAAc,KACZ,EAAO,QACL,kCAAkC,EAAQ,QAAQ,YAAY,EAAQ,QAAQ,YACzE,EAAQ,gBAAgB,kBAAkB,EAAQ,QAAQ,YAC1D,EAAQ,SAAS,2BAA2B,EAAQ,OAAO,SAC5D,EAAS,aAAe,KAE7B,CACF,CAGC,EAAO,SAAW,UACpB,KAAK,QAAQ,KAAK,EAAE"}
1
+ {"version":3,"file":"impl-CWINXCFq2.mjs","names":[],"sources":["../src/commands/custom-functions/push/impl.ts"],"sourcesContent":["import { CustomFunctionPayloadType, CustomFunctionType } from '@transcend-io/privacy-types';\nimport {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllCustomFunctions,\n resolveEffectiveSombraId,\n resolveExistingCustomFunction,\n syncCustomFunction,\n type CustomFunctionSyncResult,\n} from '@transcend-io/sdk';\nimport { mapSeries } from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { validateTranscendAuth } from '../../../lib/api-keys/index.js';\nimport { selectCommandLogger } from '../../../lib/cli/command-output.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { buildCustomFunctionPushJsonResult } from '../../../lib/custom-functions/command-output.js';\nimport {\n readCustomFunctionsManifest,\n writeCustomFunctionIdsToManifest,\n} from '../../../lib/custom-functions/manifest.js';\nimport { formatMissingManifestMessage } from '../../../lib/custom-functions/missing-manifest.js';\nimport { resolveCustomFunctionProjectPaths } from '../../../lib/custom-functions/paths.js';\nimport { discoverCustomFunctionManifests } from '../../../lib/custom-functions/project-discovery.js';\nimport { parseVariablesFromString } from '../../../lib/helpers/parseVariablesFromString.js';\nimport { assertPathPhysicallyContained } from '../../../lib/scaffolding/path-safety.js';\n\nexport interface CustomFunctionsPushCommandFlags {\n /** Transcend API key. */\n auth: string;\n /** Optional Sombra internal key. */\n sombraAuth?: string;\n /** Transcend backend URL. */\n transcendUrl: string;\n /** Explicit manifest path. */\n manifest?: string;\n /** Manifest variable substitutions. */\n variables: string;\n /** Preview remote changes without applying them. */\n dryRun: boolean;\n /** Emit stable JSON output. */\n json: boolean;\n /** Promote new revisions to active. */\n promote: boolean;\n /** Push even when no changes can be detected. */\n force: boolean;\n /** Skip test payload execution. */\n skipTests: boolean;\n /** Write assigned IDs back to the manifest. */\n updateManifest: boolean;\n /** Default Sombra gateway ID. */\n sombraId?: string;\n}\n\nexport async function push(\n this: LocalContext,\n {\n auth,\n sombraAuth,\n transcendUrl,\n manifest,\n variables,\n dryRun,\n json,\n promote,\n force,\n skipTests,\n updateManifest,\n sombraId,\n }: CustomFunctionsPushCommandFlags,\n directory?: string,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const cwd = this.process.cwd();\n const { manifestDirectory, manifestPath } = resolveCustomFunctionProjectPaths(cwd, {\n ...(directory ? { directory } : {}),\n ...(manifest ? { manifest } : {}),\n });\n\n // Read and validate the manifest before performing auth or network setup.\n if (!this.fs.existsSync(manifestPath)) {\n const message = formatMissingManifestMessage({\n cwd,\n manifestPath,\n discoveredManifestPaths: discoverCustomFunctionManifests(this, cwd),\n command: 'push',\n });\n this.logger.error(colors.red(message));\n this.process.exit(1);\n }\n\n // This command operates on a single Transcend instance\n const apiKeyOrList = validateTranscendAuth(auth, this);\n if (Array.isArray(apiKeyOrList)) {\n this.logger.error(\n colors.red(\n 'transcend custom-functions push does not support a list of API keys — pass a single API key.',\n ),\n );\n this.process.exit(1);\n }\n const apiKey = apiKeyOrList as string;\n const commandLogger = selectCommandLogger(this.logger, json);\n\n const vars = parseVariablesFromString(variables);\n commandLogger.info(colors.magenta(`Reading manifest \"${manifestPath}\"...`));\n const configs = readCustomFunctionsManifest(manifestPath, vars, (path) =>\n assertPathPhysicallyContained(this, manifestDirectory, path),\n );\n commandLogger.info(\n colors.green(`Found ${configs.length} custom function(s) in \"${manifestPath}\"`),\n );\n\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey);\n\n // Fetch existing functions once to diff against\n const existing = await fetchAllCustomFunctions(client, { logger: commandLogger });\n\n // Each custom function belongs to a single Sombra gateway whose keys sign\n // its code, so code must be signed against that specific gateway's customer\n // ingress. Cache one connection per distinct gateway + internal key across\n // the run.\n type SombraGot = Awaited<ReturnType<typeof createSombraGotInstance>>;\n const sombraByGateway = new Map<string, SombraGot>();\n const getSombraForGateway = async (\n gatewaySombraId: string | undefined,\n sombraApiKey: string | undefined,\n ): Promise<SombraGot> => {\n const key = `${gatewaySombraId ?? ''}\\u0000${sombraApiKey ?? ''}`;\n const cached = sombraByGateway.get(key);\n if (cached) {\n return cached;\n }\n commandLogger.info(\n colors.magenta(\n `Connecting to the ${\n gatewaySombraId ? `Sombra gateway \"${gatewaySombraId}\"` : 'primary Sombra gateway'\n } to sign code...`,\n ),\n );\n const sombra = await createSombraGotInstance(transcendUrl, apiKey, {\n logger: commandLogger,\n sombraApiKey,\n ...(gatewaySombraId ? { sombraId: gatewaySombraId } : {}),\n });\n sombraByGateway.set(key, sombra);\n return sombra;\n };\n\n /**\n * Resolve the Sombra internal key for a manifest entry: the env variable\n * named by `sombra-auth-env` when set (which must be exported), else the\n * `--sombraAuth` flag.\n *\n * @param input - The manifest entry\n * @returns The internal key to authenticate with, if any\n */\n const resolveEntrySombraAuth = (input: {\n /** Function name, for error messages */\n name: string;\n /** Env variable name holding the gateway's internal key */\n sombraAuthEnv?: string;\n }): string | undefined => {\n if (!input.sombraAuthEnv) {\n return sombraAuth;\n }\n const value = this.process.env[input.sombraAuthEnv];\n if (!value) {\n throw new Error(\n `Custom function \"${input.name}\" sets sombra-auth-env: ${input.sombraAuthEnv}, ` +\n 'but that environment variable is not set. Export it (e.g. from a CI secret) ' +\n 'before pushing.',\n );\n }\n return value;\n };\n\n // Sync each function in order\n const results: { name: string; result?: CustomFunctionSyncResult; error?: Error }[] = [];\n await mapSeries(configs, async (input) => {\n try {\n // Resolve the gateway this function belongs to: manifest sombra-id,\n // else the existing function's gateway, else --sombraId, else primary.\n // Also validates manifest-vs-existing gateway mismatches.\n const effectiveSombraId = resolveEffectiveSombraId(\n input,\n resolveExistingCustomFunction(existing, input),\n sombraId,\n );\n const result = await syncCustomFunction(client, {\n input,\n sombra: dryRun\n ? undefined\n : await getSombraForGateway(effectiveSombraId, resolveEntrySombraAuth(input)),\n defaultSombraId: sombraId,\n existing,\n promote,\n dryRun,\n force,\n // Test the freshly signed code before pushing; every payload must\n // pass or the function is rejected. Dry runs never sign, so nothing\n // is tested either.\n ...(!skipTests && input.testPayloads !== undefined\n ? { testPayloads: input.testPayloads }\n : {}),\n logger: commandLogger,\n });\n results.push({ name: input.name, result });\n\n const suffix = result.versionNumber ? ` (version ${result.versionNumber})` : '';\n const changes =\n result.changedFields.length > 0 ? ` [${result.changedFields.join(', ')}]` : '';\n switch (result.outcome) {\n case 'created':\n if (result.createdDataSilo && result.dataSiloId) {\n commandLogger.info(\n colors.green(\n `Created DSR integration (data silo ${result.dataSiloId}) for \"${input.name}\"`,\n ),\n );\n }\n commandLogger.info(colors.green(`Created custom function \"${input.name}\"${suffix}`));\n break;\n case 'updated':\n commandLogger.info(\n colors.green(\n `Pushed new revision to \"${input.name}\"${suffix}${changes}${\n result.promoted ? ' and promoted to active' : ' as a draft'\n }`,\n ),\n );\n break;\n case 'metadata-updated':\n commandLogger.info(\n colors.green(\n `Updated metadata for \"${input.name}\"${changes} — code unchanged, no new revision`,\n ),\n );\n break;\n case 'skipped':\n commandLogger.info(\n colors.yellow(\n `Skipped \"${input.name}\" — no changes detected ` +\n '(env variable values cannot be diffed; use --force if only values changed)',\n ),\n );\n break;\n case 'would-create':\n commandLogger.info(\n colors.cyan(\n `[dry run] Would create custom function \"${input.name}\"${\n input.type === CustomFunctionType.Dsr && !input.dataSiloId\n ? ' and its DSR integration (data silo)'\n : ''\n }`,\n ),\n );\n break;\n case 'would-update':\n commandLogger.info(\n colors.cyan(`[dry run] Would push a new revision to \"${input.name}\"${changes}`),\n );\n break;\n case 'test-failed': {\n const failed = (result.testResults ?? []).filter(({ passed }) => !passed);\n commandLogger.error(\n colors.red(\n `Rejected \"${input.name}\" — ${failed.length} of ${\n result.testResults?.length ?? 0\n } test run(s) failed`,\n ),\n );\n failed.forEach(({ payloadType, result: execution }) => {\n const label = payloadType ? `[${payloadType}] ` : '';\n commandLogger.error(\n colors.red(\n ` ${label}${\n execution.error\n ? execution.error.message\n : `failed with exit code ${execution.exitCode}`\n }`,\n ),\n );\n execution.logs.forEach(({ file: logFile, message }) => {\n commandLogger.error(colors.red(` [${logFile}] ${message}`));\n });\n });\n if (result.createdDataSilo) {\n commandLogger.error(\n colors.red(\n ` The DSR integration (data silo) created for \"${input.name}\" was rolled back.`,\n ),\n );\n }\n break;\n }\n }\n\n // Anything that reached the push path without a test payload was\n // promoted untested — call it out so payloads get added over time\n if (\n !skipTests &&\n (input.testPayloads === undefined || input.testPayloads.length === 0) &&\n (result.outcome === 'created' || result.outcome === 'updated')\n ) {\n commandLogger.warn(\n colors.yellow(\n `Custom function \"${input.name}\" was pushed without a test run — add a ` +\n 'test-payload to its manifest entry to enable test-before-promote.',\n ),\n );\n }\n\n // DSR functions have two entry points (default export = DATA_POINT,\n // enricher export = REQUEST_ENRICHER); nudge toward covering both\n if (\n !skipTests &&\n input.type === CustomFunctionType.Dsr &&\n input.testPayloads !== undefined &&\n input.testPayloads.length > 0 &&\n (result.outcome === 'created' || result.outcome === 'updated')\n ) {\n const coveredTypes = new Set(\n input.testPayloads.map(\n ({ payloadType }) => payloadType ?? CustomFunctionPayloadType.DataPoint,\n ),\n );\n if (coveredTypes.size === 1) {\n const [covered] = coveredTypes;\n const uncovered =\n covered === CustomFunctionPayloadType.DataPoint\n ? CustomFunctionPayloadType.RequestEnricher\n : CustomFunctionPayloadType.DataPoint;\n commandLogger.warn(\n colors.yellow(\n `DSR custom function \"${input.name}\" only tests its ${covered} export — if it ` +\n `also implements the ${uncovered} export, add a test payload with ` +\n `payload-type: ${uncovered} so both entry points are tested on every push.`,\n ),\n );\n }\n }\n } catch (err) {\n results.push({ name: input.name, error: err as Error });\n commandLogger.error(\n colors.red(`Failed to sync custom function \"${input.name}\": ${(err as Error).message}`),\n );\n }\n });\n\n // Write assigned IDs back into the manifest so future pushes match by ID\n // instead of by (potentially non-unique) name, and DSR entries keep\n // pointing at their (possibly auto-created) integration\n if (updateManifest && !dryRun) {\n const idsByIndex = configs.map((input, index) => {\n const result = results[index]?.result;\n if (!result) {\n return undefined;\n }\n const ids = {\n ...(!input.id && result.customFunctionId ? { id: result.customFunctionId } : {}),\n ...(!input.dataSiloId && result.dataSiloId ? { dataSiloId: result.dataSiloId } : {}),\n };\n return Object.keys(ids).length > 0 ? ids : undefined;\n });\n const updatedCount = writeCustomFunctionIdsToManifest(manifestPath, idsByIndex);\n if (updatedCount > 0) {\n commandLogger.info(\n colors.green(\n `Wrote assigned id(s) back to ${updatedCount} manifest entr(ies) in \"${manifestPath}\" — ` +\n 'commit this change so future pushes match by ID.',\n ),\n );\n }\n }\n\n const output = buildCustomFunctionPushJsonResult(manifestPath, dryRun, results);\n if (json) {\n this.process.stdout.write(`${JSON.stringify(output)}\\n`);\n } else {\n const { summary } = output;\n commandLogger.info(\n colors.magenta(\n `Custom function sync complete: ${summary.created} created, ${summary.updated} updated, ` +\n `${summary.metadataUpdated} metadata-only, ${summary.skipped} skipped, ` +\n `${summary.rejected} rejected (test failed), ${summary.failed} failed${\n dryRun ? ' (dry run)' : ''\n }`,\n ),\n );\n }\n\n if (output.status === 'failed') {\n this.process.exit(1);\n }\n}\n"],"mappings":"21BAuDA,eAAsB,EAEpB,CACE,OACA,aACA,eACA,WACA,YACA,SACA,OACA,UACA,QACA,YACA,iBACA,YAEF,EACe,CACf,EAAoB,KAAK,QAAQ,CAEjC,IAAM,EAAM,KAAK,QAAQ,KAAK,CACxB,CAAE,oBAAmB,gBAAiB,EAAkC,EAAK,CACjF,GAAI,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"}
@@ -1,2 +1,2 @@
1
- import{i as e}from"./policy-project-discovery-DTSl0Gfl.mjs";import{n as t,r as n}from"./runOpa-ojIqU1tO.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import i from"node:path";import a from"colors";async function o({package:o,input:s,"stdin-input":c,format:l,schema:u,explain:d,metrics:f,instrument:p,profile:m,timeout:h,"var-values":g,"show-builtin-errors":_},v){if(r(this.process),n(),c&&s)throw Error(`Pass either --input or --stdin-input, not both.`);if(!c&&!s)throw Error(`Provide an input document with --input <path> or --stdin-input.`);let y,b;if(c)y=[`--stdin-input`],b=`stdin`;else{let e=i.resolve(this.process.cwd(),s);if(!this.fs.existsSync(e))throw Error(`Input file not found: ${e}`);y=[`--input`,e],b=e}let x=e(this.process.cwd(),v),S=u?i.resolve(this.process.cwd(),u):void 0;if(S&&!this.fs.existsSync(S))throw Error(`Schema path not found: ${S}`);let C=[`eval`,`--format`,l,...y,`-b`,x,`--ignore`,`*_test.rego`,...S?[`--schema`,S]:[],...d&&d!==`off`?[`--explain`,d]:[],...f?[`--metrics`]:[],...p?[`--instrument`]:[],...m?[`--profile`]:[],...h?[`--timeout`,h]:[],...g?[`--var-values`]:[],..._?[`--show-builtin-errors`]:[],o];this.logger.info(a.green(`Evaluating ${o} with input ${b}...`));let w=await t(C);w!==0&&this.process.exit(w)}export{o as _eval};
2
- //# sourceMappingURL=impl-Dd39KsYO.mjs.map
1
+ import{i as e}from"./policy-project-discovery-CND7N2HI.mjs";import{n as t,r as n}from"./runOpa-ojIqU1tO.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import i from"node:path";import a from"colors";async function o({package:o,input:s,"stdin-input":c,format:l,schema:u,explain:d,metrics:f,instrument:p,profile:m,timeout:h,"var-values":g,"show-builtin-errors":_},v){if(r(this.process),n(),c&&s)throw Error(`Pass either --input or --stdin-input, not both.`);if(!c&&!s)throw Error(`Provide an input document with --input <path> or --stdin-input.`);let y,b;if(c)y=[`--stdin-input`],b=`stdin`;else{let e=i.resolve(this.process.cwd(),s);if(!this.fs.existsSync(e))throw Error(`Input file not found: ${e}`);y=[`--input`,e],b=e}let x=e(this.process.cwd(),v),S=u?i.resolve(this.process.cwd(),u):void 0;if(S&&!this.fs.existsSync(S))throw Error(`Schema path not found: ${S}`);let C=[`eval`,`--format`,l,...y,`-b`,x,`--ignore`,`*_test.rego`,...S?[`--schema`,S]:[],...d&&d!==`off`?[`--explain`,d]:[],...f?[`--metrics`]:[],...p?[`--instrument`]:[],...m?[`--profile`]:[],...h?[`--timeout`,h]:[],...g?[`--var-values`]:[],..._?[`--show-builtin-errors`]:[],o];this.logger.info(a.green(`Evaluating ${o} with input ${b}...`));let w=await t(C);w!==0&&this.process.exit(w)}export{o as _eval};
2
+ //# sourceMappingURL=impl-C_lIkMLn2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"impl-C_lIkMLn2.mjs","names":[],"sources":["../src/commands/policy/eval/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 { resolvePolicyProjectDirectory } from '../../../lib/policy/policy-project-discovery.js';\nimport { assertOpaInstalled, runOpa } from '../helpers/index.js';\nimport type { PolicyEvalExplainMode, PolicyEvalFormat } from './command.js';\n\n/** CLI flags for `transcend policy eval`. */\nexport interface EvalCommandFlags {\n /** OPA query to evaluate (e.g. `data.example.result`). */\n package: string;\n /** Path to a JSON envelope input file. */\n input?: string;\n /** Read the input document from stdin (`opa eval --stdin-input`). */\n 'stdin-input': boolean;\n /** `opa eval --format` value. */\n format: PolicyEvalFormat;\n /** Optional `opa eval --schema` path. */\n schema?: string;\n /** Optional `opa eval --explain` mode. */\n explain?: PolicyEvalExplainMode;\n /** `opa eval --metrics`. */\n metrics: boolean;\n /** `opa eval --instrument`. */\n instrument: boolean;\n /** `opa eval --profile`. */\n profile: boolean;\n /** Optional `opa eval --timeout` duration. */\n timeout?: string;\n /** `opa eval --var-values`. */\n 'var-values': boolean;\n /** `opa eval --show-builtin-errors`. */\n 'show-builtin-errors': boolean;\n}\n\n/**\n * Evaluate one envelope against a local policy bundle via `opa eval`.\n *\n * @param this - CLI context\n * @param flags - Command flags\n * @param directory - Policy bundle directory containing a `.manifest`\n */\nexport async function _eval(\n this: LocalContext,\n {\n package: query,\n input,\n 'stdin-input': stdinInput,\n format,\n schema,\n explain,\n metrics,\n instrument,\n profile,\n timeout,\n 'var-values': varValues,\n 'show-builtin-errors': showBuiltinErrors,\n }: EvalCommandFlags,\n directory: string,\n): Promise<void> {\n doneInputValidation(this.process);\n\n assertOpaInstalled();\n\n if (stdinInput && input) {\n throw new Error('Pass either --input or --stdin-input, not both.');\n }\n if (!stdinInput && !input) {\n throw new Error('Provide an input document with --input <path> or --stdin-input.');\n }\n\n let inputArgs: string[];\n let inputLabel: string;\n if (stdinInput) {\n inputArgs = ['--stdin-input'];\n inputLabel = 'stdin';\n } else {\n const inputPath = path.resolve(this.process.cwd(), input!);\n if (!this.fs.existsSync(inputPath)) {\n throw new Error(`Input file not found: ${inputPath}`);\n }\n inputArgs = ['--input', inputPath];\n inputLabel = inputPath;\n }\n\n const bundlePath = resolvePolicyProjectDirectory(this.process.cwd(), directory);\n const schemaPath = schema ? path.resolve(this.process.cwd(), schema) : undefined;\n if (schemaPath && !this.fs.existsSync(schemaPath)) {\n throw new Error(`Schema path not found: ${schemaPath}`);\n }\n\n // Match check/publish and production Evaluate: `*_test.rego` is local-only and\n // never shipped. Keep `-b` / `--ignore` owned by the CLI (not pass-through).\n const args = [\n 'eval',\n '--format',\n format,\n ...inputArgs,\n '-b',\n bundlePath,\n '--ignore',\n '*_test.rego',\n ...(schemaPath ? ['--schema', schemaPath] : []),\n ...(explain && explain !== 'off' ? ['--explain', explain] : []),\n ...(metrics ? ['--metrics'] : []),\n ...(instrument ? ['--instrument'] : []),\n ...(profile ? ['--profile'] : []),\n ...(timeout ? ['--timeout', timeout] : []),\n ...(varValues ? ['--var-values'] : []),\n ...(showBuiltinErrors ? ['--show-builtin-errors'] : []),\n query,\n ];\n\n this.logger.info(colors.green(`Evaluating ${query} with input ${inputLabel}...`));\n\n const exitCode = await runOpa(args);\n if (exitCode !== 0) {\n this.process.exit(exitCode);\n }\n}\n"],"mappings":"qNA6CA,eAAsB,EAEpB,CACE,QAAS,EACT,QACA,cAAe,EACf,SACA,SACA,UACA,UACA,aACA,UACA,UACA,aAAc,EACd,sBAAuB,GAEzB,EACe,CAKf,GAJA,EAAoB,KAAK,QAAQ,CAEjC,GAAoB,CAEhB,GAAc,EAChB,MAAU,MAAM,kDAAkD,CAEpE,GAAI,CAAC,GAAc,CAAC,EAClB,MAAU,MAAM,kEAAkE,CAGpF,IAAI,EACA,EACJ,GAAI,EACF,EAAY,CAAC,gBAAgB,CAC7B,EAAa,YACR,CACL,IAAM,EAAY,EAAK,QAAQ,KAAK,QAAQ,KAAK,CAAE,EAAO,CAC1D,GAAI,CAAC,KAAK,GAAG,WAAW,EAAU,CAChC,MAAU,MAAM,yBAAyB,IAAY,CAEvD,EAAY,CAAC,UAAW,EAAU,CAClC,EAAa,EAGf,IAAM,EAAa,EAA8B,KAAK,QAAQ,KAAK,CAAE,EAAU,CACzE,EAAa,EAAS,EAAK,QAAQ,KAAK,QAAQ,KAAK,CAAE,EAAO,CAAG,IAAA,GACvE,GAAI,GAAc,CAAC,KAAK,GAAG,WAAW,EAAW,CAC/C,MAAU,MAAM,0BAA0B,IAAa,CAKzD,IAAM,EAAO,CACX,OACA,WACA,EACA,GAAG,EACH,KACA,EACA,WACA,cACA,GAAI,EAAa,CAAC,WAAY,EAAW,CAAG,EAAE,CAC9C,GAAI,GAAW,IAAY,MAAQ,CAAC,YAAa,EAAQ,CAAG,EAAE,CAC9D,GAAI,EAAU,CAAC,YAAY,CAAG,EAAE,CAChC,GAAI,EAAa,CAAC,eAAe,CAAG,EAAE,CACtC,GAAI,EAAU,CAAC,YAAY,CAAG,EAAE,CAChC,GAAI,EAAU,CAAC,YAAa,EAAQ,CAAG,EAAE,CACzC,GAAI,EAAY,CAAC,eAAe,CAAG,EAAE,CACrC,GAAI,EAAoB,CAAC,wBAAwB,CAAG,EAAE,CACtD,EACD,CAED,KAAK,OAAO,KAAK,EAAO,MAAM,cAAc,EAAM,cAAc,EAAW,KAAK,CAAC,CAEjF,IAAM,EAAW,MAAM,EAAO,EAAK,CAC/B,IAAa,GACf,KAAK,QAAQ,KAAK,EAAS"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./markSilentPrivacyRequests-BTI3rH-V.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,actions:i,statuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d}){t(this.process),await e({transcendUrl:r,requestActions:i,auth:n,requestIds:o,statuses:a,concurrency:d,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u})}export{n as markSilent};
2
- //# sourceMappingURL=impl-EDwngLc7.mjs.map
1
+ import{t as e}from"./markSilentPrivacyRequests-D7ncAg8k.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,actions:i,statuses:a,requestIds:o,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u,concurrency:d}){t(this.process),await e({transcendUrl:r,requestActions:i,auth:n,requestIds:o,statuses:a,concurrency:d,createdAtBefore:s,createdAtAfter:c,updatedAtBefore:l,updatedAtAfter:u})}export{n as markSilent};
2
+ //# sourceMappingURL=impl-CcPwm8a4.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-EDwngLc7.mjs","names":[],"sources":["../src/commands/request/mark-silent/impl.ts"],"sourcesContent":["import type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { markSilentPrivacyRequests } from '../../../lib/requests/index.js';\n\nexport interface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function markSilent(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n actions,\n statuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"iHAmBA,eAAsB,EAEpB,CACE,OACA,eACA,UACA,WACA,aACA,kBACA,iBACA,kBACA,iBACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA0B,CAC9B,eACA,eAAgB,EAChB,OACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
1
+ {"version":3,"file":"impl-CcPwm8a4.mjs","names":[],"sources":["../src/commands/request/mark-silent/impl.ts"],"sourcesContent":["import type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { markSilentPrivacyRequests } from '../../../lib/requests/index.js';\n\nexport interface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n updatedAtBefore?: Date;\n updatedAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function markSilent(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n actions,\n statuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n updatedAtBefore,\n updatedAtAfter,\n });\n}\n"],"mappings":"iHAmBA,eAAsB,EAEpB,CACE,OACA,eACA,UACA,WACA,aACA,kBACA,iBACA,kBACA,iBACA,eAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAA0B,CAC9B,eACA,eAAgB,EAChB,OACA,aACA,WACA,cACA,kBACA,iBACA,kBACA,iBACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./collectCsvFilesOrExit-BindZ0dF.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";import{n,r,t as i}from"./createPoolingCommandUi-BdtnLBBM.mjs";import a from"colors";import{CHILD_FLAG as o,PoolCancelledError as s,computePoolSize as c,resolveWorkerPath as l,runPool as u}from"@transcend-io/utils";function d(e){return n(e)}function f(e){return r(e)}const p={renderHeader:d,renderWorkers:f};async function m(n){t(this.process);let{directory:r,outputDir:d,clearOutputDir:f,chunkSizeMB:m,concurrency:h,viewerMode:g}=n,_=i(this,p,g),v=e(r,this),{poolSize:y,cpuCount:b}=c(h,v.length);this.logger.info(a.green(`Chunking ${v.length} CSV file(s) with pool size ${y} (CPU=${b})`));let x=v.map(e=>({filePath:e,options:{outputDir:d,clearOutputDir:f,chunkSizeMB:m}}));await u({title:`Chunk CSV - ${r}`,baseDir:r||d||this.process.cwd(),childFlag:o,childModulePath:l(import.meta.url,`commands/admin/chunk-csv/worker.mjs`),poolSize:y,cpuCount:b,filesTotal:v.length,hooks:{nextTask:()=>x.shift(),taskLabel:e=>e.filePath,initTotals:()=>({}),initSlotProgress:()=>void 0,onProgress:e=>e,onResult:(e,t)=>({totals:e,ok:!!t.ok}),postProcess:async()=>{}},viewerMode:g,..._}).catch(e=>{throw e instanceof s&&this.process.exit(130),e})}export{m as chunkCsv};
2
- //# sourceMappingURL=impl-DGtCNANL.mjs.map
1
+ import{t as e}from"./collectCsvFilesOrExit-BindZ0dF.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";import{n,r,t as i}from"./createPoolingCommandUi-DZx16Cn8.mjs";import a from"colors";import{CHILD_FLAG as o,PoolCancelledError as s,computePoolSize as c,resolveWorkerPath as l,runPool as u}from"@transcend-io/utils";function d(e){return n(e)}function f(e){return r(e)}const p={renderHeader:d,renderWorkers:f};async function m(n){t(this.process);let{directory:r,outputDir:d,clearOutputDir:f,chunkSizeMB:m,concurrency:h,viewerMode:g}=n,_=i(this,p,g),v=e(r,this),{poolSize:y,cpuCount:b}=c(h,v.length);this.logger.info(a.green(`Chunking ${v.length} CSV file(s) with pool size ${y} (CPU=${b})`));let x=v.map(e=>({filePath:e,options:{outputDir:d,clearOutputDir:f,chunkSizeMB:m}}));await u({title:`Chunk CSV - ${r}`,baseDir:r||d||this.process.cwd(),childFlag:o,childModulePath:l(import.meta.url,`commands/admin/chunk-csv/worker.mjs`),poolSize:y,cpuCount:b,filesTotal:v.length,hooks:{nextTask:()=>x.shift(),taskLabel:e=>e.filePath,initTotals:()=>({}),initSlotProgress:()=>void 0,onProgress:e=>e,onResult:(e,t)=>({totals:e,ok:!!t.ok}),postProcess:async()=>{}},viewerMode:g,..._}).catch(e=>{throw e instanceof s&&this.process.exit(130),e})}export{m as chunkCsv};
2
+ //# sourceMappingURL=impl-CjjiXsMh.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DGtCNANL.mjs","names":[],"sources":["../src/commands/admin/chunk-csv/ui/plugin.ts","../src/commands/admin/chunk-csv/impl.ts"],"sourcesContent":["import {\n makeHeader,\n makeWorkerRows,\n type ChunkSlotProgress,\n type CommonCtx,\n type DashboardPlugin,\n} from '../../../../lib/pooling/index.js';\n\n/**\n * Header for chunk-csv (no extra totals block).\n *\n * @param ctx - Dashboard context.\n * @returns Header lines.\n */\nfunction renderHeader<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n // no extra lines — reuse the shared header as-is\n return makeHeader(ctx);\n}\n\n/**\n * Worker rows for chunk-csv — share the generic row renderer.\n *\n * @param ctx - Dashboard context.\n * @returns Array of strings, each representing one worker row.\n */\nfunction renderWorkers<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n return makeWorkerRows(ctx);\n}\n\nexport const chunkCsvPlugin: DashboardPlugin<unknown, ChunkSlotProgress> = {\n renderHeader,\n renderWorkers,\n // no extras\n};\n","import {\n CHILD_FLAG,\n type PoolHooks,\n runPool,\n computePoolSize,\n PoolCancelledError,\n resolveWorkerPath,\n} from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { collectCsvFilesOrExit } from '../../../lib/helpers/collectCsvFilesOrExit.js';\nimport { createPoolingCommandUi } from '../../../lib/pooling/index.js';\nimport { chunkCsvPlugin } from './ui/index.js';\nimport type { ChunkProgress, ChunkResult, ChunkTask } from './worker.js';\n\n/**\n * Totals aggregate for this command.\n * We don’t need custom counters since the runner already tracks\n * completed/failed counts in its header — so we just use an empty record.\n */\ntype Totals = Record<string, never>;\n\n/**\n * CLI flags accepted by the `chunk-csv` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type ChunkCsvCommandFlags = {\n directory: string;\n outputDir?: string;\n clearOutputDir: boolean;\n chunkSizeMB: number;\n concurrency?: number;\n viewerMode: boolean;\n};\n\n/**\n * Parent entrypoint for chunking many CSVs in parallel using the worker pool runner.\n *\n * Lifecycle:\n * 1) Discover CSV inputs (exit if none).\n * 2) Compute pool size (CPU-count heuristic or --concurrency).\n * 3) Build a FIFO queue of `ChunkTask`s.\n * 4) Define pool hooks to drive task assignment, progress, and result handling.\n * 5) Launch the pool with `runPool`, rendering via the `chunkCsvPlugin`.\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function chunkCsv(this: LocalContext, flags: ChunkCsvCommandFlags): Promise<void> {\n doneInputValidation(this.process);\n\n const { directory, outputDir, clearOutputDir, chunkSizeMB, concurrency, viewerMode } = flags;\n const poolingUi = createPoolingCommandUi(this, chunkCsvPlugin, viewerMode);\n\n /* 1) Discover CSV inputs */\n const files = collectCsvFilesOrExit(directory, this);\n\n /* 2) Size the pool */\n const { poolSize, cpuCount } = computePoolSize(concurrency, files.length);\n\n this.logger.info(\n colors.green(\n `Chunking ${files.length} CSV file(s) with pool size ${poolSize} (CPU=${cpuCount})`,\n ),\n );\n\n /* 3) Prepare a simple FIFO queue of tasks (one per file). */\n const queue = files.map<ChunkTask>((filePath) => ({\n filePath,\n options: { outputDir, clearOutputDir, chunkSizeMB },\n }));\n\n /* 4) Define pool hooks to adapt runner to this command. */\n const hooks: PoolHooks<ChunkTask, ChunkProgress, ChunkResult, Totals> = {\n nextTask: () => queue.shift(),\n taskLabel: (t) => t.filePath,\n initTotals: () => ({}) as Totals,\n initSlotProgress: () => undefined,\n onProgress: (totals) => totals,\n onResult: (totals, res) => ({ totals, ok: !!res.ok }),\n // postProcess receives log context when viewerMode=true — we don’t need it here.\n postProcess: async () => {\n // nothing extra for chunk-csv\n },\n };\n\n /* 5) Launch the pool runner with our hooks and custom dashboard plugin. */\n await runPool({\n title: `Chunk CSV - ${directory}`,\n baseDir: directory || outputDir || this.process.cwd(),\n childFlag: CHILD_FLAG,\n childModulePath: resolveWorkerPath(import.meta.url, 'commands/admin/chunk-csv/worker.mjs'),\n poolSize,\n cpuCount,\n filesTotal: files.length,\n hooks,\n viewerMode,\n ...poolingUi,\n }).catch((err) => {\n if (err instanceof PoolCancelledError) {\n this.process.exit(130);\n }\n throw err;\n });\n}\n"],"mappings":"mUAcA,SAAS,EAAsB,EAAsD,CAEnF,OAAO,EAAW,EAAI,CASxB,SAAS,EAAuB,EAAsD,CACpF,OAAO,EAAe,EAAI,CAG5B,MAAa,EAA8D,CACzE,eACA,gBAED,CCkBD,eAAsB,EAA6B,EAA4C,CAC7F,EAAoB,KAAK,QAAQ,CAEjC,GAAM,CAAE,YAAW,YAAW,iBAAgB,cAAa,cAAa,cAAe,EACjF,EAAY,EAAuB,KAAM,EAAgB,EAAW,CAGpE,EAAQ,EAAsB,EAAW,KAAK,CAG9C,CAAE,WAAU,YAAa,EAAgB,EAAa,EAAM,OAAO,CAEzE,KAAK,OAAO,KACV,EAAO,MACL,YAAY,EAAM,OAAO,8BAA8B,EAAS,QAAQ,EAAS,GAClF,CACF,CAGD,IAAM,EAAQ,EAAM,IAAgB,IAAc,CAChD,WACA,QAAS,CAAE,YAAW,iBAAgB,cAAa,CACpD,EAAE,CAiBH,MAAM,EAAQ,CACZ,MAAO,eAAe,IACtB,QAAS,GAAa,GAAa,KAAK,QAAQ,KAAK,CACrD,UAAW,EACX,gBAAiB,EAAkB,OAAO,KAAK,IAAK,sCAAsC,CAC1F,WACA,WACA,WAAY,EAAM,OAClB,MAAA,CArBA,aAAgB,EAAM,OAAO,CAC7B,UAAY,GAAM,EAAE,SACpB,gBAAmB,EAAE,EACrB,qBAAwB,IAAA,GACxB,WAAa,GAAW,EACxB,UAAW,EAAQ,KAAS,CAAE,SAAQ,GAAI,CAAC,CAAC,EAAI,GAAI,EAEpD,YAAa,SAAY,GAcpB,CACL,aACA,GAAG,EACJ,CAAC,CAAC,MAAO,GAAQ,CAIhB,MAHI,aAAe,GACjB,KAAK,QAAQ,KAAK,IAAI,CAElB,GACN"}
1
+ {"version":3,"file":"impl-CjjiXsMh.mjs","names":[],"sources":["../src/commands/admin/chunk-csv/ui/plugin.ts","../src/commands/admin/chunk-csv/impl.ts"],"sourcesContent":["import {\n makeHeader,\n makeWorkerRows,\n type ChunkSlotProgress,\n type CommonCtx,\n type DashboardPlugin,\n} from '../../../../lib/pooling/index.js';\n\n/**\n * Header for chunk-csv (no extra totals block).\n *\n * @param ctx - Dashboard context.\n * @returns Header lines.\n */\nfunction renderHeader<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n // no extra lines — reuse the shared header as-is\n return makeHeader(ctx);\n}\n\n/**\n * Worker rows for chunk-csv — share the generic row renderer.\n *\n * @param ctx - Dashboard context.\n * @returns Array of strings, each representing one worker row.\n */\nfunction renderWorkers<TTotals>(ctx: CommonCtx<TTotals, ChunkSlotProgress>): string[] {\n return makeWorkerRows(ctx);\n}\n\nexport const chunkCsvPlugin: DashboardPlugin<unknown, ChunkSlotProgress> = {\n renderHeader,\n renderWorkers,\n // no extras\n};\n","import {\n CHILD_FLAG,\n type PoolHooks,\n runPool,\n computePoolSize,\n PoolCancelledError,\n resolveWorkerPath,\n} from '@transcend-io/utils';\nimport colors from 'colors';\n\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { collectCsvFilesOrExit } from '../../../lib/helpers/collectCsvFilesOrExit.js';\nimport { createPoolingCommandUi } from '../../../lib/pooling/index.js';\nimport { chunkCsvPlugin } from './ui/index.js';\nimport type { ChunkProgress, ChunkResult, ChunkTask } from './worker.js';\n\n/**\n * Totals aggregate for this command.\n * We don’t need custom counters since the runner already tracks\n * completed/failed counts in its header — so we just use an empty record.\n */\ntype Totals = Record<string, never>;\n\n/**\n * CLI flags accepted by the `chunk-csv` command.\n *\n * These are passed down from the CLI parser into the parent process.\n */\nexport type ChunkCsvCommandFlags = {\n directory: string;\n outputDir?: string;\n clearOutputDir: boolean;\n chunkSizeMB: number;\n concurrency?: number;\n viewerMode: boolean;\n};\n\n/**\n * Parent entrypoint for chunking many CSVs in parallel using the worker pool runner.\n *\n * Lifecycle:\n * 1) Discover CSV inputs (exit if none).\n * 2) Compute pool size (CPU-count heuristic or --concurrency).\n * 3) Build a FIFO queue of `ChunkTask`s.\n * 4) Define pool hooks to drive task assignment, progress, and result handling.\n * 5) Launch the pool with `runPool`, rendering via the `chunkCsvPlugin`.\n *\n * @param this - Bound CLI context (provides process exit + logging).\n * @param flags - CLI options for the run.\n */\nexport async function chunkCsv(this: LocalContext, flags: ChunkCsvCommandFlags): Promise<void> {\n doneInputValidation(this.process);\n\n const { directory, outputDir, clearOutputDir, chunkSizeMB, concurrency, viewerMode } = flags;\n const poolingUi = createPoolingCommandUi(this, chunkCsvPlugin, viewerMode);\n\n /* 1) Discover CSV inputs */\n const files = collectCsvFilesOrExit(directory, this);\n\n /* 2) Size the pool */\n const { poolSize, cpuCount } = computePoolSize(concurrency, files.length);\n\n this.logger.info(\n colors.green(\n `Chunking ${files.length} CSV file(s) with pool size ${poolSize} (CPU=${cpuCount})`,\n ),\n );\n\n /* 3) Prepare a simple FIFO queue of tasks (one per file). */\n const queue = files.map<ChunkTask>((filePath) => ({\n filePath,\n options: { outputDir, clearOutputDir, chunkSizeMB },\n }));\n\n /* 4) Define pool hooks to adapt runner to this command. */\n const hooks: PoolHooks<ChunkTask, ChunkProgress, ChunkResult, Totals> = {\n nextTask: () => queue.shift(),\n taskLabel: (t) => t.filePath,\n initTotals: () => ({}) as Totals,\n initSlotProgress: () => undefined,\n onProgress: (totals) => totals,\n onResult: (totals, res) => ({ totals, ok: !!res.ok }),\n // postProcess receives log context when viewerMode=true — we don’t need it here.\n postProcess: async () => {\n // nothing extra for chunk-csv\n },\n };\n\n /* 5) Launch the pool runner with our hooks and custom dashboard plugin. */\n await runPool({\n title: `Chunk CSV - ${directory}`,\n baseDir: directory || outputDir || this.process.cwd(),\n childFlag: CHILD_FLAG,\n childModulePath: resolveWorkerPath(import.meta.url, 'commands/admin/chunk-csv/worker.mjs'),\n poolSize,\n cpuCount,\n filesTotal: files.length,\n hooks,\n viewerMode,\n ...poolingUi,\n }).catch((err) => {\n if (err instanceof PoolCancelledError) {\n this.process.exit(130);\n }\n throw err;\n });\n}\n"],"mappings":"mUAcA,SAAS,EAAsB,EAAsD,CAEnF,OAAO,EAAW,EAAI,CASxB,SAAS,EAAuB,EAAsD,CACpF,OAAO,EAAe,EAAI,CAG5B,MAAa,EAA8D,CACzE,eACA,gBAED,CCkBD,eAAsB,EAA6B,EAA4C,CAC7F,EAAoB,KAAK,QAAQ,CAEjC,GAAM,CAAE,YAAW,YAAW,iBAAgB,cAAa,cAAa,cAAe,EACjF,EAAY,EAAuB,KAAM,EAAgB,EAAW,CAGpE,EAAQ,EAAsB,EAAW,KAAK,CAG9C,CAAE,WAAU,YAAa,EAAgB,EAAa,EAAM,OAAO,CAEzE,KAAK,OAAO,KACV,EAAO,MACL,YAAY,EAAM,OAAO,8BAA8B,EAAS,QAAQ,EAAS,GAClF,CACF,CAGD,IAAM,EAAQ,EAAM,IAAgB,IAAc,CAChD,WACA,QAAS,CAAE,YAAW,iBAAgB,cAAa,CACpD,EAAE,CAiBH,MAAM,EAAQ,CACZ,MAAO,eAAe,IACtB,QAAS,GAAa,GAAa,KAAK,QAAQ,KAAK,CACrD,UAAW,EACX,gBAAiB,EAAkB,OAAO,KAAK,IAAK,sCAAsC,CAC1F,WACA,WACA,WAAY,EAAM,OAClB,MAAA,CArBA,aAAgB,EAAM,OAAO,CAC7B,UAAY,GAAM,EAAE,SACpB,gBAAmB,EAAE,EACrB,qBAAwB,IAAA,GACxB,WAAa,GAAW,EACxB,UAAW,EAAQ,KAAS,CAAE,SAAQ,GAAI,CAAC,CAAC,EAAI,GAAI,EAEpD,YAAa,SAAY,GAcpB,CACL,aACA,GAAG,EACJ,CAAC,CAAC,MAAO,GAAQ,CAIhB,MAHI,aAAe,GACjB,KAAK,QAAQ,KAAK,IAAI,CAElB,GACN"}
@@ -1,2 +1,2 @@
1
- import{C as e}from"./codecs-CfcaFoZR.mjs";import{o as t}from"./readTranscendYaml-BfqQbPiT.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{ConsentTrackerStatus as r,DataFlowScope as i}from"@transcend-io/privacy-types";import a from"colors";import{decodeCodec as o}from"@transcend-io/type-utils";import*as s from"io-ts";function c({file:c,output:l}){n(this.process),this.fs.existsSync(c)||(this.logger.error(a.red(`File does not exist: --file="${c}"`)),this.process.exit(1));let u=o(s.array(e),this.fs.readFileSync(c,`utf-8`)),d=[],f=[];u.forEach(e=>{e.dataFlows.filter(({type:e})=>e!==i.CSP).forEach(e=>{d.push({value:e.value,type:e.type,status:r.Live,trackingPurposes:e.trackingPurposes})}),e.cookies.forEach(e=>{f.push({name:e.name,status:r.Live,trackingPurposes:e.trackingPurposes})})}),this.fs.writeFileSync(l,t({"data-flows":d,cookies:f})),this.logger.info(a.green(`Successfully wrote ${d.length} data flows and ${f.length} cookies to file "${l}"`))}export{c as consentManagerServiceJsonToYml};
2
- //# sourceMappingURL=impl-BLOhoP-b2.mjs.map
1
+ import{C as e}from"./codecs-8T8Jhxsr.mjs";import{o as t}from"./readTranscendYaml-D576bvzR.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";import{ConsentTrackerStatus as r,DataFlowScope as i}from"@transcend-io/privacy-types";import a from"colors";import{decodeCodec as o}from"@transcend-io/type-utils";import*as s from"io-ts";function c({file:c,output:l}){n(this.process),this.fs.existsSync(c)||(this.logger.error(a.red(`File does not exist: --file="${c}"`)),this.process.exit(1));let u=o(s.array(e),this.fs.readFileSync(c,`utf-8`)),d=[],f=[];u.forEach(e=>{e.dataFlows.filter(({type:e})=>e!==i.CSP).forEach(e=>{d.push({value:e.value,type:e.type,status:r.Live,trackingPurposes:e.trackingPurposes})}),e.cookies.forEach(e=>{f.push({name:e.name,status:r.Live,trackingPurposes:e.trackingPurposes})})}),this.fs.writeFileSync(l,t({"data-flows":d,cookies:f})),this.logger.info(a.green(`Successfully wrote ${d.length} data flows and ${f.length} cookies to file "${l}"`))}export{c as consentManagerServiceJsonToYml};
2
+ //# sourceMappingURL=impl-CzFfjx8n2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BLOhoP-b2.mjs","names":[],"sources":["../src/commands/inventory/consent-manager-service-json-to-yml/impl.ts"],"sourcesContent":["import { ConsentTrackerStatus, DataFlowScope } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport { ConsentManagerServiceMetadata, CookieInput, DataFlowInput } from '../../../codecs.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface ConsentManagerServiceJsonToYmlCommandFlags {\n file: string;\n output: string;\n}\n\nexport function consentManagerServiceJsonToYml(\n this: LocalContext,\n { file, output }: ConsentManagerServiceJsonToYmlCommandFlags,\n): void {\n doneInputValidation(this.process);\n\n // Ensure files exist\n if (!this.fs.existsSync(file)) {\n this.logger.error(colors.red(`File does not exist: --file=\"${file}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const services = decodeCodec(\n t.array(ConsentManagerServiceMetadata),\n this.fs.readFileSync(file, 'utf-8'),\n );\n\n // Create data flows and cookie configurations\n const dataFlows: DataFlowInput[] = [];\n const cookies: CookieInput[] = [];\n services.forEach((service) => {\n service.dataFlows\n .filter(({ type }) => type !== DataFlowScope.CSP)\n .forEach((dataFlow) => {\n dataFlows.push({\n value: dataFlow.value,\n type: dataFlow.type,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: dataFlow.trackingPurposes,\n });\n });\n\n service.cookies.forEach((cookie) => {\n cookies.push({\n name: cookie.name,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: cookie.trackingPurposes,\n });\n });\n });\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'data-flows': dataFlows,\n cookies,\n }),\n );\n\n this.logger.info(\n colors.green(\n `Successfully wrote ${dataFlows.length} data flows and ${cookies.length} cookies to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"mVAeA,SAAgB,EAEd,CAAE,OAAM,UACF,CACN,EAAoB,KAAK,QAAQ,CAG5B,KAAK,GAAG,WAAW,EAAK,GAC3B,KAAK,OAAO,MAAM,EAAO,IAAI,gCAAgC,EAAK,GAAG,CAAC,CACtE,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAW,EACf,EAAE,MAAM,EAA8B,CACtC,KAAK,GAAG,aAAa,EAAM,QAAQ,CACpC,CAGK,EAA6B,EAAE,CAC/B,EAAyB,EAAE,CACjC,EAAS,QAAS,GAAY,CAC5B,EAAQ,UACL,QAAQ,CAAE,UAAW,IAAS,EAAc,IAAI,CAChD,QAAS,GAAa,CACrB,EAAU,KAAK,CACb,MAAO,EAAS,MAChB,KAAM,EAAS,KACf,OAAQ,EAAqB,KAC7B,iBAAkB,EAAS,iBAC5B,CAAC,EACF,CAEJ,EAAQ,QAAQ,QAAS,GAAW,CAClC,EAAQ,KAAK,CACX,KAAM,EAAO,KACb,OAAQ,EAAqB,KAC7B,iBAAkB,EAAO,iBAC1B,CAAC,EACF,EACF,CAEF,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,aAAc,EACd,UACD,CAAC,CACH,CAED,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAU,OAAO,kBAAkB,EAAQ,OAAO,oBAAoB,EAAO,GACpG,CACF"}
1
+ {"version":3,"file":"impl-CzFfjx8n2.mjs","names":[],"sources":["../src/commands/inventory/consent-manager-service-json-to-yml/impl.ts"],"sourcesContent":["import { ConsentTrackerStatus, DataFlowScope } from '@transcend-io/privacy-types';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport * as t from 'io-ts';\n\nimport { ConsentManagerServiceMetadata, CookieInput, DataFlowInput } from '../../../codecs.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface ConsentManagerServiceJsonToYmlCommandFlags {\n file: string;\n output: string;\n}\n\nexport function consentManagerServiceJsonToYml(\n this: LocalContext,\n { file, output }: ConsentManagerServiceJsonToYmlCommandFlags,\n): void {\n doneInputValidation(this.process);\n\n // Ensure files exist\n if (!this.fs.existsSync(file)) {\n this.logger.error(colors.red(`File does not exist: --file=\"${file}\"`));\n this.process.exit(1);\n }\n\n // Read in each consent manager configuration\n const services = decodeCodec(\n t.array(ConsentManagerServiceMetadata),\n this.fs.readFileSync(file, 'utf-8'),\n );\n\n // Create data flows and cookie configurations\n const dataFlows: DataFlowInput[] = [];\n const cookies: CookieInput[] = [];\n services.forEach((service) => {\n service.dataFlows\n .filter(({ type }) => type !== DataFlowScope.CSP)\n .forEach((dataFlow) => {\n dataFlows.push({\n value: dataFlow.value,\n type: dataFlow.type,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: dataFlow.trackingPurposes,\n });\n });\n\n service.cookies.forEach((cookie) => {\n cookies.push({\n name: cookie.name,\n status: ConsentTrackerStatus.Live,\n trackingPurposes: cookie.trackingPurposes,\n });\n });\n });\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'data-flows': dataFlows,\n cookies,\n }),\n );\n\n this.logger.info(\n colors.green(\n `Successfully wrote ${dataFlows.length} data flows and ${cookies.length} cookies to file \"${output}\"`,\n ),\n );\n}\n"],"mappings":"mVAeA,SAAgB,EAEd,CAAE,OAAM,UACF,CACN,EAAoB,KAAK,QAAQ,CAG5B,KAAK,GAAG,WAAW,EAAK,GAC3B,KAAK,OAAO,MAAM,EAAO,IAAI,gCAAgC,EAAK,GAAG,CAAC,CACtE,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAW,EACf,EAAE,MAAM,EAA8B,CACtC,KAAK,GAAG,aAAa,EAAM,QAAQ,CACpC,CAGK,EAA6B,EAAE,CAC/B,EAAyB,EAAE,CACjC,EAAS,QAAS,GAAY,CAC5B,EAAQ,UACL,QAAQ,CAAE,UAAW,IAAS,EAAc,IAAI,CAChD,QAAS,GAAa,CACrB,EAAU,KAAK,CACb,MAAO,EAAS,MAChB,KAAM,EAAS,KACf,OAAQ,EAAqB,KAC7B,iBAAkB,EAAS,iBAC5B,CAAC,EACF,CAEJ,EAAQ,QAAQ,QAAS,GAAW,CAClC,EAAQ,KAAK,CACX,KAAM,EAAO,KACb,OAAQ,EAAqB,KAC7B,iBAAkB,EAAO,iBAC1B,CAAC,EACF,EACF,CAEF,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,aAAc,EACd,UACD,CAAC,CACH,CAED,KAAK,OAAO,KACV,EAAO,MACL,sBAAsB,EAAU,OAAO,kBAAkB,EAAQ,OAAO,oBAAoB,EAAO,GACpG,CACF"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./pushManualEnrichmentIdentifiersFromCsv--4dYCvyv.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,file:i,enricherId:a,concurrency:o,markSilent:s,sombraAuth:c}){t(this.process),await e({file:i,transcendUrl:r,enricherId:a,concurrency:o,markSilent:s,auth:n,sombraAuth:c})}export{n as pushIdentifiers};
2
- //# sourceMappingURL=impl-BXGpJz21.mjs.map
1
+ import{t as e}from"./pushManualEnrichmentIdentifiersFromCsv-R9BXYuFk.mjs";import{t}from"./done-input-validation-LiTaCEzF.mjs";async function n({auth:n,transcendUrl:r,file:i,enricherId:a,concurrency:o,markSilent:s,sombraAuth:c}){t(this.process),await e({file:i,transcendUrl:r,enricherId:a,concurrency:o,markSilent:s,auth:n,sombraAuth:c})}export{n as pushIdentifiers};
2
+ //# sourceMappingURL=impl-D6e2LNBm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-BXGpJz21.mjs","names":[],"sources":["../src/commands/request/preflight/push-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"8HAcA,eAAsB,EAEpB,CACE,OACA,eACA,OACA,aACA,cACA,aACA,cAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAuC,CAC3C,OACA,eACA,aACA,cACA,aACA,OACA,aACD,CAAC"}
1
+ {"version":3,"file":"impl-D6e2LNBm.mjs","names":[],"sources":["../src/commands/request/preflight/push-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context.js';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation.js';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment/index.js';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"8HAcA,eAAsB,EAEpB,CACE,OACA,eACA,OACA,aACA,cACA,aACA,cAEa,CACf,EAAoB,KAAK,QAAQ,CAEjC,MAAM,EAAuC,CAC3C,OACA,eACA,aACA,cACA,aACA,OACA,aACD,CAAC"}
@@ -1,2 +1,2 @@
1
- import{l as e}from"./constants-FDjw7bPS.mjs";import{t}from"./generateCrossAccountApiKeys-FtWwlf_L.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";async function r({email:r,password:i,apiKeyTitle:a,file:o,scopes:s,deleteExistingApiKey:c,createNewApiKey:l,parentOrganizationId:u,transcendUrl:d}){n(this.process);let{errors:f,apiKeys:p}=await t({transcendUrl:d,password:i,email:r,parentOrganizationId:u,deleteExistingApiKey:c,createNewApiKey:l,apiKeyTitle:a,scopes:s.map(t=>e[t].name)});this.fs.writeFileSync(o,`${JSON.stringify(p,null,2)}\n`),f.length>0&&this.process.exit(1)}export{r as generateApiKeys};
2
- //# sourceMappingURL=impl-SOebshza.mjs.map
1
+ import{l as e}from"./constants-DAx9VK1C.mjs";import{t}from"./generateCrossAccountApiKeys-CjmSyfwm.mjs";import{t as n}from"./done-input-validation-LiTaCEzF.mjs";async function r({email:r,password:i,apiKeyTitle:a,file:o,scopes:s,deleteExistingApiKey:c,createNewApiKey:l,parentOrganizationId:u,transcendUrl:d}){n(this.process);let{errors:f,apiKeys:p}=await t({transcendUrl:d,password:i,email:r,parentOrganizationId:u,deleteExistingApiKey:c,createNewApiKey:l,apiKeyTitle:a,scopes:s.map(t=>e[t].name)});this.fs.writeFileSync(o,`${JSON.stringify(p,null,2)}\n`),f.length>0&&this.process.exit(1)}export{r as generateApiKeys};
2
+ //# sourceMappingURL=impl-D8yF0jw9.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-SOebshza.mjs","names":[],"sources":["../src/commands/admin/generate-api-keys/impl.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\n\nimport { SCOPES_BY_TITLE } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { generateCrossAccountApiKeys } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\n\n// Command flag interface\nexport interface GenerateApiKeysCommandFlags {\n email: string;\n password: string;\n apiKeyTitle: string;\n file: string;\n scopes: string[];\n deleteExistingApiKey: boolean;\n createNewApiKey: boolean;\n parentOrganizationId?: string;\n transcendUrl: string;\n}\n\n// Command implementation\nexport async function generateApiKeys(\n this: LocalContext,\n {\n email,\n password,\n apiKeyTitle,\n file,\n scopes,\n deleteExistingApiKey,\n createNewApiKey,\n parentOrganizationId,\n transcendUrl,\n }: GenerateApiKeysCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const scopeNames = scopes.map((scopeTitle) => SCOPES_BY_TITLE[scopeTitle].name as ScopeName);\n\n // Upload privacy requests\n const { errors, apiKeys } = await generateCrossAccountApiKeys({\n transcendUrl,\n password,\n email,\n parentOrganizationId,\n deleteExistingApiKey,\n createNewApiKey,\n apiKeyTitle,\n scopes: scopeNames,\n });\n\n // Write to disk\n this.fs.writeFileSync(file, `${JSON.stringify(apiKeys, null, 2)}\\n`);\n if (errors.length > 0) {\n this.process.exit(1);\n }\n}\n"],"mappings":"gKAqBA,eAAsB,EAEpB,CACE,QACA,WACA,cACA,OACA,SACA,uBACA,kBACA,uBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAKjC,GAAM,CAAE,SAAQ,WAAY,MAAM,EAA4B,CAC5D,eACA,WACA,QACA,uBACA,uBACA,kBACA,cACA,OAXiB,EAAO,IAAK,GAAe,EAAgB,GAAY,KAWtD,CACnB,CAAC,CAGF,KAAK,GAAG,cAAc,EAAM,GAAG,KAAK,UAAU,EAAS,KAAM,EAAE,CAAC,IAAI,CAChE,EAAO,OAAS,GAClB,KAAK,QAAQ,KAAK,EAAE"}
1
+ {"version":3,"file":"impl-D8yF0jw9.mjs","names":[],"sources":["../src/commands/admin/generate-api-keys/impl.ts"],"sourcesContent":["import { ScopeName } from '@transcend-io/privacy-types';\n\nimport { SCOPES_BY_TITLE } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { generateCrossAccountApiKeys } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\n\n// Command flag interface\nexport interface GenerateApiKeysCommandFlags {\n email: string;\n password: string;\n apiKeyTitle: string;\n file: string;\n scopes: string[];\n deleteExistingApiKey: boolean;\n createNewApiKey: boolean;\n parentOrganizationId?: string;\n transcendUrl: string;\n}\n\n// Command implementation\nexport async function generateApiKeys(\n this: LocalContext,\n {\n email,\n password,\n apiKeyTitle,\n file,\n scopes,\n deleteExistingApiKey,\n createNewApiKey,\n parentOrganizationId,\n transcendUrl,\n }: GenerateApiKeysCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n const scopeNames = scopes.map((scopeTitle) => SCOPES_BY_TITLE[scopeTitle].name as ScopeName);\n\n // Upload privacy requests\n const { errors, apiKeys } = await generateCrossAccountApiKeys({\n transcendUrl,\n password,\n email,\n parentOrganizationId,\n deleteExistingApiKey,\n createNewApiKey,\n apiKeyTitle,\n scopes: scopeNames,\n });\n\n // Write to disk\n this.fs.writeFileSync(file, `${JSON.stringify(apiKeys, null, 2)}\\n`);\n if (errors.length > 0) {\n this.process.exit(1);\n }\n}\n"],"mappings":"gKAqBA,eAAsB,EAEpB,CACE,QACA,WACA,cACA,OACA,SACA,uBACA,kBACA,uBACA,gBAEa,CACf,EAAoB,KAAK,QAAQ,CAKjC,GAAM,CAAE,SAAQ,WAAY,MAAM,EAA4B,CAC5D,eACA,WACA,QACA,uBACA,uBACA,kBACA,cACA,OAXiB,EAAO,IAAK,GAAe,EAAgB,GAAY,KAWtD,CACnB,CAAC,CAGF,KAAK,GAAG,cAAc,EAAM,GAAG,KAAK,UAAU,EAAS,KAAM,EAAE,CAAC,IAAI,CAChE,EAAO,OAAS,GAClB,KAAK,QAAQ,KAAK,EAAE"}
@@ -1,2 +1,2 @@
1
- import{o as e,r as t}from"./readTranscendYaml-BfqQbPiT.mjs";import{t as n}from"./listFiles-DDGCBdtx.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{t as i}from"./dataFlowsToDataSilos-CRqbNjZ0.mjs";import{difference as a}from"lodash-es";import o from"node:path";import s from"colors";import{buildTranscendGraphQLClient as c,fetchAndIndexCatalogs as l}from"@transcend-io/sdk";async function u({auth:u,dataFlowsYmlFolder:d,output:f,ignoreYmls:p=[],transcendUrl:m}){r(this.process),(!this.fs.existsSync(d)||!this.fs.lstatSync(d).isDirectory())&&(this.logger.error(s.red(`Folder does not exist: "${d}"`)),this.process.exit(1));let h=p.map(e=>e.split(`.`)[0]),g=n(this.fs.readdirSync(d)).map(e=>{let n=o.join(d,e),{"data-flows":r=[]}=t(this.fs.readFileSync(n,`utf8`),{},n),{adTechDataSilos:a,siteTechDataSilos:s}=i(r,{serviceToSupportedIntegration:S,serviceToTitle:x});return{adTechDataSilos:a,siteTechDataSilos:s,organizationName:e.split(`.`)[0]}}),_={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t,organizationName:n})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName;_[t]||(_[t]=[]),_[t].push(n),_[t]=[...new Set(_[t])]})});let v=[...new Set(g.map(({adTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],y=a([...new Set(g.map(({siteTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],v),b={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName,n=e.attributes?.find(e=>e.key===`Found On Domain`);b[t]||(b[t]=[]),b[t].push(...n?.values||[]),b[t]=[...new Set(b[t])]})});let{serviceToTitle:x,serviceToSupportedIntegration:S}=await l(c(m,u),{logger:this.logger}),C=[...v,...y].map(e=>({title:x[e],...S[e]?{integrationName:e}:{integrationName:`promptAPerson`,"outer-type":e},attributes:[{key:`Tech Type`,values:[`Ad Tech`]},{key:`Business Units`,values:a(_[e]||[],h)},{key:`Found On Domain`,values:b[e]||[]}]}));this.logger.log(`Total Services: ${C.length}`),this.logger.log(`Ad Tech Services: ${v.length}`),this.logger.log(`Site Tech Services: ${y.length}`),this.fs.writeFileSync(f,e({"data-silos":C}))}export{u as deriveDataSilosFromDataFlowsCrossInstance};
2
- //# sourceMappingURL=impl-DeCRXfAh2.mjs.map
1
+ import{o as e,r as t}from"./readTranscendYaml-D576bvzR.mjs";import{t as n}from"./listFiles-DDGCBdtx.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{t as i}from"./dataFlowsToDataSilos-CRqbNjZ0.mjs";import{difference as a}from"lodash-es";import o from"node:path";import s from"colors";import{buildTranscendGraphQLClient as c,fetchAndIndexCatalogs as l}from"@transcend-io/sdk";async function u({auth:u,dataFlowsYmlFolder:d,output:f,ignoreYmls:p=[],transcendUrl:m}){r(this.process),(!this.fs.existsSync(d)||!this.fs.lstatSync(d).isDirectory())&&(this.logger.error(s.red(`Folder does not exist: "${d}"`)),this.process.exit(1));let h=p.map(e=>e.split(`.`)[0]),g=n(this.fs.readdirSync(d)).map(e=>{let n=o.join(d,e),{"data-flows":r=[]}=t(this.fs.readFileSync(n,`utf8`),{},n),{adTechDataSilos:a,siteTechDataSilos:s}=i(r,{serviceToSupportedIntegration:S,serviceToTitle:x});return{adTechDataSilos:a,siteTechDataSilos:s,organizationName:e.split(`.`)[0]}}),_={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t,organizationName:n})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName;_[t]||(_[t]=[]),_[t].push(n),_[t]=[...new Set(_[t])]})});let v=[...new Set(g.map(({adTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],y=a([...new Set(g.map(({siteTechDataSilos:e})=>e.map(e=>e[`outer-type`]||e.integrationName)).flat())],v),b={};g.forEach(({adTechDataSilos:e,siteTechDataSilos:t})=>{[...e,...t].forEach(e=>{let t=e[`outer-type`]||e.integrationName,n=e.attributes?.find(e=>e.key===`Found On Domain`);b[t]||(b[t]=[]),b[t].push(...n?.values||[]),b[t]=[...new Set(b[t])]})});let{serviceToTitle:x,serviceToSupportedIntegration:S}=await l(c(m,u),{logger:this.logger}),C=[...v,...y].map(e=>({title:x[e],...S[e]?{integrationName:e}:{integrationName:`promptAPerson`,"outer-type":e},attributes:[{key:`Tech Type`,values:[`Ad Tech`]},{key:`Business Units`,values:a(_[e]||[],h)},{key:`Found On Domain`,values:b[e]||[]}]}));this.logger.log(`Total Services: ${C.length}`),this.logger.log(`Ad Tech Services: ${v.length}`),this.logger.log(`Site Tech Services: ${y.length}`),this.fs.writeFileSync(f,e({"data-silos":C}))}export{u as deriveDataSilosFromDataFlowsCrossInstance};
2
+ //# sourceMappingURL=impl-DEF-meSg2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DeCRXfAh2.mjs","names":[],"sources":["../src/commands/inventory/derive-data-silos-from-data-flows-cross-instance/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { buildTranscendGraphQLClient, fetchAndIndexCatalogs } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { difference } from 'lodash-es';\n\nimport { DataFlowInput } from '../../../codecs.js';\nimport type { LocalContext } from '../../../context.js';\nimport { filterFileNames } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { dataFlowsToDataSilos } from '../../../lib/consent-manager/dataFlowsToDataSilos.js';\nimport { parseTranscendYaml, serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface DeriveDataSilosFromDataFlowsCrossInstanceCommandFlags {\n auth: string;\n dataFlowsYmlFolder: string;\n output: string;\n ignoreYmls?: string[];\n transcendUrl: string;\n}\n\nexport async function deriveDataSilosFromDataFlowsCrossInstance(\n this: LocalContext,\n {\n auth,\n dataFlowsYmlFolder,\n output,\n ignoreYmls = [],\n transcendUrl,\n }: DeriveDataSilosFromDataFlowsCrossInstanceCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Ensure folder is passed\n if (\n !this.fs.existsSync(dataFlowsYmlFolder) ||\n !this.fs.lstatSync(dataFlowsYmlFolder).isDirectory()\n ) {\n this.logger.error(colors.red(`Folder does not exist: \"${dataFlowsYmlFolder}\"`));\n this.process.exit(1);\n }\n\n // Ignore the data flows in these yml files\n const instancesToIgnore = ignoreYmls.map((x) => x.split('.')[0]);\n\n // Map over each data flow yml file and convert to data silo configurations\n const dataSiloInputs = filterFileNames(this.fs.readdirSync(dataFlowsYmlFolder)).map(\n (directory) => {\n const inputPath = path.join(dataFlowsYmlFolder, directory);\n\n // read in the data flows for a specific instance\n const { 'data-flows': dataFlows = [] } = parseTranscendYaml(\n this.fs.readFileSync(inputPath, 'utf8'),\n {},\n inputPath,\n );\n\n // map the data flows to data silos\n const { adTechDataSilos, siteTechDataSilos } = dataFlowsToDataSilos(\n dataFlows as DataFlowInput[],\n {\n serviceToSupportedIntegration,\n serviceToTitle,\n },\n );\n\n return {\n adTechDataSilos,\n siteTechDataSilos,\n organizationName: directory.split('.')[0],\n };\n },\n );\n\n // Mapping from service name to instances that have that service\n const serviceToInstance: { [k in string]: string[] } = {};\n dataSiloInputs.forEach(({ adTechDataSilos, siteTechDataSilos, organizationName }) => {\n const allDataSilos = [...adTechDataSilos, ...siteTechDataSilos];\n allDataSilos.forEach((dataSilo) => {\n const service = dataSilo['outer-type'] || dataSilo.integrationName;\n // create mapping to instance\n if (!serviceToInstance[service]) {\n serviceToInstance[service] = [];\n }\n serviceToInstance[service]!.push(organizationName);\n serviceToInstance[service] = [...new Set(serviceToInstance[service])];\n });\n });\n\n // List of ad tech integrations\n const adTechIntegrations = [\n ...new Set(\n dataSiloInputs\n .map(({ adTechDataSilos }) =>\n adTechDataSilos.map((silo) => silo['outer-type'] || silo.integrationName),\n )\n .flat(),\n ),\n ];\n\n // List of site tech integrations\n const siteTechIntegrations = difference(\n [\n ...new Set(\n dataSiloInputs\n .map(({ siteTechDataSilos }) =>\n siteTechDataSilos.map((silo) => silo['outer-type'] || silo.integrationName),\n )\n .flat(),\n ),\n ],\n adTechIntegrations,\n );\n\n // Mapping from service name to list of\n const serviceToFoundOnDomain: { [k in string]: string[] } = {};\n dataSiloInputs.forEach(({ adTechDataSilos, siteTechDataSilos }) => {\n const allDataSilos = [...adTechDataSilos, ...siteTechDataSilos];\n allDataSilos.forEach((dataSilo) => {\n const service = dataSilo['outer-type'] || dataSilo.integrationName;\n const foundOnDomain = dataSilo.attributes?.find((attr) => attr.key === 'Found On Domain');\n // create mapping to instance\n if (!serviceToFoundOnDomain[service]) {\n serviceToFoundOnDomain[service] = [];\n }\n serviceToFoundOnDomain[service]!.push(...(foundOnDomain?.values || []));\n serviceToFoundOnDomain[service] = [...new Set(serviceToFoundOnDomain[service])];\n });\n });\n\n // Fetch all integrations in the catalog\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { serviceToTitle, serviceToSupportedIntegration } = await fetchAndIndexCatalogs(client, {\n logger: this.logger,\n });\n\n // construct the aggregated data silo inputs\n const dataSilos = [...adTechIntegrations, ...siteTechIntegrations].map((service) => ({\n title: serviceToTitle[service],\n ...(serviceToSupportedIntegration[service]\n ? { integrationName: service }\n : { integrationName: 'promptAPerson', 'outer-type': service }),\n attributes: [\n {\n key: 'Tech Type',\n values: ['Ad Tech'],\n },\n {\n key: 'Business Units',\n values: difference(serviceToInstance[service] || [], instancesToIgnore),\n },\n {\n key: 'Found On Domain',\n values: serviceToFoundOnDomain[service] || [],\n },\n ],\n }));\n\n // Log output\n this.logger.log(`Total Services: ${dataSilos.length}`);\n this.logger.log(`Ad Tech Services: ${adTechIntegrations.length}`);\n this.logger.log(`Site Tech Services: ${siteTechIntegrations.length}`);\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'data-silos': dataSilos,\n }),\n );\n}\n"],"mappings":"2YAqBA,eAAsB,EAEpB,CACE,OACA,qBACA,SACA,aAAa,EAAE,CACf,gBAEa,CACf,EAAoB,KAAK,QAAQ,EAI/B,CAAC,KAAK,GAAG,WAAW,EAAmB,EACvC,CAAC,KAAK,GAAG,UAAU,EAAmB,CAAC,aAAa,IAEpD,KAAK,OAAO,MAAM,EAAO,IAAI,2BAA2B,EAAmB,GAAG,CAAC,CAC/E,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAoB,EAAW,IAAK,GAAM,EAAE,MAAM,IAAI,C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,KAAK,GAAI,GAAe,QAAU,EAAE,CAAE,CACvE,EAAuB,GAAW,CAAC,GAAG,IAAI,IAAI,EAAuB,GAAS,CAAC,EAC/E,EACF,CAIF,GAAM,CAAE,iBAAgB,iCAAkC,MAAM,EADjD,EAA4B,EAAc,EACmC,CAAE,CAC5F,OAAQ,KAAK,OACd,CAAC,CAGI,EAAY,CAAC,GAAG,EAAoB,GAAG,EAAqB,CAAC,IAAK,IAAa,CACnF,MAAO,EAAe,GACtB,GAAI,EAA8B,GAC9B,CAAE,gBAAiB,EAAS,CAC5B,CAAE,gBAAiB,gBAAiB,aAAc,EAAS,CAC/D,WAAY,CACV,CACE,IAAK,YACL,OAAQ,CAAC,UAAU,CACpB,CACD,CACE,IAAK,iBACL,OAAQ,EAAW,EAAkB,IAAY,EAAE,CAAE,EAAkB,CACxE,CACD,CACE,IAAK,kBACL,OAAQ,EAAuB,IAAY,EAAE,CAC9C,CACF,CACF,EAAE,CAGH,KAAK,OAAO,IAAI,mBAAmB,EAAU,SAAS,CACtD,KAAK,OAAO,IAAI,qBAAqB,EAAmB,SAAS,CACjE,KAAK,OAAO,IAAI,uBAAuB,EAAqB,SAAS,CAErE,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,aAAc,EACf,CAAC,CACH"}
1
+ {"version":3,"file":"impl-DEF-meSg2.mjs","names":[],"sources":["../src/commands/inventory/derive-data-silos-from-data-flows-cross-instance/impl.ts"],"sourcesContent":["import path from 'node:path';\n\nimport { buildTranscendGraphQLClient, fetchAndIndexCatalogs } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { difference } from 'lodash-es';\n\nimport { DataFlowInput } from '../../../codecs.js';\nimport type { LocalContext } from '../../../context.js';\nimport { filterFileNames } from '../../../lib/api-keys/index.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { dataFlowsToDataSilos } from '../../../lib/consent-manager/dataFlowsToDataSilos.js';\nimport { parseTranscendYaml, serializeTranscendYaml } from '../../../lib/readTranscendYaml.js';\n\nexport interface DeriveDataSilosFromDataFlowsCrossInstanceCommandFlags {\n auth: string;\n dataFlowsYmlFolder: string;\n output: string;\n ignoreYmls?: string[];\n transcendUrl: string;\n}\n\nexport async function deriveDataSilosFromDataFlowsCrossInstance(\n this: LocalContext,\n {\n auth,\n dataFlowsYmlFolder,\n output,\n ignoreYmls = [],\n transcendUrl,\n }: DeriveDataSilosFromDataFlowsCrossInstanceCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n // Ensure folder is passed\n if (\n !this.fs.existsSync(dataFlowsYmlFolder) ||\n !this.fs.lstatSync(dataFlowsYmlFolder).isDirectory()\n ) {\n this.logger.error(colors.red(`Folder does not exist: \"${dataFlowsYmlFolder}\"`));\n this.process.exit(1);\n }\n\n // Ignore the data flows in these yml files\n const instancesToIgnore = ignoreYmls.map((x) => x.split('.')[0]);\n\n // Map over each data flow yml file and convert to data silo configurations\n const dataSiloInputs = filterFileNames(this.fs.readdirSync(dataFlowsYmlFolder)).map(\n (directory) => {\n const inputPath = path.join(dataFlowsYmlFolder, directory);\n\n // read in the data flows for a specific instance\n const { 'data-flows': dataFlows = [] } = parseTranscendYaml(\n this.fs.readFileSync(inputPath, 'utf8'),\n {},\n inputPath,\n );\n\n // map the data flows to data silos\n const { adTechDataSilos, siteTechDataSilos } = dataFlowsToDataSilos(\n dataFlows as DataFlowInput[],\n {\n serviceToSupportedIntegration,\n serviceToTitle,\n },\n );\n\n return {\n adTechDataSilos,\n siteTechDataSilos,\n organizationName: directory.split('.')[0],\n };\n },\n );\n\n // Mapping from service name to instances that have that service\n const serviceToInstance: { [k in string]: string[] } = {};\n dataSiloInputs.forEach(({ adTechDataSilos, siteTechDataSilos, organizationName }) => {\n const allDataSilos = [...adTechDataSilos, ...siteTechDataSilos];\n allDataSilos.forEach((dataSilo) => {\n const service = dataSilo['outer-type'] || dataSilo.integrationName;\n // create mapping to instance\n if (!serviceToInstance[service]) {\n serviceToInstance[service] = [];\n }\n serviceToInstance[service]!.push(organizationName);\n serviceToInstance[service] = [...new Set(serviceToInstance[service])];\n });\n });\n\n // List of ad tech integrations\n const adTechIntegrations = [\n ...new Set(\n dataSiloInputs\n .map(({ adTechDataSilos }) =>\n adTechDataSilos.map((silo) => silo['outer-type'] || silo.integrationName),\n )\n .flat(),\n ),\n ];\n\n // List of site tech integrations\n const siteTechIntegrations = difference(\n [\n ...new Set(\n dataSiloInputs\n .map(({ siteTechDataSilos }) =>\n siteTechDataSilos.map((silo) => silo['outer-type'] || silo.integrationName),\n )\n .flat(),\n ),\n ],\n adTechIntegrations,\n );\n\n // Mapping from service name to list of\n const serviceToFoundOnDomain: { [k in string]: string[] } = {};\n dataSiloInputs.forEach(({ adTechDataSilos, siteTechDataSilos }) => {\n const allDataSilos = [...adTechDataSilos, ...siteTechDataSilos];\n allDataSilos.forEach((dataSilo) => {\n const service = dataSilo['outer-type'] || dataSilo.integrationName;\n const foundOnDomain = dataSilo.attributes?.find((attr) => attr.key === 'Found On Domain');\n // create mapping to instance\n if (!serviceToFoundOnDomain[service]) {\n serviceToFoundOnDomain[service] = [];\n }\n serviceToFoundOnDomain[service]!.push(...(foundOnDomain?.values || []));\n serviceToFoundOnDomain[service] = [...new Set(serviceToFoundOnDomain[service])];\n });\n });\n\n // Fetch all integrations in the catalog\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const { serviceToTitle, serviceToSupportedIntegration } = await fetchAndIndexCatalogs(client, {\n logger: this.logger,\n });\n\n // construct the aggregated data silo inputs\n const dataSilos = [...adTechIntegrations, ...siteTechIntegrations].map((service) => ({\n title: serviceToTitle[service],\n ...(serviceToSupportedIntegration[service]\n ? { integrationName: service }\n : { integrationName: 'promptAPerson', 'outer-type': service }),\n attributes: [\n {\n key: 'Tech Type',\n values: ['Ad Tech'],\n },\n {\n key: 'Business Units',\n values: difference(serviceToInstance[service] || [], instancesToIgnore),\n },\n {\n key: 'Found On Domain',\n values: serviceToFoundOnDomain[service] || [],\n },\n ],\n }));\n\n // Log output\n this.logger.log(`Total Services: ${dataSilos.length}`);\n this.logger.log(`Ad Tech Services: ${adTechIntegrations.length}`);\n this.logger.log(`Site Tech Services: ${siteTechIntegrations.length}`);\n\n this.fs.writeFileSync(\n output,\n serializeTranscendYaml({\n 'data-silos': dataSilos,\n }),\n );\n}\n"],"mappings":"2YAqBA,eAAsB,EAEpB,CACE,OACA,qBACA,SACA,aAAa,EAAE,CACf,gBAEa,CACf,EAAoB,KAAK,QAAQ,EAI/B,CAAC,KAAK,GAAG,WAAW,EAAmB,EACvC,CAAC,KAAK,GAAG,UAAU,EAAmB,CAAC,aAAa,IAEpD,KAAK,OAAO,MAAM,EAAO,IAAI,2BAA2B,EAAmB,GAAG,CAAC,CAC/E,KAAK,QAAQ,KAAK,EAAE,EAItB,IAAM,EAAoB,EAAW,IAAK,GAAM,EAAE,MAAM,IAAI,CAAC,GAAG,CAG1D,EAAiB,EAAgB,KAAK,GAAG,YAAY,EAAmB,CAAC,CAAC,IAC7E,GAAc,CACb,IAAM,EAAY,EAAK,KAAK,EAAoB,EAAU,CAGpD,CAAE,aAAc,EAAY,EAAE,EAAK,EACvC,KAAK,GAAG,aAAa,EAAW,OAAO,CACvC,EAAE,CACF,EACD,CAGK,CAAE,kBAAiB,qBAAsB,EAC7C,EACA,CACE,gCACA,iBACD,CACF,CAED,MAAO,CACL,kBACA,oBACA,iBAAkB,EAAU,MAAM,IAAI,CAAC,GACxC,EAEJ,CAGK,EAAiD,EAAE,CACzD,EAAe,SAAS,CAAE,kBAAiB,oBAAmB,sBAAuB,CAEnF,CADsB,GAAG,EAAiB,GAAG,EACjC,CAAC,QAAS,GAAa,CACjC,IAAM,EAAU,EAAS,eAAiB,EAAS,gBAE9C,EAAkB,KACrB,EAAkB,GAAW,EAAE,EAEjC,EAAkB,GAAU,KAAK,EAAiB,CAClD,EAAkB,GAAW,CAAC,GAAG,IAAI,IAAI,EAAkB,GAAS,CAAC,EACrE,EACF,CAGF,IAAM,EAAqB,CACzB,GAAG,IAAI,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BAAuB,EAAqB,SAAS,CAErE,KAAK,GAAG,cACN,EACA,EAAuB,CACrB,aAAc,EACf,CAAC,CACH"}
@@ -1,2 +1,2 @@
1
- import{n as e}from"./constants-FDjw7bPS.mjs";import{s as t}from"./writeCsv-CNZrq3zU.mjs";import{t as n}from"./pullAllDatapoints-CNqQSSmF.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{groupBy as i,uniq as a}from"lodash-es";import o from"colors";import{buildTranscendGraphQLClient as s}from"@transcend-io/sdk";async function c({auth:c,file:l,transcendUrl:u,dataSiloIds:d,includeAttributes:f,includeGuessedCategories:p,parentCategories:m,subCategories:h=[]}){r(this.process);try{let e=await n(s(u,c),{dataSiloIds:d,includeGuessedCategories:p,parentCategories:m,includeAttributes:f,subCategories:h});this.logger.info(o.magenta(`Writing datapoints to file "${l}"...`));let r=[];await t(l,e.map(e=>{let t={"Property ID":e.id,"Data Silo":e.dataSilo.title,Object:e.dataPoint.name,"Object Path":e.dataPoint.path.join(`.`),Property:e.name,"Property Description":e.description,"Data Categories":e.categories.map(e=>`${e.category}:${e.name}`).join(`, `),"Guessed Category":e.pendingCategoryGuesses?.[0]?`${e.pendingCategoryGuesses[0].category.category}:${e.pendingCategoryGuesses[0].category.name}`:``,"Processing Purposes":e.purposes.map(e=>`${e.purpose}:${e.name}`).join(`, `),...Object.entries(i(e.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[t,n])=>(e[t]=n.map(e=>e.name).join(`,`),e),{})};return r=a([...r,...Object.keys(t)]),t}),r)}catch(e){this.logger.error(o.red(`An error occurred syncing the datapoints: ${e.message}`)),this.process.exit(1)}this.logger.info(o.green(`Successfully synced datapoints to disk at ${l}! View at ${e}`))}export{c as pullDatapoints};
2
- //# sourceMappingURL=impl-DZoTWLfw2.mjs.map
1
+ import{n as e}from"./constants-DAx9VK1C.mjs";import{s as t}from"./writeCsv-CNZrq3zU.mjs";import{t as n}from"./pullAllDatapoints-CNqQSSmF.mjs";import{t as r}from"./done-input-validation-LiTaCEzF.mjs";import{groupBy as i,uniq as a}from"lodash-es";import o from"colors";import{buildTranscendGraphQLClient as s}from"@transcend-io/sdk";async function c({auth:c,file:l,transcendUrl:u,dataSiloIds:d,includeAttributes:f,includeGuessedCategories:p,parentCategories:m,subCategories:h=[]}){r(this.process);try{let e=await n(s(u,c),{dataSiloIds:d,includeGuessedCategories:p,parentCategories:m,includeAttributes:f,subCategories:h});this.logger.info(o.magenta(`Writing datapoints to file "${l}"...`));let r=[];await t(l,e.map(e=>{let t={"Property ID":e.id,"Data Silo":e.dataSilo.title,Object:e.dataPoint.name,"Object Path":e.dataPoint.path.join(`.`),Property:e.name,"Property Description":e.description,"Data Categories":e.categories.map(e=>`${e.category}:${e.name}`).join(`, `),"Guessed Category":e.pendingCategoryGuesses?.[0]?`${e.pendingCategoryGuesses[0].category.category}:${e.pendingCategoryGuesses[0].category.name}`:``,"Processing Purposes":e.purposes.map(e=>`${e.purpose}:${e.name}`).join(`, `),...Object.entries(i(e.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[t,n])=>(e[t]=n.map(e=>e.name).join(`,`),e),{})};return r=a([...r,...Object.keys(t)]),t}),r)}catch(e){this.logger.error(o.red(`An error occurred syncing the datapoints: ${e.message}`)),this.process.exit(1)}this.logger.info(o.green(`Successfully synced datapoints to disk at ${l}! View at ${e}`))}export{c as pullDatapoints};
2
+ //# sourceMappingURL=impl-DEPuP4Oy2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"impl-DZoTWLfw2.mjs","names":[],"sources":["../src/commands/inventory/pull-datapoints/impl.ts"],"sourcesContent":["import { DataCategoryType } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullAllDatapoints } from '../../../lib/data-inventory/index.js';\nimport { writeLargeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n this.logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(point.attributeValues || [], ({ attributeKey }) => attributeKey.name),\n ).reduce(\n (acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n },\n {} as Record<string, string>,\n ),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n await writeLargeCsv(file, inputs, headers);\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the datapoints: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"],"mappings":"2UAsBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,cACA,oBACA,2BACA,mBACA,gBAAgB,EAAE,EAEL,CACf,EAAoB,KAAK,QAAQ,CAEjC,GAAI,CAIF,IAAM,EAAa,MAAM,EAFV,EAA4B,EAAc,EAER,CAAE,CACjD,cACA,2BACA,mBACA,oBACA,gBACD,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,QAAQ,+BAA+B,EAAK,MAAM,CAAC,CAC3E,IAAI,EAAoB,EAAE,CAiC1B,MAAM,EAAc,EAhCL,EAAW,IAAK,GAAU,CACvC,IAAM,EAAS,CACb,cAAe,EAAM,GACrB,YAAa,EAAM,SAAS,MAC5B,OAAQ,EAAM,UAAU,KACxB,cAAe,EAAM,UAAU,KAAK,KAAK,IAAI,CAC7C,SAAU,EAAM,KAChB,uBAAwB,EAAM,YAC9B,kBAAmB,EAAM,WACtB,IAAK,GAAa,GAAG,EAAS,SAAS,GAAG,EAAS,OAAO,CAC1D,KAAK,KAAK,CACb,mBAAoB,EAAM,yBAAyB,GAC/C,GAAG,EAAM,uBAAwB,GAAI,SAAS,SAAS,GACrD,EAAM,uBAAwB,GAAI,SAAS,OAE7C,GACJ,sBAAuB,EAAM,SAC1B,IAAK,GAAY,GAAG,EAAQ,QAAQ,GAAG,EAAQ,OAAO,CACtD,KAAK,KAAK,CACb,GAAG,OAAO,QACR,EAAQ,EAAM,iBAAmB,EAAE,EAAG,CAAE,kBAAmB,EAAa,KAAK,CAC9E,CAAC,QACC,EAAK,CAAC,EAAK,MACV,EAAI,GAAO,EAAO,IAAK,GAAU,EAAM,KAAK,CAAC,KAAK,IAAI,CAC/C,GAET,EAAE,CACH,CACF,CAED,MADA,GAAU,EAAK,CAAC,GAAG,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,CAAC,CAC7C,GAEuB,CAAE,EAAQ,OACnC,EAAK,CACZ,KAAK,OAAO,MAAM,EAAO,IAAI,6CAA6C,EAAI,UAAU,CAAC,CACzF,KAAK,QAAQ,KAAK,EAAE,CAItB,KAAK,OAAO,KACV,EAAO,MACL,6CAA6C,EAAK,YAAY,IAC/D,CACF"}
1
+ {"version":3,"file":"impl-DEPuP4Oy2.mjs","names":[],"sources":["../src/commands/inventory/pull-datapoints/impl.ts"],"sourcesContent":["import { DataCategoryType } from '@transcend-io/privacy-types';\nimport { buildTranscendGraphQLClient } from '@transcend-io/sdk';\nimport colors from 'colors';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants.js';\nimport type { LocalContext } from '../../../context.js';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation.js';\nimport { pullAllDatapoints } from '../../../lib/data-inventory/index.js';\nimport { writeLargeCsv } from '../../../lib/helpers/index.js';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n this.logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(point.attributeValues || [], ({ attributeKey }) => attributeKey.name),\n ).reduce(\n (acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n },\n {} as Record<string, string>,\n ),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n await writeLargeCsv(file, inputs, headers);\n } catch (err) {\n this.logger.error(colors.red(`An error occurred syncing the datapoints: ${err.message}`));\n this.process.exit(1);\n }\n\n // Indicate success\n this.logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"],"mappings":"2UAsBA,eAAsB,EAEpB,CACE,OACA,OACA,eACA,cACA,oBACA,2BACA,mBACA,gBAAgB,EAAE,EAEL,CACf,EAAoB,KAAK,QAAQ,CAEjC,GAAI,CAIF,IAAM,EAAa,MAAM,EAFV,EAA4B,EAAc,EAER,CAAE,CACjD,cACA,2BACA,mBACA,oBACA,gBACD,CAAC,CAEF,KAAK,OAAO,KAAK,EAAO,QAAQ,+BAA+B,EAAK,MAAM,CAAC,CAC3E,IAAI,EAAoB,EAAE,CAiC1B,MAAM,EAAc,EAhCL,EAAW,IAAK,GAAU,CACvC,IAAM,EAAS,CACb,cAAe,EAAM,GACrB,YAAa,EAAM,SAAS,MAC5B,OAAQ,EAAM,UAAU,KACxB,cAAe,EAAM,UAAU,KAAK,KAAK,IAAI,CAC7C,SAAU,EAAM,KAChB,uBAAwB,EAAM,YAC9B,kBAAmB,E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