@transcend-io/cli 8.30.1 → 8.31.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.
- package/README.md +4 -4
- package/dist/bin/bash-complete.cjs +1 -1
- package/dist/bin/cli.cjs +1 -1
- package/dist/bin/deprecated-command.cjs +2 -2
- package/dist/{chunk-LRADV5OI.cjs → chunk-52MA7ZLS.cjs} +2 -2
- package/dist/{chunk-LRADV5OI.cjs.map → chunk-52MA7ZLS.cjs.map} +1 -1
- package/dist/{chunk-HTS7K7QD.cjs → chunk-55B57ZAY.cjs} +4 -4
- package/dist/{chunk-HTS7K7QD.cjs.map → chunk-55B57ZAY.cjs.map} +1 -1
- package/dist/{chunk-LZA5Y4SB.cjs → chunk-7H4ALAHC.cjs} +4 -4
- package/dist/{chunk-LZA5Y4SB.cjs.map → chunk-7H4ALAHC.cjs.map} +1 -1
- package/dist/{chunk-T3BBQIRY.cjs → chunk-7PB6LVSE.cjs} +2 -2
- package/dist/chunk-7PB6LVSE.cjs.map +1 -0
- package/dist/{chunk-LU3DKRNK.cjs → chunk-ABKDAPPR.cjs} +2 -2
- package/dist/{chunk-LU3DKRNK.cjs.map → chunk-ABKDAPPR.cjs.map} +1 -1
- package/dist/{chunk-XEXS6R45.cjs → chunk-ALOB5SWZ.cjs} +2 -2
- package/dist/{chunk-XEXS6R45.cjs.map → chunk-ALOB5SWZ.cjs.map} +1 -1
- package/dist/{chunk-SPN6SWMF.cjs → chunk-DIB7IOEX.cjs} +2 -2
- package/dist/{chunk-SPN6SWMF.cjs.map → chunk-DIB7IOEX.cjs.map} +1 -1
- package/dist/{chunk-RAA5VWQS.cjs → chunk-G522ZIHS.cjs} +2 -2
- package/dist/{chunk-RAA5VWQS.cjs.map → chunk-G522ZIHS.cjs.map} +1 -1
- package/dist/{chunk-UXFL56TL.cjs → chunk-HCEZRZHV.cjs} +6 -6
- package/dist/{chunk-UXFL56TL.cjs.map → chunk-HCEZRZHV.cjs.map} +1 -1
- package/dist/{chunk-BQSBPO63.cjs → chunk-JH5HRI6D.cjs} +3 -3
- package/dist/{chunk-BQSBPO63.cjs.map → chunk-JH5HRI6D.cjs.map} +1 -1
- package/dist/{chunk-WURUFVEG.cjs → chunk-M3Y6JH6I.cjs} +2 -2
- package/dist/{chunk-WURUFVEG.cjs.map → chunk-M3Y6JH6I.cjs.map} +1 -1
- package/dist/{chunk-FIJLHU4Q.cjs → chunk-M7OVJJGB.cjs} +4 -4
- package/dist/{chunk-FIJLHU4Q.cjs.map → chunk-M7OVJJGB.cjs.map} +1 -1
- package/dist/{chunk-6KRRRMY2.cjs → chunk-MXT7N555.cjs} +21 -21
- package/dist/{chunk-6KRRRMY2.cjs.map → chunk-MXT7N555.cjs.map} +1 -1
- package/dist/{chunk-YYDWSYMF.cjs → chunk-NC6VWOMN.cjs} +2 -2
- package/dist/{chunk-YYDWSYMF.cjs.map → chunk-NC6VWOMN.cjs.map} +1 -1
- package/dist/{chunk-Z2DYKPKM.cjs → chunk-Q2RJZGYW.cjs} +2 -2
- package/dist/{chunk-Z2DYKPKM.cjs.map → chunk-Q2RJZGYW.cjs.map} +1 -1
- package/dist/{chunk-3FIDP42N.cjs → chunk-SKOTYI3A.cjs} +2 -2
- package/dist/chunk-SKOTYI3A.cjs.map +1 -0
- package/dist/{chunk-FHUHBSLE.cjs → chunk-TSJTXXLZ.cjs} +2 -2
- package/dist/{chunk-FHUHBSLE.cjs.map → chunk-TSJTXXLZ.cjs.map} +1 -1
- package/dist/{chunk-OMVVROKB.cjs → chunk-XXFLFF7Q.cjs} +2 -2
- package/dist/{chunk-OMVVROKB.cjs.map → chunk-XXFLFF7Q.cjs.map} +1 -1
- package/dist/impl-4CWCLU5Z.cjs +2 -0
- package/dist/{impl-J62VZXDY.cjs.map → impl-4CWCLU5Z.cjs.map} +1 -1
- package/dist/{impl-BSIFPZLW.cjs → impl-542SIWQ2.cjs} +2 -2
- package/dist/{impl-BSIFPZLW.cjs.map → impl-542SIWQ2.cjs.map} +1 -1
- package/dist/impl-55GTRVMZ.cjs +2 -0
- package/dist/{impl-FKXR7U4X.cjs.map → impl-55GTRVMZ.cjs.map} +1 -1
- package/dist/{impl-KBVYLYIZ.cjs → impl-5VMEZB7F.cjs} +2 -2
- package/dist/{impl-KBVYLYIZ.cjs.map → impl-5VMEZB7F.cjs.map} +1 -1
- package/dist/{impl-2X2FNMJR.cjs → impl-6ANYWCOV.cjs} +2 -2
- package/dist/{impl-2X2FNMJR.cjs.map → impl-6ANYWCOV.cjs.map} +1 -1
- package/dist/{impl-VBE4QUJN.cjs → impl-A7XL5O4W.cjs} +2 -2
- package/dist/{impl-VBE4QUJN.cjs.map → impl-A7XL5O4W.cjs.map} +1 -1
- package/dist/{impl-COZ7ADUO.cjs → impl-BQNXMBQ4.cjs} +4 -4
- package/dist/{impl-COZ7ADUO.cjs.map → impl-BQNXMBQ4.cjs.map} +1 -1
- package/dist/{impl-3BTFEGV4.cjs → impl-CFYRFABZ.cjs} +5 -5
- package/dist/{impl-3BTFEGV4.cjs.map → impl-CFYRFABZ.cjs.map} +1 -1
- package/dist/{impl-T7EOUHYL.cjs → impl-D2HENZNO.cjs} +2 -2
- package/dist/{impl-T7EOUHYL.cjs.map → impl-D2HENZNO.cjs.map} +1 -1
- package/dist/{impl-IFHM4YOL.cjs → impl-GEEPG7OH.cjs} +2 -2
- package/dist/{impl-IFHM4YOL.cjs.map → impl-GEEPG7OH.cjs.map} +1 -1
- package/dist/{impl-EE3BM53W.cjs → impl-GRGWQUU7.cjs} +2 -2
- package/dist/{impl-EE3BM53W.cjs.map → impl-GRGWQUU7.cjs.map} +1 -1
- package/dist/{impl-Z3EAXTJV.cjs → impl-JFYHXSOV.cjs} +2 -2
- package/dist/{impl-Z3EAXTJV.cjs.map → impl-JFYHXSOV.cjs.map} +1 -1
- package/dist/impl-JQVCW52V.cjs +2 -0
- package/dist/{impl-RTZTJWMX.cjs.map → impl-JQVCW52V.cjs.map} +1 -1
- package/dist/impl-JSXYZHX4.cjs +2 -0
- package/dist/{impl-VHY4ALCB.cjs.map → impl-JSXYZHX4.cjs.map} +1 -1
- package/dist/{impl-Q5WCETP4.cjs → impl-K2D3GTZG.cjs} +2 -2
- package/dist/{impl-Q5WCETP4.cjs.map → impl-K2D3GTZG.cjs.map} +1 -1
- package/dist/{impl-463J7BYV.cjs → impl-KQYINEBI.cjs} +2 -2
- package/dist/{impl-463J7BYV.cjs.map → impl-KQYINEBI.cjs.map} +1 -1
- package/dist/impl-KRJNBGJ6.cjs +2 -0
- package/dist/{impl-7BAUUGZT.cjs.map → impl-KRJNBGJ6.cjs.map} +1 -1
- package/dist/{impl-5WHENVVS.cjs → impl-NK42TN4C.cjs} +2 -2
- package/dist/{impl-5WHENVVS.cjs.map → impl-NK42TN4C.cjs.map} +1 -1
- package/dist/{impl-5GGFGRTD.cjs → impl-OQAP7YDW.cjs} +2 -2
- package/dist/{impl-5GGFGRTD.cjs.map → impl-OQAP7YDW.cjs.map} +1 -1
- package/dist/{impl-T5V56TM5.cjs → impl-PHBUSAGS.cjs} +2 -2
- package/dist/{impl-T5V56TM5.cjs.map → impl-PHBUSAGS.cjs.map} +1 -1
- package/dist/{impl-XAZ6YY3R.cjs → impl-PKWSORXX.cjs} +2 -2
- package/dist/{impl-XAZ6YY3R.cjs.map → impl-PKWSORXX.cjs.map} +1 -1
- package/dist/{impl-4CA7VK4U.cjs → impl-PWYKAVK4.cjs} +2 -2
- package/dist/{impl-4CA7VK4U.cjs.map → impl-PWYKAVK4.cjs.map} +1 -1
- package/dist/{impl-UMVE7IPO.cjs → impl-Q3P6DGHG.cjs} +2 -2
- package/dist/{impl-UMVE7IPO.cjs.map → impl-Q3P6DGHG.cjs.map} +1 -1
- package/dist/{impl-ZJ2L727T.cjs → impl-RD5UOJY6.cjs} +2 -2
- package/dist/{impl-ZJ2L727T.cjs.map → impl-RD5UOJY6.cjs.map} +1 -1
- package/dist/{impl-U76PZBUK.cjs → impl-REKQO7ZI.cjs} +2 -2
- package/dist/{impl-U76PZBUK.cjs.map → impl-REKQO7ZI.cjs.map} +1 -1
- package/dist/{impl-IM22LNW5.cjs → impl-RI3WQFOE.cjs} +3 -3
- package/dist/{impl-IM22LNW5.cjs.map → impl-RI3WQFOE.cjs.map} +1 -1
- package/dist/impl-SRI65ZIC.cjs +2 -0
- package/dist/{impl-IBOGAUVL.cjs.map → impl-SRI65ZIC.cjs.map} +1 -1
- package/dist/{impl-YEXEFJS7.cjs → impl-T67PUM7X.cjs} +2 -2
- package/dist/{impl-YEXEFJS7.cjs.map → impl-T67PUM7X.cjs.map} +1 -1
- package/dist/{impl-NEV6KDPU.cjs → impl-TCR3Y3J2.cjs} +2 -2
- package/dist/{impl-NEV6KDPU.cjs.map → impl-TCR3Y3J2.cjs.map} +1 -1
- package/dist/{impl-VPUALIUR.cjs → impl-U46BMUFL.cjs} +2 -2
- package/dist/{impl-VPUALIUR.cjs.map → impl-U46BMUFL.cjs.map} +1 -1
- package/dist/{impl-BLIELFUK.cjs → impl-UVQJ7HSK.cjs} +3 -3
- package/dist/{impl-BLIELFUK.cjs.map → impl-UVQJ7HSK.cjs.map} +1 -1
- package/dist/{impl-GJMVAL3N.cjs → impl-V3MXFXZF.cjs} +2 -2
- package/dist/{impl-GJMVAL3N.cjs.map → impl-V3MXFXZF.cjs.map} +1 -1
- package/dist/{impl-76E4DKAE.cjs → impl-VL3CJ2OT.cjs} +2 -2
- package/dist/{impl-76E4DKAE.cjs.map → impl-VL3CJ2OT.cjs.map} +1 -1
- package/dist/{impl-Z5HT5JQU.cjs → impl-VT3C6SP4.cjs} +2 -2
- package/dist/{impl-Z5HT5JQU.cjs.map → impl-VT3C6SP4.cjs.map} +1 -1
- package/dist/{impl-OFB5I4S6.cjs → impl-VUAC7AYF.cjs} +2 -2
- package/dist/{impl-OFB5I4S6.cjs.map → impl-VUAC7AYF.cjs.map} +1 -1
- package/dist/impl-VXOHC45F.cjs +3 -0
- package/dist/{impl-LMKJ6UBT.cjs.map → impl-VXOHC45F.cjs.map} +1 -1
- package/dist/{impl-UPDFANVR.cjs → impl-WMI46UXI.cjs} +2 -2
- package/dist/{impl-UPDFANVR.cjs.map → impl-WMI46UXI.cjs.map} +1 -1
- package/dist/{impl-FTSCECOZ.cjs → impl-XJBUIDZP.cjs} +2 -2
- package/dist/{impl-FTSCECOZ.cjs.map → impl-XJBUIDZP.cjs.map} +1 -1
- package/dist/impl-XLL66FXK.cjs +2 -0
- package/dist/{impl-X6TORGVF.cjs.map → impl-XLL66FXK.cjs.map} +1 -1
- package/dist/{impl-BSI3RBQ2.cjs → impl-YGVW4RTA.cjs} +2 -2
- package/dist/{impl-BSI3RBQ2.cjs.map → impl-YGVW4RTA.cjs.map} +1 -1
- package/dist/{impl-AWWB3TEU.cjs → impl-ZAKPYQ32.cjs} +2 -2
- package/dist/{impl-AWWB3TEU.cjs.map → impl-ZAKPYQ32.cjs.map} +1 -1
- package/dist/{impl-DS73OYLE.cjs → impl-ZTYQ3IB5.cjs} +2 -2
- package/dist/{impl-DS73OYLE.cjs.map → impl-ZTYQ3IB5.cjs.map} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +3 -3
- package/package.json +1 -1
- package/dist/chunk-3FIDP42N.cjs.map +0 -1
- package/dist/chunk-T3BBQIRY.cjs.map +0 -1
- package/dist/impl-7BAUUGZT.cjs +0 -2
- package/dist/impl-FKXR7U4X.cjs +0 -2
- package/dist/impl-IBOGAUVL.cjs +0 -2
- package/dist/impl-J62VZXDY.cjs +0 -2
- package/dist/impl-LMKJ6UBT.cjs +0 -3
- package/dist/impl-RTZTJWMX.cjs +0 -2
- package/dist/impl-VHY4ALCB.cjs +0 -2
- package/dist/impl-X6TORGVF.cjs +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var
|
|
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 _chunkXXFLFF7Qcjs = require('./chunk-XXFLFF7Q.cjs');var _chunk7PB6LVSEcjs = require('./chunk-7PB6LVSE.cjs');var _core = require('@stricli/core');var _privacytypes = require('@transcend-io/privacy-types');var _ms = require('ms'); var _ms2 = _interopRequireDefault(_ms);function S(e){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))throw new Error(`Invalid UUID format: ${e}`);return e}function n(e){try{return new URL(e).toString().replace(/\/$/,"")}catch (e2){throw new Error(`Invalid URL format: ${e}`)}}function T(e){return e.split(",").map(r=>r.trim()).filter(r=>r.length>0)}function y(e){let r=new Date(e);if(Number.isNaN(r.getTime()))throw new TypeError(`Invalid date: ${e}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`);return r}function k(e){if(typeof e=="number"&&Number.isFinite(e))return Math.round(e*1e3);if(typeof e=="string"){let r=e.trim();if(r==="")throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".');let t=Number(r);if(r!==""&&Number.isFinite(t))return Math.round(t*1e3);let a;try{a=_ms2.default.call(void 0, r)}catch (e3){throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}if(typeof a=="number"&&Number.isFinite(a))return a}throw new Error('Invalid duration. Examples: "45", "2d", "1h", "90 minutes", "10s".')}var d=({scopes:e,requiresSiloScope:r=!1})=>{let t={kind:"parsed",parse:String,brief:"The Transcend API key."};return r&&(t.brief+=" This key must be associated with the data silo(s) being operated on."),e==="Varies"?{...t,brief:`${t.brief} The scopes required will vary depending on the operation performed. If in doubt, the ${_privacytypes.TRANSCEND_SCOPES[_privacytypes.ScopeName.FullAdmin].title} scope will always work.`}:e.length===0?{...t,brief:`${t.brief} No scopes are required for this command.`}:{...t,brief:`${t.brief} Requires scopes: ${e.map(a=>`"${_privacytypes.TRANSCEND_SCOPES[a].title}"`).join(", ")}`}},u= exports.f =(e=_chunkXXFLFF7Qcjs.r)=>({kind:"parsed",parse:n,brief:"URL of the Transcend backend. Use https://api.us.transcend.io for US hosting",default:e}),x= exports.g =(e=_chunkXXFLFF7Qcjs.s)=>({kind:"parsed",parse:n,brief:"URL of the Transcend consent backend. Use https://consent.us.transcend.io for US hosting",default:e}),A= exports.h =()=>({kind:"parsed",parse:String,brief:"The Sombra internal key, use for additional authentication when self-hosting Sombra",optional:!0});var g=["dataSilos","enrichers","templates","apiKeys"],I= exports.j =Object.values(_privacytypes.ConsentTrackerStatus),R= exports.k =_core.buildCommand.call(void 0, {loader:async()=>{let{pull:e}=await Promise.resolve().then(() => _interopRequireWildcard(require("./impl-UVQJ7HSK.cjs")));return e},parameters:{flags:{auth:d({scopes:"Varies"}),resources:{kind:"enum",values:["all",...Object.values(_chunk7PB6LVSEcjs.d)],brief:`The different resource types to pull in. Defaults to ${g.join(",")}.`,variadic:",",optional:!0},file:{kind:"parsed",parse:String,brief:"Path to the YAML file to pull into",default:"./transcend.yml"},transcendUrl:u(),dataSiloIds:{kind:"parsed",parse:String,variadic:",",brief:"The UUIDs of the data silos that should be pulled into the YAML file",optional:!0},integrationNames:{kind:"parsed",parse:String,variadic:",",brief:"The types of integrations to pull down",optional:!0},trackerStatuses:{kind:"enum",values:Object.values(_privacytypes.ConsentTrackerStatus),variadic:",",brief:"The statuses of consent manager trackers to pull down. Defaults to all statuses.",optional:!0},pageSize:{kind:"parsed",parse:_core.numberParser,brief:"The page size to use when paginating over the API",default:"50"},skipDatapoints:{kind:"boolean",brief:"When true, skip pulling in datapoints alongside data silo resource",default:!1},skipSubDatapoints:{kind:"boolean",brief:"When true, skip pulling in subDatapoints alongside data silo resource",default:!1},includeGuessedCategories:{kind:"boolean",brief:"When true, included guessed data categories that came from the content classifier",default:!1},debug:{kind:"boolean",brief:"Set to true to include debug logs while pulling the configuration",default:!1}}},docs:{brief:"Pull metadata from Transcend into transcend.yml",fullDescription:`Generates a transcend.yml by pulling the configuration from your Transcend instance.
|
|
2
2
|
|
|
3
3
|
The API key needs various scopes depending on the resources being pulled (see the CLI's README for more details).
|
|
4
4
|
|
|
@@ -6,4 +6,4 @@ This command can be helpful if you are looking to:
|
|
|
6
6
|
|
|
7
7
|
- Copy your data into another instance
|
|
8
8
|
- Generate a transcend.yml file as a starting point to maintain parts of your data inventory in code.`}});exports.a = S; exports.b = T; exports.c = y; exports.d = k; exports.e = d; exports.f = u; exports.g = x; exports.h = A; exports.i = g; exports.j = I; exports.k = R;
|
|
9
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
//# sourceMappingURL=chunk-DIB7IOEX.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-DIB7IOEX.cjs","../src/commands/inventory/pull/command.ts","../src/lib/cli/parsers.ts"],"names":["uuidParser","input"],"mappings":"AAAA,mfAA0C,wDAAyC,qCCAxC,2DACN,gECDiB,SAStCA,CAAAA,CAAWC,CAAAA,CAAuB,CAGhD,EAAA,CAAI,CADF,4EAAA,CACa,IAAA,CAAKA,CAAK,CAAA,CACvB,MAAM,IAAI,KAAA,CAAM,CAAA,qBAAA,EAAwBA,CAAK,CAAA,CAAA;ADwF5B;AAAA;AAAA;AAAA;AAAA;AAAA;AASpB,qGAAA","file":"/home/runner/work/cli/cli/dist/chunk-DIB7IOEX.cjs","sourcesContent":[null,"import { buildCommand, numberParser } from '@stricli/core';\nimport { ConsentTrackerStatus } from '@transcend-io/privacy-types';\nimport {\n createAuthParameter,\n createTranscendUrlParameter,\n} from '../../../lib/cli/common-parameters';\nimport { TranscendPullResource } from '../../../enums';\n\nexport const DEFAULT_TRANSCEND_PULL_RESOURCES = [\n TranscendPullResource.DataSilos,\n TranscendPullResource.Enrichers,\n TranscendPullResource.Templates,\n TranscendPullResource.ApiKeys,\n];\n\nexport const DEFAULT_CONSENT_TRACKER_STATUSES =\n Object.values(ConsentTrackerStatus);\n\nexport const pullCommand = buildCommand({\n loader: async () => {\n const { pull } = await import('./impl');\n return pull;\n },\n parameters: {\n flags: {\n auth: createAuthParameter({\n scopes: 'Varies',\n }),\n resources: {\n kind: 'enum',\n values: ['all', ...Object.values(TranscendPullResource)],\n brief: `The different resource types to pull in. Defaults to ${DEFAULT_TRANSCEND_PULL_RESOURCES.join(\n ',',\n )}.`,\n variadic: ',',\n optional: true,\n },\n file: {\n kind: 'parsed',\n parse: String,\n brief: 'Path to the YAML file to pull into',\n default: './transcend.yml',\n },\n transcendUrl: createTranscendUrlParameter(),\n dataSiloIds: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief:\n 'The UUIDs of the data silos that should be pulled into the YAML file',\n optional: true,\n },\n integrationNames: {\n kind: 'parsed',\n parse: String,\n variadic: ',',\n brief: 'The types of integrations to pull down',\n optional: true,\n },\n trackerStatuses: {\n kind: 'enum',\n values: Object.values(ConsentTrackerStatus),\n variadic: ',',\n brief:\n 'The statuses of consent manager trackers to pull down. Defaults to all statuses.',\n optional: true,\n },\n pageSize: {\n kind: 'parsed',\n parse: numberParser,\n brief: 'The page size to use when paginating over the API',\n default: '50',\n },\n skipDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in datapoints alongside data silo resource',\n default: false,\n },\n skipSubDatapoints: {\n kind: 'boolean',\n brief:\n 'When true, skip pulling in subDatapoints alongside data silo resource',\n default: false,\n },\n includeGuessedCategories: {\n kind: 'boolean',\n brief:\n 'When true, included guessed data categories that came from the content classifier',\n default: false,\n },\n debug: {\n kind: 'boolean',\n brief:\n 'Set to true to include debug logs while pulling the configuration',\n default: false,\n },\n },\n },\n docs: {\n brief: 'Pull metadata from Transcend into transcend.yml',\n fullDescription: `Generates a transcend.yml by pulling the configuration from your Transcend instance.\n\nThe API key needs various scopes depending on the resources being pulled (see the CLI's README for more details).\n\nThis command can be helpful if you are looking to:\n\n- Copy your data into another instance\n- Generate a transcend.yml file as a starting point to maintain parts of your data inventory in code.`,\n },\n});\n","import ms, { type StringValue as MsStringValue } from 'ms';\n\n/**\n * Validates and returns a UUID string.\n *\n * @param input - The input string to validate as UUID\n * @returns The validated UUID string\n * @throws Error if input is not a valid UUID\n */\nexport function uuidParser(input: string): string {\n const uuidRegex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(input)) {\n throw new Error(`Invalid UUID format: ${input}`);\n }\n return input;\n}\n\n/**\n * Validates and returns a URL string.\n *\n * @param input - The input string to validate as URL\n * @returns The validated URL string\n * @throws Error if input is not a valid URL\n */\nexport function urlParser(input: string): string {\n try {\n const url = new URL(input);\n return url.toString().replace(/\\/$/, '');\n } catch {\n throw new Error(`Invalid URL format: ${input}`);\n }\n}\n\n/**\n * Parse a comma-separated string to array.\n * NOTE: Prefer using `variadic` for list arguments instead of this function. This should only be used for arguments which have a default value.\n *\n * @param input - The comma-separated string to parse\n * @returns Array of trimmed, non-empty strings\n */\nexport function arrayParser(input: string): string[] {\n return input\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/**\n * Parse a date string to a Date object.\n *\n * @param input - The date string to parse\n * @returns The parsed Date object\n * @throws TypeError if input is not a valid date\n */\nexport function dateParser(input: string): Date {\n const date = new Date(input);\n if (Number.isNaN(date.getTime())) {\n throw new TypeError(\n `Invalid date: ${input}. Try using the ISO 8601 format (YYYY-MM-DDTHH:MM:SS.SSSZ)`,\n );\n }\n return date;\n}\n\n/**\n * Parse a duration string to milliseconds.\n * Accepts concise/natural-ish strings (powered by `ms`) and returns milliseconds.\n * Examples: \"3600\", \"2d\", \"1h\", \"90 minutes\", \"10s\".\n *\n * @param input - The duration to parse\n * @returns The parsed duration in milliseconds\n * @throws Error if input is not a valid duration\n */\nexport function parseDurationToMs(input: unknown): number {\n if (typeof input === 'number' && Number.isFinite(input)) {\n // backward-compat: numbers => seconds\n return Math.round(input * 1000);\n }\n\n if (typeof input === 'string') {\n const trimmed = input.trim();\n // empty string → our standardized error (avoid ms throwing its own)\n if (trimmed === '') {\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n\n // bare numeric string => seconds (backward-compat)\n const asNumber = Number(trimmed);\n if (trimmed !== '' && Number.isFinite(asNumber)) {\n return Math.round(asNumber * 1000);\n }\n\n // let ms parse human strings\n let parsed: number | undefined;\n try {\n parsed = ms(trimmed as MsStringValue);\n } catch {\n // normalize ms' error to ours\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n }\n if (typeof parsed === 'number' && Number.isFinite(parsed)) {\n return parsed;\n }\n }\n\n throw new Error(\n 'Invalid duration. Examples: \"45\", \"2d\", \"1h\", \"90 minutes\", \"10s\".',\n );\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var
|
|
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 _chunk55B57ZAYcjs = require('./chunk-55B57ZAY.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkXXFLFF7Qcjs = require('./chunk-XXFLFF7Q.cjs');var _privacytypes = require('@transcend-io/privacy-types');var _bluebird = require('bluebird');var _colors = require('colors'); var _colors2 = _interopRequireDefault(_colors);async function te({file:u,auth:s,sombraAuth:g,requestActions:f=[],concurrency:p=100,transcendUrl:n=_chunkXXFLFF7Qcjs.r}){let o=_chunk55B57ZAYcjs.xc.call(void 0, n,s),e=await _chunk55B57ZAYcjs.yc.call(void 0, n,s,g);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Pulling manual enrichment requests, filtered for actions: ${f.join(",")}`));let d=await _chunk55B57ZAYcjs.od.call(void 0, o,{actions:f,statuses:[_privacytypes.RequestStatus.Enriching]}),i=[];await _bluebird.map.call(void 0, d,async t=>{let c=await _chunk55B57ZAYcjs.id.call(void 0, o,{requestId:t.id});if(c.filter(({status:m})=>m==="ACTION_REQUIRED")){let m=await _chunk55B57ZAYcjs.ld.call(void 0, o,e,{requestId:t.id});i.push({...t,requestIdentifiers:m,requestEnrichers:c})}},{concurrency:p});let l=i.map(({attributeValues:t,requestIdentifiers:c,requestEnrichers:w,...m})=>({...m,...Object.entries(_chunkXXFLFF7Qcjs.d.call(void 0, c,"name")).reduce((I,[P,$])=>Object.assign(I,{[P]:$.map(({value:C})=>C).join(",")}),{}),...Object.entries(_chunkXXFLFF7Qcjs.d.call(void 0, t,"attributeKey.name")).reduce((I,[P,$])=>Object.assign(I,{[P]:$.map(({name:C})=>C).join(",")}),{})})),a=_chunkXXFLFF7Qcjs.j.call(void 0, l.map(t=>Object.keys(t)).flat());return await _chunk55B57ZAYcjs.rg.call(void 0, u,l,a),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully wrote ${i.length} requests to file "${u}"`)),i}var _iots = require('io-ts'); var R = _interopRequireWildcard(_iots);var T="https://app.transcend.io/privacy-requests/incoming-requests/",F= exports.b =R.record(R.string,R.string);async function M(u,{id:s,...g},f,p){if(!s){let e=`Request ID must be provided to enricher request.${p?` Found error in row: ${p}`:""}`;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(e)),new Error(e)}let n=s.toLowerCase(),o=Object.entries(g).reduce((e,[d,i])=>_chunkXXFLFF7Qcjs.j.call(void 0, _chunk55B57ZAYcjs.pc.call(void 0, i)).length===0?e:Object.assign(e,{[d]:_chunkXXFLFF7Qcjs.j.call(void 0, _chunk55B57ZAYcjs.pc.call(void 0, i)).map(a=>({value:d==="email"?a.toLowerCase():a}))}),{});try{return await u.post("v1/enrich-identifiers",{headers:{"x-transcend-request-id":n,"x-transcend-enricher-id":f},json:{enrichedIdentifiers:o}}).json(),_chunkZUNVPK23cjs.a.error(_colors2.default.green(`Successfully enriched request: ${T}${n}`)),!0}catch(e){if(typeof e.response.body=="string"&&e.response.body.includes("Cannot update a resolved RequestEnricher"))return _chunkZUNVPK23cjs.a.warn(_colors2.default.magenta(`Skipped enrichment for request: ${T}${n}, request is no longer in the enriching phase.`)),!1;throw _chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to enricher identifiers for request with id: ${T}${n} - ${e.message} - ${e.response.body}`)),e}}async function ge({file:u,auth:s,sombraAuth:g,enricherId:f,markSilent:p,concurrency:n=100,transcendUrl:o=_chunkXXFLFF7Qcjs.r}){let e=await _chunk55B57ZAYcjs.yc.call(void 0, o,s,g),d=_chunk55B57ZAYcjs.xc.call(void 0, o,s);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading "${u}" from disk`));let i=_chunk55B57ZAYcjs.sc.call(void 0, u,F);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Enriching "${i.length}" privacy requests.`));let l=0,a=0,t=0;if(await _bluebird.map.call(void 0, i,async(c,w)=>{try{p&&(await _chunk55B57ZAYcjs.ug.call(void 0, d,_chunk55B57ZAYcjs.Z,{input:{id:c.id,isSilent:!0}}),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Mark request as silent mode - ${c.id}`))),await M(e,c,f,w)?l+=1:a+=1}catch (e2){t+=1}},{concurrency:n}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully notified Transcend!
|
|
2
2
|
Success count: ${l}.`)),a>0&&_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Skipped count: ${a}.`)),t>0)throw _chunkZUNVPK23cjs.a.info(_colors2.default.red(`Error Count: ${t}.`)),new Error(`Failed to enrich: ${t} requests.`);return i.length}exports.a = te; exports.b = F; exports.c = M; exports.d = ge;
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-G522ZIHS.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-G522ZIHS.cjs","../src/lib/manual-enrichment/pullManualEnrichmentIdentifiersToCsv.ts","../src/lib/manual-enrichment/pushManualEnrichmentIdentifiersFromCsv.ts"],"names":["pullManualEnrichmentIdentifiersToCsv","file","auth","sombraAuth","requestActions","concurrency","transcendUrl","DEFAULT_TRANSCEND_API","client","buildTranscendGraphQLClient","sombra","createSombraGotInstance","logger","colors"],"mappings":"AAAA,mfAAgH,wDAAyC,wDAAuD,2DCAnK,oCACzB,gFACD,MA6BnB,SAAsBA,EAAAA,CAAqC,CACzD,IAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,UAAA,CAAAC,CAAAA,CACA,cAAA,CAAAC,CAAAA,CAAiB,CAAC,CAAA,CAClB,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,YAAA,CAAAC,CAAAA,CAAeC,mBACjB,CAAA,CAa6C,CAE3C,IAAMC,CAAAA,CAASC,kCAAAA,CAA4BH,CAAcJ,CAAI,CAAA,CACvDQ,CAAAA,CAAS,MAAMC,kCAAAA,CAAwBL,CAAcJ,CAAAA,CAAMC,CAAU,CAAA,CAE3ES,mBAAAA,CAAO,IAAA,CACLC,gBAAAA,CAAO,OAAA,CACL,CAAA,0DAAA,EAA6DT,CAAAA,CAAe,IAAA,CAC1E,GACF,CAAC,CAAA,CAAA;ACuDP,gBAAA","file":"/home/runner/work/cli/cli/dist/chunk-G522ZIHS.cjs","sourcesContent":[null,"import { RequestAction, RequestStatus } from '@transcend-io/privacy-types';\nimport { map } from 'bluebird';\nimport colors from 'colors';\nimport { groupBy, uniq } from 'lodash-es';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport { writeCsv } from '../helpers/writeCsv';\nimport {\n PrivacyRequest,\n RequestEnricher,\n RequestIdentifier,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllRequestEnrichers,\n fetchAllRequestIdentifiers,\n fetchAllRequests,\n} from '../graphql';\nimport { logger } from '../../logger';\n\nexport interface PrivacyRequestWithIdentifiers extends PrivacyRequest {\n /** Request Enrichers */\n requestEnrichers: RequestEnricher[];\n /** Request Identifiers */\n requestIdentifiers: RequestIdentifier[];\n}\n\n/**\n * Pull the set of manual enrichment jobs to CSV\n *\n * @param options - Options\n * @returns List of requests with identifiers\n */\nexport async function pullManualEnrichmentIdentifiersToCsv({\n file,\n auth,\n sombraAuth,\n requestActions = [],\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** Sombra API key */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** The request actions to fetch */\n requestActions?: RequestAction[];\n /** API URL for Transcend backend */\n transcendUrl?: string;\n}): Promise<PrivacyRequestWithIdentifiers[]> {\n // Find all requests made before createdAt that are in a removing data state\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n\n logger.info(\n colors.magenta(\n `Pulling manual enrichment requests, filtered for actions: ${requestActions.join(\n ',',\n )}`,\n ),\n );\n\n // Pull all privacy requests\n const allRequests = await fetchAllRequests(client, {\n actions: requestActions,\n statuses: [RequestStatus.Enriching],\n });\n\n // Requests to save\n const savedRequests: PrivacyRequestWithIdentifiers[] = [];\n\n // Filter down requests to what is needed\n await map(\n allRequests,\n async (request) => {\n // Fetch enrichers\n const requestEnrichers = await fetchAllRequestEnrichers(client, {\n requestId: request.id,\n });\n\n // Check if manual enrichment exists for that request\n const hasManualEnrichment = requestEnrichers.filter(\n ({ status }) => status === 'ACTION_REQUIRED',\n );\n\n // Save request to queue\n if (hasManualEnrichment) {\n const requestIdentifiers = await fetchAllRequestIdentifiers(\n client,\n sombra,\n {\n requestId: request.id,\n },\n );\n savedRequests.push({\n ...request,\n requestIdentifiers,\n requestEnrichers,\n });\n }\n },\n {\n concurrency,\n },\n );\n\n const data = savedRequests.map(\n ({\n attributeValues,\n requestIdentifiers,\n requestEnrichers, // eslint-disable-line @typescript-eslint/no-unused-vars\n ...request\n }) => ({\n ...request,\n // flatten identifiers\n ...Object.entries(groupBy(requestIdentifiers, 'name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ value }) => value).join(','),\n }),\n {},\n ),\n // flatten attributes\n ...Object.entries(groupBy(attributeValues, 'attributeKey.name')).reduce(\n (acc, [key, values]) =>\n Object.assign(acc, {\n [key]: values.map(({ name }) => name).join(','),\n }),\n {},\n ),\n }),\n );\n\n // Write out to CSV\n const headers = uniq(data.map((d) => Object.keys(d)).flat());\n await writeCsv(file, data, headers);\n\n logger.info(\n colors.green(\n `Successfully wrote ${savedRequests.length} requests to file \"${file}\"`,\n ),\n );\n\n return savedRequests;\n}\n","import colors from 'colors';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport {\n UPDATE_PRIVACY_REQUEST,\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n makeGraphQLRequest,\n} from '../graphql';\nimport {\n enrichPrivacyRequest,\n EnrichPrivacyRequest,\n} from './enrichPrivacyRequest';\nimport { readCsv } from '../requests';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\n\n/**\n * Push a CSV of enriched requests back into Transcend\n *\n * @param options - Options\n * @returns Number of items processed\n */\nexport async function pushManualEnrichmentIdentifiersFromCsv({\n file,\n auth,\n sombraAuth,\n enricherId,\n markSilent,\n concurrency = 100,\n transcendUrl = DEFAULT_TRANSCEND_API,\n}: {\n /** CSV file path */\n file: string;\n /** Transcend API key authentication */\n auth: string;\n /** ID of enricher being uploaded to */\n enricherId: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Concurrency */\n concurrency?: number;\n /** API URL for Transcend backend */\n transcendUrl?: string;\n /** Mark requests in silent mode before enriching */\n markSilent?: boolean;\n}): Promise<number> {\n // Create sombra instance to communicate with\n const sombra = await createSombraGotInstance(transcendUrl, auth, sombraAuth);\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n // Read from CSV\n logger.info(colors.magenta(`Reading \"${file}\" from disk`));\n const activeResults = readCsv(file, EnrichPrivacyRequest);\n\n // Notify Transcend\n logger.info(\n colors.magenta(`Enriching \"${activeResults.length}\" privacy requests.`),\n );\n\n let successCount = 0;\n let skippedCount = 0;\n let errorCount = 0;\n\n await map(\n activeResults,\n async (request, index) => {\n try {\n // Mark requests in silent mode before a certain date\n if (markSilent) {\n await makeGraphQLRequest(client, UPDATE_PRIVACY_REQUEST, {\n input: {\n id: request.id,\n isSilent: true,\n },\n });\n\n logger.info(\n colors.magenta(`Mark request as silent mode - ${request.id}`),\n );\n }\n\n const result = await enrichPrivacyRequest(\n sombra,\n request,\n enricherId,\n index,\n );\n if (result) {\n successCount += 1;\n } else {\n skippedCount += 1;\n }\n } catch (err) {\n errorCount += 1;\n }\n },\n { concurrency },\n );\n\n logger.info(\n colors.green(\n `Successfully notified Transcend! \\n Success count: ${successCount}.`,\n ),\n );\n\n if (skippedCount > 0) {\n logger.info(colors.magenta(`Skipped count: ${skippedCount}.`));\n }\n\n if (errorCount > 0) {\n logger.info(colors.red(`Error Count: ${errorCount}.`));\n throw new Error(`Failed to enrich: ${errorCount} requests.`);\n }\n\n return activeResults.length;\n}\n"]}
|
|
@@ -1,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 _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var
|
|
2
|
-
`)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${t.timestampColum}" is present for all row`))}return t}async function Ie(a,t){let f=
|
|
3
|
-
`)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await
|
|
4
|
-
When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(S&&Re({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})&&!p){e.skippedUpdates[P]=w;return}if(S&&Fe({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})){e.pendingConflictUpdates[P]={row:w,record:S};return}e.pendingSafeUpdates[P]=w}),r[a]=e,await o.setValue(r,"fileMetadata");let C=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${a}" in ${(C-i)/1e3}s`))}var De=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]))}),Pr=n.record(n.string,De),et=n.type({name:n.string,isUniqueOnPreferenceStore:n.boolean}),$r=n.record(n.string,et),tt=n.intersection([n.type({columnToPurposeName:n.record(n.string,De),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})]),br=n.record(n.string,n.union([n.boolean,_privacytypes.PreferenceUpdateItem])),Cr=n.record(n.string,n.union([n.boolean,n.record(n.string,n.string)])),Tr=n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),Sr=n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),Mr=n.record(n.string,n.record(n.string,n.string)),Ve=n.type({fileMetadata:n.record(n.string,tt),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 Gr({auth:a,sombraAuth:t,receiptFilepath:f,file:u,partition:c,isSilent:d=!0,dryRun:p=!1,skipWorkflowTriggers:o=!1,skipConflictUpdates:i=!1,skipExistingRecordCheck:r=!1,attributes:s=[],transcendUrl:e,forceTriggerWorkflows:l=!1}){let y=
|
|
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 _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk55B57ZAYcjs = require('./chunk-55B57ZAY.cjs');var _chunkZUNVPK23cjs = require('./chunk-ZUNVPK23.cjs');var _chunkXXFLFF7Qcjs = require('./chunk-XXFLFF7Q.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 G = _interopRequireWildcard(_iots); var I = _interopRequireWildcard(_iots); var n = _interopRequireWildcard(_iots);var _typeutils = require('@transcend-io/type-utils');var ze=["ENOTFOUND","ECONNRESET","ETIMEDOUT","502 Bad Gateway","504 Gateway Time-out","Task timed out after","unknown request error"].map(a=>a.toLowerCase());async function D(a,{maxAttempts:t=3,baseDelayMs:f=250,isRetryable:u=(d,p)=>ze.some(o=>p.toLowerCase().includes(o)),onRetry:c}={}){let d=0;for(;;){d+=1;try{return await a()}catch(p){let o=_nullishCoalesce((p&&(_optionalChain([p, 'access', _2 => _2.response, 'optionalAccess', _3 => _3.body])||p.message)), () => (String(_nullishCoalesce(p, () => ("Unknown error")))));if(!(d<t&&u(p,o)))throw new Error(`Preference query failed after ${d} attempt(s): ${o}`);_optionalChain([c, 'optionalCall', _4 => _4(d,p,o)]);let r=f*2**(d-1),s=Math.floor(Math.random()*f),e=r+s;_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[retry] attempt ${d}/${t-1}; backing off ${e}ms: ${o}`)),await _chunk55B57ZAYcjs.Zf.call(void 0, e)}}}var _privacytypes = require('@transcend-io/privacy-types');var V=I.intersection([I.type({nodes:I.array(_privacytypes.PreferenceQueryResponseItem)}),I.partial({cursor:I.string})]);async function Se(a,{identifiers:t,partitionKey:f,skipLogging:u=!1,concurrency:c=40}){let d=[],p=_chunkXXFLFF7Qcjs.b.call(void 0, t,100),o=new Date().getTime(),i=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic);u||i.start(t.length,0);let r=0;await _bluebird.map.call(void 0, p,async l=>{let y=await D(()=>a.post(`v1/preferences/${f}/query`,{json:{filter:{identifiers:l},limit:l.length}}).json(),{onRetry:(h,C,w)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`[RETRY] group size=${l.length} partition=${f} attempt=${h}: ${w}`))}}),g=_typeutils.decodeCodec.call(void 0, V,y);d.push(...g.nodes),r+=l.length,i.update(r)},{concurrency:c}),i.stop();let e=new Date().getTime()-o;return u||_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Completed download in "${e/1e3}" seconds.`)),d}function J({row:a,columnToPurposeName:t,purposeSlugs:f,preferenceTopics:u}){let c={};return Object.entries(t).forEach(([d,{purpose:p,preference:o,valueMapping:i}])=>{if(!f.includes(p))throw new Error(`Invalid purpose slug: ${p}, expected: ${f.join(", ")}`);let r=a[d];if(o){let s=u.find(e=>e.slug===o&&e.purpose.trackingType===p);if(!s){let e=u.filter(l=>l.purpose.trackingType===p).map(l=>l.slug);throw new Error(`Invalid preference slug: ${o} for purpose: ${p}. Allowed preference slugs for purpose are: ${e.join(",")}`)}switch(c[p]||(c[p]={preferences:[]}),c[p].preferences||(c[p].preferences=[]),s.type){case _privacytypes.PreferenceTopicType.Boolean:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="boolean")throw new Error(`Invalid value for boolean preference: ${o}, expected boolean, got: ${r}`);c[p].preferences.push({topic:o,choice:{booleanValue:e}});break}case _privacytypes.PreferenceTopicType.Select:{let e=i[r];if(e===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(e==null)return;if(typeof e!="string")throw new Error(`Invalid value for select preference: ${o}, expected string, got: ${r}`);let l=e.trim()||null;if(l&&!s.preferenceOptionValues.map(({slug:y})=>y).includes(l))throw new Error(`Invalid value for select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:y})=>y).join(", ")}, got: ${r}`);c[p].preferences.push({topic:o,choice:{selectValue:l}});break}case _privacytypes.PreferenceTopicType.MultiSelect:{if(typeof r!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected string, got: ${r}`);let e=_chunk55B57ZAYcjs.pc.call(void 0, r).map(l=>{let y=i[l];if(y===void 0&&r!=="")throw new Error(`No preference mapping found for multi select token "${r}" in column "${d}" (purpose=${p}, preference=${o})`);if(y==null)return null;if(typeof y!="string")throw new Error(`Invalid value for multi select preference: ${o}, expected one of: ${s.preferenceOptionValues.map(({slug:g})=>g).join(", ")}, got: ${l}`);return y}).filter(l=>l!==null).sort((l,y)=>l.localeCompare(y));e.length>0&&c[p].preferences.push({topic:o,choice:{selectValues:e}});break}default:throw new Error(`Unknown preference type: ${s.type}`)}}else{let s=i[r];if(s===void 0&&r!=="")throw new Error(`No preference mapping found for value "${r}" in column "${d}" (purpose=${p}, preference=\u2205)`);if(s===null)return;c[p]?c[p].enabled=s===!0:c[p]={enabled:s===!0}}}),_typeutils.apply.call(void 0, c,(d,p)=>{if(typeof d.enabled!="boolean")throw new Error(`No mapping provided for purpose.enabled=true/false value: ${p}`);return{...d,enabled:d.enabled}})}var _inquirer = require('inquirer'); var _inquirer2 = _interopRequireDefault(_inquirer);var H="[NONE]";async function ke(a,t){let f=_chunkXXFLFF7Qcjs.j.call(void 0, a.map(c=>Object.keys(c)).flat()),u=_chunkXXFLFF7Qcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.timestampColum){let{timestampName:c}=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,H]}]);t.timestampColum=c}if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using timestamp column "${t.timestampColum}"`)),t.timestampColum!==H){let c=a.map((d,p)=>d[t.timestampColum]?null:[p]).filter(d=>!!d).flat();if(c.length>0)throw new Error(`The timestamp column "${t.timestampColum}" is missing a value for the following rows: ${c.join(`
|
|
2
|
+
`)}`);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The timestamp column "${t.timestampColum}" is present for all row`))}return t}async function Ie(a,t){let f=_chunkXXFLFF7Qcjs.j.call(void 0, a.map(o=>Object.keys(o)).flat()),u=_chunkXXFLFF7Qcjs.c.call(void 0, f,[...t.identifierColumn?[t.identifierColumn]:[],...Object.keys(t.columnToPurposeName)]);if(!t.identifierColumn){let{identifierName:o}=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(i=>i.toLowerCase().includes("email"))||u[0],choices:u}]);t.identifierColumn=o}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Using identifier column "${t.identifierColumn}"`));let c=a.map((o,i)=>o[t.identifierColumn]?null:[i]).filter(o=>!!o).flat();if(c.length>0){let o=`The identifier column "${t.identifierColumn}" is missing a value for the following rows: ${c.join(", ")}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunk55B57ZAYcjs.Tf.call(void 0, {message:"Would you like to skip rows missing an identifier?"}))throw new Error(o);let r=a.length;a=a.filter(s=>s[t.identifierColumn]),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Skipped ${r-a.length} rows missing an identifier`))}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`The identifier column "${t.identifierColumn}" is present for all rows`));let d=_chunkXXFLFF7Qcjs.d.call(void 0, a,t.identifierColumn),p=Object.entries(d).filter(([,o])=>o.length>1);if(p.length>0){let o=`The identifier column "${t.identifierColumn}" has duplicate values for the following rows: ${p.slice(0,10).map(([r,s])=>`${r} (${s.length})`).join(`
|
|
3
|
+
`)}`;if(_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(o)),!await _chunk55B57ZAYcjs.Tf.call(void 0, {message:"Would you like to automatically take the latest update?"}))throw new Error(o);a=Object.entries(d).map(([,r])=>r.sort((e,l)=>new Date(l[t.timestampColum]).getTime()-new Date(e[t.timestampColum]).getTime())[0]).filter(r=>r)}return{currentState:t,preferences:a}}async function xe(a,t,{purposeSlugs:f,preferenceTopics:u,forceTriggerWorkflows:c}){let d=_chunkXXFLFF7Qcjs.j.call(void 0, a.map(i=>Object.keys(i)).flat()),p=_chunkXXFLFF7Qcjs.c.call(void 0, d,[...t.identifierColumn?[t.identifierColumn]:[],...t.timestampColum?[t.timestampColum]:[]]);if(p.length===0){if(c)return t;throw new Error("No other columns to process")}let o=[...f,...u.map(i=>`${i.purpose.trackingType}->${i.slug}`)];return await _bluebird.mapSeries.call(void 0, p,async i=>{let r=_chunkXXFLFF7Qcjs.j.call(void 0, a.map(e=>e[i])),s=t.columnToPurposeName[i];if(s)_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Column "${i}" is associated with purpose "${s.purpose}"`));else{let{purposeName:e}=await _inquirer2.default.prompt([{name:"purposeName",message:`Choose the purpose that column ${i} is associated with`,type:"list",default:o.find(g=>g.startsWith(f[0])),choices:o}]),[l,y]=e.split("->");s={purpose:l,preference:y||null,valueMapping:{}}}await _bluebird.mapSeries.call(void 0, r,async e=>{if(s.valueMapping[e]!==void 0){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Value "${e}" is associated with purpose value "${s.valueMapping[e]}"`));return}if(s.preference===null){let{purposeValue:l}=await _inquirer2.default.prompt([{name:"purposeValue",message:`Choose the purpose value for value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=l}if(s.preference!==null){let l=u.find(g=>g.slug===s.preference);if(!l){_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Preference topic "${s.preference}" not found`));return}let y=l.preferenceOptionValues.map(({slug:g})=>g);if(l.type===_privacytypes.PreferenceTopicType.Boolean){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"confirm",default:e!=="false"}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.Select){let{preferenceValue:g}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${e}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(h=>h===e)}]);s.valueMapping[e]=g;return}if(l.type===_privacytypes.PreferenceTopicType.MultiSelect){let g=_chunk55B57ZAYcjs.pc.call(void 0, e);await _bluebird.mapSeries.call(void 0, g,async h=>{if(s.valueMapping[h]!==void 0)return;let{preferenceValue:C}=await _inquirer2.default.prompt([{name:"preferenceValue",message:`Choose the preference value for "${l.slug}" value "${h}" associated with purpose "${s.purpose}"`,type:"list",choices:y,default:y.find(w=>w===h)}]);s.valueMapping[h]=C});return}throw new Error(`Unknown preference topic type: ${l.type}`)}}),t.columnToPurposeName[i]=s}),t}function Re({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f}){return Object.entries(t).every(([u,{preferences:c=[],enabled:d}])=>{let p=a.purposes.find(i=>i.purpose===u);return!!p&&p.enabled===d?c.every(({topic:i,choice:r})=>p.preferences&&p.preferences.find(s=>{if(s.topic!==i)return!1;let e=f.find(l=>l.slug===i&&l.purpose.trackingType===u);if(!e)throw new Error(`Could not find preference topic for ${i}`);switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return s.choice.booleanValue===r.booleanValue;case _privacytypes.PreferenceTopicType.Select:return s.choice.selectValue===r.selectValue;case _privacytypes.PreferenceTopicType.MultiSelect:let l=(s.choice.selectValues||[]).sort(),y=(r.selectValues||[]).sort();return l.length===y.length&&l.every((g,h)=>g===y[h]);default:throw new Error(`Unknown preference topic type: ${e.type}`)}})):!1})}function Fe({currentConsentRecord:a,pendingUpdates:t,preferenceTopics:f,log:u}){return!!Object.entries(t).find(([c,{preferences:d=[],enabled:p}])=>{let o=a.purposes.find(i=>i.purpose===c);return o?o.enabled!==p?(u&&_chunkZUNVPK23cjs.a.warn(`Purpose ${c} enabled value conflict for user ${a.userId}. Pending Value: ${p}, Current Value: ${o.enabled}`),!0):!!d.find(({topic:i,choice:r})=>{let s=(o.preferences||[]).find(g=>g.topic===i);if(!s)return u&&_chunkZUNVPK23cjs.a.warn(`No existing preference found for topic ${i} in purpose ${c} for user ${a.userId}.`),!1;let e=f.find(g=>g.slug===i&&g.purpose.trackingType===c);if(!e)throw new Error(`Could not find preference topic for ${i}`);let l,y;switch(e.type){case _privacytypes.PreferenceTopicType.Boolean:return l=s.choice.booleanValue!==r.booleanValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} boolean value conflict for user ${a.userId}. Expected: ${r.booleanValue}, Found: ${s.choice.booleanValue}`),l;case _privacytypes.PreferenceTopicType.Select:return y=s.choice.selectValue!==r.selectValue,u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} select value conflict for user ${a.userId}. Expected: ${r.selectValue}, Found: ${s.choice.selectValue}`),y;case _privacytypes.PreferenceTopicType.MultiSelect:let g=(s.choice.selectValues||[]).sort(),h=(r.selectValues||[]).sort();return y=g.length!==h.length||!g.every((C,w)=>C===h[w]),u&&_chunkZUNVPK23cjs.a.warn(`Preference topic ${i} multi-select value conflict for user ${a.userId}. Expected: ${h.join(", ")}, Found: ${g.join(", ")}`),y;default:throw new Error(`Unknown preference topic type: ${e.type}`)}}):(u&&_chunkZUNVPK23cjs.a.warn(`No existing purpose found for ${c} in consent record for ${a.userId}.`),!1)})}async function ve({file:a,sombra:t,purposeSlugs:f,preferenceTopics:u,partitionKey:c,skipExistingRecordCheck:d,forceTriggerWorkflows:p},o){let i=new Date().getTime(),r=o.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Reading in file: "${a}"`));let s=_chunk55B57ZAYcjs.sc.call(void 0, a,G.record(G.string,G.string)),e={columnToPurposeName:{},pendingSafeUpdates:{},pendingConflictUpdates:{},skippedUpdates:{},...r[a]||{},lastFetchedAt:new Date().toISOString()};e=await ke(s,e),r[a]=e,await o.setValue(r,"fileMetadata");let l=await Ie(s,e);e=l.currentState,s=l.preferences,r[a]=e,await o.setValue(r,"fileMetadata"),e=await xe(s,e,{preferenceTopics:u,purposeSlugs:f,forceTriggerWorkflows:p}),r[a]=e,await o.setValue(r,"fileMetadata");let y=s.map(w=>w[e.identifierColumn]),g=d?[]:await Se(t,{identifiers:y.map(w=>({value:w})),partitionKey:c}),h=_chunkXXFLFF7Qcjs.e.call(void 0, g,"userId");e.pendingConflictUpdates={},e.pendingSafeUpdates={},e.skippedUpdates={},s.forEach(w=>{let P=w[e.identifierColumn],b=J({row:w,columnToPurposeName:e.columnToPurposeName,preferenceTopics:u,purposeSlugs:f}),S=h[P];if(p&&!S)throw new Error(`No existing consent record found for user with id: ${P}.
|
|
4
|
+
When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`);if(S&&Re({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})&&!p){e.skippedUpdates[P]=w;return}if(S&&Fe({currentConsentRecord:S,pendingUpdates:b,preferenceTopics:u})){e.pendingConflictUpdates[P]={row:w,record:S};return}e.pendingSafeUpdates[P]=w}),r[a]=e,await o.setValue(r,"fileMetadata");let C=new Date().getTime();_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully pre-processed file: "${a}" in ${(C-i)/1e3}s`))}var De=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]))}),Pr=n.record(n.string,De),et=n.type({name:n.string,isUniqueOnPreferenceStore:n.boolean}),$r=n.record(n.string,et),tt=n.intersection([n.type({columnToPurposeName:n.record(n.string,De),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})]),br=n.record(n.string,n.union([n.boolean,_privacytypes.PreferenceUpdateItem])),Cr=n.record(n.string,n.union([n.boolean,n.record(n.string,n.string)])),Tr=n.record(n.string,n.type({uploadedAt:n.string,error:n.string,update:_privacytypes.PreferenceUpdateItem})),Sr=n.record(n.string,n.type({record:_privacytypes.PreferenceQueryResponseItem,row:n.record(n.string,n.string)})),Mr=n.record(n.string,n.record(n.string,n.string)),Ve=n.type({fileMetadata:n.record(n.string,tt),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 Gr({auth:a,sombraAuth:t,receiptFilepath:f,file:u,partition:c,isSilent:d=!0,dryRun:p=!1,skipWorkflowTriggers:o=!1,skipConflictUpdates:i=!1,skipExistingRecordCheck:r=!1,attributes:s=[],transcendUrl:e,forceTriggerWorkflows:l=!1}){let y=_chunk55B57ZAYcjs.rc.call(void 0, s),g=new (0, _persistedstate.PersistedState)(f,Ve,{fileMetadata:{},failingUpdates:{},pendingUpdates:{}}),h=g.getValue("failingUpdates"),C=g.getValue("pendingUpdates"),w=g.getValue("fileMetadata");_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Restored cache, there are:
|
|
5
5
|
${Object.values(h).length} failing requests to be retried
|
|
6
6
|
${Object.values(C).length} pending requests to be processed
|
|
7
7
|
The following files are stored in cache and will be used:
|
|
8
8
|
${Object.keys(w).map(M=>M).join(`
|
|
9
9
|
`)}
|
|
10
10
|
The following file will be processed: ${u}
|
|
11
|
-
`));let P=_chunkHTS7K7QDcjs.xc.call(void 0, e,a),[b,S,fe]=await Promise.all([_chunkHTS7K7QDcjs.yc.call(void 0, e,a,t),l?Promise.resolve([]):_chunkHTS7K7QDcjs.gd.call(void 0, P),l?Promise.resolve([]):_chunkHTS7K7QDcjs.cd.call(void 0, P)]);await ve({file:u,purposeSlugs:S.map(M=>M.trackingType),preferenceTopics:fe,sombra:b,partitionKey:c,skipExistingRecordCheck:r,forceTriggerWorkflows:l},g);let Q={};w=g.getValue("fileMetadata");let F=w[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...F.pendingSafeUpdates,...i?{}:_typeutils.apply.call(void 0, F.pendingConflictUpdates,({row:M})=>M)}).forEach(([M,k])=>{let _=F.timestampColum===H?new Date:new Date(k[F.timestampColum]),O=J({row:k,columnToPurposeName:F.columnToPurposeName,preferenceTopics:fe,purposeSlugs:S.map(N=>N.trackingType)});Q[M]={userId:M,partition:c,timestamp:_.toISOString(),purposes:Object.entries(O).map(([N,_e])=>({..._e,purpose:N,workflowSettings:{attributes:y,isSilent:d,skipWorkflowTrigger:o}}))}}),await g.setValue(Q,"pendingUpdates"),await g.setValue({},"failingUpdates"),p){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(Q).length} pending updates. Check file: ${f}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(Q).length} preferences to partition: ${c}`));let Ge=new Date().getTime(),ee=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),me=0,te=Object.entries(Q),qe=_chunkOMVVROKBcjs.b.call(void 0, te,o?100:10);ee.start(te.length,0),await _bluebird.map.call(void 0, qe,async M=>{try{await b.put("v1/preferences",{json:{records:M.map(([,k])=>k),skipWorkflowTriggers:o,forceTriggerWorkflows:l}}).json()}catch(k){try{let O=JSON.parse(_optionalChain([k, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");O.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${O.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${M.length} user preferences to partition ${c}: ${_optionalChain([k, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([k, 'optionalAccess', _9 => _9.message])}`));let _=g.getValue("failingUpdates");M.forEach(([O,N])=>{_[O]={uploadedAt:new Date().toISOString(),update:N,error:_optionalChain([k, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([k, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await g.setValue(_,"failingUpdates")}me+=M.length,ee.update(me)},{concurrency:40}),ee.stop();let Le=new Date().getTime()-Ge;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${te.length} user preferences to partition ${c} in "${Le/1e3}" seconds!`))}function Lr({identifiers:a=[],purposes:t=[],metadata:f=[],consentManagement:u={},system:c={decryptionStatus:"DECRYPTED"},...d}){let p={...d,...c,...u};if(Array.isArray(a)){let o=new Map;for(let{name:i,value:r}of a)o.has(i)||o.set(i,new Set),r&&o.get(i).add(r);for(let[i,r]of o.entries())p[i]=Array.from(r).join(",")}if(Array.isArray(f)&&(p.metadata=JSON.stringify(f.reduce((o,{key:i,value:r})=>(o[i]=r,o),{}))),Array.isArray(t)){for(let{purpose:o,preferences:i,enabled:r}of t)if(p[o]=!!r,Array.isArray(i))for(let{topic:s,choice:e}of i){let l=`${o}_${s}`,y=null;typeof e.booleanValue=="boolean"?y=e.booleanValue:e.selectValue?y=e.selectValue:Array.isArray(e.selectValues)?y=e.selectValues.filter(h=>h.length>0).join(","):y=null,p[l]=y}}return p}async function*X(a,t,f,u){let c;for(;;){let d={limit:u};f&&Object.keys(f).length&&(d.filter=f),c&&(d.cursor=c);let p=await D(()=>a.post(`v1/preferences/${t}/query`,{json:d}).json(),{onRetry:(r,s,e)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${r} for fetchConsentPreferences due to error: ${e}`))}}),{nodes:o,cursor:i}=_typeutils.decodeCodec.call(void 0, V,p);if(!_optionalChain([o, 'optionalAccess', _13 => _13.length])||(yield o,!i))break;c=i}}function Z(a){return!!a.timestampAfter||!!a.timestampBefore?"timestamp":"updated"}function E(a,t){return a==="timestamp"?new Date(t.timestamp):_optionalChain([t, 'access', _14 => _14.system, 'optionalAccess', _15 => _15.updatedAt])?new Date(t.system.updatedAt):new Date}function Ae(a,t){if(a==="timestamp")return{after:t.timestampAfter?new Date(t.timestampAfter):void 0,before:t.timestampBefore?new Date(t.timestampBefore):void 0};let f=_nullishCoalesce(t.system, () => ({}));return{after:f.updatedAfter?new Date(f.updatedAfter):void 0,before:f.updatedBefore?new Date(f.updatedBefore):void 0}}function q(a,t,f){return a==="timestamp"?{...t,timestampBefore:_nullishCoalesce(f, () => (t.timestampBefore))}:{...t,system:{...t.system||{},...f?{updatedBefore:f}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function L(a,t,f){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Single-record probe with filter: ${JSON.stringify(f)}`));let c=await X(a,t,f,1).next();if(c.done||!c.value||c.value.length===0)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Probe result: no record")),null;let d=c.value[0];return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Probe result: found record at ${E(Z(f),d).toISOString()}`)),d}async function Qe(a,t){let{partition:f,mode:u,baseFilter:c,maxLookbackDays:d=3650}=t,p=await L(a,f,q(u,c));if(!p)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found; defaulting earliest day to today.")),_chunkHTS7K7QDcjs.jg.call(void 0, new Date);let o=E(u,p);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest instant: ${o.toISOString()}`));let i=[1,7,30],r=0,s=i[0]*864e5,e=o,l=null;for(;;){let w=r<i.length?new Date(o.getTime()-i[r]*864e5):new Date(o.getTime()-s);if((_chunkHTS7K7QDcjs.jg.call(void 0, new Date).getTime()-_chunkHTS7K7QDcjs.jg.call(void 0, w).getTime())/864e5>d){_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Exponential jump exceeded maxLookbackDays=${d}. Using current bounds.`)),l=w;break}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Probing before=${w.toISOString()} (jump step ${r<i.length?`${i[r]}d`:`${Math.round(s/864e5)}d`})\u2026`));let b=await L(a,f,q(u,c,w.toISOString()));if(b){e=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Found older record at ${e.toISOString()} \u2014 continue jumping back.`)),r<i.length-1?(r+=1,s=i[r]*864e5):r===i.length-1?(r+=1,s=i[i.length-1]*2*864e5):s*=2;continue}l=w,_chunkZUNVPK23cjs.a.info(_colors2.default.green(`No record before ${w.toISOString()} \u2014 established empty lower bound.`));break}l||(l=new Date(e.getTime()-864e5));let y=l,g=e,h=Math.max(864e5,Math.floor((g.getTime()-y.getTime())/64));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Exponential forward-from-empty start: empty=${y.toISOString()} found=${g.toISOString()} step=${Math.round(h/864e5)}d`));for(let w=0;w<8;w+=1){let P=new Date(y.getTime()+h);if(P.getTime()>=g.getTime())break;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Forward gallop probe before=${P.toISOString()}\u2026`));let b=await L(a,f,q(u,c,P.toISOString()));if(b?(g=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Gallop hit at ${g.toISOString()} \u2014 tightening found bound. Next step halves.`)),h=Math.max(864e5,Math.floor(h/2))):(y.setTime(P.getTime()),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Gallop miss \u2014 advancing empty bound to ${y.toISOString()}. Next step doubles.`)),h=Math.min(g.getTime()-y.getTime(),h*2),h<864e5&&(h=864e5)),g.getTime()-y.getTime()<=864e5)break}for(;g.getTime()-y.getTime()>864e5;){let w=new Date(y.getTime()+Math.floor((g.getTime()-y.getTime())/2));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Binary probe before=${w.toISOString()}\u2026`));let P=await L(a,f,q(u,c,w.toISOString()));if(P){let b=E(u,P);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Binary probe found record at ${b.toISOString()}.`)),g=b}else _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Binary probe found no record.")),y=w}let C=_chunkHTS7K7QDcjs.jg.call(void 0, g);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Earliest day (UTC) resolved to ${C.toISOString()} (instant \u2248 ${g.toISOString()}).`)),C}async function Ne(a,t){let{partition:f,mode:u,baseFilter:c}=t;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Latest-day discovery: probing newest record\u2026"));let d=await L(a,f,q(u,c));if(!d)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found at all; defaulting latest day to today.")),_chunkHTS7K7QDcjs.jg.call(void 0, new Date);let p=E(u,d);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest record instant is ${p.toISOString()}.`));let o=_chunkHTS7K7QDcjs.jg.call(void 0, p);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Latest day (UTC) resolved to ${o.toISOString()} from instant ${p.toISOString()}.`)),o}function je(a,t,f,u=5e3){let c=Math.max(0,f.getTime()-t.getTime());if(c===0)return[];let d=new Date(Math.floor(t.getTime()/3e5)*3e5),p=Math.ceil(c/Math.max(1,u)),o=Math.max(3e5,p),i=Math.ceil((f.getTime()-d.getTime())/o),r=[];for(let s=0;s<i;s+=1){let e=d.getTime()+s*o,y=Math.min(f.getTime(),e+o)-1,g=Math.max(e,y),h=new Date(e).toISOString(),C=new Date(g).toISOString();a==="timestamp"?r.push({timestampAfter:h,timestampBefore:C}):r.push({system:{updatedAfter:h,updatedBefore:C}})}return r}function pt(a,t,f){return a==="timestamp"?{...t,timestampAfter:_nullishCoalesce(f.timestampAfter, () => (t.timestampAfter)),timestampBefore:_nullishCoalesce(f.timestampBefore, () => (t.timestampBefore)),system:void 0}:{...t,system:{...t.system||{},..._optionalChain([f, 'access', _16 => _16.system, 'optionalAccess', _17 => _17.updatedAfter])?{updatedAfter:f.system.updatedAfter}:{},..._optionalChain([f, 'access', _18 => _18.system, 'optionalAccess', _19 => _19.updatedBefore])?{updatedBefore:f.system.updatedBefore}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function $o(a,{partition:t,filterBy:f={},limit:u=50,windowConcurrency:c=25,maxChunks:d=5e3,maxLookbackDays:p=3650,onItems:o}){let i=Z(f);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences in chunks by ${i==="timestamp"?"timestamp":"system.updatedAt"}...`));let{after:r,before:s}=Ae(i,f);if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Initial bounds: after=${_nullishCoalesce(_optionalChain([r, 'optionalAccess', _20 => _20.toISOString, 'call', _21 => _21()]), () => ("undefined"))} before=${_nullishCoalesce(_optionalChain([s, 'optionalAccess', _22 => _22.toISOString, 'call', _23 => _23()]), () => ("undefined"))}`)),(!r||!s)&&(r||(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering earliest day with data for partition ${t}...`)),r=await Qe(a,{partition:t,mode:i,baseFilter:f,maxLookbackDays:p}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered earliest day with data: ${r.toISOString()}`))),!s)){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering latest day with data for partition ${t}...`));let P=await Ne(a,{partition:t,mode:i,baseFilter:f,earliest:r});s=_chunkHTS7K7QDcjs.mg.call(void 0, P,1),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered latest day with data: ${P.toISOString()}`))}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Final bounds (UTC): after=${r.toISOString()} before=${s.toISOString()}`));let e=je(i,r,s,d);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences from partition ${t} in ${e.length} chunks...`));let l=new _cliprogress2.default.SingleBar({format:"Downloading [{bar}] {percentage}% | chunks {value}/{total} | fetched {fetched}"},_cliprogress2.default.Presets.shades_classic),y=0,g=0;l.start(e.length,0,{fetched:g});let h=Date.now(),C=_chunkHTS7K7QDcjs.ig.call(void 0, u),w=[];return await _bluebird.map.call(void 0, e.map((P,b)=>({windowFilter:P,idx:b})),async({windowFilter:P})=>{let b=pt(i,f,P);for await(let S of X(a,t,b,C))g+=S.length,l.update(y,{fetched:g}),o?await o(S):w.push(...S);y+=1,l.update(y,{fetched:g})},{concurrency:Math.max(1,c)}),l.update(y,{fetched:g}),l.stop(),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Fetched ${g} consent preference records from partition ${t} in ${(Date.now()-h)/1e3}s.`)),o?[]:w}async function xo(a,{partition:t,filterBy:f={},limit:u=50,onItems:c}){let d=[],p,o=f&&(Object.keys(f).length>0||f.system&&Object.keys(f.system).length>0),i=Math.max(1,Math.min(50,_nullishCoalesce(u, () => (50))));for(;;){let r={limit:i};o&&(r.filter=f),p&&(r.cursor=p);let s=await D(()=>a.post(`v1/preferences/${t}/query`,{json:r}).json(),{onRetry:(y,g,h)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${y} for fetchConsentPreferences due to error: ${h}`))}}),{nodes:e,cursor:l}=_typeutils.decodeCodec.call(void 0, V,s);if(!e||e.length===0||(c?await c(e):d.push(...e),!l))break;p=l}return c?[]:d}exports.a = Gr; exports.b = Lr; exports.c = $o; exports.d = xo;
|
|
12
|
-
//# sourceMappingURL=chunk-
|
|
11
|
+
`));let P=_chunk55B57ZAYcjs.xc.call(void 0, e,a),[b,S,fe]=await Promise.all([_chunk55B57ZAYcjs.yc.call(void 0, e,a,t),l?Promise.resolve([]):_chunk55B57ZAYcjs.gd.call(void 0, P),l?Promise.resolve([]):_chunk55B57ZAYcjs.cd.call(void 0, P)]);await ve({file:u,purposeSlugs:S.map(M=>M.trackingType),preferenceTopics:fe,sombra:b,partitionKey:c,skipExistingRecordCheck:r,forceTriggerWorkflows:l},g);let Q={};w=g.getValue("fileMetadata");let F=w[u];if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingSafeUpdates).length} safe updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.pendingConflictUpdates).length} conflict updates in ${u}`)),_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Found ${Object.entries(F.skippedUpdates).length} skipped updates in ${u}`)),Object.entries({...F.pendingSafeUpdates,...i?{}:_typeutils.apply.call(void 0, F.pendingConflictUpdates,({row:M})=>M)}).forEach(([M,k])=>{let _=F.timestampColum===H?new Date:new Date(k[F.timestampColum]),O=J({row:k,columnToPurposeName:F.columnToPurposeName,preferenceTopics:fe,purposeSlugs:S.map(N=>N.trackingType)});Q[M]={userId:M,partition:c,timestamp:_.toISOString(),purposes:Object.entries(O).map(([N,_e])=>({..._e,purpose:N,workflowSettings:{attributes:y,isSilent:d,skipWorkflowTrigger:o}}))}}),await g.setValue(Q,"pendingUpdates"),await g.setValue({},"failingUpdates"),p){_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Dry run complete, exiting. ${Object.values(Q).length} pending updates. Check file: ${f}`));return}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Uploading ${Object.values(Q).length} preferences to partition: ${c}`));let Ge=new Date().getTime(),ee=new _cliprogress2.default.SingleBar({},_cliprogress2.default.Presets.shades_classic),me=0,te=Object.entries(Q),qe=_chunkXXFLFF7Qcjs.b.call(void 0, te,o?100:10);ee.start(te.length,0),await _bluebird.map.call(void 0, qe,async M=>{try{await b.put("v1/preferences",{json:{records:M.map(([,k])=>k),skipWorkflowTriggers:o,forceTriggerWorkflows:l}}).json()}catch(k){try{let O=JSON.parse(_optionalChain([k, 'optionalAccess', _5 => _5.response, 'optionalAccess', _6 => _6.body])||"{}");O.error&&_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Error: ${O.error}`))}catch (e2){}_chunkZUNVPK23cjs.a.error(_colors2.default.red(`Failed to upload ${M.length} user preferences to partition ${c}: ${_optionalChain([k, 'optionalAccess', _7 => _7.response, 'optionalAccess', _8 => _8.body])||_optionalChain([k, 'optionalAccess', _9 => _9.message])}`));let _=g.getValue("failingUpdates");M.forEach(([O,N])=>{_[O]={uploadedAt:new Date().toISOString(),update:N,error:_optionalChain([k, 'optionalAccess', _10 => _10.response, 'optionalAccess', _11 => _11.body])||_optionalChain([k, 'optionalAccess', _12 => _12.message])||"Unknown error"}}),await g.setValue(_,"failingUpdates")}me+=M.length,ee.update(me)},{concurrency:40}),ee.stop();let Le=new Date().getTime()-Ge;_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Successfully uploaded ${te.length} user preferences to partition ${c} in "${Le/1e3}" seconds!`))}function Lr({identifiers:a=[],purposes:t=[],metadata:f=[],consentManagement:u={},system:c={decryptionStatus:"DECRYPTED"},...d}){let p={...d,...c,...u};if(Array.isArray(a)){let o=new Map;for(let{name:i,value:r}of a)o.has(i)||o.set(i,new Set),r&&o.get(i).add(r);for(let[i,r]of o.entries())p[i]=Array.from(r).join(",")}if(Array.isArray(f)&&(p.metadata=JSON.stringify(f.reduce((o,{key:i,value:r})=>(o[i]=r,o),{}))),Array.isArray(t)){for(let{purpose:o,preferences:i,enabled:r}of t)if(p[o]=!!r,Array.isArray(i))for(let{topic:s,choice:e}of i){let l=`${o}_${s}`,y=null;typeof e.booleanValue=="boolean"?y=e.booleanValue:e.selectValue?y=e.selectValue:Array.isArray(e.selectValues)?y=e.selectValues.filter(h=>h.length>0).join(","):y=null,p[l]=y}}return p}async function*X(a,t,f,u){let c;for(;;){let d={limit:u};f&&Object.keys(f).length&&(d.filter=f),c&&(d.cursor=c);let p=await D(()=>a.post(`v1/preferences/${t}/query`,{json:d}).json(),{onRetry:(r,s,e)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${r} for fetchConsentPreferences due to error: ${e}`))}}),{nodes:o,cursor:i}=_typeutils.decodeCodec.call(void 0, V,p);if(!_optionalChain([o, 'optionalAccess', _13 => _13.length])||(yield o,!i))break;c=i}}function Z(a){return!!a.timestampAfter||!!a.timestampBefore?"timestamp":"updated"}function E(a,t){return a==="timestamp"?new Date(t.timestamp):_optionalChain([t, 'access', _14 => _14.system, 'optionalAccess', _15 => _15.updatedAt])?new Date(t.system.updatedAt):new Date}function Ae(a,t){if(a==="timestamp")return{after:t.timestampAfter?new Date(t.timestampAfter):void 0,before:t.timestampBefore?new Date(t.timestampBefore):void 0};let f=_nullishCoalesce(t.system, () => ({}));return{after:f.updatedAfter?new Date(f.updatedAfter):void 0,before:f.updatedBefore?new Date(f.updatedBefore):void 0}}function q(a,t,f){return a==="timestamp"?{...t,timestampBefore:_nullishCoalesce(f, () => (t.timestampBefore))}:{...t,system:{...t.system||{},...f?{updatedBefore:f}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function L(a,t,f){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Single-record probe with filter: ${JSON.stringify(f)}`));let c=await X(a,t,f,1).next();if(c.done||!c.value||c.value.length===0)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Probe result: no record")),null;let d=c.value[0];return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Probe result: found record at ${E(Z(f),d).toISOString()}`)),d}async function Qe(a,t){let{partition:f,mode:u,baseFilter:c,maxLookbackDays:d=3650}=t,p=await L(a,f,q(u,c));if(!p)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found; defaulting earliest day to today.")),_chunk55B57ZAYcjs.jg.call(void 0, new Date);let o=E(u,p);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest instant: ${o.toISOString()}`));let i=[1,7,30],r=0,s=i[0]*864e5,e=o,l=null;for(;;){let w=r<i.length?new Date(o.getTime()-i[r]*864e5):new Date(o.getTime()-s);if((_chunk55B57ZAYcjs.jg.call(void 0, new Date).getTime()-_chunk55B57ZAYcjs.jg.call(void 0, w).getTime())/864e5>d){_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Exponential jump exceeded maxLookbackDays=${d}. Using current bounds.`)),l=w;break}_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Probing before=${w.toISOString()} (jump step ${r<i.length?`${i[r]}d`:`${Math.round(s/864e5)}d`})\u2026`));let b=await L(a,f,q(u,c,w.toISOString()));if(b){e=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Found older record at ${e.toISOString()} \u2014 continue jumping back.`)),r<i.length-1?(r+=1,s=i[r]*864e5):r===i.length-1?(r+=1,s=i[i.length-1]*2*864e5):s*=2;continue}l=w,_chunkZUNVPK23cjs.a.info(_colors2.default.green(`No record before ${w.toISOString()} \u2014 established empty lower bound.`));break}l||(l=new Date(e.getTime()-864e5));let y=l,g=e,h=Math.max(864e5,Math.floor((g.getTime()-y.getTime())/64));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Exponential forward-from-empty start: empty=${y.toISOString()} found=${g.toISOString()} step=${Math.round(h/864e5)}d`));for(let w=0;w<8;w+=1){let P=new Date(y.getTime()+h);if(P.getTime()>=g.getTime())break;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Forward gallop probe before=${P.toISOString()}\u2026`));let b=await L(a,f,q(u,c,P.toISOString()));if(b?(g=E(u,b),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Gallop hit at ${g.toISOString()} \u2014 tightening found bound. Next step halves.`)),h=Math.max(864e5,Math.floor(h/2))):(y.setTime(P.getTime()),_chunkZUNVPK23cjs.a.info(_colors2.default.yellow(`Gallop miss \u2014 advancing empty bound to ${y.toISOString()}. Next step doubles.`)),h=Math.min(g.getTime()-y.getTime(),h*2),h<864e5&&(h=864e5)),g.getTime()-y.getTime()<=864e5)break}for(;g.getTime()-y.getTime()>864e5;){let w=new Date(y.getTime()+Math.floor((g.getTime()-y.getTime())/2));_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Binary probe before=${w.toISOString()}\u2026`));let P=await L(a,f,q(u,c,w.toISOString()));if(P){let b=E(u,P);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Binary probe found record at ${b.toISOString()}.`)),g=b}else _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("Binary probe found no record.")),y=w}let C=_chunk55B57ZAYcjs.jg.call(void 0, g);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Earliest day (UTC) resolved to ${C.toISOString()} (instant \u2248 ${g.toISOString()}).`)),C}async function Ne(a,t){let{partition:f,mode:u,baseFilter:c}=t;_chunkZUNVPK23cjs.a.info(_colors2.default.magenta("Latest-day discovery: probing newest record\u2026"));let d=await L(a,f,q(u,c));if(!d)return _chunkZUNVPK23cjs.a.info(_colors2.default.yellow("No records found at all; defaulting latest day to today.")),_chunk55B57ZAYcjs.jg.call(void 0, new Date);let p=E(u,d);_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Newest record instant is ${p.toISOString()}.`));let o=_chunk55B57ZAYcjs.jg.call(void 0, p);return _chunkZUNVPK23cjs.a.info(_colors2.default.green(`Latest day (UTC) resolved to ${o.toISOString()} from instant ${p.toISOString()}.`)),o}function je(a,t,f,u=5e3){let c=Math.max(0,f.getTime()-t.getTime());if(c===0)return[];let d=new Date(Math.floor(t.getTime()/3e5)*3e5),p=Math.ceil(c/Math.max(1,u)),o=Math.max(3e5,p),i=Math.ceil((f.getTime()-d.getTime())/o),r=[];for(let s=0;s<i;s+=1){let e=d.getTime()+s*o,y=Math.min(f.getTime(),e+o)-1,g=Math.max(e,y),h=new Date(e).toISOString(),C=new Date(g).toISOString();a==="timestamp"?r.push({timestampAfter:h,timestampBefore:C}):r.push({system:{updatedAfter:h,updatedBefore:C}})}return r}function pt(a,t,f){return a==="timestamp"?{...t,timestampAfter:_nullishCoalesce(f.timestampAfter, () => (t.timestampAfter)),timestampBefore:_nullishCoalesce(f.timestampBefore, () => (t.timestampBefore)),system:void 0}:{...t,system:{...t.system||{},..._optionalChain([f, 'access', _16 => _16.system, 'optionalAccess', _17 => _17.updatedAfter])?{updatedAfter:f.system.updatedAfter}:{},..._optionalChain([f, 'access', _18 => _18.system, 'optionalAccess', _19 => _19.updatedBefore])?{updatedBefore:f.system.updatedBefore}:{}},timestampAfter:void 0,timestampBefore:void 0}}async function $o(a,{partition:t,filterBy:f={},limit:u=50,windowConcurrency:c=25,maxChunks:d=5e3,maxLookbackDays:p=3650,onItems:o}){let i=Z(f);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences in chunks by ${i==="timestamp"?"timestamp":"system.updatedAt"}...`));let{after:r,before:s}=Ae(i,f);if(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Initial bounds: after=${_nullishCoalesce(_optionalChain([r, 'optionalAccess', _20 => _20.toISOString, 'call', _21 => _21()]), () => ("undefined"))} before=${_nullishCoalesce(_optionalChain([s, 'optionalAccess', _22 => _22.toISOString, 'call', _23 => _23()]), () => ("undefined"))}`)),(!r||!s)&&(r||(_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering earliest day with data for partition ${t}...`)),r=await Qe(a,{partition:t,mode:i,baseFilter:f,maxLookbackDays:p}),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered earliest day with data: ${r.toISOString()}`))),!s)){_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Discovering latest day with data for partition ${t}...`));let P=await Ne(a,{partition:t,mode:i,baseFilter:f,earliest:r});s=_chunk55B57ZAYcjs.mg.call(void 0, P,1),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Discovered latest day with data: ${P.toISOString()}`))}_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Final bounds (UTC): after=${r.toISOString()} before=${s.toISOString()}`));let e=je(i,r,s,d);_chunkZUNVPK23cjs.a.info(_colors2.default.magenta(`Fetching consent preferences from partition ${t} in ${e.length} chunks...`));let l=new _cliprogress2.default.SingleBar({format:"Downloading [{bar}] {percentage}% | chunks {value}/{total} | fetched {fetched}"},_cliprogress2.default.Presets.shades_classic),y=0,g=0;l.start(e.length,0,{fetched:g});let h=Date.now(),C=_chunk55B57ZAYcjs.ig.call(void 0, u),w=[];return await _bluebird.map.call(void 0, e.map((P,b)=>({windowFilter:P,idx:b})),async({windowFilter:P})=>{let b=pt(i,f,P);for await(let S of X(a,t,b,C))g+=S.length,l.update(y,{fetched:g}),o?await o(S):w.push(...S);y+=1,l.update(y,{fetched:g})},{concurrency:Math.max(1,c)}),l.update(y,{fetched:g}),l.stop(),_chunkZUNVPK23cjs.a.info(_colors2.default.green(`Fetched ${g} consent preference records from partition ${t} in ${(Date.now()-h)/1e3}s.`)),o?[]:w}async function xo(a,{partition:t,filterBy:f={},limit:u=50,onItems:c}){let d=[],p,o=f&&(Object.keys(f).length>0||f.system&&Object.keys(f.system).length>0),i=Math.max(1,Math.min(50,_nullishCoalesce(u, () => (50))));for(;;){let r={limit:i};o&&(r.filter=f),p&&(r.cursor=p);let s=await D(()=>a.post(`v1/preferences/${t}/query`,{json:r}).json(),{onRetry:(y,g,h)=>{_chunkZUNVPK23cjs.a.warn(_colors2.default.yellow(`Retry attempt ${y} for fetchConsentPreferences due to error: ${h}`))}}),{nodes:e,cursor:l}=_typeutils.decodeCodec.call(void 0, V,s);if(!e||e.length===0||(c?await c(e):d.push(...e),!l))break;p=l}return c?[]:d}exports.a = Gr; exports.b = Lr; exports.c = $o; exports.d = xo;
|
|
12
|
+
//# sourceMappingURL=chunk-HCEZRZHV.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-UXFL56TL.cjs","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/withPreferenceQueryRetry.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/codecs.ts"],"names":["RETRY_PREFERENCE_MSGS","s","withPreferenceQueryRetry","fn","maxAttempts","baseDelayMs","isRetryable","_err","msg","m","onRetry","attempt","err"],"mappings":"AAAA,2lCAA2J,wDAAyC,wDAAuE,gFCQxP,oCACC,qGAGI,+DAEO,qJCXZ,qDCES,ICGfA,EAAAA,CAAkC,CAC7C,WAAA,CACA,YAAA,CACA,WAAA,CACA,iBAAA,CACA,sBAAA,CACA,sBAAA,CACA,uBACF,CAAA,CAAE,GAAA,CAAKC,CAAAA,EAAMA,CAAAA,CAAE,WAAA,CAAY,CAAC,CAAA,CAwB5B,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,CAACC,CAAAA,CAAMC,CAAAA,CAAAA,EACnBR,EAAAA,CAAsB,IAAA,CAAMS,CAAAA,EAAMD,CAAAA,CAAI,WAAA,CAAY,CAAA,CAAE,QAAA,CAASC,CAAC,CAAC,CAAA,CACjE,OAAA,CAAAC,CACF,CAAA,CAAkB,CAAC,CAAA,CACP,CACZ,IAAIC,CAAAA,CAAU,CAAA,CAEd,GAAA,CAAA,CAAA,CAAA,CAAa,CACXA,CAAAA,EAAW,CAAA,CACX,GAAI,CACF,OAAO,MAAMR,CAAAA,CAAG,CAElB,CAAA,KAAA,CAASS,CAAAA,CAAU,CACjB,IAAMJ,CAAAA,kBAAAA,CACHI,CAAAA,EAAAA,iBAAQA,CAAAA,qBAAI,QAAA,6BAAU,MAAA,EAAQA,CAAAA,CAAI,OAAA,CAAA,CAAA,SACnC,MAAA,kBAAOA,CAAAA,SAAO,iBAAe,GAAA,CAE/B,EAAA,CAAI,CAAA,CADcD,CAAAA,CAAUP,CAAAA,EAAeE,CAAAA,CAAYM,CAAAA,CAAKJ,CAAG,CAAA,CAAA,CAE7D,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiCG,CAAO,CAAA,aAAA,EAAgBH,CAAG,CAAA,CAAA;ACiC/D;ACnBU;ACyBD,oGAAA;ANbP;AAGA;AAAA;AAKQ;AAAK;AACgC,sCAAA;AA+FY","file":"/home/runner/work/cli/cli/dist/chunk-UXFL56TL.cjs","sourcesContent":[null,"import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from 'bluebird';\nimport { chunk } from 'lodash-es';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${\n Object.values(pendingUpdates).length\n } preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Wheather to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(\n preferences,\n currentState,\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(\n preferences,\n currentState,\n );\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}. \n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport { withPreferenceQueryRetry } from './withPreferenceQueryRetry';\nimport { ConsentPreferenceResponse } from './types';\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n concurrency = 40,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n /** Concurrency for requests (default 40) */\n concurrency?: number;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n const rawResult = await withPreferenceQueryRetry(\n () =>\n sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: { identifiers: group },\n limit: group.length,\n },\n })\n .json(),\n {\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(\n `[RETRY] group size=${group.length} partition=${partitionKey} attempt=${attempt}: ${msg}`,\n ),\n );\n },\n },\n );\n\n const result = decodeCodec(ConsentPreferenceResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n },\n {\n concurrency,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import colors from 'colors';\nimport { logger } from '../../logger';\nimport { sleepPromise } from '../helpers';\n\n/**\n * Transient network / platform errors that merit a retry.\n * Keep this list short and specific to avoid masking real failures.\n */\nexport const RETRY_PREFERENCE_MSGS: string[] = [\n 'ENOTFOUND',\n 'ECONNRESET',\n 'ETIMEDOUT',\n '502 Bad Gateway',\n '504 Gateway Time-out',\n 'Task timed out after',\n 'unknown request error',\n].map((s) => s.toLowerCase());\n\n/**\n * Options for retrying preference queries.\n */\nexport type RetryOptions = {\n /** Max attempts including the first try (default 3) */\n maxAttempts?: number;\n /** Initial backoff in ms (default 250) */\n baseDelayMs?: number;\n /** Optional custom predicate to decide if an error is retryable */\n isRetryable?: (err: unknown, message: string) => boolean;\n /** Optional hook to log on each retry */\n onRetry?: (attempt: number, err: unknown, message: string) => void;\n};\n\n/**\n * Run an async function with standardized retry behavior for preference queries.\n * Exponential backoff with jitter; only retries on known-transient messages.\n *\n * @param fn - Function to run\n * @param options - Retry options\n * @returns Result of the function\n */\nexport async function withPreferenceQueryRetry<T>(\n fn: () => Promise<T>,\n {\n maxAttempts = 3,\n baseDelayMs = 250,\n isRetryable = (_err, msg) =>\n RETRY_PREFERENCE_MSGS.some((m) => msg.toLowerCase().includes(m)),\n onRetry,\n }: RetryOptions = {},\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt += 1;\n try {\n return await fn();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n const msg: string =\n (err && (err.response?.body || err.message)) ??\n String(err ?? 'Unknown error');\n const willRetry = attempt < maxAttempts && isRetryable(err, msg);\n if (!willRetry) {\n throw new Error(\n `Preference query failed after ${attempt} attempt(s): ${msg}`,\n );\n }\n onRetry?.(attempt, err, msg);\n\n const backoff = baseDelayMs * 2 ** (attempt - 1);\n const jitter = Math.floor(Math.random() * baseDelayMs);\n const delay = backoff + jitter;\n logger.warn(\n colors.yellow(\n `[retry] attempt ${attempt}/${\n maxAttempts - 1\n }; backing off ${delay}ms: ${msg}`,\n ),\n );\n await sleepPromise(delay);\n }\n }\n}\n","import { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(\n ', ',\n )}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(\n ([, rows]) => rows.length > 1,\n );\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from 'bluebird';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(\n t.string,\n t.union([t.string, t.boolean, t.null, t.undefined]),\n ),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\n/**\n * Mapping of column name to purpose row mapping.\n * This is used to map each column in the CSV to the relevant purpose and preference definitions in\n * transcend.\n */\nexport const ColumnPurposeMap = t.record(t.string, PurposeRowMapping);\n\n/** Override type */\nexport type ColumnPurposeMap = t.TypeOf<typeof ColumnPurposeMap>;\n\nexport const IdentifierMetadataForPreference = t.type({\n /** The identifier name */\n name: t.string,\n /** Is unique on preference store */\n isUniqueOnPreferenceStore: t.boolean,\n});\n\n/** Override type */\nexport type IdentifierMetadataForPreference = t.TypeOf<\n typeof IdentifierMetadataForPreference\n>;\n\n/**\n * Mapping of identifier name to the column name in the CSV file.\n * This is used to map each identifier name to the column in the CSV file.\n */\nexport const ColumnIdentifierMap = t.record(\n t.string,\n IdentifierMetadataForPreference,\n);\n\n/** Override type */\nexport type ColumnIdentifierMap = t.TypeOf<typeof ColumnIdentifierMap>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/**\n * This is the type of the receipts that are stored in the file\n * that is used to track the state of the upload process.\n * It is used to resume the upload process from where it left off.\n * It is used to persist the state of the upload process across multiple runs.\n */\nexport const PreferenceUpdateMap = t.record(\n t.string,\n // This can either be true to indicate the record is pending\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, PreferenceUpdateItem]),\n);\n\n/** Override type */\nexport type PreferenceUpdateMap = t.TypeOf<typeof PreferenceUpdateMap>;\n\n/**\n * This is the type of the pending updates that are safe to run without\n * conflicts with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is safe to upload.\n */\nexport const PendingSafePreferenceUpdates = t.record(\n t.string,\n // This can either be true to indicate the record is safe\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, t.record(t.string, t.string)]),\n);\n\n/** Override type */\nexport type PendingSafePreferenceUpdates = t.TypeOf<\n typeof PendingSafePreferenceUpdates\n>;\n\n/**\n * These are the updates that failed to be uploaded to the API.\n */\nexport const FailingPreferenceUpdates = t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n);\n\n/** Override type */\nexport type FailingPreferenceUpdates = t.TypeOf<\n typeof FailingPreferenceUpdates\n>;\n\n/**\n * This is the type of the pending updates that are in conflict with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is pending upload.\n */\nexport const PendingWithConflictPreferenceUpdates = t.record(\n t.string,\n // We always return the conflicts for investigation\n t.type({\n /** Record to be inserted to transcend v1/preferences API */\n record: PreferenceQueryResponseItem,\n /** The row in the file that is pending upload */\n row: t.record(t.string, t.string),\n }),\n);\n\n/** Override type */\nexport type PendingWithConflictPreferenceUpdates = t.TypeOf<\n typeof PendingWithConflictPreferenceUpdates\n>;\n\n/**\n * The set of preference updates that are skipped\n * Key is primaryKey and value is the row in the CSV\n * that is skipped.\n *\n * This is usually because the preferences are already in the store\n * or there are duplicate rows in the CSV file that are identical.\n */\nexport const SkippedPreferenceUpdates = t.record(\n t.string,\n t.record(t.string, t.string),\n);\n\n/** Override type */\nexport type SkippedPreferenceUpdates = t.TypeOf<\n typeof SkippedPreferenceUpdates\n>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-HCEZRZHV.cjs","../src/lib/preference-management/uploadPreferenceManagementPreferencesInteractive.ts","../src/lib/preference-management/parsePreferenceManagementCsv.ts","../src/lib/preference-management/getPreferencesForIdentifiers.ts","../src/lib/preference-management/withPreferenceQueryRetry.ts","../src/lib/preference-management/parsePreferenceIdentifiersFromCsv.ts","../src/lib/preference-management/parsePreferenceAndPurposeValuesFromCsv.ts","../src/lib/preference-management/codecs.ts"],"names":["RETRY_PREFERENCE_MSGS","s","withPreferenceQueryRetry","fn","maxAttempts","baseDelayMs","isRetryable","_err","msg","m","onRetry","attempt","err"],"mappings":"AAAA,2lCAA2J,wDAAyC,wDAAuE,gFCQxP,oCACC,qGAGI,+DAEO,qJCXZ,qDCES,ICGfA,EAAAA,CAAkC,CAC7C,WAAA,CACA,YAAA,CACA,WAAA,CACA,iBAAA,CACA,sBAAA,CACA,sBAAA,CACA,uBACF,CAAA,CAAE,GAAA,CAAKC,CAAAA,EAAMA,CAAAA,CAAE,WAAA,CAAY,CAAC,CAAA,CAwB5B,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CACA,CACE,WAAA,CAAAC,CAAAA,CAAc,CAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,GAAA,CACd,WAAA,CAAAC,CAAAA,CAAc,CAACC,CAAAA,CAAMC,CAAAA,CAAAA,EACnBR,EAAAA,CAAsB,IAAA,CAAMS,CAAAA,EAAMD,CAAAA,CAAI,WAAA,CAAY,CAAA,CAAE,QAAA,CAASC,CAAC,CAAC,CAAA,CACjE,OAAA,CAAAC,CACF,CAAA,CAAkB,CAAC,CAAA,CACP,CACZ,IAAIC,CAAAA,CAAU,CAAA,CAEd,GAAA,CAAA,CAAA,CAAA,CAAa,CACXA,CAAAA,EAAW,CAAA,CACX,GAAI,CACF,OAAO,MAAMR,CAAAA,CAAG,CAElB,CAAA,KAAA,CAASS,CAAAA,CAAU,CACjB,IAAMJ,CAAAA,kBAAAA,CACHI,CAAAA,EAAAA,iBAAQA,CAAAA,qBAAI,QAAA,6BAAU,MAAA,EAAQA,CAAAA,CAAI,OAAA,CAAA,CAAA,SACnC,MAAA,kBAAOA,CAAAA,SAAO,iBAAe,GAAA,CAE/B,EAAA,CAAI,CAAA,CADcD,CAAAA,CAAUP,CAAAA,EAAeE,CAAAA,CAAYM,CAAAA,CAAKJ,CAAG,CAAA,CAAA,CAE7D,MAAM,IAAI,KAAA,CACR,CAAA,8BAAA,EAAiCG,CAAO,CAAA,aAAA,EAAgBH,CAAG,CAAA,CAAA;ACiC/D;ACnBU;ACyBD,oGAAA;ANbP;AAGA;AAAA;AAKQ;AAAK;AACgC,sCAAA;AA+FY","file":"/home/runner/work/cli/cli/dist/chunk-HCEZRZHV.cjs","sourcesContent":[null,"import {\n buildTranscendGraphQLClient,\n createSombraGotInstance,\n fetchAllPurposes,\n fetchAllPreferenceTopics,\n PreferenceTopic,\n Purpose,\n} from '../graphql';\nimport colors from 'colors';\nimport { map } from 'bluebird';\nimport { chunk } from 'lodash-es';\nimport { logger } from '../../logger';\nimport cliProgress from 'cli-progress';\nimport { parseAttributesFromString } from '../requests';\nimport { PersistedState } from '@transcend-io/persisted-state';\nimport { parsePreferenceManagementCsvWithCache } from './parsePreferenceManagementCsv';\nimport { PreferenceState } from './codecs';\nimport { PreferenceUpdateItem } from '@transcend-io/privacy-types';\nimport { apply } from '@transcend-io/type-utils';\nimport { NONE_PREFERENCE_MAP } from './parsePreferenceTimestampsFromCsv';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\n\n/**\n * Upload a set of consent preferences\n *\n * @param options - Options\n */\nexport async function uploadPreferenceManagementPreferencesInteractive({\n auth,\n sombraAuth,\n receiptFilepath,\n file,\n partition,\n isSilent = true,\n dryRun = false,\n skipWorkflowTriggers = false,\n skipConflictUpdates = false,\n skipExistingRecordCheck = false,\n attributes = [],\n transcendUrl,\n forceTriggerWorkflows = false,\n}: {\n /** The Transcend API key */\n auth: string;\n /** Sombra API key authentication */\n sombraAuth?: string;\n /** Partition key */\n partition: string;\n /** File where to store receipt and continue from where left off */\n receiptFilepath: string;\n /** The file to process */\n file: string;\n /** API URL for Transcend backend */\n transcendUrl: string;\n /** Whether to do a dry run */\n dryRun?: boolean;\n /** Whether to upload as isSilent */\n isSilent?: boolean;\n /** Attributes string pre-parse. In format Key:Value */\n attributes?: string[];\n /** Skip workflow triggers */\n skipWorkflowTriggers?: boolean;\n /**\n * When true, only update preferences that do not conflict with existing\n * preferences. When false, update all preferences in CSV based on timestamp.\n */\n skipConflictUpdates?: boolean;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck?: boolean;\n /** Whether to force trigger workflows */\n forceTriggerWorkflows?: boolean;\n}): Promise<void> {\n // Parse out the extra attributes to apply to all requests uploaded\n const parsedAttributes = parseAttributesFromString(attributes);\n\n // Create a new state file to store the requests from this run\n const preferenceState = new PersistedState(receiptFilepath, PreferenceState, {\n fileMetadata: {},\n failingUpdates: {},\n pendingUpdates: {},\n });\n const failingRequests = preferenceState.getValue('failingUpdates');\n const pendingRequests = preferenceState.getValue('pendingUpdates');\n let fileMetadata = preferenceState.getValue('fileMetadata');\n\n logger.info(\n colors.magenta(\n 'Restored cache, there are: \\n' +\n `${\n Object.values(failingRequests).length\n } failing requests to be retried\\n` +\n `${\n Object.values(pendingRequests).length\n } pending requests to be processed\\n` +\n `The following files are stored in cache and will be used:\\n${Object.keys(\n fileMetadata,\n )\n .map((x) => x)\n .join('\\n')}\\n` +\n `The following file will be processed: ${file}\\n`,\n ),\n );\n\n // Create GraphQL client to connect to Transcend backend\n const client = buildTranscendGraphQLClient(transcendUrl, auth);\n\n const [sombra, purposes, preferenceTopics] = await Promise.all([\n // Create sombra instance to communicate with\n createSombraGotInstance(transcendUrl, auth, sombraAuth),\n // get all purposes and topics\n forceTriggerWorkflows\n ? Promise.resolve([] as Purpose[])\n : fetchAllPurposes(client),\n forceTriggerWorkflows\n ? Promise.resolve([] as PreferenceTopic[])\n : fetchAllPreferenceTopics(client),\n ]);\n\n // Process the file\n await parsePreferenceManagementCsvWithCache(\n {\n file,\n purposeSlugs: purposes.map((x) => x.trackingType),\n preferenceTopics,\n sombra,\n partitionKey: partition,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n },\n preferenceState,\n );\n\n // Construct the pending updates\n const pendingUpdates: Record<string, PreferenceUpdateItem> = {};\n fileMetadata = preferenceState.getValue('fileMetadata');\n const metadata = fileMetadata[file];\n\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingSafeUpdates).length\n } safe updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.pendingConflictUpdates).length\n } conflict updates in ${file}`,\n ),\n );\n logger.info(\n colors.magenta(\n `Found ${\n Object.entries(metadata.skippedUpdates).length\n } skipped updates in ${file}`,\n ),\n );\n\n // Update either safe updates only or safe + conflict\n Object.entries({\n ...metadata.pendingSafeUpdates,\n ...(skipConflictUpdates\n ? {}\n : apply(metadata.pendingConflictUpdates, ({ row }) => row)),\n }).forEach(([userId, update]) => {\n // Determine timestamp\n const timestamp =\n metadata.timestampColum === NONE_PREFERENCE_MAP\n ? new Date()\n : new Date(update[metadata.timestampColum!]);\n\n // Determine updates\n const updates = getPreferenceUpdatesFromRow({\n row: update,\n columnToPurposeName: metadata.columnToPurposeName,\n preferenceTopics,\n purposeSlugs: purposes.map((x) => x.trackingType),\n });\n pendingUpdates[userId] = {\n userId,\n partition,\n timestamp: timestamp.toISOString(),\n purposes: Object.entries(updates).map(([purpose, value]) => ({\n ...value,\n purpose,\n workflowSettings: {\n attributes: parsedAttributes,\n isSilent,\n skipWorkflowTrigger: skipWorkflowTriggers,\n },\n })),\n };\n });\n await preferenceState.setValue(pendingUpdates, 'pendingUpdates');\n await preferenceState.setValue({}, 'failingUpdates');\n\n // Exist early if dry run\n if (dryRun) {\n logger.info(\n colors.green(\n `Dry run complete, exiting. ${\n Object.values(pendingUpdates).length\n } pending updates. Check file: ${receiptFilepath}`,\n ),\n );\n return;\n }\n\n logger.info(\n colors.magenta(\n `Uploading ${\n Object.values(pendingUpdates).length\n } preferences to partition: ${partition}`,\n ),\n );\n\n // Time duration\n const t0 = new Date().getTime();\n\n // create a new progress bar instance and use shades_classic theme\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n\n // Build a GraphQL client\n let total = 0;\n const updatesToRun = Object.entries(pendingUpdates);\n const chunkedUpdates = chunk(updatesToRun, skipWorkflowTriggers ? 100 : 10);\n progressBar.start(updatesToRun.length, 0);\n await map(\n chunkedUpdates,\n async (currentChunk) => {\n // Make the request\n try {\n await sombra\n .put('v1/preferences', {\n json: {\n records: currentChunk.map(([, update]) => update),\n skipWorkflowTriggers,\n forceTriggerWorkflows,\n },\n })\n .json();\n } catch (err) {\n try {\n const parsed = JSON.parse(err?.response?.body || '{}');\n if (parsed.error) {\n logger.error(colors.red(`Error: ${parsed.error}`));\n }\n } catch (e) {\n // continue\n }\n logger.error(\n colors.red(\n `Failed to upload ${\n currentChunk.length\n } user preferences to partition ${partition}: ${\n err?.response?.body || err?.message\n }`,\n ),\n );\n const failingUpdates = preferenceState.getValue('failingUpdates');\n currentChunk.forEach(([userId, update]) => {\n failingUpdates[userId] = {\n uploadedAt: new Date().toISOString(),\n update,\n error: err?.response?.body || err?.message || 'Unknown error',\n };\n });\n await preferenceState.setValue(failingUpdates, 'failingUpdates');\n }\n\n total += currentChunk.length;\n progressBar.update(total);\n },\n {\n concurrency: 40,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n logger.info(\n colors.green(\n `Successfully uploaded ${\n updatesToRun.length\n } user preferences to partition ${partition} in \"${\n totalTime / 1000\n }\" seconds!`,\n ),\n );\n}\n","import { PersistedState } from '@transcend-io/persisted-state';\nimport type { Got } from 'got';\nimport { keyBy } from 'lodash-es';\nimport * as t from 'io-ts';\nimport colors from 'colors';\nimport { FileMetadataState, PreferenceState } from './codecs';\nimport { logger } from '../../logger';\nimport { readCsv } from '../requests';\nimport { getPreferencesForIdentifiers } from './getPreferencesForIdentifiers';\nimport { PreferenceTopic } from '../graphql';\nimport { getPreferenceUpdatesFromRow } from './getPreferenceUpdatesFromRow';\nimport { parsePreferenceTimestampsFromCsv } from './parsePreferenceTimestampsFromCsv';\nimport { parsePreferenceIdentifiersFromCsv } from './parsePreferenceIdentifiersFromCsv';\nimport { parsePreferenceAndPurposeValuesFromCsv } from './parsePreferenceAndPurposeValuesFromCsv';\nimport { checkIfPendingPreferenceUpdatesAreNoOp } from './checkIfPendingPreferenceUpdatesAreNoOp';\nimport { checkIfPendingPreferenceUpdatesCauseConflict } from './checkIfPendingPreferenceUpdatesCauseConflict';\n\n/**\n * Parse a file into the cache\n *\n *\n * @param options - Options\n * @param cache - The cache to store the parsed file in\n * @returns The cache with the parsed file\n */\nexport async function parsePreferenceManagementCsvWithCache(\n {\n file,\n sombra,\n purposeSlugs,\n preferenceTopics,\n partitionKey,\n skipExistingRecordCheck,\n forceTriggerWorkflows,\n }: {\n /** File to parse */\n file: string;\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Sombra got instance */\n sombra: Got;\n /** Partition key */\n partitionKey: string;\n /** Whether to skip the check for existing records. SHOULD ONLY BE USED FOR INITIAL UPLOAD */\n skipExistingRecordCheck: boolean;\n /** Wheather to force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n cache: PersistedState<typeof PreferenceState>,\n): Promise<void> {\n // Start the timer\n const t0 = new Date().getTime();\n\n // Get the current metadata\n const fileMetadata = cache.getValue('fileMetadata');\n\n // Read in the file\n logger.info(colors.magenta(`Reading in file: \"${file}\"`));\n let preferences = readCsv(file, t.record(t.string, t.string));\n\n // start building the cache, can use previous cache as well\n let currentState: FileMetadataState = {\n columnToPurposeName: {},\n pendingSafeUpdates: {},\n pendingConflictUpdates: {},\n skippedUpdates: {},\n // Load in the last fetched time\n ...((fileMetadata[file] || {}) as Partial<FileMetadataState>),\n lastFetchedAt: new Date().toISOString(),\n };\n\n // Validate that all timestamps are present in the file\n currentState = await parsePreferenceTimestampsFromCsv(\n preferences,\n currentState,\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Validate that all identifiers are present and unique\n const result = await parsePreferenceIdentifiersFromCsv(\n preferences,\n currentState,\n );\n currentState = result.currentState;\n preferences = result.preferences;\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Ensure all other columns are mapped to purpose and preference\n // slug values\n currentState = await parsePreferenceAndPurposeValuesFromCsv(\n preferences,\n currentState,\n {\n preferenceTopics,\n purposeSlugs,\n forceTriggerWorkflows,\n },\n );\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n\n // Grab existing preference store records\n const identifiers = preferences.map(\n (pref) => pref[currentState.identifierColumn!],\n );\n const existingConsentRecords = skipExistingRecordCheck\n ? []\n : await getPreferencesForIdentifiers(sombra, {\n identifiers: identifiers.map((x) => ({ value: x })),\n partitionKey,\n });\n const consentRecordByIdentifier = keyBy(existingConsentRecords, 'userId');\n\n // Clear out previous updates\n currentState.pendingConflictUpdates = {};\n currentState.pendingSafeUpdates = {};\n currentState.skippedUpdates = {};\n\n // Process each row\n preferences.forEach((pref) => {\n // Grab unique Id for the user\n const userId = pref[currentState.identifierColumn!];\n\n // determine updates for user\n const pendingUpdates = getPreferenceUpdatesFromRow({\n row: pref,\n columnToPurposeName: currentState.columnToPurposeName,\n preferenceTopics,\n purposeSlugs,\n });\n\n // Grab current state of the update\n const currentConsentRecord = consentRecordByIdentifier[userId];\n if (forceTriggerWorkflows && !currentConsentRecord) {\n throw new Error(\n `No existing consent record found for user with id: ${userId}. \n When 'forceTriggerWorkflows' is set all the user identifiers should contain a consent record`,\n );\n }\n // Check if the update can be skipped\n // this is the case if a record exists, and the purpose\n // and preference values are all in sync\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesAreNoOp({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n }) &&\n !forceTriggerWorkflows\n ) {\n currentState.skippedUpdates[userId] = pref;\n return;\n }\n\n // Determine if there are any conflicts\n if (\n currentConsentRecord &&\n checkIfPendingPreferenceUpdatesCauseConflict({\n currentConsentRecord,\n pendingUpdates,\n preferenceTopics,\n })\n ) {\n currentState.pendingConflictUpdates[userId] = {\n row: pref,\n record: currentConsentRecord,\n };\n return;\n }\n\n // Add to pending updates\n currentState.pendingSafeUpdates[userId] = pref;\n });\n\n // Read in the file\n fileMetadata[file] = currentState;\n await cache.setValue(fileMetadata, 'fileMetadata');\n const t1 = new Date().getTime();\n logger.info(\n colors.green(\n `Successfully pre-processed file: \"${file}\" in ${(t1 - t0) / 1000}s`,\n ),\n );\n}\n","import { PreferenceQueryResponseItem } from '@transcend-io/privacy-types';\nimport type { Got } from 'got';\nimport colors from 'colors';\nimport cliProgress from 'cli-progress';\nimport { chunk } from 'lodash-es';\nimport { decodeCodec } from '@transcend-io/type-utils';\nimport { map } from 'bluebird';\nimport { logger } from '../../logger';\nimport { withPreferenceQueryRetry } from './withPreferenceQueryRetry';\nimport { ConsentPreferenceResponse } from './types';\n\n/**\n * Grab the current consent preference values for a list of identifiers\n *\n * @param sombra - Backend to make API call to\n * @param options - Options\n * @returns Plaintext context information\n */\nexport async function getPreferencesForIdentifiers(\n sombra: Got,\n {\n identifiers,\n partitionKey,\n skipLogging = false,\n concurrency = 40,\n }: {\n /** The list of identifiers to look up */\n identifiers: {\n /** The value of the identifier */\n value: string;\n }[];\n /** The partition key to look up */\n partitionKey: string;\n /** Whether to skip logging */\n skipLogging?: boolean;\n /** Concurrency for requests (default 40) */\n concurrency?: number;\n },\n): Promise<PreferenceQueryResponseItem[]> {\n const results: PreferenceQueryResponseItem[] = [];\n const groupedIdentifiers = chunk(identifiers, 100);\n\n // create a new progress bar instance and use shades_classic theme\n const t0 = new Date().getTime();\n const progressBar = new cliProgress.SingleBar(\n {},\n cliProgress.Presets.shades_classic,\n );\n if (!skipLogging) {\n progressBar.start(identifiers.length, 0);\n }\n\n let total = 0;\n await map(\n groupedIdentifiers,\n async (group) => {\n const rawResult = await withPreferenceQueryRetry(\n () =>\n sombra\n .post(`v1/preferences/${partitionKey}/query`, {\n json: {\n filter: { identifiers: group },\n limit: group.length,\n },\n })\n .json(),\n {\n onRetry: (attempt, _err, msg) => {\n logger.warn(\n colors.yellow(\n `[RETRY] group size=${group.length} partition=${partitionKey} attempt=${attempt}: ${msg}`,\n ),\n );\n },\n },\n );\n\n const result = decodeCodec(ConsentPreferenceResponse, rawResult);\n results.push(...result.nodes);\n total += group.length;\n progressBar.update(total);\n },\n {\n concurrency,\n },\n );\n\n progressBar.stop();\n const t1 = new Date().getTime();\n const totalTime = t1 - t0;\n\n if (!skipLogging) {\n // Log completion time\n logger.info(\n colors.green(`Completed download in \"${totalTime / 1000}\" seconds.`),\n );\n }\n\n return results;\n}\n","import colors from 'colors';\nimport { logger } from '../../logger';\nimport { sleepPromise } from '../helpers';\n\n/**\n * Transient network / platform errors that merit a retry.\n * Keep this list short and specific to avoid masking real failures.\n */\nexport const RETRY_PREFERENCE_MSGS: string[] = [\n 'ENOTFOUND',\n 'ECONNRESET',\n 'ETIMEDOUT',\n '502 Bad Gateway',\n '504 Gateway Time-out',\n 'Task timed out after',\n 'unknown request error',\n].map((s) => s.toLowerCase());\n\n/**\n * Options for retrying preference queries.\n */\nexport type RetryOptions = {\n /** Max attempts including the first try (default 3) */\n maxAttempts?: number;\n /** Initial backoff in ms (default 250) */\n baseDelayMs?: number;\n /** Optional custom predicate to decide if an error is retryable */\n isRetryable?: (err: unknown, message: string) => boolean;\n /** Optional hook to log on each retry */\n onRetry?: (attempt: number, err: unknown, message: string) => void;\n};\n\n/**\n * Run an async function with standardized retry behavior for preference queries.\n * Exponential backoff with jitter; only retries on known-transient messages.\n *\n * @param fn - Function to run\n * @param options - Retry options\n * @returns Result of the function\n */\nexport async function withPreferenceQueryRetry<T>(\n fn: () => Promise<T>,\n {\n maxAttempts = 3,\n baseDelayMs = 250,\n isRetryable = (_err, msg) =>\n RETRY_PREFERENCE_MSGS.some((m) => msg.toLowerCase().includes(m)),\n onRetry,\n }: RetryOptions = {},\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n attempt += 1;\n try {\n return await fn();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (err: any) {\n const msg: string =\n (err && (err.response?.body || err.message)) ??\n String(err ?? 'Unknown error');\n const willRetry = attempt < maxAttempts && isRetryable(err, msg);\n if (!willRetry) {\n throw new Error(\n `Preference query failed after ${attempt} attempt(s): ${msg}`,\n );\n }\n onRetry?.(attempt, err, msg);\n\n const backoff = baseDelayMs * 2 ** (attempt - 1);\n const jitter = Math.floor(Math.random() * baseDelayMs);\n const delay = backoff + jitter;\n logger.warn(\n colors.yellow(\n `[retry] attempt ${attempt}/${\n maxAttempts - 1\n }; backing off ${delay}ms: ${msg}`,\n ),\n );\n await sleepPromise(delay);\n }\n }\n}\n","import { uniq, groupBy, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { inquirerConfirmBoolean } from '../helpers';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse identifiers from a CSV list of preferences\n *\n * Ensures that all rows have a valid identifier\n * and that all identifiers are unique.\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceIdentifiersFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n): Promise<{\n /** The updated state */\n currentState: FileMetadataState;\n /** The updated preferences */\n preferences: Record<string, string>[];\n}> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const remainingColumnsForIdentifier = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...Object.keys(currentState.columnToPurposeName),\n ]);\n\n // Determine the identifier column to work off of\n if (!currentState.identifierColumn) {\n const { identifierName } = await inquirer.prompt<{\n /** Identifier name */\n identifierName: string;\n }>([\n {\n name: 'identifierName',\n message:\n 'Choose the column that will be used as the identifier to upload consent preferences by',\n type: 'list',\n default:\n remainingColumnsForIdentifier.find((col) =>\n col.toLowerCase().includes('email'),\n ) || remainingColumnsForIdentifier[0],\n choices: remainingColumnsForIdentifier,\n },\n ]);\n currentState.identifierColumn = identifierName;\n }\n logger.info(\n colors.magenta(\n `Using identifier column \"${currentState.identifierColumn}\"`,\n ),\n );\n\n // Validate that the identifier column is present for all rows and unique\n const identifierColumnsMissing = preferences\n .map((pref, ind) => (pref[currentState.identifierColumn!] ? null : [ind]))\n .filter((x): x is number[] => !!x)\n .flat();\n if (identifierColumnsMissing.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" is missing a value for the following rows: ${identifierColumnsMissing.join(\n ', ',\n )}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to skip rows missing an identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to skip rows missing an identifier?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n\n // Filter out rows missing an identifier\n const previous = preferences.length;\n preferences = preferences.filter(\n (pref) => pref[currentState.identifierColumn!],\n );\n logger.info(\n colors.yellow(\n `Skipped ${previous - preferences.length} rows missing an identifier`,\n ),\n );\n }\n logger.info(\n colors.magenta(\n `The identifier column \"${currentState.identifierColumn}\" is present for all rows`,\n ),\n );\n\n // Validate that all identifiers are unique\n const rowsByUserId = groupBy(preferences, currentState.identifierColumn);\n const duplicateIdentifiers = Object.entries(rowsByUserId).filter(\n ([, rows]) => rows.length > 1,\n );\n if (duplicateIdentifiers.length > 0) {\n const msg = `The identifier column \"${\n currentState.identifierColumn\n }\" has duplicate values for the following rows: ${duplicateIdentifiers\n .slice(0, 10)\n .map(([userId, rows]) => `${userId} (${rows.length})`)\n .join('\\n')}`;\n logger.warn(colors.yellow(msg));\n\n // Ask user if they would like to take the most recent update\n // for each duplicate identifier\n const skip = await inquirerConfirmBoolean({\n message: 'Would you like to automatically take the latest update?',\n });\n if (!skip) {\n throw new Error(msg);\n }\n preferences = Object.entries(rowsByUserId)\n .map(([, rows]) => {\n const sorted = rows.sort(\n (a, b) =>\n new Date(b[currentState.timestampColum!]).getTime() -\n new Date(a[currentState.timestampColum!]).getTime(),\n );\n return sorted[0];\n })\n .filter((x) => x);\n }\n\n return { currentState, preferences };\n}\n/* eslint-enable no-param-reassign */\n","import { uniq, difference } from 'lodash-es';\nimport colors from 'colors';\nimport inquirer from 'inquirer';\nimport { FileMetadataState } from './codecs';\nimport { logger } from '../../logger';\nimport { mapSeries } from 'bluebird';\nimport { PreferenceTopic } from '../graphql';\nimport { PreferenceTopicType } from '@transcend-io/privacy-types';\nimport { splitCsvToList } from '../requests';\n\n/* eslint-disable no-param-reassign */\n\n/**\n * Parse out the purpose.enabled and preference values from a CSV file\n *\n * @param preferences - List of preferences\n * @param currentState - The current file metadata state for parsing this list\n * @param options - Options\n * @returns The updated file metadata state\n */\nexport async function parsePreferenceAndPurposeValuesFromCsv(\n preferences: Record<string, string>[],\n currentState: FileMetadataState,\n {\n purposeSlugs,\n preferenceTopics,\n forceTriggerWorkflows,\n }: {\n /** The purpose slugs that are allowed to be updated */\n purposeSlugs: string[];\n /** The preference topics */\n preferenceTopics: PreferenceTopic[];\n /** Force workflow triggers */\n forceTriggerWorkflows: boolean;\n },\n): Promise<FileMetadataState> {\n // Determine columns to map\n const columnNames = uniq(preferences.map((x) => Object.keys(x)).flat());\n\n // Determine the columns that could potentially be used for identifier\n const otherColumns = difference(columnNames, [\n ...(currentState.identifierColumn ? [currentState.identifierColumn] : []),\n ...(currentState.timestampColum ? [currentState.timestampColum] : []),\n ]);\n if (otherColumns.length === 0) {\n if (forceTriggerWorkflows) {\n return currentState;\n }\n throw new Error('No other columns to process');\n }\n\n // The purpose and preferences to map to\n const purposeNames = [\n ...purposeSlugs,\n ...preferenceTopics.map((x) => `${x.purpose.trackingType}->${x.slug}`),\n ];\n\n // Ensure all columns are accounted for\n await mapSeries(otherColumns, async (col) => {\n // Determine the unique values to map in this column\n const uniqueValues = uniq(preferences.map((x) => x[col]));\n\n // Map the column to a purpose\n let purposeMapping = currentState.columnToPurposeName[col];\n if (purposeMapping) {\n logger.info(\n colors.magenta(\n `Column \"${col}\" is associated with purpose \"${purposeMapping.purpose}\"`,\n ),\n );\n } else {\n const { purposeName } = await inquirer.prompt<{\n /** purpose name */\n purposeName: string;\n }>([\n {\n name: 'purposeName',\n message: `Choose the purpose that column ${col} is associated with`,\n type: 'list',\n default: purposeNames.find((x) => x.startsWith(purposeSlugs[0])),\n choices: purposeNames,\n },\n ]);\n const [purposeSlug, preferenceSlug] = purposeName.split('->');\n purposeMapping = {\n purpose: purposeSlug,\n preference: preferenceSlug || null,\n valueMapping: {},\n };\n }\n\n // map each value to the purpose value\n await mapSeries(uniqueValues, async (value) => {\n if (purposeMapping.valueMapping[value] !== undefined) {\n logger.info(\n colors.magenta(\n `Value \"${value}\" is associated with purpose value \"${purposeMapping.valueMapping[value]}\"`,\n ),\n );\n return;\n }\n // if preference is null, this column is just for the purpose\n if (purposeMapping.preference === null) {\n const { purposeValue } = await inquirer.prompt<{\n /** purpose value */\n purposeValue: boolean;\n }>([\n {\n name: 'purposeValue',\n message: `Choose the purpose value for value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = purposeValue;\n }\n\n // if preference is not null, this column is for a specific preference\n if (purposeMapping.preference !== null) {\n const preferenceTopic = preferenceTopics.find(\n (x) => x.slug === purposeMapping.preference,\n );\n if (!preferenceTopic) {\n logger.error(\n colors.red(\n `Preference topic \"${purposeMapping.preference}\" not found`,\n ),\n );\n return;\n }\n const preferenceOptions = preferenceTopic.preferenceOptionValues.map(\n ({ slug }) => slug,\n );\n\n if (preferenceTopic.type === PreferenceTopicType.Boolean) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n message:\n // eslint-disable-next-line max-len\n `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'confirm',\n default: value !== 'false',\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.Select) {\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${value}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === value),\n },\n ]);\n purposeMapping.valueMapping[value] = preferenceValue;\n return;\n }\n\n if (preferenceTopic.type === PreferenceTopicType.MultiSelect) {\n const parsedValues = splitCsvToList(value);\n // need to do this serially\n await mapSeries(parsedValues, async (parsedValue) => {\n // if we already have a value, skip re-processing it again\n if (purposeMapping.valueMapping[parsedValue] !== undefined) {\n return;\n }\n const { preferenceValue } = await inquirer.prompt<{\n /** purpose value */\n preferenceValue: boolean;\n }>([\n {\n name: 'preferenceValue',\n // eslint-disable-next-line max-len\n message: `Choose the preference value for \"${preferenceTopic.slug}\" value \"${parsedValue}\" associated with purpose \"${purposeMapping.purpose}\"`,\n type: 'list',\n choices: preferenceOptions,\n default: preferenceOptions.find((x) => x === parsedValue),\n },\n ]);\n purposeMapping.valueMapping[parsedValue] = preferenceValue;\n });\n return;\n }\n\n throw new Error(\n `Unknown preference topic type: ${preferenceTopic.type}`,\n );\n }\n });\n\n currentState.columnToPurposeName[col] = purposeMapping;\n });\n\n return currentState;\n}\n/* eslint-enable no-param-reassign */\n","import {\n PreferenceQueryResponseItem,\n PreferenceUpdateItem,\n} from '@transcend-io/privacy-types';\nimport * as t from 'io-ts';\n\nexport const PurposeRowMapping = t.type({\n /**\n * The slug or trackingType of the purpose to map to\n *\n * e.g. `Marketing`\n */\n purpose: t.string,\n /**\n * If the column maps to a preference instead of a purpose\n * this is the slug of the purpose.\n *\n * null value indicates that this column maps to the true/false\n * value of the purpose\n */\n preference: t.union([t.string, t.null]),\n /**\n * The mapping between each row value and purpose/preference value.\n *\n * e.g. for a boolean preference or purpose\n * {\n * 'true': true,\n * 'false': false,\n * '': true,\n * }\n *\n * or for a single or multi select preference\n * {\n * '': true,\n * 'value1': 'Value1',\n * 'value2': 'Value2',\n * }\n */\n valueMapping: t.record(\n t.string,\n t.union([t.string, t.boolean, t.null, t.undefined]),\n ),\n});\n\n/** Override type */\nexport type PurposeRowMapping = t.TypeOf<typeof PurposeRowMapping>;\n\n/**\n * Mapping of column name to purpose row mapping.\n * This is used to map each column in the CSV to the relevant purpose and preference definitions in\n * transcend.\n */\nexport const ColumnPurposeMap = t.record(t.string, PurposeRowMapping);\n\n/** Override type */\nexport type ColumnPurposeMap = t.TypeOf<typeof ColumnPurposeMap>;\n\nexport const IdentifierMetadataForPreference = t.type({\n /** The identifier name */\n name: t.string,\n /** Is unique on preference store */\n isUniqueOnPreferenceStore: t.boolean,\n});\n\n/** Override type */\nexport type IdentifierMetadataForPreference = t.TypeOf<\n typeof IdentifierMetadataForPreference\n>;\n\n/**\n * Mapping of identifier name to the column name in the CSV file.\n * This is used to map each identifier name to the column in the CSV file.\n */\nexport const ColumnIdentifierMap = t.record(\n t.string,\n IdentifierMetadataForPreference,\n);\n\n/** Override type */\nexport type ColumnIdentifierMap = t.TypeOf<typeof ColumnIdentifierMap>;\n\nexport const FileMetadataState = t.intersection([\n t.type({\n /**\n * Definition of how to map each column in the CSV to\n * the relevant purpose and preference definitions in transcend\n */\n columnToPurposeName: t.record(t.string, PurposeRowMapping),\n /** Last time the file was last parsed at */\n lastFetchedAt: t.string,\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * These uploads are overwriting non-existent preferences and are safe\n */\n pendingSafeUpdates: t.record(t.string, t.record(t.string, t.string)),\n /**\n * Mapping of userId to the rows in the file that need to be uploaded\n * these records have conflicts with existing consent preferences\n */\n pendingConflictUpdates: t.record(\n t.string,\n t.type({\n record: PreferenceQueryResponseItem,\n row: t.record(t.string, t.string),\n }),\n ),\n /**\n * Mapping of userId to the rows in the file that can be skipped because\n * their preferences are already in the store\n */\n skippedUpdates: t.record(t.string, t.record(t.string, t.string)),\n }),\n t.partial({\n /** Determine which column name in file maps to consent record identifier to upload on */\n identifierColumn: t.string,\n /** Determine which column name in file maps to the timestamp */\n timestampColum: t.string,\n }),\n]);\n\n/** Override type */\nexport type FileMetadataState = t.TypeOf<typeof FileMetadataState>;\n\n/**\n * This is the type of the receipts that are stored in the file\n * that is used to track the state of the upload process.\n * It is used to resume the upload process from where it left off.\n * It is used to persist the state of the upload process across multiple runs.\n */\nexport const PreferenceUpdateMap = t.record(\n t.string,\n // This can either be true to indicate the record is pending\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, PreferenceUpdateItem]),\n);\n\n/** Override type */\nexport type PreferenceUpdateMap = t.TypeOf<typeof PreferenceUpdateMap>;\n\n/**\n * This is the type of the pending updates that are safe to run without\n * conflicts with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is safe to upload.\n */\nexport const PendingSafePreferenceUpdates = t.record(\n t.string,\n // This can either be true to indicate the record is safe\n // or it can be an object showing the object\n // We only return a fixed number of results to avoid\n // making the JSON file too large\n t.union([t.boolean, t.record(t.string, t.string)]),\n);\n\n/** Override type */\nexport type PendingSafePreferenceUpdates = t.TypeOf<\n typeof PendingSafePreferenceUpdates\n>;\n\n/**\n * These are the updates that failed to be uploaded to the API.\n */\nexport const FailingPreferenceUpdates = t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n);\n\n/** Override type */\nexport type FailingPreferenceUpdates = t.TypeOf<\n typeof FailingPreferenceUpdates\n>;\n\n/**\n * This is the type of the pending updates that are in conflict with existing consent preferences.\n *\n * Key is primaryKey of the record in the file.\n * The value is the row in the file that is pending upload.\n */\nexport const PendingWithConflictPreferenceUpdates = t.record(\n t.string,\n // We always return the conflicts for investigation\n t.type({\n /** Record to be inserted to transcend v1/preferences API */\n record: PreferenceQueryResponseItem,\n /** The row in the file that is pending upload */\n row: t.record(t.string, t.string),\n }),\n);\n\n/** Override type */\nexport type PendingWithConflictPreferenceUpdates = t.TypeOf<\n typeof PendingWithConflictPreferenceUpdates\n>;\n\n/**\n * The set of preference updates that are skipped\n * Key is primaryKey and value is the row in the CSV\n * that is skipped.\n *\n * This is usually because the preferences are already in the store\n * or there are duplicate rows in the CSV file that are identical.\n */\nexport const SkippedPreferenceUpdates = t.record(\n t.string,\n t.record(t.string, t.string),\n);\n\n/** Override type */\nexport type SkippedPreferenceUpdates = t.TypeOf<\n typeof SkippedPreferenceUpdates\n>;\n\n/** Persist this data between runs of the script */\nexport const PreferenceState = t.type({\n /**\n * Store a cache of previous files read in\n */\n fileMetadata: t.record(t.string, FileMetadataState),\n /**\n * The set of successful uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n failingUpdates: t.record(\n t.string,\n t.type({\n /** Time upload ran at */\n uploadedAt: t.string,\n /** Attempts to upload that resulted in an error */\n error: t.string,\n /** The update body */\n update: PreferenceUpdateItem,\n }),\n ),\n /**\n * The set of pending uploads to Transcend\n * Mapping from userId to the upload metadata\n */\n pendingUpdates: t.record(t.string, PreferenceUpdateItem),\n});\n\n/** Override type */\nexport type PreferenceState = t.TypeOf<typeof PreferenceState>;\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunkABKDAPPRcjs = require('./chunk-ABKDAPPR.cjs');var _typeutils = require('@transcend-io/type-utils');var _jsyaml = require('js-yaml'); var _jsyaml2 = _interopRequireDefault(_jsyaml);var _fs = require('fs');var s=/<<parameters\.(.+?)>>/,i= exports.b ="parameters";function u(e,t,a=""){let r=e;if(Object.entries(t).forEach(([n,p])=>{r=r.split(`<<${i}.${n}>>`).join(p)}),s.test(r)){let[,n]=s.exec(r)||[];throw new Error(`Found variable that was not set: ${n}.
|
|
2
2
|
Make sure you are passing all parameters through the --${i}=${n}:value-for-param flag.
|
|
3
|
-
${a}`)}return r}function b(e,t={}){let a=_fs.readFileSync.call(void 0, e,"utf-8"),r=u(a,t,`Also check that there are no extra variables defined in your yaml: ${e}`);return _typeutils.decodeCodec.call(void 0,
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
${a}`)}return r}function b(e,t={}){let a=_fs.readFileSync.call(void 0, e,"utf-8"),r=u(a,t,`Also check that there are no extra variables defined in your yaml: ${e}`);return _typeutils.decodeCodec.call(void 0, _chunkABKDAPPRcjs.ha,_jsyaml2.default.load(r))}function h(e,t){_fs.writeFileSync.call(void 0, e,_jsyaml2.default.dump(_typeutils.decodeCodec.call(void 0, _chunkABKDAPPRcjs.ha,t)))}exports.a = s; exports.b = i; exports.c = u; exports.d = b; exports.e = h;
|
|
4
|
+
//# sourceMappingURL=chunk-JH5HRI6D.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/cli/cli/dist/chunk-JH5HRI6D.cjs","../src/lib/readTranscendYaml.ts"],"names":["VARIABLE_PARAMETERS_REGEXP","VARIABLE_PARAMETERS_NAME","replaceVariablesInYaml","input","variables","extraErrorMessage","contents","name","value"],"mappings":"AAAA,iOAAyC,qDCAA,iFACxB,wBAC2B,IAG/BA,CAAAA,CAA6B,uBAAA,CAC7BC,CAAAA,aAA2B,YAAA,CAWjC,SAASC,CAAAA,CACdC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAoB,EAAA,CACZ,CACR,IAAIC,CAAAA,CAAWH,CAAAA,CASf,EAAA,CAPA,MAAA,CAAO,OAAA,CAAQC,CAAS,CAAA,CAAE,OAAA,CAAQ,CAAC,CAACG,CAAAA,CAAMC,CAAK,CAAA,CAAA,EAAM,CACnDF,CAAAA,CAAWA,CAAAA,CACR,KAAA,CAAM,CAAA,EAAA,EAAKL,CAAwB,CAAA,CAAA,EAAIM,CAAI,CAAA,EAAA,CAAI,CAAA,CAC/C,IAAA,CAAKC,CAAK,CACf,CAAC,CAAA,CAGGR,CAAAA,CAA2B,IAAA,CAAKM,CAAQ,CAAA,CAAG,CAC7C,GAAM,CAAC,CAAEC,CAAI,CAAA,CAAIP,CAAAA,CAA2B,IAAA,CAAKM,CAAQ,CAAA,EAAK,CAAC,CAAA,CAC/D,MAAM,IAAI,KAAA,CACR,CAAA,iCAAA,EAAoCC,CAAI,CAAA;AAAA,uDAAA,EACWN,CAAwB,CAAA,CAAA,EAAIM,CAAI,CAAA;AAAA,EACvFF,CAAiB,CAAA,CAAA","file":"/home/runner/work/cli/cli/dist/chunk-JH5HRI6D.cjs","sourcesContent":[null,"import { decodeCodec, ObjByString } from '@transcend-io/type-utils';\nimport yaml from 'js-yaml';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { TranscendInput } from '../codecs';\n\nexport const VARIABLE_PARAMETERS_REGEXP = /<<parameters\\.(.+?)>>/;\nexport const VARIABLE_PARAMETERS_NAME = 'parameters';\n\n/**\n * Function that replaces variables in a text file.\n * Throws error if there are variables that have not been replaced\n *\n * @param input - Input text\n * @param variables - Variables to replace\n * @param extraErrorMessage - Additional error message text\n * @returns Output text\n */\nexport function replaceVariablesInYaml(\n input: string,\n variables: ObjByString,\n extraErrorMessage = '',\n): string {\n let contents = input;\n // Replace variables\n Object.entries(variables).forEach(([name, value]) => {\n contents = contents\n .split(`<<${VARIABLE_PARAMETERS_NAME}.${name}>>`)\n .join(value);\n });\n\n // Throw error if unfilled variables\n if (VARIABLE_PARAMETERS_REGEXP.test(contents)) {\n const [, name] = VARIABLE_PARAMETERS_REGEXP.exec(contents) || [];\n throw new Error(\n `Found variable that was not set: ${name}.\nMake sure you are passing all parameters through the --${VARIABLE_PARAMETERS_NAME}=${name}:value-for-param flag.\n${extraErrorMessage}`,\n );\n }\n\n return contents;\n}\n\n/**\n * Read in the contents of a yaml file and validate that the shape\n * of the yaml file matches the codec API\n *\n * @param filePath - Path to yaml file\n * @param variables - Variables to fill in\n * @returns The contents of the yaml file, type-checked\n */\nexport function readTranscendYaml(\n filePath: string,\n variables: ObjByString = {},\n): TranscendInput {\n // Read in contents\n const fileContents = readFileSync(filePath, 'utf-8');\n\n // Replace variables\n const replacedVariables = replaceVariablesInYaml(\n fileContents,\n variables,\n `Also check that there are no extra variables defined in your yaml: ${filePath}`,\n );\n\n // Validate shape\n return decodeCodec(TranscendInput, yaml.load(replacedVariables));\n}\n\n/**\n * Write a Transcend configuration to disk\n *\n * @param filePath - Path to yaml file\n * @param input - The input to write out\n */\nexport function writeTranscendYaml(\n filePath: string,\n input: TranscendInput,\n): void {\n writeFileSync(filePath, yaml.dump(decodeCodec(TranscendInput, input)));\n}\n"]}
|