@transcend-io/cli 8.1.0 → 8.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +70 -35
  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-YCB6J5EJ.cjs → chunk-6CS4GCJ4.cjs} +2 -2
  6. package/dist/{chunk-YCB6J5EJ.cjs.map → chunk-6CS4GCJ4.cjs.map} +1 -1
  7. package/dist/{chunk-4B22XVLO.cjs → chunk-BICC2LJL.cjs} +3 -3
  8. package/dist/{chunk-4B22XVLO.cjs.map → chunk-BICC2LJL.cjs.map} +1 -1
  9. package/dist/{chunk-2STE3YIZ.cjs → chunk-DVJLLHL3.cjs} +2 -2
  10. package/dist/{chunk-2STE3YIZ.cjs.map → chunk-DVJLLHL3.cjs.map} +1 -1
  11. package/dist/{chunk-AMP7MT7M.cjs → chunk-HI7ACKKB.cjs} +2 -2
  12. package/dist/{chunk-AMP7MT7M.cjs.map → chunk-HI7ACKKB.cjs.map} +1 -1
  13. package/dist/{chunk-MKLPDKJQ.cjs → chunk-IFAKI5FF.cjs} +2 -2
  14. package/dist/{chunk-MKLPDKJQ.cjs.map → chunk-IFAKI5FF.cjs.map} +1 -1
  15. package/dist/{chunk-GRBF73LS.cjs → chunk-MGAJ7ILD.cjs} +2 -2
  16. package/dist/{chunk-GRBF73LS.cjs.map → chunk-MGAJ7ILD.cjs.map} +1 -1
  17. package/dist/{chunk-FM3LX7FQ.cjs → chunk-MRXBJEKL.cjs} +20 -20
  18. package/dist/{chunk-FM3LX7FQ.cjs.map → chunk-MRXBJEKL.cjs.map} +1 -1
  19. package/dist/{chunk-QRBSG22E.cjs → chunk-NC5QVXJW.cjs} +2 -2
  20. package/dist/{chunk-QRBSG22E.cjs.map → chunk-NC5QVXJW.cjs.map} +1 -1
  21. package/dist/{chunk-ZVE6Y6D3.cjs → chunk-QPIUQDJ6.cjs} +4 -4
  22. package/dist/{chunk-ZVE6Y6D3.cjs.map → chunk-QPIUQDJ6.cjs.map} +1 -1
  23. package/dist/{chunk-MRJ2BRU4.cjs → chunk-QRDYTLVB.cjs} +2 -2
  24. package/dist/{chunk-MRJ2BRU4.cjs.map → chunk-QRDYTLVB.cjs.map} +1 -1
  25. package/dist/{chunk-63GGJ2XI.cjs → chunk-W6BLSHVE.cjs} +4 -4
  26. package/dist/{chunk-63GGJ2XI.cjs.map → chunk-W6BLSHVE.cjs.map} +1 -1
  27. package/dist/{chunk-PVQIV735.cjs → chunk-XKYSQSRO.cjs} +2 -2
  28. package/dist/{chunk-PVQIV735.cjs.map → chunk-XKYSQSRO.cjs.map} +1 -1
  29. package/dist/{impl-XZOJGVZ7.cjs → impl-4VPFFGGS.cjs} +2 -2
  30. package/dist/{impl-XZOJGVZ7.cjs.map → impl-4VPFFGGS.cjs.map} +1 -1
  31. package/dist/{impl-7SHEZUAI.cjs → impl-5H6DFFAS.cjs} +2 -2
  32. package/dist/{impl-7SHEZUAI.cjs.map → impl-5H6DFFAS.cjs.map} +1 -1
  33. package/dist/{impl-BCEZUJCK.cjs → impl-6JRE252A.cjs} +2 -2
  34. package/dist/{impl-BCEZUJCK.cjs.map → impl-6JRE252A.cjs.map} +1 -1
  35. package/dist/{impl-BJU7SNUT.cjs → impl-7RJYKTCZ.cjs} +6 -6
  36. package/dist/{impl-BJU7SNUT.cjs.map → impl-7RJYKTCZ.cjs.map} +1 -1
  37. package/dist/{impl-AOB56N6K.cjs → impl-BKEVLUMO.cjs} +2 -2
  38. package/dist/{impl-AOB56N6K.cjs.map → impl-BKEVLUMO.cjs.map} +1 -1
  39. package/dist/{impl-MZWGXBZH.cjs → impl-BRUSOMXU.cjs} +2 -2
  40. package/dist/{impl-MZWGXBZH.cjs.map → impl-BRUSOMXU.cjs.map} +1 -1
  41. package/dist/{impl-ZH4AWDRT.cjs → impl-BUQ2V3WM.cjs} +2 -2
  42. package/dist/{impl-ZH4AWDRT.cjs.map → impl-BUQ2V3WM.cjs.map} +1 -1
  43. package/dist/{impl-QF3LYRIM.cjs → impl-C7DRIULL.cjs} +2 -2
  44. package/dist/{impl-QF3LYRIM.cjs.map → impl-C7DRIULL.cjs.map} +1 -1
  45. package/dist/{impl-Y7C42SDM.cjs → impl-CK5QRU26.cjs} +2 -2
  46. package/dist/{impl-Y7C42SDM.cjs.map → impl-CK5QRU26.cjs.map} +1 -1
  47. package/dist/{impl-KGA7YWGV.cjs → impl-DDOPMEH6.cjs} +5 -5
  48. package/dist/{impl-KGA7YWGV.cjs.map → impl-DDOPMEH6.cjs.map} +1 -1
  49. package/dist/{impl-U6S7JMJK.cjs → impl-DYGW2VXN.cjs} +2 -2
  50. package/dist/{impl-U6S7JMJK.cjs.map → impl-DYGW2VXN.cjs.map} +1 -1
  51. package/dist/{impl-76NYSLL3.cjs → impl-ED76NZLR.cjs} +3 -3
  52. package/dist/{impl-76NYSLL3.cjs.map → impl-ED76NZLR.cjs.map} +1 -1
  53. package/dist/{impl-DZDGMNPH.cjs → impl-EL3GY7PX.cjs} +2 -2
  54. package/dist/{impl-DZDGMNPH.cjs.map → impl-EL3GY7PX.cjs.map} +1 -1
  55. package/dist/{impl-ITID6Y4N.cjs → impl-FRDPRLKI.cjs} +2 -2
  56. package/dist/{impl-ITID6Y4N.cjs.map → impl-FRDPRLKI.cjs.map} +1 -1
  57. package/dist/{impl-4VTKQJRY.cjs → impl-GDONPQQ6.cjs} +2 -2
  58. package/dist/{impl-4VTKQJRY.cjs.map → impl-GDONPQQ6.cjs.map} +1 -1
  59. package/dist/{impl-K4D7ATKB.cjs → impl-I3QZ2ZHY.cjs} +2 -2
  60. package/dist/{impl-K4D7ATKB.cjs.map → impl-I3QZ2ZHY.cjs.map} +1 -1
  61. package/dist/{impl-RTPMOLO6.cjs → impl-LBJYOQEP.cjs} +2 -2
  62. package/dist/{impl-RTPMOLO6.cjs.map → impl-LBJYOQEP.cjs.map} +1 -1
  63. package/dist/{impl-IHKKGU4K.cjs → impl-LNF5A3IV.cjs} +2 -2
  64. package/dist/{impl-IHKKGU4K.cjs.map → impl-LNF5A3IV.cjs.map} +1 -1
  65. package/dist/{impl-2QMFSSRH.cjs → impl-LV5VZGGG.cjs} +2 -2
  66. package/dist/{impl-2QMFSSRH.cjs.map → impl-LV5VZGGG.cjs.map} +1 -1
  67. package/dist/{impl-K2ZOFSCD.cjs → impl-MT4XWK25.cjs} +2 -2
  68. package/dist/{impl-K2ZOFSCD.cjs.map → impl-MT4XWK25.cjs.map} +1 -1
  69. package/dist/{impl-UKSTSUL7.cjs → impl-NOS3MDB5.cjs} +2 -2
  70. package/dist/{impl-UKSTSUL7.cjs.map → impl-NOS3MDB5.cjs.map} +1 -1
  71. package/dist/{impl-PFVHMRSW.cjs → impl-O6ZZ6G7V.cjs} +2 -2
  72. package/dist/{impl-PFVHMRSW.cjs.map → impl-O6ZZ6G7V.cjs.map} +1 -1
  73. package/dist/{impl-AKBOHO2I.cjs → impl-OXVQMF3C.cjs} +2 -2
  74. package/dist/{impl-AKBOHO2I.cjs.map → impl-OXVQMF3C.cjs.map} +1 -1
  75. package/dist/{impl-YVMZ7QMB.cjs → impl-P3ZEQOP4.cjs} +2 -2
  76. package/dist/{impl-YVMZ7QMB.cjs.map → impl-P3ZEQOP4.cjs.map} +1 -1
  77. package/dist/{impl-C3ZNAX3B.cjs → impl-PE35IGX2.cjs} +2 -2
  78. package/dist/{impl-C3ZNAX3B.cjs.map → impl-PE35IGX2.cjs.map} +1 -1
  79. package/dist/{impl-47CZEYNP.cjs → impl-PKQQUVYK.cjs} +2 -2
  80. package/dist/{impl-47CZEYNP.cjs.map → impl-PKQQUVYK.cjs.map} +1 -1
  81. package/dist/{impl-T3BWUKPN.cjs → impl-QAMYNNJD.cjs} +2 -2
  82. package/dist/{impl-T3BWUKPN.cjs.map → impl-QAMYNNJD.cjs.map} +1 -1
  83. package/dist/{impl-WQDLUVZ6.cjs → impl-QPUYYCCD.cjs} +5 -5
  84. package/dist/{impl-WQDLUVZ6.cjs.map → impl-QPUYYCCD.cjs.map} +1 -1
  85. package/dist/{impl-ZA25XTRE.cjs → impl-SC7VG3C5.cjs} +2 -2
  86. package/dist/{impl-ZA25XTRE.cjs.map → impl-SC7VG3C5.cjs.map} +1 -1
  87. package/dist/{impl-6RBT5EJC.cjs → impl-SCX5AEQB.cjs} +2 -2
  88. package/dist/{impl-6RBT5EJC.cjs.map → impl-SCX5AEQB.cjs.map} +1 -1
  89. package/dist/{impl-KQET2XDP.cjs → impl-SWFUVUV6.cjs} +2 -2
  90. package/dist/{impl-KQET2XDP.cjs.map → impl-SWFUVUV6.cjs.map} +1 -1
  91. package/dist/{impl-IEDZ4YTQ.cjs → impl-TSGEOZLY.cjs} +2 -2
  92. package/dist/{impl-IEDZ4YTQ.cjs.map → impl-TSGEOZLY.cjs.map} +1 -1
  93. package/dist/{impl-SKFVDXWS.cjs → impl-US4VOSBF.cjs} +4 -4
  94. package/dist/{impl-SKFVDXWS.cjs.map → impl-US4VOSBF.cjs.map} +1 -1
  95. package/dist/{impl-GTZ6RYJB.cjs → impl-UZE2LR6H.cjs} +2 -2
  96. package/dist/{impl-GTZ6RYJB.cjs.map → impl-UZE2LR6H.cjs.map} +1 -1
  97. package/dist/impl-UZTSGARM.cjs +2 -0
  98. package/dist/{impl-LLM4EEIP.cjs.map → impl-UZTSGARM.cjs.map} +1 -1
  99. package/dist/{impl-NZIDPNPS.cjs → impl-WO3LVKNE.cjs} +2 -2
  100. package/dist/{impl-NZIDPNPS.cjs.map → impl-WO3LVKNE.cjs.map} +1 -1
  101. package/dist/{impl-FGUGKHTG.cjs → impl-WVAGHUZI.cjs} +3 -3
  102. package/dist/{impl-FGUGKHTG.cjs.map → impl-WVAGHUZI.cjs.map} +1 -1
  103. package/dist/{impl-G2TM3DQW.cjs → impl-X2FXS267.cjs} +2 -2
  104. package/dist/{impl-G2TM3DQW.cjs.map → impl-X2FXS267.cjs.map} +1 -1
  105. package/dist/{impl-GGV7EW55.cjs → impl-ZWNKU6OC.cjs} +2 -2
  106. package/dist/{impl-GGV7EW55.cjs.map → impl-ZWNKU6OC.cjs.map} +1 -1
  107. package/dist/index.cjs +3 -3
  108. package/dist/index.d.cts +1 -1
  109. package/package.json +1 -1
  110. package/dist/impl-LLM4EEIP.cjs +0 -2
