@transcend-io/cli 8.32.4 → 8.32.7

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 (121) hide show
  1. package/README.md +46 -46
  2. package/dist/bin/bash-complete.cjs +1 -1
  3. package/dist/bin/cli.cjs +1 -1
  4. package/dist/bin/deprecated-command.cjs +2 -2
  5. package/dist/{chunk-22KX2NM4.cjs → chunk-4GILGOAM.cjs} +4 -4
  6. package/dist/{chunk-22KX2NM4.cjs.map → chunk-4GILGOAM.cjs.map} +1 -1
  7. package/dist/{chunk-PGO2YKRX.cjs → chunk-4NEO6Q2F.cjs} +2 -2
  8. package/dist/{chunk-PGO2YKRX.cjs.map → chunk-4NEO6Q2F.cjs.map} +1 -1
  9. package/dist/{chunk-DYBVUGHH.cjs → chunk-4OEVQFNG.cjs} +21 -21
  10. package/dist/{chunk-DYBVUGHH.cjs.map → chunk-4OEVQFNG.cjs.map} +1 -1
  11. package/dist/{chunk-DQCPGPXG.cjs → chunk-5MG2CEZV.cjs} +2 -2
  12. package/dist/{chunk-DQCPGPXG.cjs.map → chunk-5MG2CEZV.cjs.map} +1 -1
  13. package/dist/{chunk-CM7VJEOY.cjs → chunk-ATEDOYYC.cjs} +2 -2
  14. package/dist/{chunk-CM7VJEOY.cjs.map → chunk-ATEDOYYC.cjs.map} +1 -1
  15. package/dist/{chunk-VUQAH7YK.cjs → chunk-EMLESF76.cjs} +6 -6
  16. package/dist/{chunk-VUQAH7YK.cjs.map → chunk-EMLESF76.cjs.map} +1 -1
  17. package/dist/{chunk-VCPZG4FJ.cjs → chunk-ETSLJPTD.cjs} +2 -2
  18. package/dist/{chunk-VCPZG4FJ.cjs.map → chunk-ETSLJPTD.cjs.map} +1 -1
  19. package/dist/{chunk-LQUVB4MI.cjs → chunk-GCTE43TS.cjs} +4 -4
  20. package/dist/{chunk-LQUVB4MI.cjs.map → chunk-GCTE43TS.cjs.map} +1 -1
  21. package/dist/{chunk-IHUCIK5T.cjs → chunk-H3EBIKX6.cjs} +2 -2
  22. package/dist/{chunk-IHUCIK5T.cjs.map → chunk-H3EBIKX6.cjs.map} +1 -1
  23. package/dist/{chunk-D3VRD5F5.cjs → chunk-HZU3YROT.cjs} +2 -2
  24. package/dist/{chunk-D3VRD5F5.cjs.map → chunk-HZU3YROT.cjs.map} +1 -1
  25. package/dist/{chunk-6TKTYQIF.cjs → chunk-ILBF5XZN.cjs} +2 -2
  26. package/dist/{chunk-6TKTYQIF.cjs.map → chunk-ILBF5XZN.cjs.map} +1 -1
  27. package/dist/{chunk-BPOXNSPY.cjs → chunk-JRYG6ZXI.cjs} +2 -2
  28. package/dist/{chunk-BPOXNSPY.cjs.map → chunk-JRYG6ZXI.cjs.map} +1 -1
  29. package/dist/{chunk-56QKBG2R.cjs → chunk-KYOQWIIS.cjs} +4 -4
  30. package/dist/{chunk-56QKBG2R.cjs.map → chunk-KYOQWIIS.cjs.map} +1 -1
  31. package/dist/{chunk-P5GD5LAK.cjs → chunk-ZNTCC7Y7.cjs} +2 -2
  32. package/dist/{chunk-P5GD5LAK.cjs.map → chunk-ZNTCC7Y7.cjs.map} +1 -1
  33. package/dist/{impl-SSBP4ONX.cjs → impl-2NLTX2DX.cjs} +2 -2
  34. package/dist/{impl-SSBP4ONX.cjs.map → impl-2NLTX2DX.cjs.map} +1 -1
  35. package/dist/{impl-LKX6OLE2.cjs → impl-2Z37FQLH.cjs} +2 -2
  36. package/dist/{impl-LKX6OLE2.cjs.map → impl-2Z37FQLH.cjs.map} +1 -1
  37. package/dist/{impl-X23VUODX.cjs → impl-3G7CA7V7.cjs} +2 -2
  38. package/dist/{impl-X23VUODX.cjs.map → impl-3G7CA7V7.cjs.map} +1 -1
  39. package/dist/{impl-RMPDHVAH.cjs → impl-43DHFRH3.cjs} +2 -2
  40. package/dist/{impl-RMPDHVAH.cjs.map → impl-43DHFRH3.cjs.map} +1 -1
  41. package/dist/{impl-J5PWNHKL.cjs → impl-4GESIKYG.cjs} +2 -2
  42. package/dist/{impl-J5PWNHKL.cjs.map → impl-4GESIKYG.cjs.map} +1 -1
  43. package/dist/{impl-NW57RBBR.cjs → impl-4LNG6EWX.cjs} +2 -2
  44. package/dist/{impl-NW57RBBR.cjs.map → impl-4LNG6EWX.cjs.map} +1 -1
  45. package/dist/{impl-GZNNNSYW.cjs → impl-5BSN73TG.cjs} +4 -4
  46. package/dist/{impl-GZNNNSYW.cjs.map → impl-5BSN73TG.cjs.map} +1 -1
  47. package/dist/{impl-4AI7T6RD.cjs → impl-AB7CBUNN.cjs} +2 -2
  48. package/dist/{impl-4AI7T6RD.cjs.map → impl-AB7CBUNN.cjs.map} +1 -1
  49. package/dist/{impl-GA6T4SCB.cjs → impl-ANZ5Q2QW.cjs} +2 -2
  50. package/dist/{impl-GA6T4SCB.cjs.map → impl-ANZ5Q2QW.cjs.map} +1 -1
  51. package/dist/{impl-S64WVKSC.cjs → impl-B2KHIHOI.cjs} +2 -2
  52. package/dist/{impl-S64WVKSC.cjs.map → impl-B2KHIHOI.cjs.map} +1 -1
  53. package/dist/{impl-WVOFYJLG.cjs → impl-BCRCUBC6.cjs} +2 -2
  54. package/dist/{impl-WVOFYJLG.cjs.map → impl-BCRCUBC6.cjs.map} +1 -1
  55. package/dist/{impl-SE32ARTN.cjs → impl-BFSM3FLJ.cjs} +2 -2
  56. package/dist/{impl-SE32ARTN.cjs.map → impl-BFSM3FLJ.cjs.map} +1 -1
  57. package/dist/{impl-UA7V6YEM.cjs → impl-C3RL4PL5.cjs} +2 -2
  58. package/dist/{impl-UA7V6YEM.cjs.map → impl-C3RL4PL5.cjs.map} +1 -1
  59. package/dist/{impl-IOS3QLTX.cjs → impl-C3YOETUJ.cjs} +2 -2
  60. package/dist/{impl-IOS3QLTX.cjs.map → impl-C3YOETUJ.cjs.map} +1 -1
  61. package/dist/{impl-2JA6BPE7.cjs → impl-CUQGOWYL.cjs} +2 -2
  62. package/dist/{impl-2JA6BPE7.cjs.map → impl-CUQGOWYL.cjs.map} +1 -1
  63. package/dist/{impl-JY7YM3QH.cjs → impl-CWWJOV4W.cjs} +2 -2
  64. package/dist/{impl-JY7YM3QH.cjs.map → impl-CWWJOV4W.cjs.map} +1 -1
  65. package/dist/{impl-QPLTL2SO.cjs → impl-D27XUTVP.cjs} +2 -2
  66. package/dist/{impl-QPLTL2SO.cjs.map → impl-D27XUTVP.cjs.map} +1 -1
  67. package/dist/{impl-MRC5UI22.cjs → impl-D6D7MZ4F.cjs} +2 -2
  68. package/dist/{impl-MRC5UI22.cjs.map → impl-D6D7MZ4F.cjs.map} +1 -1
  69. package/dist/{impl-Z54SB7SM.cjs → impl-EOWKDUEB.cjs} +2 -2
  70. package/dist/{impl-Z54SB7SM.cjs.map → impl-EOWKDUEB.cjs.map} +1 -1
  71. package/dist/impl-EQL4NORJ.cjs +2 -0
  72. package/dist/{impl-JI6COVDW.cjs.map → impl-EQL4NORJ.cjs.map} +1 -1
  73. package/dist/{impl-4YFJOKCA.cjs → impl-FAE3G5FE.cjs} +2 -2
  74. package/dist/{impl-4YFJOKCA.cjs.map → impl-FAE3G5FE.cjs.map} +1 -1
  75. package/dist/{impl-WTGAAEUZ.cjs → impl-FVEGOBQM.cjs} +2 -2
  76. package/dist/{impl-WTGAAEUZ.cjs.map → impl-FVEGOBQM.cjs.map} +1 -1
  77. package/dist/{impl-66CDS7IN.cjs → impl-HNWZZEKE.cjs} +2 -2
  78. package/dist/{impl-66CDS7IN.cjs.map → impl-HNWZZEKE.cjs.map} +1 -1
  79. package/dist/{impl-IQGUF37H.cjs → impl-JJ56CQTW.cjs} +2 -2
  80. package/dist/{impl-IQGUF37H.cjs.map → impl-JJ56CQTW.cjs.map} +1 -1
  81. package/dist/{impl-XYHIS7X5.cjs → impl-JNDENIQD.cjs} +2 -2
  82. package/dist/{impl-XYHIS7X5.cjs.map → impl-JNDENIQD.cjs.map} +1 -1
  83. package/dist/{impl-DA7AASRR.cjs → impl-JOK5WPTD.cjs} +2 -2
  84. package/dist/{impl-DA7AASRR.cjs.map → impl-JOK5WPTD.cjs.map} +1 -1
  85. package/dist/{impl-4LAJNPQ4.cjs → impl-KJTD4WO2.cjs} +3 -3
  86. package/dist/{impl-4LAJNPQ4.cjs.map → impl-KJTD4WO2.cjs.map} +1 -1
  87. package/dist/{impl-B6DTQRYV.cjs → impl-KRMOTRYI.cjs} +2 -2
  88. package/dist/{impl-B6DTQRYV.cjs.map → impl-KRMOTRYI.cjs.map} +1 -1
  89. package/dist/{impl-ZTEP5CYM.cjs → impl-LX4ZUDUY.cjs} +2 -2
  90. package/dist/{impl-ZTEP5CYM.cjs.map → impl-LX4ZUDUY.cjs.map} +1 -1
  91. package/dist/{impl-FRWZLZ2V.cjs → impl-MBWE7OAC.cjs} +2 -2
  92. package/dist/{impl-FRWZLZ2V.cjs.map → impl-MBWE7OAC.cjs.map} +1 -1
  93. package/dist/{impl-Y3MY5EKD.cjs → impl-O4WDS4V2.cjs} +2 -2
  94. package/dist/{impl-Y3MY5EKD.cjs.map → impl-O4WDS4V2.cjs.map} +1 -1
  95. package/dist/{impl-5RX3NB6C.cjs → impl-PISNT2E4.cjs} +2 -2
  96. package/dist/{impl-5RX3NB6C.cjs.map → impl-PISNT2E4.cjs.map} +1 -1
  97. package/dist/{impl-GG3S2VBT.cjs → impl-PS3WRA65.cjs} +2 -2
  98. package/dist/{impl-GG3S2VBT.cjs.map → impl-PS3WRA65.cjs.map} +1 -1
  99. package/dist/{impl-R35FW4U7.cjs → impl-TBYACXLK.cjs} +5 -5
  100. package/dist/{impl-R35FW4U7.cjs.map → impl-TBYACXLK.cjs.map} +1 -1
  101. package/dist/{impl-XU54KM62.cjs → impl-TD5BKXIH.cjs} +2 -2
  102. package/dist/{impl-XU54KM62.cjs.map → impl-TD5BKXIH.cjs.map} +1 -1
  103. package/dist/{impl-EXHOBCQW.cjs → impl-VBS6LHXD.cjs} +2 -2
  104. package/dist/{impl-EXHOBCQW.cjs.map → impl-VBS6LHXD.cjs.map} +1 -1
  105. package/dist/impl-WPM2STGX.cjs +2 -0
  106. package/dist/{impl-QOCEM2K5.cjs.map → impl-WPM2STGX.cjs.map} +1 -1
  107. package/dist/{impl-YIPC6MAR.cjs → impl-WQF6YIDK.cjs} +3 -3
  108. package/dist/{impl-YIPC6MAR.cjs.map → impl-WQF6YIDK.cjs.map} +1 -1
  109. package/dist/{impl-ADPBEB3N.cjs → impl-WWYWKXMK.cjs} +2 -2
  110. package/dist/{impl-ADPBEB3N.cjs.map → impl-WWYWKXMK.cjs.map} +1 -1
  111. package/dist/{impl-IZIXOMMN.cjs → impl-Y5TP56IB.cjs} +2 -2
  112. package/dist/{impl-IZIXOMMN.cjs.map → impl-Y5TP56IB.cjs.map} +1 -1
  113. package/dist/{impl-BLGX7DMN.cjs → impl-YOSAEFO2.cjs} +3 -3
  114. package/dist/{impl-BLGX7DMN.cjs.map → impl-YOSAEFO2.cjs.map} +1 -1
  115. package/dist/{impl-BHA2L6BP.cjs → impl-ZIBUPJJN.cjs} +2 -2
  116. package/dist/{impl-BHA2L6BP.cjs.map → impl-ZIBUPJJN.cjs.map} +1 -1
  117. package/dist/index.cjs +3 -3
  118. package/dist/index.d.cts +1 -1
  119. package/package.json +1 -1
  120. package/dist/impl-JI6COVDW.cjs +0 -2
  121. package/dist/impl-QOCEM2K5.cjs +0 -2
@@ -1,4 +1,4 @@
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 _chunk56QKBG2Rcjs = require('./chunk-56QKBG2R.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDQCPGPXGcjs = require('./chunk-DQCPGPXG.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _graphqlrequest = require('graphql-request');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function q(u,{dataSiloIds:e=[],includeGuessedCategories:l,includeAttributes:a,parentCategories:c=[],subCategories:t=[],pageSize:p=1e3}={}){let n=[],m=new Date().getTime(),d=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),s={...c.length>0?{category:c}:{},...t.length>0?{subCategoryIds:t}:{},...c.length+t.length>0&&!l?{status:_privacytypes.SubDataPointDataSubCategoryGuessStatus.Approved}:{},...e.length>0?{dataSilos:e}:{}},{subDataPoints:{totalCount:o}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_chunk56QKBG2Rcjs.f,{filterBy:s});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("[Step 1/3] Pulling in all subdatapoints")),d.start(o,0);let y=0,D=!1,r,b=0;do try{let{subDataPoints:{nodes:P}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_graphqlrequest.gql`
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 _chunkKYOQWIIScjs = require('./chunk-KYOQWIIS.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunk5MG2CEZVcjs = require('./chunk-5MG2CEZV.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _graphqlrequest = require('graphql-request');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function q(u,{dataSiloIds:e=[],includeGuessedCategories:l,includeAttributes:a,parentCategories:c=[],subCategories:t=[],pageSize:p=1e3}={}){let n=[],m=new Date().getTime(),d=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),s={...c.length>0?{category:c}:{},...t.length>0?{subCategoryIds:t}:{},...c.length+t.length>0&&!l?{status:_privacytypes.SubDataPointDataSubCategoryGuessStatus.Approved}:{},...e.length>0?{dataSilos:e}:{}},{subDataPoints:{totalCount:o}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_chunkKYOQWIIScjs.f,{filterBy:s});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("[Step 1/3] Pulling in all subdatapoints")),d.start(o,0);let y=0,D=!1,r,b=0;do try{let{subDataPoints:{nodes:P}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_graphqlrequest.gql`
2
2
  query TranscendCliSubDataPointCsvExport(
3
3
  $filterBy: SubDataPointFiltersInput
4
4
  $first: Int!
@@ -41,7 +41,7 @@
41
41
  }
42
42
  }
43
43
  }
