@transcend-io/cli 7.0.3 → 7.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/dist/bin/bash-complete.cjs +1 -1
  2. package/dist/bin/cli.cjs +1 -1
  3. package/dist/bin/deprecated-command.cjs +2 -2
  4. package/dist/{chunk-T66BMKXU.cjs → chunk-3ZKZCSGD.cjs} +157 -140
  5. package/dist/chunk-3ZKZCSGD.cjs.map +1 -0
  6. package/dist/{chunk-LD6RM4JJ.cjs → chunk-6DWFLWWT.cjs} +2 -2
  7. package/dist/{chunk-LD6RM4JJ.cjs.map → chunk-6DWFLWWT.cjs.map} +1 -1
  8. package/dist/{chunk-6VV64JQD.cjs → chunk-6FGYCQAQ.cjs} +2 -2
  9. package/dist/{chunk-6VV64JQD.cjs.map → chunk-6FGYCQAQ.cjs.map} +1 -1
  10. package/dist/{chunk-3L4DLV6F.cjs → chunk-BF5T3SGE.cjs} +2 -2
  11. package/dist/{chunk-3L4DLV6F.cjs.map → chunk-BF5T3SGE.cjs.map} +1 -1
  12. package/dist/{chunk-DM7WURT2.cjs → chunk-E3CF3RKX.cjs} +2 -2
  13. package/dist/{chunk-DM7WURT2.cjs.map → chunk-E3CF3RKX.cjs.map} +1 -1
  14. package/dist/{chunk-VBCQ7F34.cjs → chunk-EVZLUL56.cjs} +4 -4
  15. package/dist/{chunk-VBCQ7F34.cjs.map → chunk-EVZLUL56.cjs.map} +1 -1
  16. package/dist/{chunk-GF4AD4KW.cjs → chunk-FPXWBUHS.cjs} +2 -2
  17. package/dist/{chunk-GF4AD4KW.cjs.map → chunk-FPXWBUHS.cjs.map} +1 -1
  18. package/dist/{chunk-A57ZB6XS.cjs → chunk-G2T7YVBG.cjs} +19 -19
  19. package/dist/{chunk-A57ZB6XS.cjs.map → chunk-G2T7YVBG.cjs.map} +1 -1
  20. package/dist/{chunk-MYCE3NIE.cjs → chunk-IG65EYJY.cjs} +2 -2
  21. package/dist/{chunk-MYCE3NIE.cjs.map → chunk-IG65EYJY.cjs.map} +1 -1
  22. package/dist/{chunk-WLVJQVRU.cjs → chunk-L7YT5ETS.cjs} +2 -2
  23. package/dist/{chunk-WLVJQVRU.cjs.map → chunk-L7YT5ETS.cjs.map} +1 -1
  24. package/dist/{chunk-S27CXPPN.cjs → chunk-R4IKDXM5.cjs} +2 -2
  25. package/dist/{chunk-S27CXPPN.cjs.map → chunk-R4IKDXM5.cjs.map} +1 -1
  26. package/dist/{chunk-JQ7LX2L3.cjs → chunk-TS5EYI4O.cjs} +3 -3
  27. package/dist/{chunk-JQ7LX2L3.cjs.map → chunk-TS5EYI4O.cjs.map} +1 -1
  28. package/dist/{chunk-DFOLIGJP.cjs → chunk-WIXQSFS6.cjs} +2 -2
  29. package/dist/{chunk-DFOLIGJP.cjs.map → chunk-WIXQSFS6.cjs.map} +1 -1
  30. package/dist/chunk-Y4BWTFTX.cjs +15 -0
  31. package/dist/chunk-Y4BWTFTX.cjs.map +1 -0
  32. package/dist/{chunk-2DLJ3BDD.cjs → chunk-YA5UZ3YM.cjs} +2 -2
  33. package/dist/{chunk-2DLJ3BDD.cjs.map → chunk-YA5UZ3YM.cjs.map} +1 -1
  34. package/dist/impl-2G6FOZLU.cjs +2 -0
  35. package/dist/{impl-IVH7T3MG.cjs.map → impl-2G6FOZLU.cjs.map} +1 -1
  36. package/dist/{impl-CTN3RH3H.cjs → impl-4EDFESYC.cjs} +2 -2
  37. package/dist/{impl-CTN3RH3H.cjs.map → impl-4EDFESYC.cjs.map} +1 -1
  38. package/dist/{impl-XSP2L4A3.cjs → impl-5FO2QEHJ.cjs} +2 -2
  39. package/dist/{impl-XSP2L4A3.cjs.map → impl-5FO2QEHJ.cjs.map} +1 -1
  40. package/dist/{impl-LEPYMCRL.cjs → impl-6B7JDOM5.cjs} +2 -2
  41. package/dist/{impl-LEPYMCRL.cjs.map → impl-6B7JDOM5.cjs.map} +1 -1
  42. package/dist/impl-AUOR6D3Q.cjs +2 -0
  43. package/dist/{impl-5R7QQLXX.cjs.map → impl-AUOR6D3Q.cjs.map} +1 -1
  44. package/dist/{impl-45GI5GBX.cjs → impl-B5HQXUMH.cjs} +2 -2
  45. package/dist/{impl-45GI5GBX.cjs.map → impl-B5HQXUMH.cjs.map} +1 -1
  46. package/dist/{impl-EJWCZU32.cjs → impl-BNFADMTO.cjs} +2 -2
  47. package/dist/{impl-EJWCZU32.cjs.map → impl-BNFADMTO.cjs.map} +1 -1
  48. package/dist/{impl-EHZWLIEN.cjs → impl-BPWMOF4U.cjs} +2 -2
  49. package/dist/{impl-EHZWLIEN.cjs.map → impl-BPWMOF4U.cjs.map} +1 -1
  50. package/dist/{impl-LGMUBZ3P.cjs → impl-CNCC36M6.cjs} +5 -5
  51. package/dist/{impl-LGMUBZ3P.cjs.map → impl-CNCC36M6.cjs.map} +1 -1
  52. package/dist/{impl-S4J44FBI.cjs → impl-DBDL4Z23.cjs} +2 -2
  53. package/dist/{impl-S4J44FBI.cjs.map → impl-DBDL4Z23.cjs.map} +1 -1
  54. package/dist/{impl-I7IZGNDD.cjs → impl-FG47LALL.cjs} +2 -2
  55. package/dist/{impl-I7IZGNDD.cjs.map → impl-FG47LALL.cjs.map} +1 -1
  56. package/dist/{impl-BJNS6ODX.cjs → impl-GNB7TDFU.cjs} +2 -2
  57. package/dist/{impl-BJNS6ODX.cjs.map → impl-GNB7TDFU.cjs.map} +1 -1
  58. package/dist/{impl-O72S3ARJ.cjs → impl-HB3R7YDP.cjs} +2 -2
  59. package/dist/{impl-O72S3ARJ.cjs.map → impl-HB3R7YDP.cjs.map} +1 -1
  60. package/dist/{impl-4CKKKZSW.cjs → impl-ICI7EQKE.cjs} +2 -2
  61. package/dist/{impl-4CKKKZSW.cjs.map → impl-ICI7EQKE.cjs.map} +1 -1
  62. package/dist/impl-KOMGU55G.cjs +2 -0
  63. package/dist/{impl-PBCOYUN3.cjs.map → impl-KOMGU55G.cjs.map} +1 -1
  64. package/dist/{impl-U7KRGFYL.cjs → impl-KP27234L.cjs} +2 -2
  65. package/dist/{impl-U7KRGFYL.cjs.map → impl-KP27234L.cjs.map} +1 -1
  66. package/dist/{impl-4JIOV3X6.cjs → impl-KZ2L66Q3.cjs} +2 -2
  67. package/dist/{impl-4JIOV3X6.cjs.map → impl-KZ2L66Q3.cjs.map} +1 -1
  68. package/dist/{impl-OIRM2C3D.cjs → impl-L3M67IGI.cjs} +4 -4
  69. package/dist/{impl-OIRM2C3D.cjs.map → impl-L3M67IGI.cjs.map} +1 -1
  70. package/dist/{impl-P64XABL2.cjs → impl-LTOV5CHF.cjs} +2 -2
  71. package/dist/{impl-P64XABL2.cjs.map → impl-LTOV5CHF.cjs.map} +1 -1
  72. package/dist/{impl-OOVHRMYF.cjs → impl-MO6AOGQM.cjs} +2 -2
  73. package/dist/{impl-OOVHRMYF.cjs.map → impl-MO6AOGQM.cjs.map} +1 -1
  74. package/dist/{impl-KHC6VQQ3.cjs → impl-MPGDZ2M2.cjs} +6 -6
  75. package/dist/{impl-KHC6VQQ3.cjs.map → impl-MPGDZ2M2.cjs.map} +1 -1
  76. package/dist/{impl-HBRGW4FK.cjs → impl-N54C7NPT.cjs} +2 -2
  77. package/dist/{impl-HBRGW4FK.cjs.map → impl-N54C7NPT.cjs.map} +1 -1
  78. package/dist/{impl-YST7YAME.cjs → impl-N6ML5K5S.cjs} +2 -2
  79. package/dist/{impl-YST7YAME.cjs.map → impl-N6ML5K5S.cjs.map} +1 -1
  80. package/dist/{impl-TSBZWYSU.cjs → impl-NKLZ5RG4.cjs} +2 -2
  81. package/dist/{impl-TSBZWYSU.cjs.map → impl-NKLZ5RG4.cjs.map} +1 -1
  82. package/dist/{impl-RBCLAU3L.cjs → impl-NNOWJ4Q4.cjs} +3 -3
  83. package/dist/{impl-RBCLAU3L.cjs.map → impl-NNOWJ4Q4.cjs.map} +1 -1
  84. package/dist/{impl-DNQUVLSW.cjs → impl-OLEEHZUA.cjs} +3 -3
  85. package/dist/{impl-DNQUVLSW.cjs.map → impl-OLEEHZUA.cjs.map} +1 -1
  86. package/dist/{impl-2WTVQZVH.cjs → impl-Q6EQYFKN.cjs} +2 -2
  87. package/dist/{impl-2WTVQZVH.cjs.map → impl-Q6EQYFKN.cjs.map} +1 -1
  88. package/dist/{impl-U5LM6TOR.cjs → impl-QHTG36G3.cjs} +2 -2
  89. package/dist/{impl-U5LM6TOR.cjs.map → impl-QHTG36G3.cjs.map} +1 -1
  90. package/dist/{impl-KCK7ESJ2.cjs → impl-QITUCVEV.cjs} +2 -2
  91. package/dist/{impl-KCK7ESJ2.cjs.map → impl-QITUCVEV.cjs.map} +1 -1
  92. package/dist/{impl-52VR3GDJ.cjs → impl-R3KCARSP.cjs} +2 -2
  93. package/dist/{impl-52VR3GDJ.cjs.map → impl-R3KCARSP.cjs.map} +1 -1
  94. package/dist/{impl-2FABITOO.cjs → impl-RSHVCDLE.cjs} +2 -2
  95. package/dist/{impl-2FABITOO.cjs.map → impl-RSHVCDLE.cjs.map} +1 -1
  96. package/dist/impl-SNLQCZOR.cjs +2 -0
  97. package/dist/impl-SNLQCZOR.cjs.map +1 -0
  98. package/dist/{impl-LAY6PG5S.cjs → impl-TPVA6DLJ.cjs} +2 -2
  99. package/dist/{impl-LAY6PG5S.cjs.map → impl-TPVA6DLJ.cjs.map} +1 -1
  100. package/dist/{impl-OUBX3UFM.cjs → impl-TVNBHOR4.cjs} +2 -2
  101. package/dist/{impl-OUBX3UFM.cjs.map → impl-TVNBHOR4.cjs.map} +1 -1
  102. package/dist/{impl-7TE6HP4S.cjs → impl-TWLWQSZG.cjs} +2 -2
  103. package/dist/{impl-7TE6HP4S.cjs.map → impl-TWLWQSZG.cjs.map} +1 -1
  104. package/dist/impl-UKOAB6ED.cjs +2 -0
  105. package/dist/{impl-TIOK6UX4.cjs.map → impl-UKOAB6ED.cjs.map} +1 -1
  106. package/dist/{impl-CEZKH3XW.cjs → impl-ZKBMWGMK.cjs} +2 -2
  107. package/dist/{impl-CEZKH3XW.cjs.map → impl-ZKBMWGMK.cjs.map} +1 -1
  108. package/dist/{impl-4GWAH2JR.cjs → impl-ZTWLYZZO.cjs} +2 -2
  109. package/dist/{impl-4GWAH2JR.cjs.map → impl-ZTWLYZZO.cjs.map} +1 -1
  110. package/dist/index.cjs +3 -3
  111. package/dist/index.cjs.map +1 -1
  112. package/dist/index.d.cts +30 -6
  113. package/package.json +1 -1
  114. package/dist/chunk-T66BMKXU.cjs.map +0 -1
  115. package/dist/chunk-UM5F6R4I.cjs +0 -15
  116. package/dist/chunk-UM5F6R4I.cjs.map +0 -1
  117. package/dist/impl-5R7QQLXX.cjs +0 -2
  118. package/dist/impl-6WSGLEVR.cjs +0 -2
  119. package/dist/impl-6WSGLEVR.cjs.map +0 -1
  120. package/dist/impl-IVH7T3MG.cjs +0 -2
  121. package/dist/impl-PBCOYUN3.cjs +0 -2
  122. package/dist/impl-TIOK6UX4.cjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-4CKKKZSW.cjs","../src/commands/consent/update-consent-manager/impl.ts"],"names":["updateConsentManager","auth","bundleTypes","ConsentBundleType","deploy","transcendUrl","doneInputValidation","apiKeyOrList","validateTranscendAuth","updateConsentManagerVersionToLatest","logger","colors","mapSeries","apiKey"],"mappings":"AAAA,iOAAwC,wDAAoC,gCAA6B,gCAA6B,wDAAyC,gCAA6B,gCAA6B,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gFCC/X,2DACe,MAelC,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CAAc,CAACC,+BAAAA,CAAkB,UAAA,CAAYA,+BAAAA,CAAkB,IAAI,CAAA,CACnE,MAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAMC,CAAAA,CAAe,MAAMC,iCAAAA,CAA0B,CAAA,CAGjD,OAAOD,CAAAA,EAAiB,QAAA,CAAA,CAE1B,MAAME,iCAAAA,CACJ,MAAA,CAAAL,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAME,CAAAA,CACN,WAAA,CAAAL,CACF,CAAC,CAAA,CACDQ,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,KAAA,CAAM,uCAAuC,CAAC,CAAA,CAAA,CAAA,CAEjE,MAAMC,iCAAAA,CAAUL,CAAc,MAAOM,CAAAA,EAAW,CAC9CH,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,2CAAA,EAA8CE,CAAAA,CAAO,gBAAgB,CAAA,IAAA,CACvE,CACF,CAAA,CAEA,MAAMJ,iCAAAA,CACJ,MAAA,CAAAL,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAMQ,CAAAA,CAAO,MAAA,CACb,WAAA,CAAAX,CACF,CAAC,CAAA,CAEDQ,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,uDAAA,EAA0DE,CAAAA,CAAO,gBAAgB,CAAA,EAAA,CACnF,CACF,CACF,CAAC,CAAA,CACDH,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,KAAA,CAAM,wCAAwC,CAAC,CAAA,CAEtE,CAAA,iCAAA","file":"/home/runner/work/cli/cli/dist/impl-4CKKKZSW.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport colors from 'colors';\nimport { ConsentBundleType } from '@transcend-io/privacy-types';\nimport { mapSeries } from '../../../lib/bluebird-replace';\n\nimport { logger } from '../../../logger';\nimport { updateConsentManagerVersionToLatest } from '../../../lib/consent-manager';\nimport { validateTranscendAuth } from '../../../lib/api-keys';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UpdateConsentManagerCommandFlags {\n auth: string;\n bundleTypes: ConsentBundleType[];\n deploy: boolean;\n transcendUrl: string;\n}\n\nexport async function updateConsentManager(\n this: LocalContext,\n {\n auth,\n bundleTypes = [ConsentBundleType.Production, ConsentBundleType.Test],\n deploy,\n transcendUrl,\n }: UpdateConsentManagerCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Handle single update\n if (typeof apiKeyOrList === 'string') {\n // Update consent manager\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKeyOrList,\n bundleTypes,\n });\n logger.info(colors.green('Successfully updated Consent Manager!'));\n } else {\n await mapSeries(apiKeyOrList, async (apiKey) => {\n logger.info(\n colors.magenta(\n `Updating Consent Manager for organization \"${apiKey.organizationName}\"...`,\n ),\n );\n\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKey.apiKey,\n bundleTypes,\n });\n\n logger.info(\n colors.green(\n `Successfully updated Consent Manager for organization \"${apiKey.organizationName}\"!`,\n ),\n );\n });\n logger.info(colors.green('Successfully updated Consent Managers!'));\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-ICI7EQKE.cjs","../src/commands/consent/update-consent-manager/impl.ts"],"names":["updateConsentManager","auth","bundleTypes","ConsentBundleType","deploy","transcendUrl","doneInputValidation","apiKeyOrList","validateTranscendAuth","updateConsentManagerVersionToLatest","logger","colors","mapSeries","apiKey"],"mappings":"AAAA,iOAAwC,wDAAoC,gCAA6B,gCAA6B,wDAAyC,gCAA6B,gCAA6B,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gFCC/X,2DACe,MAelC,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CAAc,CAACC,+BAAAA,CAAkB,UAAA,CAAYA,+BAAAA,CAAkB,IAAI,CAAA,CACnE,MAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAMC,CAAAA,CAAe,MAAMC,iCAAAA,CAA0B,CAAA,CAGjD,OAAOD,CAAAA,EAAiB,QAAA,CAAA,CAE1B,MAAME,iCAAAA,CACJ,MAAA,CAAAL,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAME,CAAAA,CACN,WAAA,CAAAL,CACF,CAAC,CAAA,CACDQ,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,KAAA,CAAM,uCAAuC,CAAC,CAAA,CAAA,CAAA,CAEjE,MAAMC,iCAAAA,CAAUL,CAAc,MAAOM,CAAAA,EAAW,CAC9CH,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,2CAAA,EAA8CE,CAAAA,CAAO,gBAAgB,CAAA,IAAA,CACvE,CACF,CAAA,CAEA,MAAMJ,iCAAAA,CACJ,MAAA,CAAAL,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAMQ,CAAAA,CAAO,MAAA,CACb,WAAA,CAAAX,CACF,CAAC,CAAA,CAEDQ,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,uDAAA,EAA0DE,CAAAA,CAAO,gBAAgB,CAAA,EAAA,CACnF,CACF,CACF,CAAC,CAAA,CACDH,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,KAAA,CAAM,wCAAwC,CAAC,CAAA,CAEtE,CAAA,iCAAA","file":"/home/runner/work/cli/cli/dist/impl-ICI7EQKE.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport colors from 'colors';\nimport { ConsentBundleType } from '@transcend-io/privacy-types';\nimport { mapSeries } from '../../../lib/bluebird-replace';\n\nimport { logger } from '../../../logger';\nimport { updateConsentManagerVersionToLatest } from '../../../lib/consent-manager';\nimport { validateTranscendAuth } from '../../../lib/api-keys';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UpdateConsentManagerCommandFlags {\n auth: string;\n bundleTypes: ConsentBundleType[];\n deploy: boolean;\n transcendUrl: string;\n}\n\nexport async function updateConsentManager(\n this: LocalContext,\n {\n auth,\n bundleTypes = [ConsentBundleType.Production, ConsentBundleType.Test],\n deploy,\n transcendUrl,\n }: UpdateConsentManagerCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Parse authentication as API key or path to list of API keys\n const apiKeyOrList = await validateTranscendAuth(auth);\n\n // Handle single update\n if (typeof apiKeyOrList === 'string') {\n // Update consent manager\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKeyOrList,\n bundleTypes,\n });\n logger.info(colors.green('Successfully updated Consent Manager!'));\n } else {\n await mapSeries(apiKeyOrList, async (apiKey) => {\n logger.info(\n colors.magenta(\n `Updating Consent Manager for organization \"${apiKey.organizationName}\"...`,\n ),\n );\n\n await updateConsentManagerVersionToLatest({\n deploy,\n transcendUrl,\n auth: apiKey.apiKey,\n bundleTypes,\n });\n\n logger.info(\n colors.green(\n `Successfully updated Consent Manager for organization \"${apiKey.organizationName}\"!`,\n ),\n );\n });\n logger.info(colors.green('Successfully updated Consent Managers!'));\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk6DWFLWWTcjs = require('./chunk-6DWFLWWT.cjs');var _chunkWIXQSFS6cjs = require('./chunk-WIXQSFS6.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-3ZKZCSGD.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-E3CF3RKX.cjs');require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');async function g({base64EncryptionKey:t,base64SigningKey:s,partition:i,file:a,consentUrl:c,concurrency:p}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let m=_chunkWIXQSFS6cjs.q.call(void 0, a,_chunk6DWFLWWTcjs.b);await _chunk6DWFLWWTcjs.f.call(void 0, {base64EncryptionKey:t,base64SigningKey:s,preferences:m,partition:i,concurrency:p,transcendUrl:c})}exports.uploadConsentPreferences = g;
2
+ //# sourceMappingURL=impl-KOMGU55G.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-PBCOYUN3.cjs","../src/commands/consent/upload-consent-preferences/impl.ts"],"names":["uploadConsentPreferences","base64EncryptionKey","base64SigningKey","partition","file","consentUrl","concurrency","doneInputValidation","preferences","readCsv","ConsentPreferenceUpload","uploadConsents"],"mappings":"AAAA,iIAA+C,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCgBlR,SAAsBA,CAAAA,CAEpB,CACE,mBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAMC,CAAAA,CAAcC,iCAAAA,CAAQL,CAAMM,mBAAuB,CAAA,CAGzD,MAAMC,iCAAAA,CACJ,mBAAA,CAAAV,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,WAAA,CAAAM,CAAAA,CACA,SAAA,CAAAL,CAAAA,CACA,WAAA,CAAAG,CAAAA,CACA,YAAA,CAAcD,CAChB,CAAC,CACH,CAAA,qCAAA","file":"/home/runner/work/cli/cli/dist/impl-PBCOYUN3.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\n\nimport { uploadConsents } from '../../../lib/consent-manager/uploadConsents';\nimport { ConsentPreferenceUpload } from '../../../lib/consent-manager/types';\nimport { readCsv } from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UploadConsentPreferencesCommandFlags {\n base64EncryptionKey: string;\n base64SigningKey: string;\n partition: string;\n file: string;\n consentUrl: string;\n concurrency: number;\n}\n\nexport async function uploadConsentPreferences(\n this: LocalContext,\n {\n base64EncryptionKey,\n base64SigningKey,\n partition,\n file,\n consentUrl,\n concurrency,\n }: UploadConsentPreferencesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Load in preferences from csv\n const preferences = readCsv(file, ConsentPreferenceUpload);\n\n // Upload cookies\n await uploadConsents({\n base64EncryptionKey,\n base64SigningKey,\n preferences,\n partition,\n concurrency,\n transcendUrl: consentUrl,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-KOMGU55G.cjs","../src/commands/consent/upload-consent-preferences/impl.ts"],"names":["uploadConsentPreferences","base64EncryptionKey","base64SigningKey","partition","file","consentUrl","concurrency","doneInputValidation","preferences","readCsv","ConsentPreferenceUpload","uploadConsents"],"mappings":"AAAA,iIAA+C,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCgBlR,SAAsBA,CAAAA,CAEpB,CACE,mBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAMC,CAAAA,CAAcC,iCAAAA,CAAQL,CAAMM,mBAAuB,CAAA,CAGzD,MAAMC,iCAAAA,CACJ,mBAAA,CAAAV,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,WAAA,CAAAM,CAAAA,CACA,SAAA,CAAAL,CAAAA,CACA,WAAA,CAAAG,CAAAA,CACA,YAAA,CAAcD,CAChB,CAAC,CACH,CAAA,qCAAA","file":"/home/runner/work/cli/cli/dist/impl-KOMGU55G.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\n\nimport { uploadConsents } from '../../../lib/consent-manager/uploadConsents';\nimport { ConsentPreferenceUpload } from '../../../lib/consent-manager/types';\nimport { readCsv } from '../../../lib/requests';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UploadConsentPreferencesCommandFlags {\n base64EncryptionKey: string;\n base64SigningKey: string;\n partition: string;\n file: string;\n consentUrl: string;\n concurrency: number;\n}\n\nexport async function uploadConsentPreferences(\n this: LocalContext,\n {\n base64EncryptionKey,\n base64SigningKey,\n partition,\n file,\n consentUrl,\n concurrency,\n }: UploadConsentPreferencesCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n // Load in preferences from csv\n const preferences = readCsv(file, ConsentPreferenceUpload);\n\n // Upload cookies\n await uploadConsents({\n base64EncryptionKey,\n base64SigningKey,\n preferences,\n partition,\n concurrency,\n transcendUrl: consentUrl,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJQ7LX2L3cjs = require('./chunk-JQ7LX2L3.cjs');require('./chunk-LD6RM4JJ.cjs');require('./chunk-DFOLIGJP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZD2HOHJI.cjs');require('./chunk-SAEKBZGF.cjs');require('./chunk-T66BMKXU.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-DM7WURT2.cjs');require('./chunk-UM5F6R4I.cjs');require('./chunk-BY7W4UQF.cjs');async function m({auth:a,trackerStatus:r,file:s,classifyService:e,transcendUrl:n}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkJQ7LX2L3cjs.b.call(void 0, {auth:a,trackerStatus:r,file:s,classifyService:e,transcendUrl:n})}exports.uploadDataFlowsFromCsv = m;
2
- //# sourceMappingURL=impl-U7KRGFYL.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkTS5EYI4Ocjs = require('./chunk-TS5EYI4O.cjs');require('./chunk-6DWFLWWT.cjs');require('./chunk-WIXQSFS6.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZD2HOHJI.cjs');require('./chunk-SAEKBZGF.cjs');require('./chunk-3ZKZCSGD.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-E3CF3RKX.cjs');require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');async function m({auth:a,trackerStatus:r,file:s,classifyService:e,transcendUrl:n}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkTS5EYI4Ocjs.b.call(void 0, {auth:a,trackerStatus:r,file:s,classifyService:e,transcendUrl:n})}exports.uploadDataFlowsFromCsv = m;
2
+ //# sourceMappingURL=impl-KP27234L.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-U7KRGFYL.cjs","../src/commands/consent/upload-data-flows-from-csv/impl.ts"],"names":["uploadDataFlowsFromCsv","auth","trackerStatus","file","classifyService","transcendUrl","doneInputValidation"],"mappings":"AAAA,iIAAwC,gCAA6B,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCatV,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMN,iCAAAA,CACJ,IAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAC,CACH,CAAA,mCAAA","file":"/home/runner/work/cli/cli/dist/impl-U7KRGFYL.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { uploadDataFlowsFromCsv as uploadDataFlowsFromCsvHelper } from '../../../lib/consent-manager';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UploadDataFlowsFromCsvCommandFlags {\n auth: string;\n trackerStatus: ConsentTrackerStatus;\n file: string;\n classifyService: boolean;\n transcendUrl: string;\n}\n\nexport async function uploadDataFlowsFromCsv(\n this: LocalContext,\n {\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n }: UploadDataFlowsFromCsvCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await uploadDataFlowsFromCsvHelper({\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-KP27234L.cjs","../src/commands/consent/upload-data-flows-from-csv/impl.ts"],"names":["uploadDataFlowsFromCsv","auth","trackerStatus","file","classifyService","transcendUrl","doneInputValidation"],"mappings":"AAAA,iIAAwC,gCAA6B,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCatV,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMN,iCAAAA,CACJ,IAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAC,CACH,CAAA,mCAAA","file":"/home/runner/work/cli/cli/dist/impl-KP27234L.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { uploadDataFlowsFromCsv as uploadDataFlowsFromCsvHelper } from '../../../lib/consent-manager';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface UploadDataFlowsFromCsvCommandFlags {\n auth: string;\n trackerStatus: ConsentTrackerStatus;\n file: string;\n classifyService: boolean;\n transcendUrl: string;\n}\n\nexport async function uploadDataFlowsFromCsv(\n this: LocalContext,\n {\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n }: UploadDataFlowsFromCsvCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await uploadDataFlowsFromCsvHelper({\n auth,\n trackerStatus,\n file,\n classifyService,\n transcendUrl,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkDFOLIGJPcjs = require('./chunk-DFOLIGJP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-T66BMKXU.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-DM7WURT2.cjs');require('./chunk-UM5F6R4I.cjs');require('./chunk-BY7W4UQF.cjs');async function c({auth:i,transcendUrl:n,identifierNames:r,actions:o=[]}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkDFOLIGJPcjs.W.call(void 0, {requestActions:o,transcendUrl:n,auth:i,identifierNames:r})}exports.rejectUnverifiedIdentifiers = c;
2
- //# sourceMappingURL=impl-4JIOV3X6.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWIXQSFS6cjs = require('./chunk-WIXQSFS6.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-3ZKZCSGD.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-E3CF3RKX.cjs');require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');async function c({auth:i,transcendUrl:n,identifierNames:r,actions:o=[]}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkWIXQSFS6cjs.W.call(void 0, {requestActions:o,transcendUrl:n,auth:i,identifierNames:r})}exports.rejectUnverifiedIdentifiers = c;
2
+ //# sourceMappingURL=impl-KZ2L66Q3.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-4JIOV3X6.cjs","../src/commands/request/reject-unverified-identifiers/impl.ts"],"names":["rejectUnverifiedIdentifiers","auth","transcendUrl","identifierNames","actions","doneInputValidation","removeUnverifiedRequestIdentifiers"],"mappings":"AAAA,iIAAwC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCYlO,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAU,CAAC,CACb,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,cAAA,CAAgBF,CAAAA,CAChB,YAAA,CAAAF,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,eAAA,CAAAE,CACF,CAAC,CACH,CAAA,wCAAA","file":"/home/runner/work/cli/cli/dist/impl-4JIOV3X6.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { removeUnverifiedRequestIdentifiers } from '../../../lib/requests';\nimport type { RequestAction } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface RejectUnverifiedIdentifiersCommandFlags {\n auth: string;\n identifierNames: string[];\n actions?: RequestAction[];\n transcendUrl: string;\n}\n\nexport async function rejectUnverifiedIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n identifierNames,\n actions = [],\n }: RejectUnverifiedIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await removeUnverifiedRequestIdentifiers({\n requestActions: actions,\n transcendUrl,\n auth,\n identifierNames,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-KZ2L66Q3.cjs","../src/commands/request/reject-unverified-identifiers/impl.ts"],"names":["rejectUnverifiedIdentifiers","auth","transcendUrl","identifierNames","actions","doneInputValidation","removeUnverifiedRequestIdentifiers"],"mappings":"AAAA,iIAAwC,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCYlO,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CAAU,CAAC,CACb,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,cAAA,CAAgBF,CAAAA,CAChB,YAAA,CAAAF,CAAAA,CACA,IAAA,CAAAD,CAAAA,CACA,eAAA,CAAAE,CACF,CAAC,CACH,CAAA,wCAAA","file":"/home/runner/work/cli/cli/dist/impl-KZ2L66Q3.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { removeUnverifiedRequestIdentifiers } from '../../../lib/requests';\nimport type { RequestAction } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface RejectUnverifiedIdentifiersCommandFlags {\n auth: string;\n identifierNames: string[];\n actions?: RequestAction[];\n transcendUrl: string;\n}\n\nexport async function rejectUnverifiedIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n identifierNames,\n actions = [],\n }: RejectUnverifiedIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await removeUnverifiedRequestIdentifiers({\n requestActions: actions,\n transcendUrl,\n auth,\n identifierNames,\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkT66BMKXUcjs = require('./chunk-T66BMKXU.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkUM5F6R4Icjs = require('./chunk-UM5F6R4I.cjs');var _chunkBY7W4UQFcjs = require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _got = require('got'); var _got2 = _interopRequireDefault(_got);var B=({hostname:t,auth:e})=>_got2.default.extend({prefixUrl:`https://${t}`,headers:{accept:"application/json","content-type":"application/json",authorization:`Bearer ${e}`}});var _yargsparser = require('yargs-parser'); var _yargsparser2 = _interopRequireDefault(_yargsparser);var ve=Object.values(_chunkBY7W4UQFcjs.b);var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var w=({assessment:t,index:e,total:s,wrap:r=!0})=>{let n="";(e===0||r)&&(n=`[
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunk3ZKZCSGDcjs = require('./chunk-3ZKZCSGD.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkY4BWTFTXcjs = require('./chunk-Y4BWTFTX.cjs');var _chunkBY7W4UQFcjs = require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _got = require('got'); var _got2 = _interopRequireDefault(_got);var B=({hostname:t,auth:e})=>_got2.default.extend({prefixUrl:`https://${t}`,headers:{accept:"application/json","content-type":"application/json",authorization:`Bearer ${e}`}});var _yargsparser = require('yargs-parser'); var _yargsparser2 = _interopRequireDefault(_yargsparser);var ve=Object.values(_chunkBY7W4UQFcjs.b);var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);var w=({assessment:t,index:e,total:s,wrap:r=!0})=>{let n="";(e===0||r)&&(n=`[
2
2
  `);let m=JSON.stringify(t),o=s&&e<s-1&&!r?",":"";return n=`${n+m+o}
3
3
  `,(s&&e===s-1||r)&&(n+=`
4
- ]`),n};var J=({file:t,assessment:e,index:s,total:r})=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing enriched assessment ${s+1} of ${r} to file "${t}"...`)),s===0?_fs2.default.writeFileSync(t,w({assessment:e,index:s,total:r,wrap:!1})):_fs2.default.appendFileSync(t,w({assessment:e,index:s,total:r,wrap:!1}))};var _typeutils = require('@transcend-io/type-utils');var _privacytypes = require('@transcend-io/privacy-types');var K=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}=_typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetListOfAssessmentsResponse,m);n.push(..._nullishCoalesce(u, () => ([]))),e===0&&(s=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _2 => _2.totalPages]), () => (0)),r=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _3 => _3.totalElements]), () => (0))),e+=1,_chunkZUNVPK23cjs.a.info(`Fetched ${n.length} of ${r} assessments.`)}return n};var W=async({oneTrust:t,assessmentId:e})=>{let{body:s}=await t.get(`api/assessment/v2/assessments/${e}/export?ExcludeSkippedQuestions=false`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetAssessmentResponse,s)};var H=async({oneTrust:t,riskId:e})=>{let{body:s}=await t.get(`api/risk/v2/risks/${e}`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetRiskResponse,s)};var k=async({oneTrust:t,userId:e})=>{let{body:s}=await t.get(`api/scim/v2/Users/${e}`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetUserResponse,s)};var z=({assessment:t,assessmentDetails:e,riskDetails:s,creatorDetails:r,approversDetails:n,respondentsDetails:m})=>{let o=_chunkUM5F6R4Icjs.e.call(void 0, s,"id"),{sections:u,createdBy:h,...g}=e,O=u.map(i=>{let{questions:A,...$}=i,x=A.map(E=>{let{risks:U,...G}=E,v=(_nullishCoalesce(U, () => ([]))).map(y=>{let S=o[y.riskId];return{...y,...S,level:y.level,impactLevel:_nullishCoalesce(y.impactLevel, () => (0))}});return{...G,risks:v}});return{...$,questions:x}}),p={...h,active:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _4 => _4.active]), () => (!1)),userType:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _5 => _5.userType]), () => ("Internal")),emails:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _6 => _6.emails]), () => ([])),title:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _7 => _7.title]), () => (null)),givenName:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _8 => _8.name, 'access', _9 => _9.givenName]), () => (null)),familyName:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _10 => _10.name, 'access', _11 => _11.familyName]), () => (null))},d=_chunkUM5F6R4Icjs.e.call(void 0, 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:_nullishCoalesce(d[i.id].name.givenName, () => (null)),familyName:_nullishCoalesce(d[i.id].name.familyName, () => (null))}}]:[]),T=_chunkUM5F6R4Icjs.e.call(void 0, m,"id"),C=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:_nullishCoalesce(T[i.id].name.givenName, () => (null)),familyName:_nullishCoalesce(T[i.id].name.familyName, () => (null))}]:[]);return{...t,...g,approvers:l,respondents:C,createdBy:p,sections:O}};var F=async({transcend:t,assessment:e,total:s,index:r})=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing enriched assessment ${r+1} ${s?`of ${s} `:" "}to Transcend...`));let m={json:w({assessment:e,index:r,total:s})};try{await _chunkT66BMKXUcjs._b.call(void 0, t,_chunkT66BMKXUcjs.ha,{input:m})}catch (e2){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to sync assessment ${r+1} ${s?`of ${s} `:" "}to Transcend.
4
+ ]`),n};var J=({file:t,assessment:e,index:s,total:r})=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing enriched assessment ${s+1} of ${r} to file "${t}"...`)),s===0?_fs2.default.writeFileSync(t,w({assessment:e,index:s,total:r,wrap:!1})):_fs2.default.appendFileSync(t,w({assessment:e,index:s,total:r,wrap:!1}))};var _typeutils = require('@transcend-io/type-utils');var _privacytypes = require('@transcend-io/privacy-types');var K=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}=_typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetListOfAssessmentsResponse,m);n.push(..._nullishCoalesce(u, () => ([]))),e===0&&(s=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _2 => _2.totalPages]), () => (0)),r=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _3 => _3.totalElements]), () => (0))),e+=1,_chunkZUNVPK23cjs.a.info(`Fetched ${n.length} of ${r} assessments.`)}return n};var W=async({oneTrust:t,assessmentId:e})=>{let{body:s}=await t.get(`api/assessment/v2/assessments/${e}/export?ExcludeSkippedQuestions=false`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetAssessmentResponse,s)};var H=async({oneTrust:t,riskId:e})=>{let{body:s}=await t.get(`api/risk/v2/risks/${e}`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetRiskResponse,s)};var k=async({oneTrust:t,userId:e})=>{let{body:s}=await t.get(`api/scim/v2/Users/${e}`);return _typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustGetUserResponse,s)};var z=({assessment:t,assessmentDetails:e,riskDetails:s,creatorDetails:r,approversDetails:n,respondentsDetails:m})=>{let o=_chunkY4BWTFTXcjs.e.call(void 0, s,"id"),{sections:u,createdBy:h,...g}=e,O=u.map(i=>{let{questions:A,...$}=i,x=A.map(E=>{let{risks:U,...G}=E,v=(_nullishCoalesce(U, () => ([]))).map(y=>{let S=o[y.riskId];return{...y,...S,level:y.level,impactLevel:_nullishCoalesce(y.impactLevel, () => (0))}});return{...G,risks:v}});return{...$,questions:x}}),p={...h,active:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _4 => _4.active]), () => (!1)),userType:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _5 => _5.userType]), () => ("Internal")),emails:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _6 => _6.emails]), () => ([])),title:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _7 => _7.title]), () => (null)),givenName:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _8 => _8.name, 'access', _9 => _9.givenName]), () => (null)),familyName:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _10 => _10.name, 'access', _11 => _11.familyName]), () => (null))},d=_chunkY4BWTFTXcjs.e.call(void 0, 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:_nullishCoalesce(d[i.id].name.givenName, () => (null)),familyName:_nullishCoalesce(d[i.id].name.familyName, () => (null))}}]:[]),T=_chunkY4BWTFTXcjs.e.call(void 0, m,"id"),C=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:_nullishCoalesce(T[i.id].name.givenName, () => (null)),familyName:_nullishCoalesce(T[i.id].name.familyName, () => (null))}]:[]);return{...t,...g,approvers:l,respondents:C,createdBy:p,sections:O}};var F=async({transcend:t,assessment:e,total:s,index:r})=>{_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing enriched assessment ${r+1} ${s?`of ${s} `:" "}to Transcend...`));let m={json:w({assessment:e,index:r,total:s})};try{await _chunk3ZKZCSGDcjs.$b.call(void 0, t,_chunk3ZKZCSGDcjs.ha,{input:m})}catch (e2){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to sync assessment ${r+1} ${s?`of ${s} `:" "}to Transcend.
5
5
  Assessment Title: ${e.name}. Template Title: ${e.template.name}
6
- `))}};var Y=async({oneTrust:t,file:e,dryRun:s,transcend:r})=>{_chunkZUNVPK23cjs.a.info("Getting list of all assessments from OneTrust...");let n=await K({oneTrust:t}),m={},o=5,u=Array.from({length:Math.ceil(n.length/o)},(h,g)=>n.slice(g*o,(g+1)*o));await _chunkT66BMKXUcjs.a.call(void 0, u,async(h,g)=>{let O=[];await _chunkT66BMKXUcjs.b.call(void 0, h,async(p,d)=>{let l=o*g+d+1;_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching details...`);let{templateName:T,assessmentId:C}=p,i=await W({oneTrust:t,assessmentId:C}),A=i.createdBy.id,$=m[A];if(!$){_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching creator...`);try{$=await k({oneTrust:t,userId:A}),m[A]=$}catch (e3){_chunkZUNVPK23cjs.a.warn(_colors2.default.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&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching approvers...`),E=await _chunkT66BMKXUcjs.b.call(void 0, x.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await k({oneTrust:t,userId:c}),m[c]=f),[f]}catch (e4){return _chunkZUNVPK23cjs.a.warn(_colors2.default.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:U}=i,G=U.filter(c=>!c.name.includes("@")),v=[];G.length>0&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching respondents...`),v=await _chunkT66BMKXUcjs.b.call(void 0, G.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await k({oneTrust:t,userId:c}),m[c]=f),[f]}catch (e5){return _chunkZUNVPK23cjs.a.warn(_colors2.default.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=_chunkUM5F6R4Icjs.j.call(void 0, i.sections.flatMap(c=>c.questions.flatMap(f=>(_nullishCoalesce(f.risks, () => ([]))).flatMap(ee=>ee.riskId))));S.length>0&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching risks...`),y=await _chunkT66BMKXUcjs.b.call(void 0, S,c=>H({oneTrust:t,riskId:c}),{concurrency:5}));let X=z({assessment:p,assessmentDetails:i,riskDetails:y,creatorDetails:$,approversDetails:E.flat(),respondentsDetails:v.flat()});O.push(X)},{concurrency:o}),await _chunkT66BMKXUcjs.a.call(void 0, O,async(p,d)=>{let l=g*o+d;s&&e?J({assessment:p,index:l,total:n.length,file:e}):r&&await F({assessment:p,transcend:r,total:n.length,index:l})})})};var _JSONStream = require('JSONStream'); var _JSONStream2 = _interopRequireDefault(_JSONStream);var Z=({transcend:t,file:e})=>(_chunkZUNVPK23cjs.a.info(`Getting list of all assessments from file ${e}...`),new Promise((s,r)=>{let n=_fs.createReadStream.call(void 0, e,{encoding:"utf-8",highWaterMark:65536}),m=_JSONStream2.default.parse("*"),o=0;n.pipe(m),m.on("data",async u=>{try{m.pause();let h=_typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustEnrichedAssessment,u);await F({assessment:h,transcend:t,index:o}),o+=1,m.resume()}catch(h){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to parse the assessment ${o} from file '${e}': ${h.message}.`))}}),m.on("end",()=>{_chunkZUNVPK23cjs.a.info(`Finished processing ${o} assessments from file ${e}`),s()}),m.on("error",u=>{_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error parsing file '${e}': ${u.message}`)),r(u)}),n.on("error",u=>{_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error reading file '${e}': ${u.message}`)),r(u)})}));async function Ds({hostname:t,oneTrustAuth:e,source:s,transcendAuth:r,transcendUrl:n,resource:m,file:o,dryRun:u,debug:h}){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.')}_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let g=t&&e?B({hostname:t,auth:e}):void 0,O=n&&r?_chunkT66BMKXUcjs.pe.call(void 0, n,r):void 0;try{m==="assessments"&&(s==="oneTrust"&&g?await Y({oneTrust:g,file:o,dryRun:u,...O&&{transcend:O}}):s==="file"&&o&&O&&await Z({file:o,transcend:O}))}catch(p){throw new Error(`An error occurred syncing the resource ${m} from OneTrust: ${h?p.stack:p.message}`)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced OneTrust ${m} to ${u?`disk at "${o}"`:"Transcend"}!`))}exports.syncOt = Ds;
7
- //# sourceMappingURL=impl-OIRM2C3D.cjs.map
6
+ `))}};var Y=async({oneTrust:t,file:e,dryRun:s,transcend:r})=>{_chunkZUNVPK23cjs.a.info("Getting list of all assessments from OneTrust...");let n=await K({oneTrust:t}),m={},o=5,u=Array.from({length:Math.ceil(n.length/o)},(h,g)=>n.slice(g*o,(g+1)*o));await _chunk3ZKZCSGDcjs.a.call(void 0, u,async(h,g)=>{let O=[];await _chunk3ZKZCSGDcjs.b.call(void 0, h,async(p,d)=>{let l=o*g+d+1;_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching details...`);let{templateName:T,assessmentId:C}=p,i=await W({oneTrust:t,assessmentId:C}),A=i.createdBy.id,$=m[A];if(!$){_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching creator...`);try{$=await k({oneTrust:t,userId:A}),m[A]=$}catch (e3){_chunkZUNVPK23cjs.a.warn(_colors2.default.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&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching approvers...`),E=await _chunk3ZKZCSGDcjs.b.call(void 0, x.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await k({oneTrust:t,userId:c}),m[c]=f),[f]}catch (e4){return _chunkZUNVPK23cjs.a.warn(_colors2.default.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:U}=i,G=U.filter(c=>!c.name.includes("@")),v=[];G.length>0&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching respondents...`),v=await _chunk3ZKZCSGDcjs.b.call(void 0, G.map(({id:c})=>c),async c=>{try{let f=m[c];return f||(f=await k({oneTrust:t,userId:c}),m[c]=f),[f]}catch (e5){return _chunkZUNVPK23cjs.a.warn(_colors2.default.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=_chunkY4BWTFTXcjs.j.call(void 0, i.sections.flatMap(c=>c.questions.flatMap(f=>(_nullishCoalesce(f.risks, () => ([]))).flatMap(ee=>ee.riskId))));S.length>0&&(_chunkZUNVPK23cjs.a.info(`[assessment ${l} of ${n.length}]: fetching risks...`),y=await _chunk3ZKZCSGDcjs.b.call(void 0, S,c=>H({oneTrust:t,riskId:c}),{concurrency:5}));let X=z({assessment:p,assessmentDetails:i,riskDetails:y,creatorDetails:$,approversDetails:E.flat(),respondentsDetails:v.flat()});O.push(X)},{concurrency:o}),await _chunk3ZKZCSGDcjs.a.call(void 0, O,async(p,d)=>{let l=g*o+d;s&&e?J({assessment:p,index:l,total:n.length,file:e}):r&&await F({assessment:p,transcend:r,total:n.length,index:l})})})};var _JSONStream = require('JSONStream'); var _JSONStream2 = _interopRequireDefault(_JSONStream);var Z=({transcend:t,file:e})=>(_chunkZUNVPK23cjs.a.info(`Getting list of all assessments from file ${e}...`),new Promise((s,r)=>{let n=_fs.createReadStream.call(void 0, e,{encoding:"utf-8",highWaterMark:65536}),m=_JSONStream2.default.parse("*"),o=0;n.pipe(m),m.on("data",async u=>{try{m.pause();let h=_typeutils.decodeCodec.call(void 0, _privacytypes.OneTrustEnrichedAssessment,u);await F({assessment:h,transcend:t,index:o}),o+=1,m.resume()}catch(h){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to parse the assessment ${o} from file '${e}': ${h.message}.`))}}),m.on("end",()=>{_chunkZUNVPK23cjs.a.info(`Finished processing ${o} assessments from file ${e}`),s()}),m.on("error",u=>{_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error parsing file '${e}': ${u.message}`)),r(u)}),n.on("error",u=>{_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error reading file '${e}': ${u.message}`)),r(u)})}));async function Ds({hostname:t,oneTrustAuth:e,source:s,transcendAuth:r,transcendUrl:n,resource:m,file:o,dryRun:u,debug:h}){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.')}_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let g=t&&e?B({hostname:t,auth:e}):void 0,O=n&&r?_chunk3ZKZCSGDcjs.qe.call(void 0, n,r):void 0;try{m==="assessments"&&(s==="oneTrust"&&g?await Y({oneTrust:g,file:o,dryRun:u,...O&&{transcend:O}}):s==="file"&&o&&O&&await Z({file:o,transcend:O}))}catch(p){throw new Error(`An error occurred syncing the resource ${m} from OneTrust: ${h?p.stack:p.message}`)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced OneTrust ${m} to ${u?`disk at "${o}"`:"Transcend"}!`))}exports.syncOt = Ds;
7
+ //# sourceMappingURL=impl-L3M67IGI.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-OIRM2C3D.cjs","../src/commands/migration/sync-ot/impl.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts"],"names":["createOneTrustGotInstance","hostname","auth","got"],"mappings":"AAAA,y0BAAwC,wDAAwE,wDAAoC,wDAAgD,wDAAyC,gFCE1N,oECFM,IAQZA,CAAAA,CAA4B,CAAC,CACxC,QAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CACF,CAAA,CAAA,EAMEC,aAAAA,CAAI,MAAA,CAAO,CACT,SAAA,CAAW,CAAA,QAAA,EAAWF,CAAQ,CAAA,CAAA;ACiBwB;AAIzC;ACrCW,CAAA;ACyEiE,mBAAA;ACC3B","file":"/home/runner/work/cli/cli/dist/impl-OIRM2C3D.cjs","sourcesContent":[null,"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';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${\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 { 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 { 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 { 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 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"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-L3M67IGI.cjs","../src/commands/migration/sync-ot/impl.ts","../src/lib/oneTrust/createOneTrustGotInstance.ts","../src/lib/oneTrust/helpers/oneTrustAssessmentToJson.ts","../src/lib/oneTrust/endpoints/getListOfOneTrustAssessments.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentToTranscend.ts","../src/lib/oneTrust/helpers/syncOneTrustAssessmentsFromOneTrust.ts"],"names":["createOneTrustGotInstance","hostname","auth","got"],"mappings":"AAAA,y0BAAwC,wDAAwE,wDAAoC,wDAAgD,wDAAyC,gFCE1N,oECFM,IAQZA,CAAAA,CAA4B,CAAC,CACxC,QAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CACF,CAAA,CAAA,EAMEC,aAAAA,CAAI,MAAA,CAAO,CACT,SAAA,CAAW,CAAA,QAAA,EAAWF,CAAQ,CAAA,CAAA;ACiBwB;AAIzC;ACrCW,CAAA;ACyEiE,mBAAA;ACC3B","file":"/home/runner/work/cli/cli/dist/impl-L3M67IGI.cjs","sourcesContent":[null,"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';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\n// Command flag interface\nexport interface SyncOtCommandFlags {\n hostname?: string;\n oneTrustAuth?: string;\n source: OneTrustPullSource;\n transcendAuth?: string;\n transcendUrl: string;\n file?: string;\n resource: OneTrustPullResource;\n dryRun: boolean;\n debug: boolean;\n}\n\n// Command implementation\nexport async function syncOt(\n this: LocalContext,\n {\n hostname,\n oneTrustAuth,\n source,\n transcendAuth,\n transcendUrl,\n resource,\n file,\n dryRun,\n debug,\n }: SyncOtCommandFlags,\n): Promise<void> {\n // Must be able to authenticate to transcend to sync resources to it\n if (!dryRun && !transcendAuth) {\n throw new Error(\n // eslint-disable-next-line no-template-curly-in-string\n 'Must specify a \"transcendAuth\" parameter to sync resources to Transcend. e.g. --transcendAuth=${TRANSCEND_API_KEY}',\n );\n }\n\n // If trying to sync to disk, must specify a file path\n if (dryRun && !file) {\n throw new Error(\n 'Must set a \"file\" parameter when \"dryRun\" is \"true\". e.g. --file=./oneTrustAssessments.json',\n );\n }\n\n if (file) {\n const splitFile = file.split('.');\n if (splitFile.length < 2) {\n throw new Error(\n 'The \"file\" parameter has an invalid format. Expected a path with extensions. e.g. --file=./pathToFile.json.',\n );\n }\n if (splitFile.at(-1) !== OneTrustFileFormat.Json) {\n throw new Error(\n `Expected the format of the \"file\" parameters '${file}' to be '${\n OneTrustFileFormat.Json\n }', but got '${splitFile.at(-1)}'.`,\n );\n }\n }\n\n // if reading assessments from a OneTrust\n if (source === OneTrustPullSource.OneTrust) {\n // must specify the OneTrust hostname\n if (!hostname) {\n throw new Error(\n 'Missing required parameter \"hostname\". e.g. --hostname=customer.my.onetrust.com',\n );\n }\n // must specify the OneTrust auth\n if (!oneTrustAuth) {\n throw new Error(\n 'Missing required parameter \"oneTrustAuth\". e.g. --oneTrustAuth=$ONE_TRUST_AUTH_TOKEN',\n );\n }\n } else {\n // if reading the assessments from a file, must specify a file to read from\n if (!file) {\n throw new Error(\n 'Must specify a \"file\" parameter to read the OneTrust assessments from. e.g. --source=./oneTrustAssessments.json',\n );\n }\n\n // Cannot try reading from file and save assessments to a file simultaneously\n if (dryRun) {\n throw new Error(\n 'Cannot read and write to a file simultaneously.' +\n ` Emit the \"source\" parameter or set it to ${OneTrustPullSource.OneTrust} if \"dryRun\" is enabled.`,\n );\n }\n }\n\n doneInputValidation(this.process.exit);\n\n // instantiate a client to talk to OneTrust\n const oneTrust =\n hostname && oneTrustAuth\n ? createOneTrustGotInstance({\n hostname,\n auth: oneTrustAuth,\n })\n : undefined;\n\n // instantiate a client to talk to Transcend\n const transcend =\n transcendUrl && transcendAuth\n ? buildTranscendGraphQLClient(transcendUrl, transcendAuth)\n : undefined;\n\n try {\n if (resource === OneTrustPullResource.Assessments) {\n if (source === OneTrustPullSource.OneTrust && oneTrust) {\n await syncOneTrustAssessmentsFromOneTrust({\n oneTrust,\n file,\n dryRun,\n ...(transcend && { transcend }),\n });\n } else if (source === OneTrustPullSource.File && file && transcend) {\n await syncOneTrustAssessmentsFromFile({ file, transcend });\n }\n }\n } catch (err) {\n throw new Error(\n `An error occurred syncing the resource ${resource} from OneTrust: ${\n debug ? err.stack : err.message\n }`,\n );\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced OneTrust ${resource} to ${\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 { 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 { 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 { 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 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"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk2DLJ3BDDcjs = require('./chunk-2DLJ3BDD.cjs');require('./chunk-MYCE3NIE.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZD2HOHJI.cjs');require('./chunk-SAEKBZGF.cjs');var _chunkT66BMKXUcjs = require('./chunk-T66BMKXU.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDM7WURT2cjs = require('./chunk-DM7WURT2.cjs');require('./chunk-UM5F6R4I.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _child_process = require('child_process');var d='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 A({auth:f,scanPath:r,ignoreDirs:u,repositoryName:h,transcendUrl:y}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let e=h;if(!e)try{let o=_child_process.execSync.call(void 0, `cd ${r} && git config --get remote.origin.url`).toString("utf-8").trim();[e]=o.includes("https:")?o.split("/").slice(3).join("/").split("."):(o.split(":").pop()||"").split("."),e||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(d)),this.process.exit(1))}catch(a){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`${d} - Got error: ${a.message}`)),this.process.exit(1)}let x=_chunkT66BMKXUcjs.pe.call(void 0, y,f),n=await _chunk2DLJ3BDDcjs.b.call(void 0, {scanPath:r,ignoreDirs:u,repositoryName:e});await _chunkT66BMKXUcjs.ke.call(void 0, x,n);let s=new URL(_chunkDM7WURT2cjs.b);s.pathname="/code-scanning/code-packages",_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Scan found ${n.length} packages at ${r}! View results at '${s.href}'`))}exports.scanPackages = A;
2
- //# sourceMappingURL=impl-P64XABL2.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkYA5UZ3YMcjs = require('./chunk-YA5UZ3YM.cjs');require('./chunk-IG65EYJY.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZD2HOHJI.cjs');require('./chunk-SAEKBZGF.cjs');var _chunk3ZKZCSGDcjs = require('./chunk-3ZKZCSGD.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkE3CF3RKXcjs = require('./chunk-E3CF3RKX.cjs');require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _child_process = require('child_process');var d='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 A({auth:f,scanPath:r,ignoreDirs:u,repositoryName:h,transcendUrl:y}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let e=h;if(!e)try{let o=_child_process.execSync.call(void 0, `cd ${r} && git config --get remote.origin.url`).toString("utf-8").trim();[e]=o.includes("https:")?o.split("/").slice(3).join("/").split("."):(o.split(":").pop()||"").split("."),e||(_chunkZUNVPK23cjs.a.error(_colors2.default.red(d)),this.process.exit(1))}catch(a){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`${d} - Got error: ${a.message}`)),this.process.exit(1)}let x=_chunk3ZKZCSGDcjs.qe.call(void 0, y,f),n=await _chunkYA5UZ3YMcjs.b.call(void 0, {scanPath:r,ignoreDirs:u,repositoryName:e});await _chunk3ZKZCSGDcjs.le.call(void 0, x,n);let s=new URL(_chunkE3CF3RKXcjs.b);s.pathname="/code-scanning/code-packages",_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Scan found ${n.length} packages at ${r}! View results at '${s.href}'`))}exports.scanPackages = A;
2
+ //# sourceMappingURL=impl-LTOV5CHF.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-P64XABL2.cjs","../src/commands/inventory/scan-packages/impl.ts"],"names":["REPO_ERROR","scanPackages","auth","scanPath","ignoreDirs","repositoryName","transcendUrl","doneInputValidation","gitRepositoryName","url","execSync","logger","colors","err"],"mappings":"AAAA,iOAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,wDAAkD,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gFCEnV,8CAOM,IAGnBA,CAAAA,CACJ,0LAAA,CAYF,MAAA,SAAsBC,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAIC,CAAAA,CAAoBH,CAAAA,CACxB,EAAA,CAAI,CAACG,CAAAA,CACH,GAAI,CAKF,IAAMC,CAAAA,CAJOC,qCAAAA,CACX,GAAA,EAAMP,CAAQ,CAAA,sCAAA,CAChB,CAAA,CAEiB,QAAA,CAAS,OAAO,CAAA,CAAE,IAAA,CAAK,CAAA,CACxC,CAACK,CAAiB,CAAA,CAAKC,CAAAA,CAAI,QAAA,CAAS,QAAQ,CAAA,CAExCA,CAAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAAE,KAAA,CAAM,GAAG,CAAA,CAAA,CAD1CA,CAAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAA,EAAK,EAAA,CAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAErCD,CAAAA,EAAAA,CACHG,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAIZ,CAAU,CAAC,CAAA,CACnC,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAEvB,CAAA,KAAA,CAASa,CAAAA,CAAK,CACZF,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAI,CAAA,EAAA","file":"/home/runner/work/cli/cli/dist/impl-P64XABL2.cjs","sourcesContent":[null,"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';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\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\nexport interface 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 doneInputValidation(this.process.exit);\n\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 this.process.exit(1);\n }\n } catch (err) {\n logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n this.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"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-LTOV5CHF.cjs","../src/commands/inventory/scan-packages/impl.ts"],"names":["REPO_ERROR","scanPackages","auth","scanPath","ignoreDirs","repositoryName","transcendUrl","doneInputValidation","gitRepositoryName","url","execSync","logger","colors","err"],"mappings":"AAAA,iOAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,wDAAkD,wDAAyC,wDAAyC,gCAA6B,gCAA6B,gFCEnV,8CAOM,IAGnBA,CAAAA,CACJ,0LAAA,CAYF,MAAA,SAAsBC,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAGrC,IAAIC,CAAAA,CAAoBH,CAAAA,CACxB,EAAA,CAAI,CAACG,CAAAA,CACH,GAAI,CAKF,IAAMC,CAAAA,CAJOC,qCAAAA,CACX,GAAA,EAAMP,CAAQ,CAAA,sCAAA,CAChB,CAAA,CAEiB,QAAA,CAAS,OAAO,CAAA,CAAE,IAAA,CAAK,CAAA,CACxC,CAACK,CAAiB,CAAA,CAAKC,CAAAA,CAAI,QAAA,CAAS,QAAQ,CAAA,CAExCA,CAAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,CAAC,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAAE,KAAA,CAAM,GAAG,CAAA,CAAA,CAD1CA,CAAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAAE,GAAA,CAAI,CAAA,EAAK,EAAA,CAAA,CAAI,KAAA,CAAM,GAAG,CAAA,CAErCD,CAAAA,EAAAA,CACHG,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAIZ,CAAU,CAAC,CAAA,CACnC,IAAA,CAAK,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,CAEvB,CAAA,KAAA,CAASa,CAAAA,CAAK,CACZF,mBAAAA,CAAO,KAAA,CAAMC,gBAAAA,CAAO,GAAA,CAAI,CAAA,EAAA","file":"/home/runner/work/cli/cli/dist/impl-LTOV5CHF.cjs","sourcesContent":[null,"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';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\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\nexport interface 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 doneInputValidation(this.process.exit);\n\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 this.process.exit(1);\n }\n } catch (err) {\n logger.error(colors.red(`${REPO_ERROR} - Got error: ${err.message}`));\n this.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"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkVBCQ7F34cjs = require('./chunk-VBCQ7F34.cjs');require('./chunk-6VV64JQD.cjs');var _chunkZVK4HIDFcjs = require('./chunk-ZVK4HIDF.cjs');require('./chunk-DFOLIGJP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkT66BMKXUcjs = require('./chunk-T66BMKXU.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDM7WURT2cjs = require('./chunk-DM7WURT2.cjs');var _chunkUM5F6R4Icjs = require('./chunk-UM5F6R4I.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function v({auth:y,file:a,transcendUrl:C,dataSiloIds:f,includeAttributes:D,includeGuessedCategories:P,parentCategories:b,subCategories:h=[]}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);try{let o=_chunkT66BMKXUcjs.pe.call(void 0, C,y),$=await _chunkVBCQ7F34cjs.a.call(void 0, o,{dataSiloIds:f,includeGuessedCategories:P,parentCategories:b,includeAttributes:D,subCategories:h});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing datapoints to file "${a}"...`));let s=[],j=$.map(t=>{let n={"Property ID":t.id,"Data Silo":t.dataSilo.title,Object:t.dataPoint.name,"Object Path":t.dataPoint.path.join("."),Property:t.name,"Property Description":t.description,"Data Categories":t.categories.map(e=>`${e.category}:${e.name}`).join(", "),"Guessed Category":_optionalChain([t, 'access', _ => _.pendingCategoryGuesses, 'optionalAccess', _2 => _2[0]])?`${t.pendingCategoryGuesses[0].category.category}:${t.pendingCategoryGuesses[0].category.name}`:"","Processing Purposes":t.purposes.map(e=>`${e.purpose}:${e.name}`).join(", "),...Object.entries(_chunkUM5F6R4Icjs.d.call(void 0, t.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[x,A])=>(e[x]=A.map(G=>G.name).join(","),e),{})};return s=_chunkUM5F6R4Icjs.j.call(void 0, [...s,...Object.keys(n)]),n});_chunkZVK4HIDFcjs.c.call(void 0, a,j,s)}catch(o){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error occurred syncing the datapoints: ${o.message}`)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced datapoints to disk at ${a}! View at ${_chunkDM7WURT2cjs.d}`))}exports.pullDatapoints = v;
2
- //# sourceMappingURL=impl-OOVHRMYF.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkEVZLUL56cjs = require('./chunk-EVZLUL56.cjs');require('./chunk-6FGYCQAQ.cjs');var _chunkZVK4HIDFcjs = require('./chunk-ZVK4HIDF.cjs');require('./chunk-WIXQSFS6.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunk3ZKZCSGDcjs = require('./chunk-3ZKZCSGD.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkE3CF3RKXcjs = require('./chunk-E3CF3RKX.cjs');var _chunkY4BWTFTXcjs = require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function v({auth:y,file:a,transcendUrl:C,dataSiloIds:f,includeAttributes:D,includeGuessedCategories:P,parentCategories:b,subCategories:h=[]}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);try{let o=_chunk3ZKZCSGDcjs.qe.call(void 0, C,y),$=await _chunkEVZLUL56cjs.a.call(void 0, o,{dataSiloIds:f,includeGuessedCategories:P,parentCategories:b,includeAttributes:D,subCategories:h});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Writing datapoints to file "${a}"...`));let s=[],j=$.map(t=>{let n={"Property ID":t.id,"Data Silo":t.dataSilo.title,Object:t.dataPoint.name,"Object Path":t.dataPoint.path.join("."),Property:t.name,"Property Description":t.description,"Data Categories":t.categories.map(e=>`${e.category}:${e.name}`).join(", "),"Guessed Category":_optionalChain([t, 'access', _ => _.pendingCategoryGuesses, 'optionalAccess', _2 => _2[0]])?`${t.pendingCategoryGuesses[0].category.category}:${t.pendingCategoryGuesses[0].category.name}`:"","Processing Purposes":t.purposes.map(e=>`${e.purpose}:${e.name}`).join(", "),...Object.entries(_chunkY4BWTFTXcjs.d.call(void 0, t.attributeValues||[],({attributeKey:e})=>e.name)).reduce((e,[x,A])=>(e[x]=A.map(G=>G.name).join(","),e),{})};return s=_chunkY4BWTFTXcjs.j.call(void 0, [...s,...Object.keys(n)]),n});_chunkZVK4HIDFcjs.c.call(void 0, a,j,s)}catch(o){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error occurred syncing the datapoints: ${o.message}`)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully synced datapoints to disk at ${a}! View at ${_chunkE3CF3RKXcjs.d}`))}exports.pullDatapoints = v;
2
+ //# sourceMappingURL=impl-MO6AOGQM.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-OOVHRMYF.cjs","../src/commands/inventory/pull-datapoints/impl.ts"],"names":["pullDatapoints","auth","file","transcendUrl","dataSiloIds","includeAttributes","includeGuessedCategories","parentCategories","subCategories","doneInputValidation","client","buildTranscendGraphQLClient","dataPoints","pullAllDatapoints","logger","colors","headers","inputs","point","result","category"],"mappings":"AAAA,quBAAwC,gCAA6B,wDAAyC,gCAA6B,wDAAyC,wDAA0C,wDAAyC,wDAAyC,wDAAgD,gCAA6B,gFCI1W,MAmBnB,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,wBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAC,CACnB,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,GAAI,CAEF,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BR,CAAcF,CAAI,CAAA,CAEvDW,CAAAA,CAAa,MAAMC,iCAAAA,CAAkBH,CAAQ,CACjD,WAAA,CAAAN,CAAAA,CACA,wBAAA,CAAAE,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAF,CAAAA,CACA,aAAA,CAAAG,CACF,CAAC,CAAA,CAEDM,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,CAAA,4BAAA,EAA+Bb,CAAI,CAAA,IAAA,CAAM,CAAC,CAAA,CACrE,IAAIc,CAAAA,CAAoB,CAAC,CAAA,CACnBC,CAAAA,CAASL,CAAAA,CAAW,GAAA,CAAKM,CAAAA,EAAU,CACvC,IAAMC,CAAAA,CAAS,CACb,aAAA,CAAeD,CAAAA,CAAM,EAAA,CACrB,WAAA,CAAaA,CAAAA,CAAM,QAAA,CAAS,KAAA,CAC5B,MAAA,CAAQA,CAAAA,CAAM,SAAA,CAAU,IAAA,CACxB,aAAA,CAAeA,CAAAA,CAAM,SAAA,CAAU,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA,CAC5C,QAAA,CAAUA,CAAAA,CAAM,IAAA,CAChB,sBAAA,CAAwBA,CAAAA,CAAM,WAAA,CAC9B,iBAAA,CAAmBA,CAAAA,CAAM,UAAA,CACtB,GAAA,CAAKE,CAAAA,EAAa,CAAA,EAAA","file":"/home/runner/work/cli/cli/dist/impl-OOVHRMYF.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { buildTranscendGraphQLClient } from '../../../lib/graphql';\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants';\nimport { pullAllDatapoints } from '../../../lib/data-inventory';\nimport { writeCsv } from '../../../lib/cron';\nimport { DataCategoryType } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(\n point.attributeValues || [],\n ({ attributeKey }) => attributeKey.name,\n ),\n ).reduce((acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n }, {} as Record<string, string>),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n writeCsv(file, inputs, headers);\n } catch (err) {\n logger.error(\n colors.red(`An error occurred syncing the datapoints: ${err.message}`),\n );\n this.process.exit(1);\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-MO6AOGQM.cjs","../src/commands/inventory/pull-datapoints/impl.ts"],"names":["pullDatapoints","auth","file","transcendUrl","dataSiloIds","includeAttributes","includeGuessedCategories","parentCategories","subCategories","doneInputValidation","client","buildTranscendGraphQLClient","dataPoints","pullAllDatapoints","logger","colors","headers","inputs","point","result","category"],"mappings":"AAAA,quBAAwC,gCAA6B,wDAAyC,gCAA6B,wDAAyC,wDAA0C,wDAAyC,wDAAyC,wDAAgD,gCAA6B,gFCI1W,MAmBnB,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,wBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAC,CACnB,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,GAAI,CAEF,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BR,CAAcF,CAAI,CAAA,CAEvDW,CAAAA,CAAa,MAAMC,iCAAAA,CAAkBH,CAAQ,CACjD,WAAA,CAAAN,CAAAA,CACA,wBAAA,CAAAE,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAF,CAAAA,CACA,aAAA,CAAAG,CACF,CAAC,CAAA,CAEDM,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,CAAA,4BAAA,EAA+Bb,CAAI,CAAA,IAAA,CAAM,CAAC,CAAA,CACrE,IAAIc,CAAAA,CAAoB,CAAC,CAAA,CACnBC,CAAAA,CAASL,CAAAA,CAAW,GAAA,CAAKM,CAAAA,EAAU,CACvC,IAAMC,CAAAA,CAAS,CACb,aAAA,CAAeD,CAAAA,CAAM,EAAA,CACrB,WAAA,CAAaA,CAAAA,CAAM,QAAA,CAAS,KAAA,CAC5B,MAAA,CAAQA,CAAAA,CAAM,SAAA,CAAU,IAAA,CACxB,aAAA,CAAeA,CAAAA,CAAM,SAAA,CAAU,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA,CAC5C,QAAA,CAAUA,CAAAA,CAAM,IAAA,CAChB,sBAAA,CAAwBA,CAAAA,CAAM,WAAA,CAC9B,iBAAA,CAAmBA,CAAAA,CAAM,UAAA,CACtB,GAAA,CAAKE,CAAAA,EAAa,CAAA,EAAA","file":"/home/runner/work/cli/cli/dist/impl-MO6AOGQM.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { uniq, groupBy } from 'lodash-es';\n\nimport { logger } from '../../../logger';\nimport colors from 'colors';\nimport { buildTranscendGraphQLClient } from '../../../lib/graphql';\nimport { ADMIN_DASH_DATAPOINTS } from '../../../constants';\nimport { pullAllDatapoints } from '../../../lib/data-inventory';\nimport { writeCsv } from '../../../lib/cron';\nimport { DataCategoryType } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface PullDatapointsCommandFlags {\n auth: string;\n file: string;\n transcendUrl: string;\n dataSiloIds?: string[];\n includeAttributes: boolean;\n includeGuessedCategories: boolean;\n parentCategories?: DataCategoryType[];\n subCategories?: string[];\n}\n\nexport async function pullDatapoints(\n this: LocalContext,\n {\n auth,\n file,\n transcendUrl,\n dataSiloIds,\n includeAttributes,\n includeGuessedCategories,\n parentCategories,\n subCategories = [],\n }: PullDatapointsCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n try {\n // Create a GraphQL client\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const dataPoints = await pullAllDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n parentCategories,\n includeAttributes,\n subCategories, // TODO: https://transcend.height.app/T-40482 - do by name not ID\n });\n\n logger.info(colors.magenta(`Writing datapoints to file \"${file}\"...`));\n let headers: string[] = [];\n const inputs = dataPoints.map((point) => {\n const result = {\n 'Property ID': point.id,\n 'Data Silo': point.dataSilo.title,\n Object: point.dataPoint.name,\n 'Object Path': point.dataPoint.path.join('.'),\n Property: point.name,\n 'Property Description': point.description,\n 'Data Categories': point.categories\n .map((category) => `${category.category}:${category.name}`)\n .join(', '),\n 'Guessed Category': point.pendingCategoryGuesses?.[0]\n ? `${point.pendingCategoryGuesses![0]!.category.category}:${\n point.pendingCategoryGuesses![0]!.category.name\n }`\n : '',\n 'Processing Purposes': point.purposes\n .map((purpose) => `${purpose.purpose}:${purpose.name}`)\n .join(', '),\n ...Object.entries(\n groupBy(\n point.attributeValues || [],\n ({ attributeKey }) => attributeKey.name,\n ),\n ).reduce((acc, [key, values]) => {\n acc[key] = values.map((value) => value.name).join(',');\n return acc;\n }, {} as Record<string, string>),\n };\n headers = uniq([...headers, ...Object.keys(result)]);\n return result;\n });\n writeCsv(file, inputs, headers);\n } catch (err) {\n logger.error(\n colors.red(`An error occurred syncing the datapoints: ${err.message}`),\n );\n this.process.exit(1);\n }\n\n // Indicate success\n logger.info(\n colors.green(\n `Successfully synced datapoints to disk at ${file}! View at ${ADMIN_DASH_DATAPOINTS}`,\n ),\n );\n}\n"]}
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkS27CXPPNcjs = require('./chunk-S27CXPPN.cjs');require('./chunk-TD7ADMVO.cjs');var _chunkDFOLIGJPcjs = require('./chunk-DFOLIGJP.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-SAEKBZGF.cjs');var _chunkT66BMKXUcjs = require('./chunk-T66BMKXU.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');require('./chunk-DM7WURT2.cjs');var _chunkUM5F6R4Icjs = require('./chunk-UM5F6R4I.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var A = _interopRequireWildcard(_iots); var T = _interopRequireWildcard(_iots); var o = _interopRequireWildcard(_iots);var _privacytypes = require('@transcend-io/privacy-types');var _typeutils = require('@transcend-io/type-utils');var Se=T.intersection([T.type({nodes:T.array(_privacytypes.PreferenceQueryResponseItem)}),T.partial({cursor:T.string})]),Ie=["ENOTFOUND","ETIMEDOUT","504 Gateway Time-out","Task timed out after"];async function fe(m,{identifiers:n,partitionKey:w,skipLogging:d=!1}){let s=[],u=_chunkUM5F6R4Icjs.b.call(void 0, n,100),i=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);d||t.start(n.length,0);let c=0;await _chunkT66BMKXUcjs.b.call(void 0, u,async e=>{let a=0,g=3;for(;a<g;)try{let p=await m.post(`v1/preferences/${w}/query`,{json:{filter:{identifiers:e},limit:e.length}}).json(),h=_typeutils.decodeCodec.call(void 0, Se,p);s.push(...h.nodes),c+=e.length,t.update(c);break}catch(p){a+=1;let h=_optionalChain([p, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([p, 'optionalAccess', _4 => _4.message])||"";if(a>=g||!Ie.some(P=>h.includes(P)))throw new Error(`Received an error from server after ${a} attempts: ${h}`);_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRYING FAILED REQUEST - Attempt ${a}] Failed to fetch ${e.length} user preferences from partition ${w}: ${h}`))}},{concurrency:40}),t.stop();let r=new Date().getTime()-i;return d||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${r/1e3}" seconds.`)),s}function Q({row:m,columnToPurposeName:n,purposeSlugs:w,preferenceTopics:d}){let s={};return Object.entries(n).forEach(([u,{purpose:i,preference:t,valueMapping:c}])=>{if(!w.includes(i))throw new Error(`Invalid purpose slug: ${i}, expected: ${w.join(", ")}`);if(t){let f=d.find(g=>g.slug===t&&g.purpose.trackingType===i);if(!f){let g=d.filter(p=>p.purpose.trackingType===i).map(p=>p.slug);throw new Error(`Invalid preference slug: ${t} for purpose: ${i}. Allowed preference slugs for purpose are: ${g.join(",")}`)}s[i]||(s[i]={preferences:[]}),s[i].preferences||(s[i].preferences=[]);let r=m[u],e=c[r],a=typeof e=="string"&&e.trim()||null;switch(f.type){case _privacytypes.PreferenceTopicType.Boolean:if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${t}, expected boolean, got: ${r}`);s[i].preferences.push({topic:t,choice:{booleanValue:e}});break;case _privacytypes.PreferenceTopicType.Select:if(typeof e!="string"&&e!==null)throw new Error(`Invalid value for select preference: ${t}, expected string or null, got: ${r}`);if(a&&!f.preferenceOptionValues.map(({slug:g})=>g).includes(a))throw new Error(`Invalid value for select preference: ${t}, expected one of: ${f.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${r}`);s[i].preferences.push({topic:t,choice:{selectValue:a}});break;case _privacytypes.PreferenceTopicType.MultiSelect:if(typeof r!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected string, got: ${r}`);s[i].preferences.push({topic:t,choice:{selectValues:_chunkDFOLIGJPcjs.n.call(void 0, r).map(g=>{let p=c[g];if(typeof p!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected one of: ${f.preferenceOptionValues.map(({slug:h})=>h).join(", ")}, got: ${g}`);return p}).sort((g,p)=>g.localeCompare(p))}});break;default:throw new Error(`Unknown preference type: ${f.type}`)}}else s[i]?s[i].enabled=c[m[u]]===!0:s[i]={enabled:c[m[u]]===!0}}),_typeutils.apply.call(void 0, s,(u,i)=>{if(typeof u.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${i}`);return{...u,enabled:u.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var L="[NONE]";async function ue(m,n){let w=_chunkUM5F6R4Icjs.j.call(void 0, m.map(s=>Object.keys(s)).flat()),d=_chunkUM5F6R4Icjs.c.call(void 0, w,[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.timestampColum){let{timestampName:s}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:d.find(u=>u.toLowerCase().includes("date"))||d.find(u=>u.toLowerCase().includes("time"))||d[0],choices:[...d,L]}]);n.timestampColum=s}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${n.timestampColum}"`)),n.timestampColum!==L){let s=m.map((u,i)=>u[n.timestampColum]?null:[i]).filter(u=>!!u).flat();if(s.length>0)throw new Error(`The timestamp column "${n.timestampColum}" is missing a value for the following rows: ${s.join(`
2
- `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${n.timestampColum}" is present for all row`))}return n}async function de(m,n){let w=_chunkUM5F6R4Icjs.j.call(void 0, m.map(t=>Object.keys(t)).flat()),d=_chunkUM5F6R4Icjs.c.call(void 0, w,[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.identifierColumn){let{identifierName:t}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:d.find(c=>c.toLowerCase().includes("email"))||d[0],choices:d}]);n.identifierColumn=t}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${n.identifierColumn}"`));let s=m.map((t,c)=>t[n.identifierColumn]?null:[c]).filter(t=>!!t).flat();if(s.length>0){let t=`The identifier column "${n.identifierColumn}" is missing a value for the following rows: ${s.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkS27CXPPNcjs.a.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(t);let f=m.length;m=m.filter(r=>r[n.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${f-m.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${n.identifierColumn}" is present for all rows`));let u=_chunkUM5F6R4Icjs.d.call(void 0, m,n.identifierColumn),i=Object.entries(u).filter(([,t])=>t.length>1);if(i.length>0){let t=`The identifier column "${n.identifierColumn}" has duplicate values for the following rows: ${i.slice(0,10).map(([f,r])=>`${f} (${r.length})`).join(`
3
- `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkS27CXPPNcjs.a.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(t);m=Object.entries(u).map(([,f])=>f.sort((e,a)=>new Date(a[n.timestampColum]).getTime()-new Date(e[n.timestampColum]).getTime())[0]).filter(f=>f)}return{currentState:n,preferences:m}}async function ge(m,n,{purposeSlugs:w,preferenceTopics:d,forceTriggerWorkflows:s}){let u=_chunkUM5F6R4Icjs.j.call(void 0, m.map(c=>Object.keys(c)).flat()),i=_chunkUM5F6R4Icjs.c.call(void 0, u,[...n.identifierColumn?[n.identifierColumn]:[],...n.timestampColum?[n.timestampColum]:[]]);if(i.length===0){if(s)return n;throw new Error("No other columns to process")}let t=[...w,...d.map(c=>`${c.purpose.trackingType}->${c.slug}`)];return await _chunkT66BMKXUcjs.a.call(void 0, i,async c=>{let f=_chunkUM5F6R4Icjs.j.call(void 0, m.map(e=>e[c])),r=n.columnToPurposeName[c];if(r)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${c}" is associated with purpose "${r.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${c} is associated with`,type:"list",default:t.find(p=>p.startsWith(w[0])),choices:t}]),[a,g]=e.split("->");r={purpose:a,preference:g||null,valueMapping:{}}}await _chunkT66BMKXUcjs.a.call(void 0, f,async e=>{if(r.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${r.valueMapping[e]}"`));return}if(r.preference===null){let{purposeValue:a}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=a}if(r.preference!==null){let a=d.find(p=>p.slug===r.preference);if(!a){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${r.preference}" not found`));return}let g=a.preferenceOptionValues.map(({slug:p})=>p);if(a.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:p}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=p;return}if(a.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:p}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(h=>h===e)}]);r.valueMapping[e]=p;return}if(a.type===_privacytypes.PreferenceTopicType.MultiSelect){let p=_chunkDFOLIGJPcjs.n.call(void 0, e);await _chunkT66BMKXUcjs.a.call(void 0, p,async h=>{if(r.valueMapping[h]!==void 0)return;let{preferenceValue:P}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${h}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(y=>y===h)}]);r.valueMapping[h]=P});return}throw new Error(`Unknown preference topic type: ${a.type}`)}}),n.columnToPurposeName[c]=r}),n}function he({currentConsentRecord:m,pendingUpdates:n,preferenceTopics:w}){return Object.entries(n).every(([d,{preferences:s=[],enabled:u}])=>{let i=m.purposes.find(c=>c.purpose===d);return!!i&&i.enabled===u?s.every(({topic:c,choice:f})=>i.preferences&&i.preferences.find(r=>{if(r.topic!==c)return!1;let e=w.find(a=>a.slug===c&&a.purpose.trackingType===d);if(!e)throw new Error(`Could not find preference topic for ${c}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return r.choice.booleanValue===f.booleanValue;case _privacytypes.PreferenceTopicType.Select:return r.choice.selectValue===f.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let a=(r.choice.selectValues||[]).sort(),g=(f.selectValues||[]).sort();return a.length===g.length&&a.every((p,h)=>p===g[h]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function we({currentConsentRecord:m,pendingUpdates:n,preferenceTopics:w}){return!!Object.entries(n).find(([d,{preferences:s=[],enabled:u}])=>{let i=m.purposes.find(t=>t.purpose===d);return i?i.enabled!==u?!0:!!s.find(({topic:t,choice:c})=>{let f=(i.preferences||[]).find(e=>e.topic===t);if(!f)return!1;let r=w.find(e=>e.slug===t&&e.purpose.trackingType===d);if(!r)throw new Error(`Could not find preference topic for ${t}`);switch(r.type){case _privacytypes.PreferenceTopicType.Boolean:return f.choice.booleanValue!==c.booleanValue;case _privacytypes.PreferenceTopicType.Select:return f.choice.selectValue!==c.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let e=(f.choice.selectValues||[]).sort(),a=(c.selectValues||[]).sort();return e.length!==a.length||!e.every((g,p)=>g===a[p]);default:throw new Error(`Unknown preference topic type: ${r.type}`)}}):!1})}async function Pe({file:m,sombra:n,purposeSlugs:w,preferenceTopics:d,partitionKey:s,skipExistingRecordCheck:u,forceTriggerWorkflows:i},t){let c=new Date().getTime(),f=t.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${m}"`));let r=_chunkDFOLIGJPcjs.q.call(void 0, m,A.record(A.string,A.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...f[m]||{},lastFetchedAt:new Date().toISOString()};e=await ue(r,e),f[m]=e,await t.setValue(f,"fileMetadata");let a=await de(r,e);e=a.currentState,r=a.preferences,f[m]=e,await t.setValue(f,"fileMetadata"),e=await ge(r,e,{preferenceTopics:d,purposeSlugs:w,forceTriggerWorkflows:i}),f[m]=e,await t.setValue(f,"fileMetadata");let g=r.map(y=>y[e.identifierColumn]),p=u?[]:await fe(n,{identifiers:g.map(y=>({value:y})),partitionKey:s}),h=_chunkUM5F6R4Icjs.e.call(void 0, p,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},r.forEach(y=>{let $=y[e.identifierColumn],E=Q({row:y,columnToPurposeName:e.columnToPurposeName,preferenceTopics:d,purposeSlugs:w}),U=h[$];if(i&&!U)throw new Error(`No existing consent record found for user with id: ${$}.
4
- When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(U&&he({currentConsentRecord:U,pendingUpdates:E,preferenceTopics:d})&&!i){e.skippedUpdates[$]=y;return}if(U&&we({currentConsentRecord:U,pendingUpdates:E,preferenceTopics:d})){e.pendingConflictUpdates[$]={row:y,record:U};return}e.pendingSafeUpdates[$]=y}),f[m]=e,await t.setValue(f,"fileMetadata");let P=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${m}" in ${(P-c)/1e3}s`))}var je=o.type({purpose:o.string,preference:o.union([o.string,o.null]),valueMapping:o.record(o.string,o.union([o.string,o.boolean,o.null]))}),Ae=o.intersection([o.type({columnToPurposeName:o.record(o.string,je),lastFetchedAt:o.string,pendingSafeUpdates:o.record(o.string,o.record(o.string,o.string)),pendingConflictUpdates:o.record(o.string,o.type({record:_privacytypes.PreferenceQueryResponseItem,row:o.record(o.string,o.string)})),skippedUpdates:o.record(o.string,o.record(o.string,o.string))}),o.partial({identifierColumn:o.string,timestampColum:o.string})]),$e=o.type({fileMetadata:o.record(o.string,Ae),failingUpdates:o.record(o.string,o.type({uploadedAt:o.string,error:o.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:o.record(o.string,_privacytypes.PreferenceUpdateItem)});async function Te({auth:m,sombraAuth:n,receiptFilepath:w,file:d,partition:s,isSilent:u=!0,dryRun:i=!1,skipWorkflowTriggers:t=!1,skipConflictUpdates:c=!1,skipExistingRecordCheck:f=!1,attributes:r=[],transcendUrl:e,forceTriggerWorkflows:a=!1}){let g=_chunkDFOLIGJPcjs.p.call(void 0, r),p=new (0, _persistedstate.PersistedState)(w,$e,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),h=p.getValue("failingUpdates"),P=p.getValue("pendingUpdates"),y=p.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkR4IKDXM5cjs = require('./chunk-R4IKDXM5.cjs');require('./chunk-TD7ADMVO.cjs');var _chunkWIXQSFS6cjs = require('./chunk-WIXQSFS6.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-SAEKBZGF.cjs');var _chunk3ZKZCSGDcjs = require('./chunk-3ZKZCSGD.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');require('./chunk-E3CF3RKX.cjs');var _chunkY4BWTFTXcjs = require('./chunk-Y4BWTFTX.cjs');require('./chunk-BY7W4UQF.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var A = _interopRequireWildcard(_iots); var T = _interopRequireWildcard(_iots); var o = _interopRequireWildcard(_iots);var _privacytypes = require('@transcend-io/privacy-types');var _typeutils = require('@transcend-io/type-utils');var Se=T.intersection([T.type({nodes:T.array(_privacytypes.PreferenceQueryResponseItem)}),T.partial({cursor:T.string})]),Ie=["ENOTFOUND","ETIMEDOUT","504 Gateway Time-out","Task timed out after"];async function fe(m,{identifiers:n,partitionKey:w,skipLogging:d=!1}){let s=[],u=_chunkY4BWTFTXcjs.b.call(void 0, n,100),i=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);d||t.start(n.length,0);let c=0;await _chunk3ZKZCSGDcjs.b.call(void 0, u,async e=>{let a=0,g=3;for(;a<g;)try{let p=await m.post(`v1/preferences/${w}/query`,{json:{filter:{identifiers:e},limit:e.length}}).json(),h=_typeutils.decodeCodec.call(void 0, Se,p);s.push(...h.nodes),c+=e.length,t.update(c);break}catch(p){a+=1;let h=_optionalChain([p, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([p, 'optionalAccess', _4 => _4.message])||"";if(a>=g||!Ie.some(P=>h.includes(P)))throw new Error(`Received an error from server after ${a} attempts: ${h}`);_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRYING FAILED REQUEST - Attempt ${a}] Failed to fetch ${e.length} user preferences from partition ${w}: ${h}`))}},{concurrency:40}),t.stop();let r=new Date().getTime()-i;return d||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${r/1e3}" seconds.`)),s}function Q({row:m,columnToPurposeName:n,purposeSlugs:w,preferenceTopics:d}){let s={};return Object.entries(n).forEach(([u,{purpose:i,preference:t,valueMapping:c}])=>{if(!w.includes(i))throw new Error(`Invalid purpose slug: ${i}, expected: ${w.join(", ")}`);if(t){let f=d.find(g=>g.slug===t&&g.purpose.trackingType===i);if(!f){let g=d.filter(p=>p.purpose.trackingType===i).map(p=>p.slug);throw new Error(`Invalid preference slug: ${t} for purpose: ${i}. Allowed preference slugs for purpose are: ${g.join(",")}`)}s[i]||(s[i]={preferences:[]}),s[i].preferences||(s[i].preferences=[]);let r=m[u],e=c[r],a=typeof e=="string"&&e.trim()||null;switch(f.type){case _privacytypes.PreferenceTopicType.Boolean:if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${t}, expected boolean, got: ${r}`);s[i].preferences.push({topic:t,choice:{booleanValue:e}});break;case _privacytypes.PreferenceTopicType.Select:if(typeof e!="string"&&e!==null)throw new Error(`Invalid value for select preference: ${t}, expected string or null, got: ${r}`);if(a&&!f.preferenceOptionValues.map(({slug:g})=>g).includes(a))throw new Error(`Invalid value for select preference: ${t}, expected one of: ${f.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${r}`);s[i].preferences.push({topic:t,choice:{selectValue:a}});break;case _privacytypes.PreferenceTopicType.MultiSelect:if(typeof r!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected string, got: ${r}`);s[i].preferences.push({topic:t,choice:{selectValues:_chunkWIXQSFS6cjs.n.call(void 0, r).map(g=>{let p=c[g];if(typeof p!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected one of: ${f.preferenceOptionValues.map(({slug:h})=>h).join(", ")}, got: ${g}`);return p}).sort((g,p)=>g.localeCompare(p))}});break;default:throw new Error(`Unknown preference type: ${f.type}`)}}else s[i]?s[i].enabled=c[m[u]]===!0:s[i]={enabled:c[m[u]]===!0}}),_typeutils.apply.call(void 0, s,(u,i)=>{if(typeof u.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${i}`);return{...u,enabled:u.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var L="[NONE]";async function ue(m,n){let w=_chunkY4BWTFTXcjs.j.call(void 0, m.map(s=>Object.keys(s)).flat()),d=_chunkY4BWTFTXcjs.c.call(void 0, w,[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.timestampColum){let{timestampName:s}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:d.find(u=>u.toLowerCase().includes("date"))||d.find(u=>u.toLowerCase().includes("time"))||d[0],choices:[...d,L]}]);n.timestampColum=s}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${n.timestampColum}"`)),n.timestampColum!==L){let s=m.map((u,i)=>u[n.timestampColum]?null:[i]).filter(u=>!!u).flat();if(s.length>0)throw new Error(`The timestamp column "${n.timestampColum}" is missing a value for the following rows: ${s.join(`
2
+ `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${n.timestampColum}" is present for all row`))}return n}async function de(m,n){let w=_chunkY4BWTFTXcjs.j.call(void 0, m.map(t=>Object.keys(t)).flat()),d=_chunkY4BWTFTXcjs.c.call(void 0, w,[...n.identifierColumn?[n.identifierColumn]:[],...Object.keys(n.columnToPurposeName)]);if(!n.identifierColumn){let{identifierName:t}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:d.find(c=>c.toLowerCase().includes("email"))||d[0],choices:d}]);n.identifierColumn=t}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${n.identifierColumn}"`));let s=m.map((t,c)=>t[n.identifierColumn]?null:[c]).filter(t=>!!t).flat();if(s.length>0){let t=`The identifier column "${n.identifierColumn}" is missing a value for the following rows: ${s.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkR4IKDXM5cjs.a.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(t);let f=m.length;m=m.filter(r=>r[n.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${f-m.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${n.identifierColumn}" is present for all rows`));let u=_chunkY4BWTFTXcjs.d.call(void 0, m,n.identifierColumn),i=Object.entries(u).filter(([,t])=>t.length>1);if(i.length>0){let t=`The identifier column "${n.identifierColumn}" has duplicate values for the following rows: ${i.slice(0,10).map(([f,r])=>`${f} (${r.length})`).join(`
3
+ `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkR4IKDXM5cjs.a.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(t);m=Object.entries(u).map(([,f])=>f.sort((e,a)=>new Date(a[n.timestampColum]).getTime()-new Date(e[n.timestampColum]).getTime())[0]).filter(f=>f)}return{currentState:n,preferences:m}}async function ge(m,n,{purposeSlugs:w,preferenceTopics:d,forceTriggerWorkflows:s}){let u=_chunkY4BWTFTXcjs.j.call(void 0, m.map(c=>Object.keys(c)).flat()),i=_chunkY4BWTFTXcjs.c.call(void 0, u,[...n.identifierColumn?[n.identifierColumn]:[],...n.timestampColum?[n.timestampColum]:[]]);if(i.length===0){if(s)return n;throw new Error("No other columns to process")}let t=[...w,...d.map(c=>`${c.purpose.trackingType}->${c.slug}`)];return await _chunk3ZKZCSGDcjs.a.call(void 0, i,async c=>{let f=_chunkY4BWTFTXcjs.j.call(void 0, m.map(e=>e[c])),r=n.columnToPurposeName[c];if(r)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${c}" is associated with purpose "${r.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${c} is associated with`,type:"list",default:t.find(p=>p.startsWith(w[0])),choices:t}]),[a,g]=e.split("->");r={purpose:a,preference:g||null,valueMapping:{}}}await _chunk3ZKZCSGDcjs.a.call(void 0, f,async e=>{if(r.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${r.valueMapping[e]}"`));return}if(r.preference===null){let{purposeValue:a}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=a}if(r.preference!==null){let a=d.find(p=>p.slug===r.preference);if(!a){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${r.preference}" not found`));return}let g=a.preferenceOptionValues.map(({slug:p})=>p);if(a.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:p}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=p;return}if(a.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:p}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(h=>h===e)}]);r.valueMapping[e]=p;return}if(a.type===_privacytypes.PreferenceTopicType.MultiSelect){let p=_chunkWIXQSFS6cjs.n.call(void 0, e);await _chunk3ZKZCSGDcjs.a.call(void 0, p,async h=>{if(r.valueMapping[h]!==void 0)return;let{preferenceValue:P}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${a.slug}" value "${h}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(y=>y===h)}]);r.valueMapping[h]=P});return}throw new Error(`Unknown preference topic type: ${a.type}`)}}),n.columnToPurposeName[c]=r}),n}function he({currentConsentRecord:m,pendingUpdates:n,preferenceTopics:w}){return Object.entries(n).every(([d,{preferences:s=[],enabled:u}])=>{let i=m.purposes.find(c=>c.purpose===d);return!!i&&i.enabled===u?s.every(({topic:c,choice:f})=>i.preferences&&i.preferences.find(r=>{if(r.topic!==c)return!1;let e=w.find(a=>a.slug===c&&a.purpose.trackingType===d);if(!e)throw new Error(`Could not find preference topic for ${c}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return r.choice.booleanValue===f.booleanValue;case _privacytypes.PreferenceTopicType.Select:return r.choice.selectValue===f.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let a=(r.choice.selectValues||[]).sort(),g=(f.selectValues||[]).sort();return a.length===g.length&&a.every((p,h)=>p===g[h]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function we({currentConsentRecord:m,pendingUpdates:n,preferenceTopics:w}){return!!Object.entries(n).find(([d,{preferences:s=[],enabled:u}])=>{let i=m.purposes.find(t=>t.purpose===d);return i?i.enabled!==u?!0:!!s.find(({topic:t,choice:c})=>{let f=(i.preferences||[]).find(e=>e.topic===t);if(!f)return!1;let r=w.find(e=>e.slug===t&&e.purpose.trackingType===d);if(!r)throw new Error(`Could not find preference topic for ${t}`);switch(r.type){case _privacytypes.PreferenceTopicType.Boolean:return f.choice.booleanValue!==c.booleanValue;case _privacytypes.PreferenceTopicType.Select:return f.choice.selectValue!==c.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let e=(f.choice.selectValues||[]).sort(),a=(c.selectValues||[]).sort();return e.length!==a.length||!e.every((g,p)=>g===a[p]);default:throw new Error(`Unknown preference topic type: ${r.type}`)}}):!1})}async function Pe({file:m,sombra:n,purposeSlugs:w,preferenceTopics:d,partitionKey:s,skipExistingRecordCheck:u,forceTriggerWorkflows:i},t){let c=new Date().getTime(),f=t.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${m}"`));let r=_chunkWIXQSFS6cjs.q.call(void 0, m,A.record(A.string,A.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...f[m]||{},lastFetchedAt:new Date().toISOString()};e=await ue(r,e),f[m]=e,await t.setValue(f,"fileMetadata");let a=await de(r,e);e=a.currentState,r=a.preferences,f[m]=e,await t.setValue(f,"fileMetadata"),e=await ge(r,e,{preferenceTopics:d,purposeSlugs:w,forceTriggerWorkflows:i}),f[m]=e,await t.setValue(f,"fileMetadata");let g=r.map(y=>y[e.identifierColumn]),p=u?[]:await fe(n,{identifiers:g.map(y=>({value:y})),partitionKey:s}),h=_chunkY4BWTFTXcjs.e.call(void 0, p,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},r.forEach(y=>{let $=y[e.identifierColumn],E=Q({row:y,columnToPurposeName:e.columnToPurposeName,preferenceTopics:d,purposeSlugs:w}),U=h[$];if(i&&!U)throw new Error(`No existing consent record found for user with id: ${$}.
4
+ When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(U&&he({currentConsentRecord:U,pendingUpdates:E,preferenceTopics:d})&&!i){e.skippedUpdates[$]=y;return}if(U&&we({currentConsentRecord:U,pendingUpdates:E,preferenceTopics:d})){e.pendingConflictUpdates[$]={row:y,record:U};return}e.pendingSafeUpdates[$]=y}),f[m]=e,await t.setValue(f,"fileMetadata");let P=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${m}" in ${(P-c)/1e3}s`))}var je=o.type({purpose:o.string,preference:o.union([o.string,o.null]),valueMapping:o.record(o.string,o.union([o.string,o.boolean,o.null]))}),Ae=o.intersection([o.type({columnToPurposeName:o.record(o.string,je),lastFetchedAt:o.string,pendingSafeUpdates:o.record(o.string,o.record(o.string,o.string)),pendingConflictUpdates:o.record(o.string,o.type({record:_privacytypes.PreferenceQueryResponseItem,row:o.record(o.string,o.string)})),skippedUpdates:o.record(o.string,o.record(o.string,o.string))}),o.partial({identifierColumn:o.string,timestampColum:o.string})]),$e=o.type({fileMetadata:o.record(o.string,Ae),failingUpdates:o.record(o.string,o.type({uploadedAt:o.string,error:o.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:o.record(o.string,_privacytypes.PreferenceUpdateItem)});async function Te({auth:m,sombraAuth:n,receiptFilepath:w,file:d,partition:s,isSilent:u=!0,dryRun:i=!1,skipWorkflowTriggers:t=!1,skipConflictUpdates:c=!1,skipExistingRecordCheck:f=!1,attributes:r=[],transcendUrl:e,forceTriggerWorkflows:a=!1}){let g=_chunkWIXQSFS6cjs.p.call(void 0, r),p=new (0, _persistedstate.PersistedState)(w,$e,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),h=p.getValue("failingUpdates"),P=p.getValue("pendingUpdates"),y=p.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
5
5
  ${Object.values(h).length} failing requests to be retried
6
6
  ${Object.values(P).length} pending requests to be processed
7
7
  The following files are stored in cache and will be used:
8
8
  ${Object.keys(y).map(b=>b).join(`
9
9
  `)}
10
10
  The following file will be processed: ${d}
11
- `));let $=_chunkT66BMKXUcjs.pe.call(void 0, e,m),[E,U,X]=await Promise.all([_chunkT66BMKXUcjs.qe.call(void 0, e,m,n),a?Promise.resolve([]):_chunkT66BMKXUcjs.Qc.call(void 0, $),a?Promise.resolve([]):_chunkT66BMKXUcjs._d.call(void 0, $)]);await Pe({file:d,purposeSlugs:U.map(b=>b.trackingType),preferenceTopics:X,sombra:E,partitionKey:s,skipExistingRecordCheck:f,forceTriggerWorkflows:a},p);let x={};y=p.getValue("fileMetadata");let M=y[d];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.pendingSafeUpdates).length} safe updates in ${d}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.pendingConflictUpdates).length} conflict updates in ${d}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.skippedUpdates).length} skipped updates in ${d}`)),Object.entries({...M.pendingSafeUpdates,...c?{}:_typeutils.apply.call(void 0, M.pendingConflictUpdates,({row:b})=>b)}).forEach(([b,C])=>{let D=M.timestampColum===L?new Date:new Date(C[M.timestampColum]),R=Q({row:C,columnToPurposeName:M.columnToPurposeName,preferenceTopics:X,purposeSlugs:U.map(O=>O.trackingType)});x[b]={userId:b,partition:s,timestamp:D.toISOString(),purposes:Object.entries(R).map(([O,Re])=>({...Re,purpose:O,workflowSettings:{attributes:g,isSilent:u,skipWorkflowTrigger:t}}))}}),await p.setValue(x,"pendingUpdates"),await p.setValue({},"failingUpdates"),i){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(x).length} pending updates. Check file: ${w}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(x).length} preferences to partition: ${s}`));let Ue=new Date().getTime(),G=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),Z=0,W=Object.entries(x),ke=_chunkUM5F6R4Icjs.b.call(void 0, W,t?100:10);G.start(W.length,0),await _chunkT66BMKXUcjs.b.call(void 0, ke,async b=>{try{await E.put("v1/preferences",{json:{records:b.map(([,C])=>C),skipWorkflowTriggers:t,forceTriggerWorkflows:a}}).json()}catch(C){try{let R=JSON.parse(_optionalChain([C, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");R.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${R.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${b.length} user preferences to partition ${s}: ${_optionalChain([C, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([C, 'optionalAccess', _9 => _9.message])}`));let D=p.getValue("failingUpdates");b.forEach(([R,O])=>{D[R]={uploadedAt:new Date().toISOString(),update:O,error:_optionalChain([C, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([C, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await p.setValue(D,"failingUpdates")}Z+=b.length,G.update(Z)},{concurrency:40}),G.stop();let Me=new Date().getTime()-Ue;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${W.length} user preferences to partition ${s} in "${Me/1e3}" seconds!`))}var _fs = require('fs');var _path = require('path');async function kr({auth:m,partition:n,sombraAuth:w,transcendUrl:d,file:s="",directory:u,dryRun:i,skipExistingRecordCheck:t,receiptFileDir:c,skipWorkflowTriggers:f,forceTriggerWorkflows:r,skipConflictUpdates:e,isSilent:a,attributes:g,concurrency:p}){u&&s&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Cannot provide both a directory and a file. Please provide only one.")),this.process.exit(1)),!s&&!u&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences")),this.process.exit(1)),_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let h=[];if(u)try{let y=_fs.readdirSync.call(void 0, u).filter($=>$.endsWith(".csv"));y.length===0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`No CSV files found in directory: ${u}`)),this.process.exit(1)),h.push(...y.map($=>_path.join.call(void 0, u,$)))}catch(P){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to read directory: ${u}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(P.message)),this.process.exit(1)}else try{s.endsWith(".csv")||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("File must be a CSV file")),this.process.exit(1)),h.push(s)}catch(P){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to access file: ${s}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(P.message)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Processing ${h.length} consent preferences files for partition: ${n}`)),_chunkZUNVPK23cjs.a.debug(`Files to process: ${h.join(", ")}`),t&&_chunkZUNVPK23cjs.a.info(_colors2.default.bgYellow(`Skipping existing record check: ${t}`)),await _chunkT66BMKXUcjs.b.call(void 0, h,async P=>{let y=_path.basename.call(void 0, P).replace(".csv","");await Te({receiptFilepath:_path.join.call(void 0, c,`${y}-receipts.json`),auth:m,sombraAuth:w,file:P,partition:n,transcendUrl:d,skipConflictUpdates:e,skipWorkflowTriggers:f,skipExistingRecordCheck:t,isSilent:a,dryRun:i,attributes:_chunkDFOLIGJPcjs.n.call(void 0, g),forceTriggerWorkflows:r})},{concurrency:p})}exports.uploadPreferences = kr;
12
- //# sourceMappingURL=impl-KHC6VQQ3.cjs.map
11
+ `));let $=_chunk3ZKZCSGDcjs.qe.call(void 0, e,m),[E,U,X]=await Promise.all([_chunk3ZKZCSGDcjs.re.call(void 0, e,m,n),a?Promise.resolve([]):_chunk3ZKZCSGDcjs.Rc.call(void 0, $),a?Promise.resolve([]):_chunk3ZKZCSGDcjs.$d.call(void 0, $)]);await Pe({file:d,purposeSlugs:U.map(b=>b.trackingType),preferenceTopics:X,sombra:E,partitionKey:s,skipExistingRecordCheck:f,forceTriggerWorkflows:a},p);let x={};y=p.getValue("fileMetadata");let M=y[d];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.pendingSafeUpdates).length} safe updates in ${d}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.pendingConflictUpdates).length} conflict updates in ${d}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(M.skippedUpdates).length} skipped updates in ${d}`)),Object.entries({...M.pendingSafeUpdates,...c?{}:_typeutils.apply.call(void 0, M.pendingConflictUpdates,({row:b})=>b)}).forEach(([b,C])=>{let D=M.timestampColum===L?new Date:new Date(C[M.timestampColum]),R=Q({row:C,columnToPurposeName:M.columnToPurposeName,preferenceTopics:X,purposeSlugs:U.map(O=>O.trackingType)});x[b]={userId:b,partition:s,timestamp:D.toISOString(),purposes:Object.entries(R).map(([O,Re])=>({...Re,purpose:O,workflowSettings:{attributes:g,isSilent:u,skipWorkflowTrigger:t}}))}}),await p.setValue(x,"pendingUpdates"),await p.setValue({},"failingUpdates"),i){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(x).length} pending updates. Check file: ${w}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(x).length} preferences to partition: ${s}`));let Ue=new Date().getTime(),G=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),Z=0,W=Object.entries(x),ke=_chunkY4BWTFTXcjs.b.call(void 0, W,t?100:10);G.start(W.length,0),await _chunk3ZKZCSGDcjs.b.call(void 0, ke,async b=>{try{await E.put("v1/preferences",{json:{records:b.map(([,C])=>C),skipWorkflowTriggers:t,forceTriggerWorkflows:a}}).json()}catch(C){try{let R=JSON.parse(_optionalChain([C, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");R.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${R.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${b.length} user preferences to partition ${s}: ${_optionalChain([C, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([C, 'optionalAccess', _9 => _9.message])}`));let D=p.getValue("failingUpdates");b.forEach(([R,O])=>{D[R]={uploadedAt:new Date().toISOString(),update:O,error:_optionalChain([C, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([C, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await p.setValue(D,"failingUpdates")}Z+=b.length,G.update(Z)},{concurrency:40}),G.stop();let Me=new Date().getTime()-Ue;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${W.length} user preferences to partition ${s} in "${Me/1e3}" seconds!`))}var _fs = require('fs');var _path = require('path');async function kr({auth:m,partition:n,sombraAuth:w,transcendUrl:d,file:s="",directory:u,dryRun:i,skipExistingRecordCheck:t,receiptFileDir:c,skipWorkflowTriggers:f,forceTriggerWorkflows:r,skipConflictUpdates:e,isSilent:a,attributes:g,concurrency:p}){u&&s&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Cannot provide both a directory and a file. Please provide only one.")),this.process.exit(1)),!s&&!u&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences")),this.process.exit(1)),_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let h=[];if(u)try{let y=_fs.readdirSync.call(void 0, u).filter($=>$.endsWith(".csv"));y.length===0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`No CSV files found in directory: ${u}`)),this.process.exit(1)),h.push(...y.map($=>_path.join.call(void 0, u,$)))}catch(P){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to read directory: ${u}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(P.message)),this.process.exit(1)}else try{s.endsWith(".csv")||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("File must be a CSV file")),this.process.exit(1)),h.push(s)}catch(P){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to access file: ${s}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(P.message)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Processing ${h.length} consent preferences files for partition: ${n}`)),_chunkZUNVPK23cjs.a.debug(`Files to process: ${h.join(", ")}`),t&&_chunkZUNVPK23cjs.a.info(_colors2.default.bgYellow(`Skipping existing record check: ${t}`)),await _chunk3ZKZCSGDcjs.b.call(void 0, h,async P=>{let y=_path.basename.call(void 0, P).replace(".csv","");await Te({receiptFilepath:_path.join.call(void 0, c,`${y}-receipts.json`),auth:m,sombraAuth:w,file:P,partition:n,transcendUrl:d,skipConflictUpdates:e,skipWorkflowTriggers:f,skipExistingRecordCheck:t,isSilent:a,dryRun:i,attributes:_chunkWIXQSFS6cjs.n.call(void 0, g),forceTriggerWorkflows:r})},{concurrency:p})}exports.uploadPreferences = kr;
12
+ //# sourceMappingURL=impl-MPGDZ2M2.cjs.map