@@ -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 _chunkZVE6Y6D3cjs = require('./chunk-ZVE6Y6D3.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkGRBF73LScjs = require('./chunk-GRBF73LS.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var S = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var X=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 U(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(X)}),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 L=S.type({nonce:S.string,identifier:S.string});async function B(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 _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);async function ge({file:r,dataSiloId:s,auth:c,sombraAuth:n,concurrency:a=100,transcendUrl:i=_chunkGRBF73LScjs.r,sleepSeconds:f=10}){let y=await _chunkZVE6Y6D3cjs.wc.call(void 0, i,c,n);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${r}" from disk`));let o=_chunkZVE6Y6D3cjs.qc.call(void 0, r,L);_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=_chunkGRBF73LScjs.b.call(void 0, o,a),I=m.length;await _bluebird.mapSeries.call(void 0, m,async($,P)=>{_chunkZUNVPK23cjs.a.info(_colors2.default.blue(`Processing chunk ${P+1}/${I} (${_chunkGRBF73LScjs.b.length} items)`)),await _bluebird.map.call(void 0, $,async h=>{try{await B(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&&P<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 D=new Date().getTime()-C;if(_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend for ${d} identifiers in "${D/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 Se({requestIds:r,dataSiloId:s,auth:c,concurrency:n=100,status:a=_privacytypes.RequestDataSiloStatus.Resolved,transcendUrl:i=_chunkGRBF73LScjs.r}){let f=_chunkZVE6Y6D3cjs.vc.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 _bluebird.map.call(void 0, r,async u=>{let l=await _chunkZVE6Y6D3cjs.Cd.call(void 0, f,{requestId:u,dataSiloId:s});try{await _chunkZVE6Y6D3cjs.Xf.call(void 0, f,_chunkZVE6Y6D3cjs.ua,{requestDataSiloId:l.id,status:a})}catch(m){if(!m.message.includes("Client error: Request must be active:"))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 _e({dataSiloId:r,auth:s,sombraAuth:c,actions:n,apiPageSize:a=100,savePageSize:i=1e3,onSave:f,transcendUrl:y=_chunkGRBF73LScjs.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 _chunkZVE6Y6D3cjs.wc.call(void 0, y,s,c),w=_chunkZVE6Y6D3cjs.vc.call(void 0, y,s),d=0;o||(d=await _chunkZVE6Y6D3cjs.Dd.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 _bluebird.mapSeries.call(void 0, n,async $=>{let P=0,h=!0;for(;h;){let b=await U(C,{dataSiloId:r,limit:a,offset:P,requestType:$}),k=b.map(A=>(m.add(A.requestId),{...A,action:$})),J=k.map(({attributes:A,...K})=>({...K,...A.reduce((M,E)=>Object.assign(M,{[E.key]:E.values.join(",")}),{})}));I.push(...k),g.push(...J),g.length>=i&&(await f(g),g=[]),h=b.length===a,P+=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 D=new Date().getTime()-u;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled ${I.length} outstanding identifiers from ${m.size} requests in "${D/1e3}" seconds!`)),{identifiers:I}}exports.a = X; exports.b = U; exports.c = L; exports.d = B; exports.e = ge; exports.f = Se; exports.g = _e;
2
- //# sourceMappingURL=chunk-MRJ2BRU4.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 _chunkQPIUQDJ6cjs = require('./chunk-QPIUQDJ6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGAJ7ILDcjs = require('./chunk-MGAJ7ILD.cjs');var _iots = require('io-ts'); var e = _interopRequireWildcard(_iots); var S = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var X=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 U(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(X)}),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 L=S.type({nonce:S.string,identifier:S.string});async function B(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 _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);async function ge({file:r,dataSiloId:s,auth:c,sombraAuth:n,concurrency:a=100,transcendUrl:i=_chunkMGAJ7ILDcjs.r,sleepSeconds:f=10}){let y=await _chunkQPIUQDJ6cjs.wc.call(void 0, i,c,n);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${r}" from disk`));let o=_chunkQPIUQDJ6cjs.qc.call(void 0, r,L);_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=_chunkMGAJ7ILDcjs.b.call(void 0, o,a),I=m.length;await _bluebird.mapSeries.call(void 0, m,async($,P)=>{_chunkZUNVPK23cjs.a.info(_colors2.default.blue(`Processing chunk ${P+1}/${I} (${_chunkMGAJ7ILDcjs.b.length} items)`)),await _bluebird.map.call(void 0, $,async h=>{try{await B(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&&P<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 D=new Date().getTime()-C;if(_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend for ${d} identifiers in "${D/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 Se({requestIds:r,dataSiloId:s,auth:c,concurrency:n=100,status:a=_privacytypes.RequestDataSiloStatus.Resolved,transcendUrl:i=_chunkMGAJ7ILDcjs.r}){let f=_chunkQPIUQDJ6cjs.vc.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 _bluebird.map.call(void 0, r,async u=>{let l=await _chunkQPIUQDJ6cjs.Cd.call(void 0, f,{requestId:u,dataSiloId:s});try{await _chunkQPIUQDJ6cjs.Xf.call(void 0, f,_chunkQPIUQDJ6cjs.ua,{requestDataSiloId:l.id,status:a})}catch(m){if(!m.message.includes("Client error: Request must be active:"))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 _e({dataSiloId:r,auth:s,sombraAuth:c,actions:n,apiPageSize:a=100,savePageSize:i=1e3,onSave:f,transcendUrl:y=_chunkMGAJ7ILDcjs.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 _chunkQPIUQDJ6cjs.wc.call(void 0, y,s,c),w=_chunkQPIUQDJ6cjs.vc.call(void 0, y,s),d=0;o||(d=await _chunkQPIUQDJ6cjs.Dd.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 _bluebird.mapSeries.call(void 0, n,async $=>{let P=0,h=!0;for(;h;){let b=await U(C,{dataSiloId:r,limit:a,offset:P,requestType:$}),k=b.map(A=>(m.add(A.requestId),{...A,action:$})),J=k.map(({attributes:A,...K})=>({...K,...A.reduce((M,E)=>Object.assign(M,{[E.key]:E.values.join(",")}),{})}));I.push(...k),g.push(...J),g.length>=i&&(await f(g),g=[]),h=b.length===a,P+=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 D=new Date().getTime()-u;return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled ${I.length} outstanding identifiers from ${m.size} requests in "${D/1e3}" seconds!`)),{identifiers:I}}exports.a = X; exports.b = U; exports.c = L; exports.d = B; exports.e = ge; exports.f = Se; exports.g = _e;
2
+ //# sourceMappingURL=chunk-QRDYTLVB.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-MRJ2BRU4.cjs","../src/lib/cron/pullCronPageOfIdentifiers.ts"],"names":["CronIdentifier","pullCronPageOfIdentifiers","sombra","dataSiloId","limit","offset","requestType","response"],"mappings":"AAAA,u/BAAyF,wDAAyC,wDAAgD,6GCA/J,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-MRJ2BRU4.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-QRDYTLVB.cjs","../src/lib/cron/pullCronPageOfIdentifiers.ts"],"names":["CronIdentifier","pullCronPageOfIdentifiers","sombra","dataSiloId","limit","offset","requestType","response"],"mappings":"AAAA,u/BAAyF,wDAAyC,wDAAgD,6GCA/J,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-QRDYTLVB.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,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 _chunkZVE6Y6D3cjs = require('./chunk-ZVE6Y6D3.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkGRBF73LScjs = require('./chunk-GRBF73LS.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);var _bluebird = require('bluebird');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 _chunkZVE6Y6D3cjs.Xf.call(void 0, u,_chunkZVE6Y6D3cjs.d,{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 _chunkZVE6Y6D3cjs.Xf.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 _chunkQPIUQDJ6cjs = require('./chunk-QPIUQDJ6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGAJ7ILDcjs = require('./chunk-MGAJ7ILD.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);var _bluebird = require('bluebird');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 _chunkQPIUQDJ6cjs.Xf.call(void 0, u,_chunkQPIUQDJ6cjs.d,{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 _chunkQPIUQDJ6cjs.Xf.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=_chunkGRBF73LScjs.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=_chunkGRBF73LScjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _bluebird.mapSeries.call(void 0, p,async s=>{try{let{dataPoints:{nodes:o}}=await _chunkZVE6Y6D3cjs.Xf.call(void 0, u,_chunkZVE6Y6D3cjs.g,{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=_chunkGRBF73LScjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _bluebird.mapSeries.call(void 0, p,async s=>{try{let{dataSilos:{nodes:o}}=await _chunkZVE6Y6D3cjs.Xf.call(void 0, u,_chunkZVE6Y6D3cjs.j,{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=_chunkGRBF73LScjs.j.call(void 0, n.map(r=>r.dataPointId)),d=await F(u,{dataPointIds:m}),s=_chunkGRBF73LScjs.e.call(void 0, d,"id"),o=_chunkGRBF73LScjs.j.call(void 0, n.map(r=>r.dataSiloId)),y=await Q(u,{dataSiloIds:o}),D=_chunkGRBF73LScjs.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 _chunkZVE6Y6D3cjs.Xf.call(void 0, u,_chunkZVE6Y6D3cjs.h,{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 _chunkZVE6Y6D3cjs.Xf.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=_chunkMGAJ7ILDcjs.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=_chunkMGAJ7ILDcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _bluebird.mapSeries.call(void 0, p,async s=>{try{let{dataPoints:{nodes:o}}=await _chunkQPIUQDJ6cjs.Xf.call(void 0, u,_chunkQPIUQDJ6cjs.g,{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=_chunkMGAJ7ILDcjs.b.call(void 0, e,l);t.start(e.length,0);let n=0;await _bluebird.mapSeries.call(void 0, p,async s=>{try{let{dataSilos:{nodes:o}}=await _chunkQPIUQDJ6cjs.Xf.call(void 0, u,_chunkQPIUQDJ6cjs.j,{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=_chunkMGAJ7ILDcjs.j.call(void 0, n.map(r=>r.dataPointId)),d=await F(u,{dataPointIds:m}),s=_chunkMGAJ7ILDcjs.e.call(void 0, d,"id"),o=_chunkMGAJ7ILDcjs.j.call(void 0, n.map(r=>r.dataSiloId)),y=await Q(u,{dataSiloIds:o}),D=_chunkMGAJ7ILDcjs.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 _chunkQPIUQDJ6cjs.Xf.call(void 0, u,_chunkQPIUQDJ6cjs.h,{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 _chunkQPIUQDJ6cjs.Xf.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 T=new Date().getTime()-n,C=_chunkGRBF73LScjs.g.call(void 0, p,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${C.length} subdatapoints in ${T/1e3} seconds!`)),C}exports.a = Y; exports.b = nt;
75
- //# sourceMappingURL=chunk-63GGJ2XI.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 T=new Date().getTime()-n,C=_chunkMGAJ7ILDcjs.g.call(void 0, p,"name");return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pulled in ${C.length} subdatapoints in ${T/1e3} seconds!`)),C}exports.a = Y; exports.b = nt;
75
+ //# sourceMappingURL=chunk-W6BLSHVE.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-63GGJ2XI.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":"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","file":"/home/runner/work/cli/cli/dist/chunk-63GGJ2XI.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-W6BLSHVE.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":"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","file":"/home/runner/work/cli/cli/dist/chunk-W6BLSHVE.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 }; }var _chunkQEM6S2W7cjs = require('./chunk-QEM6S2W7.cjs');var _chunkZVE6Y6D3cjs = require('./chunk-ZVE6Y6D3.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkGRBF73LScjs = require('./chunk-GRBF73LS.cjs');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function H({email:r,password:a,scopes:f,apiKeyTitle:t,parentOrganizationId:o,deleteExistingApiKey:l=!0,createNewApiKey:I=!0,transcendUrl:x=_chunkGRBF73LScjs.r}){let s=await _chunkZVE6Y6D3cjs.uc.call(void 0, x,{});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Logging in using email and password."));let{roles:d,loginCookie:k}=await _chunkZVE6Y6D3cjs.Fd.call(void 0, s,{email:r,password:a});_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully logged in and found ${d.length} role${d.length===1?"":"s"}!`));let P=o?d.filter(e=>e.organization.id===o||e.organization.parentOrganizationId===o):d;s.setHeaders({Cookie:k});let m=[],c=[];return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Generating API keys with title: ${t}, scopes: ${f.join(",")}.`)),await _bluebird.mapSeries.call(void 0, P,async e=>{try{await _chunkZVE6Y6D3cjs.Gd.call(void 0, s,{roleId:e.id,email:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Checking if API key already exists in organization "${e.organization.name}" with title: "${t}".`));let[g]=await _chunkZVE6Y6D3cjs.od.call(void 0, s,[t]);if(g&&l)_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Deleting existing API key in "${e.organization.name}" with title: "${t}".`)),await _chunkZVE6Y6D3cjs.Id.call(void 0, s,g.id),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully deleted API key in "${e.organization.name}" with title: "${t}".`));else if(g)throw new Error(`API key already exists with title: "${t}"`);if(I){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Creating API key in "${e.organization.name}" with title: "${t}".`));let{apiKey:K}=await _chunkZVE6Y6D3cjs.Hd.call(void 0, s,{title:t,scopes:f});m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:K}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created API key in "${e.organization.name}" with title: "${t}".`))}else m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:""})}catch(g){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create API key in organization "${e.organization.name}"! - ${g.message}`)),c.push({organizationName:e.organization.name,organizationId:e.organization.id,error:g.message})}}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created ${m.length} API key${m.length===1?"":"s"}`)),c.length>0&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create ${c.length} API key${c.length===1?"":"s"}!`)),{errors:c,apiKeys:m}}var _typeutils = require('@transcend-io/type-utils');var _iots = require('io-ts'); var S = _interopRequireWildcard(_iots);var _fs = require('fs');function T(r){return r||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A Transcend API key must be provided. You can specify using --auth=$TRANSCEND_API_KEY")),process.exit(1)),_fs.existsSync.call(void 0, r)?_typeutils.decodeCodec.call(void 0, S.array(_chunkQEM6S2W7cjs.ha),_fs.readFileSync.call(void 0, r,"utf-8")):r}function Z(r,a,f=!1){if(!_fs.existsSync.call(void 0, r))return[];let t=_fs.readdirSync.call(void 0, r).filter(o=>a?a.filter(l=>o.endsWith(l)).length:!0).filter(o=>o.indexOf(".")>0);return f?t.map(o=>o.replace(/\.[^/.]+$/,"")):t}var _path = require('path');function te(r){return _fs.readdirSync.call(void 0, r).filter(a=>_fs.statSync.call(void 0, _path.join.call(void 0, r,a)).isDirectory())}exports.a = H; exports.b = T; exports.c = Z; exports.d = te;
2
- //# sourceMappingURL=chunk-PVQIV735.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 }; }var _chunkQEM6S2W7cjs = require('./chunk-QEM6S2W7.cjs');var _chunkQPIUQDJ6cjs = require('./chunk-QPIUQDJ6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGAJ7ILDcjs = require('./chunk-MGAJ7ILD.cjs');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function H({email:r,password:a,scopes:f,apiKeyTitle:t,parentOrganizationId:o,deleteExistingApiKey:l=!0,createNewApiKey:I=!0,transcendUrl:x=_chunkMGAJ7ILDcjs.r}){let s=await _chunkQPIUQDJ6cjs.uc.call(void 0, x,{});_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Logging in using email and password."));let{roles:d,loginCookie:k}=await _chunkQPIUQDJ6cjs.Fd.call(void 0, s,{email:r,password:a});_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully logged in and found ${d.length} role${d.length===1?"":"s"}!`));let P=o?d.filter(e=>e.organization.id===o||e.organization.parentOrganizationId===o):d;s.setHeaders({Cookie:k});let m=[],c=[];return _chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Generating API keys with title: ${t}, scopes: ${f.join(",")}.`)),await _bluebird.mapSeries.call(void 0, P,async e=>{try{await _chunkQPIUQDJ6cjs.Gd.call(void 0, s,{roleId:e.id,email:r}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Checking if API key already exists in organization "${e.organization.name}" with title: "${t}".`));let[g]=await _chunkQPIUQDJ6cjs.od.call(void 0, s,[t]);if(g&&l)_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Deleting existing API key in "${e.organization.name}" with title: "${t}".`)),await _chunkQPIUQDJ6cjs.Id.call(void 0, s,g.id),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully deleted API key in "${e.organization.name}" with title: "${t}".`));else if(g)throw new Error(`API key already exists with title: "${t}"`);if(I){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Creating API key in "${e.organization.name}" with title: "${t}".`));let{apiKey:K}=await _chunkQPIUQDJ6cjs.Hd.call(void 0, s,{title:t,scopes:f});m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:K}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created API key in "${e.organization.name}" with title: "${t}".`))}else m.push({organizationName:e.organization.name,organizationId:e.organization.id,apiKey:""})}catch(g){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create API key in organization "${e.organization.name}"! - ${g.message}`)),c.push({organizationName:e.organization.name,organizationId:e.organization.id,error:g.message})}}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully created ${m.length} API key${m.length===1?"":"s"}`)),c.length>0&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to create ${c.length} API key${c.length===1?"":"s"}!`)),{errors:c,apiKeys:m}}var _typeutils = require('@transcend-io/type-utils');var _iots = require('io-ts'); var S = _interopRequireWildcard(_iots);var _fs = require('fs');function T(r){return r||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A Transcend API key must be provided. You can specify using --auth=$TRANSCEND_API_KEY")),process.exit(1)),_fs.existsSync.call(void 0, r)?_typeutils.decodeCodec.call(void 0, S.array(_chunkQEM6S2W7cjs.ha),_fs.readFileSync.call(void 0, r,"utf-8")):r}function Z(r,a,f=!1){if(!_fs.existsSync.call(void 0, r))return[];let t=_fs.readdirSync.call(void 0, r).filter(o=>a?a.filter(l=>o.endsWith(l)).length:!0).filter(o=>o.indexOf(".")>0);return f?t.map(o=>o.replace(/\.[^/.]+$/,"")):t}var _path = require('path');function te(r){return _fs.readdirSync.call(void 0, r).filter(a=>_fs.statSync.call(void 0, _path.join.call(void 0, r,a)).isDirectory())}exports.a = H; exports.b = T; exports.c = Z; exports.d = te;
2
+ //# sourceMappingURL=chunk-XKYSQSRO.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-PVQIV735.cjs","../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"names":["generateCrossAccountApiKeys","email","password","scopes","apiKeyTitle","parentOrganizationId","deleteExistingApiKey","createNewApiKey","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClientGeneric","logger","colors","roles","loginCookie","loginUser","filteredRoles","role","results","errors","mapSeries","assumeRole","apiKeyWithTitle","fetchAllApiKeys","deleteApiKey","apiKey","createApiKey","err"],"mappings":"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","file":"/home/runner/work/cli/cli/dist/chunk-PVQIV735.cjs","sourcesContent":[null,"import { mapSeries } from 'bluebird';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '../graphql';\nimport { ScopeName } from '@transcend-io/privacy-types';\nimport colors from 'colors';\nimport { StoredApiKey } from '../../codecs';\nimport { logger } from '../../logger';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${\n roles.length === 1 ? '' : 's'\n }!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(\n `Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(\n ',',\n )}.`,\n ),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, [apiKeyTitle]);\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, apiKeyWithTitle.id);\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n title: apiKeyTitle,\n scopes,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${\n results.length === 1 ? '' : 's'\n }`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(\n `Failed to create ${errors.length} API key${\n errors.length === 1 ? '' : 's'\n }!`,\n ),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-XKYSQSRO.cjs","../src/lib/api-keys/generateCrossAccountApiKeys.ts"],"names":["generateCrossAccountApiKeys","email","password","scopes","apiKeyTitle","parentOrganizationId","deleteExistingApiKey","createNewApiKey","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClientGeneric","logger","colors","roles","loginCookie","loginUser","filteredRoles","role","results","errors","mapSeries","assumeRole","apiKeyWithTitle","fetchAllApiKeys","deleteApiKey","apiKey","createApiKey","err"],"mappings":"AAAA,mfAAyC,wDAAkF,wDAAyC,wDAAyC,oCCAnL,gFAUP,MAoBnB,SAAsBA,CAAAA,CAA4B,CAChD,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,MAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CAAuB,CAAA,CAAA,CACvB,eAAA,CAAAC,CAAAA,CAAkB,CAAA,CAAA,CAClB,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAsBG,CAED,IAAMC,CAAAA,CAAS,MAAMC,kCAAAA,CAAmCH,CAAc,CAAC,CAAC,CAAA,CAGxEI,mBAAAA,CAAO,IAAA,CAAKC,gBAAAA,CAAO,OAAA,CAAQ,sCAAsC,CAAC,CAAA,CAClE,GAAM,CAAE,KAAA,CAAAC,CAAAA,CAAO,WAAA,CAAAC,CAAY,CAAA,CAAI,MAAMC,kCAAAA,CAAUN,CAAQ,CAAE,KAAA,CAAAT,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,CAAA,CAC1EU,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCC,CAAAA,CAAM,MAAM,CAAA,KAAA,EAC9CA,CAAAA,CAAM,MAAA,GAAW,CAAA,CAAI,EAAA,CAAK,GAC5B,CAAA,CAAA,CACF,CACF,CAAA,CAGA,IAAMG,CAAAA,CAAgBZ,CAAAA,CAClBS,CAAAA,CAAM,MAAA,CACHI,CAAAA,EACCA,CAAAA,CAAK,YAAA,CAAa,EAAA,GAAOb,CAAAA,EACzBa,CAAAA,CAAK,YAAA,CAAa,oBAAA,GAAyBb,CAC/C,CAAA,CACAS,CAAAA,CAGJJ,CAAAA,CAAO,UAAA,CAAW,CAChB,MAAA,CAAQK,CACV,CAAC,CAAA,CAGD,IAAMI,CAAAA,CAA0B,CAAC,CAAA,CAC3BC,CAAAA,CAAgC,CAAC,CAAA,CAGvC,OAAAR,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,gCAAA,EAAmCT,CAAW,CAAA,UAAA,EAAaD,CAAAA,CAAO,IAAA,CAChE,GACF,CAAC,CAAA,CAAA,CACH,CACF,CAAA,CAGA,MAAMkB,iCAAAA,CAAUJ,CAAe,MAAOC,CAAAA,EAAS,CAC7C,GAAI,CAEF,MAAMI,kCAAAA,CAAWZ,CAAQ,CAAE,MAAA,CAAQQ,CAAAA,CAAK,EAAA,CAAI,KAAA,CAAAjB,CAAM,CAAC,CAAA,CAGnDW,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,oDAAA,EAAuDK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC5G,CACF,CAAA,CAGA,GAAM,CAACmB,CAAe,CAAA,CAAI,MAAMC,kCAAAA,CAAgBd,CAAQ,CAACN,CAAW,CAAC,CAAA,CACrE,EAAA,CAAImB,CAAAA,EAAmBjB,CAAAA,CACrBM,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,MAAA,CACL,CAAA,8BAAA,EAAiCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACtF,CACF,CAAA,CACA,MAAMqB,kCAAAA,CAAaf,CAAQa,CAAAA,CAAgB,EAAE,CAAA,CAC7CX,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CAAA,CAAA,KAAA,EAAA,CACSmB,CAAAA,CAET,MAAM,IAAI,KAAA,CAAM,CAAA,oCAAA,EAAuCnB,CAAW,CAAA,CAAA,CAAG,CAAA,CAIvE,EAAA,CAAIG,CAAAA,CAAiB,CACnBK,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,qBAAA,EAAwBK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CAC7E,CACF,CAAA,CACA,GAAM,CAAE,MAAA,CAAAsB,CAAO,CAAA,CAAI,MAAMC,kCAAAA,CAAajB,CAAQ,CAC5C,KAAA,CAAON,CAAAA,CACP,MAAA,CAAAD,CACF,CAAC,CAAA,CACDgB,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAAQ,CACF,CAAC,CAAA,CACDd,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,KAAA,CACL,CAAA,iCAAA,EAAoCK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,eAAA,EAAkBd,CAAW,CAAA,EAAA,CACzF,CACF,CACF,CAAA,KAEEe,CAAAA,CAAQ,IAAA,CAAK,CACX,gBAAA,CAAkBD,CAAAA,CAAK,YAAA,CAAa,IAAA,CACpC,cAAA,CAAgBA,CAAAA,CAAK,YAAA,CAAa,EAAA,CAClC,MAAA,CAAQ,EACV,CAAC,CAEL,CAAA,KAAA,CAASU,CAAAA,CAAK,CACZhB,mBAAAA,CAAO,KAAA,CACLC,gBAAAA,CAAO,GAAA,CACL,CAAA,0CAAA,EAA6CK,CAAAA,CAAK,YAAA,CAAa,IAAI,CAAA,KAAA,EAAQU,CAAAA,CAAI,OAAO,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-XKYSQSRO.cjs","sourcesContent":[null,"import { mapSeries } from 'bluebird';\nimport {\n buildTranscendGraphQLClientGeneric,\n loginUser,\n createApiKey,\n fetchAllApiKeys,\n deleteApiKey,\n assumeRole,\n} from '../graphql';\nimport { ScopeName } from '@transcend-io/privacy-types';\nimport colors from 'colors';\nimport { StoredApiKey } from '../../codecs';\nimport { logger } from '../../logger';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\nexport interface ApiKeyGenerateError {\n /** Name of instance */\n organizationName: string;\n /** Error */\n error: string;\n /** Organization ID API key is for */\n organizationId: string;\n}\n\n/**\n * Generate API keys across multiple transcend accounts\n *\n * @param options - Options\n * @returns Number of API keys created\n */\nexport async function generateCrossAccountApiKeys({\n email,\n password,\n scopes,\n apiKeyTitle,\n parentOrganizationId,\n deleteExistingApiKey = true,\n createNewApiKey = true,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** Email address of user generating API keys */\n email: string;\n /** Password of user generating API keys */\n password: string;\n /** Filter for organizations that match this parent organization ID */\n parentOrganizationId?: string;\n /** Title of the API create to create */\n apiKeyTitle: string;\n /** Title of the API create to create */\n scopes: ScopeName[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** When true delete existing API keys with that title, if set to false an API key exists with that title, an error is thrown */\n deleteExistingApiKey?: boolean;\n /** When true, generate new API keys, otherwise only will delete past API keys */\n createNewApiKey?: boolean;\n}): Promise<{\n /** Successfully generated */\n apiKeys: StoredApiKey[];\n /** Error results */\n errors: ApiKeyGenerateError[];\n}> {\n // Create GraphQL client\n const client = await buildTranscendGraphQLClientGeneric(transcendUrl, {});\n\n // Login the user\n logger.info(colors.magenta('Logging in using email and password.'));\n const { roles, loginCookie } = await loginUser(client, { email, password });\n logger.info(\n colors.green(\n `Successfully logged in and found ${roles.length} role${\n roles.length === 1 ? '' : 's'\n }!`,\n ),\n );\n\n // Filter down by parentOrganizationId\n const filteredRoles = parentOrganizationId\n ? roles.filter(\n (role) =>\n role.organization.id === parentOrganizationId ||\n role.organization.parentOrganizationId === parentOrganizationId,\n )\n : roles;\n\n // Save cookie to call route subsequent times\n client.setHeaders({\n Cookie: loginCookie,\n });\n\n // Save the resulting API keys\n const results: StoredApiKey[] = [];\n const errors: ApiKeyGenerateError[] = [];\n\n // Generate API keys\n logger.info(\n colors.magenta(\n `Generating API keys with title: ${apiKeyTitle}, scopes: ${scopes.join(\n ',',\n )}.`,\n ),\n );\n\n // Map over each role\n await mapSeries(filteredRoles, async (role) => {\n try {\n // Log into the other instance\n await assumeRole(client, { roleId: role.id, email });\n\n // Grab API keys with that title\n logger.info(\n colors.magenta(\n `Checking if API key already exists in organization \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n\n // Delete existing API key\n const [apiKeyWithTitle] = await fetchAllApiKeys(client, [apiKeyTitle]);\n if (apiKeyWithTitle && deleteExistingApiKey) {\n logger.info(\n colors.yellow(\n `Deleting existing API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n await deleteApiKey(client, apiKeyWithTitle.id);\n logger.info(\n colors.green(\n `Successfully deleted API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else if (apiKeyWithTitle) {\n // throw error if one exists but not configured to delete\n throw new Error(`API key already exists with title: \"${apiKeyTitle}\"`);\n }\n\n // Create the API key\n if (createNewApiKey) {\n logger.info(\n colors.magenta(\n `Creating API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n const { apiKey } = await createApiKey(client, {\n title: apiKeyTitle,\n scopes,\n });\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey,\n });\n logger.info(\n colors.green(\n `Successfully created API key in \"${role.organization.name}\" with title: \"${apiKeyTitle}\".`,\n ),\n );\n } else {\n // Delete only\n results.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n apiKey: '',\n });\n }\n } catch (err) {\n logger.error(\n colors.red(\n `Failed to create API key in organization \"${role.organization.name}\"! - ${err.message}`,\n ),\n );\n errors.push({\n organizationName: role.organization.name,\n organizationId: role.organization.id,\n error: err.message,\n });\n }\n });\n logger.info(\n colors.green(\n `Successfully created ${results.length} API key${\n results.length === 1 ? '' : 's'\n }`,\n ),\n );\n\n if (errors.length > 0) {\n logger.error(\n colors.red(\n `Failed to create ${errors.length} API key${\n errors.length === 1 ? '' : 's'\n }!`,\n ),\n );\n }\n\n return { errors, apiKeys: results };\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkMRJ2BRU4cjs = require('./chunk-MRJ2BRU4.cjs');require('./chunk-LR3CPNDM.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZVE6Y6D3.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-GRBF73LS.cjs');require('./chunk-Q7I37FJV.cjs');async function d({file:i,transcendUrl:o,auth:r,sombraAuth:n,dataSiloId:s}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkMRJ2BRU4cjs.e.call(void 0, {file:i,transcendUrl:o,auth:r,sombraAuth:n,dataSiloId:s})}exports.markIdentifiersCompleted = d;
2
- //# sourceMappingURL=impl-XZOJGVZ7.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkQRDYTLVBcjs = require('./chunk-QRDYTLVB.cjs');require('./chunk-LR3CPNDM.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-QPIUQDJ6.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-MGAJ7ILD.cjs');require('./chunk-Q7I37FJV.cjs');async function d({file:i,transcendUrl:o,auth:r,sombraAuth:n,dataSiloId:s}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkQRDYTLVBcjs.e.call(void 0, {file:i,transcendUrl:o,auth:r,sombraAuth:n,dataSiloId:s})}exports.markIdentifiersCompleted = d;
2
+ //# sourceMappingURL=impl-4VPFFGGS.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-XZOJGVZ7.cjs","../src/commands/request/cron/mark-identifiers-completed/impl.ts"],"names":["markIdentifiersCompleted","file","transcendUrl","auth","sombraAuth","dataSiloId","doneInputValidation","pushCronIdentifiersFromCsv"],"mappings":"AAAA,iIAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCY/P,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,IAAA,CAAAN,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAC,CACH,CAAA,qCAAA","file":"/home/runner/work/cli/cli/dist/impl-XZOJGVZ7.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../../context';\nimport { pushCronIdentifiersFromCsv } from '../../../../lib/cron';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface MarkIdentifiersCompletedCommandFlags {\n file: string;\n transcendUrl: string;\n auth: string;\n sombraAuth?: string;\n dataSiloId: string;\n}\n\nexport async function markIdentifiersCompleted(\n this: LocalContext,\n {\n file,\n transcendUrl,\n auth,\n sombraAuth,\n dataSiloId,\n }: MarkIdentifiersCompletedCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushCronIdentifiersFromCsv({\n file,\n transcendUrl,\n auth,\n sombraAuth,\n dataSiloId,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-4VPFFGGS.cjs","../src/commands/request/cron/mark-identifiers-completed/impl.ts"],"names":["markIdentifiersCompleted","file","transcendUrl","auth","sombraAuth","dataSiloId","doneInputValidation","pushCronIdentifiersFromCsv"],"mappings":"AAAA,iIAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCY/P,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,IAAA,CAAAN,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAC,CACH,CAAA,qCAAA","file":"/home/runner/work/cli/cli/dist/impl-4VPFFGGS.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../../context';\nimport { pushCronIdentifiersFromCsv } from '../../../../lib/cron';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface MarkIdentifiersCompletedCommandFlags {\n file: string;\n transcendUrl: string;\n auth: string;\n sombraAuth?: string;\n dataSiloId: string;\n}\n\nexport async function markIdentifiersCompleted(\n this: LocalContext,\n {\n file,\n transcendUrl,\n auth,\n sombraAuth,\n dataSiloId,\n }: MarkIdentifiersCompletedCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushCronIdentifiersFromCsv({\n file,\n transcendUrl,\n auth,\n sombraAuth,\n dataSiloId,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk2STE3YIZcjs = require('./chunk-2STE3YIZ.cjs');require('./chunk-LR3CPNDM.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-ZVE6Y6D3.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-GRBF73LS.cjs');require('./chunk-Q7I37FJV.cjs');async function u({auth:r,transcendUrl:i,file:e,enricherId:o,concurrency:s,markSilent:a,sombraAuth:m}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunk2STE3YIZcjs.d.call(void 0, {file:e,transcendUrl:i,enricherId:o,concurrency:s,markSilent:a,auth:r,sombraAuth:m})}exports.pushIdentifiers = u;
2
- //# sourceMappingURL=impl-7SHEZUAI.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkDVJLLHL3cjs = require('./chunk-DVJLLHL3.cjs');require('./chunk-LR3CPNDM.cjs');var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');require('./chunk-QPIUQDJ6.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-MGAJ7ILD.cjs');require('./chunk-Q7I37FJV.cjs');async function u({auth:r,transcendUrl:i,file:e,enricherId:o,concurrency:s,markSilent:a,sombraAuth:m}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkDVJLLHL3cjs.d.call(void 0, {file:e,transcendUrl:i,enricherId:o,concurrency:s,markSilent:a,auth:r,sombraAuth:m})}exports.pushIdentifiers = u;
2
+ //# sourceMappingURL=impl-5H6DFFAS.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-7SHEZUAI.cjs","../src/commands/request/preflight/push-identifiers/impl.ts"],"names":["pushIdentifiers","auth","transcendUrl","file","enricherId","concurrency","markSilent","sombraAuth","doneInputValidation","pushManualEnrichmentIdentifiersFromCsv"],"mappings":"AAAA,iIAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCc/P,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,IAAA,CAAAN,CAAAA,CACA,YAAA,CAAAD,CAAAA,CACA,UAAA,CAAAE,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,IAAA,CAAAL,CAAAA,CACA,UAAA,CAAAM,CACF,CAAC,CACH,CAAA,4BAAA","file":"/home/runner/work/cli/cli/dist/impl-7SHEZUAI.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../../context';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-5H6DFFAS.cjs","../src/commands/request/preflight/push-identifiers/impl.ts"],"names":["pushIdentifiers","auth","transcendUrl","file","enricherId","concurrency","markSilent","sombraAuth","doneInputValidation","pushManualEnrichmentIdentifiersFromCsv"],"mappings":"AAAA,iIAAwC,gCAA6B,wDAAyC,gCAA6B,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCc/P,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,iCAAAA,CACJ,IAAA,CAAAN,CAAAA,CACA,YAAA,CAAAD,CAAAA,CACA,UAAA,CAAAE,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,IAAA,CAAAL,CAAAA,CACA,UAAA,CAAAM,CACF,CAAC,CACH,CAAA,4BAAA","file":"/home/runner/work/cli/cli/dist/impl-5H6DFFAS.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../../context';\nimport { pushManualEnrichmentIdentifiersFromCsv } from '../../../../lib/manual-enrichment';\nimport { doneInputValidation } from '../../../../lib/cli/done-input-validation';\n\nexport interface PushIdentifiersCommandFlags {\n auth: string;\n enricherId: string;\n sombraAuth?: string;\n transcendUrl: string;\n file: string;\n markSilent: boolean;\n concurrency: number;\n}\n\nexport async function pushIdentifiers(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n file,\n enricherId,\n concurrency,\n markSilent,\n sombraAuth,\n }: PushIdentifiersCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await pushManualEnrichmentIdentifiersFromCsv({\n file,\n transcendUrl,\n enricherId,\n concurrency,\n markSilent,\n auth,\n sombraAuth,\n });\n}\n"]}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkZVE6Y6D3cjs = require('./chunk-ZVE6Y6D3.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-GRBF73LS.cjs');require('./chunk-Q7I37FJV.cjs');async function d({auth:r,transcendUrl:n,actions:o,statuses:s,requestIds:a,createdAtBefore:i,createdAtAfter:c,concurrency:m}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkZVE6Y6D3cjs.hf.call(void 0, {transcendUrl:n,requestActions:o,auth:r,requestIds:a,statuses:s,concurrency:m,createdAtBefore:i,createdAtAfter:c})}exports.markSilent = d;
2
- //# sourceMappingURL=impl-BCEZUJCK.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkQPIUQDJ6cjs = require('./chunk-QPIUQDJ6.cjs');require('./chunk-LCDYXJN6.cjs');require('./chunk-ZUNVPK23.cjs');require('./chunk-MGAJ7ILD.cjs');require('./chunk-Q7I37FJV.cjs');async function d({auth:r,transcendUrl:n,actions:o,statuses:s,requestIds:a,createdAtBefore:i,createdAtAfter:c,concurrency:m}){_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit),await _chunkQPIUQDJ6cjs.hf.call(void 0, {transcendUrl:n,requestActions:o,auth:r,requestIds:a,statuses:s,concurrency:m,createdAtBefore:i,createdAtAfter:c})}exports.markSilent = d;
2
+ //# sourceMappingURL=impl-6JRE252A.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-BCEZUJCK.cjs","../src/commands/request/mark-silent/impl.ts"],"names":["markSilent","auth","transcendUrl","actions","statuses","requestIds","createdAtBefore","createdAtAfter","concurrency","doneInputValidation","markSilentPrivacyRequests"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCgBtM,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,kCAAAA,CACJ,YAAA,CAAAR,CAAAA,CACA,cAAA,CAAgBC,CAAAA,CAChB,IAAA,CAAAF,CAAAA,CACA,UAAA,CAAAI,CAAAA,CACA,QAAA,CAAAD,CAAAA,CACA,WAAA,CAAAI,CAAAA,CACA,eAAA,CAAAF,CAAAA,CACA,cAAA,CAAAC,CACF,CAAC,CACH,CAAA,uBAAA","file":"/home/runner/work/cli/cli/dist/impl-BCEZUJCK.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { markSilentPrivacyRequests } from '../../../lib/requests';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function markSilent(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n actions,\n statuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/cli/cli/dist/impl-6JRE252A.cjs","../src/commands/request/mark-silent/impl.ts"],"names":["markSilent","auth","transcendUrl","actions","statuses","requestIds","createdAtBefore","createdAtAfter","concurrency","doneInputValidation","markSilentPrivacyRequests"],"mappings":"AAAA,iIAAwC,wDAA0C,gCAA6B,gCAA6B,gCAA6B,gCAA6B,MCgBtM,SAAsBA,CAAAA,CAEpB,CACE,IAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CACF,CAAA,CACe,CACfC,iCAAAA,IAAoB,CAAK,OAAA,CAAQ,IAAI,CAAA,CAErC,MAAMC,kCAAAA,CACJ,YAAA,CAAAR,CAAAA,CACA,cAAA,CAAgBC,CAAAA,CAChB,IAAA,CAAAF,CAAAA,CACA,UAAA,CAAAI,CAAAA,CACA,QAAA,CAAAD,CAAAA,CACA,WAAA,CAAAI,CAAAA,CACA,eAAA,CAAAF,CAAAA,CACA,cAAA,CAAAC,CACF,CAAC,CACH,CAAA,uBAAA","file":"/home/runner/work/cli/cli/dist/impl-6JRE252A.cjs","sourcesContent":[null,"import type { LocalContext } from '../../../context';\nimport { markSilentPrivacyRequests } from '../../../lib/requests';\nimport type { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { doneInputValidation } from '../../../lib/cli/done-input-validation';\n\nexport interface MarkSilentCommandFlags {\n auth: string;\n actions: RequestAction[];\n statuses?: RequestStatus[];\n requestIds?: string[];\n createdAtBefore?: Date;\n createdAtAfter?: Date;\n transcendUrl: string;\n concurrency: number;\n}\n\nexport async function markSilent(\n this: LocalContext,\n {\n auth,\n transcendUrl,\n actions,\n statuses,\n requestIds,\n createdAtBefore,\n createdAtAfter,\n concurrency,\n }: MarkSilentCommandFlags,\n): Promise<void> {\n doneInputValidation(this.process.exit);\n\n await markSilentPrivacyRequests({\n transcendUrl,\n requestActions: actions,\n auth,\n requestIds,\n statuses,\n concurrency,\n createdAtBefore,\n createdAtAfter,\n });\n}\n"]}
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkZVE6Y6D3cjs = require('./chunk-ZVE6Y6D3.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkGRBF73LScjs = require('./chunk-GRBF73LS.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var j = _interopRequireWildcard(_iots); var T = _interopRequireWildcard(_iots); var n = _interopRequireWildcard(_iots);var _privacytypes = require('@transcend-io/privacy-types');var _typeutils = require('@transcend-io/type-utils');var Fe=T.intersection([T.type({nodes:T.array(_privacytypes.PreferenceQueryResponseItem)}),T.partial({cursor:T.string})]),xe=["ENOTFOUND","ETIMEDOUT","504 Gateway Time-out","Task timed out after"];async function fe(c,{identifiers:i,partitionKey:h,skipLogging:u=!1}){let a=[],d=_chunkGRBF73LScjs.b.call(void 0, i,100),l=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);u||t.start(i.length,0);let f=0;await _bluebird.map.call(void 0, d,async e=>{let o=0,g=3;for(;o<g;)try{let m=await c.post(`v1/preferences/${h}/query`,{json:{filter:{identifiers:e},limit:e.length}}).json(),w=_typeutils.decodeCodec.call(void 0, Fe,m);a.push(...w.nodes),f+=e.length,t.update(f);break}catch(m){o+=1;let w=_optionalChain([m, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([m, 'optionalAccess', _4 => _4.message])||"";if(o>=g||!xe.some(y=>w.includes(y)))throw new Error(`Received an error from server after ${o} attempts: ${w}`);_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRYING FAILED REQUEST - Attempt ${o}] Failed to fetch ${e.length} user preferences from partition ${h}: ${w}`))}},{concurrency:40}),t.stop();let r=new Date().getTime()-l;return u||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${r/1e3}" seconds.`)),a}function q({row:c,columnToPurposeName:i,purposeSlugs:h,preferenceTopics:u}){let a={};return Object.entries(i).forEach(([d,{purpose:l,preference:t,valueMapping:f}])=>{if(!h.includes(l))throw new Error(`Invalid purpose slug: ${l}, expected: ${h.join(", ")}`);let s=c[d];if(t){let r=u.find(e=>e.slug===t&&e.purpose.trackingType===l);if(!r){let e=u.filter(o=>o.purpose.trackingType===l).map(o=>o.slug);throw new Error(`Invalid preference slug: ${t} for purpose: ${l}. Allowed preference slugs for purpose are: ${e.join(",")}`)}switch(a[l]||(a[l]={preferences:[]}),a[l].preferences||(a[l].preferences=[]),r.type){case _privacytypes.PreferenceTopicType.Boolean:{let e=f[s];if(e===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(e==null)return;if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${t}, expected boolean, got: ${s}`);a[l].preferences.push({topic:t,choice:{booleanValue:e}});break}case _privacytypes.PreferenceTopicType.Select:{let e=f[s];if(e===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(e==null)return;if(typeof e!="string")throw new Error(`Invalid value for select preference: ${t}, expected string, got: ${s}`);let o=e.trim()||null;if(o&&!r.preferenceOptionValues.map(({slug:g})=>g).includes(o))throw new Error(`Invalid value for select preference: ${t}, expected one of: ${r.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${s}`);a[l].preferences.push({topic:t,choice:{selectValue:o}});break}case _privacytypes.PreferenceTopicType.MultiSelect:{if(typeof s!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected string, got: ${s}`);let e=_chunkZVE6Y6D3cjs.nc.call(void 0, s).map(o=>{let g=f[o];if(g===void 0&&s!=="")throw new Error(`No preference mapping found for multi select token "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(g==null)return null;if(typeof g!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected one of: ${r.preferenceOptionValues.map(({slug:m})=>m).join(", ")}, got: ${o}`);return g}).filter(o=>o!==null).sort((o,g)=>o.localeCompare(g));e.length>0&&a[l].preferences.push({topic:t,choice:{selectValues:e}});break}default:throw new Error(`Unknown preference type: ${r.type}`)}}else{let r=f[s];if(r===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=\u2205)`);if(r===null)return;a[l]?a[l].enabled=r===!0:a[l]={enabled:r===!0}}}),_typeutils.apply.call(void 0, a,(d,l)=>{if(typeof d.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${l}`);return{...d,enabled:d.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var B="[NONE]";async function me(c,i){let h=_chunkGRBF73LScjs.j.call(void 0, c.map(a=>Object.keys(a)).flat()),u=_chunkGRBF73LScjs.c.call(void 0, h,[...i.identifierColumn?[i.identifierColumn]:[],...Object.keys(i.columnToPurposeName)]);if(!i.timestampColum){let{timestampName:a}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:u.find(d=>d.toLowerCase().includes("date"))||u.find(d=>d.toLowerCase().includes("time"))||u[0],choices:[...u,B]}]);i.timestampColum=a}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${i.timestampColum}"`)),i.timestampColum!==B){let a=c.map((d,l)=>d[i.timestampColum]?null:[l]).filter(d=>!!d).flat();if(a.length>0)throw new Error(`The timestamp column "${i.timestampColum}" is missing a value for the following rows: ${a.join(`
2
- `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${i.timestampColum}" is present for all row`))}return i}async function ue(c,i){let h=_chunkGRBF73LScjs.j.call(void 0, c.map(t=>Object.keys(t)).flat()),u=_chunkGRBF73LScjs.c.call(void 0, h,[...i.identifierColumn?[i.identifierColumn]:[],...Object.keys(i.columnToPurposeName)]);if(!i.identifierColumn){let{identifierName:t}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:u.find(f=>f.toLowerCase().includes("email"))||u[0],choices:u}]);i.identifierColumn=t}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${i.identifierColumn}"`));let a=c.map((t,f)=>t[i.identifierColumn]?null:[f]).filter(t=>!!t).flat();if(a.length>0){let t=`The identifier column "${i.identifierColumn}" is missing a value for the following rows: ${a.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkZVE6Y6D3cjs.Lf.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(t);let s=c.length;c=c.filter(r=>r[i.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${s-c.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${i.identifierColumn}" is present for all rows`));let d=_chunkGRBF73LScjs.d.call(void 0, c,i.identifierColumn),l=Object.entries(d).filter(([,t])=>t.length>1);if(l.length>0){let t=`The identifier column "${i.identifierColumn}" has duplicate values for the following rows: ${l.slice(0,10).map(([s,r])=>`${s} (${r.length})`).join(`
3
- `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkZVE6Y6D3cjs.Lf.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(t);c=Object.entries(d).map(([,s])=>s.sort((e,o)=>new Date(o[i.timestampColum]).getTime()-new Date(e[i.timestampColum]).getTime())[0]).filter(s=>s)}return{currentState:i,preferences:c}}async function de(c,i,{purposeSlugs:h,preferenceTopics:u,forceTriggerWorkflows:a}){let d=_chunkGRBF73LScjs.j.call(void 0, c.map(f=>Object.keys(f)).flat()),l=_chunkGRBF73LScjs.c.call(void 0, d,[...i.identifierColumn?[i.identifierColumn]:[],...i.timestampColum?[i.timestampColum]:[]]);if(l.length===0){if(a)return i;throw new Error("No other columns to process")}let t=[...h,...u.map(f=>`${f.purpose.trackingType}->${f.slug}`)];return await _bluebird.mapSeries.call(void 0, l,async f=>{let s=_chunkGRBF73LScjs.j.call(void 0, c.map(e=>e[f])),r=i.columnToPurposeName[f];if(r)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${f}" is associated with purpose "${r.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${f} is associated with`,type:"list",default:t.find(m=>m.startsWith(h[0])),choices:t}]),[o,g]=e.split("->");r={purpose:o,preference:g||null,valueMapping:{}}}await _bluebird.mapSeries.call(void 0, s,async e=>{if(r.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${r.valueMapping[e]}"`));return}if(r.preference===null){let{purposeValue:o}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=o}if(r.preference!==null){let o=u.find(m=>m.slug===r.preference);if(!o){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${r.preference}" not found`));return}let g=o.preferenceOptionValues.map(({slug:m})=>m);if(o.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:m}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=m;return}if(o.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:m}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(w=>w===e)}]);r.valueMapping[e]=m;return}if(o.type===_privacytypes.PreferenceTopicType.MultiSelect){let m=_chunkZVE6Y6D3cjs.nc.call(void 0, e);await _bluebird.mapSeries.call(void 0, m,async w=>{if(r.valueMapping[w]!==void 0)return;let{preferenceValue:y}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${w}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find($=>$===w)}]);r.valueMapping[w]=y});return}throw new Error(`Unknown preference topic type: ${o.type}`)}}),i.columnToPurposeName[f]=r}),i}function ge({currentConsentRecord:c,pendingUpdates:i,preferenceTopics:h}){return Object.entries(i).every(([u,{preferences:a=[],enabled:d}])=>{let l=c.purposes.find(f=>f.purpose===u);return!!l&&l.enabled===d?a.every(({topic:f,choice:s})=>l.preferences&&l.preferences.find(r=>{if(r.topic!==f)return!1;let e=h.find(o=>o.slug===f&&o.purpose.trackingType===u);if(!e)throw new Error(`Could not find preference topic for ${f}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return r.choice.booleanValue===s.booleanValue;case _privacytypes.PreferenceTopicType.Select:return r.choice.selectValue===s.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let o=(r.choice.selectValues||[]).sort(),g=(s.selectValues||[]).sort();return o.length===g.length&&o.every((m,w)=>m===g[w]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function we({currentConsentRecord:c,pendingUpdates:i,preferenceTopics:h,log:u}){return!!Object.entries(i).find(([a,{preferences:d=[],enabled:l}])=>{let t=c.purposes.find(f=>f.purpose===a);return t?t.enabled!==l?(u&&_chunkZUNVPK23cjs.a.warn(`Purpose ${a} enabled value conflict for user ${c.userId}. Pending Value: ${l}, Current Value: ${t.enabled}`),!0):!!d.find(({topic:f,choice:s})=>{let r=(t.preferences||[]).find(m=>m.topic===f);if(!r)return u&&_chunkZUNVPK23cjs.a.warn(`No existing preference found for topic ${f} in purpose ${a} for user ${c.userId}.`),!1;let e=h.find(m=>m.slug===f&&m.purpose.trackingType===a);if(!e)throw new Error(`Could not find preference topic for ${f}`);let o,g;switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return o=r.choice.booleanValue!==s.booleanValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} boolean value conflict for user ${c.userId}. Expected: ${s.booleanValue}, Found: ${r.choice.booleanValue}`),o;case _privacytypes.PreferenceTopicType.Select:return g=r.choice.selectValue!==s.selectValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} select value conflict for user ${c.userId}. Expected: ${s.selectValue}, Found: ${r.choice.selectValue}`),g;case _privacytypes.PreferenceTopicType.MultiSelect:let m=(r.choice.selectValues||[]).sort(),w=(s.selectValues||[]).sort();return g=m.length!==w.length||!m.every((y,$)=>y===w[$]),u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} multi-select value conflict for user ${c.userId}. Expected: ${w.join(", ")}, Found: ${m.join(", ")}`),g;default:throw new Error(`Unknown preference topic type: ${e.type}`)}}):(u&&_chunkZUNVPK23cjs.a.warn(`No existing purpose found for ${a} in consent record for ${c.userId}.`),!1)})}async function $e({file:c,sombra:i,purposeSlugs:h,preferenceTopics:u,partitionKey:a,skipExistingRecordCheck:d,forceTriggerWorkflows:l},t){let f=new Date().getTime(),s=t.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${c}"`));let r=_chunkZVE6Y6D3cjs.qc.call(void 0, c,j.record(j.string,j.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...s[c]||{},lastFetchedAt:new Date().toISOString()};e=await me(r,e),s[c]=e,await t.setValue(s,"fileMetadata");let o=await ue(r,e);e=o.currentState,r=o.preferences,s[c]=e,await t.setValue(s,"fileMetadata"),e=await de(r,e,{preferenceTopics:u,purposeSlugs:h,forceTriggerWorkflows:l}),s[c]=e,await t.setValue(s,"fileMetadata");let g=r.map($=>$[e.identifierColumn]),m=d?[]:await fe(i,{identifiers:g.map($=>({value:$})),partitionKey:a}),w=_chunkGRBF73LScjs.e.call(void 0, m,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},r.forEach($=>{let b=$[e.identifierColumn],x=q({row:$,columnToPurposeName:e.columnToPurposeName,preferenceTopics:u,purposeSlugs:h}),V=w[b];if(l&&!V)throw new Error(`No existing consent record found for user with id: ${b}.
4
- When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(V&&ge({currentConsentRecord:V,pendingUpdates:x,preferenceTopics:u})&&!l){e.skippedUpdates[b]=$;return}if(V&&we({currentConsentRecord:V,pendingUpdates:x,preferenceTopics:u})){e.pendingConflictUpdates[b]={row:$,record:V};return}e.pendingSafeUpdates[b]=$}),s[c]=e,await t.setValue(s,"fileMetadata");let y=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${c}" in ${(y-f)/1e3}s`))}var je=n.type({purpose:n.string,preference:n.union([n.string,n.null]),valueMapping:n.record(n.string,n.union([n.string,n.boolean,n.null,n.undefined]))}),Ae=n.intersection([n.type({columnToPurposeName:n.record(n.string,je),lastFetchedAt:n.string,pendingSafeUpdates:n.record(n.string,n.record(n.string,n.string)),pendingConflictUpdates:n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),skippedUpdates:n.record(n.string,n.record(n.string,n.string))}),n.partial({identifierColumn:n.string,timestampColum:n.string})]),Pe=n.type({fileMetadata:n.record(n.string,Ae),failingUpdates:n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:n.record(n.string,_privacytypes.PreferenceUpdateItem)});async function Ce({auth:c,sombraAuth:i,receiptFilepath:h,file:u,partition:a,isSilent:d=!0,dryRun:l=!1,skipWorkflowTriggers:t=!1,skipConflictUpdates:f=!1,skipExistingRecordCheck:s=!1,attributes:r=[],transcendUrl:e,forceTriggerWorkflows:o=!1}){let g=_chunkZVE6Y6D3cjs.pc.call(void 0, r),m=new (0, _persistedstate.PersistedState)(h,Pe,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),w=m.getValue("failingUpdates"),y=m.getValue("pendingUpdates"),$=m.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkWKCTKYN4cjs = require('./chunk-WKCTKYN4.cjs');var _chunkQPIUQDJ6cjs = require('./chunk-QPIUQDJ6.cjs');require('./chunk-LCDYXJN6.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkMGAJ7ILDcjs = require('./chunk-MGAJ7ILD.cjs');require('./chunk-Q7I37FJV.cjs');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);var _bluebird = require('bluebird');var _cliprogress = require('cli-progress'); var _cliprogress2 = _interopRequireDefault(_cliprogress);var _persistedstate = require('@transcend-io/persisted-state');var _iots = require('io-ts'); var j = _interopRequireWildcard(_iots); var T = _interopRequireWildcard(_iots); var n = _interopRequireWildcard(_iots);var _privacytypes = require('@transcend-io/privacy-types');var _typeutils = require('@transcend-io/type-utils');var Fe=T.intersection([T.type({nodes:T.array(_privacytypes.PreferenceQueryResponseItem)}),T.partial({cursor:T.string})]),xe=["ENOTFOUND","ETIMEDOUT","504 Gateway Time-out","Task timed out after"];async function fe(c,{identifiers:i,partitionKey:h,skipLogging:u=!1}){let a=[],d=_chunkMGAJ7ILDcjs.b.call(void 0, i,100),l=new Date().getTime(),t=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);u||t.start(i.length,0);let f=0;await _bluebird.map.call(void 0, d,async e=>{let o=0,g=3;for(;o<g;)try{let m=await c.post(`v1/preferences/${h}/query`,{json:{filter:{identifiers:e},limit:e.length}}).json(),w=_typeutils.decodeCodec.call(void 0, Fe,m);a.push(...w.nodes),f+=e.length,t.update(f);break}catch(m){o+=1;let w=_optionalChain([m, 'optionalAccess', _2 => _2.response, 'optionalAccess', _3 => _3.body])||_optionalChain([m, 'optionalAccess', _4 => _4.message])||"";if(o>=g||!xe.some(y=>w.includes(y)))throw new Error(`Received an error from server after ${o} attempts: ${w}`);_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRYING FAILED REQUEST - Attempt ${o}] Failed to fetch ${e.length} user preferences from partition ${h}: ${w}`))}},{concurrency:40}),t.stop();let r=new Date().getTime()-l;return u||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${r/1e3}" seconds.`)),a}function q({row:c,columnToPurposeName:i,purposeSlugs:h,preferenceTopics:u}){let a={};return Object.entries(i).forEach(([d,{purpose:l,preference:t,valueMapping:f}])=>{if(!h.includes(l))throw new Error(`Invalid purpose slug: ${l}, expected: ${h.join(", ")}`);let s=c[d];if(t){let r=u.find(e=>e.slug===t&&e.purpose.trackingType===l);if(!r){let e=u.filter(o=>o.purpose.trackingType===l).map(o=>o.slug);throw new Error(`Invalid preference slug: ${t} for purpose: ${l}. Allowed preference slugs for purpose are: ${e.join(",")}`)}switch(a[l]||(a[l]={preferences:[]}),a[l].preferences||(a[l].preferences=[]),r.type){case _privacytypes.PreferenceTopicType.Boolean:{let e=f[s];if(e===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(e==null)return;if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${t}, expected boolean, got: ${s}`);a[l].preferences.push({topic:t,choice:{booleanValue:e}});break}case _privacytypes.PreferenceTopicType.Select:{let e=f[s];if(e===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(e==null)return;if(typeof e!="string")throw new Error(`Invalid value for select preference: ${t}, expected string, got: ${s}`);let o=e.trim()||null;if(o&&!r.preferenceOptionValues.map(({slug:g})=>g).includes(o))throw new Error(`Invalid value for select preference: ${t}, expected one of: ${r.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${s}`);a[l].preferences.push({topic:t,choice:{selectValue:o}});break}case _privacytypes.PreferenceTopicType.MultiSelect:{if(typeof s!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected string, got: ${s}`);let e=_chunkQPIUQDJ6cjs.nc.call(void 0, s).map(o=>{let g=f[o];if(g===void 0&&s!=="")throw new Error(`No preference mapping found for multi select token "${s}" in column "${d}" (purpose=${l}, preference=${t})`);if(g==null)return null;if(typeof g!="string")throw new Error(`Invalid value for multi select preference: ${t}, expected one of: ${r.preferenceOptionValues.map(({slug:m})=>m).join(", ")}, got: ${o}`);return g}).filter(o=>o!==null).sort((o,g)=>o.localeCompare(g));e.length>0&&a[l].preferences.push({topic:t,choice:{selectValues:e}});break}default:throw new Error(`Unknown preference type: ${r.type}`)}}else{let r=f[s];if(r===void 0&&s!=="")throw new Error(`No preference mapping found for value "${s}" in column "${d}" (purpose=${l}, preference=\u2205)`);if(r===null)return;a[l]?a[l].enabled=r===!0:a[l]={enabled:r===!0}}}),_typeutils.apply.call(void 0, a,(d,l)=>{if(typeof d.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${l}`);return{...d,enabled:d.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var B="[NONE]";async function me(c,i){let h=_chunkMGAJ7ILDcjs.j.call(void 0, c.map(a=>Object.keys(a)).flat()),u=_chunkMGAJ7ILDcjs.c.call(void 0, h,[...i.identifierColumn?[i.identifierColumn]:[],...Object.keys(i.columnToPurposeName)]);if(!i.timestampColum){let{timestampName:a}=await _inquirer2.default.prompt([{name:"timestampName",message:"Choose the column that will be used as the timestamp of last preference update",type:"list",default:u.find(d=>d.toLowerCase().includes("date"))||u.find(d=>d.toLowerCase().includes("time"))||u[0],choices:[...u,B]}]);i.timestampColum=a}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${i.timestampColum}"`)),i.timestampColum!==B){let a=c.map((d,l)=>d[i.timestampColum]?null:[l]).filter(d=>!!d).flat();if(a.length>0)throw new Error(`The timestamp column "${i.timestampColum}" is missing a value for the following rows: ${a.join(`
2
+ `)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${i.timestampColum}" is present for all row`))}return i}async function ue(c,i){let h=_chunkMGAJ7ILDcjs.j.call(void 0, c.map(t=>Object.keys(t)).flat()),u=_chunkMGAJ7ILDcjs.c.call(void 0, h,[...i.identifierColumn?[i.identifierColumn]:[],...Object.keys(i.columnToPurposeName)]);if(!i.identifierColumn){let{identifierName:t}=await _inquirer2.default.prompt([{name:"identifierName",message:"Choose the column that will be used as the identifier to upload consent preferences by",type:"list",default:u.find(f=>f.toLowerCase().includes("email"))||u[0],choices:u}]);i.identifierColumn=t}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${i.identifierColumn}"`));let a=c.map((t,f)=>t[i.identifierColumn]?null:[f]).filter(t=>!!t).flat();if(a.length>0){let t=`The identifier column "${i.identifierColumn}" is missing a value for the following rows: ${a.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkQPIUQDJ6cjs.Lf.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(t);let s=c.length;c=c.filter(r=>r[i.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${s-c.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${i.identifierColumn}" is present for all rows`));let d=_chunkMGAJ7ILDcjs.d.call(void 0, c,i.identifierColumn),l=Object.entries(d).filter(([,t])=>t.length>1);if(l.length>0){let t=`The identifier column "${i.identifierColumn}" has duplicate values for the following rows: ${l.slice(0,10).map(([s,r])=>`${s} (${r.length})`).join(`
3
+ `)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(t)),!await _chunkQPIUQDJ6cjs.Lf.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(t);c=Object.entries(d).map(([,s])=>s.sort((e,o)=>new Date(o[i.timestampColum]).getTime()-new Date(e[i.timestampColum]).getTime())[0]).filter(s=>s)}return{currentState:i,preferences:c}}async function de(c,i,{purposeSlugs:h,preferenceTopics:u,forceTriggerWorkflows:a}){let d=_chunkMGAJ7ILDcjs.j.call(void 0, c.map(f=>Object.keys(f)).flat()),l=_chunkMGAJ7ILDcjs.c.call(void 0, d,[...i.identifierColumn?[i.identifierColumn]:[],...i.timestampColum?[i.timestampColum]:[]]);if(l.length===0){if(a)return i;throw new Error("No other columns to process")}let t=[...h,...u.map(f=>`${f.purpose.trackingType}->${f.slug}`)];return await _bluebird.mapSeries.call(void 0, l,async f=>{let s=_chunkMGAJ7ILDcjs.j.call(void 0, c.map(e=>e[f])),r=i.columnToPurposeName[f];if(r)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${f}" is associated with purpose "${r.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${f} is associated with`,type:"list",default:t.find(m=>m.startsWith(h[0])),choices:t}]),[o,g]=e.split("->");r={purpose:o,preference:g||null,valueMapping:{}}}await _bluebird.mapSeries.call(void 0, s,async e=>{if(r.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${r.valueMapping[e]}"`));return}if(r.preference===null){let{purposeValue:o}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=o}if(r.preference!==null){let o=u.find(m=>m.slug===r.preference);if(!o){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${r.preference}" not found`));return}let g=o.preferenceOptionValues.map(({slug:m})=>m);if(o.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:m}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"confirm",default:e!=="false"}]);r.valueMapping[e]=m;return}if(o.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:m}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${e}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find(w=>w===e)}]);r.valueMapping[e]=m;return}if(o.type===_privacytypes.PreferenceTopicType.MultiSelect){let m=_chunkQPIUQDJ6cjs.nc.call(void 0, e);await _bluebird.mapSeries.call(void 0, m,async w=>{if(r.valueMapping[w]!==void 0)return;let{preferenceValue:y}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${o.slug}" value "${w}" associated with purpose "${r.purpose}"`,type:"list",choices:g,default:g.find($=>$===w)}]);r.valueMapping[w]=y});return}throw new Error(`Unknown preference topic type: ${o.type}`)}}),i.columnToPurposeName[f]=r}),i}function ge({currentConsentRecord:c,pendingUpdates:i,preferenceTopics:h}){return Object.entries(i).every(([u,{preferences:a=[],enabled:d}])=>{let l=c.purposes.find(f=>f.purpose===u);return!!l&&l.enabled===d?a.every(({topic:f,choice:s})=>l.preferences&&l.preferences.find(r=>{if(r.topic!==f)return!1;let e=h.find(o=>o.slug===f&&o.purpose.trackingType===u);if(!e)throw new Error(`Could not find preference topic for ${f}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return r.choice.booleanValue===s.booleanValue;case _privacytypes.PreferenceTopicType.Select:return r.choice.selectValue===s.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let o=(r.choice.selectValues||[]).sort(),g=(s.selectValues||[]).sort();return o.length===g.length&&o.every((m,w)=>m===g[w]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function we({currentConsentRecord:c,pendingUpdates:i,preferenceTopics:h,log:u}){return!!Object.entries(i).find(([a,{preferences:d=[],enabled:l}])=>{let t=c.purposes.find(f=>f.purpose===a);return t?t.enabled!==l?(u&&_chunkZUNVPK23cjs.a.warn(`Purpose ${a} enabled value conflict for user ${c.userId}. Pending Value: ${l}, Current Value: ${t.enabled}`),!0):!!d.find(({topic:f,choice:s})=>{let r=(t.preferences||[]).find(m=>m.topic===f);if(!r)return u&&_chunkZUNVPK23cjs.a.warn(`No existing preference found for topic ${f} in purpose ${a} for user ${c.userId}.`),!1;let e=h.find(m=>m.slug===f&&m.purpose.trackingType===a);if(!e)throw new Error(`Could not find preference topic for ${f}`);let o,g;switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return o=r.choice.booleanValue!==s.booleanValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} boolean value conflict for user ${c.userId}. Expected: ${s.booleanValue}, Found: ${r.choice.booleanValue}`),o;case _privacytypes.PreferenceTopicType.Select:return g=r.choice.selectValue!==s.selectValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} select value conflict for user ${c.userId}. Expected: ${s.selectValue}, Found: ${r.choice.selectValue}`),g;case _privacytypes.PreferenceTopicType.MultiSelect:let m=(r.choice.selectValues||[]).sort(),w=(s.selectValues||[]).sort();return g=m.length!==w.length||!m.every((y,$)=>y===w[$]),u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${f} multi-select value conflict for user ${c.userId}. Expected: ${w.join(", ")}, Found: ${m.join(", ")}`),g;default:throw new Error(`Unknown preference topic type: ${e.type}`)}}):(u&&_chunkZUNVPK23cjs.a.warn(`No existing purpose found for ${a} in consent record for ${c.userId}.`),!1)})}async function $e({file:c,sombra:i,purposeSlugs:h,preferenceTopics:u,partitionKey:a,skipExistingRecordCheck:d,forceTriggerWorkflows:l},t){let f=new Date().getTime(),s=t.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${c}"`));let r=_chunkQPIUQDJ6cjs.qc.call(void 0, c,j.record(j.string,j.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...s[c]||{},lastFetchedAt:new Date().toISOString()};e=await me(r,e),s[c]=e,await t.setValue(s,"fileMetadata");let o=await ue(r,e);e=o.currentState,r=o.preferences,s[c]=e,await t.setValue(s,"fileMetadata"),e=await de(r,e,{preferenceTopics:u,purposeSlugs:h,forceTriggerWorkflows:l}),s[c]=e,await t.setValue(s,"fileMetadata");let g=r.map($=>$[e.identifierColumn]),m=d?[]:await fe(i,{identifiers:g.map($=>({value:$})),partitionKey:a}),w=_chunkMGAJ7ILDcjs.e.call(void 0, m,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},r.forEach($=>{let b=$[e.identifierColumn],x=q({row:$,columnToPurposeName:e.columnToPurposeName,preferenceTopics:u,purposeSlugs:h}),V=w[b];if(l&&!V)throw new Error(`No existing consent record found for user with id: ${b}.
4
+ When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(V&&ge({currentConsentRecord:V,pendingUpdates:x,preferenceTopics:u})&&!l){e.skippedUpdates[b]=$;return}if(V&&we({currentConsentRecord:V,pendingUpdates:x,preferenceTopics:u})){e.pendingConflictUpdates[b]={row:$,record:V};return}e.pendingSafeUpdates[b]=$}),s[c]=e,await t.setValue(s,"fileMetadata");let y=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${c}" in ${(y-f)/1e3}s`))}var je=n.type({purpose:n.string,preference:n.union([n.string,n.null]),valueMapping:n.record(n.string,n.union([n.string,n.boolean,n.null,n.undefined]))}),Ae=n.intersection([n.type({columnToPurposeName:n.record(n.string,je),lastFetchedAt:n.string,pendingSafeUpdates:n.record(n.string,n.record(n.string,n.string)),pendingConflictUpdates:n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),skippedUpdates:n.record(n.string,n.record(n.string,n.string))}),n.partial({identifierColumn:n.string,timestampColum:n.string})]),Pe=n.type({fileMetadata:n.record(n.string,Ae),failingUpdates:n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),pendingUpdates:n.record(n.string,_privacytypes.PreferenceUpdateItem)});async function Ce({auth:c,sombraAuth:i,receiptFilepath:h,file:u,partition:a,isSilent:d=!0,dryRun:l=!1,skipWorkflowTriggers:t=!1,skipConflictUpdates:f=!1,skipExistingRecordCheck:s=!1,attributes:r=[],transcendUrl:e,forceTriggerWorkflows:o=!1}){let g=_chunkQPIUQDJ6cjs.pc.call(void 0, r),m=new (0, _persistedstate.PersistedState)(h,Pe,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),w=m.getValue("failingUpdates"),y=m.getValue("pendingUpdates"),$=m.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
5
5
  ${Object.values(w).length} failing requests to be retried
6
6
  ${Object.values(y).length} pending requests to be processed
7
7
  The following files are stored in cache and will be used:
8
8
  ${Object.keys($).map(P=>P).join(`
9
9
  `)}
10
10
  The following file will be processed: ${u}
11
- `));let b=_chunkZVE6Y6D3cjs.vc.call(void 0, e,c),[x,V,H]=await Promise.all([_chunkZVE6Y6D3cjs.wc.call(void 0, e,c,i),o?Promise.resolve([]):_chunkZVE6Y6D3cjs.dd.call(void 0, b),o?Promise.resolve([]):_chunkZVE6Y6D3cjs.$c.call(void 0, b)]);await $e({file:u,purposeSlugs:V.map(P=>P.trackingType),preferenceTopics:H,sombra:x,partitionKey:a,skipExistingRecordCheck:s,forceTriggerWorkflows:o},m);let S={};$=m.getValue("fileMetadata");let k=$[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...k.pendingSafeUpdates,...f?{}:_typeutils.apply.call(void 0, k.pendingConflictUpdates,({row:P})=>P)}).forEach(([P,C])=>{let A=k.timestampColum===B?new Date:new Date(C[k.timestampColum]),M=q({row:C,columnToPurposeName:k.columnToPurposeName,preferenceTopics:H,purposeSlugs:V.map(R=>R.trackingType)});S[P]={userId:P,partition:a,timestamp:A.toISOString(),purposes:Object.entries(M).map(([R,ke])=>({...ke,purpose:R,workflowSettings:{attributes:g,isSilent:d,skipWorkflowTrigger:t}}))}}),await m.setValue(S,"pendingUpdates"),await m.setValue({},"failingUpdates"),l){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(S).length} pending updates. Check file: ${h}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(S).length} preferences to partition: ${a}`));let ve=new Date().getTime(),Q=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),X=0,L=Object.entries(S),Ve=_chunkGRBF73LScjs.b.call(void 0, L,t?100:10);Q.start(L.length,0),await _bluebird.map.call(void 0, Ve,async P=>{try{await x.put("v1/preferences",{json:{records:P.map(([,C])=>C),skipWorkflowTriggers:t,forceTriggerWorkflows:o}}).json()}catch(C){try{let M=JSON.parse(_optionalChain([C, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");M.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${M.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${P.length} user preferences to partition ${a}: ${_optionalChain([C, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([C, 'optionalAccess', _9 => _9.message])}`));let A=m.getValue("failingUpdates");P.forEach(([M,R])=>{A[M]={uploadedAt:new Date().toISOString(),update:R,error:_optionalChain([C, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([C, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await m.setValue(A,"failingUpdates")}X+=P.length,Q.update(X)},{concurrency:40}),Q.stop();let Ue=new Date().getTime()-ve;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${L.length} user preferences to partition ${a} in "${Ue/1e3}" seconds!`))}var _fs = require('fs');var _path = require('path');async function It({auth:c,partition:i,sombraAuth:h,transcendUrl:u,file:a="",directory:d,dryRun:l,skipExistingRecordCheck:t,receiptFileDir:f,skipWorkflowTriggers:s,forceTriggerWorkflows:r,skipConflictUpdates:e,isSilent:o,attributes:g,concurrency:m}){d&&a&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Cannot provide both a directory and a file. Please provide only one.")),this.process.exit(1)),!a&&!d&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences")),this.process.exit(1)),_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let w=[];if(d)try{let $=_fs.readdirSync.call(void 0, d).filter(b=>b.endsWith(".csv"));$.length===0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`No CSV files found in directory: ${d}`)),this.process.exit(1)),w.push(...$.map(b=>_path.join.call(void 0, d,b)))}catch(y){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to read directory: ${d}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(y.message)),this.process.exit(1)}else try{a.endsWith(".csv")||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("File must be a CSV file")),this.process.exit(1)),w.push(a)}catch(y){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to access file: ${a}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(y.message)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Processing ${w.length} consent preferences files for partition: ${i}`)),_chunkZUNVPK23cjs.a.debug(`Files to process: ${w.join(", ")}`),t&&_chunkZUNVPK23cjs.a.info(_colors2.default.bgYellow(`Skipping existing record check: ${t}`)),await _bluebird.map.call(void 0, w,async y=>{let $=_path.basename.call(void 0, y).replace(".csv","");await Ce({receiptFilepath:_path.join.call(void 0, f,`${$}-receipts.json`),auth:c,sombraAuth:h,file:y,partition:i,transcendUrl:u,skipConflictUpdates:e,skipWorkflowTriggers:s,skipExistingRecordCheck:t,isSilent:o,dryRun:l,attributes:_chunkZVE6Y6D3cjs.nc.call(void 0, g),forceTriggerWorkflows:r})},{concurrency:m})}exports.uploadPreferences = It;
12
- //# sourceMappingURL=impl-BJU7SNUT.cjs.map
11
+ `));let b=_chunkQPIUQDJ6cjs.vc.call(void 0, e,c),[x,V,H]=await Promise.all([_chunkQPIUQDJ6cjs.wc.call(void 0, e,c,i),o?Promise.resolve([]):_chunkQPIUQDJ6cjs.dd.call(void 0, b),o?Promise.resolve([]):_chunkQPIUQDJ6cjs.$c.call(void 0, b)]);await $e({file:u,purposeSlugs:V.map(P=>P.trackingType),preferenceTopics:H,sombra:x,partitionKey:a,skipExistingRecordCheck:s,forceTriggerWorkflows:o},m);let S={};$=m.getValue("fileMetadata");let k=$[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(k.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...k.pendingSafeUpdates,...f?{}:_typeutils.apply.call(void 0, k.pendingConflictUpdates,({row:P})=>P)}).forEach(([P,C])=>{let A=k.timestampColum===B?new Date:new Date(C[k.timestampColum]),M=q({row:C,columnToPurposeName:k.columnToPurposeName,preferenceTopics:H,purposeSlugs:V.map(R=>R.trackingType)});S[P]={userId:P,partition:a,timestamp:A.toISOString(),purposes:Object.entries(M).map(([R,ke])=>({...ke,purpose:R,workflowSettings:{attributes:g,isSilent:d,skipWorkflowTrigger:t}}))}}),await m.setValue(S,"pendingUpdates"),await m.setValue({},"failingUpdates"),l){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(S).length} pending updates. Check file: ${h}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(S).length} preferences to partition: ${a}`));let ve=new Date().getTime(),Q=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),X=0,L=Object.entries(S),Ve=_chunkMGAJ7ILDcjs.b.call(void 0, L,t?100:10);Q.start(L.length,0),await _bluebird.map.call(void 0, Ve,async P=>{try{await x.put("v1/preferences",{json:{records:P.map(([,C])=>C),skipWorkflowTriggers:t,forceTriggerWorkflows:o}}).json()}catch(C){try{let M=JSON.parse(_optionalChain([C, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");M.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${M.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${P.length} user preferences to partition ${a}: ${_optionalChain([C, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([C, 'optionalAccess', _9 => _9.message])}`));let A=m.getValue("failingUpdates");P.forEach(([M,R])=>{A[M]={uploadedAt:new Date().toISOString(),update:R,error:_optionalChain([C, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([C, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await m.setValue(A,"failingUpdates")}X+=P.length,Q.update(X)},{concurrency:40}),Q.stop();let Ue=new Date().getTime()-ve;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${L.length} user preferences to partition ${a} in "${Ue/1e3}" seconds!`))}var _fs = require('fs');var _path = require('path');async function It({auth:c,partition:i,sombraAuth:h,transcendUrl:u,file:a="",directory:d,dryRun:l,skipExistingRecordCheck:t,receiptFileDir:f,skipWorkflowTriggers:s,forceTriggerWorkflows:r,skipConflictUpdates:e,isSilent:o,attributes:g,concurrency:m}){d&&a&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("Cannot provide both a directory and a file. Please provide only one.")),this.process.exit(1)),!a&&!d&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red("A file or directory must be provided. Please provide one using --file=./preferences.csv or --directory=./preferences")),this.process.exit(1)),_chunkWKCTKYN4cjs.a.call(void 0, this.process.exit);let w=[];if(d)try{let $=_fs.readdirSync.call(void 0, d).filter(b=>b.endsWith(".csv"));$.length===0&&(_chunkZUNVPK23cjs.a.error(_colors2.default.red(`No CSV files found in directory: ${d}`)),this.process.exit(1)),w.push(...$.map(b=>_path.join.call(void 0, d,b)))}catch(y){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to read directory: ${d}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(y.message)),this.process.exit(1)}else try{a.endsWith(".csv")||(_chunkZUNVPK23cjs.a.error(_colors2.default.red("File must be a CSV file")),this.process.exit(1)),w.push(a)}catch(y){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to access file: ${a}`)),_chunkZUNVPK23cjs.a.error(_colors2.default.red(y.message)),this.process.exit(1)}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Processing ${w.length} consent preferences files for partition: ${i}`)),_chunkZUNVPK23cjs.a.debug(`Files to process: ${w.join(", ")}`),t&&_chunkZUNVPK23cjs.a.info(_colors2.default.bgYellow(`Skipping existing record check: ${t}`)),await _bluebird.map.call(void 0, w,async y=>{let $=_path.basename.call(void 0, y).replace(".csv","");await Ce({receiptFilepath:_path.join.call(void 0, f,`${$}-receipts.json`),auth:c,sombraAuth:h,file:y,partition:i,transcendUrl:u,skipConflictUpdates:e,skipWorkflowTriggers:s,skipExistingRecordCheck:t,isSilent:o,dryRun:l,attributes:_chunkQPIUQDJ6cjs.nc.call(void 0, g),forceTriggerWorkflows:r})},{concurrency:m})}exports.uploadPreferences = It;
12
+ //# sourceMappingURL=impl-7RJYKTCZ.cjs.map