44
- `,{first:p,offset:b,filterBy:{...s}});r=_optionalChain([P, 'access', _2 => _2[P.length-1], 'optionalAccess', _3 => _3.id]),n.push(...P),D=P.length===p,y+=P.length,b+=P.length,d.update(y)}catch(P){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for cursor ${r} and offset ${b}`)),P}while(D);d.stop();let C=new Date().getTime()-m,g=_chunkDQCPGPXGcjs.g.call(void 0, n,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${g.length} subdatapoints in ${C/1e3} seconds!`)),g}async function F(u,{dataPointIds:e=[],pageSize:l=100}){let a=[],c=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`[Step 2/3] Fetching metadata for ${e.length} datapoints`));let p=_chunkDQCPGPXGcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _chunk56QKBG2Rcjs.b.call(void 0, p,async s=>{try{let{dataPoints:{nodes:o}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_chunk56QKBG2Rcjs.i,{first:l,filterBy:{ids:s}});a.push(...o),n+=s.length,t.update(n)}catch(o){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for IDs ${s.join(", ")}`)),o}}),t.stop();let d=new Date().getTime()-c;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${a.length} dataPoints in ${d/1e3} seconds!`)),a}async function Q(u,{dataSiloIds:e=[],pageSize:l=100}){let a=[],c=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`[Step 3/3] Fetching metadata for ${e.length} data silos`));let p=_chunkDQCPGPXGcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _chunk56QKBG2Rcjs.b.call(void 0, p,async s=>{try{let{dataSilos:{nodes:o}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_chunk56QKBG2Rcjs.l,{first:l,filterBy:{ids:s}});a.push(...o),n+=s.length,t.update(n)}catch(o){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching data silos for IDs ${s.join(", ")}`)),o}}),t.stop();let d=new Date().getTime()-c;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${a.length} data silos in ${d/1e3} seconds!`)),a}async function Y(u,{dataSiloIds:e=[],includeGuessedCategories:l,includeAttributes:a,parentCategories:c=[],subCategories:t=[],pageSize:p=1e3}={}){let n=await q(u,{dataSiloIds:e,includeGuessedCategories:l,includeAttributes:a,parentCategories:c,subCategories:t,pageSize:p}),m=_chunkDQCPGPXGcjs.j.call(void 0, n.map(r=>r.dataPointId)),d=await F(u,{dataPointIds:m}),s=_chunkDQCPGPXGcjs.e.call(void 0, d,"id"),o=_chunkDQCPGPXGcjs.j.call(void 0, n.map(r=>r.dataSiloId)),y=await Q(u,{dataSiloIds:o}),D=_chunkDQCPGPXGcjs.e.call(void 0, y,"id");return n.map(r=>({...r,dataPoint:s[r.dataPointId],dataSilo:D[r.dataSiloId]}))}async function nt(u,{dataSiloIds:e=[],status:l,subCategories:a=[],includeEncryptedSnippets:c,pageSize:t=100}={}){let p=[],n=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),d={...a.length>0?{subCategoryIds:a}:{},...l?{status:l}:{},...e.length>0?{dataSilos:e}:{}},{unstructuredSubDataPointRecommendations:{totalCount:s}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_chunk56QKBG2Rcjs.j,{filterBy:d});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("[Step 1/3] Pulling in all subdatapoints")),m.start(s,0);let o=0,y=!1,D,r=0;do try{let{unstructuredSubDataPointRecommendations:{nodes:g}}=await _chunk56QKBG2Rcjs.wg.call(void 0, u,_graphqlrequest.gql`
44
+ `,{first:p,offset:b,filterBy:{...s}});r=_optionalChain([P, 'access', _2 => _2[P.length-1], 'optionalAccess', _3 => _3.id]),n.push(...P),D=P.length===p,y+=P.length,b+=P.length,d.update(y)}catch(P){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for cursor ${r} and offset ${b}`)),P}while(D);d.stop();let C=new Date().getTime()-m,g=_chunk5MG2CEZVcjs.g.call(void 0, n,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${g.length} subdatapoints in ${C/1e3} seconds!`)),g}async function F(u,{dataPointIds:e=[],pageSize:l=100}){let a=[],c=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`[Step 2/3] Fetching metadata for ${e.length} datapoints`));let p=_chunk5MG2CEZVcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _chunkKYOQWIIScjs.b.call(void 0, p,async s=>{try{let{dataPoints:{nodes:o}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_chunkKYOQWIIScjs.i,{first:l,filterBy:{ids:s}});a.push(...o),n+=s.length,t.update(n)}catch(o){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for IDs ${s.join(", ")}`)),o}}),t.stop();let d=new Date().getTime()-c;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${a.length} dataPoints in ${d/1e3} seconds!`)),a}async function Q(u,{dataSiloIds:e=[],pageSize:l=100}){let a=[],c=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`[Step 3/3] Fetching metadata for ${e.length} data silos`));let p=_chunk5MG2CEZVcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _chunkKYOQWIIScjs.b.call(void 0, p,async s=>{try{let{dataSilos:{nodes:o}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_chunkKYOQWIIScjs.l,{first:l,filterBy:{ids:s}});a.push(...o),n+=s.length,t.update(n)}catch(o){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching data silos for IDs ${s.join(", ")}`)),o}}),t.stop();let d=new Date().getTime()-c;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${a.length} data silos in ${d/1e3} seconds!`)),a}async function Y(u,{dataSiloIds:e=[],includeGuessedCategories:l,includeAttributes:a,parentCategories:c=[],subCategories:t=[],pageSize:p=1e3}={}){let n=await q(u,{dataSiloIds:e,includeGuessedCategories:l,includeAttributes:a,parentCategories:c,subCategories:t,pageSize:p}),m=_chunk5MG2CEZVcjs.j.call(void 0, n.map(r=>r.dataPointId)),d=await F(u,{dataPointIds:m}),s=_chunk5MG2CEZVcjs.e.call(void 0, d,"id"),o=_chunk5MG2CEZVcjs.j.call(void 0, n.map(r=>r.dataSiloId)),y=await Q(u,{dataSiloIds:o}),D=_chunk5MG2CEZVcjs.e.call(void 0, y,"id");return n.map(r=>({...r,dataPoint:s[r.dataPointId],dataSilo:D[r.dataSiloId]}))}async function nt(u,{dataSiloIds:e=[],status:l,subCategories:a=[],includeEncryptedSnippets:c,pageSize:t=100}={}){let p=[],n=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),d={...a.length>0?{subCategoryIds:a}:{},...l?{status:l}:{},...e.length>0?{dataSilos:e}:{}},{unstructuredSubDataPointRecommendations:{totalCount:s}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_chunkKYOQWIIScjs.j,{filterBy:d});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("[Step 1/3] Pulling in all subdatapoints")),m.start(s,0);let o=0,y=!1,D,r=0;do try{let{unstructuredSubDataPointRecommendations:{nodes:g}}=await _chunkKYOQWIIScjs.wg.call(void 0, u,_graphqlrequest.gql`
45
45
  query TranscendCliUnstructuredSubDataPointRecommendationCsvExport(
46
46
  $filterBy: UnstructuredSubDataPointRecommendationsFilterInput
47
47
  $first: Int!
@@ -71,5 +71,5 @@
71
71
  }
72
72
  }
73
73
  }
