@transcend-io/cli 7.0.0 → 8.0.0-alpha.1

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 (271) hide show
  1. package/dist/bin/bash-complete.js +4 -0
  2. package/dist/bin/bash-complete.js.map +1 -0
  3. package/dist/bin/cli.js +3 -0
  4. package/dist/bin/cli.js.map +1 -0
  5. package/dist/bin/deprecated-command.js +7 -0
  6. package/dist/bin/deprecated-command.js.map +1 -0
  7. package/dist/chunk-26T4RUOI.js +12 -0
  8. package/dist/chunk-26T4RUOI.js.map +1 -0
  9. package/dist/chunk-2LCGZ77N.js +2 -0
  10. package/dist/chunk-2LCGZ77N.js.map +1 -0
  11. package/dist/chunk-2V6ABZRI.js +2 -0
  12. package/dist/chunk-2V6ABZRI.js.map +1 -0
  13. package/dist/chunk-347UQP43.js +2 -0
  14. package/dist/chunk-347UQP43.js.map +1 -0
  15. package/dist/chunk-43JWXG77.js +2 -0
  16. package/dist/chunk-43JWXG77.js.map +1 -0
  17. package/dist/chunk-4GLITB3Y.js +2 -0
  18. package/dist/chunk-4GLITB3Y.js.map +1 -0
  19. package/dist/chunk-65I2PF73.js +2 -0
  20. package/dist/chunk-65I2PF73.js.map +1 -0
  21. package/dist/chunk-72U6ETHG.js +2 -0
  22. package/dist/chunk-72U6ETHG.js.map +1 -0
  23. package/dist/chunk-ARVEJERC.js +2 -0
  24. package/dist/chunk-ARVEJERC.js.map +1 -0
  25. package/dist/chunk-CBAHSBSW.js +2 -0
  26. package/dist/{chunk-UBUNHRCG.cjs.map → chunk-CBAHSBSW.js.map} +1 -1
  27. package/dist/chunk-EZHASXA5.js +2 -0
  28. package/dist/chunk-EZHASXA5.js.map +1 -0
  29. package/dist/chunk-FHZRITAV.js +2 -0
  30. package/dist/chunk-FHZRITAV.js.map +1 -0
  31. package/dist/chunk-HJULYIHF.js +3 -0
  32. package/dist/chunk-HJULYIHF.js.map +1 -0
  33. package/dist/chunk-HOZXN2EM.js +94 -0
  34. package/dist/chunk-HOZXN2EM.js.map +1 -0
  35. package/dist/chunk-L5ULN3IT.js +2 -0
  36. package/dist/chunk-L5ULN3IT.js.map +1 -0
  37. package/dist/chunk-L7ZIX4SU.js +2 -0
  38. package/dist/chunk-L7ZIX4SU.js.map +1 -0
  39. package/dist/chunk-LAYHULHH.js +2 -0
  40. package/dist/chunk-LAYHULHH.js.map +1 -0
  41. package/dist/chunk-MA4JWWRO.js +6 -0
  42. package/dist/chunk-MA4JWWRO.js.map +1 -0
  43. package/dist/chunk-MK5T6DBK.js +2831 -0
  44. package/dist/chunk-MK5T6DBK.js.map +1 -0
  45. package/dist/chunk-N6JZHL5U.js +2 -0
  46. package/dist/chunk-N6JZHL5U.js.map +1 -0
  47. package/dist/chunk-NZZKRVAI.js +4 -0
  48. package/dist/chunk-NZZKRVAI.js.map +1 -0
  49. package/dist/chunk-OEB7WG3G.js +4 -0
  50. package/dist/chunk-OEB7WG3G.js.map +1 -0
  51. package/dist/chunk-SRLEEKKQ.js +9 -0
  52. package/dist/chunk-SRLEEKKQ.js.map +1 -0
  53. package/dist/chunk-WO5MQBXP.js +75 -0
  54. package/dist/chunk-WO5MQBXP.js.map +1 -0
  55. package/dist/impl-24IS3GIF.js +2 -0
  56. package/dist/impl-24IS3GIF.js.map +1 -0
  57. package/dist/impl-3YESYKVQ.js +2 -0
  58. package/dist/impl-3YESYKVQ.js.map +1 -0
  59. package/dist/impl-6MGNPY7O.js +2 -0
  60. package/dist/impl-6MGNPY7O.js.map +1 -0
  61. package/dist/impl-6SYXV3YI.js +2 -0
  62. package/dist/impl-6SYXV3YI.js.map +1 -0
  63. package/dist/impl-BVOF3W2V.js +4 -0
  64. package/dist/impl-BVOF3W2V.js.map +1 -0
  65. package/dist/impl-D4AEXEMN.js +12 -0
  66. package/dist/impl-D4AEXEMN.js.map +1 -0
  67. package/dist/impl-EAY4M3OY.js +2 -0
  68. package/dist/impl-EAY4M3OY.js.map +1 -0
  69. package/dist/impl-F4IQEKTF.js +9 -0
  70. package/dist/impl-F4IQEKTF.js.map +1 -0
  71. package/dist/impl-G4JGSVWD.js +2 -0
  72. package/dist/impl-G4JGSVWD.js.map +1 -0
  73. package/dist/impl-HFXHM3PH.js +2 -0
  74. package/dist/impl-HFXHM3PH.js.map +1 -0
  75. package/dist/impl-HMHOYOZZ.js +2 -0
  76. package/dist/impl-HMHOYOZZ.js.map +1 -0
  77. package/dist/impl-IU4EANSX.js +7 -0
  78. package/dist/impl-IU4EANSX.js.map +1 -0
  79. package/dist/impl-IWDHKBWZ.js +2 -0
  80. package/dist/impl-IWDHKBWZ.js.map +1 -0
  81. package/dist/impl-JFD2JMP6.js +2 -0
  82. package/dist/impl-JFD2JMP6.js.map +1 -0
  83. package/dist/impl-JH4VBMNT.js +2 -0
  84. package/dist/impl-JH4VBMNT.js.map +1 -0
  85. package/dist/impl-LSP4V37Z.js +6 -0
  86. package/dist/impl-LSP4V37Z.js.map +1 -0
  87. package/dist/impl-MIJFNSLS.js +2 -0
  88. package/dist/impl-MIJFNSLS.js.map +1 -0
  89. package/dist/impl-NL32KFH4.js +2 -0
  90. package/dist/impl-NL32KFH4.js.map +1 -0
  91. package/dist/impl-NLCPSIYZ.js +2 -0
  92. package/dist/impl-NLCPSIYZ.js.map +1 -0
  93. package/dist/impl-NXRQU2U5.js +6 -0
  94. package/dist/impl-NXRQU2U5.js.map +1 -0
  95. package/dist/impl-QEOVZIM5.js +2 -0
  96. package/dist/impl-QEOVZIM5.js.map +1 -0
  97. package/dist/impl-QRK4B3FD.js +2 -0
  98. package/dist/impl-QRK4B3FD.js.map +1 -0
  99. package/dist/impl-QZBKOJBQ.js +2 -0
  100. package/dist/impl-QZBKOJBQ.js.map +1 -0
  101. package/dist/impl-RFRQUKQY.js +2 -0
  102. package/dist/impl-RFRQUKQY.js.map +1 -0
  103. package/dist/impl-RIVVHWBR.js +2 -0
  104. package/dist/impl-RIVVHWBR.js.map +1 -0
  105. package/dist/impl-SJHU5PR7.js +2 -0
  106. package/dist/impl-SJHU5PR7.js.map +1 -0
  107. package/dist/impl-SYC5TORT.js +2 -0
  108. package/dist/impl-SYC5TORT.js.map +1 -0
  109. package/dist/impl-TP4QITXR.js +2 -0
  110. package/dist/impl-TP4QITXR.js.map +1 -0
  111. package/dist/impl-UOB7PV4W.js +2 -0
  112. package/dist/impl-UOB7PV4W.js.map +1 -0
  113. package/dist/impl-UUQ2BEZR.js +2 -0
  114. package/dist/impl-UUQ2BEZR.js.map +1 -0
  115. package/dist/impl-WH2I2JB7.js +2 -0
  116. package/dist/impl-WH2I2JB7.js.map +1 -0
  117. package/dist/impl-X6N6NFUV.js +6 -0
  118. package/dist/impl-X6N6NFUV.js.map +1 -0
  119. package/dist/impl-XF3OTAQZ.js +2 -0
  120. package/dist/impl-XF3OTAQZ.js.map +1 -0
  121. package/dist/impl-XH3KTZRN.js +2 -0
  122. package/dist/{impl-EJT3AX73.cjs.map → impl-XH3KTZRN.js.map} +1 -1
  123. package/dist/impl-XQBTTRCU.js +2 -0
  124. package/dist/impl-XQBTTRCU.js.map +1 -0
  125. package/dist/impl-YA2HU57Y.js +2 -0
  126. package/dist/impl-YA2HU57Y.js.map +1 -0
  127. package/dist/impl-YEGS4G24.js +2 -0
  128. package/dist/impl-YEGS4G24.js.map +1 -0
  129. package/dist/impl-YNBHGQJK.js +2 -0
  130. package/dist/impl-YNBHGQJK.js.map +1 -0
  131. package/dist/impl-ZJL2YE7A.js +2 -0
  132. package/dist/impl-ZJL2YE7A.js.map +1 -0
  133. package/dist/{index.d.cts → index.d.ts} +1 -1
  134. package/dist/index.js +5 -0
  135. package/dist/index.js.map +1 -0
  136. package/package.json +45 -48
  137. package/dist/bin/bash-complete.cjs +0 -4
  138. package/dist/bin/bash-complete.cjs.map +0 -1
  139. package/dist/bin/cli.cjs +0 -3
  140. package/dist/bin/cli.cjs.map +0 -1
  141. package/dist/bin/deprecated-command.cjs +0 -7
  142. package/dist/bin/deprecated-command.cjs.map +0 -1
  143. package/dist/chunk-ANCIGXE5.cjs +0 -4
  144. package/dist/chunk-ANCIGXE5.cjs.map +0 -1
  145. package/dist/chunk-AW6I4V4F.cjs +0 -3
  146. package/dist/chunk-AW6I4V4F.cjs.map +0 -1
  147. package/dist/chunk-BY7W4UQF.cjs +0 -2
  148. package/dist/chunk-BY7W4UQF.cjs.map +0 -1
  149. package/dist/chunk-CHTWXNEA.cjs +0 -2
  150. package/dist/chunk-CHTWXNEA.cjs.map +0 -1
  151. package/dist/chunk-DS6VH676.cjs +0 -2
  152. package/dist/chunk-DS6VH676.cjs.map +0 -1
  153. package/dist/chunk-EG4L6YAJ.cjs +0 -2
  154. package/dist/chunk-EG4L6YAJ.cjs.map +0 -1
  155. package/dist/chunk-ETNRSKUM.cjs +0 -2
  156. package/dist/chunk-ETNRSKUM.cjs.map +0 -1
  157. package/dist/chunk-GM2EDRKN.cjs +0 -12
  158. package/dist/chunk-GM2EDRKN.cjs.map +0 -1
  159. package/dist/chunk-IBTP5OXE.cjs +0 -2
  160. package/dist/chunk-IBTP5OXE.cjs.map +0 -1
  161. package/dist/chunk-KOV2SQO2.cjs +0 -4
  162. package/dist/chunk-KOV2SQO2.cjs.map +0 -1
  163. package/dist/chunk-LBDIZJ23.cjs +0 -2844
  164. package/dist/chunk-LBDIZJ23.cjs.map +0 -1
  165. package/dist/chunk-LZYEIVWM.cjs +0 -94
  166. package/dist/chunk-LZYEIVWM.cjs.map +0 -1
  167. package/dist/chunk-MPJABCSW.cjs +0 -75
  168. package/dist/chunk-MPJABCSW.cjs.map +0 -1
  169. package/dist/chunk-R5N2S5UU.cjs +0 -2
  170. package/dist/chunk-R5N2S5UU.cjs.map +0 -1
  171. package/dist/chunk-RW5GSSAA.cjs +0 -2
  172. package/dist/chunk-RW5GSSAA.cjs.map +0 -1
  173. package/dist/chunk-RZWMOCW3.cjs +0 -2
  174. package/dist/chunk-RZWMOCW3.cjs.map +0 -1
  175. package/dist/chunk-SAEKBZGF.cjs +0 -2
  176. package/dist/chunk-SAEKBZGF.cjs.map +0 -1
  177. package/dist/chunk-T462ONFX.cjs +0 -2
  178. package/dist/chunk-T462ONFX.cjs.map +0 -1
  179. package/dist/chunk-TD7ADMVO.cjs +0 -2
  180. package/dist/chunk-TD7ADMVO.cjs.map +0 -1
  181. package/dist/chunk-UBUNHRCG.cjs +0 -2
  182. package/dist/chunk-UEGX6GZ2.cjs +0 -2
  183. package/dist/chunk-UEGX6GZ2.cjs.map +0 -1
  184. package/dist/chunk-VCWGXJ2H.cjs +0 -9
  185. package/dist/chunk-VCWGXJ2H.cjs.map +0 -1
  186. package/dist/chunk-ZUNVPK23.cjs +0 -2
  187. package/dist/chunk-ZUNVPK23.cjs.map +0 -1
  188. package/dist/chunk-ZVK4HIDF.cjs +0 -6
  189. package/dist/chunk-ZVK4HIDF.cjs.map +0 -1
  190. package/dist/impl-2GU6CYMY.cjs +0 -2
  191. package/dist/impl-2GU6CYMY.cjs.map +0 -1
  192. package/dist/impl-2OEHQTIR.cjs +0 -2
  193. package/dist/impl-2OEHQTIR.cjs.map +0 -1
  194. package/dist/impl-2QXJ3WST.cjs +0 -9
  195. package/dist/impl-2QXJ3WST.cjs.map +0 -1
  196. package/dist/impl-442H4ODN.cjs +0 -7
  197. package/dist/impl-442H4ODN.cjs.map +0 -1
  198. package/dist/impl-44QRPPUX.cjs +0 -6
  199. package/dist/impl-44QRPPUX.cjs.map +0 -1
  200. package/dist/impl-4DOGSDPC.cjs +0 -2
  201. package/dist/impl-4DOGSDPC.cjs.map +0 -1
  202. package/dist/impl-5J3MG42D.cjs +0 -2
  203. package/dist/impl-5J3MG42D.cjs.map +0 -1
  204. package/dist/impl-5YMSNFJU.cjs +0 -2
  205. package/dist/impl-5YMSNFJU.cjs.map +0 -1
  206. package/dist/impl-6TBKGA4Y.cjs +0 -2
  207. package/dist/impl-6TBKGA4Y.cjs.map +0 -1
  208. package/dist/impl-7VYQSZVO.cjs +0 -2
  209. package/dist/impl-7VYQSZVO.cjs.map +0 -1
  210. package/dist/impl-BB24LU3N.cjs +0 -2
  211. package/dist/impl-BB24LU3N.cjs.map +0 -1
  212. package/dist/impl-CWZ26FTN.cjs +0 -2
  213. package/dist/impl-CWZ26FTN.cjs.map +0 -1
  214. package/dist/impl-EFTKRWUA.cjs +0 -2
  215. package/dist/impl-EFTKRWUA.cjs.map +0 -1
  216. package/dist/impl-EJT3AX73.cjs +0 -2
  217. package/dist/impl-EKQ6ZNN3.cjs +0 -2
  218. package/dist/impl-EKQ6ZNN3.cjs.map +0 -1
  219. package/dist/impl-EV6T5UOK.cjs +0 -6
  220. package/dist/impl-EV6T5UOK.cjs.map +0 -1
  221. package/dist/impl-FPFUAY4Q.cjs +0 -2
  222. package/dist/impl-FPFUAY4Q.cjs.map +0 -1
  223. package/dist/impl-GDKUHX2J.cjs +0 -2
  224. package/dist/impl-GDKUHX2J.cjs.map +0 -1
  225. package/dist/impl-GXDABG5X.cjs +0 -2
  226. package/dist/impl-GXDABG5X.cjs.map +0 -1
  227. package/dist/impl-IG7QEF6D.cjs +0 -2
  228. package/dist/impl-IG7QEF6D.cjs.map +0 -1
  229. package/dist/impl-JQLYJA5L.cjs +0 -2
  230. package/dist/impl-JQLYJA5L.cjs.map +0 -1
  231. package/dist/impl-LPI3M7L3.cjs +0 -6
  232. package/dist/impl-LPI3M7L3.cjs.map +0 -1
  233. package/dist/impl-M7WMSIK4.cjs +0 -4
  234. package/dist/impl-M7WMSIK4.cjs.map +0 -1
  235. package/dist/impl-MRGZ5OLO.cjs +0 -2
  236. package/dist/impl-MRGZ5OLO.cjs.map +0 -1
  237. package/dist/impl-OI4UWRAU.cjs +0 -12
  238. package/dist/impl-OI4UWRAU.cjs.map +0 -1
  239. package/dist/impl-OX24YDRR.cjs +0 -2
  240. package/dist/impl-OX24YDRR.cjs.map +0 -1
  241. package/dist/impl-PFQKPCUL.cjs +0 -2
  242. package/dist/impl-PFQKPCUL.cjs.map +0 -1
  243. package/dist/impl-PXJZK6BV.cjs +0 -2
  244. package/dist/impl-PXJZK6BV.cjs.map +0 -1
  245. package/dist/impl-QOGUUIE6.cjs +0 -2
  246. package/dist/impl-QOGUUIE6.cjs.map +0 -1
  247. package/dist/impl-QR3LLBZL.cjs +0 -2
  248. package/dist/impl-QR3LLBZL.cjs.map +0 -1
  249. package/dist/impl-RODUB22E.cjs +0 -2
  250. package/dist/impl-RODUB22E.cjs.map +0 -1
  251. package/dist/impl-S56PHXGG.cjs +0 -2
  252. package/dist/impl-S56PHXGG.cjs.map +0 -1
  253. package/dist/impl-SDGCTSWN.cjs +0 -2
  254. package/dist/impl-SDGCTSWN.cjs.map +0 -1
  255. package/dist/impl-VEMQEG27.cjs +0 -2
  256. package/dist/impl-VEMQEG27.cjs.map +0 -1
  257. package/dist/impl-VFWBSWT5.cjs +0 -2
  258. package/dist/impl-VFWBSWT5.cjs.map +0 -1
  259. package/dist/impl-XRRNIJUK.cjs +0 -2
  260. package/dist/impl-XRRNIJUK.cjs.map +0 -1
  261. package/dist/impl-YA7HWMYB.cjs +0 -2
  262. package/dist/impl-YA7HWMYB.cjs.map +0 -1
  263. package/dist/impl-YOWRUVYG.cjs +0 -2
  264. package/dist/impl-YOWRUVYG.cjs.map +0 -1
  265. package/dist/impl-ZHZOMOST.cjs +0 -2
  266. package/dist/impl-ZHZOMOST.cjs.map +0 -1
  267. package/dist/index.cjs +0 -5
  268. package/dist/index.cjs.map +0 -1
  269. /package/dist/bin/{bash-complete.d.cts → bash-complete.d.ts} +0 -0
  270. /package/dist/bin/{cli.d.cts → cli.d.ts} +0 -0
  271. /package/dist/bin/{deprecated-command.d.cts → deprecated-command.d.ts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/consent/upload-preferences/impl.ts","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/getPreferenceUpdatesFromRow.ts","../src/lib/preference-management/parsePreferenceTimestampsFromCsv.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/checkIfPendingPreferenceUpdatesAreNoOp.ts","../src/lib/preference-management/checkIfPendingPreferenceUpdatesCauseConflict.ts","../src/lib/preference-management/codecs.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger';\nimport { uploadPreferenceManagementPreferencesInteractive } from '../../../lib/preference-management';\nimport { splitCsvToList } from '../../../lib/requests';\nimport { readdirSync } from 'fs';\nimport { map } from '../../../lib/bluebird-replace';\nimport { basename, join } from 'path';\n\ninterface UploadPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n consentUrl: string;\n file?: string;\n directory?: string;\n dryRun: boolean;\n skipExistingRecordCheck: boolean;\n receiptFileDir: string;\n skipWorkflowTriggers: boolean;\n forceTriggerWorkflows: boolean;\n skipConflictUpdates: boolean;\n isSilent: boolean;\n attributes: string;\n receiptFilepath: string;\n concurrency: number;\n}\n\nexport async function uploadPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n consentUrl,\n file = '',\n directory,\n dryRun,\n skipExistingRecordCheck,\n receiptFileDir,\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n skipConflictUpdates,\n isSilent,\n attributes,\n concurrency,\n }: UploadPreferencesCommandFlags,\n): Promise<void> {\n if (!!directory && !!file) {\n logger.error(\n colors.red(\n 'Cannot provide both a directory and a file. Please provide only one.',\n ),\n );\n process.exit(1);\n }\n\n if (!file && !directory) {\n logger.error(\n colors.red(\n 'A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences',\n ),\n );\n process.exit(1);\n }\n\n const files: string[] = [];\n\n if (directory) {\n try {\n const filesInDirectory = readdirSync(directory);\n const csvFiles = filesInDirectory.filter((file) => file.endsWith('.csv'));\n\n if (csvFiles.length === 0) {\n logger.error(\n colors.red(`No CSV files found in directory: ${directory}`),\n );\n process.exit(1);\n }\n\n // Add full paths for each CSV file\n files.push(...csvFiles.map((file) => join(directory, file)));\n } catch (err) {\n logger.error(colors.red(`Failed to read directory: ${directory}`));\n logger.error(colors.red((err as Error).message));\n process.exit(1);\n }\n } else {\n try {\n // Verify file exists and is a CSV\n if (!file.endsWith('.csv')) {\n logger.error(colors.red('File must be a CSV file'));\n process.exit(1);\n }\n files.push(file);\n } catch (err) {\n logger.error(colors.red(`Failed to access file: ${file}`));\n logger.error(colors.red((err as Error).message));\n process.exit(1);\n }\n }\n\n logger.info(\n colors.green(\n `Processing ${files.length} consent preferences files for partition: ${partition}`,\n ),\n );\n logger.debug(`Files to process: ${files.join(', ')}`);\n\n if (skipExistingRecordCheck) {\n logger.info(\n colors.bgYellow(\n `Skipping existing record check: ${skipExistingRecordCheck}`,\n ),\n );\n }\n\n await map(\n files,\n async (filePath) => {\n const fileName = basename(filePath).replace('.csv', '');\n await uploadPreferenceManagementPreferencesInteractive({\n receiptFilepath: join(receiptFileDir, `${fileName}-receipts.json`),\n auth,\n sombraAuth,\n file: filePath,\n partition,\n transcendUrl: consentUrl,\n skipConflictUpdates,\n skipWorkflowTriggers,\n skipExistingRecordCheck,\n isSilent,\n dryRun,\n attributes: splitCsvToList(attributes),\n forceTriggerWorkflows,\n });\n },\n { concurrency },\n );\n}\n","import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from '../bluebird-replace';\nimport { chunk } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_CONSENT_API } from '../../constants';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl = DEFAULT_TRANSCEND_CONSENT_API,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${\n Object.values(pendingUpdates).length\n } preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Wheather to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(\n preferences,\n currentState,\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(\n preferences,\n currentState,\n );\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}. \n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport * as t from 'io-ts';\nimport { map } from '../bluebird-replace';\nimport { logger } from '../../logger';\n\nconst PreferenceRecordsQueryResponse = t.intersection([\n t.type({\n nodes: t.array(PreferenceQueryResponseItem),\n }),\n t.partial({\n /** The base64 encoded(PreferenceStorePaginationKey) cursor for pagination */\n cursor: t.string,\n }),\n]);\n\nconst MSGS = [\n 'ENOTFOUND',\n 'ETIMEDOUT',\n '504 Gateway Time-out',\n 'Task timed out after',\n];\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n // Make the request with retry logic\n let attempts = 0;\n const maxAttempts = 3;\n while (attempts < maxAttempts) {\n try {\n const rawResult = await sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: {\n identifiers: group,\n },\n limit: group.length,\n },\n })\n .json();\n\n const result = decodeCodec(PreferenceRecordsQueryResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n break; // Exit loop if successful\n } catch (err) {\n attempts += 1;\n const msg = err?.response?.body || err?.message || '';\n if (\n attempts >= maxAttempts ||\n !MSGS.some((errorMessage) => msg.includes(errorMessage))\n ) {\n throw new Error(\n `Received an error from server after ${attempts} attempts: ${msg}`,\n );\n }\n\n logger.warn(\n colors.yellow(\n `[RETRYING FAILED REQUEST - Attempt ${attempts}] ` +\n `Failed to fetch ${group.length} user preferences from partition ${partitionKey}: ${msg}`,\n ),\n );\n }\n }\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import {\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PurposeRowMapping } from './codecs';\nimport { apply } from '@transcend-io/type-utils';\nimport { PreferenceTopic } from '../graphql';\nimport { splitCsvToList } from '../requests';\n\n/**\n * Parse an arbitrary object to the Transcend PUT /v1/preference update shape\n * by using a mapping of column names to purpose/preference slugs.\n *\n * columnToPurposeName looks like:\n * {\n * 'my_purpose': 'Marketing',\n * 'has_topic_1': 'Marketing->BooleanPreference1',\n * 'has_topic_2': 'Marketing->BooleanPreference2'\n * }\n *\n * row looks like:\n * {\n * 'my_purpose': 'true',\n * 'has_topic_1': 'true',\n * 'has_topic_2': 'false'\n * }\n *\n * @param options - Options\n * @returns The parsed row\n */\nexport function getPreferenceUpdatesFromRow({\n row,\n columnToPurposeName,\n purposeSlugs,\n preferenceTopics,\n}: {\n /** Row to parse */\n row: Record<string, string>;\n /** Mapping from column name ot row */\n columnToPurposeName: Record<string, PurposeRowMapping>;\n /** The set of allowed purpose slugs */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n}): {\n [k in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n} {\n // Create a result object to store the parsed preferences\n const result: {\n [k in string]: Partial<PreferenceStorePurposeResponse>;\n } = {};\n\n // Iterate over each column and map to the purpose or preference\n Object.entries(columnToPurposeName).forEach(\n ([columnName, { purpose, preference, valueMapping }]) => {\n // Ensure the purpose is valid\n if (!purposeSlugs.includes(purpose)) {\n throw new Error(\n `Invalid purpose slug: ${purpose}, expected: ${purposeSlugs.join(\n ', ',\n )}`,\n );\n }\n\n // CHeck if parsing a preference or just the top level purpose\n if (preference) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === preference && x.purpose.trackingType === purpose,\n );\n if (!preferenceTopic) {\n const allowedTopics = preferenceTopics\n .filter((x) => x.purpose.trackingType === purpose)\n .map((x) => x.slug);\n throw new Error(\n `Invalid preference slug: ${preference} for purpose: ${purpose}. ` +\n `Allowed preference slugs for purpose are: ${allowedTopics.join(\n ',',\n )}`,\n );\n }\n\n // If parsing preferences, default to an empty array\n if (!result[purpose]) {\n result[purpose] = {\n preferences: [],\n };\n }\n if (!result[purpose].preferences) {\n result[purpose].preferences = [];\n }\n\n // The value to parse\n const rawValue = row[columnName];\n const rawMapping = valueMapping[rawValue];\n const trimmedMapping =\n typeof rawMapping === 'string' ? rawMapping.trim() || null : null;\n\n // handle each type of preference\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n if (typeof rawMapping !== 'boolean') {\n throw new Error(\n `Invalid value for boolean preference: ${preference}, expected boolean, got: ${rawValue}`,\n );\n }\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n booleanValue: rawMapping,\n },\n });\n break;\n case PreferenceTopicType.Select:\n if (typeof rawMapping !== 'string' && rawMapping !== null) {\n throw new Error(\n `Invalid value for select preference: ${preference}, expected string or null, got: ${rawValue}`,\n );\n }\n\n if (\n trimmedMapping &&\n !preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .includes(trimmedMapping)\n ) {\n throw new Error(\n `Invalid value for select preference: ${preference}, expected one of: ` +\n `${preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .join(', ')}, got: ${rawValue}`,\n );\n }\n\n // Update preferences\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n selectValue: trimmedMapping,\n },\n });\n break;\n case PreferenceTopicType.MultiSelect:\n if (typeof rawValue !== 'string') {\n throw new Error(\n `Invalid value for multi select preference: ${preference}, expected string, got: ${rawValue}`,\n );\n }\n // Update preferences\n result[purpose].preferences!.push({\n topic: preference,\n choice: {\n selectValues: splitCsvToList(rawValue)\n .map((val) => {\n const result = valueMapping[val];\n if (typeof result !== 'string') {\n throw new Error(\n `Invalid value for multi select preference: ${preference}, ` +\n `expected one of: ${preferenceTopic.preferenceOptionValues\n .map(({ slug }) => slug)\n .join(', ')}, got: ${val}`,\n );\n }\n return result;\n })\n .sort((a, b) => a.localeCompare(b)),\n },\n });\n break;\n default:\n throw new Error(`Unknown preference type: ${preferenceTopic.type}`);\n }\n } else if (!result[purpose]) {\n // Handle updating top level purpose for the first time\n result[purpose] = {\n enabled: valueMapping[row[columnName]] === true,\n };\n } else {\n // Handle updating top level purpose but preserve preference updates\n result[purpose].enabled = valueMapping[row[columnName]] === true;\n }\n },\n );\n\n // Ensure that enabled is provided\n return apply(result, (x, purposeName) => {\n if (typeof x.enabled !== 'boolean') {\n throw new Error(\n `No mapping provided for purpose.enabled=true/false value: ${purposeName}`,\n );\n }\n return {\n ...x,\n enabled: x.enabled!,\n };\n });\n}\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\n\nexport const NONE_PREFERENCE_MAP = '[NONE]';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse timestamps from a CSV list of preferences\n *\n * When timestamp is requested, this script\n * ensures that all rows have a valid timestamp.\n *\n * Error is throw if timestamp is missing\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceTimestampsFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for timestamp\n const remainingColumnsForTimestamp = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the timestamp column to work off of\n if (!currentState.timestampColum) {\n const { timestampName } = await inquirer.prompt<{\n /** timestamp name */\n timestampName: string;\n }>([\n {\n name: 'timestampName',\n message:\n 'Choose the column that will be used as the timestamp of last preference update',\n type: 'list',\n default:\n remainingColumnsForTimestamp.find((col) =>\n col.toLowerCase().includes('date'),\n ) ||\n remainingColumnsForTimestamp.find((col) =>\n col.toLowerCase().includes('time'),\n ) ||\n remainingColumnsForTimestamp[0],\n choices: [...remainingColumnsForTimestamp, NONE_PREFERENCE_MAP],\n },\n ]);\n currentState.timestampColum = timestampName;\n }\n logger.info(\n colors.magenta(`Using timestamp column \"${currentState.timestampColum}\"`),\n );\n\n // Validate that all rows have valid timestamp\n if (currentState.timestampColum !== NONE_PREFERENCE_MAP) {\n const timestampColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.timestampColum!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (timestampColumnsMissing.length > 0) {\n throw new Error(\n `The timestamp column \"${\n currentState.timestampColum\n }\" is missing a value for the following rows: ${timestampColumnsMissing.join(\n '\\n',\n )}`,\n );\n }\n logger.info(\n colors.magenta(\n `The timestamp column \"${currentState.timestampColum}\" is present for all row`,\n ),\n );\n }\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(\n ', ',\n )}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(\n ([, rows]) => rows.length > 1,\n );\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from '../bluebird-replace';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PreferenceTopic } from '../graphql';\n\n/**\n * Check if the pending set of updates are exactly the same as the current consent record.\n *\n * @param options - Options\n * @returns Whether the pending updates already exist in the preference store\n */\nexport function checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n}: {\n /** The current consent record */\n currentConsentRecord: PreferenceQueryResponseItem;\n /** The pending updates */\n pendingUpdates: {\n [purposeName in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n };\n /** The preference topic configurations */\n preferenceTopics: PreferenceTopic[];\n}): boolean {\n // Check each update\n return Object.entries(pendingUpdates).every(\n ([purposeName, { preferences = [], enabled }]) => {\n // Ensure the purpose exists\n const currentPurpose = currentConsentRecord.purposes.find(\n (existingPurpose) => existingPurpose.purpose === purposeName,\n );\n\n // Ensure purpose.enabled is in sync\n // Also false if the purpose does not exist\n const enabledIsInSync =\n !!currentPurpose && currentPurpose.enabled === enabled;\n if (!enabledIsInSync) {\n return false;\n }\n\n // Compare the preferences are in sync\n return preferences.every(\n ({ topic, choice }) =>\n // ensure preferences exist on record\n currentPurpose.preferences &&\n currentPurpose.preferences.find((existingPreference) => {\n // find matching topic\n if (existingPreference.topic !== topic) {\n return false;\n }\n\n // Determine type of preference topic\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === topic && x.purpose.trackingType === purposeName,\n );\n if (!preferenceTopic) {\n throw new Error(`Could not find preference topic for ${topic}`);\n }\n\n // Handle comparison based on type\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n return (\n existingPreference.choice.booleanValue === choice.booleanValue\n );\n case PreferenceTopicType.Select:\n return (\n existingPreference.choice.selectValue === choice.selectValue\n );\n case PreferenceTopicType.MultiSelect:\n // eslint-disable-next-line no-case-declarations\n const sortedCurrentValues = (\n existingPreference.choice.selectValues || []\n ).sort();\n // eslint-disable-next-line no-case-declarations\n const sortedNewValues = (choice.selectValues || []).sort();\n return (\n sortedCurrentValues.length === sortedNewValues.length &&\n sortedCurrentValues.every((x, i) => x === sortedNewValues[i])\n );\n default:\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n }),\n );\n },\n );\n}\n","import {\n PreferenceQueryResponseItem,\n PreferenceStorePurposeResponse,\n PreferenceTopicType,\n} from '@transcend-io/privacy-types';\nimport { PreferenceTopic } from '../graphql';\n\n/**\n * Check if the pending set of updates will result in a change of\n * value to an existing purpose or preference in the preference store.\n *\n * @param options - Options\n * @returns True if conflict, false if no conflict and just adding new data for first time\n */\nexport function checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n}: {\n /** The current consent record */\n currentConsentRecord: PreferenceQueryResponseItem;\n /** The pending updates */\n pendingUpdates: {\n [purposeName in string]: Omit<PreferenceStorePurposeResponse, 'purpose'>;\n };\n /** The preference topic configurations */\n preferenceTopics: PreferenceTopic[];\n}): boolean {\n // Check if any update has conflict\n return !!Object.entries(pendingUpdates).find(\n ([purposeName, { preferences = [], enabled }]) => {\n // Ensure the purpose exists\n const currentPurpose = currentConsentRecord.purposes.find(\n (existingPurpose) => existingPurpose.purpose === purposeName,\n );\n\n // If no purpose exists, then it is not a conflict\n if (!currentPurpose) {\n return false;\n }\n\n // If purpose.enabled value is off, this is a conflict\n if (currentPurpose.enabled !== enabled) {\n return true;\n }\n\n // Check if any preferences are out of sync\n return !!preferences.find(({ topic, choice }) => {\n // find matching topic\n const currentPreference = (currentPurpose.preferences || []).find(\n (existingPreference) => existingPreference.topic === topic,\n );\n\n // if no topic exists, no conflict\n if (!currentPreference) {\n return false;\n }\n\n // Determine type of preference topic\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === topic && x.purpose.trackingType === purposeName,\n );\n if (!preferenceTopic) {\n throw new Error(`Could not find preference topic for ${topic}`);\n }\n\n // Handle comparison based on type\n switch (preferenceTopic.type) {\n case PreferenceTopicType.Boolean:\n return (\n currentPreference.choice.booleanValue !== choice.booleanValue\n );\n case PreferenceTopicType.Select:\n return currentPreference.choice.selectValue !== choice.selectValue;\n case PreferenceTopicType.MultiSelect:\n // eslint-disable-next-line no-case-declarations\n const sortedCurrentValues = (\n currentPreference.choice.selectValues || []\n ).sort();\n // eslint-disable-next-line no-case-declarations\n const sortedNewValues = (choice.selectValues || []).sort();\n return (\n sortedCurrentValues.length !== sortedNewValues.length ||\n !sortedCurrentValues.every((x, i) => x === sortedNewValues[i])\n );\n default:\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n },\n );\n}\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(t.string, t.union([t.string, t.boolean, t.null])),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"],"mappings":"iXACA,OAAOA,MAAY,SCOnB,OAAOC,MAAY,SAEnB,OAAS,SAAAC,OAAa,YAGtB,OAAOC,OAAiB,eAExB,OAAS,kBAAAC,OAAsB,gCCb/B,OAAS,SAAAC,OAAa,YACtB,UAAYC,MAAO,QACnB,OAAOC,OAAY,SCJnB,OAAS,+BAAAC,OAAmC,8BAE5C,OAAOC,OAAY,SACnB,OAAOC,OAAiB,eACxB,OAAS,SAAAC,OAAa,YACtB,OAAS,eAAAC,OAAmB,2BAC5B,UAAYC,MAAO,QAInB,IAAMC,GAAmC,eAAa,CAClD,OA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EAEhDV,GACFQ,EAAO,KACLC,EAAO,SACL,mCAAmCT,CAAuB,EAC5D,CACF,EAGF,MAAMc,EACJJ,EACA,MAAOK,GAAa,CAClB,IAAMC,EAAW1B,GAASyB,CAAQ,EAAE,QAAQ,OAAQ,EAAE,EACtD,MAAME,GAAiD,CACrD,gBAAiB1B,GAAKU,EAAgB,GAAGe,CAAQ,gBAAgB,EACjE,KAAAvB,EACA,WAAAE,EACA,KAAMoB,EACN,UAAArB,EACA,aAAcE,EACd,oBAAAQ,EACA,qBAAAF,EACA,wBAAAF,EACA,SAAAK,EACA,OAAAN,EACA,WAAYmB,EAAeZ,CAAU,EACrC,sBAAAH,CACF,CAAC,CACH,EACA,CAAE,YAAAI,CAAY,CAChB,CACF","names":["colors","colors","chunk","cliProgress","PersistedState","keyBy","t","colors","PreferenceQueryResponseItem","colors","cliProgress","chunk","decodeCodec","t","PreferenceRecordsQueryResponse","PreferenceQueryResponseItem","MSGS","getPreferencesForIdentifiers","sombra","identifiers","partitionKey","skipLogging","results","groupedIdentifiers","chunk","t0","progressBar","cliProgress","total","map","group","attempts","maxAttempts","rawResult","result","decodeCodec","err","msg","errorMessage","logger","colors","totalTime","PreferenceTopicType","apply","getPreferenceUpdatesFromRow","row","columnToPurposeName","purposeSlugs","preferenceTopics","result","columnName","purpose","preference","valueMapping","preferenceTopic","x","allowedTopics","rawValue","rawMapping","trimmedMapping","PreferenceTopicType","slug","splitCsvToList","val","a","b","apply","purposeName","uniq","difference","colors","inquirer","NONE_PREFERENCE_MAP","parsePreferenceTimestampsFromCsv","preferences","currentState","columnNames","uniq","x","remainingColumnsForTimestamp","difference","timestampName","inquirer","col","logger","colors","timestampColumnsMissing","pref","ind","uniq","groupBy","difference","colors","inquirer","parsePreferenceIdentifiersFromCsv","preferences","currentState","columnNames","uniq","x","remainingColumnsForIdentifier","difference","identifierName","inquirer","col","logger","colors","identifierColumnsMissing","pref","ind","msg","inquirerConfirmBoolean","previous","rowsByUserId","groupBy","duplicateIdentifiers","rows","userId","a","b","uniq","difference","colors","inquirer","PreferenceTopicType","parsePreferenceAndPurposeValuesFromCsv","preferences","currentState","purposeSlugs","preferenceTopics","forceTriggerWorkflows","columnNames","uniq","x","otherColumns","difference","purposeNames","mapSeries","col","uniqueValues","purposeMapping","logger","colors","purposeName","inquirer","purposeSlug","preferenceSlug","value","purposeValue","preferenceTopic","preferenceOptions","slug","PreferenceTopicType","preferenceValue","parsedValues","splitCsvToList","parsedValue","PreferenceTopicType","checkIfPendingPreferenceUpdatesAreNoOp","currentConsentRecord","pendingUpdates","preferenceTopics","purposeName","preferences","enabled","currentPurpose","existingPurpose","topic","choice","existingPreference","preferenceTopic","x","sortedCurrentValues","sortedNewValues","i","PreferenceTopicType","checkIfPendingPreferenceUpdatesCauseConflict","currentConsentRecord","pendingUpdates","preferenceTopics","purposeName","preferences","enabled","currentPurpose","existingPurpose","topic","choice","currentPreference","existingPreference","preferenceTopic","x","sortedCurrentValues","sortedNewValues","i","parsePreferenceManagementCsvWithCache","file","sombra","purposeSlugs","preferenceTopics","partitionKey","skipExistingRecordCheck","forceTriggerWorkflows","cache","t0","fileMetadata","logger","colors","preferences","readCsv","currentState","parsePreferenceTimestampsFromCsv","result","parsePreferenceIdentifiersFromCsv","parsePreferenceAndPurposeValuesFromCsv","identifiers","pref","existingConsentRecords","getPreferencesForIdentifiers","x","consentRecordByIdentifier","keyBy","userId","pendingUpdates","getPreferenceUpdatesFromRow","currentConsentRecord","checkIfPendingPreferenceUpdatesAreNoOp","checkIfPendingPreferenceUpdatesCauseConflict","t1","PreferenceQueryResponseItem","PreferenceUpdateItem","t","PurposeRowMapping","FileMetadataState","PreferenceState","apply","uploadPreferenceManagementPreferencesInteractive","auth","sombraAuth","receiptFilepath","file","partition","isSilent","dryRun","skipWorkflowTriggers","skipConflictUpdates","skipExistingRecordCheck","attributes","transcendUrl","DEFAULT_TRANSCEND_CONSENT_API","forceTriggerWorkflows","parsedAttributes","parseAttributesFromString","preferenceState","PersistedState","PreferenceState","failingRequests","pendingRequests","fileMetadata","logger","colors","x","client","buildTranscendGraphQLClient","sombra","purposes","preferenceTopics","createSombraGotInstance","fetchAllPurposes","fetchAllPreferenceTopics","parsePreferenceManagementCsvWithCache","pendingUpdates","metadata","apply","row","userId","update","timestamp","NONE_PREFERENCE_MAP","updates","getPreferenceUpdatesFromRow","purpose","value","t0","progressBar","cliProgress","total","updatesToRun","chunkedUpdates","chunk","map","currentChunk","err","parsed","failingUpdates","totalTime","readdirSync","basename","join","uploadPreferences","auth","partition","sombraAuth","consentUrl","file","directory","dryRun","skipExistingRecordCheck","receiptFileDir","skipWorkflowTriggers","forceTriggerWorkflows","skipConflictUpdates","isSilent","attributes","concurrency","logger","colors","files","csvFiles","readdirSync","err","map","filePath","fileName","uploadPreferenceManagementPreferencesInteractive","splitCsvToList"]}
@@ -0,0 +1,2 @@
1
+ import{b as r}from"./chunk-65I2PF73.js";import{g as t}from"./chunk-26T4RUOI.js";import"./chunk-2V6ABZRI.js";import"./chunk-N6JZHL5U.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import"./chunk-MK5T6DBK.js";import{a as n}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import e from"colors";import{writeFileSync as g}from"fs";async function C({auth:d,xdiLocation:s,file:i,removeIpAddresses:c,domainBlockList:o,xdiAllowedCommands:l,transcendUrl:a}){let m=await r(d),{syncGroups:p,html:f}=await t(m,{xdiLocation:s,transcendUrl:a,removeIpAddresses:c,domainBlockList:o.length>0?o:void 0,xdiAllowedCommands:l});n.info(e.green(`Successfully constructed sync endpoint for sync groups: ${JSON.stringify(p,null,2)}`)),g(i,f),n.info(e.green(`Wrote configuration to file "${i}"!`))}export{C as buildXdiSyncEndpoint};
2
+ //# sourceMappingURL=impl-EAY4M3OY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/consent/build-xdi-sync-endpoint/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { writeFileSync } from 'fs';\nimport { validateTranscendAuth } from '../../../lib/api-keys';\nimport { buildXdiSyncEndpoint as buildXdiSyncEndpointHelper } from '../../../lib/consent-manager';\n\ninterface BuildXdiSyncEndpointCommandFlags {\n auth: string;\n xdiLocation: string;\n file: string;\n removeIpAddresses: boolean;\n domainBlockList: string[];\n xdiAllowedCommands: string;\n transcendUrl: string;\n}\n\nexport async function buildXdiSyncEndpoint(\n this: LocalContext,\n {\n auth,\n xdiLocation,\n file,\n removeIpAddresses,\n domainBlockList,\n xdiAllowedCommands,\n transcendUrl,\n }: BuildXdiSyncEndpointCommandFlags,\n): Promise<void> {\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Build the sync endpoint\n const { syncGroups, html } = await buildXdiSyncEndpointHelper(apiKeyOrList, {\n xdiLocation,\n transcendUrl,\n removeIpAddresses,\n domainBlockList: domainBlockList.length > 0 ? domainBlockList : undefined,\n xdiAllowedCommands,\n });\n\n // Log success\n logger.info(\n colors.green(\n `Successfully constructed sync endpoint for sync groups: ${JSON.stringify(\n syncGroups,\n null,\n 2,\n )}`,\n ),\n );\n\n // Write to disk\n writeFileSync(file, html);\n logger.info(colors.green(`Wrote configuration to file \"${file}\"!`));\n}\n"],"mappings":"wVAEA,OAAOA,MAAY,SACnB,OAAS,iBAAAC,MAAqB,KAc9B,eAAsBC,EAEpB,CACE,KAAAC,EACA,YAAAC,EACA,KAAAC,EACA,kBAAAC,EACA,gBAAAC,EACA,mBAAAC,EACA,aAAAC,CACF,EACe,CAEf,IAAMC,EAAe,MAAMC,EAAsBR,CAAI,EAG/C,CAAE,WAAAS,EAAY,KAAAC,CAAK,EAAI,MAAMX,EAA2BQ,EAAc,CAC1E,YAAAN,EACA,aAAAK,EACA,kBAAAH,EACA,gBAAiBC,EAAgB,OAAS,EAAIA,EAAkB,OAChE,mBAAAC,CACF,CAAC,EAGDM,EAAO,KACLC,EAAO,MACL,2DAA2D,KAAK,UAC9DH,EACA,KACA,CACF,CAAC,EACH,CACF,EAGAI,EAAcX,EAAMQ,CAAI,EACxBC,EAAO,KAAKC,EAAO,MAAM,gCAAgCV,CAAI,IAAI,CAAC,CACpE","names":["colors","writeFileSync","buildXdiSyncEndpoint","auth","xdiLocation","file","removeIpAddresses","domainBlockList","xdiAllowedCommands","transcendUrl","apiKeyOrList","validateTranscendAuth","syncGroups","html","logger","colors","writeFileSync"]}
@@ -0,0 +1,9 @@
1
+ import{b as O}from"./chunk-65I2PF73.js";import"./chunk-2LCGZ77N.js";import{c as v}from"./chunk-MA4JWWRO.js";import{d as b}from"./chunk-26T4RUOI.js";import"./chunk-2V6ABZRI.js";import"./chunk-N6JZHL5U.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{a as M,pe as x,sc as S}from"./chunk-MK5T6DBK.js";import{a as t}from"./chunk-43JWXG77.js";import{c as y}from"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import e from"colors";import{join as w}from"path";import E,{existsSync as j,mkdirSync as T}from"fs";async function q({auth:A,start:C,end:f,folder:r,bin:l,transcendUrl:N}){let m=await O(A);E.existsSync(r)&&!E.lstatSync(r).isDirectory()&&(t.error(e.red('The provided argument "folder" was passed a file. expected: folder="./consent-metrics/"')),process.exit(1));let g=l;Object.values(S).includes(g)||(t.error(e.red(`Failed to parse argument "bin" with value "${l}"
2
+ Expected one of:
3
+ ${Object.values(S).join(`
4
+ `)}`)),process.exit(1));let i=new Date(C),o=f?new Date(f):new Date;if(Number.isNaN(i.getTime())&&(t.error(e.red(`Start date provided is invalid date. Got --start="${C}" expected --start="01/01/2023"`)),process.exit(1)),Number.isNaN(o.getTime())&&(t.error(e.red(`End date provided is invalid date. Got --end="${f}" expected --end="01/01/2023"`)),process.exit(1)),i>o&&(t.error(e.red(`Got a start date "${i.toISOString()}" that was larger than the end date "${o.toISOString()}". Start date must be before end date.`)),process.exit(1)),j(r)||T(r),t.info(e.magenta(`Pulling consent metrics from start=${i.toString()} to end=${o.toISOString()} with bin size "${l}"`)),typeof m=="string"){try{let n=x(N,m),s=await b(n,{bin:g,start:i,end:o});Object.entries(s).forEach(([p,c])=>{c.forEach(({points:u,name:d})=>{let a=w(r,`${p}_${d}.csv`);t.info(e.magenta(`Writing configuration to file "${a}"...`)),v(a,u.map(({key:$,value:h})=>({timestamp:$,value:h})))})})}catch(n){t.error(e.red(`An error occurred syncing the schema: ${n.message}`)),process.exit(1)}t.info(e.green(`Successfully synced consent metrics to disk in folder "${r}"! View at ${y}`))}else{let n=[];await M(m,async(s,p)=>{let c=`[${p+1}/${m.length}][${s.organizationName}] `;t.info(e.magenta(`~~~
5
+
6
+ ${c}Attempting to pull consent metrics...
7
+
8
+ ~~~`));let u=x(N,s.apiKey);try{let d=await b(u,{bin:g,start:i,end:o}),a=w(r,s.organizationName);j(a)||T(a),Object.entries(d).forEach(([$,h])=>{h.forEach(({points:I,name:F})=>{let D=w(a,`${$}_${F}.csv`);t.info(e.magenta(`Writing configuration to file "${D}"...`)),v(D,I.map(({key:G,value:z})=>({timestamp:G,value:z})))})}),t.info(e.green(`${c}Successfully pulled configuration!`))}catch{t.error(e.red(`${c}Failed to sync configuration.`)),n.push(s.organizationName)}}),n.length>0&&(t.info(e.red(`Sync encountered errors for "${n.join(",")}". View output above for more information, or check out ${y}`)),process.exit(1))}}export{q as pullConsentMetrics};
9
+ //# sourceMappingURL=impl-F4IQEKTF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/consent/pull-consent-metrics/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { mapSeries } from '../../../lib/bluebird-replace';\nimport { join } from 'path';\nimport fs, { existsSync, mkdirSync } from 'fs';\nimport {\n buildTranscendGraphQLClient,\n ConsentManagerMetricBin,\n} from '../../../lib/graphql';\nimport { validateTranscendAuth } from '../../../lib/api-keys';\nimport { ADMIN_DASH_INTEGRATIONS } from '../../../constants';\nimport { pullConsentManagerMetrics } from '../../../lib/consent-manager';\nimport { writeCsv } from '../../../lib/cron';\n\ninterface PullConsentMetricsCommandFlags {\n auth: string;\n start: Date;\n end?: Date;\n folder: string;\n bin: string;\n transcendUrl: string;\n}\n\nexport async function pullConsentMetrics(\n this: LocalContext,\n {\n auth,\n start,\n end,\n folder,\n bin,\n transcendUrl,\n }: PullConsentMetricsCommandFlags,\n): Promise<void> {\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Ensure folder either does not exist or is not a file\n if (fs.existsSync(folder) && !fs.lstatSync(folder).isDirectory()) {\n logger.error(\n colors.red(\n 'The provided argument \"folder\" was passed a file. expected: folder=\"./consent-metrics/\"',\n ),\n );\n process.exit(1);\n }\n\n // Validate bin\n const parsedBin = bin as ConsentManagerMetricBin;\n if (!Object.values(ConsentManagerMetricBin).includes(parsedBin)) {\n logger.error(\n colors.red(\n `Failed to parse argument \"bin\" with value \"${bin}\"\\n` +\n `Expected one of: \\n${Object.values(ConsentManagerMetricBin).join(\n '\\n',\n )}`,\n ),\n );\n process.exit(1);\n }\n\n // Parse the dates\n const startDate = new Date(start);\n const endDate = end ? new Date(end) : new Date();\n if (Number.isNaN(startDate.getTime())) {\n logger.error(\n colors.red(\n `Start date provided is invalid date. Got --start=\"${start}\" expected --start=\"01/01/2023\"`,\n ),\n );\n process.exit(1);\n }\n if (Number.isNaN(endDate.getTime())) {\n logger.error(\n colors.red(\n `End date provided is invalid date. Got --end=\"${end}\" expected --end=\"01/01/2023\"`,\n ),\n );\n process.exit(1);\n }\n if (startDate > endDate) {\n logger.error(\n colors.red(\n `Got a start date \"${startDate.toISOString()}\" that was larger than the end date \"${endDate.toISOString()}\". ` +\n 'Start date must be before end date.',\n ),\n );\n process.exit(1);\n }\n\n // Create the folder if it does not exist\n if (!existsSync(folder)) {\n mkdirSync(folder);\n }\n\n logger.info(\n colors.magenta(\n `Pulling consent metrics from start=${startDate.toString()} to end=${endDate.toISOString()} with bin size \"${bin}\"`,\n ),\n );\n\n // Sync to Disk\n if (typeof apiKeyOrList === 'string') {\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKeyOrList);\n\n // Pull the metrics\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // Write to file\n Object.entries(configuration).forEach(([metricName, metrics]) => {\n metrics.forEach(({ points, name }) => {\n const file = join(folder, `${metricName}_${name}.csv`);\n logger.info(\n colors.magenta(`Writing configuration to file \"${file}\"...`),\n );\n writeCsv(\n file,\n points.map(({ key, value }) => ({\n timestamp: key,\n value,\n })),\n );\n });\n });\n } catch (err) {\n logger.error(\n colors.red(`An error occurred syncing the schema: ${err.message}`),\n );\n process.exit(1);\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced consent metrics to disk in folder \"${folder}\"! View at ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n } else {\n const encounteredErrors: string[] = [];\n await mapSeries(apiKeyOrList, async (apiKey, ind) => {\n const prefix = `[${ind + 1}/${apiKeyOrList.length}][${\n apiKey.organizationName\n }] `;\n logger.info(\n colors.magenta(\n `~~~\\n\\n${prefix}Attempting to pull consent metrics...\\n\\n~~~`,\n ),\n );\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, apiKey.apiKey);\n\n try {\n const configuration = await pullConsentManagerMetrics(client, {\n bin: parsedBin,\n start: startDate,\n end: endDate,\n });\n\n // ensure folder exists for that organization\n const subFolder = join(folder, apiKey.organizationName);\n if (!existsSync(subFolder)) {\n mkdirSync(subFolder);\n }\n\n // Write to file\n Object.entries(configuration).forEach(([metricName, metrics]) => {\n metrics.forEach(({ points, name }) => {\n const file = join(subFolder, `${metricName}_${name}.csv`);\n logger.info(\n colors.magenta(`Writing configuration to file \"${file}\"...`),\n );\n writeCsv(\n file,\n points.map(({ key, value }) => ({\n timestamp: key,\n value,\n })),\n );\n });\n });\n\n logger.info(\n colors.green(`${prefix}Successfully pulled configuration!`),\n );\n } catch (err) {\n logger.error(colors.red(`${prefix}Failed to sync configuration.`));\n encounteredErrors.push(apiKey.organizationName);\n }\n });\n\n if (encounteredErrors.length > 0) {\n logger.info(\n colors.red(\n `Sync encountered errors for \"${encounteredErrors.join(\n ',',\n )}\". View output above for more information, or check out ${ADMIN_DASH_INTEGRATIONS}`,\n ),\n );\n\n process.exit(1);\n }\n }\n}\n"],"mappings":"ocAEA,OAAOA,MAAY,SAEnB,OAAS,QAAAC,MAAY,OACrB,OAAOC,GAAM,cAAAC,EAAY,aAAAC,MAAiB,KAmB1C,eAAsBC,EAEpB,CACE,KAAAC,EACA,MAAAC,EACA,IAAAC,EACA,OAAAC,EACA,IAAAC,EACA,aAAAC,CACF,EACe,CAEf,IAAMC,EAAe,MAAMC,EAAsBP,CAAI,EAGjDQ,EAAG,WAAWL,CAAM,GAAK,CAACK,EAAG,UAAUL,CAAM,EAAE,YAAY,IAC7DM,EAAO,MACLC,EAAO,IACL,yFACF,CACF,EACA,QAAQ,KAAK,CAAC,GAIhB,IAAMC,EAAYP,EACb,OAAO,OAAOQ,CAAuB,EAAE,SAASD,CAAS,IAC5DF,EAAO,MACLC,EAAO,IACL,8CAA8CN,CAAG;AAAA;AAAA,EACzB,OAAO,OAAOQ,CAAuB,EAAE,KAC3D;AAAA,CACF,CAAC,EACL,CACF,EACA,QAAQ,KAAK,CAAC,GAIhB,IAAMC,EAAY,IAAI,KAAKZ,CAAK,EAC1Ba,EAAUZ,EAAM,IAAI,KAAKA,CAAG,EAAI,IAAI,KAuC1C,GAtCI,OAAO,MAAMW,EAAU,QAAQ,CAAC,IAClCJ,EAAO,MACLC,EAAO,IACL,qDAAqDT,CAAK,iCAC5D,CACF,EACA,QAAQ,KAAK,CAAC,GAEZ,OAAO,MAAMa,EAAQ,QAAQ,CAAC,IAChCL,EAAO,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ID,EAAM,CAAC,IAAI7B,EAAa,MAAM,KAC/C4B,EAAO,gBACT,KACAzB,EAAO,KACLC,EAAO,QACL;AAAA;AAAA,EAAU0B,CAAM;AAAA;AAAA,IAClB,CACF,EAGA,IAAMnB,EAASC,EAA4Bb,EAAc6B,EAAO,MAAM,EAEtE,GAAI,CACF,IAAMf,EAAgB,MAAMC,EAA0BH,EAAQ,CAC5D,IAAKN,EACL,MAAOE,EACP,IAAKC,CACP,CAAC,EAGKuB,EAAYX,EAAKvB,EAAQ+B,EAAO,gBAAgB,EACjDnB,EAAWsB,CAAS,GACvBrB,EAAUqB,CAAS,EAIrB,OAAO,QAAQlB,CAAa,EAAE,QAAQ,CAAC,CAACE,EAAYC,CAAO,IAAM,CAC/DA,EAAQ,QAAQ,CAAC,CAAE,OAAAC,EAAQ,KAAAC,CAAK,IAAM,CACpC,IAAMC,EAAOC,EAAKW,EAAW,GAAGhB,CAAU,IAAIG,CAAI,MAAM,EACxDf,EAAO,KACLC,EAAO,QAAQ,kCAAkCe,CAAI,MAAM,CAC7D,EACAE,EACEF,EACAF,EAAO,IAAI,CAAC,CAAE,IAAAK,EAAK,MAAAC,CAAM,KAAO,CAC9B,UAAWD,EACX,MAAAC,CACF,EAAE,CACJ,CACF,CAAC,CACH,CAAC,EAEDpB,EAAO,KACLC,EAAO,MAAM,GAAG0B,CAAM,oCAAoC,CAC5D,CACF,MAAc,CACZ3B,EAAO,MAAMC,EAAO,IAAI,GAAG0B,CAAM,+BAA+B,CAAC,EACjEJ,EAAkB,KAAKE,EAAO,gBAAgB,CAChD,CACF,CAAC,EAEGF,EAAkB,OAAS,IAC7BvB,EAAO,KACLC,EAAO,IACL,gCAAgCsB,EAAkB,KAChD,GACF,CAAC,2DAA2DD,CAAuB,EACrF,CACF,EAEA,QAAQ,KAAK,CAAC,EAElB,CACF","names":["colors","join","fs","existsSync","mkdirSync","pullConsentMetrics","auth","start","end","folder","bin","transcendUrl","apiKeyOrList","validateTranscendAuth","fs","logger","colors","parsedBin","ConsentManagerMetricBin","startDate","endDate","existsSync","mkdirSync","client","buildTranscendGraphQLClient","configuration","pullConsentManagerMetrics","metricName","metrics","points","name","file","join","writeCsv","key","value","err","ADMIN_DASH_INTEGRATIONS","encounteredErrors","mapSeries","apiKey","ind","prefix","subFolder"]}
@@ -0,0 +1,2 @@
1
+ import{b as p}from"./chunk-NZZKRVAI.js";import"./chunk-65I2PF73.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{ke as c,pe as m}from"./chunk-MK5T6DBK.js";import{a as r}from"./chunk-43JWXG77.js";import{b as g}from"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import n from"colors";import{execSync as k}from"child_process";var l='A repository name must be provided. You can specify using --repositoryName=$REPO_NAME or by ensuring the command "git config --get remote.origin.url" returns the name of the repository';async function S({auth:d,scanPath:o,ignoreDirs:f,repositoryName:u,transcendUrl:y}){let e=u;if(!e)try{let t=k(`cd ${o} && git config --get remote.origin.url`).toString("utf-8").trim();[e]=t.includes("https:")?t.split("/").slice(3).join("/").split("."):(t.split(":").pop()||"").split("."),e||(r.error(n.red(l)),process.exit(1))}catch(a){r.error(n.red(`${l} - Got error: ${a.message}`)),process.exit(1)}let h=m(y,d),i=await p({scanPath:o,ignoreDirs:f,repositoryName:e});await c(h,i);let s=new URL(g);s.pathname="/code-scanning/code-packages",r.info(n.green(`Scan found ${i.length} packages at ${o}! View results at '${s.href}'`))}export{S as scanPackages};
2
+ //# sourceMappingURL=impl-G4JGSVWD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/inventory/scan-packages/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { ADMIN_DASH } from '../../../constants';\nimport { findCodePackagesInFolder } from '../../../lib/code-scanning';\nimport {\n buildTranscendGraphQLClient,\n syncCodePackages,\n} from '../../../lib/graphql';\nimport { execSync } from 'child_process';\n\nconst REPO_ERROR =\n 'A repository name must be provided. ' +\n 'You can specify using --repositoryName=$REPO_NAME or by ensuring the ' +\n 'command \"git config --get remote.origin.url\" returns the name of the repository';\n\ninterface ScanPackagesCommandFlags {\n auth: string;\n scanPath: string;\n ignoreDirs?: string[];\n repositoryName?: string;\n transcendUrl: string;\n}\n\nexport async function scanPackages(\n this: LocalContext,\n {\n auth,\n scanPath,\n ignoreDirs,\n repositoryName,\n transcendUrl,\n }: ScanPackagesCommandFlags,\n): Promise<void> {\n // Ensure repository name is specified\n let gitRepositoryName = repositoryName;\n if (!gitRepositoryName) {\n try {\n const name = execSync(\n `cd ${scanPath} && git config --get remote.origin.url`,\n );\n // Trim and parse the URL\n const url = name.toString('utf-8').trim();\n [gitRepositoryName] = !url.includes('https:')\n ? (url.split(':').pop() || '').split('.')\n : url.split('/').slice(3).join('/').split('.');\n if (!gitRepositoryName) {\n logger.error(colors.red(REPO_ERROR));\n process.exit(1);\n }\n } catch (err) {\n logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n process.exit(1);\n }\n }\n\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Scan the codebase to discovery packages\n const results = await findCodePackagesInFolder({\n scanPath,\n ignoreDirs,\n repositoryName: gitRepositoryName,\n });\n\n // Report scan to Transcend\n await syncCodePackages(client, results);\n\n const newUrl = new URL(ADMIN_DASH);\n newUrl.pathname = '/code-scanning/code-packages';\n\n // Indicate success\n logger.info(\n colors.green(\n `Scan found ${results.length} packages at ${scanPath}! ` +\n `View results at '${newUrl.href}'`,\n ),\n );\n}\n"],"mappings":"qTAEA,OAAOA,MAAY,SAOnB,OAAS,YAAAC,MAAgB,gBAEzB,IAAMC,EACJ,2LAYF,eAAsBC,EAEpB,CACE,KAAAC,EACA,SAAAC,EACA,WAAAC,EACA,eAAAC,EACA,aAAAC,CACF,EACe,CAEf,IAAIC,EAAoBF,EACxB,GAAI,CAACE,EACH,GAAI,CAKF,IAAMC,EAJOT,EACX,MAAMI,CAAQ,wCAChB,EAEiB,SAAS,OAAO,EAAE,KAAK,EACxC,CAACI,CAAiB,EAAKC,EAAI,SAAS,QAAQ,EAExCA,EAAI,MAAM,GAAG,EAAE,MAAM,CAAC,EAAE,KAAK,GAAG,EAAE,MAAM,GAAG,GAD1CA,EAAI,MAAM,GAAG,EAAE,IAAI,GAAK,IAAI,MAAM,GAAG,EAErCD,IACHE,EAAO,MAAMC,EAAO,IAAIV,CAAU,CAAC,EACnC,QAAQ,KAAK,CAAC,EAElB,OAASW,EAAK,CACZF,EAAO,MAAMC,EAAO,IAAI,GAAGV,CAAU,iBAAiBW,EAAI,OAAO,EAAE,CAAC,EACpE,QAAQ,KAAK,CAAC,CAChB,CAIF,IAAMC,EAASC,EAA4BP,EAAcJ,CAAI,EAGvDY,EAAU,MAAMC,EAAyB,CAC7C,SAAAZ,EACA,WAAAC,EACA,eAAgBG,CAClB,CAAC,EAGD,MAAMS,EAAiBJ,EAAQE,CAAO,EAEtC,IAAMG,EAAS,IAAI,IAAIC,CAAU,EACjCD,EAAO,SAAW,+BAGlBR,EAAO,KACLC,EAAO,MACL,cAAcI,EAAQ,MAAM,gBAAgBX,CAAQ,sBAC9Bc,EAAO,IAAI,GACnC,CACF,CACF","names":["colors","execSync","REPO_ERROR","scanPackages","auth","scanPath","ignoreDirs","repositoryName","transcendUrl","gitRepositoryName","url","logger","colors","err","client","buildTranscendGraphQLClient","results","findCodePackagesInFolder","syncCodePackages","newUrl","ADMIN_DASH"]}
@@ -0,0 +1,2 @@
1
+ import{a as t}from"./chunk-HJULYIHF.js";import"./chunk-MA4JWWRO.js";import"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function c({auth:n,transcendUrl:e,file:i,concurrency:r,actions:o,sombraAuth:s}){await t({file:i,transcendUrl:e,concurrency:r,requestActions:o,auth:n,sombraAuth:s})}export{c as pullIdentifiers};
2
+ //# sourceMappingURL=impl-HFXHM3PH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/preflight/pull-identifiers/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../../context';\nimport { pullManualEnrichmentIdentifiersToCsv } from '../../../../lib/manual-enrichment';\nimport type { RequestAction } from '@transcend-io/privacy-types';\n\ninterface PullIdentifiersCommandFlags {\n auth: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n actions?: RequestAction[];\n concurrency: number;\n}\n\nexport async function pullIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n concurrency,\n actions,\n sombraAuth,\n }: PullIdentifiersCommandFlags,\n): Promise<void> {\n await pullManualEnrichmentIdentifiersToCsv({\n file,\n transcendUrl,\n concurrency,\n requestActions: actions,\n auth,\n sombraAuth,\n });\n}\n"],"mappings":"4OAaA,eAAsBA,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,KAAAC,EACA,YAAAC,EACA,QAAAC,EACA,WAAAC,CACF,EACe,CACf,MAAMC,EAAqC,CACzC,KAAAJ,EACA,aAAAD,EACA,YAAAE,EACA,eAAgBC,EAChB,KAAAJ,EACA,WAAAK,CACF,CAAC,CACH","names":["pullIdentifiers","auth","transcendUrl","file","concurrency","actions","sombraAuth","pullManualEnrichmentIdentifiersToCsv"]}
@@ -0,0 +1,2 @@
1
+ import{c as o}from"./chunk-26T4RUOI.js";import"./chunk-2V6ABZRI.js";import"./chunk-N6JZHL5U.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function i({auth:t,trackerStatus:r,file:s,transcendUrl:a}){await o({auth:t,trackerStatus:r,file:s,transcendUrl:a})}export{i as uploadCookiesFromCsv};
2
+ //# sourceMappingURL=impl-HMHOYOZZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/consent/upload-cookies-from-csv/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { uploadCookiesFromCsv as uploadCookiesFromCsvHelper } from '../../../lib/consent-manager';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\n\ninterface UploadCookiesFromCsvCommandFlags {\n auth: string;\n trackerStatus: ConsentTrackerStatus;\n file: string;\n transcendUrl: string;\n}\n\nexport async function uploadCookiesFromCsv(\n this: LocalContext,\n { auth, trackerStatus, file, transcendUrl }: UploadCookiesFromCsvCommandFlags,\n): Promise<void> {\n // Upload cookies\n await uploadCookiesFromCsvHelper({\n auth,\n trackerStatus,\n file,\n transcendUrl,\n });\n}\n"],"mappings":"oSAWA,eAAsBA,EAEpB,CAAE,KAAAC,EAAM,cAAAC,EAAe,KAAAC,EAAM,aAAAC,CAAa,EAC3B,CAEf,MAAMJ,EAA2B,CAC/B,KAAAC,EACA,cAAAC,EACA,KAAAC,EACA,aAAAC,CACF,CAAC,CACH","names":["uploadCookiesFromCsv","auth","trackerStatus","file","transcendUrl"]}
@@ -0,0 +1,7 @@
1
+ import{_b as L,a as N,b as R,ha as _,pe as D}from"./chunk-MK5T6DBK.js";import{a}from"./chunk-43JWXG77.js";import"./chunk-EZHASXA5.js";import{b as U}from"./chunk-ARVEJERC.js";import ge from"colors";import X from"got";var Q=({hostname:t,auth:e})=>X.extend({prefixUrl:`https://${t}`,headers:{accept:"application/json","content-type":"application/json",authorization:`Bearer ${e}`}});import Re from"colors";import xe from"yargs-parser";var Ge=Object.values(U);import te from"colors";import j from"fs";var w=({assessment:t,index:e,total:s,wrap:r=!0})=>{let n="";(e===0||r)&&(n=`[
2
+ `);let m=JSON.stringify(t),o=s&&e<s-1&&!r?",":"";return n=`${n+m+o}
3
+ `,(s&&e===s-1||r)&&(n+=`
4
+ ]`),n};var B=({file:t,assessment:e,index:s,total:r})=>{a.info(te.magenta(`Writing enriched assessment ${s+1} of ${r} to file "${t}"...`)),s===0?j.writeFileSync(t,w({assessment:e,index:s,total:r,wrap:!1})):j.appendFileSync(t,w({assessment:e,index:s,total:r,wrap:!1}))};import P from"colors";import{decodeCodec as re}from"@transcend-io/type-utils";import{OneTrustGetListOfAssessmentsResponse as ne}from"@transcend-io/privacy-types";var q=async({oneTrust:t})=>{let e=0,s=1,r=0,n=[];for(;e<s;){let{body:m}=await t.get(`api/assessment/v2/assessments?page=${e}&size=2000`),{page:o,content:u}=re(ne,m);n.push(...u??[]),e===0&&(s=o?.totalPages??0,r=o?.totalElements??0),e+=1,a.info(`Fetched ${n.length} of ${r} assessments.`)}return n};import{decodeCodec as oe}from"@transcend-io/type-utils";import{OneTrustGetAssessmentResponse as ie}from"@transcend-io/privacy-types";var J=async({oneTrust:t,assessmentId:e})=>{let{body:s}=await t.get(`api/assessment/v2/assessments/${e}/export?ExcludeSkippedQuestions=false`);return oe(ie,s)};import{decodeCodec as ae}from"@transcend-io/type-utils";import{OneTrustGetRiskResponse as me}from"@transcend-io/privacy-types";var K=async({oneTrust:t,riskId:e})=>{let{body:s}=await t.get(`api/risk/v2/risks/${e}`);return ae(me,s)};import{decodeCodec as ce}from"@transcend-io/type-utils";import{OneTrustGetUserResponse as ue}from"@transcend-io/privacy-types";var b=async({oneTrust:t,userId:e})=>{let{body:s}=await t.get(`api/scim/v2/Users/${e}`);return ce(ue,s)};import{uniq as pe}from"lodash-es";import{keyBy as I}from"lodash-es";var W=({assessment:t,assessmentDetails:e,riskDetails:s,creatorDetails:r,approversDetails:n,respondentsDetails:m})=>{let o=I(s,"id"),{sections:u,createdBy:g,...h}=e,O=u.map(i=>{let{questions:A,...$}=i,x=A.map(E=>{let{risks:C,...G}=E,v=(C??[]).map(y=>{let S=o[y.riskId];return{...y,...S,level:y.level,impactLevel:y.impactLevel??0}});return{...G,risks:v}});return{...$,questions:x}}),p={...g,active:r?.active??!1,userType:r?.userType??"Internal",emails:r?.emails??[],title:r?.title??null,givenName:r?.name.givenName??null,familyName:r?.name.familyName??null},d=I(n,"id"),l=e.approvers.flatMap(i=>d[i.id]?[{...i,approver:{...i.approver,active:d[i.id].active,userType:d[i.id].userType,emails:d[i.id].emails,title:d[i.id].title,givenName:d[i.id].name.givenName??null,familyName:d[i.id].name.familyName??null}}]:[]),T=I(m,"id"),F=e.respondents.filter(i=>!i.name.includes("@")).flatMap(i=>T[i.id]?[{...i,active:T[i.id].active,userType:T[i.id].userType,emails:T[i.id].emails,title:T[i.id].title,givenName:T[i.id].name.givenName??null,familyName:T[i.id].name.familyName??null}]:[]);return{...t,...h,approvers:l,respondents:F,createdBy:p,sections:O}};import H from"colors";var k=async({transcend:t,assessment:e,total:s,index:r})=>{a.info(H.magenta(`Writing enriched assessment ${r+1} ${s?`of ${s} `:" "}to Transcend...`));let m={json:w({assessment:e,index:r,total:s})};try{await L(t,_,{input:m})}catch{a.error(H.red(`Failed to sync assessment ${r+1} ${s?`of ${s} `:" "}to Transcend.
5
+ Assessment Title: ${e.name}. Template Title: ${e.template.name}
6
+ `))}};var z=async({oneTrust:t,file:e,dryRun:s,transcend:r})=>{a.info("Getting list of all assessments from OneTrust...");let n=await q({oneTrust:t}),m={},o=5,u=Array.from({length:Math.ceil(n.length/o)},(g,h)=>n.slice(h*o,(h+1)*o));await N(u,async(g,h)=>{let O=[];await R(g,async(p,d)=>{let l=o*h+d+1;a.info(`[assessment ${l} of ${n.length}]: fetching details...`);let{templateName:T,assessmentId:F}=p,i=await J({oneTrust:t,assessmentId:F}),A=i.createdBy.id,$=m[A];if(!$){a.info(`[assessment ${l} of ${n.length}]: fetching creator...`);try{$=await b({oneTrust:t,userId:A}),m[A]=$}catch{a.warn(P.yellow(`[assessment ${l} of ${n.length}]: failed to fetch form creator. creatorId: ${A}. Assessment Title: ${p.name}. Template Title: ${T}`))}}let{approvers:x}=i,E=[];x.length>0&&(a.info(`[assessment ${l} of ${n.length}]: fetching approvers...`),E=await R(x.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await b({oneTrust:t,userId:c}),m[c]=f),[f]}catch{return a.warn(P.yellow(`[assessment ${l} of ${n.length}]: failed to fetch a form approver. approverId: ${c}. Assessment Title: ${p.name}. Template Title: ${T}`)),[]}},{concurrency:5}));let{respondents:C}=i,G=C.filter(c=>!c.name.includes("@")),v=[];G.length>0&&(a.info(`[assessment ${l} of ${n.length}]: fetching respondents...`),v=await R(G.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await b({oneTrust:t,userId:c}),m[c]=f),[f]}catch{return a.warn(P.yellow(`[assessment ${l} of ${n.length}]: failed to fetch a respondent. respondentId: ${c}. Assessment Title: ${p.name}. Template Title: ${T}`)),[]}},{concurrency:5}));let y=[],S=pe(i.sections.flatMap(c=>c.questions.flatMap(f=>(f.risks??[]).flatMap(Z=>Z.riskId))));S.length>0&&(a.info(`[assessment ${l} of ${n.length}]: fetching risks...`),y=await R(S,c=>K({oneTrust:t,riskId:c}),{concurrency:5}));let V=W({assessment:p,assessmentDetails:i,riskDetails:y,creatorDetails:$,approversDetails:E.flat(),respondentsDetails:v.flat()});O.push(V)},{concurrency:o}),await N(O,async(p,d)=>{let l=h*o+d;s&&e?B({assessment:p,index:l,total:n.length,file:e}):r&&await k({assessment:p,transcend:r,total:n.length,index:l})})})};import{decodeCodec as le}from"@transcend-io/type-utils";import M from"colors";import fe from"JSONStream";import{createReadStream as de}from"fs";import{OneTrustEnrichedAssessment as Te}from"@transcend-io/privacy-types";var Y=({transcend:t,file:e})=>(a.info(`Getting list of all assessments from file ${e}...`),new Promise((s,r)=>{let n=de(e,{encoding:"utf-8",highWaterMark:65536}),m=fe.parse("*"),o=0;n.pipe(m),m.on("data",async u=>{try{m.pause();let g=le(Te,u);await k({assessment:g,transcend:t,index:o}),o+=1,m.resume()}catch(g){a.error(M.red(`Failed to parse the assessment ${o} from file '${e}': ${g.message}.`))}}),m.on("end",()=>{a.info(`Finished processing ${o} assessments from file ${e}`),s()}),m.on("error",u=>{a.error(M.red(`Error parsing file '${e}': ${u.message}`)),r(u)}),n.on("error",u=>{a.error(M.red(`Error reading file '${e}': ${u.message}`)),r(u)})}));async function _s({hostname:t,oneTrustAuth:e,source:s,transcendAuth:r,transcendUrl:n,resource:m,file:o,dryRun:u,debug:g}){if(!u&&!r)throw new Error('Must specify a "transcendAuth" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}');if(u&&!o)throw new Error('Must set a "file" parameter when "dryRun" is "true". e.g. --file=./oneTrustAssessments.json');if(o){let p=o.split(".");if(p.length<2)throw new Error('The "file" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.');if(p.at(-1)!=="json")throw new Error(`Expected the format of the "file" parameters '${o}' to be 'json', but got '${p.at(-1)}'.`)}if(s==="oneTrust"){if(!t)throw new Error('Missing required parameter "hostname". e.g. --hostname=customer.my.onetrust.com');if(!e)throw new Error('Missing required parameter "oneTrustAuth". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN')}else{if(!o)throw new Error('Must specify a "file" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json');if(u)throw new Error('Cannot read and write to a file simultaneously. Emit the "source" parameter or set it to oneTrust if "dryRun" is enabled.')}let h=t&&e?Q({hostname:t,auth:e}):void 0,O=n&&r?D(n,r):void 0;try{m==="assessments"&&(s==="oneTrust"&&h?await z({oneTrust:h,file:o,dryRun:u,...O&&{transcend:O}}):s==="file"&&o&&O&&await Y({file:o,transcend:O}))}catch(p){throw new Error(`An error occurred syncing the resource ${m} from OneTrust: ${g?p.stack:p.message}`)}a.info(ge.green(`Successfully synced OneTrust ${m} to ${u?`disk at "${o}"`:"Transcend"}!`))}export{_s as syncOt};
7
+ //# sourceMappingURL=impl-IU4EANSX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/migration/sync-ot/impl.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/lib/oneTrust/helpers/parseCliSyncOtArguments.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToDisk.ts","../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/endpoints/getOneTrustAssessment.ts","../src/lib/oneTrust/endpoints/getOneTrustRisk.ts","../src/lib/oneTrust/endpoints/getOneTrustUser.ts","../src/lib/oneTrust/helpers/enrichOneTrustAssessment.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromFile.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { createOneTrustGotInstance } from '../../../lib/oneTrust';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\nimport { buildTranscendGraphQLClient } from '../../../lib/graphql';\nimport {\n syncOneTrustAssessmentsFromFile,\n syncOneTrustAssessmentsFromOneTrust,\n} from '../../../lib/oneTrust/helpers';\n\n// Command flag interface\ninterface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${\n dryRun ? `disk at \"${file}\"` : 'Transcend'\n }!`,\n ),\n );\n}\n","import got, { Got } from 'got';\n\n/**\n * Instantiate an instance of got that is capable of making requests to OneTrust\n *\n * @param param - information about the OneTrust URL\n * @returns The instance of got that is capable of making requests to the customer ingress\n */\nexport const createOneTrustGotInstance = ({\n hostname,\n auth,\n}: {\n /** Hostname of the OneTrust API */\n hostname: string;\n /** The OAuth access token */\n auth: string;\n}): Got =>\n got.extend({\n prefixUrl: `https://${hostname}`,\n headers: {\n accept: 'application/json',\n 'content-type': 'application/json',\n authorization: `Bearer ${auth}`,\n },\n });\n","import { logger } from '../../../logger';\nimport colors from 'colors';\nimport yargs from 'yargs-parser';\nimport {\n OneTrustFileFormat,\n OneTrustPullResource,\n OneTrustPullSource,\n} from '../../../enums';\n\nconst VALID_RESOURCES = Object.values(OneTrustPullResource);\n\ninterface OneTrustCliArguments {\n /** The name of the file to write the resources to */\n file: string;\n /** The OneTrust hostname to send the requests to */\n hostname?: string;\n /** The OAuth Bearer token used to authenticate the requests to OneTrust */\n oneTrustAuth?: string;\n /** The Transcend API key to authenticate the requests to Transcend */\n transcendAuth: string;\n /** The Transcend URL where to forward requests */\n transcendUrl: string;\n /** The resource to pull from OneTrust */\n resource: OneTrustPullResource;\n /** Whether to enable debugging while reporting errors */\n debug: boolean;\n /** Whether to export the resource into a file rather than push to transcend */\n dryRun: boolean;\n /** Where to read the OneTrust resource from */\n source: OneTrustPullSource;\n}\n\n/**\n * Parse the command line arguments\n *\n * @returns the parsed arguments\n */\nexport const parseCliSyncOtArguments = (): OneTrustCliArguments => {\n const {\n file,\n hostname,\n oneTrustAuth,\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n } = yargs(process.argv.slice(2), {\n string: [\n 'file',\n 'hostname',\n 'oneTrustAuth',\n 'resource',\n 'dryRun',\n 'transcendAuth',\n 'transcendUrl',\n 'source',\n ],\n boolean: ['debug', 'dryRun'],\n default: {\n resource: OneTrustPullResource.Assessments,\n debug: false,\n dryRun: false,\n transcendUrl: 'https://api.transcend.io',\n source: OneTrustPullSource.OneTrust,\n },\n });\n\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n logger.error(\n colors.red(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n ),\n );\n return process.exit(1);\n }\n if (!dryRun && !transcendUrl) {\n logger.error(\n colors.red(\n // eslint-disable-next-line max-len\n 'Must specify a \"transcendUrl\" parameter to sync resources to Transcend. e.g. --transcendUrl=https://api.transcend.io',\n ),\n );\n return process.exit(1);\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n logger.error(\n colors.red(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n logger.error(\n colors.red(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n ),\n );\n return process.exit(1);\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n logger.error(\n colors.red(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n ),\n );\n return process.exit(1);\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n logger.error(\n colors.red(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n ),\n );\n return process.exit(1);\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n logger.error(\n colors.red(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n ),\n );\n return process.exit(1);\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n logger.error(\n colors.red(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n ),\n );\n return process.exit(1);\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n logger.error(\n colors.red(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n ),\n );\n return process.exit(1);\n }\n }\n\n if (!VALID_RESOURCES.includes(resource)) {\n logger.error(\n colors.red(\n `Received invalid resource value: \"${resource}\". Allowed: ${VALID_RESOURCES.join(\n ',',\n )}`,\n ),\n );\n return process.exit(1);\n }\n\n return {\n file,\n ...(hostname && { hostname }),\n ...(oneTrustAuth && { oneTrustAuth }),\n resource,\n debug,\n dryRun,\n transcendAuth,\n transcendUrl,\n source,\n };\n};\n","import { logger } from '../../../logger';\nimport colors from 'colors';\nimport fs from 'fs';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Write the assessment to disk at the specified file path.\n *\n *\n * @param param - information about the assessment to write\n */\nexport const syncOneTrustAssessmentToDisk = ({\n file,\n assessment,\n index,\n total,\n}: {\n /** The file path to write the assessment to */\n file: string;\n /** The basic assessment */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total: number;\n}): void => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${\n index + 1\n } of ${total} to file \"${file}\"...`,\n ),\n );\n\n if (index === 0) {\n fs.writeFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n } else {\n fs.appendFileSync(\n file,\n oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n wrap: false,\n }),\n );\n }\n};\n","import { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\n\n/**\n * Converts the assessment into a json entry.\n *\n * @param param - information about the assessment and amount of entries\n * @returns a stringified json entry ready to be appended to a file\n */\nexport const oneTrustAssessmentToJson = ({\n assessment,\n index,\n total,\n wrap = true,\n}: {\n /** The assessment to convert */\n assessment: OneTrustEnrichedAssessment;\n /** The position of the assessment in the final Json object */\n index: number;\n /** The total amount of the assessments in the final Json object */\n total?: number;\n /** Whether to wrap every entry in brackets */\n wrap?: boolean;\n}): string => {\n let jsonEntry = '';\n // start with an opening bracket\n if (index === 0 || wrap) {\n jsonEntry = '[\\n';\n }\n\n const stringifiedAssessment = JSON.stringify(assessment);\n\n // Add comma for all items except the last one\n const comma = total && index < total - 1 && !wrap ? ',' : '';\n\n // write to file\n jsonEntry = `${jsonEntry + stringifiedAssessment + comma}\\n`;\n\n // end with closing bracket\n if ((total && index === total - 1) || wrap) {\n jsonEntry += '\\n]';\n }\n\n return jsonEntry;\n};\n","import type { Got } from 'got';\nimport colors from 'colors';\nimport {\n getListOfOneTrustAssessments,\n getOneTrustAssessment,\n getOneTrustRisk,\n getOneTrustUser,\n} from '../endpoints';\nimport { mapSeries, map } from '../../bluebird-replace';\nimport { logger } from '../../../logger';\nimport {\n OneTrustAssessmentQuestion,\n OneTrustAssessmentSection,\n OneTrustEnrichedAssessment,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { uniq } from 'lodash-es';\nimport { enrichOneTrustAssessment } from './enrichOneTrustAssessment';\nimport { syncOneTrustAssessmentToDisk } from './syncOneTrustAssessmentToDisk';\nimport { GraphQLClient } from 'graphql-request';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Reads all the assessments from a OneTrust instance and syncs them to Transcend or to Disk.\n *\n * @param param - the information about the assessment, its OneTrust source, and destination (disk or Transcend)\n */\nexport const syncOneTrustAssessmentsFromOneTrust = async ({\n oneTrust,\n file,\n dryRun,\n transcend,\n}: {\n /** the OneTrust client instance */\n oneTrust: Got;\n /** the Transcend client instance */\n transcend?: GraphQLClient;\n /** Whether to write to file instead of syncing to Transcend */\n dryRun: boolean;\n /** the path to the file in case dryRun is true */\n file?: string;\n}): Promise<void> => {\n // fetch the list of all assessments in the OneTrust organization\n logger.info('Getting list of all assessments from OneTrust...');\n const assessments = await getListOfOneTrustAssessments({ oneTrust });\n\n // a cache of OneTrust users so we avoid requesting already fetched users\n const oneTrustCachedUsers: Record<string, OneTrustGetUserResponse> = {};\n\n // split all assessments in batches, so we can process some of steps in parallel\n const BATCH_SIZE = 5;\n const assessmentBatches = Array.from(\n {\n length: Math.ceil(assessments.length / BATCH_SIZE),\n },\n (_, i) => assessments.slice(i * BATCH_SIZE, (i + 1) * BATCH_SIZE),\n );\n\n // process each batch and sync the batch right away so it's garbage collected and we don't run out of memory\n await mapSeries(assessmentBatches, async (assessmentBatch, batch) => {\n const batchEnrichedAssessments: OneTrustEnrichedAssessment[] = [];\n\n // fetch assessment details from OneTrust in parallel\n await map(\n assessmentBatch,\n async (assessment, index) => {\n const assessmentNumber = BATCH_SIZE * batch + index + 1;\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching details...`,\n );\n const { templateName, assessmentId } = assessment;\n const assessmentDetails = await getOneTrustAssessment({\n oneTrust,\n assessmentId,\n });\n // fetch assessment's creator information\n const creatorId = assessmentDetails.createdBy.id;\n let creator = oneTrustCachedUsers[creatorId];\n if (!creator) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching creator...`,\n );\n try {\n creator = await getOneTrustUser({\n oneTrust,\n userId: creatorId,\n });\n oneTrustCachedUsers[creatorId] = creator;\n } catch (e) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch form creator.` +\n `\\tcreatorId: ${creatorId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n );\n }\n }\n\n // fetch assessment approvers information\n const { approvers } = assessmentDetails;\n let approversDetails: OneTrustGetUserResponse[][] = [];\n if (approvers.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching approvers...`,\n );\n approversDetails = await map(\n approvers.map(({ id }) => id),\n async (userId) => {\n try {\n let approver = oneTrustCachedUsers[userId];\n if (!approver) {\n approver = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = approver;\n }\n return [approver];\n } catch (e) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a form approver.` +\n `\\tapproverId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment internal respondents information\n const { respondents } = assessmentDetails;\n // if a user is an internal respondents, their 'name' field can't be an email.\n const internalRespondents = respondents.filter(\n (r) => !r.name.includes('@'),\n );\n let respondentsDetails: OneTrustGetUserResponse[][] = [];\n if (internalRespondents.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching respondents...`,\n );\n respondentsDetails = await map(\n internalRespondents.map(({ id }) => id),\n async (userId) => {\n try {\n let respondent = oneTrustCachedUsers[userId];\n if (!respondent) {\n respondent = await getOneTrustUser({ oneTrust, userId });\n oneTrustCachedUsers[userId] = respondent;\n }\n return [respondent];\n } catch (e) {\n logger.warn(\n colors.yellow(\n `[assessment ${assessmentNumber} of ${assessments.length}]: failed to fetch a respondent.` +\n `\\trespondentId: ${userId}. Assessment Title: ${assessment.name}. Template Title: ${templateName}`,\n ),\n );\n return [];\n }\n },\n { concurrency: 5 },\n );\n }\n\n // fetch assessment risk information\n let riskDetails: OneTrustGetRiskResponse[] = [];\n const riskIds = uniq(\n assessmentDetails.sections.flatMap((s: OneTrustAssessmentSection) =>\n s.questions.flatMap((q: OneTrustAssessmentQuestion) =>\n (q.risks ?? []).flatMap((r) => r.riskId),\n ),\n ),\n );\n if (riskIds.length > 0) {\n logger.info(\n `[assessment ${assessmentNumber} of ${assessments.length}]: fetching risks...`,\n );\n riskDetails = await map(\n riskIds,\n (riskId) => getOneTrustRisk({ oneTrust, riskId: riskId as string }),\n {\n concurrency: 5,\n },\n );\n }\n\n // enrich the assessments with user and risk details\n const enrichedAssessment = enrichOneTrustAssessment({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails: creator,\n approversDetails: approversDetails.flat(),\n respondentsDetails: respondentsDetails.flat(),\n });\n\n batchEnrichedAssessments.push(enrichedAssessment);\n },\n { concurrency: BATCH_SIZE },\n );\n\n // sync assessments in series to avoid concurrency bugs\n await mapSeries(\n batchEnrichedAssessments,\n async (enrichedAssessment, index) => {\n // the assessment's global index takes its batch into consideration\n const globalIndex = batch * BATCH_SIZE + index;\n\n if (dryRun && file) {\n // sync to file\n syncOneTrustAssessmentToDisk({\n assessment: enrichedAssessment,\n index: globalIndex,\n total: assessments.length,\n file,\n });\n } else if (transcend) {\n // sync to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: enrichedAssessment,\n transcend,\n total: assessments.length,\n index: globalIndex,\n });\n }\n },\n );\n });\n};\n","import { Got } from 'got';\nimport { logger } from '../../../logger';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport {\n OneTrustAssessment,\n OneTrustGetListOfAssessmentsResponse,\n} from '@transcend-io/privacy-types';\n\n/**\n * Fetch a list of all assessments from the OneTrust client.\n * ref: https://developer.onetrust.com/onetrust/reference/getallassessmentbasicdetailsusingget\n *\n * @param param - the information about the OneTrust client\n * @returns a list of OneTrustAssessment\n */\nexport const getListOfOneTrustAssessments = async ({\n oneTrust,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n}): Promise<OneTrustAssessment[]> => {\n let currentPage = 0;\n let totalPages = 1;\n let totalElements = 0;\n\n const allAssessments: OneTrustAssessment[] = [];\n\n while (currentPage < totalPages) {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments?page=${currentPage}&size=2000`,\n );\n\n const { page, content } = decodeCodec(\n OneTrustGetListOfAssessmentsResponse,\n body,\n );\n allAssessments.push(...(content ?? []));\n if (currentPage === 0) {\n totalPages = page?.totalPages ?? 0;\n totalElements = page?.totalElements ?? 0;\n }\n currentPage += 1;\n\n // log progress\n logger.info(\n `Fetched ${allAssessments.length} of ${totalElements} assessments.`,\n );\n }\n\n return allAssessments;\n};\n","import { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetAssessmentResponse } from '@transcend-io/privacy-types';\n\n/**\n * Retrieve details about a particular assessment.\n * ref: https://developer.onetrust.com/onetrust/reference/exportassessmentusingget\n *\n * @param param - the information about the OneTrust client and assessment to retrieve\n * @returns details about the assessment\n */\nexport const getOneTrustAssessment = async ({\n oneTrust,\n assessmentId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the assessment to retrieve */\n assessmentId: string;\n}): Promise<OneTrustGetAssessmentResponse> => {\n const { body } = await oneTrust.get(\n `api/assessment/v2/assessments/${assessmentId}/export?ExcludeSkippedQuestions=false`,\n );\n\n return decodeCodec(OneTrustGetAssessmentResponse, body);\n};\n","import { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetRiskResponse } from '@transcend-io/privacy-types';\n\n/**\n * Retrieve details about a particular risk.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustRisk = async ({\n oneTrust,\n riskId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust risk to retrieve */\n riskId: string;\n}): Promise<OneTrustGetRiskResponse> => {\n const { body } = await oneTrust.get(`api/risk/v2/risks/${riskId}`);\n\n return decodeCodec(OneTrustGetRiskResponse, body);\n};\n","import { Got } from 'got';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { OneTrustGetUserResponse } from '@transcend-io/privacy-types';\n\n/**\n * Retrieve details about a particular user.\n * ref: https://developer.onetrust.com/onetrust/reference/getriskusingget\n *\n * @param param - the information about the OneTrust client and risk to retrieve\n * @returns the OneTrust risk\n */\nexport const getOneTrustUser = async ({\n oneTrust,\n userId,\n}: {\n /** The OneTrust client instance */\n oneTrust: Got;\n /** The ID of the OneTrust user to retrieve */\n userId: string;\n}): Promise<OneTrustGetUserResponse> => {\n const { body } = await oneTrust.get(`api/scim/v2/Users/${userId}`);\n\n return decodeCodec(OneTrustGetUserResponse, body);\n};\n","import {\n OneTrustAssessment,\n OneTrustEnrichedAssessment,\n OneTrustGetAssessmentResponse,\n OneTrustGetRiskResponse,\n OneTrustGetUserResponse,\n} from '@transcend-io/privacy-types';\nimport { keyBy } from 'lodash-es';\n\n/**\n * Merge the assessment, assessmentDetails, and riskDetails into one object.\n *\n * @param param - the assessment and risk information\n * @returns the assessment enriched with details and risk information\n */\nexport const enrichOneTrustAssessment = ({\n assessment,\n assessmentDetails,\n riskDetails,\n creatorDetails,\n approversDetails,\n respondentsDetails,\n}: {\n /** The OneTrust risk details */\n riskDetails: OneTrustGetRiskResponse[];\n /** The OneTrust assessment as returned from Get List of Assessments endpoint */\n assessment: OneTrustAssessment;\n /** The OneTrust assessment details */\n assessmentDetails: OneTrustGetAssessmentResponse;\n /** The OneTrust assessment creator details */\n creatorDetails: OneTrustGetUserResponse;\n /** The OneTrust assessment approvers details */\n approversDetails: OneTrustGetUserResponse[];\n /** The OneTrust assessment internal respondents details */\n respondentsDetails: OneTrustGetUserResponse[];\n}): OneTrustEnrichedAssessment => {\n const riskDetailsById = keyBy(riskDetails, 'id');\n const { sections, createdBy, ...restAssessmentDetails } = assessmentDetails;\n const sectionsWithEnrichedRisk = sections.map((section) => {\n const { questions, ...restSection } = section;\n const enrichedQuestions = questions.map((question) => {\n const { risks, ...restQuestion } = question;\n const enrichedRisks = (risks ?? []).map((risk) => {\n const details = riskDetailsById[risk.riskId];\n return {\n ...risk,\n ...details,\n level: risk.level,\n impactLevel: risk.impactLevel ?? 0,\n };\n });\n return {\n ...restQuestion,\n risks: enrichedRisks,\n };\n });\n return {\n ...restSection,\n questions: enrichedQuestions,\n };\n });\n\n // grab creator details\n const enrichedCreatedBy = {\n ...createdBy,\n active: creatorDetails?.active ?? false,\n userType: creatorDetails?.userType ?? 'Internal',\n emails: creatorDetails?.emails ?? [],\n title: creatorDetails?.title ?? null,\n givenName: creatorDetails?.name.givenName ?? null,\n familyName: creatorDetails?.name.familyName ?? null,\n };\n\n // grab approvers details\n const approverDetailsById = keyBy(approversDetails, 'id');\n const enrichedApprovers = assessmentDetails.approvers.flatMap(\n (originalApprover) =>\n approverDetailsById[originalApprover.id]\n ? [\n {\n ...originalApprover,\n approver: {\n ...originalApprover.approver,\n active: approverDetailsById[originalApprover.id].active,\n userType: approverDetailsById[originalApprover.id].userType,\n emails: approverDetailsById[originalApprover.id].emails,\n title: approverDetailsById[originalApprover.id].title,\n givenName:\n approverDetailsById[originalApprover.id].name.givenName ??\n null,\n familyName:\n approverDetailsById[originalApprover.id].name.familyName ??\n null,\n },\n },\n ]\n : [],\n );\n\n // grab respondents details\n const respondentsDetailsById = keyBy(respondentsDetails, 'id');\n const enrichedRespondents = assessmentDetails.respondents\n .filter((r) => !r.name.includes('@')) // search only internal respondents\n .flatMap((respondent) =>\n respondentsDetailsById[respondent.id]\n ? [\n {\n ...respondent,\n active: respondentsDetailsById[respondent.id].active,\n userType: respondentsDetailsById[respondent.id].userType,\n emails: respondentsDetailsById[respondent.id].emails,\n title: respondentsDetailsById[respondent.id].title,\n givenName:\n respondentsDetailsById[respondent.id].name.givenName ?? null,\n familyName:\n respondentsDetailsById[respondent.id].name.familyName ?? null,\n },\n ]\n : [],\n );\n\n // combine everything into a single enriched assessment\n return {\n ...assessment,\n ...restAssessmentDetails,\n approvers: enrichedApprovers,\n respondents: enrichedRespondents,\n createdBy: enrichedCreatedBy,\n sections: sectionsWithEnrichedRisk,\n };\n};\n","import { logger } from '../../../logger';\nimport colors from 'colors';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n IMPORT_ONE_TRUST_ASSESSMENT_FORMS,\n makeGraphQLRequest,\n} from '../../graphql';\nimport { ImportOnetrustAssessmentsInput } from '../../../codecs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { oneTrustAssessmentToJson } from './oneTrustAssessmentToJson';\n\nexport interface AssessmentForm {\n /** ID of Assessment Form */\n id: string;\n /** Title of Assessment Form */\n name: string;\n}\n\n/**\n * Write the assessment to a Transcend instance.\n *\n *\n * @param param - information about the assessment and Transcend instance to write to\n */\nexport const syncOneTrustAssessmentToTranscend = async ({\n transcend,\n assessment,\n total,\n index,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** the assessment to sync to Transcend */\n assessment: OneTrustEnrichedAssessment;\n /** The index of the assessment being written to the file */\n index: number;\n /** The total amount of assessments that we will write */\n total?: number;\n}): Promise<void> => {\n logger.info(\n colors.magenta(\n `Writing enriched assessment ${index + 1} ${\n total ? `of ${total} ` : ' '\n }to Transcend...`,\n ),\n );\n\n // convert the OneTrust assessment object into a json record\n const json = oneTrustAssessmentToJson({\n assessment,\n index,\n total,\n });\n\n // transform the json record into a valid input to the mutation\n const input: ImportOnetrustAssessmentsInput = {\n json,\n };\n\n try {\n await makeGraphQLRequest<{\n /** the importOneTrustAssessmentForms mutation */\n importOneTrustAssessmentForms: {\n /** Created Assessment Forms */\n assessmentForms: AssessmentForm[];\n };\n }>(transcend, IMPORT_ONE_TRUST_ASSESSMENT_FORMS, {\n input,\n });\n } catch (e) {\n logger.error(\n colors.red(\n `Failed to sync assessment ${index + 1} ${\n total ? `of ${total} ` : ' '\n }to Transcend.\\n` +\n `\\tAssessment Title: ${assessment.name}. Template Title: ${assessment.template.name}\\n`,\n ),\n );\n }\n};\n","import { decodeCodec } from '@transcend-io/type-utils';\nimport colors from 'colors';\nimport { logger } from '../../../logger';\nimport JSONStream from 'JSONStream';\n\nimport { createReadStream } from 'fs';\nimport { OneTrustEnrichedAssessment } from '@transcend-io/privacy-types';\nimport { syncOneTrustAssessmentToTranscend } from './syncOneTrustAssessmentToTranscend';\nimport { GraphQLClient } from 'graphql-request';\n\n/**\n * Reads assessments from a file and syncs them to Transcend.\n *\n * @param param - the information about the source file and Transcend instance to write them to.\n */\nexport const syncOneTrustAssessmentsFromFile = ({\n transcend,\n file,\n}: {\n /** the Transcend client instance */\n transcend: GraphQLClient;\n /** The name of the file from which to read the OneTrust assessments */\n file: string;\n}): Promise<void> => {\n logger.info(`Getting list of all assessments from file ${file}...`);\n\n return new Promise((resolve, reject) => {\n // Create a readable stream from the file\n const fileStream = createReadStream(file, {\n encoding: 'utf-8',\n highWaterMark: 64 * 1024, // 64KB chunks\n });\n\n // Create a JSONStream parser to parse the array of OneTrust assessments from the file\n const parser = JSONStream.parse('*'); // '*' matches each element in the root array\n\n let index = 0;\n\n // Pipe the file stream into the JSON parser\n fileStream.pipe(parser);\n\n // Handle each parsed assessment object\n parser.on('data', async (assessment) => {\n try {\n // Pause the stream while processing to avoid overwhelming memory\n parser.pause();\n\n // Decode and validate the assessment\n const parsedAssessment = decodeCodec(\n OneTrustEnrichedAssessment,\n assessment,\n );\n\n // Sync the assessment to transcend\n await syncOneTrustAssessmentToTranscend({\n assessment: parsedAssessment,\n transcend,\n index,\n });\n\n index += 1;\n\n // Resume the stream after processing\n parser.resume();\n } catch (e) {\n // if failed to parse a line, report error and continue\n logger.error(\n colors.red(\n `Failed to parse the assessment ${index} from file '${file}': ${e.message}.`,\n ),\n );\n }\n });\n\n // Handle completion\n parser.on('end', () => {\n logger.info(`Finished processing ${index} assessments from file ${file}`);\n resolve();\n });\n\n // Handle stream or parsing errors\n parser.on('error', (error) => {\n logger.error(\n colors.red(`Error parsing file '${file}': ${error.message}`),\n );\n reject(error);\n });\n\n fileStream.on('error', (error) => {\n logger.error(\n colors.red(`Error reading file '${file}': ${error.message}`),\n );\n reject(error);\n });\n });\n};\n"],"mappings":"8KAEA,OAAOA,OAAY,SCFnB,OAAOC,MAAkB,MAQlB,IAAMC,EAA4B,CAAC,CACxC,SAAAC,EACA,KAAAC,CACF,IAMEH,EAAI,OAAO,CACT,UAAW,WAAWE,CAAQ,GAC9B,QAAS,CACP,OAAQ,mBACR,eAAgB,mBAChB,cAAe,UAAUC,CAAI,EAC/B,CACF,CAAC,ECvBH,OAAOC,OAAY,SACnB,OAAOC,OAAW,eAOlB,IAAMC,GAAkB,OAAO,OAAOC,CAAoB,ECR1D,OAAOC,OAAY,SACnB,OAAOC,MAAQ,KCMR,IAAMC,EAA2B,CAAC,CACvC,WAAAC,EACA,MAAAC,EACA,MAAAC,EACA,KAAAC,EAAO,EACT,IASc,CACZ,IAAIC,EAAY,IAEZH,IAAU,GAAKE,KACjBC,EAAY;AAAA,GAGd,IAAMC,EAAwB,KAAK,UAAUL,CAAU,EAGjDM,EAAQJ,GAASD,EAAQC,EAAQ,GAAK,CAACC,EAAO,IAAM,GAG1D,OAAAC,EAAY,GAAGA,EAAYC,EAAwBC,CAAK;AAAA,GAGnDJ,GAASD,IAAUC,EAAQ,GAAMC,KACpCC,GAAa;AAAA,IAGRA,CACT,ED/BO,IAAMG,EAA+B,CAAC,CAC3C,KAAAC,EACA,WAAAC,EACA,MAAAC,EACA,MAAAC,CACF,IASY,CACVC,EAAO,KACLC,GAAO,QACL,+BACEH,EAAQ,CACV,OAAOC,CAAK,aAAaH,CAAI,MAC/B,CACF,EAEIE,IAAU,EACZI,EAAG,cACDN,EACAO,EAAyB,CACvB,WAAAN,EACA,MAAAC,EACA,MAAAC,EACA,KAAM,EACR,CAAC,CACH,EAEAG,EAAG,eACDN,EACAO,EAAyB,CACvB,WAAAN,EACA,MAAAC,EACA,MAAAC,EACA,KAAM,EACR,CAAC,CACH,CAEJ,EEvDA,OAAOK,MAAY,SCCnB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IG,EAAU,OAAS,EACrB,MAAM,IAAI,MACR,6GACF,EAEF,GAAIA,EAAU,GAAG,EAAE,IAAM,OACvB,MAAM,IAAI,MACR,iDAAiDH,CAAI,4BAEtCG,EAAU,GAAG,EAAE,CAAC,IACjC,CAEJ,CAGA,GAAIP,IAAW,WAA6B,CAE1C,GAAI,CAACF,EACH,MAAM,IAAI,MACR,iFACF,EAGF,GAAI,CAACC,EACH,MAAM,IAAI,MACR,sFACF,CAEJ,KAAO,CAEL,GAAI,CAACK,EACH,MAAM,IAAI,MACR,iHACF,EAIF,GAAIC,EACF,MAAM,IAAI,iIAGV,CAEJ,CAGA,IAAMG,EACJV,GAAYC,EACRU,EAA0B,CACxB,SAAAX,EACA,KAAMC,CACR,CAAC,EACD,OAGAW,EACJR,GAAgBD,EACZU,EAA4BT,EAAcD,CAAa,EACvD,OAEN,GAAI,CACEE,IAAa,gBACXH,IAAW,YAA+BQ,EAC5C,MAAMI,EAAoC,CACxC,SAAAJ,EACA,KAAAJ,EACA,OAAAC,EACA,GAAIK,GAAa,CAAE,UAAAA,CAAU,CAC/B,CAAC,EACQV,IAAW,QAA2BI,GAAQM,GACvD,MAAMG,EAAgC,CAAE,KAAAT,EAAM,UAAAM,CAAU,CAAC,EAG/D,OAASI,EAAK,CACZ,MAAM,IAAI,MACR,0CAA0CX,CAAQ,mBAChDG,EAAQQ,EAAI,MAAQA,EAAI,OAC1B,EACF,CACF,CAGAC,EAAO,KACLC,GAAO,MACL,gCAAgCb,CAAQ,OACtCE,EAAS,YAAYD,CAAI,IAAM,WACjC,GACF,CACF,CACF","names":["colors","got","createOneTrustGotInstance","hostname","auth","colors","yargs","VALID_RESOURCES","OneTrustPullResource","colors","fs","oneTrustAssessmentToJson","assessment","index","total","wrap","jsonEntry","stringifiedAssessment","comma","syncOneTrustAssessmentToDisk","file","assessment","index","total","logger","colors","fs","oneTrustAssessmentToJson","colors","decodeCodec","OneTrustGetListOfAssessmentsResponse","getListOfOneTrustAssessments","oneTrust","currentPage","totalPages","totalElements","allAssessments","body","page","content","logger","decodeCodec","OneTrustGetAssessmentResponse","getOneTrustAssessment","oneTrust","assessmentId","body","decodeCodec","OneTrustGetRiskResponse","getOneTrustRisk","oneTrust","riskId","body","decodeCodec","OneTrustGetUserResponse","getOneTrustUser","oneTrust","userId","body","uniq","keyBy","enrichOneTrustAssessment","assessment","assessmentDetails","riskDetails","creatorDetails","approversDetails","respondentsDetails","riskDetailsById","sections","createdBy","restAssessmentDetails","sectionsWithEnrichedRisk","section","questions","restSection","enrichedQuestions","question","risks","restQuestion","enrichedRisks","risk","details","enrichedCreatedBy","approverDetailsById","enrichedApprovers","originalApprover","respondentsDetailsById","enrichedRespondents","r","respondent","colors","syncOneTrustAssessmentToTranscend","transcend","assessment","total","index","logger","colors","input","oneTrustAssessmentToJson","makeGraphQLRequest","IMPORT_ONE_TRUST_ASSESSMENT_FORMS","syncOneTrustAssessmentsFromOneTrust","oneTrust","file","dryRun","transcend","logger","assessments","getListOfOneTrustAssessments","oneTrustCachedUsers","BATCH_SIZE","assessmentBatches","_","i","mapSeries","assessmentBatch","batch","batchEnrichedAssessments","map","assessment","index","assessmentNumber","templateName","assessmentId","assessmentDetails","getOneTrustAssessment","creatorId","creator","getOneTrustUser","colors","approvers","approversDetails","id","userId","approver","respondents","internalRespondents","r","respondentsDetails","respondent","riskDetails","riskIds","uniq","s","q","riskId","getOneTrustRisk","enrichedAssessment","enrichOneTrustAssessment","globalIndex","syncOneTrustAssessmentToDisk","syncOneTrustAssessmentToTranscend","decodeCodec","colors","JSONStream","createReadStream","OneTrustEnrichedAssessment","syncOneTrustAssessmentsFromFile","transcend","file","logger","resolve","reject","fileStream","createReadStream","parser","JSONStream","index","assessment","parsedAssessment","decodeCodec","OneTrustEnrichedAssessment","syncOneTrustAssessmentToTranscend","e","colors","error","syncOt","hostname","oneTrustAuth","source","transcendAuth","transcendUrl","resource","file","dryRun","debug","splitFile","oneTrust","createOneTrustGotInstance","transcend","buildTranscendGraphQLClient","syncOneTrustAssessmentsFromOneTrust","syncOneTrustAssessmentsFromFile","err","logger","colors"]}
@@ -0,0 +1,2 @@
1
+ import{R as t}from"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function e({auth:i,transcendUrl:o,enricherIds:r}){await t({transcendUrl:o,auth:i,enricherIds:r})}export{e as skipPreflightJobs};
2
+ //# sourceMappingURL=impl-IWDHKBWZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/skip-preflight-jobs/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { skipPreflightJobs as skipPreflightJobsHelper } from '../../../lib/requests';\n\ninterface SkipPreflightJobsCommandFlags {\n auth: string;\n enricherIds: string[];\n transcendUrl: string;\n}\n\nexport async function skipPreflightJobs(\n this: LocalContext,\n { auth, transcendUrl, enricherIds }: SkipPreflightJobsCommandFlags,\n): Promise<void> {\n await skipPreflightJobsHelper({\n transcendUrl,\n auth,\n enricherIds,\n });\n}\n"],"mappings":"oLASA,eAAsBA,EAEpB,CAAE,KAAAC,EAAM,aAAAC,EAAc,YAAAC,CAAY,EACnB,CACf,MAAMH,EAAwB,CAC5B,aAAAE,EACA,KAAAD,EACA,YAAAE,CACF,CAAC,CACH","names":["skipPreflightJobs","auth","transcendUrl","enricherIds"]}
@@ -0,0 +1,2 @@
1
+ import{t}from"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function u({auth:e,transcendUrl:r,actions:a,statuses:n,requestIds:s,createdAtBefore:o,createdAtAfter:i,concurrency:c}){await t({transcendUrl:r,requestActions:a,auth:e,requestIds:s,statuses:n,concurrency:c,createdAtBefore:o,createdAtAfter:i})}export{u as markSilent};
2
+ //# sourceMappingURL=impl-JFD2JMP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/mark-silent/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { markSilentPrivacyRequests } from '../../../lib/requests';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\ninterface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: 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 concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"],"mappings":"+KAeA,eAAsBA,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,QAAAC,EACA,SAAAC,EACA,WAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,YAAAC,CACF,EACe,CACf,MAAMC,EAA0B,CAC9B,aAAAP,EACA,eAAgBC,EAChB,KAAAF,EACA,WAAAI,EACA,SAAAD,EACA,YAAAI,EACA,gBAAAF,EACA,eAAAC,CACF,CAAC,CACH","names":["markSilent","auth","transcendUrl","actions","statuses","requestIds","createdAtBefore","createdAtAfter","concurrency","markSilentPrivacyRequests"]}
@@ -0,0 +1,2 @@
1
+ import"./chunk-2LCGZ77N.js";import{c as s}from"./chunk-MA4JWWRO.js";import{U as r}from"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import{a as o}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import y from"colors";import{uniq as q}from"lodash-es";async function v({auth:n,transcendUrl:a,file:e,pageLimit:i,actions:m,sombraAuth:c,statuses:u,createdAtBefore:p,createdAtAfter:f,showTests:l}){let{requestsFormattedForCsv:t}=await r({transcendUrl:a,pageLimit:i,actions:m,statuses:u,auth:n,sombraAuth:c,createdAtBefore:p,createdAtAfter:f,isTest:l}),g=q(t.map(d=>Object.keys(d)).flat());s(e,t,g),o.info(y.green(`Successfully wrote ${t.length} requests to file "${e}"`))}export{v as _export};
2
+ //# sourceMappingURL=impl-JH4VBMNT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/export/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport colors from 'colors';\n\nimport { logger } from '../../../logger';\nimport { uniq } from 'lodash-es';\nimport { pullPrivacyRequests } from '../../../lib/requests';\nimport { writeCsv } from '../../../lib/cron';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\n\ninterface ExportCommandFlags {\n auth: string;\n sombraAuth?: string;\n actions?: RequestAction[];\n statuses?: RequestStatus[];\n transcendUrl: string;\n file: string;\n concurrency: number;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n showTests?: boolean;\n pageLimit: number;\n}\n\n// `export` is a reserved keyword, so we need to prefix it with an underscore\n// eslint-disable-next-line no-underscore-dangle\nexport async function _export(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n pageLimit,\n actions,\n sombraAuth,\n statuses,\n createdAtBefore,\n createdAtAfter,\n showTests,\n }: ExportCommandFlags,\n): Promise<void> {\n const { requestsFormattedForCsv } = await pullPrivacyRequests({\n transcendUrl,\n pageLimit,\n actions,\n statuses,\n auth,\n sombraAuth,\n createdAtBefore,\n createdAtAfter,\n isTest: showTests,\n });\n\n // Write to CSV\n const headers = uniq(\n requestsFormattedForCsv.map((d) => Object.keys(d)).flat(),\n );\n writeCsv(file, requestsFormattedForCsv, headers);\n logger.info(\n colors.green(\n `Successfully wrote ${requestsFormattedForCsv.length} requests to file \"${file}\"`,\n ),\n );\n}\n"],"mappings":"oQACA,OAAOA,MAAY,SAGnB,OAAS,QAAAC,MAAY,YAqBrB,eAAsBC,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,KAAAC,EACA,UAAAC,EACA,QAAAC,EACA,WAAAC,EACA,SAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,UAAAC,CACF,EACe,CACf,GAAM,CAAE,wBAAAC,CAAwB,EAAI,MAAMC,EAAoB,CAC5D,aAAAV,EACA,UAAAE,EACA,QAAAC,EACA,SAAAE,EACA,KAAAN,EACA,WAAAK,EACA,gBAAAE,EACA,eAAAC,EACA,OAAQC,CACV,CAAC,EAGKG,EAAUC,EACdH,EAAwB,IAAK,GAAM,OAAO,KAAK,CAAC,CAAC,EAAE,KAAK,CAC1D,EACAI,EAASZ,EAAMQ,EAAyBE,CAAO,EAC/CG,EAAO,KACLC,EAAO,MACL,sBAAsBN,EAAwB,MAAM,sBAAsBR,CAAI,GAChF,CACF,CACF","names":["colors","uniq","_export","auth","transcendUrl","file","pageLimit","actions","sombraAuth","statuses","createdAtBefore","createdAtAfter","showTests","requestsFormattedForCsv","pullPrivacyRequests","headers","uniq","writeCsv","logger","colors"]}
@@ -0,0 +1,6 @@
1
+ import{a}from"./chunk-65I2PF73.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import"./chunk-MK5T6DBK.js";import{a as n}from"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import x from"colors";import{writeFileSync as A}from"fs";import{TRANSCEND_SCOPES as E}from"@transcend-io/privacy-types";import{keyBy as K}from"lodash-es";var i=K(Object.entries(E).map(([t,o])=>({...o,name:t})),"title"),N=Object.keys(i);async function P({email:t,password:o,apiKeyTitle:p,file:c,scopes:m,deleteExistingApiKey:l,createNewApiKey:g,parentOrganizationId:f,transcendUrl:y}){let r=m.map(e=>e.trim()),s=r.filter(e=>!i[e]);s.length>0&&(n.error(x.red(`Failed to parse scopes:"${s.join(",")}".
2
+ Expected one of:
3
+ ${N.join(`
4
+ `)}`)),process.exit(1));let S=r.map(e=>i[e].name),{errors:d,apiKeys:C}=await a({transcendUrl:y,password:o,email:t,parentOrganizationId:f,deleteExistingApiKey:l,createNewApiKey:g,apiKeyTitle:p,scopes:S});A(c,`${JSON.stringify(C,null,2)}
5
+ `),d.length>0&&process.exit(1)}export{P as generateApiKeys};
6
+ //# sourceMappingURL=impl-LSP4V37Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/admin/generate-api-keys/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport colors from 'colors';\nimport { writeFileSync } from 'fs';\n\nimport { ScopeName, TRANSCEND_SCOPES } from '@transcend-io/privacy-types';\n\nimport { logger } from '../../../logger';\nimport { generateCrossAccountApiKeys } from '../../../lib/api-keys';\nimport { keyBy } from 'lodash-es';\n\nconst SCOPES_BY_TITLE = keyBy(\n Object.entries(TRANSCEND_SCOPES).map(([name, value]) => ({\n ...value,\n name,\n })),\n 'title',\n);\nconst SCOPE_TITLES = Object.keys(SCOPES_BY_TITLE);\n\n// Command flag interface\ninterface 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 // Validate scopes\n const splitScopes = scopes.map((x) => x.trim());\n const invalidScopes = splitScopes.filter(\n (scopeTitle) => !SCOPES_BY_TITLE[scopeTitle],\n );\n if (invalidScopes.length > 0) {\n logger.error(\n colors.red(\n `Failed to parse scopes:\"${invalidScopes.join(',')}\".\\n` +\n `Expected one of: \\n${SCOPE_TITLES.join('\\n')}`,\n ),\n );\n process.exit(1);\n }\n\n const scopeNames = splitScopes.map(\n (scopeTitle) => SCOPES_BY_TITLE[scopeTitle].name as ScopeName,\n );\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 writeFileSync(file, `${JSON.stringify(apiKeys, null, 2)}\\n`);\n if (errors.length > 0) {\n process.exit(1);\n }\n}\n"],"mappings":"mPACA,OAAOA,MAAY,SACnB,OAAS,iBAAAC,MAAqB,KAE9B,OAAoB,oBAAAC,MAAwB,8BAI5C,OAAS,SAAAC,MAAa,YAEtB,IAAMC,EAAkBD,EACtB,OAAO,QAAQE,CAAgB,EAAE,IAAI,CAAC,CAACC,EAAMC,CAAK,KAAO,CACvD,GAAGA,EACH,KAAAD,CACF,EAAE,EACF,OACF,EACME,EAAe,OAAO,KAAKJ,CAAe,EAgBhD,eAAsBK,EAEpB,CACE,MAAAC,EACA,SAAAC,EACA,YAAAC,EACA,KAAAC,EACA,OAAAC,EACA,qBAAAC,EACA,gBAAAC,EACA,qBAAAC,EACA,aAAAC,CACF,EACe,CAEf,IAAMC,EAAcL,EAAO,IAAKM,GAAMA,EAAE,KAAK,CAAC,EACxCC,EAAgBF,EAAY,OAC/BG,GAAe,CAAClB,EAAgBkB,CAAU,CAC7C,EACID,EAAc,OAAS,IACzBE,EAAO,MACLC,EAAO,IACL,2BAA2BH,EAAc,KAAK,GAAG,CAAC;AAAA;AAAA,EAC1Bb,EAAa,KAAK;AAAA,CAAI,CAAC,EACjD,CACF,EACA,QAAQ,KAAK,CAAC,GAGhB,IAAMiB,EAAaN,EAAY,IAC5BG,GAAelB,EAAgBkB,CAAU,EAAE,IAC9C,EAGM,CAAE,OAAAI,EAAQ,QAAAC,CAAQ,EAAI,MAAMC,EAA4B,CAC5D,aAAAV,EACA,SAAAP,EACA,MAAAD,EACA,qBAAAO,EACA,qBAAAF,EACA,gBAAAC,EACA,YAAAJ,EACA,OAAQa,CACV,CAAC,EAGDI,EAAchB,EAAM,GAAG,KAAK,UAAUc,EAAS,KAAM,CAAC,CAAC;AAAA,CAAI,EACvDD,EAAO,OAAS,GAClB,QAAQ,KAAK,CAAC,CAElB","names":["colors","writeFileSync","TRANSCEND_SCOPES","keyBy","SCOPES_BY_TITLE","TRANSCEND_SCOPES","name","value","SCOPE_TITLES","generateApiKeys","email","password","apiKeyTitle","file","scopes","deleteExistingApiKey","createNewApiKey","parentOrganizationId","transcendUrl","splitScopes","x","invalidScopes","scopeTitle","logger","colors","scopeNames","errors","apiKeys","generateCrossAccountApiKeys","writeFileSync"]}
@@ -0,0 +1,2 @@
1
+ import{F as t}from"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";import{RequestStatus as e}from"@transcend-io/privacy-types";async function f({auth:o,transcendUrl:a,folderPath:r,requestIds:n,statuses:s=[e.Approving,e.Downloadable],concurrency:i,createdAtBefore:l,createdAtAfter:d,approveAfterDownload:c}){await t({transcendUrl:a,auth:o,folderPath:r,requestIds:n,statuses:s,concurrency:i,createdAtBefore:l,createdAtAfter:d,approveAfterDownload:c})}export{f as downloadFiles};
2
+ //# sourceMappingURL=impl-MIJFNSLS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/download-files/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\nimport { downloadPrivacyRequestFiles } from '../../../lib/requests';\nimport { RequestStatus } from '@transcend-io/privacy-types';\n\ninterface DownloadFilesCommandFlags {\n auth: string;\n sombraAuth?: string;\n concurrency: number;\n requestIds?: string[];\n statuses?: RequestStatus[];\n folderPath: string;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n approveAfterDownload: boolean;\n transcendUrl: string;\n}\n\nexport async function downloadFiles(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n folderPath,\n requestIds,\n statuses = [RequestStatus.Approving, RequestStatus.Downloadable],\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n }: DownloadFilesCommandFlags,\n): Promise<void> {\n await downloadPrivacyRequestFiles({\n transcendUrl,\n auth,\n folderPath,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n approveAfterDownload,\n });\n}\n"],"mappings":"oLAEA,OAAS,iBAAAA,MAAqB,8BAe9B,eAAsBC,EAEpB,CACE,KAAAC,EACA,aAAAC,EACA,WAAAC,EACA,WAAAC,EACA,SAAAC,EAAW,CAACN,EAAc,UAAWA,EAAc,YAAY,EAC/D,YAAAO,EACA,gBAAAC,EACA,eAAAC,EACA,qBAAAC,CACF,EACe,CACf,MAAMC,EAA4B,CAChC,aAAAR,EACA,KAAAD,EACA,WAAAE,EACA,WAAAC,EACA,SAAAC,EACA,YAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,qBAAAC,CACF,CAAC,CACH","names":["RequestStatus","downloadFiles","auth","transcendUrl","folderPath","requestIds","statuses","concurrency","createdAtBefore","createdAtAfter","approveAfterDownload","downloadPrivacyRequestFiles"]}
@@ -0,0 +1,2 @@
1
+ import{I as e}from"./chunk-N6JZHL5U.js";import"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function m({auth:t,actions:r,origins:o,silentModeBefore:i,createdAtBefore:n,createdAtAfter:a,transcendUrl:s,concurrency:c}){await e({transcendUrl:s,requestActions:r,auth:t,requestOrigins:o,concurrency:c,silentModeBefore:i,createdAtBefore:n,createdAtAfter:a})}export{m as approve};
2
+ //# sourceMappingURL=impl-NL32KFH4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/request/approve/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\n\nimport { RequestAction, RequestOrigin } from '@transcend-io/privacy-types';\nimport { approvePrivacyRequests } from '../../../lib/requests';\n\ninterface ApproveCommandFlags {\n auth: string;\n actions: RequestAction[];\n origins?: RequestOrigin[];\n silentModeBefore?: Date;\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function approve(\n this: LocalContext,\n {\n auth,\n actions,\n origins,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n transcendUrl,\n concurrency,\n }: ApproveCommandFlags,\n): Promise<void> {\n await approvePrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestOrigins: origins,\n concurrency,\n silentModeBefore,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"],"mappings":"oLAgBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,QAAAC,EACA,QAAAC,EACA,iBAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,aAAAC,EACA,YAAAC,CACF,EACe,CACf,MAAMC,EAAuB,CAC3B,aAAAF,EACA,eAAgBL,EAChB,KAAAD,EACA,eAAgBE,EAChB,YAAAK,EACA,iBAAAJ,EACA,gBAAAC,EACA,eAAAC,CACF,CAAC,CACH","names":["approve","auth","actions","origins","silentModeBefore","createdAtBefore","createdAtAfter","transcendUrl","concurrency","approvePrivacyRequests"]}
@@ -0,0 +1,2 @@
1
+ import"./chunk-2LCGZ77N.js";import{c as i}from"./chunk-MA4JWWRO.js";import{j as s}from"./chunk-26T4RUOI.js";import"./chunk-2V6ABZRI.js";import"./chunk-N6JZHL5U.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{qe as o}from"./chunk-MK5T6DBK.js";import"./chunk-43JWXG77.js";import"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import"./chunk-ARVEJERC.js";async function h({auth:a,partition:m,sombraAuth:c,file:p,transcendUrl:f,timestampBefore:e,timestampAfter:r,identifiers:n=[],concurrency:l}){let g=await o(f,a,c),u=await s(g,{partition:m,filterBy:{...e?{timestampBefore:e.toISOString()}:{},...r?{timestampAfter:r.toISOString()}:{},...n.length>0?{identifiers:n}:{}},limit:l});i(p,u.map(t=>({...t,purposes:JSON.stringify(t.purposes),...t.purposes})))}export{h as pullConsentPreferences};
2
+ //# sourceMappingURL=impl-NLCPSIYZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/consent/pull-consent-preferences/impl.ts"],"sourcesContent":["import type { LocalContext } from '../../../context';\n\nimport { fetchConsentPreferences } from '../../../lib/consent-manager';\nimport { writeCsv } from '../../../lib/cron';\nimport { createSombraGotInstance } from '../../../lib/graphql';\n\ninterface PullConsentPreferencesCommandFlags {\n auth: string;\n partition: string;\n sombraAuth?: string;\n file: string;\n transcendUrl: string;\n timestampBefore?: Date;\n timestampAfter?: Date;\n identifiers?: string[];\n concurrency: number;\n}\n\nexport async function pullConsentPreferences(\n this: LocalContext,\n {\n auth,\n partition,\n sombraAuth,\n file,\n transcendUrl,\n timestampBefore,\n timestampAfter,\n identifiers = [],\n concurrency,\n }: PullConsentPreferencesCommandFlags,\n): Promise<void> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n // Fetch preferences\n const preferences = await fetchConsentPreferences(sombra, {\n partition,\n filterBy: {\n ...(timestampBefore\n ? { timestampBefore: timestampBefore.toISOString() }\n : {}),\n ...(timestampAfter\n ? { timestampAfter: timestampAfter.toISOString() }\n : {}),\n ...(identifiers.length > 0 ? { identifiers } : {}),\n },\n limit: concurrency,\n });\n\n // Write to disk\n writeCsv(\n file,\n preferences.map((pref) => ({\n ...pref,\n purposes: JSON.stringify(pref.purposes),\n ...pref.purposes,\n })),\n );\n}\n"],"mappings":"qXAkBA,eAAsBA,EAEpB,CACE,KAAAC,EACA,UAAAC,EACA,WAAAC,EACA,KAAAC,EACA,aAAAC,EACA,gBAAAC,EACA,eAAAC,EACA,YAAAC,EAAc,CAAC,EACf,YAAAC,CACF,EACe,CAEf,IAAMC,EAAS,MAAMC,EAAwBN,EAAcJ,EAAME,CAAU,EAGrES,EAAc,MAAMC,EAAwBH,EAAQ,CACxD,UAAAR,EACA,SAAU,CACR,GAAII,EACA,CAAE,gBAAiBA,EAAgB,YAAY,CAAE,EACjD,CAAC,EACL,GAAIC,EACA,CAAE,eAAgBA,EAAe,YAAY,CAAE,EAC/C,CAAC,EACL,GAAIC,EAAY,OAAS,EAAI,CAAE,YAAAA,CAAY,EAAI,CAAC,CAClD,EACA,MAAOC,CACT,CAAC,EAGDK,EACEV,EACAQ,EAAY,IAAKG,IAAU,CACzB,GAAGA,EACH,SAAU,KAAK,UAAUA,EAAK,QAAQ,EACtC,GAAGA,EAAK,QACV,EAAE,CACJ,CACF","names":["pullConsentPreferences","auth","partition","sombraAuth","file","transcendUrl","timestampBefore","timestampAfter","identifiers","concurrency","sombra","createSombraGotInstance","preferences","fetchConsentPreferences","writeCsv","pref"]}
@@ -0,0 +1,6 @@
1
+ import{e as l}from"./chunk-OEB7WG3G.js";import{h as R,i as b}from"./chunk-SRLEEKKQ.js";import{b as N}from"./chunk-65I2PF73.js";import"./chunk-LAYHULHH.js";import"./chunk-347UQP43.js";import{a as P,be as m,pe as u}from"./chunk-MK5T6DBK.js";import{a as o}from"./chunk-43JWXG77.js";import{c as f}from"./chunk-L5ULN3IT.js";import"./chunk-EZHASXA5.js";import{d as E}from"./chunk-ARVEJERC.js";import n from"colors";import{join as k}from"path";import D from"fs";async function M({auth:x,resources:g=R,file:t,transcendUrl:p,dataSiloIds:d=[],integrationNames:T=[],trackerStatuses:y=b,pageSize:S,skipDatapoints:h,skipSubDatapoints:$,includeGuessedCategories:A,debug:a}){let i=await N(x),C=g.includes("all")?Object.values(E):g;if(typeof i=="string"){try{let r=u(p,i),e=await m(r,{dataSiloIds:d,integrationNames:T,resources:C,pageSize:S,debug:a,skipDatapoints:h,skipSubDatapoints:$,includeGuessedCategories:A,trackerStatuses:y});o.info(n.magenta(`Writing configuration to file "${t}"...`)),l(t,e)}catch(r){o.error(n.red(`An error occurred syncing the schema: ${a?r.stack:r.message}`)),process.exit(1)}o.info(n.green(`Successfully synced yaml file to disk at ${t}! View at ${f}`))}else{if(!D.lstatSync(t).isDirectory())throw new Error("File is expected to be a folder when passing in a list of API keys to pull from. e.g. --file=./working/");let r=[];await P(i,async(e,L)=>{let s=`[${L+1}/${i.length}][${e.organizationName}] `;o.info(n.magenta(`~~~
2
+
3
+ ${s}Attempting to pull configuration...
4
+
5
+ ~~~`));let _=u(p,e.apiKey);try{let c=await m(_,{dataSiloIds:d,integrationNames:T,resources:C,pageSize:S,debug:a,skipDatapoints:h,skipSubDatapoints:$,includeGuessedCategories:A,trackerStatuses:y}),w=k(t,`${e.organizationName}.yml`);o.info(n.magenta(`Writing configuration to file "${w}"...`)),l(w,c),o.info(n.green(`${s}Successfully pulled configuration!`))}catch(c){o.error(n.red(`${s}Failed to sync configuration. - ${c.message}`)),r.push(e.organizationName)}}),r.length>0&&(o.info(n.red(`Sync encountered errors for "${r.join(",")}". View output above for more information, or check out ${f}`)),process.exit(1))}}export{M as pull};
6
+ //# sourceMappingURL=impl-NXRQU2U5.js.map