74
- `,{first:t,offset:r,filterBy:{...d}});D=_optionalChain([g, 'access', _4 => _4[g.length-1], 'optionalAccess', _5 => _5.id]),p.push(...g),y=g.length===t,o+=g.length,r+=g.length,m.update(o)}catch(g){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for cursor ${D} and offset ${r}`)),g}while(y);m.stop();let R=new Date().getTime()-n,C=_chunkDQCPGPXGcjs.g.call(void 0, p,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${C.length} subdatapoints in ${R/1e3} seconds!`)),C}exports.a = Y; exports.b = nt;
75
- //# sourceMappingURL=chunk-LQUVB4MI.cjs.map
74
+ `,{first:t,offset:r,filterBy:{...d}});D=_optionalChain([g, 'access', _4 => _4[g.length-1], 'optionalAccess', _5 => _5.id]),p.push(...g),y=g.length===t,o+=g.length,r+=g.length,m.update(o)}catch(g){throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`An error fetching subdatapoints for cursor ${D} and offset ${r}`)),g}while(y);m.stop();let R=new Date().getTime()-n,C=_chunk5MG2CEZVcjs.g.call(void 0, p,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${C.length} subdatapoints in ${R/1e3} seconds!`)),C}exports.a = Y; exports.b = nt;
75
+ //# sourceMappingURL=chunk-GCTE43TS.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-LQUVB4MI.cjs","../src/lib/data-inventory/pullAllDatapoints.ts","../src/lib/data-inventory/pullUnstructuredSubDataPointRecommendations.ts"],"names":["pullSubDatapoints","client","dataSiloIds","includeGuessedCategories","includeAttributes","parentCategories","subCategories","pageSize","subDataPoints","t0","progressBar","cliProgress","filterBy","SubDataPointDataSubCategoryGuessStatus","totalCount","makeGraphQLRequest","SUB_DATA_POINTS_COUNT","logger","colors","total","shouldContinue","cursor","offset","nodes","gql","err"],"mappings":"AAAA,quBAA4E,wDAAyC,wDAA8D,2DCK5K,qGACiB,iDACJ,gFACD,MAkFnB,SAAeA,CAAAA,CACbC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAC,CAAA,CACf,wBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CAAmB,CAAC,CAAA,CACpB,aAAA,CAAAC,CAAAA,CAAgB,CAAC,CAAA,CACjB,QAAA,CAAAC,CAAAA,CAAW,GACb,CAAA,CAGI,CAAC,CAAA,CAC8B,CACnC,IAAMC,CAAAA,CAA0C,CAAC,CAAA,CAG3CC,CAAAA,CAAK,IAAI,IAAA,CAAK,CAAA,CAAE,OAAA,CAAQ,CAAA,CAGxBC,CAAAA,CAAc,IAAIC,qBAAAA,CAAY,SAAA,CAClC,CAAC,CAAA,CACDA,qBAAAA,CAAY,OAAA,CAAQ,cACtB,CAAA,CAGMC,CAAAA,CAAW,CACf,GAAIP,CAAAA,CAAiB,MAAA,CAAS,CAAA,CAAI,CAAE,QAAA,CAAUA,CAAiB,CAAA,CAAI,CAAC,CAAA,CACpE,GAAIC,CAAAA,CAAc,MAAA,CAAS,CAAA,CAAI,CAAE,cAAA,CAAgBA,CAAc,CAAA,CAAI,CAAC,CAAA,CAEpE,GAAID,CAAAA,CAAiB,MAAA,CAASC,CAAAA,CAAc,MAAA,CAAS,CAAA,EACrD,CAACH,CAAAA,CAEG,CAAE,MAAA,CAAQU,oDAAAA,CAAuC,QAAS,CAAA,CAC1D,CAAC,CAAA,CACL,GAAIX,CAAAA,CAAY,MAAA,CAAS,CAAA,CAAI,CAAE,SAAA,CAAWA,CAAY,CAAA,CAAI,CAAC,CAC7D,CAAA,CAGM,CACJ,aAAA,CAAe,CAAE,UAAA,CAAAY,CAAW,CAC9B,CAAA,CAAI,MAAMC,kCAAAA,CAMPd,CAAQe,mBAAAA,CAAuB,CAChC,QAAA,CAAAJ,CACF,CAAC,CAAA,CAEDK,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,yCAAyC,CAAC,CAAA,CAErER,CAAAA,CAAY,KAAA,CAAMI,CAAAA,CAAY,CAAC,CAAA,CAC/B,IAAIK,CAAAA,CAAQ,CAAA,CACRC,CAAAA,CAAiB,CAAA,CAAA,CACjBC,CAAAA,CACAC,CAAAA,CAAS,CAAA,CACb,GACE,GAAI,CACF,GAAM,CACJ,aAAA,CAAe,CAAE,KAAA,CAAAC,CAAM,CACzB,CAAA,CAAI,MAAMR,kCAAAA,CAORd,CACAuB,mBAAAA,CAAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAA,EA2BUrB,CAAAA,CACI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAA,CAAA,CAQA,EACN,CAAA;AAAA,gBAAA,EAEEC,CAAAA,CACI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAA,CAAA,CAMA,EACN,CAAA;AAAA;AAAA;AAAA;AAAA,QAAA,CAAA,CAKR,CACE,KAAA,CAAOG,CAAAA,CACP,MAAA,CAAAe,CAAAA,CACA,QAAA,CAAU,CACR,GAAGV,CAGL,CACF,CACF,CAAA,CAEAS,CAAAA,iBAASE,CAAAA,qBAAMA,CAAAA,CAAM,MAAA,CAAS,CAAC,CAAA,6BAAG,IAAA,CAClCf,CAAAA,CAAc,IAAA,CAAK,GAAGe,CAAK,CAAA,CAC3BH,CAAAA,CAAiBG,CAAAA,CAAM,MAAA,GAAWhB,CAAAA,CAClCY,CAAAA,EAASI,CAAAA,CAAM,MAAA,CACfD,CAAAA,EAAUC,CAAAA,CAAM,MAAA,CAChBb,CAAAA,CAAY,MAAA,CAAOS,CAAK,CAC1B,CAAA,KAAA,CAASM,CAAAA,CAAK,CACZ,MAAAR,mBAAAA,CAAO,KAAA,CACLC,gBAAAA,CAAO,GAAA,CACL,CAAA,2CAAA,EAA8CG,CAAM,CAAA,YAAA,EAAeC,CAAM,CAAA,CAAA;AC7G3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBgD,gBAAA;AACU,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BiB,QAAA","file":"/home/runner/work/cli/cli/dist/chunk-LQUVB4MI.cjs","sourcesContent":[null,"/* eslint-disable max-lines */\nimport { keyBy, uniq, chunk, sortBy } from 'lodash-es';\nimport {\n type DataCategoryType,\n SubDataPointDataSubCategoryGuessStatus,\n} from '@transcend-io/privacy-types';\nimport cliProgress from 'cli-progress';\nimport { gql } from 'graphql-request';\nimport colors from 'colors';\nimport type { GraphQLClient } from 'graphql-request';\nimport {\n DATAPOINT_EXPORT,\n DATA_SILO_EXPORT,\n type DataSiloAttributeValue,\n SUB_DATA_POINTS_COUNT,\n makeGraphQLRequest,\n} from '../graphql';\nimport { logger } from '../../logger';\nimport type { DataCategoryInput, ProcessingPurposeInput } from '../../codecs';\nimport { mapSeries } from '../bluebird';\n\nexport interface DataSiloCsvPreview {\n /** ID of dataSilo */\n id: string;\n /** Name of dataSilo */\n title: string;\n}\n\nexport interface DataPointCsvPreview {\n /** ID of dataPoint */\n id: string;\n /** The path to this data point */\n path: string[];\n /** Description */\n description: {\n /** Default message */\n defaultMessage: string;\n };\n /** Name */\n name: string;\n}\n\nexport interface SubDataPointCsvPreview {\n /** ID of subDatapoint */\n id: string;\n /** Name (or key) of the subdatapoint */\n name: string;\n /** The description */\n description?: string;\n /** Personal data category */\n categories: DataCategoryInput[];\n /** Data point ID */\n dataPointId: string;\n /** The data silo ID */\n dataSiloId: string;\n /** The processing purpose for this sub datapoint */\n purposes: ProcessingPurposeInput[];\n /** Attribute attached to subdatapoint */\n attributeValues?: DataSiloAttributeValue[];\n /** Data category guesses that are output by the classifier */\n pendingCategoryGuesses?: {\n /** Data category being guessed */\n category: DataCategoryInput;\n /** Status of guess */\n status: SubDataPointDataSubCategoryGuessStatus;\n /** classifier version that produced the guess */\n classifierVersion: number;\n }[];\n}\n\nexport interface DatapointFilterOptions {\n /** IDs of data silos to filter down */\n dataSiloIds?: string[];\n /** Whether to include guessed categories, defaults to only approved categories */\n includeGuessedCategories?: boolean;\n /** Whether or not to include attributes */\n includeAttributes?: boolean;\n /** Parent categories to filter down for */\n parentCategories?: DataCategoryType[];\n /** Sub categories to filter down for */\n subCategories?: string[]; // TODO: https://transcend.height.app/T-40482 - do by name not ID\n}\n\n/**\n * Pull subdatapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The subdatapoints\n */\nasync function pullSubDatapoints(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n includeGuessedCategories,\n includeAttributes,\n parentCategories = [],\n subCategories = [],\n pageSize = 1000,\n }: DatapointFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<SubDataPointCsvPreview[]> {\n const subDataPoints: SubDataPointCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Filters\n const filterBy = {\n ...(parentCategories.length > 0 ? { category: parentCategories } : {}),\n ...(subCategories.length > 0 ? { subCategoryIds: subCategories } : {}),\n // if parentCategories or subCategories and not includeGuessedCategories\n ...(parentCategories.length + subCategories.length > 0 &&\n !includeGuessedCategories\n ? // then only show data points with approved data categories\n { status: SubDataPointDataSubCategoryGuessStatus.Approved }\n : {}),\n ...(dataSiloIds.length > 0 ? { dataSilos: dataSiloIds } : {}),\n };\n\n // Build a GraphQL client\n const {\n subDataPoints: { totalCount },\n } = await makeGraphQLRequest<{\n /** Query response */\n subDataPoints: {\n /** Count */\n totalCount: number;\n };\n }>(client, SUB_DATA_POINTS_COUNT, {\n filterBy,\n });\n\n logger.info(colors.magenta('[Step 1/3] Pulling in all subdatapoints'));\n\n progressBar.start(totalCount, 0);\n let total = 0;\n let shouldContinue = false;\n let cursor: string | undefined;\n let offset = 0;\n do {\n try {\n const {\n subDataPoints: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n subDataPoints: {\n /** List of matches */\n nodes: SubDataPointCsvPreview[];\n };\n }>(\n client,\n gql`\n query TranscendCliSubDataPointCsvExport(\n $filterBy: SubDataPointFiltersInput\n $first: Int!\n $offset: Int!\n ) {\n subDataPoints(\n filterBy: $filterBy\n first: $first\n offset: $offset\n useMaster: false\n ) {\n nodes {\n id\n name\n description\n dataPointId\n dataSiloId\n purposes {\n name\n purpose\n }\n categories {\n name\n category\n }\n ${\n includeGuessedCategories\n ? `pendingCategoryGuesses {\n category {\n name\n category\n }\n status\n classifierVersion\n }`\n : ''\n }\n ${\n includeAttributes\n ? `attributeValues {\n attributeKey {\n name\n }\n name\n }`\n : ''\n }\n }\n }\n }\n `,\n {\n first: pageSize,\n offset,\n filterBy: {\n ...filterBy,\n // TODO: https://transcend.height.app/T-40484 - add cursor support\n // ...(cursor ? { cursor: { id: cursor } } : {}),\n },\n },\n );\n\n cursor = nodes[nodes.length - 1]?.id as string;\n subDataPoints.push(...nodes);\n shouldContinue = nodes.length === pageSize;\n total += nodes.length;\n offset += nodes.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for cursor ${cursor} and offset ${offset}`,\n ),\n );\n throw err;\n }\n } while (shouldContinue);\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n const sorted = sortBy(subDataPoints, 'name');\n\n logger.info(\n colors.green(\n `Successfully pulled in ${sorted.length} subdatapoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return sorted;\n}\n\n/**\n * Pull datapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The datapoints\n */\nasync function pullDatapoints(\n client: GraphQLClient,\n {\n dataPointIds = [],\n pageSize = 100,\n }: {\n /** IDs of data points to filter down */\n dataPointIds: string[];\n /** Page size to pull in */\n pageSize?: number;\n },\n): Promise<DataPointCsvPreview[]> {\n const dataPoints: DataPointCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n logger.info(\n colors.magenta(\n `[Step 2/3] Fetching metadata for ${dataPointIds.length} datapoints`,\n ),\n );\n\n // Group by 100\n const dataPointsGrouped = chunk(dataPointIds, pageSize);\n\n progressBar.start(dataPointIds.length, 0);\n let total = 0;\n await mapSeries(dataPointsGrouped, async (dataPointIdsGroup) => {\n try {\n const {\n dataPoints: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n dataPoints: {\n /** List of matches */\n nodes: DataPointCsvPreview[];\n };\n }>(client, DATAPOINT_EXPORT, {\n first: pageSize,\n filterBy: {\n ids: dataPointIdsGroup,\n },\n });\n\n dataPoints.push(...nodes);\n total += dataPointIdsGroup.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for IDs ${dataPointIdsGroup.join(\n ', ',\n )}`,\n ),\n );\n throw err;\n }\n });\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully pulled in ${dataPoints.length} dataPoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return dataPoints;\n}\n\n/**\n * Pull data silo information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The data silos\n */\nasync function pullDataSilos(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n pageSize = 100,\n }: {\n /** IDs of data silos to filter down */\n dataSiloIds: string[];\n /** Page size to pull in */\n pageSize?: number;\n },\n): Promise<DataSiloCsvPreview[]> {\n const dataSilos: DataSiloCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n logger.info(\n colors.magenta(\n `[Step 3/3] Fetching metadata for ${dataSiloIds.length} data silos`,\n ),\n );\n\n // Group by 100\n const dataSilosGrouped = chunk(dataSiloIds, pageSize);\n\n progressBar.start(dataSiloIds.length, 0);\n let total = 0;\n await mapSeries(dataSilosGrouped, async (dataSiloIdsGroup) => {\n try {\n const {\n dataSilos: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n dataSilos: {\n /** List of matches */\n nodes: DataSiloCsvPreview[];\n };\n }>(client, DATA_SILO_EXPORT, {\n first: pageSize,\n filterBy: {\n ids: dataSiloIdsGroup,\n },\n });\n\n dataSilos.push(...nodes);\n total += dataSiloIdsGroup.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching data silos for IDs ${dataSiloIdsGroup.join(', ')}`,\n ),\n );\n throw err;\n }\n });\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully pulled in ${dataSilos.length} data silos in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return dataSilos;\n}\n\n/**\n * Pull all datapoints from the data inventory.\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The datapoints and data silos\n */\nexport async function pullAllDatapoints(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n includeGuessedCategories,\n includeAttributes,\n parentCategories = [],\n subCategories = [],\n pageSize = 1000,\n }: DatapointFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<\n (SubDataPointCsvPreview & {\n /** Data point information */\n dataPoint: DataPointCsvPreview;\n /** Data silo information */\n dataSilo: DataSiloCsvPreview;\n })[]\n> {\n // Subdatapoint information\n const subDatapoints = await pullSubDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n includeAttributes,\n parentCategories,\n subCategories,\n pageSize,\n });\n\n // The datapoint ids to grab\n const dataPointIds = uniq(subDatapoints.map((point) => point.dataPointId));\n const dataPoints = await pullDatapoints(client, {\n dataPointIds,\n });\n const dataPointById = keyBy(dataPoints, 'id');\n\n // The data silo IDs to grab\n const allDataSiloIds = uniq(subDatapoints.map((point) => point.dataSiloId));\n const dataSilos = await pullDataSilos(client, {\n dataSiloIds: allDataSiloIds,\n });\n const dataSiloById = keyBy(dataSilos, 'id');\n\n return subDatapoints.map((subDataPoint) => ({\n ...subDataPoint,\n dataPoint: dataPointById[subDataPoint.dataPointId],\n dataSilo: dataSiloById[subDataPoint.dataSiloId],\n }));\n}\n/* eslint-enable max-lines */\n","import type { UnstructuredSubDataPointRecommendationStatus } from '@transcend-io/privacy-types';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { gql, type GraphQLClient } from 'graphql-request';\nimport { sortBy } from 'lodash-es';\nimport type { DataCategoryInput } from '../../codecs';\nimport { ENTRY_COUNT, makeGraphQLRequest } from '../graphql';\nimport { logger } from '../../logger';\n\ninterface UnstructuredSubDataPointRecommendationCsvPreview {\n /** ID of subDatapoint */\n id: string;\n /** Entry or Named Entity recognized by the classifier */\n name: string;\n /** Context snippet including entry */\n contextSnippet: string;\n /** Scanned object ID */\n scannedObjectId: string;\n /** Scanned object path ID */\n scannedObjectPathId: string;\n /** The data silo ID */\n dataSiloId: string;\n /** Personal data category */\n dataSubCategory: DataCategoryInput;\n /** Classification Status */\n status: UnstructuredSubDataPointRecommendationStatus;\n /** Confidence */\n confidence: number;\n /** Classification method */\n classificationMethod: string;\n /** Classifier version */\n classifierVersion: string;\n}\n\ninterface EntryFilterOptions {\n /** IDs of data silos to filter down */\n dataSiloIds?: string[];\n /** Parent categories to filter down for */\n status?: UnstructuredSubDataPointRecommendationStatus[];\n /** Sub categories to filter down for */\n subCategories?: string[]; // TODO: https://transcend.height.app/T-40482 - do by name not ID\n /** Include entry and snippet */\n includeEncryptedSnippets?: boolean;\n /** Include encryptedSamplesS3Key */\n includeEncryptedSamplesS3Key?: boolean;\n}\n/**\n * Pull unstructured subdatapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @param options.dataSiloIds - IDs of data silos to filter down\n * @param options.status - Parent categories to filter down for\n * @param options.subCategories - Sub categories to filter down for\n * @param options.includeEncryptedSnippets - Include entry and snippet\n * @param options.includeEncryptedSamplesS3Key - Include encryptedSamplesS3Key\n * @param options.pageSize - Page size to pull in\n * @returns A promise that resolves to an array of unstructured subdatapoint recommendations\n */\nexport async function pullUnstructuredSubDataPointRecommendations(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n status,\n subCategories = [],\n includeEncryptedSnippets,\n pageSize = 100,\n }: EntryFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<UnstructuredSubDataPointRecommendationCsvPreview[]> {\n const unstructuredSubDataPointRecommendations: UnstructuredSubDataPointRecommendationCsvPreview[] =\n [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Filters\n const filterBy = {\n ...(subCategories.length > 0 ? { subCategoryIds: subCategories } : {}),\n ...(status ? { status } : {}),\n ...(dataSiloIds.length > 0 ? { dataSilos: dataSiloIds } : {}),\n };\n\n // Build a GraphQL client\n const {\n unstructuredSubDataPointRecommendations: { totalCount },\n } = await makeGraphQLRequest<{\n /** Query response */\n unstructuredSubDataPointRecommendations: {\n /** Count */\n totalCount: number;\n };\n }>(client, ENTRY_COUNT, {\n filterBy,\n });\n\n logger.info(colors.magenta('[Step 1/3] Pulling in all subdatapoints'));\n\n progressBar.start(totalCount, 0);\n let total = 0;\n let shouldContinue = false;\n let cursor: string | undefined;\n let offset = 0;\n do {\n try {\n const {\n unstructuredSubDataPointRecommendations: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n unstructuredSubDataPointRecommendations: {\n /** List of matches */\n nodes: UnstructuredSubDataPointRecommendationCsvPreview[];\n };\n }>(\n client,\n gql`\n query TranscendCliUnstructuredSubDataPointRecommendationCsvExport(\n $filterBy: UnstructuredSubDataPointRecommendationsFilterInput\n $first: Int!\n $offset: Int!\n ) {\n unstructuredSubDataPointRecommendations(\n filterBy: $filterBy\n first: $first\n offset: $offset\n useMaster: false\n ) {\n nodes {\n id\n dataSiloId\n scannedObjectPathId\n scannedObjectId\n ${includeEncryptedSnippets ? 'name' : ''}\n ${includeEncryptedSnippets ? 'contextSnippet' : ''}\n dataSubCategory {\n name\n category\n }\n status\n confidence\n classificationMethod\n classifierVersion\n }\n }\n }\n `,\n {\n first: pageSize,\n offset,\n filterBy: {\n ...filterBy,\n },\n },\n );\n\n cursor = nodes[nodes.length - 1]?.id as string;\n unstructuredSubDataPointRecommendations.push(...nodes);\n shouldContinue = nodes.length === pageSize;\n total += nodes.length;\n offset += nodes.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for cursor ${cursor} and offset ${offset}`,\n ),\n );\n throw err;\n }\n } while (shouldContinue);\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n const sorted = sortBy(unstructuredSubDataPointRecommendations, 'name');\n\n logger.info(\n colors.green(\n `Successfully pulled in ${sorted.length} subdatapoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return sorted;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-GCTE43TS.cjs","../src/lib/data-inventory/pullAllDatapoints.ts","../src/lib/data-inventory/pullUnstructuredSubDataPointRecommendations.ts"],"names":["pullSubDatapoints","client","dataSiloIds","includeGuessedCategories","includeAttributes","parentCategories","subCategories","pageSize","subDataPoints","t0","progressBar","cliProgress","filterBy","SubDataPointDataSubCategoryGuessStatus","totalCount","makeGraphQLRequest","SUB_DATA_POINTS_COUNT","logger","colors","total","shouldContinue","cursor","offset","nodes","gql","err"],"mappings":"AAAA,quBAA4E,wDAAyC,wDAA8D,2DCK5K,qGACiB,iDACJ,gFACD,MAkFnB,SAAeA,CAAAA,CACbC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAC,CAAA,CACf,wBAAA,CAAAC,CAAAA,CACA,iBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CAAmB,CAAC,CAAA,CACpB,aAAA,CAAAC,CAAAA,CAAgB,CAAC,CAAA,CACjB,QAAA,CAAAC,CAAAA,CAAW,GACb,CAAA,CAGI,CAAC,CAAA,CAC8B,CACnC,IAAMC,CAAAA,CAA0C,CAAC,CAAA,CAG3CC,CAAAA,CAAK,IAAI,IAAA,CAAK,CAAA,CAAE,OAAA,CAAQ,CAAA,CAGxBC,CAAAA,CAAc,IAAIC,qBAAAA,CAAY,SAAA,CAClC,CAAC,CAAA,CACDA,qBAAAA,CAAY,OAAA,CAAQ,cACtB,CAAA,CAGMC,CAAAA,CAAW,CACf,GAAIP,CAAAA,CAAiB,MAAA,CAAS,CAAA,CAAI,CAAE,QAAA,CAAUA,CAAiB,CAAA,CAAI,CAAC,CAAA,CACpE,GAAIC,CAAAA,CAAc,MAAA,CAAS,CAAA,CAAI,CAAE,cAAA,CAAgBA,CAAc,CAAA,CAAI,CAAC,CAAA,CAEpE,GAAID,CAAAA,CAAiB,MAAA,CAASC,CAAAA,CAAc,MAAA,CAAS,CAAA,EACrD,CAACH,CAAAA,CAEG,CAAE,MAAA,CAAQU,oDAAAA,CAAuC,QAAS,CAAA,CAC1D,CAAC,CAAA,CACL,GAAIX,CAAAA,CAAY,MAAA,CAAS,CAAA,CAAI,CAAE,SAAA,CAAWA,CAAY,CAAA,CAAI,CAAC,CAC7D,CAAA,CAGM,CACJ,aAAA,CAAe,CAAE,UAAA,CAAAY,CAAW,CAC9B,CAAA,CAAI,MAAMC,kCAAAA,CAMPd,CAAQe,mBAAAA,CAAuB,CAChC,QAAA,CAAAJ,CACF,CAAC,CAAA,CAEDK,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,yCAAyC,CAAC,CAAA,CAErER,CAAAA,CAAY,KAAA,CAAMI,CAAAA,CAAY,CAAC,CAAA,CAC/B,IAAIK,CAAAA,CAAQ,CAAA,CACRC,CAAAA,CAAiB,CAAA,CAAA,CACjBC,CAAAA,CACAC,CAAAA,CAAS,CAAA,CACb,GACE,GAAI,CACF,GAAM,CACJ,aAAA,CAAe,CAAE,KAAA,CAAAC,CAAM,CACzB,CAAA,CAAI,MAAMR,kCAAAA,CAORd,CACAuB,mBAAAA,CAAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAA,EA2BUrB,CAAAA,CACI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAA,CAAA,CAQA,EACN,CAAA;AAAA,gBAAA,EAEEC,CAAAA,CACI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAA,CAAA,CAMA,EACN,CAAA;AAAA;AAAA;AAAA;AAAA,QAAA,CAAA,CAKR,CACE,KAAA,CAAOG,CAAAA,CACP,MAAA,CAAAe,CAAAA,CACA,QAAA,CAAU,CACR,GAAGV,CAGL,CACF,CACF,CAAA,CAEAS,CAAAA,iBAASE,CAAAA,qBAAMA,CAAAA,CAAM,MAAA,CAAS,CAAC,CAAA,6BAAG,IAAA,CAClCf,CAAAA,CAAc,IAAA,CAAK,GAAGe,CAAK,CAAA,CAC3BH,CAAAA,CAAiBG,CAAAA,CAAM,MAAA,GAAWhB,CAAAA,CAClCY,CAAAA,EAASI,CAAAA,CAAM,MAAA,CACfD,CAAAA,EAAUC,CAAAA,CAAM,MAAA,CAChBb,CAAAA,CAAY,MAAA,CAAOS,CAAK,CAC1B,CAAA,KAAA,CAASM,CAAAA,CAAK,CACZ,MAAAR,mBAAAA,CAAO,KAAA,CACLC,gBAAAA,CAAO,GAAA,CACL,CAAA,2CAAA,EAA8CG,CAAM,CAAA,YAAA,EAAeC,CAAM,CAAA,CAAA;AC7G3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBgD,gBAAA;AACU,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BiB,QAAA","file":"/home/runner/work/cli/cli/dist/chunk-GCTE43TS.cjs","sourcesContent":[null,"/* eslint-disable max-lines */\nimport { keyBy, uniq, chunk, sortBy } from 'lodash-es';\nimport {\n type DataCategoryType,\n SubDataPointDataSubCategoryGuessStatus,\n} from '@transcend-io/privacy-types';\nimport cliProgress from 'cli-progress';\nimport { gql } from 'graphql-request';\nimport colors from 'colors';\nimport type { GraphQLClient } from 'graphql-request';\nimport {\n DATAPOINT_EXPORT,\n DATA_SILO_EXPORT,\n type DataSiloAttributeValue,\n SUB_DATA_POINTS_COUNT,\n makeGraphQLRequest,\n} from '../graphql';\nimport { logger } from '../../logger';\nimport type { DataCategoryInput, ProcessingPurposeInput } from '../../codecs';\nimport { mapSeries } from '../bluebird';\n\nexport interface DataSiloCsvPreview {\n /** ID of dataSilo */\n id: string;\n /** Name of dataSilo */\n title: string;\n}\n\nexport interface DataPointCsvPreview {\n /** ID of dataPoint */\n id: string;\n /** The path to this data point */\n path: string[];\n /** Description */\n description: {\n /** Default message */\n defaultMessage: string;\n };\n /** Name */\n name: string;\n}\n\nexport interface SubDataPointCsvPreview {\n /** ID of subDatapoint */\n id: string;\n /** Name (or key) of the subdatapoint */\n name: string;\n /** The description */\n description?: string;\n /** Personal data category */\n categories: DataCategoryInput[];\n /** Data point ID */\n dataPointId: string;\n /** The data silo ID */\n dataSiloId: string;\n /** The processing purpose for this sub datapoint */\n purposes: ProcessingPurposeInput[];\n /** Attribute attached to subdatapoint */\n attributeValues?: DataSiloAttributeValue[];\n /** Data category guesses that are output by the classifier */\n pendingCategoryGuesses?: {\n /** Data category being guessed */\n category: DataCategoryInput;\n /** Status of guess */\n status: SubDataPointDataSubCategoryGuessStatus;\n /** classifier version that produced the guess */\n classifierVersion: number;\n }[];\n}\n\nexport interface DatapointFilterOptions {\n /** IDs of data silos to filter down */\n dataSiloIds?: string[];\n /** Whether to include guessed categories, defaults to only approved categories */\n includeGuessedCategories?: boolean;\n /** Whether or not to include attributes */\n includeAttributes?: boolean;\n /** Parent categories to filter down for */\n parentCategories?: DataCategoryType[];\n /** Sub categories to filter down for */\n subCategories?: string[]; // TODO: https://transcend.height.app/T-40482 - do by name not ID\n}\n\n/**\n * Pull subdatapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The subdatapoints\n */\nasync function pullSubDatapoints(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n includeGuessedCategories,\n includeAttributes,\n parentCategories = [],\n subCategories = [],\n pageSize = 1000,\n }: DatapointFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<SubDataPointCsvPreview[]> {\n const subDataPoints: SubDataPointCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Filters\n const filterBy = {\n ...(parentCategories.length > 0 ? { category: parentCategories } : {}),\n ...(subCategories.length > 0 ? { subCategoryIds: subCategories } : {}),\n // if parentCategories or subCategories and not includeGuessedCategories\n ...(parentCategories.length + subCategories.length > 0 &&\n !includeGuessedCategories\n ? // then only show data points with approved data categories\n { status: SubDataPointDataSubCategoryGuessStatus.Approved }\n : {}),\n ...(dataSiloIds.length > 0 ? { dataSilos: dataSiloIds } : {}),\n };\n\n // Build a GraphQL client\n const {\n subDataPoints: { totalCount },\n } = await makeGraphQLRequest<{\n /** Query response */\n subDataPoints: {\n /** Count */\n totalCount: number;\n };\n }>(client, SUB_DATA_POINTS_COUNT, {\n filterBy,\n });\n\n logger.info(colors.magenta('[Step 1/3] Pulling in all subdatapoints'));\n\n progressBar.start(totalCount, 0);\n let total = 0;\n let shouldContinue = false;\n let cursor: string | undefined;\n let offset = 0;\n do {\n try {\n const {\n subDataPoints: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n subDataPoints: {\n /** List of matches */\n nodes: SubDataPointCsvPreview[];\n };\n }>(\n client,\n gql`\n query TranscendCliSubDataPointCsvExport(\n $filterBy: SubDataPointFiltersInput\n $first: Int!\n $offset: Int!\n ) {\n subDataPoints(\n filterBy: $filterBy\n first: $first\n offset: $offset\n useMaster: false\n ) {\n nodes {\n id\n name\n description\n dataPointId\n dataSiloId\n purposes {\n name\n purpose\n }\n categories {\n name\n category\n }\n ${\n includeGuessedCategories\n ? `pendingCategoryGuesses {\n category {\n name\n category\n }\n status\n classifierVersion\n }`\n : ''\n }\n ${\n includeAttributes\n ? `attributeValues {\n attributeKey {\n name\n }\n name\n }`\n : ''\n }\n }\n }\n }\n `,\n {\n first: pageSize,\n offset,\n filterBy: {\n ...filterBy,\n // TODO: https://transcend.height.app/T-40484 - add cursor support\n // ...(cursor ? { cursor: { id: cursor } } : {}),\n },\n },\n );\n\n cursor = nodes[nodes.length - 1]?.id as string;\n subDataPoints.push(...nodes);\n shouldContinue = nodes.length === pageSize;\n total += nodes.length;\n offset += nodes.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for cursor ${cursor} and offset ${offset}`,\n ),\n );\n throw err;\n }\n } while (shouldContinue);\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n const sorted = sortBy(subDataPoints, 'name');\n\n logger.info(\n colors.green(\n `Successfully pulled in ${sorted.length} subdatapoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return sorted;\n}\n\n/**\n * Pull datapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The datapoints\n */\nasync function pullDatapoints(\n client: GraphQLClient,\n {\n dataPointIds = [],\n pageSize = 100,\n }: {\n /** IDs of data points to filter down */\n dataPointIds: string[];\n /** Page size to pull in */\n pageSize?: number;\n },\n): Promise<DataPointCsvPreview[]> {\n const dataPoints: DataPointCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n logger.info(\n colors.magenta(\n `[Step 2/3] Fetching metadata for ${dataPointIds.length} datapoints`,\n ),\n );\n\n // Group by 100\n const dataPointsGrouped = chunk(dataPointIds, pageSize);\n\n progressBar.start(dataPointIds.length, 0);\n let total = 0;\n await mapSeries(dataPointsGrouped, async (dataPointIdsGroup) => {\n try {\n const {\n dataPoints: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n dataPoints: {\n /** List of matches */\n nodes: DataPointCsvPreview[];\n };\n }>(client, DATAPOINT_EXPORT, {\n first: pageSize,\n filterBy: {\n ids: dataPointIdsGroup,\n },\n });\n\n dataPoints.push(...nodes);\n total += dataPointIdsGroup.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for IDs ${dataPointIdsGroup.join(\n ', ',\n )}`,\n ),\n );\n throw err;\n }\n });\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully pulled in ${dataPoints.length} dataPoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return dataPoints;\n}\n\n/**\n * Pull data silo information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The data silos\n */\nasync function pullDataSilos(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n pageSize = 100,\n }: {\n /** IDs of data silos to filter down */\n dataSiloIds: string[];\n /** Page size to pull in */\n pageSize?: number;\n },\n): Promise<DataSiloCsvPreview[]> {\n const dataSilos: DataSiloCsvPreview[] = [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n logger.info(\n colors.magenta(\n `[Step 3/3] Fetching metadata for ${dataSiloIds.length} data silos`,\n ),\n );\n\n // Group by 100\n const dataSilosGrouped = chunk(dataSiloIds, pageSize);\n\n progressBar.start(dataSiloIds.length, 0);\n let total = 0;\n await mapSeries(dataSilosGrouped, async (dataSiloIdsGroup) => {\n try {\n const {\n dataSilos: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n dataSilos: {\n /** List of matches */\n nodes: DataSiloCsvPreview[];\n };\n }>(client, DATA_SILO_EXPORT, {\n first: pageSize,\n filterBy: {\n ids: dataSiloIdsGroup,\n },\n });\n\n dataSilos.push(...nodes);\n total += dataSiloIdsGroup.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching data silos for IDs ${dataSiloIdsGroup.join(', ')}`,\n ),\n );\n throw err;\n }\n });\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully pulled in ${dataSilos.length} data silos in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return dataSilos;\n}\n\n/**\n * Pull all datapoints from the data inventory.\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @returns The datapoints and data silos\n */\nexport async function pullAllDatapoints(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n includeGuessedCategories,\n includeAttributes,\n parentCategories = [],\n subCategories = [],\n pageSize = 1000,\n }: DatapointFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<\n (SubDataPointCsvPreview & {\n /** Data point information */\n dataPoint: DataPointCsvPreview;\n /** Data silo information */\n dataSilo: DataSiloCsvPreview;\n })[]\n> {\n // Subdatapoint information\n const subDatapoints = await pullSubDatapoints(client, {\n dataSiloIds,\n includeGuessedCategories,\n includeAttributes,\n parentCategories,\n subCategories,\n pageSize,\n });\n\n // The datapoint ids to grab\n const dataPointIds = uniq(subDatapoints.map((point) => point.dataPointId));\n const dataPoints = await pullDatapoints(client, {\n dataPointIds,\n });\n const dataPointById = keyBy(dataPoints, 'id');\n\n // The data silo IDs to grab\n const allDataSiloIds = uniq(subDatapoints.map((point) => point.dataSiloId));\n const dataSilos = await pullDataSilos(client, {\n dataSiloIds: allDataSiloIds,\n });\n const dataSiloById = keyBy(dataSilos, 'id');\n\n return subDatapoints.map((subDataPoint) => ({\n ...subDataPoint,\n dataPoint: dataPointById[subDataPoint.dataPointId],\n dataSilo: dataSiloById[subDataPoint.dataSiloId],\n }));\n}\n/* eslint-enable max-lines */\n","import type { UnstructuredSubDataPointRecommendationStatus } from '@transcend-io/privacy-types';\nimport cliProgress from 'cli-progress';\nimport colors from 'colors';\nimport { gql, type GraphQLClient } from 'graphql-request';\nimport { sortBy } from 'lodash-es';\nimport type { DataCategoryInput } from '../../codecs';\nimport { ENTRY_COUNT, makeGraphQLRequest } from '../graphql';\nimport { logger } from '../../logger';\n\ninterface UnstructuredSubDataPointRecommendationCsvPreview {\n /** ID of subDatapoint */\n id: string;\n /** Entry or Named Entity recognized by the classifier */\n name: string;\n /** Context snippet including entry */\n contextSnippet: string;\n /** Scanned object ID */\n scannedObjectId: string;\n /** Scanned object path ID */\n scannedObjectPathId: string;\n /** The data silo ID */\n dataSiloId: string;\n /** Personal data category */\n dataSubCategory: DataCategoryInput;\n /** Classification Status */\n status: UnstructuredSubDataPointRecommendationStatus;\n /** Confidence */\n confidence: number;\n /** Classification method */\n classificationMethod: string;\n /** Classifier version */\n classifierVersion: string;\n}\n\ninterface EntryFilterOptions {\n /** IDs of data silos to filter down */\n dataSiloIds?: string[];\n /** Parent categories to filter down for */\n status?: UnstructuredSubDataPointRecommendationStatus[];\n /** Sub categories to filter down for */\n subCategories?: string[]; // TODO: https://transcend.height.app/T-40482 - do by name not ID\n /** Include entry and snippet */\n includeEncryptedSnippets?: boolean;\n /** Include encryptedSamplesS3Key */\n includeEncryptedSamplesS3Key?: boolean;\n}\n/**\n * Pull unstructured subdatapoint information\n *\n * @param client - Client to use for the request\n * @param options - Options\n * @param options.dataSiloIds - IDs of data silos to filter down\n * @param options.status - Parent categories to filter down for\n * @param options.subCategories - Sub categories to filter down for\n * @param options.includeEncryptedSnippets - Include entry and snippet\n * @param options.includeEncryptedSamplesS3Key - Include encryptedSamplesS3Key\n * @param options.pageSize - Page size to pull in\n * @returns A promise that resolves to an array of unstructured subdatapoint recommendations\n */\nexport async function pullUnstructuredSubDataPointRecommendations(\n client: GraphQLClient,\n {\n dataSiloIds = [],\n status,\n subCategories = [],\n includeEncryptedSnippets,\n pageSize = 100,\n }: EntryFilterOptions & {\n /** Page size to pull in */\n pageSize?: number;\n } = {},\n): Promise<UnstructuredSubDataPointRecommendationCsvPreview[]> {\n const unstructuredSubDataPointRecommendations: UnstructuredSubDataPointRecommendationCsvPreview[] =\n [];\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Filters\n const filterBy = {\n ...(subCategories.length > 0 ? { subCategoryIds: subCategories } : {}),\n ...(status ? { status } : {}),\n ...(dataSiloIds.length > 0 ? { dataSilos: dataSiloIds } : {}),\n };\n\n // Build a GraphQL client\n const {\n unstructuredSubDataPointRecommendations: { totalCount },\n } = await makeGraphQLRequest<{\n /** Query response */\n unstructuredSubDataPointRecommendations: {\n /** Count */\n totalCount: number;\n };\n }>(client, ENTRY_COUNT, {\n filterBy,\n });\n\n logger.info(colors.magenta('[Step 1/3] Pulling in all subdatapoints'));\n\n progressBar.start(totalCount, 0);\n let total = 0;\n let shouldContinue = false;\n let cursor: string | undefined;\n let offset = 0;\n do {\n try {\n const {\n unstructuredSubDataPointRecommendations: { nodes },\n } = await makeGraphQLRequest<{\n /** Query response */\n unstructuredSubDataPointRecommendations: {\n /** List of matches */\n nodes: UnstructuredSubDataPointRecommendationCsvPreview[];\n };\n }>(\n client,\n gql`\n query TranscendCliUnstructuredSubDataPointRecommendationCsvExport(\n $filterBy: UnstructuredSubDataPointRecommendationsFilterInput\n $first: Int!\n $offset: Int!\n ) {\n unstructuredSubDataPointRecommendations(\n filterBy: $filterBy\n first: $first\n offset: $offset\n useMaster: false\n ) {\n nodes {\n id\n dataSiloId\n scannedObjectPathId\n scannedObjectId\n ${includeEncryptedSnippets ? 'name' : ''}\n ${includeEncryptedSnippets ? 'contextSnippet' : ''}\n dataSubCategory {\n name\n category\n }\n status\n confidence\n classificationMethod\n classifierVersion\n }\n }\n }\n `,\n {\n first: pageSize,\n offset,\n filterBy: {\n ...filterBy,\n },\n },\n );\n\n cursor = nodes[nodes.length - 1]?.id as string;\n unstructuredSubDataPointRecommendations.push(...nodes);\n shouldContinue = nodes.length === pageSize;\n total += nodes.length;\n offset += nodes.length;\n progressBar.update(total);\n } catch (err) {\n logger.error(\n colors.red(\n `An error fetching subdatapoints for cursor ${cursor} and offset ${offset}`,\n ),\n );\n throw err;\n }\n } while (shouldContinue);\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n const sorted = sortBy(unstructuredSubDataPointRecommendations, 'name');\n\n logger.info(\n colors.green(\n `Successfully pulled in ${sorted.length} subdatapoints in ${\n totalTime / 1000\n } seconds!`,\n ),\n );\n return sorted;\n}\n"]}
@@ -1,2 +1,2 @@
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 _chunk56QKBG2Rcjs = require('./chunk-56QKBG2R.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDQCPGPXGcjs = require('./chunk-DQCPGPXG.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var P = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var Z=e.type({identifier:e.string,type:e.string,coreIdentifier:e.string,dataSiloId:e.string,requestId:e.string,nonce:e.string,requestCreatedAt:e.string,daysUntilOverdue:e.number,attributes:e.array(e.type({key:e.string,values:e.array(e.string)}))});async function B(r,{dataSiloId:s,limit:c=100,offset:n=0,requestType:a}){try{let i=await r.get(`v1/data-silo/${s}/pending-requests/${a}`,{searchParams:{offset:n,limit:c}}).json(),{items:f}=_typeutils.decodeCodec.call(void 0, e.type({items:e.array(Z)}),i);return f}catch(i){throw new Error(`Received an error from server: ${_optionalChain([i, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([i, 'optionalAccess', _4 => _4.message])}`)}}var j=P.type({nonce:P.string,identifier:P.string});async function W(r,{nonce:s,identifier:c}){try{return await r.put("v1/data-silo",{headers:{"x-transcend-nonce":s},json:{profiles:[{profileId:c}]}}),!0}catch(n){if(_optionalChain([n, 'access', _5 => _5.response, 'optionalAccess', _6 => _6.statusCode])===409)return!1;throw new Error(`Received an error from server: ${_optionalChain([n, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([n, 'optionalAccess', _9 => _9.message])}`)}}var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);async function ue({file:r,dataSiloId:s,auth:c,sombraAuth:n,concurrency:a=100,transcendUrl:i=_chunkDQCPGPXGcjs.r,sleepSeconds:f=10}){let y=await _chunk56QKBG2Rcjs.Ac.call(void 0, i,c,n);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${r}" from disk`));let o=_chunk56QKBG2Rcjs.uc.call(void 0, r,j);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Notifying Transcend for data silo "${s}" marking "${o.length}" identifiers as completed.`));let C=new Date().getTime(),w=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),d=0,u=0,l=0;w.start(o.length,0);let m=_chunkDQCPGPXGcjs.b.call(void 0, o,a),I=m.length;await _chunk56QKBG2Rcjs.b.call(void 0, m,async($,S)=>{_chunkZUNVPK23cjs.a.info(_colors2.default.blue(`Processing chunk ${S+1}/${I} (${_chunkDQCPGPXGcjs.b.length} items)`)),await _chunk56QKBG2Rcjs.a.call(void 0, $,async h=>{try{await W(y,h)?d+=1:u+=1}catch(b){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error notifying Transcend for identifier "${h.identifier}" - ${_optionalChain([b, 'optionalAccess', _10 => _10.message])}`)),l+=1}w.update(d+u)}),f>0&&S<I-1&&(_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Sleeping for ${f}s before next chunk...`)),await new Promise(h=>{setTimeout(h,f*1e3)}))}),w.stop();let x=new Date().getTime()-C;if(_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend for ${d} identifiers in "${x/1e3}" seconds!`)),u&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`There were ${u} identifiers that were not in a state to be updated.They likely have already been resolved.`)),l)throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`There were ${l} identifiers that failed to be updated. Please review the logs for more information.`)),new Error("Failed to update all identifiers");return o.length}var _privacytypes = require('@transcend-io/privacy-types');async function Te({requestIds:r,dataSiloId:s,auth:c,concurrency:n=100,status:a=_privacytypes.RequestDataSiloStatus.Resolved,transcendUrl:i=_chunkDQCPGPXGcjs.r}){let f=_chunk56QKBG2Rcjs.zc.call(void 0, i,c),y=new Date().getTime(),o=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Notifying Transcend for data silo "${s}" marking "${r.length}" requests as completed.`));let C=0;o.start(r.length,0),await _chunk56QKBG2Rcjs.a.call(void 0, r,async u=>{let l=await _chunk56QKBG2Rcjs.Jd.call(void 0, f,{requestId:u,dataSiloId:s});try{await _chunk56QKBG2Rcjs.wg.call(void 0, f,_chunk56QKBG2Rcjs.xa,{requestDataSiloId:l.id,status:a})}catch(m){if(!m.message.includes("Client error: Request must be active:")&&!m.message.includes("Failed to find RequestDataSilo"))throw m}C+=1,o.update(C)},{concurrency:n}),o.stop();let d=new Date().getTime()-y;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend in "${d/1e3}" seconds!`)),r.length}async function ke({dataSiloId:r,auth:s,sombraAuth:c,actions:n,apiPageSize:a=100,savePageSize:i=1e3,onSave:f,transcendUrl:y=_chunkDQCPGPXGcjs.r,skipRequestCount:o=!1}){if(i%a!==0)throw new Error(`savePageSize must be a multiple of apiPageSize. savePageSize: ${i}, apiPageSize: ${a}`);let C=await _chunk56QKBG2Rcjs.Ac.call(void 0, y,s,c),w=_chunk56QKBG2Rcjs.zc.call(void 0, y,s),d=0;o||(d=await _chunk56QKBG2Rcjs.Kd.call(void 0, w,{dataSiloId:r})),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling ${o?"all":d} outstanding request identifiers for data silo: "${r}" for requests of types "${n.join('", "')}"`));let u=new Date().getTime(),l=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),m=new Set,I=[],g=[];o||l.start(d,0),await _chunk56QKBG2Rcjs.b.call(void 0, n,async $=>{let S=0,h=!0;for(;h;){let b=await B(C,{dataSiloId:r,limit:a,offset:S,requestType:$}),_=b.map(A=>(m.add(A.requestId),{...A,action:$})),M=_.map(({attributes:A,...V})=>({...V,...A.reduce((X,F)=>Object.assign(X,{[F.key]:F.values.join(",")}),{})}));I.push(..._),g.push(...M),g.length>=i&&(await f(g),g=[]),h=b.length===a,S+=a,o?_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulled ${b.length} outstanding identifiers for ${m.size} requests`)):l.update(m.size)}}),g.length>0&&await f(g),o||l.stop();let x=new Date().getTime()-u;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled ${I.length} outstanding identifiers from ${m.size} requests in "${x/1e3}" seconds!`)),{identifiers:I}}exports.a = Z; exports.b = B; exports.c = j; exports.d = W; exports.e = ue; exports.f = Te; exports.g = ke;
2
- //# sourceMappingURL=chunk-IHUCIK5T.cjs.map
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 _chunkKYOQWIIScjs = require('./chunk-KYOQWIIS.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunk5MG2CEZVcjs = require('./chunk-5MG2CEZV.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var P = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var Z=e.type({identifier:e.string,type:e.string,coreIdentifier:e.string,dataSiloId:e.string,requestId:e.string,nonce:e.string,requestCreatedAt:e.string,daysUntilOverdue:e.number,attributes:e.array(e.type({key:e.string,values:e.array(e.string)}))});async function B(r,{dataSiloId:s,limit:c=100,offset:n=0,requestType:a}){try{let i=await r.get(`v1/data-silo/${s}/pending-requests/${a}`,{searchParams:{offset:n,limit:c}}).json(),{items:f}=_typeutils.decodeCodec.call(void 0, e.type({items:e.array(Z)}),i);return f}catch(i){throw new Error(`Received an error from server: ${_optionalChain([i, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([i, 'optionalAccess', _4 => _4.message])}`)}}var j=P.type({nonce:P.string,identifier:P.string});async function W(r,{nonce:s,identifier:c}){try{return await r.put("v1/data-silo",{headers:{"x-transcend-nonce":s},json:{profiles:[{profileId:c}]}}),!0}catch(n){if(_optionalChain([n, 'access', _5 => _5.response, 'optionalAccess', _6 => _6.statusCode])===409)return!1;throw new Error(`Received an error from server: ${_optionalChain([n, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([n, 'optionalAccess', _9 => _9.message])}`)}}var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);async function ue({file:r,dataSiloId:s,auth:c,sombraAuth:n,concurrency:a=100,transcendUrl:i=_chunk5MG2CEZVcjs.r,sleepSeconds:f=10}){let y=await _chunkKYOQWIIScjs.Ac.call(void 0, i,c,n);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${r}" from disk`));let o=_chunkKYOQWIIScjs.uc.call(void 0, r,j);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Notifying Transcend for data silo "${s}" marking "${o.length}" identifiers as completed.`));let C=new Date().getTime(),w=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),d=0,u=0,l=0;w.start(o.length,0);let m=_chunk5MG2CEZVcjs.b.call(void 0, o,a),I=m.length;await _chunkKYOQWIIScjs.b.call(void 0, m,async($,S)=>{_chunkZUNVPK23cjs.a.info(_colors2.default.blue(`Processing chunk ${S+1}/${I} (${_chunk5MG2CEZVcjs.b.length} items)`)),await _chunkKYOQWIIScjs.a.call(void 0, $,async h=>{try{await W(y,h)?d+=1:u+=1}catch(b){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error notifying Transcend for identifier "${h.identifier}" - ${_optionalChain([b, 'optionalAccess', _10 => _10.message])}`)),l+=1}w.update(d+u)}),f>0&&S<I-1&&(_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Sleeping for ${f}s before next chunk...`)),await new Promise(h=>{setTimeout(h,f*1e3)}))}),w.stop();let x=new Date().getTime()-C;if(_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend for ${d} identifiers in "${x/1e3}" seconds!`)),u&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`There were ${u} identifiers that were not in a state to be updated.They likely have already been resolved.`)),l)throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`There were ${l} identifiers that failed to be updated. Please review the logs for more information.`)),new Error("Failed to update all identifiers");return o.length}var _privacytypes = require('@transcend-io/privacy-types');async function Te({requestIds:r,dataSiloId:s,auth:c,concurrency:n=100,status:a=_privacytypes.RequestDataSiloStatus.Resolved,transcendUrl:i=_chunk5MG2CEZVcjs.r}){let f=_chunkKYOQWIIScjs.zc.call(void 0, i,c),y=new Date().getTime(),o=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Notifying Transcend for data silo "${s}" marking "${r.length}" requests as completed.`));let C=0;o.start(r.length,0),await _chunkKYOQWIIScjs.a.call(void 0, r,async u=>{let l=await _chunkKYOQWIIScjs.Jd.call(void 0, f,{requestId:u,dataSiloId:s});try{await _chunkKYOQWIIScjs.wg.call(void 0, f,_chunkKYOQWIIScjs.xa,{requestDataSiloId:l.id,status:a})}catch(m){if(!m.message.includes("Client error: Request must be active:")&&!m.message.includes("Failed to find RequestDataSilo"))throw m}C+=1,o.update(C)},{concurrency:n}),o.stop();let d=new Date().getTime()-y;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend in "${d/1e3}" seconds!`)),r.length}async function ke({dataSiloId:r,auth:s,sombraAuth:c,actions:n,apiPageSize:a=100,savePageSize:i=1e3,onSave:f,transcendUrl:y=_chunk5MG2CEZVcjs.r,skipRequestCount:o=!1}){if(i%a!==0)throw new Error(`savePageSize must be a multiple of apiPageSize. savePageSize: ${i}, apiPageSize: ${a}`);let C=await _chunkKYOQWIIScjs.Ac.call(void 0, y,s,c),w=_chunkKYOQWIIScjs.zc.call(void 0, y,s),d=0;o||(d=await _chunkKYOQWIIScjs.Kd.call(void 0, w,{dataSiloId:r})),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling ${o?"all":d} outstanding request identifiers for data silo: "${r}" for requests of types "${n.join('", "')}"`));let u=new Date().getTime(),l=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),m=new Set,I=[],g=[];o||l.start(d,0),await _chunkKYOQWIIScjs.b.call(void 0, n,async $=>{let S=0,h=!0;for(;h;){let b=await B(C,{dataSiloId:r,limit:a,offset:S,requestType:$}),_=b.map(A=>(m.add(A.requestId),{...A,action:$})),M=_.map(({attributes:A,...V})=>({...V,...A.reduce((X,F)=>Object.assign(X,{[F.key]:F.values.join(",")}),{})}));I.push(..._),g.push(...M),g.length>=i&&(await f(g),g=[]),h=b.length===a,S+=a,o?_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulled ${b.length} outstanding identifiers for ${m.size} requests`)):l.update(m.size)}}),g.length>0&&await f(g),o||l.stop();let x=new Date().getTime()-u;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled ${I.length} outstanding identifiers from ${m.size} requests in "${x/1e3}" seconds!`)),{identifiers:I}}exports.a = Z; exports.b = B; exports.c = j; exports.d = W; exports.e = ue; exports.f = Te; exports.g = ke;
2
+ //# sourceMappingURL=chunk-H3EBIKX6.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-IHUCIK5T.cjs","../src/lib/cron/pullCronPageOfIdentifiers.ts"],"names":["CronIdentifier","pullCronPageOfIdentifiers","sombra","dataSiloId","limit","offset","requestType","response"],"mappings":"AAAA,u/BAAuG,wDAAyC,wDAAgD,6GCA7K,qDACS,IAIfA,CAAAA,CAAmB,CAAA,CAAA,IAAA,CAAK,CAEnC,UAAA,CAAc,CAAA,CAAA,MAAA,CAEd,IAAA,CAAQ,CAAA,CAAA,MAAA,CAER,cAAA,CAAkB,CAAA,CAAA,MAAA,CAElB,UAAA,CAAc,CAAA,CAAA,MAAA,CAEd,SAAA,CAAa,CAAA,CAAA,MAAA,CAEb,KAAA,CAAS,CAAA,CAAA,MAAA,CAET,gBAAA,CAAoB,CAAA,CAAA,MAAA,CAEpB,gBAAA,CAAoB,CAAA,CAAA,MAAA,CAEpB,UAAA,CAAc,CAAA,CAAA,KAAA,CACV,CAAA,CAAA,IAAA,CAAK,CACL,GAAA,CAAO,CAAA,CAAA,MAAA,CACP,MAAA,CAAU,CAAA,CAAA,KAAA,CAAQ,CAAA,CAAA,MAAM,CAC1B,CAAC,CACH,CACF,CAAC,CAAA,CAaD,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,UAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,GAAA,CACR,MAAA,CAAAC,CAAAA,CAAS,CAAA,CACT,WAAA,CAAAC,CACF,CAAA,CAU2B,CAC3B,GAAI,CAEF,IAAMC,CAAAA,CAAW,MAAML,CAAAA,CACpB,GAAA,CAAI,CAAA,aAAA,EAAgBC,CAAU,CAAA,kBAAA,EAAqBG,CAAW,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-IHUCIK5T.cjs","sourcesContent":[null,"import * as t from 'io-ts';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { RequestAction } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\n\nexport const CronIdentifier = t.type({\n /** The identifier value */\n identifier: t.string,\n /** The type of identifier */\n type: t.string,\n /** The core identifier of the request */\n coreIdentifier: t.string,\n /** The ID of the underlying data silo */\n dataSiloId: t.string,\n /** The ID of the underlying request */\n requestId: t.string,\n /** The request nonce */\n nonce: t.string,\n /** The time the request was created */\n requestCreatedAt: t.string,\n /** The number of days until the request is overdue */\n daysUntilOverdue: t.number,\n /** Request attributes */\n attributes: t.array(\n t.type({\n key: t.string,\n values: t.array(t.string),\n }),\n ),\n});\n\n/** Type override */\nexport type CronIdentifier = t.TypeOf<typeof CronIdentifier>;\n\n/**\n * Pull a offset of identifiers for a cron job\n *\n * @see https://docs.transcend.io/docs/api-reference/GET/v1/data-silo/(id)/pending-requests/(type)\n * @param sombra - Sombra instance configured to make requests\n * @param options - Additional options\n * @returns Successfully submitted request\n */\nexport async function pullCronPageOfIdentifiers(\n sombra: Got,\n {\n dataSiloId,\n limit = 100,\n offset = 0,\n requestType,\n }: {\n /** Data Silo ID */\n dataSiloId: string;\n /** Type of request */\n requestType: RequestAction;\n /** Number of identifiers to pull in */\n limit?: number;\n /** Page to pull in */\n offset?: number;\n },\n): Promise<CronIdentifier[]> {\n try {\n // Make the GraphQL request\n const response = await sombra\n .get(`v1/data-silo/${dataSiloId}/pending-requests/${requestType}`, {\n searchParams: {\n offset,\n limit,\n },\n })\n .json();\n\n const { items } = decodeCodec(\n t.type({\n items: t.array(CronIdentifier),\n }),\n response,\n );\n return items;\n } catch (err) {\n throw new Error(\n `Received an error from server: ${err?.response?.body || err?.message}`,\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-H3EBIKX6.cjs","../src/lib/cron/pullCronPageOfIdentifiers.ts"],"names":["CronIdentifier","pullCronPageOfIdentifiers","sombra","dataSiloId","limit","offset","requestType","response"],"mappings":"AAAA,u/BAAuG,wDAAyC,wDAAgD,6GCA7K,qDACS,IAIfA,CAAAA,CAAmB,CAAA,CAAA,IAAA,CAAK,CAEnC,UAAA,CAAc,CAAA,CAAA,MAAA,CAEd,IAAA,CAAQ,CAAA,CAAA,MAAA,CAER,cAAA,CAAkB,CAAA,CAAA,MAAA,CAElB,UAAA,CAAc,CAAA,CAAA,MAAA,CAEd,SAAA,CAAa,CAAA,CAAA,MAAA,CAEb,KAAA,CAAS,CAAA,CAAA,MAAA,CAET,gBAAA,CAAoB,CAAA,CAAA,MAAA,CAEpB,gBAAA,CAAoB,CAAA,CAAA,MAAA,CAEpB,UAAA,CAAc,CAAA,CAAA,KAAA,CACV,CAAA,CAAA,IAAA,CAAK,CACL,GAAA,CAAO,CAAA,CAAA,MAAA,CACP,MAAA,CAAU,CAAA,CAAA,KAAA,CAAQ,CAAA,CAAA,MAAM,CAC1B,CAAC,CACH,CACF,CAAC,CAAA,CAaD,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,UAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CAAQ,GAAA,CACR,MAAA,CAAAC,CAAAA,CAAS,CAAA,CACT,WAAA,CAAAC,CACF,CAAA,CAU2B,CAC3B,GAAI,CAEF,IAAMC,CAAAA,CAAW,MAAML,CAAAA,CACpB,GAAA,CAAI,CAAA,aAAA,EAAgBC,CAAU,CAAA,kBAAA,EAAqBG,CAAW,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-H3EBIKX6.cjs","sourcesContent":[null,"import * as t from 'io-ts';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { RequestAction } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\n\nexport const CronIdentifier = t.type({\n /** The identifier value */\n identifier: t.string,\n /** The type of identifier */\n type: t.string,\n /** The core identifier of the request */\n coreIdentifier: t.string,\n /** The ID of the underlying data silo */\n dataSiloId: t.string,\n /** The ID of the underlying request */\n requestId: t.string,\n /** The request nonce */\n nonce: t.string,\n /** The time the request was created */\n requestCreatedAt: t.string,\n /** The number of days until the request is overdue */\n daysUntilOverdue: t.number,\n /** Request attributes */\n attributes: t.array(\n t.type({\n key: t.string,\n values: t.array(t.string),\n }),\n ),\n});\n\n/** Type override */\nexport type CronIdentifier = t.TypeOf<typeof CronIdentifier>;\n\n/**\n * Pull a offset of identifiers for a cron job\n *\n * @see https://docs.transcend.io/docs/api-reference/GET/v1/data-silo/(id)/pending-requests/(type)\n * @param sombra - Sombra instance configured to make requests\n * @param options - Additional options\n * @returns Successfully submitted request\n */\nexport async function pullCronPageOfIdentifiers(\n sombra: Got,\n {\n dataSiloId,\n limit = 100,\n offset = 0,\n requestType,\n }: {\n /** Data Silo ID */\n dataSiloId: string;\n /** Type of request */\n requestType: RequestAction;\n /** Number of identifiers to pull in */\n limit?: number;\n /** Page to pull in */\n offset?: number;\n },\n): Promise<CronIdentifier[]> {\n try {\n // Make the GraphQL request\n const response = await sombra\n .get(`v1/data-silo/${dataSiloId}/pending-requests/${requestType}`, {\n searchParams: {\n offset,\n limit,\n },\n })\n .json();\n\n const { items } = decodeCodec(\n t.type({\n items: t.array(CronIdentifier),\n }),\n response,\n );\n return items;\n } catch (err) {\n throw new Error(\n `Received an error from server: ${err?.response?.body || err?.message}`,\n );\n }\n}\n"]}
@@ -1,2 +1,2 @@
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 _chunk56QKBG2Rcjs = require('./chunk-56QKBG2R.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDQCPGPXGcjs = require('./chunk-DQCPGPXG.cjs');var _crypto = require('crypto'); var $ = _interopRequireWildcard(_crypto);var _jsonwebtoken = require('jsonwebtoken'); var A = _interopRequireWildcard(_jsonwebtoken);function B(c,p,t){let n=Buffer.from(t,"base64"),u=Buffer.from(p,"base64"),f="id-aes256-wrap-pad",l=Buffer.from("A65959A6","hex"),o=$.createCipheriv(f,u,l),s={encryptedIdentifier:Buffer.concat([o.update(c),o.final()]).toString("base64")};return A.sign(s,n,{algorithm:"HS384"})}var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _iots = require('io-ts'); var r = _interopRequireWildcard(_iots);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _typeutils = require('@transcend-io/type-utils');var I=/^[0-9][Y|N]([Y|N])[Y|N]$/,R= exports.c =r.record(r.string,r.union([r.boolean,r.literal("Auto")]));async function q({base64EncryptionKey:c,base64SigningKey:p,preferences:t,partition:n,concurrency:u=100,transcendUrl:f=_chunkDQCPGPXGcjs.s}){let l=_chunk56QKBG2Rcjs.Bc.call(void 0, f),o=t.filter(e=>e.usp&&!I.test(e.usp));if(o.length>0)throw new Error(`Received invalid usp strings: ${JSON.stringify(o,null,2)}`);let d=t.map((e,g)=>[e,g]).filter(([e])=>{if(!e.purposes)return!1;try{return _typeutils.decodeCodec.call(void 0, R,e.purposes),!1}catch (e2){return!0}});if(d.length>0)throw new Error(`Received invalid purpose maps: ${JSON.stringify(d,null,2)}`);let s=t.filter(e=>!e.usp&&!e.purposes);if(s.length>0)throw new Error(`Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(s,null,2)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${t.length} user preferences to partition ${n}`));let S=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),v=0;m.start(t.length,0),await _chunk56QKBG2Rcjs.a.call(void 0, t,async({userId:e,confirmed:g="true",updated:C,prompted:P,purposes:N,...i})=>{let _=B(e,c,p),[,j]=i.usp?I.exec(i.usp)||[]:[],k={token:_,partition:n,consent:{confirmed:g==="true",purposes:N?_typeutils.decodeCodec.call(void 0, R,N):i.usp?{SaleOfInfo:j==="Y"}:{},...C?{updated:C==="true"}:{},...P?{prompted:P==="true"}:{},...i}};try{await l.post("sync",{json:k}).json()}catch(y){try{let h=JSON.parse(_optionalChain([y, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||"{}");h.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${h.error}`))}catch (e3){}throw new Error(`Received an error from server: ${_optionalChain([y, 'optionalAccess', _4 => _4.response, 'optionalAccess', _5 => _5.body])||_optionalChain([y, 'optionalAccess', _6 => _6.message])}`)}v+=1,m.update(v)},{concurrency:u}),m.stop();let O=new Date().getTime()-S;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${t.length} user preferences to partition ${n} in "${O/1e3}" seconds!`))}exports.a = B; exports.b = I; exports.c = R; exports.d = q;
2
- //# sourceMappingURL=chunk-D3VRD5F5.cjs.map
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 _chunkKYOQWIIScjs = require('./chunk-KYOQWIIS.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunk5MG2CEZVcjs = require('./chunk-5MG2CEZV.cjs');var _crypto = require('crypto'); var $ = _interopRequireWildcard(_crypto);var _jsonwebtoken = require('jsonwebtoken'); var A = _interopRequireWildcard(_jsonwebtoken);function B(c,p,t){let n=Buffer.from(t,"base64"),u=Buffer.from(p,"base64"),f="id-aes256-wrap-pad",l=Buffer.from("A65959A6","hex"),o=$.createCipheriv(f,u,l),s={encryptedIdentifier:Buffer.concat([o.update(c),o.final()]).toString("base64")};return A.sign(s,n,{algorithm:"HS384"})}var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _iots = require('io-ts'); var r = _interopRequireWildcard(_iots);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _typeutils = require('@transcend-io/type-utils');var I=/^[0-9][Y|N]([Y|N])[Y|N]$/,R= exports.c =r.record(r.string,r.union([r.boolean,r.literal("Auto")]));async function q({base64EncryptionKey:c,base64SigningKey:p,preferences:t,partition:n,concurrency:u=100,transcendUrl:f=_chunk5MG2CEZVcjs.s}){let l=_chunkKYOQWIIScjs.Bc.call(void 0, f),o=t.filter(e=>e.usp&&!I.test(e.usp));if(o.length>0)throw new Error(`Received invalid usp strings: ${JSON.stringify(o,null,2)}`);let d=t.map((e,g)=>[e,g]).filter(([e])=>{if(!e.purposes)return!1;try{return _typeutils.decodeCodec.call(void 0, R,e.purposes),!1}catch (e2){return!0}});if(d.length>0)throw new Error(`Received invalid purpose maps: ${JSON.stringify(d,null,2)}`);let s=t.filter(e=>!e.usp&&!e.purposes);if(s.length>0)throw new Error(`Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(s,null,2)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${t.length} user preferences to partition ${n}`));let S=new Date().getTime(),m=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),v=0;m.start(t.length,0),await _chunkKYOQWIIScjs.a.call(void 0, t,async({userId:e,confirmed:g="true",updated:C,prompted:P,purposes:N,...i})=>{let _=B(e,c,p),[,j]=i.usp?I.exec(i.usp)||[]:[],k={token:_,partition:n,consent:{confirmed:g==="true",purposes:N?_typeutils.decodeCodec.call(void 0, R,N):i.usp?{SaleOfInfo:j==="Y"}:{},...C?{updated:C==="true"}:{},...P?{prompted:P==="true"}:{},...i}};try{await l.post("sync",{json:k}).json()}catch(y){try{let h=JSON.parse(_optionalChain([y, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||"{}");h.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${h.error}`))}catch (e3){}throw new Error(`Received an error from server: ${_optionalChain([y, 'optionalAccess', _4 => _4.response, 'optionalAccess', _5 => _5.body])||_optionalChain([y, 'optionalAccess', _6 => _6.message])}`)}v+=1,m.update(v)},{concurrency:u}),m.stop();let O=new Date().getTime()-S;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${t.length} user preferences to partition ${n} in "${O/1e3}" seconds!`))}exports.a = B; exports.b = I; exports.c = R; exports.d = q;
2
+ //# sourceMappingURL=chunk-HZU3YROT.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-D3VRD5F5.cjs","../src/lib/consent-manager/createConsentToken.ts","../src/lib/consent-manager/uploadConsents.ts"],"names":["createConsentToken","userId","base64EncryptionKey","base64SigningKey","signingKey","encryptionKey","encryptionAlgorithm","iv","cipher","jwtPayload","USP_STRING_REGEX","PurposeMap","uploadConsents","preferences","partition","concurrency","transcendUrl","DEFAULT_TRANSCEND_CONSENT_API","transcendConsentApi","createTranscendConsentGotInstance","invalidUspStrings","pref"],"mappings":"AAAA,u/BAAgD,wDAAoC,wDAAyC,0ECArG,4FACH,SAWLA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACQ,CAER,IAAMC,CAAAA,CAAa,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAkB,QAAQ,CAAA,CACnDE,CAAAA,CAAgB,MAAA,CAAO,IAAA,CAAKH,CAAAA,CAAqB,QAAQ,CAAA,CAGzDI,CAAAA,CAAsB,oBAAA,CAEtBC,CAAAA,CAAK,MAAA,CAAO,IAAA,CAAK,UAAA,CAAY,KAAK,CAAA,CAElCC,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAeF,CAAAA,CAAqBD,CAAAA,CAAeE,CAAE,CAAA,CAYrEE,CAAAA,CAAa,CACjB,mBAAA,CAV0B,MAAA,CAAO,MAAA,CAAO,CACxCD,CAAAA,CAAO,MAAA,CAAOP,CAAM,CAAA,CACpBO,CAAAA,CAAO,KAAA,CAAM,CACf,CAAC,CAAA,CAAE,QAAA,CAAS,QAAQ,CAQpB,CAAA,CAOA,OAJyB,CAAA,CAAA,IAAA,CAAKC,CAAAA,CAAYL,CAAAA,CAAY,CACpD,SAAA,CAAW,OACb,CAAC,CAGH,CC/CA,gFAAmB,qEACA,qGAKK,qDACI,IAIfM,CAAAA,CAAmB,0BAAA,CAEnBC,CAAAA,aAAe,CAAA,CAAA,MAAA,CACxB,CAAA,CAAA,MAAA,CACA,CAAA,CAAA,KAAA,CAAM,CAAG,CAAA,CAAA,OAAA,CAAW,CAAA,CAAA,OAAA,CAAQ,MAAM,CAAC,CAAC,CACxC,CAAA,CAOA,MAAA,SAAsBC,CAAAA,CAAe,CACnC,mBAAA,CAAAV,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,WAAA,CAAAU,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAakB,CAEhB,IAAMC,CAAAA,CAAsBC,kCAAAA,CAA8C,CAAA,CAGpEC,CAAAA,CAAoBP,CAAAA,CAAY,MAAA,CACnCQ,CAAAA,EAASA,CAAAA,CAAK,GAAA,EAAO,CAACX,CAAAA,CAAiB,IAAA,CAAKW,CAAAA,CAAK,GAAG,CACvD,CAAA,CACA,EAAA,CAAID,CAAAA,CAAkB,MAAA,CAAS,CAAA,CAC7B,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiC,IAAA,CAAK,SAAA,CACpCA,CAAAA,CACA,IAAA,CACA,CACF,CAAC,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-D3VRD5F5.cjs","sourcesContent":[null,"import * as crypto from 'crypto';\nimport * as jwt from 'jsonwebtoken';\n\n/**\n * Function to create a consent manager token\n *\n * @see https://docs.transcend.io/docs/consent/reference/managed-consent-database\n * @param userId - User ID\n * @param base64EncryptionKey - Encryption key\n * @param base64SigningKey - Signing key\n * @returns Token\n */\nexport function createConsentToken(\n userId: string,\n base64EncryptionKey: string,\n base64SigningKey: string,\n): string {\n // Read on for where to find these keys\n const signingKey = Buffer.from(base64SigningKey, 'base64');\n const encryptionKey = Buffer.from(base64EncryptionKey, 'base64');\n\n // NIST's AES-KWP implementation { aes 48 } - see https://tools.ietf.org/html/rfc5649\n const encryptionAlgorithm = 'id-aes256-wrap-pad';\n // Initial Value for AES-KWP integrity check - see https://tools.ietf.org/html/rfc5649#section-3\n const iv = Buffer.from('A65959A6', 'hex');\n // Set up encryption algorithm\n const cipher = crypto.createCipheriv(encryptionAlgorithm, encryptionKey, iv);\n\n // Encrypt the userId and base64-encode the result\n const encryptedIdentifier = Buffer.concat([\n cipher.update(userId),\n cipher.final(),\n ]).toString('base64');\n\n // Create the JWT content - jwt.sign will add a 'iat' (issued at) field to the payload\n // If you wanted to add something manually, consider\n // const issued: Date = new Date();\n // const isoDate = issued.toISOString();\n const jwtPayload = {\n encryptedIdentifier,\n };\n\n // Create a JSON web token and HMAC it with SHA-384\n const consentToken = jwt.sign(jwtPayload, signingKey, {\n algorithm: 'HS384',\n });\n\n return consentToken;\n}\n","import { createTranscendConsentGotInstance } from '../graphql';\nimport colors from 'colors';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_CONSENT_API } from '../../constants';\nimport { map } from '../bluebird';\nimport { createConsentToken } from './createConsentToken';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport type { ConsentPreferenceUpload } from './types';\nimport { ConsentPreferencesBody } from '@transcend-io/airgap.js-types';\n\nexport const USP_STRING_REGEX = /^[0-9][Y|N]([Y|N])[Y|N]$/;\n\nexport const PurposeMap = t.record(\n t.string,\n t.union([t.boolean, t.literal('Auto')]),\n);\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadConsents({\n base64EncryptionKey,\n base64SigningKey,\n preferences,\n partition,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_CONSENT_API,\n}: {\n /** base64 encryption key */\n base64EncryptionKey: string;\n /** base64 signing key */\n base64SigningKey: string;\n /** Partition key */\n partition: string;\n /** Sombra API key authentication */\n preferences: ConsentPreferenceUpload[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Concurrency limit for approving */\n concurrency?: number;\n}): Promise<void> {\n // Create connection to API\n const transcendConsentApi = createTranscendConsentGotInstance(transcendUrl);\n\n // Ensure usp strings are valid\n const invalidUspStrings = preferences.filter(\n (pref) => pref.usp && !USP_STRING_REGEX.test(pref.usp),\n );\n if (invalidUspStrings.length > 0) {\n throw new Error(\n `Received invalid usp strings: ${JSON.stringify(\n invalidUspStrings,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure purpose maps are valid\n const invalidPurposeMaps = preferences\n .map((pref, ind) => [pref, ind] as [ConsentPreferenceUpload, number])\n .filter(([pref]) => {\n if (!pref.purposes) {\n return false;\n }\n try {\n decodeCodec(PurposeMap, pref.purposes);\n return false;\n } catch {\n return true;\n }\n });\n if (invalidPurposeMaps.length > 0) {\n throw new Error(\n `Received invalid purpose maps: ${JSON.stringify(\n invalidPurposeMaps,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure usp or preferences are provided\n const invalidInputs = preferences.filter(\n (pref) => !pref.usp && !pref.purposes,\n );\n if (invalidInputs.length > 0) {\n throw new Error(\n `Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(\n invalidInputs,\n null,\n 2,\n )}`,\n );\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${preferences.length} user preferences to partition ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n progressBar.start(preferences.length, 0);\n await map(\n preferences,\n async ({\n userId,\n confirmed = 'true',\n updated,\n prompted,\n purposes,\n ...consent\n }) => {\n const token = createConsentToken(\n userId,\n base64EncryptionKey,\n base64SigningKey,\n );\n\n // parse usp string\n const [, saleStatus] = consent.usp\n ? USP_STRING_REGEX.exec(consent.usp) || []\n : [];\n\n const input = {\n token,\n partition,\n consent: {\n confirmed: confirmed === 'true',\n purposes: purposes\n ? decodeCodec(PurposeMap, purposes)\n : consent.usp\n ? { SaleOfInfo: saleStatus === 'Y' }\n : {},\n ...(updated ? { updated: updated === 'true' } : {}),\n ...(prompted ? { prompted: prompted === 'true' } : {}),\n ...consent,\n },\n } as ConsentPreferencesBody;\n\n // Make the request\n try {\n await transcendConsentApi\n .post('sync', {\n json: input,\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n throw new Error(\n `Received an error from server: ${\n err?.response?.body || err?.message\n }`,\n );\n }\n\n total += 1;\n progressBar.update(total);\n },\n { concurrency },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully uploaded ${\n preferences.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-HZU3YROT.cjs","../src/lib/consent-manager/createConsentToken.ts","../src/lib/consent-manager/uploadConsents.ts"],"names":["createConsentToken","userId","base64EncryptionKey","base64SigningKey","signingKey","encryptionKey","encryptionAlgorithm","iv","cipher","jwtPayload","USP_STRING_REGEX","PurposeMap","uploadConsents","preferences","partition","concurrency","transcendUrl","DEFAULT_TRANSCEND_CONSENT_API","transcendConsentApi","createTranscendConsentGotInstance","invalidUspStrings","pref"],"mappings":"AAAA,u/BAAgD,wDAAoC,wDAAyC,0ECArG,4FACH,SAWLA,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACQ,CAER,IAAMC,CAAAA,CAAa,MAAA,CAAO,IAAA,CAAKD,CAAAA,CAAkB,QAAQ,CAAA,CACnDE,CAAAA,CAAgB,MAAA,CAAO,IAAA,CAAKH,CAAAA,CAAqB,QAAQ,CAAA,CAGzDI,CAAAA,CAAsB,oBAAA,CAEtBC,CAAAA,CAAK,MAAA,CAAO,IAAA,CAAK,UAAA,CAAY,KAAK,CAAA,CAElCC,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAeF,CAAAA,CAAqBD,CAAAA,CAAeE,CAAE,CAAA,CAYrEE,CAAAA,CAAa,CACjB,mBAAA,CAV0B,MAAA,CAAO,MAAA,CAAO,CACxCD,CAAAA,CAAO,MAAA,CAAOP,CAAM,CAAA,CACpBO,CAAAA,CAAO,KAAA,CAAM,CACf,CAAC,CAAA,CAAE,QAAA,CAAS,QAAQ,CAQpB,CAAA,CAOA,OAJyB,CAAA,CAAA,IAAA,CAAKC,CAAAA,CAAYL,CAAAA,CAAY,CACpD,SAAA,CAAW,OACb,CAAC,CAGH,CC/CA,gFAAmB,qEACA,qGAKK,qDACI,IAIfM,CAAAA,CAAmB,0BAAA,CAEnBC,CAAAA,aAAe,CAAA,CAAA,MAAA,CACxB,CAAA,CAAA,MAAA,CACA,CAAA,CAAA,KAAA,CAAM,CAAG,CAAA,CAAA,OAAA,CAAW,CAAA,CAAA,OAAA,CAAQ,MAAM,CAAC,CAAC,CACxC,CAAA,CAOA,MAAA,SAAsBC,CAAAA,CAAe,CACnC,mBAAA,CAAAV,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,WAAA,CAAAU,CAAAA,CACA,SAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAakB,CAEhB,IAAMC,CAAAA,CAAsBC,kCAAAA,CAA8C,CAAA,CAGpEC,CAAAA,CAAoBP,CAAAA,CAAY,MAAA,CACnCQ,CAAAA,EAASA,CAAAA,CAAK,GAAA,EAAO,CAACX,CAAAA,CAAiB,IAAA,CAAKW,CAAAA,CAAK,GAAG,CACvD,CAAA,CACA,EAAA,CAAID,CAAAA,CAAkB,MAAA,CAAS,CAAA,CAC7B,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiC,IAAA,CAAK,SAAA,CACpCA,CAAAA,CACA,IAAA,CACA,CACF,CAAC,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-HZU3YROT.cjs","sourcesContent":[null,"import * as crypto from 'crypto';\nimport * as jwt from 'jsonwebtoken';\n\n/**\n * Function to create a consent manager token\n *\n * @see https://docs.transcend.io/docs/consent/reference/managed-consent-database\n * @param userId - User ID\n * @param base64EncryptionKey - Encryption key\n * @param base64SigningKey - Signing key\n * @returns Token\n */\nexport function createConsentToken(\n userId: string,\n base64EncryptionKey: string,\n base64SigningKey: string,\n): string {\n // Read on for where to find these keys\n const signingKey = Buffer.from(base64SigningKey, 'base64');\n const encryptionKey = Buffer.from(base64EncryptionKey, 'base64');\n\n // NIST's AES-KWP implementation { aes 48 } - see https://tools.ietf.org/html/rfc5649\n const encryptionAlgorithm = 'id-aes256-wrap-pad';\n // Initial Value for AES-KWP integrity check - see https://tools.ietf.org/html/rfc5649#section-3\n const iv = Buffer.from('A65959A6', 'hex');\n // Set up encryption algorithm\n const cipher = crypto.createCipheriv(encryptionAlgorithm, encryptionKey, iv);\n\n // Encrypt the userId and base64-encode the result\n const encryptedIdentifier = Buffer.concat([\n cipher.update(userId),\n cipher.final(),\n ]).toString('base64');\n\n // Create the JWT content - jwt.sign will add a 'iat' (issued at) field to the payload\n // If you wanted to add something manually, consider\n // const issued: Date = new Date();\n // const isoDate = issued.toISOString();\n const jwtPayload = {\n encryptedIdentifier,\n };\n\n // Create a JSON web token and HMAC it with SHA-384\n const consentToken = jwt.sign(jwtPayload, signingKey, {\n algorithm: 'HS384',\n });\n\n return consentToken;\n}\n","import { createTranscendConsentGotInstance } from '../graphql';\nimport colors from 'colors';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_CONSENT_API } from '../../constants';\nimport { map } from '../bluebird';\nimport { createConsentToken } from './createConsentToken';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport type { ConsentPreferenceUpload } from './types';\nimport { ConsentPreferencesBody } from '@transcend-io/airgap.js-types';\n\nexport const USP_STRING_REGEX = /^[0-9][Y|N]([Y|N])[Y|N]$/;\n\nexport const PurposeMap = t.record(\n t.string,\n t.union([t.boolean, t.literal('Auto')]),\n);\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadConsents({\n base64EncryptionKey,\n base64SigningKey,\n preferences,\n partition,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_CONSENT_API,\n}: {\n /** base64 encryption key */\n base64EncryptionKey: string;\n /** base64 signing key */\n base64SigningKey: string;\n /** Partition key */\n partition: string;\n /** Sombra API key authentication */\n preferences: ConsentPreferenceUpload[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Concurrency limit for approving */\n concurrency?: number;\n}): Promise<void> {\n // Create connection to API\n const transcendConsentApi = createTranscendConsentGotInstance(transcendUrl);\n\n // Ensure usp strings are valid\n const invalidUspStrings = preferences.filter(\n (pref) => pref.usp && !USP_STRING_REGEX.test(pref.usp),\n );\n if (invalidUspStrings.length > 0) {\n throw new Error(\n `Received invalid usp strings: ${JSON.stringify(\n invalidUspStrings,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure purpose maps are valid\n const invalidPurposeMaps = preferences\n .map((pref, ind) => [pref, ind] as [ConsentPreferenceUpload, number])\n .filter(([pref]) => {\n if (!pref.purposes) {\n return false;\n }\n try {\n decodeCodec(PurposeMap, pref.purposes);\n return false;\n } catch {\n return true;\n }\n });\n if (invalidPurposeMaps.length > 0) {\n throw new Error(\n `Received invalid purpose maps: ${JSON.stringify(\n invalidPurposeMaps,\n null,\n 2,\n )}`,\n );\n }\n\n // Ensure usp or preferences are provided\n const invalidInputs = preferences.filter(\n (pref) => !pref.usp && !pref.purposes,\n );\n if (invalidInputs.length > 0) {\n throw new Error(\n `Received invalid inputs, expected either purposes or usp to be defined: ${JSON.stringify(\n invalidInputs,\n null,\n 2,\n )}`,\n );\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${preferences.length} user preferences to partition ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n progressBar.start(preferences.length, 0);\n await map(\n preferences,\n async ({\n userId,\n confirmed = 'true',\n updated,\n prompted,\n purposes,\n ...consent\n }) => {\n const token = createConsentToken(\n userId,\n base64EncryptionKey,\n base64SigningKey,\n );\n\n // parse usp string\n const [, saleStatus] = consent.usp\n ? USP_STRING_REGEX.exec(consent.usp) || []\n : [];\n\n const input = {\n token,\n partition,\n consent: {\n confirmed: confirmed === 'true',\n purposes: purposes\n ? decodeCodec(PurposeMap, purposes)\n : consent.usp\n ? { SaleOfInfo: saleStatus === 'Y' }\n : {},\n ...(updated ? { updated: updated === 'true' } : {}),\n ...(prompted ? { prompted: prompted === 'true' } : {}),\n ...consent,\n },\n } as ConsentPreferencesBody;\n\n // Make the request\n try {\n await transcendConsentApi\n .post('sync', {\n json: input,\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n throw new Error(\n `Received an error from server: ${\n err?.response?.body || err?.message\n }`,\n );\n }\n\n total += 1;\n progressBar.update(total);\n },\n { concurrency },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n logger.info(\n colors.green(\n `Successfully uploaded ${\n preferences.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n"]}
@@ -1,3 +1,3 @@
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 }; }var _chunk56QKBG2Rcjs = require('./chunk-56QKBG2R.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkDQCPGPXGcjs = require('./chunk-DQCPGPXG.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function re({file:u,auth:s,sombraAuth:g,requestActions:f=[],concurrency:p=100,transcendUrl:n=_chunkDQCPGPXGcjs.r}){let o=_chunk56QKBG2Rcjs.zc.call(void 0, n,s),e=await _chunk56QKBG2Rcjs.Ac.call(void 0, n,s,g);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling manual enrichment requests, filtered for actions: ${f.join(",")}`));let d=await _chunk56QKBG2Rcjs.qd.call(void 0, o,{actions:f,statuses:[_privacytypes.RequestStatus.Enriching]}),i=[];await _chunk56QKBG2Rcjs.a.call(void 0, d,async t=>{let c=await _chunk56QKBG2Rcjs.kd.call(void 0, o,{requestId:t.id});if(c.filter(({status:m})=>m==="ACTION_REQUIRED")){let m=await _chunk56QKBG2Rcjs.nd.call(void 0, o,e,{requestId:t.id});i.push({...t,requestIdentifiers:m,requestEnrichers:c})}},{concurrency:p});let l=i.map(({attributeValues:t,requestIdentifiers:c,requestEnrichers:I,...m})=>({...m,...Object.entries(_chunkDQCPGPXGcjs.d.call(void 0, c,"name")).reduce((P,[$,C])=>Object.assign(P,{[$]:C.map(({value:A})=>A).join(",")}),{}),...Object.entries(_chunkDQCPGPXGcjs.d.call(void 0, t,"attributeKey.name")).reduce((P,[$,C])=>Object.assign(P,{[$]:C.map(({name:A})=>A).join(",")}),{})})),a=_chunkDQCPGPXGcjs.j.call(void 0, l.map(t=>Object.keys(t)).flat());return await _chunk56QKBG2Rcjs.tg.call(void 0, u,l,a),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${i.length} requests to file "${u}"`)),i}var _iots = require('io-ts'); var R = _interopRequireWildcard(_iots);var j="https://app.transcend.io/privacy-requests/incoming-requests/",M= exports.b =R.record(R.string,R.string);async function N(u,{id:s,...g},f,p){if(!s){let e=`Request ID must be provided to enricher request.${p?` Found error in row: ${p}`:""}`;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(e)),new Error(e)}let n=s.toLowerCase(),o=Object.entries(g).reduce((e,[d,i])=>_chunkDQCPGPXGcjs.j.call(void 0, _chunk56QKBG2Rcjs.rc.call(void 0, i)).length===0?e:Object.assign(e,{[d]:_chunkDQCPGPXGcjs.j.call(void 0, _chunk56QKBG2Rcjs.rc.call(void 0, i)).map(a=>({value:d==="email"?a.toLowerCase():a}))}),{});try{return await u.post("v1/enrich-identifiers",{headers:{"x-transcend-request-id":n,"x-transcend-enricher-id":f},json:{enrichedIdentifiers:o}}).json(),_chunkZUNVPK23cjs.a.error(_colors2.default.green(`Successfully enriched request: ${j}${n}`)),!0}catch(e){if(typeof e.response.body=="string"&&e.response.body.includes("Cannot update a resolved RequestEnricher"))return _chunkZUNVPK23cjs.a.warn(_colors2.default.magenta(`Skipped enrichment for request: ${j}${n}, request is no longer in the enriching phase.`)),!1;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to enricher identifiers for request with id: ${j}${n} - ${e.message} - ${e.response.body}`)),e}}async function he({file:u,auth:s,sombraAuth:g,enricherId:f,markSilent:p,concurrency:n=100,transcendUrl:o=_chunkDQCPGPXGcjs.r}){let e=await _chunk56QKBG2Rcjs.Ac.call(void 0, o,s,g),d=_chunk56QKBG2Rcjs.zc.call(void 0, o,s);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${u}" from disk`));let i=_chunk56QKBG2Rcjs.uc.call(void 0, u,M);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Enriching "${i.length}" privacy requests.`));let l=0,a=0,t=0;if(await _chunk56QKBG2Rcjs.a.call(void 0, i,async(c,I)=>{try{p&&(await _chunk56QKBG2Rcjs.wg.call(void 0, d,_chunk56QKBG2Rcjs.$,{input:{id:c.id,isSilent:!0}}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Mark request as silent mode - ${c.id}`))),await N(e,c,f,I)?l+=1:a+=1}catch (e2){t+=1}},{concurrency:n}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend!
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 }; }var _chunkKYOQWIIScjs = require('./chunk-KYOQWIIS.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunk5MG2CEZVcjs = require('./chunk-5MG2CEZV.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function re({file:u,auth:s,sombraAuth:g,requestActions:f=[],concurrency:p=100,transcendUrl:n=_chunk5MG2CEZVcjs.r}){let o=_chunkKYOQWIIScjs.zc.call(void 0, n,s),e=await _chunkKYOQWIIScjs.Ac.call(void 0, n,s,g);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling manual enrichment requests, filtered for actions: ${f.join(",")}`));let d=await _chunkKYOQWIIScjs.qd.call(void 0, o,{actions:f,statuses:[_privacytypes.RequestStatus.Enriching]}),i=[];await _chunkKYOQWIIScjs.a.call(void 0, d,async t=>{let c=await _chunkKYOQWIIScjs.kd.call(void 0, o,{requestId:t.id});if(c.filter(({status:m})=>m==="ACTION_REQUIRED")){let m=await _chunkKYOQWIIScjs.nd.call(void 0, o,e,{requestId:t.id});i.push({...t,requestIdentifiers:m,requestEnrichers:c})}},{concurrency:p});let l=i.map(({attributeValues:t,requestIdentifiers:c,requestEnrichers:I,...m})=>({...m,...Object.entries(_chunk5MG2CEZVcjs.d.call(void 0, c,"name")).reduce((P,[$,C])=>Object.assign(P,{[$]:C.map(({value:A})=>A).join(",")}),{}),...Object.entries(_chunk5MG2CEZVcjs.d.call(void 0, t,"attributeKey.name")).reduce((P,[$,C])=>Object.assign(P,{[$]:C.map(({name:A})=>A).join(",")}),{})})),a=_chunk5MG2CEZVcjs.j.call(void 0, l.map(t=>Object.keys(t)).flat());return await _chunkKYOQWIIScjs.tg.call(void 0, u,l,a),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${i.length} requests to file "${u}"`)),i}var _iots = require('io-ts'); var R = _interopRequireWildcard(_iots);var j="https://app.transcend.io/privacy-requests/incoming-requests/",M= exports.b =R.record(R.string,R.string);async function N(u,{id:s,...g},f,p){if(!s){let e=`Request ID must be provided to enricher request.${p?` Found error in row: ${p}`:""}`;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(e)),new Error(e)}let n=s.toLowerCase(),o=Object.entries(g).reduce((e,[d,i])=>_chunk5MG2CEZVcjs.j.call(void 0, _chunkKYOQWIIScjs.rc.call(void 0, i)).length===0?e:Object.assign(e,{[d]:_chunk5MG2CEZVcjs.j.call(void 0, _chunkKYOQWIIScjs.rc.call(void 0, i)).map(a=>({value:d==="email"?a.toLowerCase():a}))}),{});try{return await u.post("v1/enrich-identifiers",{headers:{"x-transcend-request-id":n,"x-transcend-enricher-id":f},json:{enrichedIdentifiers:o}}).json(),_chunkZUNVPK23cjs.a.error(_colors2.default.green(`Successfully enriched request: ${j}${n}`)),!0}catch(e){if(typeof e.response.body=="string"&&e.response.body.includes("Cannot update a resolved RequestEnricher"))return _chunkZUNVPK23cjs.a.warn(_colors2.default.magenta(`Skipped enrichment for request: ${j}${n}, request is no longer in the enriching phase.`)),!1;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to enricher identifiers for request with id: ${j}${n} - ${e.message} - ${e.response.body}`)),e}}async function he({file:u,auth:s,sombraAuth:g,enricherId:f,markSilent:p,concurrency:n=100,transcendUrl:o=_chunk5MG2CEZVcjs.r}){let e=await _chunkKYOQWIIScjs.Ac.call(void 0, o,s,g),d=_chunkKYOQWIIScjs.zc.call(void 0, o,s);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${u}" from disk`));let i=_chunkKYOQWIIScjs.uc.call(void 0, u,M);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Enriching "${i.length}" privacy requests.`));let l=0,a=0,t=0;if(await _chunkKYOQWIIScjs.a.call(void 0, i,async(c,I)=>{try{p&&(await _chunkKYOQWIIScjs.wg.call(void 0, d,_chunkKYOQWIIScjs.$,{input:{id:c.id,isSilent:!0}}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Mark request as silent mode - ${c.id}`))),await N(e,c,f,I)?l+=1:a+=1}catch (e2){t+=1}},{concurrency:n}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend!
2
2
  Success count: ${l}.`)),a>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Skipped count: ${a}.`)),t>0)throw _chunkZUNVPK23cjs.a.info(_colors2.default.red(`Error Count: ${t}.`)),new Error(`Failed to enrich: ${t} requests.`);return i.length}exports.a = re; exports.b = M; exports.c = N; exports.d = he;
3
- //# sourceMappingURL=chunk-6TKTYQIF.cjs.map
3
+ //# sourceMappingURL=chunk-ILBF5XZN.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-6TKTYQIF.cjs","../src/lib/manual-enrichment/pullManualEnrichmentIdentifiersToCsv.ts","../src/lib/manual-enrichment/pushManualEnrichmentIdentifiersFromCsv.ts"],"names":["pullManualEnrichmentIdentifiersToCsv","file","auth","sombraAuth","requestActions","concurrency","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClient","sombra","createSombraGotInstance","logger","colors"],"mappings":"AAAA,mfAAuH,wDAAyC,wDAAuD,2DCA1K,gFAE1B,MA6BnB,SAAsBA,EAAAA,CAAqC,CACzD,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CAAiB,CAAC,CAAA,CAClB,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAa6C,CAE3C,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BH,CAAcJ,CAAI,CAAA,CACvDQ,CAAAA,CAAS,MAAMC,kCAAAA,CAAwBL,CAAcJ,CAAAA,CAAMC,CAAU,CAAA,CAE3ES,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,0DAAA,EAA6DT,CAAAA,CAAe,IAAA,CAC1E,GACF,CAAC,CAAA,CAAA;ACuDP,gBAAA","file":"/home/runner/work/cli/cli/dist/chunk-6TKTYQIF.cjs","sourcesContent":[null,"import { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { map } from '../bluebird';\nimport colors from 'colors';\nimport { groupBy, uniq } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport { writeCsv } from '../helpers/writeCsv';\nimport {\n PrivacyRequest,\n RequestEnricher,\n RequestIdentifier,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllRequestEnrichers,\n fetchAllRequestIdentifiers,\n fetchAllRequests,\n} from '../graphql';\nimport { logger } from '../../logger';\n\nexport interface PrivacyRequestWithIdentifiers extends PrivacyRequest {\n /** Request Enrichers */\n requestEnrichers: RequestEnricher[];\n /** Request Identifiers */\n requestIdentifiers: RequestIdentifier[];\n}\n\n/**\n * Pull the set of manual enrichment jobs to CSV\n *\n * @param options - Options\n * @returns List of requests with identifiers\n */\nexport async function pullManualEnrichmentIdentifiersToCsv({\n file,\n auth,\n sombraAuth,\n requestActions = [],\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** Sombra API key */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** The request actions to fetch */\n requestActions?: RequestAction[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n}): Promise<PrivacyRequestWithIdentifiers[]> {\n // Find all requests made before createdAt that are in a removing data state\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n logger.info(\n colors.magenta(\n `Pulling manual enrichment requests, filtered for actions: ${requestActions.join(\n ',',\n )}`,\n ),\n );\n\n // Pull all privacy requests\n const allRequests = await fetchAllRequests(client, {\n actions: requestActions,\n statuses: [RequestStatus.Enriching],\n });\n\n // Requests to save\n const savedRequests: PrivacyRequestWithIdentifiers[] = [];\n\n // Filter down requests to what is needed\n await map(\n allRequests,\n async (request) => {\n // Fetch enrichers\n const requestEnrichers = await fetchAllRequestEnrichers(client, {\n requestId: request.id,\n });\n\n // Check if manual enrichment exists for that request\n const hasManualEnrichment = requestEnrichers.filter(\n ({ status }) => status === 'ACTION_REQUIRED',\n );\n\n // Save request to queue\n if (hasManualEnrichment) {\n const requestIdentifiers = await fetchAllRequestIdentifiers(\n client,\n sombra,\n {\n requestId: request.id,\n },\n );\n savedRequests.push({\n ...request,\n requestIdentifiers,\n requestEnrichers,\n });\n }\n },\n {\n concurrency,\n },\n );\n\n const data = savedRequests.map(\n ({\n attributeValues,\n requestIdentifiers,\n requestEnrichers, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...request\n }) => ({\n ...request,\n // flatten identifiers\n ...Object.entries(groupBy(requestIdentifiers, 'name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ value }) => value).join(','),\n }),\n {},\n ),\n // flatten attributes\n ...Object.entries(groupBy(attributeValues, 'attributeKey.name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ name }) => name).join(','),\n }),\n {},\n ),\n }),\n );\n\n // Write out to CSV\n const headers = uniq(data.map((d) => Object.keys(d)).flat());\n await writeCsv(file, data, headers);\n\n logger.info(\n colors.green(\n `Successfully wrote ${savedRequests.length} requests to file \"${file}\"`,\n ),\n );\n\n return savedRequests;\n}\n","import colors from 'colors';\nimport { map } from '../bluebird';\nimport { logger } from '../../logger';\nimport {\n UPDATE_PRIVACY_REQUEST,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n makeGraphQLRequest,\n} from '../graphql';\nimport {\n enrichPrivacyRequest,\n EnrichPrivacyRequest,\n} from './enrichPrivacyRequest';\nimport { readCsv } from '../requests';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\n/**\n * Push a CSV of enriched requests back into Transcend\n *\n * @param options - Options\n * @returns Number of items processed\n */\nexport async function pushManualEnrichmentIdentifiersFromCsv({\n file,\n auth,\n sombraAuth,\n enricherId,\n markSilent,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** ID of enricher being uploaded to */\n enricherId: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Mark requests in silent mode before enriching */\n markSilent?: boolean;\n}): Promise<number> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read from CSV\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, EnrichPrivacyRequest);\n\n // Notify Transcend\n logger.info(\n colors.magenta(`Enriching \"${activeResults.length}\" privacy requests.`),\n );\n\n let successCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n\n await map(\n activeResults,\n async (request, index) => {\n try {\n // Mark requests in silent mode before a certain date\n if (markSilent) {\n await makeGraphQLRequest(client, UPDATE_PRIVACY_REQUEST, {\n input: {\n id: request.id,\n isSilent: true,\n },\n });\n\n logger.info(\n colors.magenta(`Mark request as silent mode - ${request.id}`),\n );\n }\n\n const result = await enrichPrivacyRequest(\n sombra,\n request,\n enricherId,\n index,\n );\n if (result) {\n successCount += 1;\n } else {\n skippedCount += 1;\n }\n } catch (err) {\n errorCount += 1;\n }\n },\n { concurrency },\n );\n\n logger.info(\n colors.green(\n `Successfully notified Transcend! \\n Success count: ${successCount}.`,\n ),\n );\n\n if (skippedCount > 0) {\n logger.info(colors.magenta(`Skipped count: ${skippedCount}.`));\n }\n\n if (errorCount > 0) {\n logger.info(colors.red(`Error Count: ${errorCount}.`));\n throw new Error(`Failed to enrich: ${errorCount} requests.`);\n }\n\n return activeResults.length;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-ILBF5XZN.cjs","../src/lib/manual-enrichment/pullManualEnrichmentIdentifiersToCsv.ts","../src/lib/manual-enrichment/pushManualEnrichmentIdentifiersFromCsv.ts"],"names":["pullManualEnrichmentIdentifiersToCsv","file","auth","sombraAuth","requestActions","concurrency","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClient","sombra","createSombraGotInstance","logger","colors"],"mappings":"AAAA,mfAAuH,wDAAyC,wDAAuD,2DCA1K,gFAE1B,MA6BnB,SAAsBA,EAAAA,CAAqC,CACzD,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CAAiB,CAAC,CAAA,CAClB,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAa6C,CAE3C,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BH,CAAcJ,CAAI,CAAA,CACvDQ,CAAAA,CAAS,MAAMC,kCAAAA,CAAwBL,CAAcJ,CAAAA,CAAMC,CAAU,CAAA,CAE3ES,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,0DAAA,EAA6DT,CAAAA,CAAe,IAAA,CAC1E,GACF,CAAC,CAAA,CAAA;ACuDP,gBAAA","file":"/home/runner/work/cli/cli/dist/chunk-ILBF5XZN.cjs","sourcesContent":[null,"import { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { map } from '../bluebird';\nimport colors from 'colors';\nimport { groupBy, uniq } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport { writeCsv } from '../helpers/writeCsv';\nimport {\n PrivacyRequest,\n RequestEnricher,\n RequestIdentifier,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllRequestEnrichers,\n fetchAllRequestIdentifiers,\n fetchAllRequests,\n} from '../graphql';\nimport { logger } from '../../logger';\n\nexport interface PrivacyRequestWithIdentifiers extends PrivacyRequest {\n /** Request Enrichers */\n requestEnrichers: RequestEnricher[];\n /** Request Identifiers */\n requestIdentifiers: RequestIdentifier[];\n}\n\n/**\n * Pull the set of manual enrichment jobs to CSV\n *\n * @param options - Options\n * @returns List of requests with identifiers\n */\nexport async function pullManualEnrichmentIdentifiersToCsv({\n file,\n auth,\n sombraAuth,\n requestActions = [],\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** Sombra API key */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** The request actions to fetch */\n requestActions?: RequestAction[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n}): Promise<PrivacyRequestWithIdentifiers[]> {\n // Find all requests made before createdAt that are in a removing data state\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n logger.info(\n colors.magenta(\n `Pulling manual enrichment requests, filtered for actions: ${requestActions.join(\n ',',\n )}`,\n ),\n );\n\n // Pull all privacy requests\n const allRequests = await fetchAllRequests(client, {\n actions: requestActions,\n statuses: [RequestStatus.Enriching],\n });\n\n // Requests to save\n const savedRequests: PrivacyRequestWithIdentifiers[] = [];\n\n // Filter down requests to what is needed\n await map(\n allRequests,\n async (request) => {\n // Fetch enrichers\n const requestEnrichers = await fetchAllRequestEnrichers(client, {\n requestId: request.id,\n });\n\n // Check if manual enrichment exists for that request\n const hasManualEnrichment = requestEnrichers.filter(\n ({ status }) => status === 'ACTION_REQUIRED',\n );\n\n // Save request to queue\n if (hasManualEnrichment) {\n const requestIdentifiers = await fetchAllRequestIdentifiers(\n client,\n sombra,\n {\n requestId: request.id,\n },\n );\n savedRequests.push({\n ...request,\n requestIdentifiers,\n requestEnrichers,\n });\n }\n },\n {\n concurrency,\n },\n );\n\n const data = savedRequests.map(\n ({\n attributeValues,\n requestIdentifiers,\n requestEnrichers, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...request\n }) => ({\n ...request,\n // flatten identifiers\n ...Object.entries(groupBy(requestIdentifiers, 'name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ value }) => value).join(','),\n }),\n {},\n ),\n // flatten attributes\n ...Object.entries(groupBy(attributeValues, 'attributeKey.name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ name }) => name).join(','),\n }),\n {},\n ),\n }),\n );\n\n // Write out to CSV\n const headers = uniq(data.map((d) => Object.keys(d)).flat());\n await writeCsv(file, data, headers);\n\n logger.info(\n colors.green(\n `Successfully wrote ${savedRequests.length} requests to file \"${file}\"`,\n ),\n );\n\n return savedRequests;\n}\n","import colors from 'colors';\nimport { map } from '../bluebird';\nimport { logger } from '../../logger';\nimport {\n UPDATE_PRIVACY_REQUEST,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n makeGraphQLRequest,\n} from '../graphql';\nimport {\n enrichPrivacyRequest,\n EnrichPrivacyRequest,\n} from './enrichPrivacyRequest';\nimport { readCsv } from '../requests';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\n/**\n * Push a CSV of enriched requests back into Transcend\n *\n * @param options - Options\n * @returns Number of items processed\n */\nexport async function pushManualEnrichmentIdentifiersFromCsv({\n file,\n auth,\n sombraAuth,\n enricherId,\n markSilent,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** ID of enricher being uploaded to */\n enricherId: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Mark requests in silent mode before enriching */\n markSilent?: boolean;\n}): Promise<number> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read from CSV\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, EnrichPrivacyRequest);\n\n // Notify Transcend\n logger.info(\n colors.magenta(`Enriching \"${activeResults.length}\" privacy requests.`),\n );\n\n let successCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n\n await map(\n activeResults,\n async (request, index) => {\n try {\n // Mark requests in silent mode before a certain date\n if (markSilent) {\n await makeGraphQLRequest(client, UPDATE_PRIVACY_REQUEST, {\n input: {\n id: request.id,\n isSilent: true,\n },\n });\n\n logger.info(\n colors.magenta(`Mark request as silent mode - ${request.id}`),\n );\n }\n\n const result = await enrichPrivacyRequest(\n sombra,\n request,\n enricherId,\n index,\n );\n if (result) {\n successCount += 1;\n } else {\n skippedCount += 1;\n }\n } catch (err) {\n errorCount += 1;\n }\n },\n { concurrency },\n );\n\n logger.info(\n colors.green(\n `Successfully notified Transcend! \\n Success count: ${successCount}.`,\n ),\n );\n\n if (skippedCount > 0) {\n logger.info(colors.magenta(`Skipped count: ${skippedCount}.`));\n }\n\n if (errorCount > 0) {\n logger.info(colors.red(`Error Count: ${errorCount}.`));\n throw new Error(`Failed to enrich: ${errorCount} requests.`);\n }\n\n return activeResults.length;\n}\n"]}
@@ -1,4 +1,4 @@
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 }; }var _chunkDQCPGPXGcjs = require('./chunk-DQCPGPXG.cjs');var _chunk7PB6LVSEcjs = require('./chunk-7PB6LVSE.cjs');var _core = require('@stricli/core');var _privacytypes = require('@transcend-io/privacy-types');var _ms = require('ms'); var _ms2 = _interopRequireDefault(_ms);function S(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new Error(`Invalid UUID format: ${e}`);return e}function n(e){try{return new URL(e).toString().replace(/\/$/,"")}catch (e2){throw new Error(`Invalid URL format: ${e}`)}}function T(e){return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function y(e){let r=new Date(e);if(Number.isNaN(r.getTime()))throw new TypeError(`Invalid date: ${e}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`);return r}function k(e){if(typeof e=="number"&&Number.isFinite(e))return Math.round(e*1e3);if(typeof e=="string"){let r=e.trim();if(r==="")throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".');let t=Number(r);if(r!==""&&Number.isFinite(t))return Math.round(t*1e3);let a;try{a=_ms2.default.call(void 0, r)}catch (e3){throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}if(typeof a=="number"&&Number.isFinite(a))return a}throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}var d=({scopes:e,requiresSiloScope:r=!1})=>{let t={kind:"parsed",parse:String,brief:"The Transcend API key."};return r&&(t.brief+=" This key must be associated with the data silo(s) being operated on."),e==="Varies"?{...t,brief:`${t.brief} The scopes required will vary depending on the operation performed. If in doubt, the ${_privacytypes.TRANSCEND_SCOPES[_privacytypes.ScopeName.FullAdmin].title} scope will always work.`}:e.length===0?{...t,brief:`${t.brief} No scopes are required for this command.`}:{...t,brief:`${t.brief} Requires scopes: ${e.map(a=>`"${_privacytypes.TRANSCEND_SCOPES[a].title}"`).join(", ")}`}},u= exports.f =(e=_chunkDQCPGPXGcjs.r)=>({kind:"parsed",parse:n,brief:"URL of the Transcend backend. Use https://api.us.transcend.io for US hosting",default:e}),x= exports.g =(e=_chunkDQCPGPXGcjs.s)=>({kind:"parsed",parse:n,brief:"URL of the Transcend consent backend. Use https://consent.us.transcend.io for US hosting",default:e}),A= exports.h =()=>({kind:"parsed",parse:String,brief:"The Sombra internal key, use for additional authentication when self-hosting Sombra",optional:!0});var g=["dataSilos","enrichers","templates","apiKeys"],I= exports.j =Object.values(_privacytypes.ConsentTrackerStatus),R= exports.k =_core.buildCommand.call(void 0, {loader:async()=>{let{pull:e}=await Promise.resolve().then(() => _interopRequireWildcard(require("./impl-YIPC6MAR.cjs")));return e},parameters:{flags:{auth:d({scopes:"Varies"}),resources:{kind:"enum",values:["all",...Object.values(_chunk7PB6LVSEcjs.d)],brief:`The different resource types to pull in. Defaults to ${g.join(",")}.`,variadic:",",optional:!0},file:{kind:"parsed",parse:String,brief:"Path to the YAML file to pull into",default:"./transcend.yml"},transcendUrl:u(),dataSiloIds:{kind:"parsed",parse:String,variadic:",",brief:"The UUIDs of the data silos that should be pulled into the YAML file",optional:!0},integrationNames:{kind:"parsed",parse:String,variadic:",",brief:"The types of integrations to pull down",optional:!0},trackerStatuses:{kind:"enum",values:Object.values(_privacytypes.ConsentTrackerStatus),variadic:",",brief:"The statuses of consent manager trackers to pull down. Defaults to all statuses.",optional:!0},pageSize:{kind:"parsed",parse:_core.numberParser,brief:"The page size to use when paginating over the API",default:"50"},skipDatapoints:{kind:"boolean",brief:"When true, skip pulling in datapoints alongside data silo resource",default:!1},skipSubDatapoints:{kind:"boolean",brief:"When true, skip pulling in subDatapoints alongside data silo resource",default:!1},includeGuessedCategories:{kind:"boolean",brief:"When true, included guessed data categories that came from the content classifier",default:!1},debug:{kind:"boolean",brief:"Set to true to include debug logs while pulling the configuration",default:!1}}},docs:{brief:"Pull metadata from Transcend into transcend.yml",fullDescription:`Generates a transcend.yml by pulling the configuration from your Transcend instance.
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 }; }var _chunk5MG2CEZVcjs = require('./chunk-5MG2CEZV.cjs');var _chunk7PB6LVSEcjs = require('./chunk-7PB6LVSE.cjs');var _core = require('@stricli/core');var _privacytypes = require('@transcend-io/privacy-types');var _ms = require('ms'); var _ms2 = _interopRequireDefault(_ms);function S(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new Error(`Invalid UUID format: ${e}`);return e}function n(e){try{return new URL(e).toString().replace(/\/$/,"")}catch (e2){throw new Error(`Invalid URL format: ${e}`)}}function T(e){return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function y(e){let r=new Date(e);if(Number.isNaN(r.getTime()))throw new TypeError(`Invalid date: ${e}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`);return r}function k(e){if(typeof e=="number"&&Number.isFinite(e))return Math.round(e*1e3);if(typeof e=="string"){let r=e.trim();if(r==="")throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".');let t=Number(r);if(r!==""&&Number.isFinite(t))return Math.round(t*1e3);let a;try{a=_ms2.default.call(void 0, r)}catch (e3){throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}if(typeof a=="number"&&Number.isFinite(a))return a}throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}var d=({scopes:e,requiresSiloScope:r=!1})=>{let t={kind:"parsed",parse:String,brief:"The Transcend API key."};return r&&(t.brief+=" This key must be associated with the data silo(s) being operated on."),e==="Varies"?{...t,brief:`${t.brief} The scopes required will vary depending on the operation performed. If in doubt, the ${_privacytypes.TRANSCEND_SCOPES[_privacytypes.ScopeName.FullAdmin].title} scope will always work.`}:e.length===0?{...t,brief:`${t.brief} No scopes are required for this command.`}:{...t,brief:`${t.brief} Requires scopes: ${e.map(a=>`"${_privacytypes.TRANSCEND_SCOPES[a].title}"`).join(", ")}`}},u= exports.f =(e=_chunk5MG2CEZVcjs.r)=>({kind:"parsed",parse:n,brief:"URL of the Transcend backend. Use https://api.us.transcend.io for US hosting",default:e}),x= exports.g =(e=_chunk5MG2CEZVcjs.s)=>({kind:"parsed",parse:n,brief:"URL of the Transcend consent backend. Use https://consent.us.transcend.io for US hosting",default:e}),A= exports.h =()=>({kind:"parsed",parse:String,brief:"The Sombra internal key, use for additional authentication when self-hosting Sombra",optional:!0});var g=["dataSilos","enrichers","templates","apiKeys"],I= exports.j =Object.values(_privacytypes.ConsentTrackerStatus),R= exports.k =_core.buildCommand.call(void 0, {loader:async()=>{let{pull:e}=await Promise.resolve().then(() => _interopRequireWildcard(require("./impl-WQF6YIDK.cjs")));return e},parameters:{flags:{auth:d({scopes:"Varies"}),resources:{kind:"enum",values:["all",...Object.values(_chunk7PB6LVSEcjs.d)],brief:`The different resource types to pull in. Defaults to ${g.join(",")}.`,variadic:",",optional:!0},file:{kind:"parsed",parse:String,brief:"Path to the YAML file to pull into",default:"./transcend.yml"},transcendUrl:u(),dataSiloIds:{kind:"parsed",parse:String,variadic:",",brief:"The UUIDs of the data silos that should be pulled into the YAML file",optional:!0},integrationNames:{kind:"parsed",parse:String,variadic:",",brief:"The types of integrations to pull down",optional:!0},trackerStatuses:{kind:"enum",values:Object.values(_privacytypes.ConsentTrackerStatus),variadic:",",brief:"The statuses of consent manager trackers to pull down. Defaults to all statuses.",optional:!0},pageSize:{kind:"parsed",parse:_core.numberParser,brief:"The page size to use when paginating over the API",default:"50"},skipDatapoints:{kind:"boolean",brief:"When true, skip pulling in datapoints alongside data silo resource",default:!1},skipSubDatapoints:{kind:"boolean",brief:"When true, skip pulling in subDatapoints alongside data silo resource",default:!1},includeGuessedCategories:{kind:"boolean",brief:"When true, included guessed data categories that came from the content classifier",default:!1},debug:{kind:"boolean",brief:"Set to true to include debug logs while pulling the configuration",default:!1}}},docs:{brief:"Pull metadata from Transcend into transcend.yml",fullDescription:`Generates a transcend.yml by pulling the configuration from your Transcend instance.
2
2
 
3
3
  The API key needs various scopes depending on the resources being pulled (see the CLI's README for more details).
4
4
 
@@ -6,4 +6,4 @@ This command can be helpful if you are looking to:
6
6
 
7
7
  - Copy your data into another instance
8
8
  - Generate a transcend.yml file as a starting point to maintain parts of your data inventory in code.`}});exports.a = S; exports.b = T; exports.c = y; exports.d = k; exports.e = d; exports.f = u; exports.g = x; exports.h = A; exports.i = g; exports.j = I; exports.k = R;
9
- //# sourceMappingURL=chunk-BPOXNSPY.cjs.map
9
+ //# sourceMappingURL=chunk-JRYG6ZXI.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-BPOXNSPY.cjs","../src/commands/inventory/pull/command.ts","../src/lib/cli/parsers.ts"],"names":["uuidParser","input"],"mappings":"AAAA,mfAA0C,wDAAyC,qCCAxC,2DACN,gECDiB,SAStCA,CAAAA,CAAWC,CAAAA,CAAuB,CAGhD,EAAA,CAAI,CADF,4EAAA,CACa,IAAA,CAAKA,CAAK,CAAA,CACvB,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBA,CAAK,CAAA,CAAA;ADwF5B;AAAA;AAAA;AAAA;AAAA;AAAA;AASpB,qGAAA","file":"/home/runner/work/cli/cli/dist/chunk-BPOXNSPY.cjs","sourcesContent":[null,"import { buildCommand, numberParser } from '@stricli/core';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport {\n createAuthParameter,\n createTranscendUrlParameter,\n} from '../../../lib/cli/common-parameters';\nimport { TranscendPullResource } from '../../../enums';\n\nexport const DEFAULT_TRANSCEND_PULL_RESOURCES = [\n TranscendPullResource.DataSilos,\n TranscendPullResource.Enrichers,\n TranscendPullResource.Templates,\n TranscendPullResource.ApiKeys,\n];\n\nexport const DEFAULT_CONSENT_TRACKER_STATUSES =\n Object.values(ConsentTrackerStatus);\n\nexport const pullCommand = buildCommand({\n loader: async () => {\n const { pull } = await import('./impl');\n return pull;\n },\n parameters: {\n flags: {\n auth: createAuthParameter({\n scopes: 'Varies',\n }),\n resources: {\n kind: 'enum',\n values: ['all', ...Object.values(TranscendPullResource)],\n brief: `The different resource types to pull in. Defaults to ${DEFAULT_TRANSCEND_PULL_RESOURCES.join(\n ',',\n )}.`,\n variadic: ',',\n optional: true,\n },\n file: {\n kind: 'parsed',\n parse: String,\n brief: 'Path to the YAML file to pull into',\n default: './transcend.yml',\n },\n transcendUrl: createTranscendUrlParameter(),\n dataSiloIds: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief:\n 'The UUIDs of the data silos that should be pulled into the YAML file',\n optional: true,\n },\n integrationNames: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief: 'The types of integrations to pull down',\n optional: true,\n },\n trackerStatuses: {\n kind: 'enum',\n values: Object.values(ConsentTrackerStatus),\n variadic: ',',\n brief:\n 'The statuses of consent manager trackers to pull down. Defaults to all statuses.',\n optional: true,\n },\n pageSize: {\n kind: 'parsed',\n parse: numberParser,\n brief: 'The page size to use when paginating over the API',\n default: '50',\n },\n skipDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in datapoints alongside data silo resource',\n default: false,\n },\n skipSubDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in subDatapoints alongside data silo resource',\n default: false,\n },\n includeGuessedCategories: {\n kind: 'boolean',\n brief:\n 'When true, included guessed data categories that came from the content classifier',\n default: false,\n },\n debug: {\n kind: 'boolean',\n brief:\n 'Set to true to include debug logs while pulling the configuration',\n default: false,\n },\n },\n },\n docs: {\n brief: 'Pull metadata from Transcend into transcend.yml',\n fullDescription: `Generates a transcend.yml by pulling the configuration from your Transcend instance.\n\nThe API key needs various scopes depending on the resources being pulled (see the CLI's README for more details).\n\nThis command can be helpful if you are looking to:\n\n- Copy your data into another instance\n- Generate a transcend.yml file as a starting point to maintain parts of your data inventory in code.`,\n },\n});\n","import ms, { type StringValue as MsStringValue } from 'ms';\n\n/**\n * Validates and returns a UUID string.\n *\n * @param input - The input string to validate as UUID\n * @returns The validated UUID string\n * @throws Error if input is not a valid UUID\n */\nexport function uuidParser(input: string): string {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(input)) {\n throw new Error(`Invalid UUID format: ${input}`);\n }\n return input;\n}\n\n/**\n * Validates and returns a URL string.\n *\n * @param input - The input string to validate as URL\n * @returns The validated URL string\n * @throws Error if input is not a valid URL\n */\nexport function urlParser(input: string): string {\n try {\n const url = new URL(input);\n return url.toString().replace(/\\/$/, '');\n } catch {\n throw new Error(`Invalid URL format: ${input}`);\n }\n}\n\n/**\n * Parse a comma-separated string to array.\n * NOTE: Prefer using `variadic` for list arguments instead of this function. This should only be used for arguments which have a default value.\n *\n * @param input - The comma-separated string to parse\n * @returns Array of trimmed, non-empty strings\n */\nexport function arrayParser(input: string): string[] {\n return input\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/**\n * Parse a date string to a Date object.\n *\n * @param input - The date string to parse\n * @returns The parsed Date object\n * @throws TypeError if input is not a valid date\n */\nexport function dateParser(input: string): Date {\n const date = new Date(input);\n if (Number.isNaN(date.getTime())) {\n throw new TypeError(\n `Invalid date: ${input}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`,\n );\n }\n return date;\n}\n\n/**\n * Parse a duration string to milliseconds.\n * Accepts concise/natural-ish strings (powered by `ms`) and returns milliseconds.\n * Examples: \"3600\", \"2d\", \"1h\", \"90 minutes\", \"10s\".\n *\n * @param input - The duration to parse\n * @returns The parsed duration in milliseconds\n * @throws Error if input is not a valid duration\n */\nexport function parseDurationToMs(input: unknown): number {\n if (typeof input === 'number' && Number.isFinite(input)) {\n // backward-compat: numbers => seconds\n return Math.round(input * 1000);\n }\n\n if (typeof input === 'string') {\n const trimmed = input.trim();\n // empty string → our standardized error (avoid ms throwing its own)\n if (trimmed === '') {\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n\n // bare numeric string => seconds (backward-compat)\n const asNumber = Number(trimmed);\n if (trimmed !== '' && Number.isFinite(asNumber)) {\n return Math.round(asNumber * 1000);\n }\n\n // let ms parse human strings\n let parsed: number | undefined;\n try {\n parsed = ms(trimmed as MsStringValue);\n } catch {\n // normalize ms' error to ours\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n if (typeof parsed === 'number' && Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-JRYG6ZXI.cjs","../src/commands/inventory/pull/command.ts","../src/lib/cli/parsers.ts"],"names":["uuidParser","input"],"mappings":"AAAA,mfAA0C,wDAAyC,qCCAxC,2DACN,gECDiB,SAStCA,CAAAA,CAAWC,CAAAA,CAAuB,CAGhD,EAAA,CAAI,CADF,4EAAA,CACa,IAAA,CAAKA,CAAK,CAAA,CACvB,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBA,CAAK,CAAA,CAAA;ADwF5B;AAAA;AAAA;AAAA;AAAA;AAAA;AASpB,qGAAA","file":"/home/runner/work/cli/cli/dist/chunk-JRYG6ZXI.cjs","sourcesContent":[null,"import { buildCommand, numberParser } from '@stricli/core';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport {\n createAuthParameter,\n createTranscendUrlParameter,\n} from '../../../lib/cli/common-parameters';\nimport { TranscendPullResource } from '../../../enums';\n\nexport const DEFAULT_TRANSCEND_PULL_RESOURCES = [\n TranscendPullResource.DataSilos,\n TranscendPullResource.Enrichers,\n TranscendPullResource.Templates,\n TranscendPullResource.ApiKeys,\n];\n\nexport const DEFAULT_CONSENT_TRACKER_STATUSES =\n Object.values(ConsentTrackerStatus);\n\nexport const pullCommand = buildCommand({\n loader: async () => {\n const { pull } = await import('./impl');\n return pull;\n },\n parameters: {\n flags: {\n auth: createAuthParameter({\n scopes: 'Varies',\n }),\n resources: {\n kind: 'enum',\n values: ['all', ...Object.values(TranscendPullResource)],\n brief: `The different resource types to pull in. Defaults to ${DEFAULT_TRANSCEND_PULL_RESOURCES.join(\n ',',\n )}.`,\n variadic: ',',\n optional: true,\n },\n file: {\n kind: 'parsed',\n parse: String,\n brief: 'Path to the YAML file to pull into',\n default: './transcend.yml',\n },\n transcendUrl: createTranscendUrlParameter(),\n dataSiloIds: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief:\n 'The UUIDs of the data silos that should be pulled into the YAML file',\n optional: true,\n },\n integrationNames: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief: 'The types of integrations to pull down',\n optional: true,\n },\n trackerStatuses: {\n kind: 'enum',\n values: Object.values(ConsentTrackerStatus),\n variadic: ',',\n brief:\n 'The statuses of consent manager trackers to pull down. Defaults to all statuses.',\n optional: true,\n },\n pageSize: {\n kind: 'parsed',\n parse: numberParser,\n brief: 'The page size to use when paginating over the API',\n default: '50',\n },\n skipDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in datapoints alongside data silo resource',\n default: false,\n },\n skipSubDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in subDatapoints alongside data silo resource',\n default: false,\n },\n includeGuessedCategories: {\n kind: 'boolean',\n brief:\n 'When true, included guessed data categories that came from the content classifier',\n default: false,\n },\n debug: {\n kind: 'boolean',\n brief:\n 'Set to true to include debug logs while pulling the configuration',\n default: false,\n },\n },\n },\n docs: {\n brief: 'Pull metadata from Transcend into transcend.yml',\n fullDescription: `Generates a transcend.yml by pulling the configuration from your Transcend instance.\n\nThe API key needs various scopes depending on the resources being pulled (see the CLI's README for more details).\n\nThis command can be helpful if you are looking to:\n\n- Copy your data into another instance\n- Generate a transcend.yml file as a starting point to maintain parts of your data inventory in code.`,\n },\n});\n","import ms, { type StringValue as MsStringValue } from 'ms';\n\n/**\n * Validates and returns a UUID string.\n *\n * @param input - The input string to validate as UUID\n * @returns The validated UUID string\n * @throws Error if input is not a valid UUID\n */\nexport function uuidParser(input: string): string {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(input)) {\n throw new Error(`Invalid UUID format: ${input}`);\n }\n return input;\n}\n\n/**\n * Validates and returns a URL string.\n *\n * @param input - The input string to validate as URL\n * @returns The validated URL string\n * @throws Error if input is not a valid URL\n */\nexport function urlParser(input: string): string {\n try {\n const url = new URL(input);\n return url.toString().replace(/\\/$/, '');\n } catch {\n throw new Error(`Invalid URL format: ${input}`);\n }\n}\n\n/**\n * Parse a comma-separated string to array.\n * NOTE: Prefer using `variadic` for list arguments instead of this function. This should only be used for arguments which have a default value.\n *\n * @param input - The comma-separated string to parse\n * @returns Array of trimmed, non-empty strings\n */\nexport function arrayParser(input: string): string[] {\n return input\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/**\n * Parse a date string to a Date object.\n *\n * @param input - The date string to parse\n * @returns The parsed Date object\n * @throws TypeError if input is not a valid date\n */\nexport function dateParser(input: string): Date {\n const date = new Date(input);\n if (Number.isNaN(date.getTime())) {\n throw new TypeError(\n `Invalid date: ${input}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`,\n );\n }\n return date;\n}\n\n/**\n * Parse a duration string to milliseconds.\n * Accepts concise/natural-ish strings (powered by `ms`) and returns milliseconds.\n * Examples: \"3600\", \"2d\", \"1h\", \"90 minutes\", \"10s\".\n *\n * @param input - The duration to parse\n * @returns The parsed duration in milliseconds\n * @throws Error if input is not a valid duration\n */\nexport function parseDurationToMs(input: unknown): number {\n if (typeof input === 'number' && Number.isFinite(input)) {\n // backward-compat: numbers => seconds\n return Math.round(input * 1000);\n }\n\n if (typeof input === 'string') {\n const trimmed = input.trim();\n // empty string → our standardized error (avoid ms throwing its own)\n if (trimmed === '') {\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n\n // bare numeric string => seconds (backward-compat)\n const asNumber = Number(trimmed);\n if (trimmed !== '' && Number.isFinite(asNumber)) {\n return Math.round(asNumber * 1000);\n }\n\n // let ms parse human strings\n let parsed: number | undefined;\n try {\n parsed = ms(trimmed as MsStringValue);\n } catch {\n // normalize ms' error to ours\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n if (typeof parsed === 'number' && Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n}\n"]}