sf-plugin-data 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +572 -240
  3. package/docs/artifact-format.md +527 -633
  4. package/docs/capabilities.md +1159 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +7 -0
  8. package/lib/api.js +7 -0
  9. package/lib/artifacts/code-fields.d.ts +49 -0
  10. package/lib/artifacts/code-fields.js +142 -0
  11. package/lib/artifacts/data-graph-document.d.ts +29 -0
  12. package/lib/artifacts/data-graph-document.js +52 -0
  13. package/lib/artifacts/data-space-field.d.ts +65 -0
  14. package/lib/artifacts/data-space-field.js +98 -0
  15. package/lib/artifacts/data-stream-document.d.ts +264 -0
  16. package/lib/artifacts/data-stream-document.js +680 -0
  17. package/lib/artifacts/data-transform-document.d.ts +152 -0
  18. package/lib/artifacts/data-transform-document.js +560 -0
  19. package/lib/artifacts/dependency-selection.d.ts +51 -0
  20. package/lib/artifacts/dependency-selection.js +154 -0
  21. package/lib/artifacts/dlo-document.d.ts +93 -0
  22. package/lib/artifacts/dlo-document.js +253 -0
  23. package/lib/artifacts/enum-case.d.ts +39 -0
  24. package/lib/artifacts/enum-case.js +67 -0
  25. package/lib/artifacts/git-deploy-selection.d.ts +68 -0
  26. package/lib/artifacts/git-deploy-selection.js +474 -0
  27. package/lib/artifacts/identity-resolution-document.d.ts +133 -0
  28. package/lib/artifacts/identity-resolution-document.js +625 -0
  29. package/lib/artifacts/mapping-document.d.ts +1 -0
  30. package/lib/artifacts/mapping-document.js +1 -0
  31. package/lib/artifacts/native-calculated-insight-document.d.ts +142 -0
  32. package/lib/artifacts/native-calculated-insight-document.js +321 -0
  33. package/lib/artifacts/native-data-graph-document.d.ts +124 -0
  34. package/lib/artifacts/native-data-graph-document.js +780 -0
  35. package/lib/artifacts/native-dmo-document.d.ts +151 -0
  36. package/lib/artifacts/native-dmo-document.js +313 -0
  37. package/lib/artifacts/native-mapping-document.d.ts +67 -0
  38. package/lib/artifacts/native-mapping-document.js +187 -0
  39. package/lib/artifacts/native-relationship-document.d.ts +76 -0
  40. package/lib/artifacts/native-relationship-document.js +232 -0
  41. package/lib/artifacts/path-selector.d.ts +55 -0
  42. package/lib/artifacts/path-selector.js +167 -0
  43. package/lib/artifacts/read-deploy-input.d.ts +222 -6
  44. package/lib/artifacts/read-deploy-input.js +1213 -53
  45. package/lib/artifacts/segment-document.d.ts +183 -0
  46. package/lib/artifacts/segment-document.js +570 -0
  47. package/lib/artifacts/verbatim-document.d.ts +203 -0
  48. package/lib/artifacts/verbatim-document.js +339 -0
  49. package/lib/artifacts/write-data-graph.d.ts +17 -0
  50. package/lib/artifacts/write-data-graph.js +162 -0
  51. package/lib/artifacts/write-data-stream.d.ts +11 -0
  52. package/lib/artifacts/write-data-stream.js +175 -0
  53. package/lib/artifacts/write-data-transform.d.ts +11 -0
  54. package/lib/artifacts/write-data-transform.js +180 -0
  55. package/lib/artifacts/write-dlo.d.ts +11 -0
  56. package/lib/artifacts/write-dlo.js +158 -0
  57. package/lib/artifacts/write-identity-resolution.d.ts +18 -0
  58. package/lib/artifacts/write-identity-resolution.js +165 -0
  59. package/lib/artifacts/write-mapping-definition.d.ts +17 -0
  60. package/lib/artifacts/write-mapping-definition.js +127 -0
  61. package/lib/artifacts/write-member-export.d.ts +88 -0
  62. package/lib/artifacts/write-member-export.js +199 -0
  63. package/lib/artifacts/write-native-calculated-insight.d.ts +21 -0
  64. package/lib/artifacts/write-native-calculated-insight.js +176 -0
  65. package/lib/artifacts/write-native-dmo.d.ts +11 -0
  66. package/lib/artifacts/write-native-dmo.js +158 -0
  67. package/lib/artifacts/write-native-mapping.d.ts +11 -0
  68. package/lib/artifacts/write-native-mapping.js +157 -0
  69. package/lib/artifacts/write-native-relationship.d.ts +11 -0
  70. package/lib/artifacts/write-native-relationship.js +157 -0
  71. package/lib/artifacts/write-segment.d.ts +26 -0
  72. package/lib/artifacts/write-segment.js +212 -0
  73. package/lib/commands/data360/delete.d.ts +280 -0
  74. package/lib/commands/data360/delete.js +2297 -0
  75. package/lib/commands/data360/deploy.d.ts +234 -15
  76. package/lib/commands/data360/deploy.js +2292 -100
  77. package/lib/commands/data360/publish.d.ts +93 -0
  78. package/lib/commands/data360/publish.js +292 -0
  79. package/lib/commands/data360/retrieve.d.ts +260 -13
  80. package/lib/commands/data360/retrieve.js +1880 -85
  81. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  82. package/lib/commands/data360/segment/members/export.js +318 -0
  83. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  84. package/lib/errors/codes/calculated-insight.js +25 -0
  85. package/lib/errors/codes/data-graph.d.ts +2 -0
  86. package/lib/errors/codes/data-graph.js +22 -0
  87. package/lib/errors/codes/data-stream.d.ts +2 -0
  88. package/lib/errors/codes/data-stream.js +70 -0
  89. package/lib/errors/codes/data-transform.d.ts +2 -0
  90. package/lib/errors/codes/data-transform.js +35 -0
  91. package/lib/errors/codes/dependency.d.ts +2 -0
  92. package/lib/errors/codes/dependency.js +11 -0
  93. package/lib/errors/codes/dlo.d.ts +2 -0
  94. package/lib/errors/codes/dlo.js +31 -0
  95. package/lib/errors/codes/dmo.d.ts +2 -0
  96. package/lib/errors/codes/dmo.js +28 -0
  97. package/lib/errors/codes/general.d.ts +2 -0
  98. package/lib/errors/codes/general.js +57 -0
  99. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  100. package/lib/errors/codes/identity-resolution.js +24 -0
  101. package/lib/errors/codes/mapping.d.ts +2 -0
  102. package/lib/errors/codes/mapping.js +42 -0
  103. package/lib/errors/codes/relationship.d.ts +2 -0
  104. package/lib/errors/codes/relationship.js +21 -0
  105. package/lib/errors/codes/segment.d.ts +2 -0
  106. package/lib/errors/codes/segment.js +49 -0
  107. package/lib/errors/registry.d.ts +60 -0
  108. package/lib/errors/registry.js +123 -0
  109. package/lib/plugin.d.ts +1 -0
  110. package/lib/plugin.js +3 -1
  111. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  112. package/lib/services/acquire-retrieve-selection.js +145 -0
  113. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  114. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  115. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  116. package/lib/services/bind-segment-dependencies.js +115 -0
  117. package/lib/services/bounded-reads.d.ts +17 -0
  118. package/lib/services/bounded-reads.js +42 -0
  119. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  120. package/lib/services/calculated-insight-sql-checks.js +193 -0
  121. package/lib/services/command-dlo.d.ts +48 -0
  122. package/lib/services/command-dlo.js +103 -0
  123. package/lib/services/command-native-data-graph.d.ts +54 -0
  124. package/lib/services/command-native-data-graph.js +485 -0
  125. package/lib/services/command-native-data-stream.d.ts +104 -0
  126. package/lib/services/command-native-data-stream.js +257 -0
  127. package/lib/services/command-native-dmo.d.ts +124 -0
  128. package/lib/services/command-native-dmo.js +338 -0
  129. package/lib/services/command-native-mapping.d.ts +65 -0
  130. package/lib/services/command-native-mapping.js +129 -0
  131. package/lib/services/command-native-relationship.d.ts +46 -0
  132. package/lib/services/command-native-relationship.js +103 -0
  133. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  134. package/lib/services/cross-dataspace-deploy.js +493 -0
  135. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  136. package/lib/services/cross-dataspace-rename.js +1314 -0
  137. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  138. package/lib/services/cross-dataspace-sql.js +1301 -0
  139. package/lib/services/cross-space-context.d.ts +23 -0
  140. package/lib/services/cross-space-context.js +36 -0
  141. package/lib/services/crud-plan.d.ts +137 -0
  142. package/lib/services/crud-plan.js +408 -0
  143. package/lib/services/data-space-check.d.ts +89 -0
  144. package/lib/services/data-space-check.js +162 -0
  145. package/lib/services/data-space-prefix.d.ts +77 -0
  146. package/lib/services/data-space-prefix.js +127 -0
  147. package/lib/services/data-transform-space.d.ts +31 -0
  148. package/lib/services/data-transform-space.js +79 -0
  149. package/lib/services/delete-calculated-insight.d.ts +44 -0
  150. package/lib/services/delete-calculated-insight.js +101 -0
  151. package/lib/services/delete-data-transform.d.ts +52 -0
  152. package/lib/services/delete-data-transform.js +222 -0
  153. package/lib/services/delete-dmo-field.d.ts +211 -0
  154. package/lib/services/delete-dmo-field.js +472 -0
  155. package/lib/services/delete-identity-resolution.d.ts +43 -0
  156. package/lib/services/delete-identity-resolution.js +295 -0
  157. package/lib/services/delete-segment.d.ts +42 -0
  158. package/lib/services/delete-segment.js +248 -0
  159. package/lib/services/deploy-result.d.ts +54 -0
  160. package/lib/services/deploy-result.js +60 -0
  161. package/lib/services/escaped-copy.d.ts +23 -0
  162. package/lib/services/escaped-copy.js +88 -0
  163. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  164. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  165. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  166. package/lib/services/execute-data-transform-deploy.js +168 -0
  167. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  168. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  169. package/lib/services/execute-segment-deploy.d.ts +45 -0
  170. package/lib/services/execute-segment-deploy.js +393 -0
  171. package/lib/services/local-file-removal.d.ts +36 -0
  172. package/lib/services/local-file-removal.js +103 -0
  173. package/lib/services/native-calculated-insight.d.ts +87 -0
  174. package/lib/services/native-calculated-insight.js +164 -0
  175. package/lib/services/native-crm-data-stream.d.ts +91 -0
  176. package/lib/services/native-crm-data-stream.js +272 -0
  177. package/lib/services/native-data-graph-context.d.ts +12 -0
  178. package/lib/services/native-data-graph-context.js +139 -0
  179. package/lib/services/native-data-graph-crd.d.ts +261 -0
  180. package/lib/services/native-data-graph-crd.js +866 -0
  181. package/lib/services/native-data-stream.d.ts +329 -0
  182. package/lib/services/native-data-stream.js +1830 -0
  183. package/lib/services/native-dlo.d.ts +163 -0
  184. package/lib/services/native-dlo.js +402 -0
  185. package/lib/services/native-dmo.d.ts +191 -0
  186. package/lib/services/native-dmo.js +614 -0
  187. package/lib/services/native-mapping.d.ts +255 -0
  188. package/lib/services/native-mapping.js +1226 -0
  189. package/lib/services/native-relationship.d.ts +132 -0
  190. package/lib/services/native-relationship.js +512 -0
  191. package/lib/services/operation-diagnostic.d.ts +83 -0
  192. package/lib/services/operation-diagnostic.js +272 -0
  193. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  194. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  195. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  196. package/lib/services/preflight-data-transform-deploy.js +104 -0
  197. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  198. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  199. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  200. package/lib/services/preflight-segment-deploy.js +109 -0
  201. package/lib/services/publish-calculated-insight.d.ts +40 -0
  202. package/lib/services/publish-calculated-insight.js +95 -0
  203. package/lib/services/publish-segment.d.ts +65 -0
  204. package/lib/services/publish-segment.js +194 -0
  205. package/lib/services/readback-pace.d.ts +16 -0
  206. package/lib/services/readback-pace.js +23 -0
  207. package/lib/services/retrieve-data-transform.d.ts +26 -0
  208. package/lib/services/retrieve-data-transform.js +65 -0
  209. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  210. package/lib/services/retrieve-identity-resolution.js +87 -0
  211. package/lib/services/retrieve-inventory.d.ts +32 -0
  212. package/lib/services/retrieve-inventory.js +151 -0
  213. package/lib/services/retrieve-segment.d.ts +120 -0
  214. package/lib/services/retrieve-segment.js +502 -0
  215. package/lib/services/segment-lookup.d.ts +46 -0
  216. package/lib/services/segment-lookup.js +108 -0
  217. package/lib/services/segment-members.d.ts +144 -0
  218. package/lib/services/segment-members.js +402 -0
  219. package/lib/services/select-native-retrieve.d.ts +60 -0
  220. package/lib/services/select-native-retrieve.js +226 -0
  221. package/lib/services/settle-calculated-insight.d.ts +22 -0
  222. package/lib/services/settle-calculated-insight.js +53 -0
  223. package/lib/services/sql-tokens.d.ts +58 -0
  224. package/lib/services/sql-tokens.js +147 -0
  225. package/lib/transport/api-version.d.ts +36 -0
  226. package/lib/transport/api-version.js +89 -0
  227. package/lib/transport/bound-ssot.d.ts +27 -0
  228. package/lib/transport/bound-ssot.js +116 -0
  229. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  230. package/lib/transport/calculated-insight-rest.js +62 -0
  231. package/lib/transport/connect-client.d.ts +94 -32
  232. package/lib/transport/connect-client.js +318 -178
  233. package/lib/transport/connect-diagnostic.d.ts +89 -0
  234. package/lib/transport/connect-diagnostic.js +331 -0
  235. package/lib/transport/data-graph-rest.d.ts +27 -0
  236. package/lib/transport/data-graph-rest.js +76 -0
  237. package/lib/transport/data-stream-rest.d.ts +62 -0
  238. package/lib/transport/data-stream-rest.js +348 -0
  239. package/lib/transport/data-transform-rest.d.ts +25 -0
  240. package/lib/transport/data-transform-rest.js +100 -0
  241. package/lib/transport/dlo-native-rest.d.ts +22 -0
  242. package/lib/transport/dlo-native-rest.js +89 -0
  243. package/lib/transport/dlo-rest.d.ts +23 -0
  244. package/lib/transport/dlo-rest.js +135 -0
  245. package/lib/transport/dmo-native-rest.d.ts +18 -0
  246. package/lib/transport/dmo-native-rest.js +55 -0
  247. package/lib/transport/dmo-rest.d.ts +30 -0
  248. package/lib/transport/dmo-rest.js +163 -0
  249. package/lib/transport/mapping-rest.d.ts +63 -0
  250. package/lib/transport/mapping-rest.js +341 -0
  251. package/lib/transport/project-metadata.d.ts +36 -0
  252. package/lib/transport/project-metadata.js +118 -0
  253. package/lib/transport/relationship-rest.d.ts +43 -0
  254. package/lib/transport/relationship-rest.js +201 -0
  255. package/package.json +29 -6
  256. package/lib/artifacts/dmo-document.d.ts +0 -181
  257. package/lib/artifacts/dmo-document.js +0 -848
  258. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  259. package/lib/artifacts/dmo-update-delta.js +0 -86
  260. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  261. package/lib/artifacts/write-other-dmo.js +0 -140
  262. package/lib/services/execute-dmo-create.d.ts +0 -24
  263. package/lib/services/execute-dmo-create.js +0 -118
  264. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  265. package/lib/services/execute-dmo-deploy.js +0 -197
  266. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  267. package/lib/services/preflight-dmo-deploy.js +0 -161
  268. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  269. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -1,34 +1,216 @@
1
+ import { DataTransformError, dataTransformName } from '../../artifacts/data-transform-document.js';
2
+ import { writeDataTransformDocument } from '../../artifacts/write-data-transform.js';
3
+ import { retrieveDataTransform } from '../../services/retrieve-data-transform.js';
4
+ import { createDataTransformClient } from '../../transport/data-transform-rest.js';
5
+ import { dataTransformSpaceMismatch } from '../../artifacts/data-transform-document.js';
6
+ import { nativeDataGraphReadContext } from '../../services/native-data-graph-context.js';
7
+ import { getConnectDiagnostic, retainConnectDiagnostic, } from '../../transport/connect-diagnostic.js';
8
+ import { retrieveNativeDataGraph } from '../../services/command-native-data-graph.js';
9
+ import { explanationOf, operationDiagnostic } from '../../services/operation-diagnostic.js';
10
+ import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js';
11
+ import { dataStreamApiVersion, nativeApiVersion } from '../../transport/api-version.js';
12
+ import { DataStreamError } from '../../artifacts/data-stream-document.js';
13
+ import { writeDataStreamDocument } from '../../artifacts/write-data-stream.js';
14
+ import { retrieveDataStreamDocument } from '../../services/native-crm-data-stream.js';
15
+ import { createDataStreamClient, createDataStreamReferenceReader, } from '../../transport/data-stream-rest.js';
16
+ import { sortedStreamMappings, streamSpaces, } from '../../services/native-data-stream.js';
17
+ import { listNativeNames, listNativeMappingNames } from '../../services/select-native-retrieve.js';
18
+ import { labelRetrievedMappings, retrieveLeanNativeMapping, } from '../../services/native-mapping.js';
19
+ import { createMappingClient, createMappingInventoryReader } from '../../transport/mapping-rest.js';
20
+ import { writeNativeMappingDocument } from '../../artifacts/write-native-mapping.js';
21
+ import { NativeMappingError, nativeMappingName } from '../../artifacts/native-mapping-document.js';
22
+ import { nativeDmoName, NativeDmoError } from '../../artifacts/native-dmo-document.js';
23
+ import { retrieveNativeDmo } from '../../services/native-dmo.js';
24
+ import { createDmoClient } from '../../transport/dmo-rest.js';
25
+ import { writeNativeDmoDocument } from '../../artifacts/write-native-dmo.js';
26
+ import { dloName, DloError } from '../../artifacts/dlo-document.js';
27
+ import { reportedIdentity } from '../../artifacts/data-space-field.js';
28
+ import { retrieveNativeDlo } from '../../services/native-dlo.js';
29
+ import { DataSpaceError, dataSpaceCheckCode, dataSpaceCheckOf, } from '../../services/data-space-check.js';
30
+ import { prefixMismatch, prefixMismatchWarning, prefixRuleCoversName, prefixRuleCoversRead, } from '../../services/data-space-prefix.js';
31
+ import { createDloClient } from '../../transport/dlo-rest.js';
32
+ import { writeDloDocument } from '../../artifacts/write-dlo.js';
33
+ import { NativeRelationshipError, relationshipDmoName, } from '../../artifacts/native-relationship-document.js';
34
+ import { writeNativeRelationshipDocument } from '../../artifacts/write-native-relationship.js';
35
+ import { labelRelationships, readLabels, relationshipLabelNames, retrieveUnlabelledRelationships, } from '../../services/native-relationship.js';
36
+ import { createRelationshipClient, relationshipReadBatch, } from '../../transport/relationship-rest.js';
37
+ import { openBoundSsot } from '../../transport/bound-ssot.js';
38
+ import { withCheckedDirectories } from '../../transport/project-metadata.js';
39
+ import { readInOrder } from '../../services/bounded-reads.js';
40
+ import { MappingDefinitionError } from '../../artifacts/write-mapping-definition.js';
41
+ import { mappingName } from '../../artifacts/mapping-document.js';
42
+ import { writeDataGraphDocument } from '../../artifacts/write-data-graph.js';
43
+ import { DataGraphError } from '../../artifacts/data-graph-document.js';
1
44
  import path from 'node:path';
45
+ import { calculatedInsightName, CalculatedInsightError, } from '../../artifacts/native-calculated-insight-document.js';
46
+ import { listCalculatedInsightNames, retrieveNativeCalculatedInsight, } from '../../services/native-calculated-insight.js';
47
+ import { createCalculatedInsightClient } from '../../transport/calculated-insight-rest.js';
48
+ import { writeNativeCalculatedInsightDocument } from '../../artifacts/write-native-calculated-insight.js';
2
49
  import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
3
- import { Org } from '@salesforce/core';
4
- import { DmoDocumentError } from '../../artifacts/dmo-document.js';
5
- import { DmoWriteError, writeDmoDocument } from '../../artifacts/write-other-dmo.js';
6
- import { DmoRetrieveError, retrieveDmo, selectDmos, validateDmoSelection, } from '../../services/retrieve-other-dmo.js';
7
- import { ConnectError } from '../../transport/connect-client.js';
50
+ import { AuthInfo, ConfigAggregator, Connection, StateAggregator } from '@salesforce/core';
51
+ import { operationApiVersion, resolveApiVersion } from '../../transport/api-version.js';
52
+ import { IdentityResolutionError, identityResolutionName, identityResolutionSpace, identityResolutionSpaceMismatch, validateIdentityResolutionDocument, } from '../../artifacts/identity-resolution-document.js';
53
+ import { listIdentityResolutionNames, retrieveIdentityResolution, } from '../../services/retrieve-identity-resolution.js';
54
+ import { writeIdentityResolutionDocument } from '../../artifacts/write-identity-resolution.js';
55
+ import { ConnectClient, ConnectError } from '../../transport/connect-client.js';
8
56
  import { plugin as packageMetadata } from '../../plugin.js';
57
+ import { SegmentError, segmentName } from '../../artifacts/segment-document.js';
58
+ import { writeSegmentDocument } from '../../artifacts/write-segment.js';
59
+ import { listSegmentNames, retrieveSegment } from '../../services/retrieve-segment.js';
60
+ import { listDataGraphNames, listDataStreamNames, listDataTransformNames, } from '../../services/retrieve-inventory.js';
61
+ import { acquireRetrieveSelection, RetrieveSelectionError, } from '../../services/acquire-retrieve-selection.js';
62
+ import { DependencySelectionError } from '../../artifacts/dependency-selection.js';
63
+ import { carriedNativeResponse, carryNativeResponse, createVerbatimDocument, isVerbatimDocument, nativeReadRecorder, recordNativeReads, verbatimFamily, verbatimReason, } from '../../artifacts/verbatim-document.js';
64
+ import { localFilePresent } from '../../services/local-file-removal.js';
65
+ /**
66
+ * The value of a settled read, or what it threw.
67
+ * @template T
68
+ * @param {Promise<SettledRead<T>>} read One outcome of readInOrder.
69
+ * @returns {Promise<T>} The read's value.
70
+ */
71
+ async function settledValue(read) {
72
+ const outcome = await read;
73
+ if ('error' in outcome)
74
+ throw outcome.error;
75
+ return outcome.value;
76
+ }
77
+ // Before an item's client exists nothing was read.
78
+ const noReads = new Map();
79
+ const nothingRead = (name) => noReads.get(name);
80
+ /** Name the actual reason a calculated insight was not exported. */
81
+ const calculatedInsightRetrieveMessages = {
82
+ CI_NOT_FOUND: 'The calculated insight was not found in the target org; no files were written.',
83
+ CI_RUNTIME_UNKNOWN: 'The calculated insight could not be read; no files were written.',
84
+ };
85
+ const retrieveFamilies = [
86
+ 'dlo',
87
+ 'dmo',
88
+ 'mapping',
89
+ 'relationship',
90
+ 'segment',
91
+ 'calculated-insight',
92
+ 'identity-resolution',
93
+ 'data-stream',
94
+ 'data-transform',
95
+ 'data-graph',
96
+ ];
97
+ const nativeFamilies = ['dlo', 'dmo', 'mapping'];
98
+ // Relationship reads in flight at once during one retrieve (bounded; see readInOrder).
99
+ const relationshipReads = 6;
100
+ // Mappings read at once during one retrieve (each: its GET and its parents' reads).
101
+ const mappingReads = 6;
102
+ /** Selector groups, in run order; `rest` holds every family without its own group. */
103
+ const selectorGroups = ['rest', 'data-stream', 'data-transform', 'data-graph'];
104
+ /**
105
+ * The family a selector names; selectors of no known family are DMO selectors.
106
+ * @param {string | undefined} selector Selector such as `dmo:Name__dlm`.
107
+ * @returns {RetrieveFamily} Its family.
108
+ */
109
+ function selectorFamily(selector) {
110
+ const prefix = (selector ?? 'dmo').split(':')[0];
111
+ return retrieveFamilies.find((family) => family === prefix) ?? 'dmo';
112
+ }
113
+ /**
114
+ * Whether a selector belongs to a group: the bare group name or `group:Name`.
115
+ * @param {string} group Group name.
116
+ * @param {string} value Selector.
117
+ * @returns {boolean} Membership.
118
+ */
119
+ function inGroup(group, value) {
120
+ return value === group || value.startsWith(`${group}:`);
121
+ }
122
+ /**
123
+ * Split the selection into groups in run order; groups without selectors are left out, and an
124
+ * empty selection is the rest group alone (every native family).
125
+ * @param {string[]} selectors Every -m selector.
126
+ * @returns {Array<[string, string[]]>} Non-empty groups in run order.
127
+ */
128
+ function groupSelectors(selectors) {
129
+ return selectorGroups
130
+ .map((group) => [
131
+ group,
132
+ group === 'rest'
133
+ ? selectors.filter((value) => !selectorGroups.some((other) => other !== 'rest' && inGroup(other, value)))
134
+ : selectors.filter((value) => inGroup(group, value)),
135
+ ])
136
+ .filter(([group, members]) => members.length > 0 || (group === 'rest' && selectors.length === 0));
137
+ }
138
+ /**
139
+ * Status of one group from the diagnostics it added.
140
+ * @param {RetrieveEnvelope} envelope Shared envelope.
141
+ * @param {number} before Diagnostics count when the group started.
142
+ * @param {boolean} failed Whether a failure was not local to one output.
143
+ * @returns {'success' | 'blocked' | 'failed'} Group status.
144
+ */
145
+ function groupStatus(envelope, before, failed) {
146
+ return envelope.diagnostics.errors.length === before ? 'success' : failed ? 'failed' : 'blocked';
147
+ }
148
+ /**
149
+ * Message of a diagnostic without a more specific explanation.
150
+ * @param {unknown} error Cause, whose safe Salesforce detail is kept.
151
+ * @returns {string} Payload-free message.
152
+ */
153
+ function retrievalMessage(error) {
154
+ const fallback = 'Retrieval did not complete. Check selection, authenticated org, service capability and output path.';
155
+ return error === undefined ? fallback : operationDiagnostic(error, fallback);
156
+ }
157
+ /**
158
+ * Name the code of the error behind a family-level diagnostic, so the cause stays visible.
159
+ * @param {string} message Diagnostic message.
160
+ * @param {unknown} error Cause.
161
+ * @returns {string} The message, followed by `Cause: <CODE>.` when the cause has a code.
162
+ */
163
+ function withInnerCode(message, error) {
164
+ const code = error?.code;
165
+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]{0,99}$/u.test(code)
166
+ ? `${message} Cause: ${code}.`
167
+ : message;
168
+ }
169
+ /**
170
+ * Code of a native inventory that could not be read.
171
+ * @param {unknown} error Cause.
172
+ * @returns {string} Its mapping code, or NATIVE_INVENTORY_FAILED.
173
+ */
174
+ function inventoryCode(error) {
175
+ return error instanceof NativeMappingError ? error.code : 'NATIVE_INVENTORY_FAILED';
176
+ }
9
177
  /** Retrieve selected DMO configuration through existing service-owned capability checks. */
178
+ /**
179
+ * The raw stream GET a verbatim file keeps, with its mappings in a stable order.
180
+ * @param {unknown} response Stream GET body.
181
+ * @returns {{ native: unknown }} Response with sorted mappings.
182
+ */
183
+ function verbatimStreamNative(response) {
184
+ if (!response || typeof response !== 'object' || Array.isArray(response))
185
+ return { native: response };
186
+ const body = response;
187
+ return Array.isArray(body.mappings)
188
+ ? { native: { ...body, mappings: sortedStreamMappings(body.mappings) } }
189
+ : { native: response };
190
+ }
10
191
  export default class Retrieve extends SfCommand {
11
192
  static aliases = ['datacloud:retrieve', 'd360:retrieve', 'dc:retrieve'];
12
- static summary = 'Retrieve Data360 DMOs into a local project.';
13
- static description = 'Repeat -m dmo:ApiName for exact selection, use -m dmo for all DMOs in the selected space, or omit selectors for all implemented families (currently DMO only). Unsupported objects produce per-object diagnostics and a nonzero aggregate while successful files are retained. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.';
193
+ static summary = 'Retrieve any mix of Data360 DLOs, DMOs, mappings, relationships, data streams, data transforms, data graphs, Segments, calculated insights and identity resolution configuration.';
194
+ static description = 'Any mix of selectors is retrieved in one run with one result: every selector is checked before the org is read, and a refused selector blocks the whole run (with several families selected, the refusal names its family). The families are then read one after another (DLO, DMO, mapping, relationship, Segment, calculated insight and identity resolution first, then data streams, data transforms and data graphs), each with its own API version and data space rules; one family failing does not stop the others. Exact -m data-transform:Name retrieves a transform (custom, system or packaged) at API68 in the run data space (c__dataSpace: its dataSpaceName or, without one, the data space of its MktDataTransform record read with SOQL; one without any data space is handled in default only; another data space is TRANSFORM_DATASPACE_MISMATCH, never a verbatim file) into data360/dataTransforms/<Name>.dataTransform.json: its create/update input as Salesforce returns it (definition or definitions, fullRunFrequency, write mode and the rest as read), without server-owned output object fields, plus its schedule projected onto the keys the schedule PUT takes (no schedule key when the transform has none, so a deploy of the file leaves the schedule alone; also left out, with a warning, when the schedule read fails). A transform with both definition and definitions is written as-is (verbatim), and deploy refuses that file. Bare -m data-transform retrieves every transform of the run data space the API lists (kept by the dataSpaceName of each entry, or its MktDataTransform record for an entry without one), each through the same path; one failing transform never blocks the others. Exact -m data-stream:ApiName retrieves an Ingestion API stream (any refresh mode and DLO category) as portable JSON using native API68 reads, when its DLO belongs to the run data space (the file lists every data space of the DLO in c__dataSpace); a stream of any other connector (for example Salesforce CRM, SalesforceDotCom) is written as its GET without server-owned keys and the system fields and mappings Salesforce adds, formulas decoded. Bare -m data-stream retrieves every stream the API lists (unless its DLO names only other data spaces), each through the same path. Native DLO, DMO and mapping retrieval writes canonical JSON under data360/<type>, retaining definition fields without source record IDs. A DLO file lists every data space the DLO belongs to in its top-level c__dataSpace key; the DLOs of the run data space are retrieved. Every retrieve first checks that the org has the run data space (one GET /ssot/data-spaces; UNKNOWN_DATASPACE otherwise). Default/auto uses API68; explicit numeric versions >=61 are preserved, and <=60 is rejected before calls. Omit selectors for all three native families, use -m dlo, -m dmo or -m mapping for complete type inventory, or repeat type:ApiName for exact selections. Omitted selectors and -m dlo (also beside other families) retrieve every DLO the Data 360 API lists in the data space, connector- and stream-created ones included; a DLO whose read or file fails gets its own diagnostic and the others are still retrieved. Mapping JSON uses the native APIs; only its label (spec.label) is read with the Metadata API (readMetadata of ObjectSourceTargetMap, up to 10 names per call), left out when it equals the mapping name (the default) and, with a warning, when that read fails. DMOs retrieved beside other families use the same native JSON at the native version. Prerequisites are checked, never pulled in; select every component to retrieve explicitly. Every DMO selection uses this native route, and --api-version latest is not accepted. Exact -m relationship:Dmo__dlm writes every relationship whose source is that DMO as native JSON under data360/relationship/<Name>.relationship-meta.json; bare -m relationship does so for every DMO the API lists, one DMO after another. Repeat -m dmo:ApiName, -m segment:ApiName, -m calculated-insight:ApiName__cio, -m data-graph:ApiName or -m identity-resolution:ExactObjectApiName for exact selection. Graph retrieval uses native API68 (auto or explicit 68.0; other versions are rejected) and writes *.native-dataGraph.json authored intent without generated identities in the run data space (c__dataSpace, and definition.dataspaceName as read; a graph of another data space is DATA_GRAPH_DATASPACE_MISMATCH, never a verbatim file); repeat data-graph:ApiName for several graphs, read one after another. Bare -m data-graph retrieves every graph of the run data space the API lists. Calculated insights use the API68 GET only (auto or 68.0, in the run data space, written to c__dataSpace): -m calculated-insight:ApiName__cio retrieves that insight and bare -m calculated-insight every insight the API lists, whatever its status, schedule or SQL; each is written as data360/calculatedInsights/<ApiName>.calculatedInsight-meta.json (the GET body as returned, without status, run history, source-CI links, creation type, sub type and the dimensions and measures Salesforce derives from the SQL) plus its SQL as plain text in <ApiName>.calculatedInsight-meta.sql. IR uses native API68 owner reads in the run data space (c__dataSpace; the file keeps the names Salesforce stores, ds2_Individual_<id> and ds2_Individual__dlm outside default; a ruleset of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH, never a verbatim file); auto and explicit numeric68 are supported, while numeric67 is rejected. -m identity-resolution:ExactObjectApiName retrieves that ruleset and bare -m identity-resolution every ruleset of the run data space the API lists (kept by the dataSpaceName of each entry, as the list answers every data space). Auto selects fixed qualified routes, never probes or upgrades an explicit numeric pin. Segment uses auto or 68.0 in the run data space (c__dataSpace; a segment of another data space is SEGMENT_DATASPACE_MISMATCH; the file carries the stored name, <prefix>_<Name> in a non-default data space; other versions are refused): -m segment:ApiName retrieves that segment and bare -m segment every segment of the run data space the API lists (kept by the dataSpace of each entry). A SQL (DBT) segment is written as one portable data360/segments/<Name>.segment.json with its DBT model names, and the SQL of each model as Salesforce returns it in <Name>.segment.<model>.sql beside it; a UI segment (built in the segment canvas) is written as a normal <Name>.segment.json with its criteria as JSON. Any other segment type is written with the same keys, without SQL files (a Waterfall with its child segments by API name in childSegments, named with one segment list read); the lookback and the refresh schedule are kept (schedule in the write shape; no schedule key for a segment that does not refresh), and a key the plugin does not know stays in the file and deploy refuses it. A segment with parameters (no write takes them), schedule details the plugin does not know or UI criteria that are not a JSON object is written as-is (verbatim) and deploy refuses that file. Use -m dmo or omit selectors for existing DMO inventory; omitted selectors do not include segments. Unsupported objects produce per-object diagnostics and a nonzero aggregate while successful files are retained. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.';
14
195
  static flags = {
15
196
  'target-org': Flags.string({
16
197
  char: 'o',
17
198
  summary: 'Authenticated org alias or username; defaults to the configured target org.',
18
199
  }),
19
200
  'api-version': Flags.orgApiVersion({
20
- default: '65.0',
21
- summary: 'Explicit Salesforce API version (current service supports 65.0).',
201
+ default: 'auto',
202
+ summary: 'Native default/auto 68.0 or an explicit numeric pin (native minimum 61.0); other families keep their qualified versions.',
203
+ parse: async (value, context, options) => value === 'auto' ? value : Flags.orgApiVersion().parse(value, context, options),
22
204
  }),
23
- 'data-space': Flags.string({
24
- default: 'default',
25
- summary: 'Logical data space (current service supports default).',
205
+ dataspace: Flags.string({
206
+ aliases: ['data-space'],
207
+ summary: 'The run data space; omitted means default (never all data spaces), and the org must have it. --data-space is a compatibility alias. Every family is retrieved in it (a DLO or stream belongs to it when the DLO lists it).',
26
208
  }),
27
209
  metadata: Flags.string({
28
210
  char: 'm',
29
211
  multiple: true,
30
212
  multipleNonGreedy: true,
31
- summary: 'Repeat dmo[:ApiName]; omitted selectors retrieve all implemented families.',
213
+ summary: 'Repeat to mix families in one run. Native dlo/dmo/mapping type or type:ApiName JSON selections; bare dlo is every DLO the API lists; omitted selects all native families. relationship:Dmo__dlm (relationships whose source is that DMO), data-stream:ApiName, data-transform:Name, data-graph:ApiName, segment:ApiName, identity-resolution:ExactObjectApiName and calculated-insight:ApiName__cio, or the bare family name for every one the API lists (bare relationship: those of every listed DMO).',
32
214
  }),
33
215
  'output-dir': Flags.directory({
34
216
  char: 'd',
@@ -41,23 +223,1601 @@ export default class Retrieve extends SfCommand {
41
223
  summary: 'Permit replacing differing selected files.',
42
224
  }),
43
225
  };
44
- acquire = retrieveDmo;
45
- selectDocuments = selectDmos;
46
- resolveOrg = (aliasOrUsername) => Org.create({ aliasOrUsername });
47
- writeDocument = writeDmoDocument;
226
+ acquireDataTransform = retrieveDataTransform;
227
+ createDataTransformClient = createDataTransformClient;
228
+ writeDataTransform = writeDataTransformDocument;
229
+ nativeGraphContext = nativeDataGraphReadContext;
230
+ retrieveNativeGraph = retrieveNativeDataGraph;
231
+ acquireDataStream = retrieveDataStreamDocument;
232
+ writeDataStream = writeDataStreamDocument;
233
+ createDataStreamClients = (connection, target, version) => {
234
+ const reader = new ConnectClient(connection, version);
235
+ return {
236
+ streams: createDataStreamClient(target, reader, version),
237
+ ...createDataStreamReferenceReader(reader, version),
238
+ dlo: {
239
+ get: (name) => reader.get(`/services/data/v${version}/ssot/data-lake-objects/${name}`),
240
+ },
241
+ };
242
+ };
243
+ acquireNativeDmo = retrieveNativeDmo;
244
+ createDmoClient = createDmoClient;
245
+ writeNativeDmo = writeNativeDmoDocument;
246
+ acquireDlo = retrieveNativeDlo;
247
+ createDloClient = createDloClient;
248
+ writeDlo = writeDloDocument;
249
+ // Authored pairs only: the generated pairs are decided from fresh source DLO and target DMO reads.
250
+ acquireNativeMapping = retrieveLeanNativeMapping;
251
+ createMappingClient = createMappingClient;
252
+ createMappingInventoryReader = createMappingInventoryReader;
253
+ writeNativeMapping = writeNativeMappingDocument;
254
+ // Native DLO/DMO/mapping reads share one bound sender per org and version on the run's own
255
+ // authenticated Connection instead of one CLI process per read. Tests replace this seam.
256
+ createSsotSender = openBoundSsot;
257
+ ssotSenders;
258
+ /**
259
+ * One shared bound sender per org and API version.
260
+ * @param {string} target Target org alias or username.
261
+ * @param {string} version Numeric API version.
262
+ * @param {Connection} connection The run's authenticated Connection for that org.
263
+ * @returns {BoundSsot} Shared sender.
264
+ */
265
+ ssotSender(target, version, connection) {
266
+ const key = `${target}\n${version}`;
267
+ // Tests build commands without field initializers, so both fields may be absent.
268
+ this.ssotSenders ??= new Map();
269
+ let sender = this.ssotSenders.get(key);
270
+ if (!sender) {
271
+ sender = (this.createSsotSender ?? openBoundSsot)(target, version, async () => connection);
272
+ this.ssotSenders.set(key, sender);
273
+ }
274
+ return sender;
275
+ }
276
+ /**
277
+ * Readers of a mapping's source DLO and target DMO; clients are created on the first read.
278
+ * @param {string} target Target org alias or username.
279
+ * @param {string} version Native API version.
280
+ * @param {BoundSsot} sender Shared bound sender for the reads.
281
+ * @param {ListedEntries} [listed] This run's DLO and DMO listing entries at the same version.
282
+ * @param {Map<string, Promise<unknown>>} [shared] This run's parent reads: a DLO or DMO that
283
+ * several mappings name is read once (a failed read is not kept); each caller gets a copy.
284
+ * @returns {MappingDependencies} Lazy source and target readers.
285
+ */
286
+ mappingParents(target, version, sender, listed, shared) {
287
+ const once = async (key, read) => {
288
+ if (!shared)
289
+ return read();
290
+ let pending = shared.get(key);
291
+ if (!pending) {
292
+ const started = read();
293
+ pending = started;
294
+ shared.set(key, started);
295
+ started.catch(() => {
296
+ if (shared.get(key) === started)
297
+ shared.delete(key);
298
+ });
299
+ }
300
+ return structuredClone(await pending);
301
+ };
302
+ return {
303
+ source: {
304
+ get: async (name) => once(`dlo:${name}`, async () => (this.createDloClient ?? createDloClient)(target, version, sender, listed?.dlo).get(name)),
305
+ },
306
+ target: {
307
+ get: async (name) => once(`dmo:${name}`, async () => (this.createDmoClient ?? createDmoClient)(target, version, undefined, sender, listed?.dmo).get(name)),
308
+ },
309
+ };
310
+ }
311
+ listNativeNames = listNativeNames;
312
+ listNativeMappingNames = listNativeMappingNames;
313
+ acquireRelationships = retrieveUnlabelledRelationships;
314
+ /**
315
+ * A relationship client on the run's shared bound sender: every DMO's reads go through one
316
+ * in-process connection, never a CLI process. Tests replace this seam.
317
+ * @param {Connection} connection The run's authenticated Connection.
318
+ * @param {string} target Target org alias or username.
319
+ * @param {string} version Native API version.
320
+ * @param {string} dataSpace The run's data space.
321
+ * @returns {ReturnType<typeof createRelationshipClient>} Relationship client.
322
+ */
323
+ createRelationshipClient(connection, target, version, dataSpace) {
324
+ return createRelationshipClient(target, version, dataSpace, this.ssotSender(target, version, connection));
325
+ }
326
+ writeRelationship = writeNativeRelationshipDocument;
327
+ writeDataGraph = writeDataGraphDocument;
328
+ createCalculatedInsightClient = createCalculatedInsightClient;
329
+ acquireCalculatedInsight = retrieveNativeCalculatedInsight;
330
+ listCalculatedInsightNames = listCalculatedInsightNames;
331
+ // Optional: tests built with Object.create skip class fields and fall back to the real listing.
332
+ listSegmentNames;
333
+ listIdentityResolutionNames;
334
+ listDataStreamNames;
335
+ listDataTransformNames;
336
+ listDataGraphNames;
337
+ writeCalculatedInsight = writeNativeCalculatedInsightDocument;
338
+ acquireIdentityResolution = retrieveIdentityResolution;
339
+ writeIdentityResolution = writeIdentityResolutionDocument;
340
+ acquireSegment = retrieveSegment;
341
+ acquireSelection = acquireRetrieveSelection;
342
+ writeSegment = writeSegmentDocument;
343
+ resolveOrg = async (aliasOrUsername) => {
344
+ const aggregator = await ConfigAggregator.create();
345
+ const state = await StateAggregator.getInstance();
346
+ const target = aliasOrUsername ?? aggregator.getPropertyValue('target-org');
347
+ const username = target ? state.aliases.resolveUsername(target) : undefined;
348
+ const connection = await Connection.create({
349
+ authInfo: await AuthInfo.create({ username }),
350
+ connectionOptions: { version: '68.0' },
351
+ });
352
+ // Org.create also probes org traits using another unversioned connection; avoid it.
353
+ return {
354
+ getOrgId: () => connection.getAuthInfoFields().orgId,
355
+ getConnection: (version) => {
356
+ if (version)
357
+ connection.setApiVersion(version);
358
+ return connection;
359
+ },
360
+ };
361
+ };
362
+ /**
363
+ * The writer of a document kind; every writer also writes a verbatim document of its kind.
364
+ * @param {VerbatimKind} kind Document kind.
365
+ * @returns {DocumentWriter} Family writer.
366
+ */
367
+ documentWriter(kind) {
368
+ const writers = {
369
+ dlo: this.writeDlo ?? writeDloDocument,
370
+ dmo: this.writeNativeDmo ?? writeNativeDmoDocument,
371
+ mapping: this.writeNativeMapping ?? writeNativeMappingDocument,
372
+ relationship: this.writeRelationship ?? writeNativeRelationshipDocument,
373
+ 'data-stream': this.writeDataStream ?? writeDataStreamDocument,
374
+ 'data-transform': this.writeDataTransform ?? writeDataTransformDocument,
375
+ 'native-data-graph': this.writeDataGraph ?? writeDataGraphDocument,
376
+ 'calculated-insight': this.writeCalculatedInsight ?? writeNativeCalculatedInsightDocument,
377
+ 'identity-resolution': this.writeIdentityResolution ?? writeIdentityResolutionDocument,
378
+ segment: this.writeSegment ?? writeSegmentDocument,
379
+ };
380
+ return writers[kind];
381
+ }
382
+ /**
383
+ * Warn when a retrieved component that users make themselves (custom DMO, insight, transform,
384
+ * graph) breaks the prefix rule of its data space. The prefixes come from the run's one data
385
+ * space list read; without it, or in an org whose spaces have no prefix, nothing is reported.
386
+ * @param {PrefixType} type Kind of component.
387
+ * @param {string} name Its name.
388
+ * @param {unknown} native Its raw read.
389
+ * @param {string} space The run's data space.
390
+ * @param {string[]} warnings Envelope warnings.
391
+ * @returns {Promise<void>} Resolves once checked.
392
+ */
393
+ async notePrefixMismatch(type, name, native, space, warnings) {
394
+ if (!prefixRuleCoversName(type, name) || !prefixRuleCoversRead(type, native))
395
+ return;
396
+ let spaces;
397
+ try {
398
+ spaces = await dataSpaceCheckOf(this, async () => {
399
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
400
+ }).entries();
401
+ }
402
+ catch {
403
+ return;
404
+ }
405
+ const mismatch = prefixMismatch(name, type, space, spaces);
406
+ if (mismatch)
407
+ warnings.push(prefixMismatchWarning(mismatch));
408
+ }
409
+ /**
410
+ * Report a written verbatim document: a warning naming the reason (and a calculated insight's
411
+ * SQL file left from an earlier retrieve), plus the item marker.
412
+ * @param {VerbatimDocument} document Written verbatim document.
413
+ * @param {string} file Its path.
414
+ * @param {string[]} warnings Envelope warnings.
415
+ * @returns {Promise<{verbatim: {reason: string}}>} Item marker.
416
+ */
417
+ async noteVerbatim(document, file, warnings) {
418
+ let text = `${verbatimFamily(document.kind)}:${document.identity.apiName}: retrieved as-is (verbatim, reason ${document.verbatim.reason}) because the plugin cannot represent it. Deploy skips the file in a folder or Git range and refuses it when it is named.`;
419
+ if (document.kind === 'calculated-insight') {
420
+ const sql = file.replace(/\.json$/u, '.sql');
421
+ if (sql !== file && (await localFilePresent(sql)))
422
+ text += ` The SQL file ${sql} from an earlier retrieve was left in place; remove it when you no longer need it.`;
423
+ }
424
+ warnings.push(text);
425
+ return { verbatim: { reason: document.verbatim.reason } };
426
+ }
427
+ /**
428
+ * The verbatim document for a failed projection or validation, or undefined when the failure
429
+ * stays an item failure (HTTP error, not found, identity/target mismatch, no response read).
430
+ * @param {unknown} error Caught error.
431
+ * @param {{native: unknown} | undefined} read Raw GET response of the item.
432
+ * @param {VerbatimKind} kind Normal document kind.
433
+ * @param {object} identity Normal identity.
434
+ * @param {string} identity.dataSpace Data space.
435
+ * @param {string} identity.apiName API name.
436
+ * @returns {VerbatimDocument | undefined} Verbatim document.
437
+ */
438
+ verbatimFor(error, read, kind, identity) {
439
+ const reason = verbatimReason(error);
440
+ return reason === undefined || read === undefined
441
+ ? undefined
442
+ : createVerbatimDocument(kind, identity, reason, read.native);
443
+ }
444
+ /**
445
+ * Catch-all of every family: an item whose projection or validation failed is written as
446
+ * Salesforce returned it, at its normal path, with a warning; it is not an item failure.
447
+ * @param {unknown} caught Caught error.
448
+ * @param {{native: unknown} | undefined} read Raw GET response of the item.
449
+ * @param {VerbatimTarget} target Kind, identity, routes, output and where to report.
450
+ * @returns {Promise<unknown>} Undefined when written; otherwise the error to report (the
451
+ * original one, or the verbatim write's own).
452
+ */
453
+ async verbatimFallback(caught, read, target) {
454
+ const document = this.verbatimFor(caught, read, target.kind, target.identity);
455
+ if (document === undefined)
456
+ return caught;
457
+ try {
458
+ const receipt = await this.documentWriter(target.kind)(document, target.root, target.overwrite);
459
+ const family = verbatimFamily(target.kind);
460
+ target.push({
461
+ identity: { ...target.identity },
462
+ operation: 'retrieve',
463
+ ...(family === 'dmo' ? {} : { family: family }),
464
+ routes: target.routes,
465
+ ...receipt,
466
+ ...(await this.noteVerbatim(document, receipt.path, target.warnings)),
467
+ });
468
+ return undefined;
469
+ }
470
+ catch (error) {
471
+ return error;
472
+ }
473
+ }
474
+ /**
475
+ * Retrieve every relationship whose source is one of the DMOs, one file each. Each DMO's
476
+ * inventory is read completely before its files are written; failures stay per DMO or file.
477
+ * @param {string[]} dmoNames Exact sorted source DMOs.
478
+ * @param {Connection} connection Command-owned connection for the bound reads.
479
+ * @param {string} target Resolved username.
480
+ * @param {string} version Native API version.
481
+ * @param {string} effectiveScope The run's data space.
482
+ * @param {string} root Project root.
483
+ * @param {boolean} overwrite Permit replacing differing files.
484
+ * @returns {Promise<object>} Items, diagnostics and whether a failure was not local.
485
+ */
486
+ async retrieveRelationshipFamily(dmoNames, connection, target, version, effectiveScope, root, overwrite) {
487
+ const items = [];
488
+ const errors = [];
489
+ const warnings = [];
490
+ let failed = false;
491
+ const diagnose = (error, apiName) => {
492
+ const code = error instanceof NativeRelationshipError ? error.code : 'NATIVE_RETRIEVE_FAILED';
493
+ if (!['OVERWRITE_REQUIRED', 'UNSAFE_PATH'].includes(code))
494
+ failed = true;
495
+ errors.push({
496
+ code,
497
+ message: operationDiagnostic(error, 'Relationship retrieval did not complete for this item; the org was not changed.'),
498
+ retryable: false,
499
+ identity: { dataSpace: effectiveScope, apiName },
500
+ family: 'relationship',
501
+ });
502
+ };
503
+ const client = this.createRelationshipClient(connection, target, version, effectiveScope);
504
+ // Up to relationshipReads DMOs are listed at once; results, files and diagnostics still follow
505
+ // the DMO order, one DMO after another.
506
+ const reads = await Promise.all(readInOrder(dmoNames, relationshipReads, async (dmo) => (this.acquireRelationships ?? retrieveUnlabelledRelationships)(dmo, client, effectiveScope, 'retrieve')));
507
+ // The labels of all DMOs are then read together, up to 10 names per Metadata API read: one
508
+ // read per DMO exhausted the org's hourly Metadata API request limit on a full retrieve.
509
+ const labels = new Map();
510
+ const labelFailures = new Map();
511
+ if (client.readDefinitions) {
512
+ const names = reads.flatMap((read) => 'error' in read ? [] : relationshipLabelNames(read.value));
513
+ for (let start = 0; start < names.length; start += relationshipReadBatch) {
514
+ const batch = names.slice(start, start + relationshipReadBatch);
515
+ try {
516
+ for (const [name, label] of await readLabels(batch, client))
517
+ labels.set(name, label);
518
+ }
519
+ catch (error) {
520
+ for (const name of batch)
521
+ labelFailures.set(name, error);
522
+ }
523
+ }
524
+ }
525
+ for (const [index, dmo] of dmoNames.entries()) {
526
+ const read = reads[index];
527
+ if ('error' in read) {
528
+ diagnose(read.error, dmo);
529
+ continue;
530
+ }
531
+ const failed = relationshipLabelNames(read.value).find((name) => labelFailures.has(name));
532
+ if (failed !== undefined) {
533
+ diagnose(labelFailures.get(failed), dmo);
534
+ continue;
535
+ }
536
+ const documents = labelRelationships(read.value, labels);
537
+ const routes = [
538
+ { operation: 'relationship.list', apiVersion: version, transport: 'native' },
539
+ ];
540
+ for (const document of documents)
541
+ try {
542
+ const receipt = await (this.writeRelationship ?? writeNativeRelationshipDocument)(document, root, overwrite);
543
+ items.push({
544
+ identity: reportedIdentity(document, effectiveScope),
545
+ operation: 'retrieve',
546
+ family: 'relationship',
547
+ routes,
548
+ ...receipt,
549
+ ...(isVerbatimDocument(document)
550
+ ? await this.noteVerbatim(document, receipt.path, warnings)
551
+ : {}),
552
+ });
553
+ }
554
+ catch (error_) {
555
+ const error = await this.verbatimFallback(error_, carriedNativeResponse(document), {
556
+ kind: 'relationship',
557
+ identity: reportedIdentity(document, effectiveScope),
558
+ routes,
559
+ root,
560
+ overwrite,
561
+ warnings,
562
+ push: (item) => items.push(item),
563
+ });
564
+ if (error !== undefined)
565
+ diagnose(error, document.identity.apiName);
566
+ }
567
+ }
568
+ return { items, errors, warnings, failed };
569
+ }
570
+ /**
571
+ * Report a family listing that could not be read; the family's named items are still read.
572
+ * @param {RetrieveEnvelope} envelope Shared envelope.
573
+ * @param {Map<RetrieveDiagnostic, string>} errorTypes Output type of each diagnostic.
574
+ * @param {unknown} error The listing failure.
575
+ * @param {RetrieveFamily} family Family whose listing failed.
576
+ */
577
+ inventoryFailure(envelope, errorTypes, error, family) {
578
+ const diagnostic = {
579
+ code: error instanceof ConnectError ? error.code : inventoryCode(error),
580
+ message: retrievalMessage(error),
581
+ retryable: false,
582
+ family,
583
+ };
584
+ envelope.diagnostics.errors.push(diagnostic);
585
+ errorTypes.set(diagnostic, family);
586
+ }
587
+ /**
588
+ * Validate exact and bare data transform selectors, then read them one after another.
589
+ * @param {string[]} selectors The data-transform group.
590
+ * @param {RetrieveRun} context Shared command state.
591
+ * @returns {GroupPlan} A refusal, or the group's read.
592
+ */
593
+ prepareDataTransforms(selectors, context) {
594
+ const { flags, envelope, outputTypes, errorTypes, effectiveScope, outputDirectory } = context;
595
+ const family = 'data-transform';
596
+ if (selectors.some((value) => value !== 'data-transform' &&
597
+ (!value.startsWith('data-transform:') || !dataTransformName.test(value.slice(15)))))
598
+ return { refusal: 'INVALID_SELECTION', family };
599
+ try {
600
+ operationApiVersion(flags['api-version'], 'data-transform');
601
+ }
602
+ catch {
603
+ return { refusal: 'INVALID_SCOPE', family };
604
+ }
605
+ return {
606
+ family,
607
+ run: async () => {
608
+ let org;
609
+ try {
610
+ org = await this.resolveOrg(flags['target-org']);
611
+ }
612
+ catch {
613
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
614
+ }
615
+ const connection = org.getConnection('68.0');
616
+ envelope.provenance.sourceOrgId ??= org.getOrgId();
617
+ envelope.metadata.soapApiVersion ??= '68.0';
618
+ const before = envelope.diagnostics.errors.length;
619
+ let failed = false;
620
+ const listed = selectors
621
+ .filter((value) => value !== 'data-transform')
622
+ .map((value) => value.slice(15));
623
+ // Bare data-transform: every transform the API lists, each read on its own.
624
+ if (selectors.includes('data-transform'))
625
+ try {
626
+ listed.push(...(await (this.listDataTransformNames ?? listDataTransformNames)(connection, envelope.diagnostics.warnings, effectiveScope)));
627
+ }
628
+ catch (error) {
629
+ failed = true;
630
+ this.inventoryFailure(envelope, errorTypes, error, family);
631
+ }
632
+ const names = [...new Set(listed)];
633
+ names.sort();
634
+ outputTypes.add('data-transform');
635
+ const routes = [
636
+ { operation: 'data-transform.get', apiVersion: '68.0', transport: 'native' },
637
+ {
638
+ operation: 'data-transform.schedule.get',
639
+ apiVersion: '68.0',
640
+ transport: 'native',
641
+ },
642
+ ];
643
+ // One client for the group: the org's transform data spaces (SOQL) are read once.
644
+ let base;
645
+ for (const apiName of names) {
646
+ let nativeOf = nothingRead;
647
+ try {
648
+ base ??= this.createDataTransformClient(connection, '68.0', effectiveScope);
649
+ const reads = recordNativeReads(base);
650
+ nativeOf = reads.nativeOf;
651
+ // The data space is resolved before anything is projected, so a transform of another
652
+ // data space is an item failure, never a verbatim file stamped with the run's space.
653
+ const observed = await this.acquireDataTransform(apiName, reads.client, 'retrieve', envelope.diagnostics.warnings, effectiveScope);
654
+ if (observed.document.definition.name !== apiName)
655
+ throw new DataTransformError('TRANSFORM_IDENTITY_MISMATCH');
656
+ // A transform of another data space is an item failure; nothing is written.
657
+ if (observed.document.c__dataSpace !== effectiveScope)
658
+ throw dataTransformSpaceMismatch(apiName, observed.document.c__dataSpace, effectiveScope);
659
+ const receipt = await this.writeDataTransform(observed.document, outputDirectory, flags.overwrite);
660
+ envelope.result.items.push({
661
+ identity: { dataSpace: effectiveScope, apiName },
662
+ operation: 'retrieve',
663
+ family: 'data-transform',
664
+ routes,
665
+ ...receipt,
666
+ });
667
+ await this.notePrefixMismatch('data-transform', apiName, nativeOf(apiName)?.native, effectiveScope, envelope.diagnostics.warnings);
668
+ }
669
+ catch (error_) {
670
+ const error = await this.verbatimFallback(error_, nativeOf(apiName), {
671
+ kind: 'data-transform',
672
+ identity: { dataSpace: effectiveScope, apiName },
673
+ routes,
674
+ root: outputDirectory,
675
+ overwrite: flags.overwrite,
676
+ warnings: envelope.diagnostics.warnings,
677
+ push: (item) => envelope.result.items.push(item),
678
+ });
679
+ if (error === undefined)
680
+ continue;
681
+ const code = error instanceof DataTransformError ? error.code : 'TRANSFORM_RETRIEVE_FAILED';
682
+ if (!['OVERWRITE_REQUIRED', 'UNSAFE_PATH'].includes(code))
683
+ failed = true;
684
+ const diagnostic = {
685
+ code,
686
+ message: operationDiagnostic(error, 'Transform retrieval did not complete; no org write attempted.'),
687
+ retryable: false,
688
+ identity: { dataSpace: effectiveScope, apiName },
689
+ };
690
+ envelope.diagnostics.errors.push(diagnostic);
691
+ errorTypes.set(diagnostic, 'data-transform');
692
+ }
693
+ }
694
+ return {
695
+ status: groupStatus(envelope, before, failed),
696
+ selection: names.map((name) => `data-transform:${name}`),
697
+ };
698
+ },
699
+ };
700
+ }
701
+ /**
702
+ * Validate exact data stream selectors, then read them one after another.
703
+ * @param {string[]} selectors The data-stream group.
704
+ * @param {RetrieveRun} context Shared command state.
705
+ * @returns {GroupPlan} A refusal, or the group's read.
706
+ */
707
+ prepareDataStreams(selectors, context) {
708
+ const { flags, envelope, outputTypes, errorTypes, effectiveScope, outputDirectory } = context;
709
+ const family = 'data-stream';
710
+ if (selectors.some((value) => value !== 'data-stream' && !/^data-stream:[A-Za-z][A-Za-z0-9_]{0,199}$/u.test(value)))
711
+ return { refusal: 'INVALID_SELECTION', family };
712
+ let version;
713
+ try {
714
+ version = dataStreamApiVersion(flags['api-version']);
715
+ }
716
+ catch {
717
+ return { refusal: 'INVALID_SCOPE', family };
718
+ }
719
+ // A stream belongs to the run's data space when its DLO's list names it.
720
+ return {
721
+ family,
722
+ run: async () => {
723
+ let org;
724
+ try {
725
+ org = await this.resolveOrg(flags['target-org']);
726
+ }
727
+ catch {
728
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
729
+ }
730
+ const connection = org.getConnection(version);
731
+ const target = flags['target-org'] ?? connection.getUsername();
732
+ if (!target)
733
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
734
+ envelope.provenance.sourceOrgId ??= org.getOrgId();
735
+ envelope.metadata.soapApiVersion ??= version;
736
+ const before = envelope.diagnostics.errors.length;
737
+ let failed = false;
738
+ const listed = selectors
739
+ .filter((value) => value !== 'data-stream')
740
+ .map((value) => value.slice('data-stream:'.length));
741
+ // Bare data-stream: every stream the API lists, each read on its own.
742
+ if (selectors.includes('data-stream'))
743
+ try {
744
+ listed.push(...(await (this.listDataStreamNames ?? listDataStreamNames)(connection, version, envelope.diagnostics.warnings, effectiveScope)));
745
+ }
746
+ catch (error) {
747
+ failed = true;
748
+ this.inventoryFailure(envelope, errorTypes, error, family);
749
+ }
750
+ const names = [...new Set(listed)];
751
+ names.sort();
752
+ outputTypes.add('data-stream');
753
+ const routes = [
754
+ { operation: 'data-stream.get', apiVersion: version, transport: 'native' },
755
+ { operation: 'dlo.get', apiVersion: version, transport: 'native' },
756
+ { operation: 'connection.read', apiVersion: version, transport: 'native' },
757
+ ];
758
+ for (const apiName of names) {
759
+ let nativeOf = nothingRead;
760
+ let clients;
761
+ try {
762
+ clients = this.createDataStreamClients(connection, target, version);
763
+ // The stream's own GET is the raw response a verbatim file keeps. Salesforce lists
764
+ // the mappings in varying order, so sort them as a modelled file does.
765
+ const reads = recordNativeReads(clients.streams, verbatimStreamNative);
766
+ nativeOf = reads.nativeOf;
767
+ const document = await this.acquireDataStream(apiName, clients.streams ? { ...clients, streams: reads.client } : clients, effectiveScope, false, 'retrieve');
768
+ const receipt = await this.writeDataStream(document, outputDirectory, flags.overwrite);
769
+ envelope.result.items.push({
770
+ identity: reportedIdentity(document, effectiveScope),
771
+ // Every data space of the stream's DLO (its file's c__dataSpace).
772
+ dataSpaces: document.c__dataSpace,
773
+ operation: 'retrieve',
774
+ family: 'data-stream',
775
+ routes,
776
+ ...receipt,
777
+ });
778
+ }
779
+ catch (error_) {
780
+ const read = nativeOf(apiName);
781
+ // A stream written as-is must belong to the run's data space too: the spaces its GET
782
+ // lists, or its DLO's when the GET names none (the check a modelled stream passes).
783
+ // When they cannot be confirmed, the item fails instead of being written.
784
+ let unconfirmed;
785
+ if (read !== undefined && clients !== undefined && verbatimReason(error_) !== undefined)
786
+ try {
787
+ await streamSpaces(read.native, apiName, effectiveScope, clients);
788
+ }
789
+ catch (spaceError) {
790
+ unconfirmed = spaceError;
791
+ }
792
+ const error = unconfirmed ??
793
+ (await this.verbatimFallback(error_, read, {
794
+ kind: 'data-stream',
795
+ identity: { dataSpace: effectiveScope, apiName },
796
+ routes,
797
+ root: outputDirectory,
798
+ overwrite: flags.overwrite,
799
+ warnings: envelope.diagnostics.warnings,
800
+ push: (item) => envelope.result.items.push(item),
801
+ }));
802
+ if (error === undefined)
803
+ continue;
804
+ const code = error instanceof DataStreamError ? error.code : 'DATA_STREAM_RETRIEVE_FAILED';
805
+ if (!['OVERWRITE_REQUIRED', 'UNSAFE_PATH'].includes(code))
806
+ failed = true;
807
+ const diagnostic = {
808
+ code,
809
+ message: operationDiagnostic(error, 'Data stream retrieval did not complete; no write attempted.'),
810
+ retryable: false,
811
+ identity: { dataSpace: effectiveScope, apiName },
812
+ };
813
+ envelope.diagnostics.errors.push(diagnostic);
814
+ errorTypes.set(diagnostic, 'data-stream');
815
+ }
816
+ }
817
+ return {
818
+ status: groupStatus(envelope, before, failed),
819
+ selection: names.map((name) => `data-stream:${name}`),
820
+ };
821
+ },
822
+ };
823
+ }
824
+ /**
825
+ * Validate exact data graph selectors, then read the graphs one after another. A failure of
826
+ * the shared org context blocks the group; a failure of one graph is reported for that graph.
827
+ * @param {string[]} selectors The data-graph group.
828
+ * @param {RetrieveRun} context Shared command state.
829
+ * @returns {GroupPlan} A refusal, or the group's read.
830
+ */
831
+ prepareDataGraphs(selectors, context) {
832
+ const { flags, envelope, outputTypes, errorTypes, effectiveScope, outputDirectory } = context;
833
+ const family = 'data-graph';
834
+ try {
835
+ operationApiVersion(flags['api-version'], 'data-graph');
836
+ }
837
+ catch {
838
+ return { refusal: 'INVALID_SCOPE', family };
839
+ }
840
+ if (selectors.some((value) => value !== 'data-graph' && !/^data-graph:[A-Za-z][A-Za-z0-9_]{0,199}$/u.test(value)))
841
+ return { refusal: 'INVALID_SELECTION', family };
842
+ return {
843
+ family,
844
+ run: async () => {
845
+ let graphContext;
846
+ let connection;
847
+ try {
848
+ const org = await this.resolveOrg(flags['target-org']);
849
+ connection = org.getConnection('68.0');
850
+ graphContext = await this.nativeGraphContext(connection, effectiveScope);
851
+ }
852
+ catch (error) {
853
+ return {
854
+ status: 'blocked',
855
+ selection: selectors,
856
+ code: 'NATIVE_GRAPH_RETRIEVE_BLOCKED',
857
+ error,
858
+ };
859
+ }
860
+ envelope.provenance.sourceOrgId ??= graphContext.orgId;
861
+ envelope.metadata.soapApiVersion ??= '68.0';
862
+ // The body of each graph's first successful read is the raw response a verbatim file keeps.
863
+ const reads = recordNativeReads(graphContext, (response) => {
864
+ const read = response;
865
+ return read?.status === 200 ? { native: read.body } : undefined;
866
+ });
867
+ graphContext = reads.client;
868
+ const before = envelope.diagnostics.errors.length;
869
+ let failed = false;
870
+ const listed = selectors
871
+ .filter((value) => value !== 'data-graph')
872
+ .map((value) => value.slice('data-graph:'.length));
873
+ // Bare data-graph: every graph of the run's data space the API lists, each read on its own.
874
+ if (selectors.includes('data-graph'))
875
+ try {
876
+ listed.push(...(await (this.listDataGraphNames ?? listDataGraphNames)(connection, envelope.diagnostics.warnings, effectiveScope)));
877
+ }
878
+ catch (error) {
879
+ failed = true;
880
+ this.inventoryFailure(envelope, errorTypes, error, family);
881
+ }
882
+ const names = [...new Set(listed)];
883
+ names.sort();
884
+ outputTypes.add('data-graph');
885
+ const routes = [
886
+ { operation: 'data-graph.get', apiVersion: '68.0', transport: 'native' },
887
+ ];
888
+ for (const apiName of names) {
889
+ try {
890
+ const document = await this.retrieveNativeGraph(apiName, graphContext);
891
+ const receipt = await this.writeDataGraph(document, outputDirectory, flags.overwrite);
892
+ envelope.result.items.push({
893
+ identity: { dataSpace: effectiveScope, apiName },
894
+ operation: 'retrieve',
895
+ family: 'data-graph',
896
+ routes,
897
+ ...receipt,
898
+ });
899
+ await this.notePrefixMismatch('data-graph', apiName, reads.nativeOf(apiName)?.native, effectiveScope, envelope.diagnostics.warnings);
900
+ }
901
+ catch (error_) {
902
+ const error = await this.verbatimFallback(error_, reads.nativeOf(apiName), {
903
+ kind: 'native-data-graph',
904
+ identity: { dataSpace: effectiveScope, apiName },
905
+ routes,
906
+ root: outputDirectory,
907
+ overwrite: flags.overwrite,
908
+ warnings: envelope.diagnostics.warnings,
909
+ push: (item) => envelope.result.items.push(item),
910
+ });
911
+ if (error === undefined)
912
+ continue;
913
+ // A graph of another name or data space keeps its own code and explanation.
914
+ const own = error instanceof DataGraphError &&
915
+ [
916
+ 'DATA_GRAPH_IDENTITY_MISMATCH',
917
+ 'DATA_GRAPH_DATASPACE_MISMATCH',
918
+ 'DATA_GRAPH_DATASPACE_UNREADABLE',
919
+ ].includes(error.code);
920
+ const diagnostic = {
921
+ code: own ? error.code : 'NATIVE_GRAPH_RETRIEVE_BLOCKED',
922
+ message: own && explanationOf(error)
923
+ ? explanationOf(error)
924
+ : withInnerCode(retrievalMessage(error), error),
925
+ retryable: false,
926
+ identity: { dataSpace: effectiveScope, apiName },
927
+ family: 'data-graph',
928
+ };
929
+ envelope.diagnostics.errors.push(diagnostic);
930
+ errorTypes.set(diagnostic, 'data-graph');
931
+ }
932
+ }
933
+ return {
934
+ status: groupStatus(envelope, before, failed),
935
+ selection: names.map((name) => `data-graph:${name}`),
936
+ };
937
+ },
938
+ };
939
+ }
940
+ /**
941
+ * Validate every other selector (DLO, DMO, mapping, relationship, Segment, calculated
942
+ * insight, identity resolution); an empty selection is every native family.
943
+ * @param {string[]} selectors The selectors of no other group.
944
+ * @param {RetrieveRun} context Shared command state.
945
+ * @returns {GroupPlan} A refusal, or the group's read.
946
+ */
947
+ prepareRest(selectors, context) {
948
+ // Relationships are read per source DMO; bare relationship reads those of every listed DMO.
949
+ const relationshipDmos = [
950
+ ...new Set(selectors
951
+ .filter((value) => value.startsWith('relationship:'))
952
+ .map((value) => value.slice('relationship:'.length))),
953
+ ];
954
+ relationshipDmos.sort();
955
+ return selectors.every((value) => inGroup('relationship', value) ||
956
+ nativeFamilies.some((family) => value === family || value.startsWith(`${family}:`)))
957
+ ? this.prepareNativeRest(selectors, relationshipDmos, context)
958
+ : this.prepareMixedRest(selectors, relationshipDmos, context);
959
+ }
960
+ /**
961
+ * Native-only DLO, DMO, mapping and relationship selection, including type inventory.
962
+ * @param {string[]} selectors The rest group, native families only.
963
+ * @param {string[]} relationshipDmos Exact sorted relationship source DMOs.
964
+ * @param {RetrieveRun} context Shared command state.
965
+ * @returns {GroupPlan} A refusal, or the group's read.
966
+ */
967
+ prepareNativeRest(selectors, relationshipDmos, context) {
968
+ const { flags, envelope, outputTypes, errorTypes, effectiveScope } = context;
969
+ const outputDirectory = context.outputDirectory;
970
+ const label = selectorFamily(selectors[0]);
971
+ let version;
972
+ try {
973
+ version = nativeApiVersion(flags['api-version']);
974
+ if (relationshipDmos.some((name) => !relationshipDmoName.test(name)))
975
+ return { refusal: 'INVALID_SELECTION', family: 'relationship' };
976
+ for (const selector of selectors) {
977
+ if (inGroup('relationship', selector))
978
+ continue;
979
+ const [family, name, extra] = selector.split(':');
980
+ if (extra !== undefined ||
981
+ (name !== undefined &&
982
+ !(family === 'dlo' ? dloName : family === 'dmo' ? nativeDmoName : nativeMappingName).test(name)))
983
+ return { refusal: 'INVALID_SELECTION', family: selectorFamily(selector) };
984
+ }
985
+ }
986
+ catch {
987
+ return { refusal: 'INVALID_SCOPE', family: label };
988
+ }
989
+ return {
990
+ family: label,
991
+ run: async () => {
992
+ let org;
993
+ try {
994
+ org = await this.resolveOrg(flags['target-org']);
995
+ }
996
+ catch {
997
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
998
+ }
999
+ const connection = org.getConnection(version);
1000
+ const target = flags['target-org'] ?? connection.getUsername();
1001
+ if (!target)
1002
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
1003
+ envelope.provenance.sourceOrgId ??= org.getOrgId();
1004
+ envelope.metadata.soapApiVersion ??= version;
1005
+ const selected = new Map();
1006
+ const before = envelope.diagnostics.errors.length;
1007
+ const warnings = envelope.diagnostics.warnings;
1008
+ // An inventory that cannot be read fails its family only; the others are still read.
1009
+ const inventoryFailures = [];
1010
+ // The DMO inventory, read once for both the DMO and the mapping family.
1011
+ let dmoInventory;
1012
+ // The listing entries; a listed object's GET answers with its entry (see createDloClient).
1013
+ const listed = { dlo: new Map(), dmo: new Map() };
1014
+ // Mapping list entries answer the mapping GET; parent reads are shared by the mappings.
1015
+ const listedMappings = new Map();
1016
+ const parentReads = new Map();
1017
+ const listDmos = async () => (dmoInventory ??= this.listNativeNames(connection, version, 'dmo', effectiveScope, warnings, listed.dmo));
1018
+ // Mappings only the inventory named (not selected by name): one that reads 404 was
1019
+ // deleted during the retrieve and is skipped with a warning.
1020
+ const listedOnly = new Set();
1021
+ // Finish every inventory before publishing any file.
1022
+ for (const family of nativeFamilies) {
1023
+ const all = selectors.length === 0 || selectors.includes(family);
1024
+ let names = selectors
1025
+ .filter((value) => value.startsWith(`${family}:`))
1026
+ .map((value) => value.slice(family.length + 1));
1027
+ const named = new Set(names);
1028
+ if (all)
1029
+ try {
1030
+ if (family === 'mapping') {
1031
+ const inventory = await this.listNativeMappingNames(await listDmos(), this.createMappingInventoryReader(connection, version, effectiveScope), effectiveScope, {
1032
+ warnings,
1033
+ listed: listedMappings,
1034
+ failure: (dmo, error) => envelope.diagnostics.errors.push({
1035
+ code: 'NATIVE_INVENTORY_FAILED',
1036
+ message: retrievalMessage(error),
1037
+ retryable: false,
1038
+ identity: { dataSpace: effectiveScope, apiName: dmo },
1039
+ family: 'mapping',
1040
+ }),
1041
+ });
1042
+ for (const name of inventory)
1043
+ if (!named.has(name))
1044
+ listedOnly.add(name);
1045
+ names.push(...inventory);
1046
+ }
1047
+ else
1048
+ names.push(...(family === 'dmo'
1049
+ ? await listDmos()
1050
+ : await this.listNativeNames(connection, version, family, effectiveScope, warnings, listed.dlo)));
1051
+ }
1052
+ catch (error) {
1053
+ inventoryFailures.push({ family, error });
1054
+ }
1055
+ names = [...new Set(names)];
1056
+ names.sort();
1057
+ selected.set(family, names);
1058
+ }
1059
+ // Bare relationship: the relationships of every DMO the API lists, one DMO at a time.
1060
+ const relationshipSources = [...relationshipDmos];
1061
+ if (selectors.includes('relationship'))
1062
+ try {
1063
+ relationshipSources.push(...(await listDmos()));
1064
+ }
1065
+ catch (error) {
1066
+ inventoryFailures.push({ family: 'relationship', error });
1067
+ }
1068
+ const relationshipNames = [...new Set(relationshipSources)];
1069
+ relationshipNames.sort();
1070
+ // Nothing else to read: the one failed inventory is the group's outcome, as before.
1071
+ if (inventoryFailures.length === 1 &&
1072
+ relationshipNames.length === 0 &&
1073
+ [...selected.values()].every((names) => names.length === 0) &&
1074
+ envelope.diagnostics.errors.length === before)
1075
+ return {
1076
+ status: 'blocked',
1077
+ selection: selectors,
1078
+ code: inventoryCode(inventoryFailures[0].error),
1079
+ error: inventoryFailures[0].error,
1080
+ family: inventoryFailures[0].family,
1081
+ };
1082
+ for (const { family, error } of inventoryFailures)
1083
+ envelope.diagnostics.errors.push({
1084
+ code: inventoryCode(error),
1085
+ message: retrievalMessage(error),
1086
+ retryable: false,
1087
+ family,
1088
+ });
1089
+ const selection = [
1090
+ // A family whose inventory failed stays in the selection under its bare name.
1091
+ ...inventoryFailures.map(({ family }) => family),
1092
+ ...[...selected].flatMap(([family, names]) => names.map((name) => `${family}:${name}`)),
1093
+ ...relationshipNames.map((name) => `relationship:${name}`),
1094
+ ];
1095
+ let failed = false;
1096
+ for (const family of nativeFamilies) {
1097
+ if (selectors.length === 0 ||
1098
+ selectors.some((selector) => selector === family || selector.startsWith(`${family}:`)))
1099
+ outputTypes.add(family);
1100
+ const routes = [
1101
+ { operation: `${family}.get`, apiVersion: version, transport: 'native' },
1102
+ ];
1103
+ const names = selected.get(family) ?? [];
1104
+ // The item's own client: its GET is the raw response a verbatim file keeps.
1105
+ const recorders = names.map(() => nativeReadRecorder());
1106
+ // Mappings are read up to mappingReads at once; files, items, warnings and diagnostics
1107
+ // still follow the name order. Retries (429, 503, network) stay per request.
1108
+ const mappingDocuments = family === 'mapping'
1109
+ ? readInOrder([...names.keys()], mappingReads, async (index) => this.acquireNativeMapping(names[index], recorders[index].wrap(this.createMappingClient(target, version, undefined, effectiveScope, this.ssotSender(target, version, connection), listedMappings)), effectiveScope, this.mappingParents(target, version, this.ssotSender(target, version, connection), listed, parentReads), 'retrieve'))
1110
+ : [];
1111
+ // The labels of the mappings read are then read together, up to 10 names per Metadata
1112
+ // API read; a failed read only leaves the label out (a warning), never the mapping.
1113
+ if (family === 'mapping' && mappingDocuments.length > 0) {
1114
+ const settled = await Promise.all(mappingDocuments);
1115
+ warnings.push(...(await labelRetrievedMappings(settled.flatMap((read) => ('value' in read ? [read.value] : [])), this.createMappingClient(target, version, undefined, effectiveScope, this.ssotSender(target, version, connection)))));
1116
+ }
1117
+ for (const [index, apiName] of names.entries()) {
1118
+ const reads = recorders[index];
1119
+ try {
1120
+ const document = family === 'mapping'
1121
+ ? await settledValue(mappingDocuments[index])
1122
+ : family === 'dlo'
1123
+ ? await this.acquireDlo(apiName, reads.wrap(this.createDloClient(target, version, this.ssotSender(target, version, connection), listed.dlo)),
1124
+ // The scope it is read in binds a DLO that belongs to several spaces.
1125
+ effectiveScope, 'retrieve')
1126
+ : await (this.acquireNativeDmo ?? retrieveNativeDmo)(apiName, reads.wrap(this.createDmoClient(target, version, undefined, this.ssotSender(target, version, connection), listed.dmo)), effectiveScope, 'retrieve');
1127
+ const root = outputDirectory;
1128
+ const receipt = document.kind === 'mapping'
1129
+ ? await this.writeNativeMapping(document, root, flags.overwrite)
1130
+ : document.kind === 'dlo'
1131
+ ? await this.writeDlo(document, root, flags.overwrite)
1132
+ : await (this.writeNativeDmo ?? writeNativeDmoDocument)(document, root, flags.overwrite);
1133
+ envelope.result.items.push({
1134
+ ...(document.kind === 'dlo'
1135
+ ? {
1136
+ identity: { dataSpace: effectiveScope, apiName: document.identity.apiName },
1137
+ dataSpaces: document.c__dataSpace,
1138
+ }
1139
+ : { identity: reportedIdentity(document, effectiveScope) }),
1140
+ operation: 'retrieve',
1141
+ ...(family === 'dmo' ? {} : { family }),
1142
+ routes,
1143
+ ...receipt,
1144
+ });
1145
+ if (document.kind === 'dmo')
1146
+ await this.notePrefixMismatch('dmo', document.identity.apiName, reads.nativeOf(apiName)?.native, effectiveScope, warnings);
1147
+ }
1148
+ catch (error_) {
1149
+ if (family === 'mapping' &&
1150
+ listedOnly.has(apiName) &&
1151
+ error_ instanceof NativeMappingError &&
1152
+ error_.code === 'MAPPING_HTTP_ERROR' &&
1153
+ error_.status === 404) {
1154
+ warnings.push(`mapping:${apiName}: listed by Salesforce but not found when read (404), so it was deleted during the retrieve; skipped.`);
1155
+ continue;
1156
+ }
1157
+ const error = await this.verbatimFallback(error_, reads.nativeOf(apiName), {
1158
+ kind: family,
1159
+ identity: { dataSpace: effectiveScope, apiName },
1160
+ routes,
1161
+ root: outputDirectory,
1162
+ overwrite: flags.overwrite,
1163
+ warnings: envelope.diagnostics.warnings,
1164
+ push: (item) => envelope.result.items.push(item),
1165
+ });
1166
+ if (error === undefined)
1167
+ continue;
1168
+ const code = error instanceof NativeMappingError ||
1169
+ error instanceof NativeDmoError ||
1170
+ error instanceof MappingDefinitionError ||
1171
+ error instanceof DloError
1172
+ ? error.code
1173
+ : 'NATIVE_RETRIEVE_FAILED';
1174
+ if (!['OVERWRITE_REQUIRED', 'UNSAFE_PATH'].includes(code))
1175
+ failed = true;
1176
+ envelope.diagnostics.errors.push({
1177
+ code,
1178
+ message: operationDiagnostic(error, 'Native component retrieval did not complete; no write attempted.'),
1179
+ retryable: false,
1180
+ identity: { dataSpace: effectiveScope, apiName },
1181
+ ...(family === 'mapping' ? { family } : {}),
1182
+ });
1183
+ errorTypes.set(envelope.diagnostics.errors.at(-1), family);
1184
+ }
1185
+ }
1186
+ }
1187
+ if (relationshipNames.length > 0 || selectors.includes('relationship')) {
1188
+ outputTypes.add('relationship');
1189
+ const relationships = await this.retrieveRelationshipFamily(relationshipNames, connection, target, version, effectiveScope, outputDirectory, flags.overwrite);
1190
+ envelope.result.items.push(...relationships.items);
1191
+ envelope.diagnostics.errors.push(...relationships.errors);
1192
+ envelope.diagnostics.warnings.push(...relationships.warnings);
1193
+ if (relationships.failed)
1194
+ failed = true;
1195
+ }
1196
+ return { status: groupStatus(envelope, before, failed), selection };
1197
+ },
1198
+ };
1199
+ }
1200
+ /**
1201
+ * DLO, mapping, relationship, DMO, Segment, calculated insight and identity resolution
1202
+ * selections that are not native-only.
1203
+ * @param {string[]} selectors The rest group.
1204
+ * @param {string[]} relationshipDmos Exact sorted relationship source DMOs.
1205
+ * @param {RetrieveRun} context Shared command state.
1206
+ * @returns {GroupPlan} A refusal, or the group's read.
1207
+ */
1208
+ prepareMixedRest(selectors, relationshipDmos, context) {
1209
+ const { flags, envelope, outputTypes, errorTypes, effectiveScope } = context;
1210
+ const outputDirectory = context.outputDirectory;
1211
+ const label = selectorFamily(selectors[0]);
1212
+ // The family whose check runs, named in a refusal beside other groups.
1213
+ let family = label;
1214
+ // This group exists only beside a segment, calculated insight or identity resolution (the
1215
+ // native-only group takes DLOs, DMOs, mappings and relationships alone). Every family is read
1216
+ // in the run's data space.
1217
+ const dloSelectors = selectors.filter((value) => value === 'dlo' || value.startsWith('dlo:'));
1218
+ const mappingSelectors = selectors.filter((value) => value.startsWith('mapping:'));
1219
+ const ciSelectors = selectors.filter((value) => inGroup('calculated-insight', value));
1220
+ const irSelectors = selectors.filter((value) => inGroup('identity-resolution', value));
1221
+ const segmentSelectors = selectors.filter((value) => inGroup('segment', value));
1222
+ const dmoSelectors = selectors.filter((value) => value !== 'dlo' &&
1223
+ !value.startsWith('dlo:') &&
1224
+ !value.startsWith('mapping:') &&
1225
+ !inGroup('relationship', value) &&
1226
+ !inGroup('segment', value) &&
1227
+ !inGroup('identity-resolution', value) &&
1228
+ !inGroup('calculated-insight', value));
1229
+ const hasDmos = dmoSelectors.length > 0;
1230
+ let effectiveVersion;
1231
+ try {
1232
+ family = 'dlo';
1233
+ if (dloSelectors.length > 0) {
1234
+ if (dloSelectors.some((value) => value !== 'dlo' && !dloName.test(value.slice(4))))
1235
+ return { refusal: 'INVALID_SELECTION', family };
1236
+ if (!['68.0', 'auto'].includes(flags['api-version']))
1237
+ return { refusal: 'INVALID_SCOPE', family };
1238
+ }
1239
+ family = 'mapping';
1240
+ if (selectors.includes('mapping'))
1241
+ throw new MappingDefinitionError('MAPPING_INVENTORY_UNQUALIFIED');
1242
+ if (mappingSelectors.length > 0) {
1243
+ nativeApiVersion(flags['api-version']);
1244
+ if (mappingSelectors.some((value) => !mappingName.test(value.slice(8))))
1245
+ throw new MappingDefinitionError('INVALID_SELECTION');
1246
+ }
1247
+ family = 'relationship';
1248
+ if (relationshipDmos.length > 0 || selectors.includes('relationship')) {
1249
+ nativeApiVersion(flags['api-version']);
1250
+ if (relationshipDmos.some((name) => !relationshipDmoName.test(name)))
1251
+ throw new NativeRelationshipError('INVALID_SELECTION');
1252
+ }
1253
+ family = 'calculated-insight';
1254
+ if (ciSelectors.length > 0) {
1255
+ operationApiVersion(flags['api-version'], 'calculated-insight');
1256
+ if (ciSelectors.some((value) => value !== 'calculated-insight' && !calculatedInsightName.test(value.slice(19))))
1257
+ throw new CalculatedInsightError('INVALID_SELECTION');
1258
+ }
1259
+ family = 'identity-resolution';
1260
+ if (irSelectors.some((value) => value !== 'identity-resolution' && !identityResolutionName.test(value.slice(20))))
1261
+ throw new IdentityResolutionError('INVALID_SELECTION');
1262
+ if (irSelectors.length > 0)
1263
+ operationApiVersion(flags['api-version'], 'identity-resolution');
1264
+ family = 'segment';
1265
+ if (segmentSelectors.length > 0)
1266
+ operationApiVersion(flags['api-version'], 'segment');
1267
+ family = 'dmo';
1268
+ // A DMO is read natively at its own version and never pins the other families.
1269
+ if (hasDmos)
1270
+ nativeApiVersion(flags['api-version']);
1271
+ const sharedFamily = segmentSelectors.length > 0
1272
+ ? 'segment'
1273
+ : ciSelectors.length > 0
1274
+ ? 'calculated-insight'
1275
+ : irSelectors.length > 0
1276
+ ? 'identity-resolution'
1277
+ : undefined;
1278
+ family = sharedFamily ?? label;
1279
+ effectiveVersion =
1280
+ dloSelectors.length === selectors.length && dloSelectors.length > 0
1281
+ ? '68.0'
1282
+ : sharedFamily
1283
+ ? operationApiVersion(flags['api-version'], sharedFamily)
1284
+ : hasDmos || mappingSelectors.length > 0
1285
+ ? nativeApiVersion(flags['api-version'])
1286
+ : operationApiVersion(flags['api-version'], 'dlo');
1287
+ }
1288
+ catch (error) {
1289
+ return {
1290
+ refusal: error instanceof MappingDefinitionError ||
1291
+ error instanceof NativeRelationshipError ||
1292
+ error instanceof DloError ||
1293
+ error instanceof IdentityResolutionError ||
1294
+ error instanceof CalculatedInsightError
1295
+ ? error.code
1296
+ : 'INVALID_SCOPE',
1297
+ family,
1298
+ };
1299
+ }
1300
+ try {
1301
+ family = 'segment';
1302
+ if (segmentSelectors.some((value) => value !== 'segment' && !segmentName.test(value.slice(8))))
1303
+ throw new SegmentError('INVALID_SELECTION');
1304
+ if (segmentSelectors.length > 0 && effectiveVersion !== '68.0')
1305
+ throw new SegmentError('INVALID_SCOPE');
1306
+ family = 'dmo';
1307
+ // Validate DMO selector syntax before auth; unknown families land here and are refused.
1308
+ if (dmoSelectors.some((value) => value !== 'dmo' && !(value.startsWith('dmo:') && nativeDmoName.test(value.slice(4)))))
1309
+ return { refusal: 'INVALID_SELECTION', family };
1310
+ }
1311
+ catch (error) {
1312
+ return {
1313
+ refusal: error instanceof SegmentError ? error.code : 'INVALID_SELECTION',
1314
+ family,
1315
+ };
1316
+ }
1317
+ return {
1318
+ family: label,
1319
+ run: async () => {
1320
+ let org;
1321
+ try {
1322
+ org = await this.resolveOrg(flags['target-org']);
1323
+ }
1324
+ catch {
1325
+ return { status: 'blocked', selection: selectors, code: 'TARGET_ORG_REQUIRED' };
1326
+ }
1327
+ let selection = selectors;
1328
+ const before = envelope.diagnostics.errors.length;
1329
+ let failed = false;
1330
+ // An inventory that cannot be read fails its family only; the other selectors still run.
1331
+ const inventoryFailure = (error, family) => {
1332
+ envelope.diagnostics.errors.push({
1333
+ code: error instanceof CalculatedInsightError ||
1334
+ error instanceof SegmentError ||
1335
+ error instanceof IdentityResolutionError ||
1336
+ error instanceof ConnectError
1337
+ ? error.code
1338
+ : 'NATIVE_INVENTORY_FAILED',
1339
+ message: retrievalMessage(error),
1340
+ retryable: false,
1341
+ family,
1342
+ });
1343
+ errorTypes.set(envelope.diagnostics.errors.at(-1), family);
1344
+ if (error instanceof ConnectError)
1345
+ failed = true;
1346
+ };
1347
+ const diagnose = (error, apiName, family = 'dmo') => {
1348
+ let code = 'RETRIEVE_FAILED';
1349
+ if (error instanceof DloError ||
1350
+ error instanceof CalculatedInsightError ||
1351
+ error instanceof IdentityResolutionError ||
1352
+ error instanceof SegmentError ||
1353
+ error instanceof DependencySelectionError ||
1354
+ error instanceof RetrieveSelectionError ||
1355
+ error instanceof NativeDmoError ||
1356
+ error instanceof ConnectError)
1357
+ code = error.code;
1358
+ else
1359
+ failed = true;
1360
+ if (code === 'IDENTITY_RESOLUTION_ACQUISITION_FAILED' ||
1361
+ code === 'OUTPUT_FAILED' ||
1362
+ code === 'PARTIAL_DMO_OUTPUT' ||
1363
+ code === 'PARTIAL_SEGMENT_OUTPUT' ||
1364
+ code === 'SEGMENT_ACQUISITION_FAILED' ||
1365
+ code === 'DEPENDENCY_ACQUISITION_FAILED' ||
1366
+ code === 'SEGMENT_DEPENDENCY_ACQUISITION_FAILED' ||
1367
+ error instanceof ConnectError ||
1368
+ code === 'ACQUISITION_FAILED')
1369
+ failed = true;
1370
+ // An insight or segment of another name or data space is a failed item, never a blocked
1371
+ // run.
1372
+ if (code === 'CI_IDENTITY_CHANGED' ||
1373
+ code === 'SEGMENT_DATASPACE_MISMATCH' ||
1374
+ code === 'IDENTITY_RESOLUTION_DATASPACE_MISMATCH')
1375
+ failed = true;
1376
+ if (error instanceof RetrieveSelectionError) {
1377
+ apiName = error.identity.apiName;
1378
+ family = error.identity.kind;
1379
+ }
1380
+ envelope.diagnostics.errors.push({
1381
+ code,
1382
+ message: getConnectDiagnostic(error) ||
1383
+ code === 'CI_IDENTITY_CHANGED' ||
1384
+ code === 'SEGMENT_DATASPACE_MISMATCH' ||
1385
+ code === 'IDENTITY_RESOLUTION_DATASPACE_MISMATCH'
1386
+ ? operationDiagnostic(error, 'This component was not retrieved; no files were written for it.')
1387
+ : apiName
1388
+ ? (calculatedInsightRetrieveMessages[code] ??
1389
+ 'This component was not retrieved. Resolve its capability, acquisition or output diagnostic.')
1390
+ : 'The selection could not be retrieved completely; no files were written.',
1391
+ retryable: false,
1392
+ ...(apiName ? { identity: { dataSpace: effectiveScope, apiName } } : {}),
1393
+ });
1394
+ errorTypes.set(envelope.diagnostics.errors.at(-1), family);
1395
+ };
1396
+ try {
1397
+ envelope.provenance.sourceOrgId ??= org.getOrgId();
1398
+ // Every remaining route is a fixed numeric pin; nothing is discovered from the org.
1399
+ const versions = await resolveApiVersion(effectiveVersion, async () => {
1400
+ throw new Error('Fixed route must not discover.');
1401
+ });
1402
+ envelope.metadata.soapApiVersion ??= versions.soapNumeric;
1403
+ // Definition-only members are independent; retain successes across read/output failures.
1404
+ let dlos = dloSelectors.filter((value) => value !== 'dlo').map((value) => value.slice(4));
1405
+ // The listing entries; a listed object's GET answers with its entry (see createDloClient).
1406
+ const listed = { dlo: new Map(), dmo: new Map() };
1407
+ // Bare dlo: every DLO the API lists, read before any file is written.
1408
+ if (dloSelectors.includes('dlo'))
1409
+ try {
1410
+ dlos.push(...(await this.listNativeNames(org.getConnection('68.0'), '68.0', 'dlo', effectiveScope, envelope.diagnostics.warnings, listed.dlo)));
1411
+ }
1412
+ catch (error) {
1413
+ inventoryFailure(error, 'dlo');
1414
+ }
1415
+ dlos = [...new Set(dlos)];
1416
+ dlos.sort();
1417
+ const dloRoutes = [
1418
+ { operation: 'dlo.get', apiVersion: '68.0', transport: 'native' },
1419
+ ];
1420
+ for (const apiName of dlos) {
1421
+ let nativeOf = nothingRead;
1422
+ try {
1423
+ const target = flags['target-org'] ?? org.getConnection(flags['api-version']).getUsername();
1424
+ if (!target)
1425
+ throw new SegmentError('TARGET_ORG_REQUIRED');
1426
+ const reads = recordNativeReads(this.createDloClient(target, '68.0', this.ssotSender(target, '68.0', org.getConnection()), listed.dlo));
1427
+ nativeOf = reads.nativeOf;
1428
+ const document = await this.acquireDlo(apiName, reads.client, effectiveScope, 'retrieve');
1429
+ const receipt = await this.writeDlo(document, outputDirectory, flags.overwrite);
1430
+ envelope.result.items.push({
1431
+ identity: { dataSpace: effectiveScope, apiName },
1432
+ operation: 'retrieve',
1433
+ family: 'dlo',
1434
+ dataSpaces: document.c__dataSpace,
1435
+ routes: dloRoutes,
1436
+ ...receipt,
1437
+ });
1438
+ }
1439
+ catch (error_) {
1440
+ const error = await this.verbatimFallback(error_, nativeOf(apiName), {
1441
+ kind: 'dlo',
1442
+ identity: { dataSpace: effectiveScope, apiName },
1443
+ routes: dloRoutes,
1444
+ root: outputDirectory,
1445
+ overwrite: flags.overwrite,
1446
+ warnings: envelope.diagnostics.warnings,
1447
+ push: (item) => envelope.result.items.push(item),
1448
+ });
1449
+ if (error === undefined)
1450
+ continue;
1451
+ diagnose(error, apiName, 'dlo');
1452
+ if (!(error instanceof SegmentError) ||
1453
+ !['OVERWRITE_REQUIRED', 'UNSAFE_PATH', 'TARGET_ORG_REQUIRED'].includes(error.code))
1454
+ failed = true;
1455
+ }
1456
+ }
1457
+ const mappings = [...new Set(mappingSelectors.map((value) => value.slice(8)))];
1458
+ mappings.sort();
1459
+ // Every mapping is read first, then the labels of those read in batches of up to 10
1460
+ // names per Metadata API read, then the files are written in name order.
1461
+ const acquired = [];
1462
+ let labelReader;
1463
+ for (const apiName of mappings) {
1464
+ const entry = { apiName, routes: [], nativeOf: nothingRead };
1465
+ acquired.push(entry);
1466
+ try {
1467
+ const version = nativeApiVersion(flags['api-version']);
1468
+ entry.routes = [
1469
+ { operation: 'mapping.get', apiVersion: version, transport: 'native' },
1470
+ ];
1471
+ const target = flags['target-org'] ?? org.getConnection(version).getUsername();
1472
+ if (!target)
1473
+ throw new MappingDefinitionError('TARGET_ORG_REQUIRED');
1474
+ const reads = recordNativeReads(this.createMappingClient(target, version, undefined, effectiveScope, this.ssotSender(target, version, org.getConnection())));
1475
+ entry.nativeOf = reads.nativeOf;
1476
+ labelReader ??= reads.client;
1477
+ entry.document = await this.acquireNativeMapping(apiName, reads.client, effectiveScope, this.mappingParents(target, version, this.ssotSender(target, version, org.getConnection())), 'retrieve');
1478
+ }
1479
+ catch (error) {
1480
+ entry.failure = { error };
1481
+ }
1482
+ }
1483
+ if (labelReader)
1484
+ envelope.diagnostics.warnings.push(...(await labelRetrievedMappings(acquired.flatMap((entry) => (entry.document === undefined ? [] : [entry.document])), labelReader)));
1485
+ for (const { apiName, routes, nativeOf, document, failure } of acquired) {
1486
+ try {
1487
+ if (failure)
1488
+ throw failure.error;
1489
+ const receipt = await this.writeNativeMapping(document, outputDirectory, flags.overwrite);
1490
+ envelope.result.items.push({
1491
+ identity: { dataSpace: effectiveScope, apiName },
1492
+ operation: 'retrieve',
1493
+ family: 'mapping',
1494
+ routes,
1495
+ ...receipt,
1496
+ });
1497
+ }
1498
+ catch (error_) {
1499
+ const error = await this.verbatimFallback(error_, nativeOf(apiName), {
1500
+ kind: 'mapping',
1501
+ identity: { dataSpace: effectiveScope, apiName },
1502
+ routes,
1503
+ root: outputDirectory,
1504
+ overwrite: flags.overwrite,
1505
+ warnings: envelope.diagnostics.warnings,
1506
+ push: (item) => envelope.result.items.push(item),
1507
+ });
1508
+ if (error === undefined)
1509
+ continue;
1510
+ const unproven = error instanceof NativeMappingError &&
1511
+ error.code === 'MAPPING_GENERATED_PAIRS_UNPROVEN';
1512
+ const code = error instanceof MappingDefinitionError || unproven ? error.code : 'OUTPUT_FAILED';
1513
+ if (![
1514
+ 'INVALID_SELECTION',
1515
+ 'INVALID_SCOPE',
1516
+ 'OVERWRITE_REQUIRED',
1517
+ 'UNSAFE_PATH',
1518
+ 'TARGET_ORG_REQUIRED',
1519
+ ].includes(code))
1520
+ failed = true;
1521
+ envelope.diagnostics.errors.push({
1522
+ code,
1523
+ family: 'mapping',
1524
+ identity: { dataSpace: effectiveScope, apiName },
1525
+ message: unproven
1526
+ ? operationDiagnostic(error, 'This mapping definition was not exported.')
1527
+ : 'This mapping definition was not exported. Check the exact selection, acquisition and output path.',
1528
+ retryable: false,
1529
+ });
1530
+ }
1531
+ }
1532
+ let relationshipNames = [...relationshipDmos];
1533
+ if (selectors.includes('relationship')) {
1534
+ // Bare relationship: the relationships of every DMO the API lists.
1535
+ const version = nativeApiVersion(flags['api-version']);
1536
+ try {
1537
+ relationshipNames.push(...(await this.listNativeNames(org.getConnection(version), version, 'dmo', effectiveScope, envelope.diagnostics.warnings)));
1538
+ }
1539
+ catch (error) {
1540
+ inventoryFailure(error, 'relationship');
1541
+ }
1542
+ relationshipNames = [...new Set(relationshipNames)];
1543
+ relationshipNames.sort();
1544
+ }
1545
+ if (relationshipNames.length > 0) {
1546
+ const target = flags['target-org'] ?? org.getConnection().getUsername();
1547
+ if (target) {
1548
+ const relationships = await this.retrieveRelationshipFamily(relationshipNames, org.getConnection(), target, nativeApiVersion(flags['api-version']), effectiveScope, outputDirectory, flags.overwrite);
1549
+ envelope.result.items.push(...relationships.items);
1550
+ envelope.diagnostics.errors.push(...relationships.errors);
1551
+ envelope.diagnostics.warnings.push(...relationships.warnings);
1552
+ if (relationships.failed)
1553
+ failed = true;
1554
+ }
1555
+ else
1556
+ envelope.diagnostics.errors.push({
1557
+ code: 'TARGET_ORG_REQUIRED',
1558
+ family: 'relationship',
1559
+ message: 'Relationships were not retrieved; no target org username was resolved.',
1560
+ retryable: false,
1561
+ });
1562
+ }
1563
+ // Pin only this command-owned connection, before any service uses it.
1564
+ const connection = org.getConnection(versions.soapNumeric);
1565
+ // The family pin of this path does not apply to native DMO reads (auto is 68.0).
1566
+ const nativeDmoVersion = nativeApiVersion(flags['api-version']);
1567
+ let names = [];
1568
+ if (hasDmos) {
1569
+ names = dmoSelectors
1570
+ .filter((selector) => selector !== 'dmo')
1571
+ .map((selector) => selector.slice(4));
1572
+ if (dmoSelectors.includes('dmo'))
1573
+ try {
1574
+ names.push(...(await this.listNativeNames(connection, nativeDmoVersion, 'dmo', effectiveScope, envelope.diagnostics.warnings, listed.dmo)));
1575
+ }
1576
+ catch (error) {
1577
+ inventoryFailure(error, 'dmo');
1578
+ }
1579
+ names = [...new Set(names)];
1580
+ names.sort();
1581
+ }
1582
+ if (hasDmos)
1583
+ outputTypes.add('dmo');
1584
+ for (const selector of selectors)
1585
+ outputTypes.add(selector.split(':')[0]);
1586
+ const segmentNames = segmentSelectors
1587
+ .filter((value) => value !== 'segment')
1588
+ .map((value) => value.slice(8));
1589
+ // Bare segment: every segment of the run's data space the API lists (filtered by each
1590
+ // entry's own data space), each read on its own.
1591
+ if (segmentSelectors.includes('segment'))
1592
+ try {
1593
+ segmentNames.push(...(await (this.listSegmentNames ?? listSegmentNames)(connection, envelope.diagnostics.warnings, effectiveScope)));
1594
+ }
1595
+ catch (error) {
1596
+ inventoryFailure(error, 'segment');
1597
+ }
1598
+ // eslint-disable-next-line unicorn/no-array-sort -- Deterministic ordering on a new deduplicated array.
1599
+ const segments = [...new Set(segmentNames)].sort();
1600
+ selection = [
1601
+ ...dlos.map((name) => `dlo:${name}`),
1602
+ ...mappings.map((name) => `mapping:${name}`),
1603
+ ...relationshipNames.map((name) => `relationship:${name}`),
1604
+ ...names.map((name) => `dmo:${name}`),
1605
+ ...segments.map((name) => `segment:${name}`),
1606
+ ];
1607
+ // Acquire and resolve the complete bounded selection before publishing any files.
1608
+ const selected = names.length > 0 || segments.length > 0
1609
+ ? await (this.acquireSelection ?? acquireRetrieveSelection)([
1610
+ ...names.map((apiName) => ({
1611
+ kind: 'dmo',
1612
+ dataSpace: effectiveScope,
1613
+ apiName,
1614
+ })),
1615
+ ...segments.map((apiName) => ({
1616
+ kind: 'segment',
1617
+ dataSpace: effectiveScope,
1618
+ apiName,
1619
+ })),
1620
+ ], connection, versions, {
1621
+ dmo: async (apiName) => {
1622
+ const target = flags['target-org'] ?? connection.getUsername();
1623
+ if (!target)
1624
+ throw new NativeDmoError('TARGET_ORG_REQUIRED');
1625
+ return (this.createDmoClient ?? createDmoClient)(target, nativeDmoVersion, undefined, this.ssotSender(target, nativeDmoVersion, connection), listed.dmo).get(apiName);
1626
+ },
1627
+ },
1628
+ // One DMO or Segment failing never blocks the others.
1629
+ (error) => diagnose(error),
1630
+ // A Segment whose DMO cannot be bound is still written, with a warning.
1631
+ (warning) => envelope.diagnostics.warnings.push(warning))
1632
+ : [];
1633
+ const calculatedInsights = [];
1634
+ if (ciSelectors.length > 0) {
1635
+ // Every CI is read before any selected output (API 68 GET only).
1636
+ const ciConnection = org.getConnection('68.0');
1637
+ const ciNames = ciSelectors
1638
+ .filter((value) => value !== 'calculated-insight')
1639
+ .map((value) => value.slice(19));
1640
+ // Bare calculated-insight: every insight the API lists in the data space.
1641
+ if (ciSelectors.includes('calculated-insight'))
1642
+ try {
1643
+ ciNames.push(...(await this.listCalculatedInsightNames(ciConnection, effectiveScope, envelope.diagnostics.warnings)));
1644
+ }
1645
+ catch (error) {
1646
+ inventoryFailure(error, 'calculated-insight');
1647
+ }
1648
+ // Each insight's GET is the raw response a verbatim file keeps.
1649
+ const ciReads = recordNativeReads(this.createCalculatedInsightClient(ciConnection, '68.0', effectiveScope));
1650
+ // eslint-disable-next-line unicorn/no-array-sort -- Deterministic CI order on a new array.
1651
+ for (const apiName of [...new Set(ciNames)].sort()) {
1652
+ try {
1653
+ const insight = await this.acquireCalculatedInsight(ciReads.client, apiName, effectiveScope);
1654
+ calculatedInsights.push({
1655
+ document: {
1656
+ kind: 'calculated-insight',
1657
+ identity: { dataSpace: insight.dataSpace, apiName },
1658
+ },
1659
+ insight: carryNativeResponse(insight, ciReads.nativeOf(apiName)?.native),
1660
+ });
1661
+ }
1662
+ catch (error) {
1663
+ const verbatim = this.verbatimFor(error, ciReads.nativeOf(apiName), 'calculated-insight', { dataSpace: effectiveScope, apiName });
1664
+ if (verbatim) {
1665
+ calculatedInsights.push({ document: verbatim });
1666
+ continue;
1667
+ }
1668
+ // One insight failing never blocks the others.
1669
+ diagnose(error, apiName, 'calculated-insight');
1670
+ }
1671
+ }
1672
+ }
1673
+ const identityResolutions = [];
1674
+ if (irSelectors.length > 0) {
1675
+ const irVersion = await resolveApiVersion('68.0', async () => {
1676
+ throw new Error('Fixed route must not discover.');
1677
+ });
1678
+ const irConnection = org.getConnection('68.0');
1679
+ const irNames = irSelectors
1680
+ .filter((value) => value !== 'identity-resolution')
1681
+ .map((value) => value.slice(20));
1682
+ // Bare identity-resolution: every ruleset of the run's data space the API lists.
1683
+ if (irSelectors.includes('identity-resolution'))
1684
+ try {
1685
+ irNames.push(...(await (this.listIdentityResolutionNames ?? listIdentityResolutionNames)(irConnection, envelope.diagnostics.warnings, effectiveScope)));
1686
+ }
1687
+ catch (error) {
1688
+ inventoryFailure(error, 'identity-resolution');
1689
+ }
1690
+ for (const apiName of [
1691
+ ...new Set(irNames),
1692
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a detached selector list within the ES2022 library target.
1693
+ ].sort()) {
1694
+ // The raw GET response travels with the acquisition, for a verbatim file.
1695
+ let read;
1696
+ try {
1697
+ const acquired = await this.acquireIdentityResolution(irConnection, apiName, irVersion, effectiveScope, 'retrieve');
1698
+ read = carriedNativeResponse(acquired);
1699
+ // A ruleset of another data space: its own explanation, naming both spaces.
1700
+ if (acquired.blockers[0] === 'IDENTITY_RESOLUTION_DATASPACE_MISMATCH' && read)
1701
+ throw identityResolutionSpaceMismatch(apiName, identityResolutionSpace(read.native), effectiveScope, 'org');
1702
+ if (acquired.blockers.length > 0 || !acquired.candidate)
1703
+ throw retainConnectDiagnostic(new IdentityResolutionError(acquired.blockers[0] ?? 'INCOMPLETE_IDENTITY_RESOLUTION'), getConnectDiagnostic(acquired));
1704
+ const document = validateIdentityResolutionDocument(acquired.candidate, 'retrieve');
1705
+ if (acquired.identity.apiName !== apiName ||
1706
+ acquired.identity.dataSpace !== effectiveScope ||
1707
+ document.identity.apiName !== apiName ||
1708
+ document.c__dataSpace !== effectiveScope)
1709
+ throw new IdentityResolutionError('IDENTITY_RESOLUTION_IDENTITY_MISMATCH');
1710
+ identityResolutions.push({
1711
+ document: read ? carryNativeResponse(document, read.native) : document,
1712
+ });
1713
+ }
1714
+ catch (error) {
1715
+ const verbatim = this.verbatimFor(error, read, 'identity-resolution', {
1716
+ dataSpace: effectiveScope,
1717
+ apiName,
1718
+ });
1719
+ if (verbatim) {
1720
+ identityResolutions.push({ document: verbatim });
1721
+ continue;
1722
+ }
1723
+ // One identity resolution failing never blocks the others.
1724
+ diagnose(error, apiName, 'identity-resolution');
1725
+ }
1726
+ }
1727
+ }
1728
+ const entries = [...selected, ...calculatedInsights, ...identityResolutions];
1729
+ selection = [
1730
+ ...dlos.map((name) => `dlo:${name}`),
1731
+ ...mappings.map((name) => `mapping:${name}`),
1732
+ ...relationshipNames.map((name) => `relationship:${name}`),
1733
+ ...entries.map(({ document }) => `${document.kind}:${document.identity.apiName}`),
1734
+ ];
1735
+ for (const entry of entries) {
1736
+ const { document } = entry;
1737
+ // dmo, segment, identity-resolution or calculated-insight (also as a verbatim file).
1738
+ const kind = document.kind;
1739
+ const routes = [
1740
+ kind === 'identity-resolution'
1741
+ ? { operation: 'identity-resolutions.get', apiVersion: '68.0', transport: 'native' }
1742
+ : {
1743
+ operation: `${kind}.get`,
1744
+ // A DMO here is always one native read.
1745
+ apiVersion: kind === 'calculated-insight'
1746
+ ? '68.0'
1747
+ : kind === 'dmo'
1748
+ ? nativeDmoVersion
1749
+ : versions.soapNumeric,
1750
+ transport: 'native',
1751
+ },
1752
+ ];
1753
+ try {
1754
+ const receipt = 'insight' in entry
1755
+ ? await this.writeCalculatedInsight(entry.insight, outputDirectory, flags.overwrite)
1756
+ : await this.documentWriter(kind)(document, outputDirectory, flags.overwrite);
1757
+ envelope.result.items.push({
1758
+ identity: reportedIdentity(document, effectiveScope),
1759
+ ...(kind === 'dmo' ? {} : { family: kind }),
1760
+ routes,
1761
+ operation: 'retrieve',
1762
+ ...receipt,
1763
+ ...(isVerbatimDocument(document)
1764
+ ? await this.noteVerbatim(document, receipt.path, envelope.diagnostics.warnings)
1765
+ : {}),
1766
+ });
1767
+ if (!isVerbatimDocument(document) &&
1768
+ (kind === 'dmo' || kind === 'calculated-insight'))
1769
+ await this.notePrefixMismatch(kind, document.identity.apiName, carriedNativeResponse('insight' in entry ? entry.insight : document)?.native, effectiveScope, envelope.diagnostics.warnings);
1770
+ }
1771
+ catch (error_) {
1772
+ const error = await this.verbatimFallback(error_, carriedNativeResponse('insight' in entry ? entry.insight : document), {
1773
+ kind,
1774
+ identity: reportedIdentity(document, effectiveScope),
1775
+ routes,
1776
+ root: outputDirectory,
1777
+ overwrite: flags.overwrite,
1778
+ warnings: envelope.diagnostics.warnings,
1779
+ push: (item) => envelope.result.items.push(item),
1780
+ });
1781
+ if (error === undefined)
1782
+ continue;
1783
+ // One file failing never blocks the others; references are not provisioned.
1784
+ diagnose(error, document.identity.apiName, document.kind);
1785
+ }
1786
+ }
1787
+ }
1788
+ catch (error) {
1789
+ diagnose(error);
1790
+ }
1791
+ return { status: groupStatus(envelope, before, failed), selection };
1792
+ },
1793
+ };
1794
+ }
48
1795
  /**
49
- * Acquire the complete runtime projection, then publish only its authored candidate.
1796
+ * Retrieve any mix of families. Every selector group is validated before any org access; the
1797
+ * groups then run one after another (rest, data-stream, data-transform, data-graph) into one
1798
+ * envelope.
50
1799
  * @returns {Promise<RetrieveEnvelope>} Versioned retrieval outcome and payload-free diagnostics.
51
1800
  */
52
1801
  async run() {
1802
+ // Each output directory's ancestor chain is checked once per run; every file still is.
1803
+ return withCheckedDirectories(async () => this.retrieveAll());
1804
+ }
1805
+ /**
1806
+ * The run itself; see run.
1807
+ * @returns {Promise<RetrieveEnvelope>} Versioned retrieval outcome and payload-free diagnostics.
1808
+ */
1809
+ async retrieveAll() {
53
1810
  const { flags } = await this.parse(Retrieve);
1811
+ const effectiveScope = flags.dataspace ?? 'default';
1812
+ // Writers require an absolute project root; resolve a relative -d against the cwd once.
1813
+ const outputDirectory = path.resolve(flags['output-dir'] ?? process.cwd());
54
1814
  const plugin = {
55
1815
  name: packageMetadata.name,
56
1816
  version: packageMetadata.version,
57
1817
  };
58
1818
  const envelope = {
59
1819
  contract: 'sf-data360-retrieve',
60
- contractVersion: '1.0.0',
1820
+ contractVersion: '1.1.0',
61
1821
  status: 'blocked',
62
1822
  metadata: { operation: 'retrieve', plugin, apiVersion: flags['api-version'] },
63
1823
  diagnostics: { warnings: [], errors: [] },
@@ -71,98 +1831,133 @@ export default class Retrieve extends SfCommand {
71
1831
  },
72
1832
  result: {
73
1833
  scope: {
74
- dataSpace: flags['data-space'],
75
- outputDir: path.resolve(flags['output-dir'] ?? process.cwd()),
1834
+ dataSpace: effectiveScope,
1835
+ outputDir: outputDirectory,
76
1836
  },
77
1837
  selection: flags.metadata ?? [],
78
1838
  items: [],
79
1839
  },
80
1840
  };
81
- const finish = (status, code) => {
1841
+ const outputTypes = new Set();
1842
+ const errorTypes = new Map();
1843
+ const finish = (status, code, error, family) => {
82
1844
  envelope.status = status;
83
1845
  if (code)
84
1846
  envelope.diagnostics.errors.push({
85
1847
  code,
86
- message: 'Retrieval did not complete. Check selection, authenticated org, service capability and output path.',
1848
+ message: family
1849
+ ? `Retrieval did not start: the ${family} selection was refused, so nothing was read. Check the ${family} selection, --api-version and --dataspace.`
1850
+ : retrievalMessage(error),
87
1851
  retryable: false,
1852
+ ...(family ? { family } : {}),
88
1853
  });
89
1854
  if (status !== 'success')
90
1855
  process.exitCode = 1;
1856
+ annotateDiagnostics(envelope);
91
1857
  if (!this.jsonEnabled()) {
92
1858
  this.log(`Retrieve: ${status}${code ? ` (${code})` : ''}.`);
1859
+ // The default data space goes without saying; any other is named.
1860
+ if (effectiveScope !== 'default')
1861
+ this.log(`Data space: ${effectiveScope}.`);
1862
+ const groups = new Set([
1863
+ ...outputTypes,
1864
+ ...envelope.result.items.map((item) => item.family ?? 'dmo'),
1865
+ ]);
1866
+ const printError = (diagnostic) => {
1867
+ this.log(formatDiagnostic(diagnostic, diagnostic.identity
1868
+ ? `${errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'}:${diagnostic.identity.apiName}: `
1869
+ : ''));
1870
+ };
1871
+ for (const family of groups) {
1872
+ const items = envelope.result.items.filter((item) => (item.family ?? 'dmo') === family);
1873
+ for (const item of items)
1874
+ this.log(`Downloaded ${family}:${item.identity.apiName} (${item.outcome}).`);
1875
+ for (const diagnostic of envelope.diagnostics.errors)
1876
+ if (diagnostic.identity &&
1877
+ (errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo') === family)
1878
+ printError(diagnostic);
1879
+ this.log(`Downloaded ${family}: ${items.length}`);
1880
+ }
93
1881
  for (const diagnostic of envelope.diagnostics.errors)
94
- this.log(`${diagnostic.identity ? `dmo:${diagnostic.identity.apiName}: ` : ''}${diagnostic.code}: ${diagnostic.message}`);
1882
+ if (!diagnostic.identity ||
1883
+ !groups.has(errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'))
1884
+ printError(diagnostic);
1885
+ for (const warning of envelope.diagnostics.warnings)
1886
+ this.log(`Warning: ${warning}`);
95
1887
  }
96
1888
  return envelope;
97
1889
  };
98
- const selectors = flags.metadata ?? [];
99
- try {
100
- validateDmoSelection(selectors, flags['api-version'], flags['data-space']);
101
- }
102
- catch (error) {
103
- return finish('blocked', error instanceof DmoRetrieveError ? error.code : 'INVALID_SELECTION');
104
- }
105
- let org;
106
- try {
107
- org = await this.resolveOrg(flags['target-org']);
108
- }
109
- catch {
110
- return finish('blocked', 'TARGET_ORG_REQUIRED');
111
- }
112
- let failed = false;
113
- const diagnose = (error, apiName) => {
114
- let code = 'RETRIEVE_FAILED';
115
- if (error instanceof DmoWriteError ||
116
- error instanceof DmoRetrieveError ||
117
- error instanceof ConnectError)
118
- code = error.code;
119
- else if (error instanceof DmoDocumentError)
120
- code = 'UNSUPPORTED_DMO_DOCUMENT';
121
- else
122
- failed = true;
123
- if (code === 'OUTPUT_FAILED' ||
124
- error instanceof ConnectError ||
125
- code === 'ACQUISITION_FAILED')
126
- failed = true;
127
- envelope.diagnostics.errors.push({
128
- code,
129
- message: apiName
130
- ? 'This DMO was not retrieved. Resolve its capability, acquisition or output diagnostic.'
131
- : 'DMO inventory could not be resolved completely; no files were written.',
132
- retryable: false,
133
- ...(apiName ? { identity: { dataSpace: flags['data-space'], apiName } } : {}),
134
- });
1890
+ const context = {
1891
+ flags,
1892
+ envelope,
1893
+ outputTypes,
1894
+ errorTypes,
1895
+ effectiveScope,
1896
+ outputDirectory,
135
1897
  };
1898
+ const groups = groupSelectors(flags.metadata ?? []);
1899
+ const plans = [];
1900
+ // Validate every group before any org access; the first refusal blocks the whole run.
1901
+ for (const [group, members] of groups) {
1902
+ const plan = group === 'data-stream'
1903
+ ? this.prepareDataStreams(members, context)
1904
+ : group === 'data-transform'
1905
+ ? this.prepareDataTransforms(members, context)
1906
+ : group === 'data-graph'
1907
+ ? this.prepareDataGraphs(members, context)
1908
+ : this.prepareRest(members, context);
1909
+ if ('refusal' in plan)
1910
+ return groups.length === 1
1911
+ ? finish('blocked', plan.refusal)
1912
+ : finish('blocked', plan.refusal, undefined, plan.family);
1913
+ plans.push({ ...plan, members });
1914
+ }
1915
+ // The run's data space must exist in the org: one read per run, before anything is read.
136
1916
  try {
137
- envelope.provenance.sourceOrgId = org.getOrgId();
138
- const connection = org.getConnection(flags['api-version']);
139
- const names = await this.selectDocuments(connection, selectors, flags['api-version'], flags['data-space']);
140
- envelope.result.selection = names.map((name) => `dmo:${name}`);
141
- for (const apiName of names) {
1917
+ await dataSpaceCheckOf(this, async () => {
1918
+ let org;
142
1919
  try {
143
- const projection = await this.acquire(connection, apiName, flags['api-version'], flags['data-space']);
144
- if (projection.status !== 'projected' ||
145
- projection.blockers.length > 0 ||
146
- !projection.candidate)
147
- throw new DmoRetrieveError(projection.blockers[0] ?? 'INCOMPLETE_DMO_PROJECTION');
148
- if (projection.candidate.identity.apiName !== apiName ||
149
- projection.candidate.identity.dataSpace !== flags['data-space'])
150
- throw new DmoRetrieveError('INVALID_METADATA');
151
- const receipt = await this.writeDocument(projection.candidate, flags['output-dir'] ?? process.cwd(), flags.overwrite);
152
- envelope.result.items.push({
153
- identity: { ...projection.candidate.identity },
154
- operation: 'retrieve',
155
- ...receipt,
156
- });
1920
+ org = await this.resolveOrg(flags['target-org']);
157
1921
  }
158
- catch (error) {
159
- diagnose(error, apiName);
1922
+ catch {
1923
+ throw new DataSpaceError('TARGET_ORG_REQUIRED');
160
1924
  }
161
- }
1925
+ const connection = org.getConnection('68.0');
1926
+ return openBoundSsot(flags['target-org'] ?? '', '68.0', async () => connection);
1927
+ }).require([effectiveScope]);
162
1928
  }
163
1929
  catch (error) {
164
- diagnose(error);
1930
+ // The check's own code, or the failure's (an expired session keeps AUTHENTICATION_FAILED).
1931
+ return finish('blocked', dataSpaceCheckCode(error, 'RETRIEVE_FAILED'), error);
1932
+ }
1933
+ if (plans.length === 1) {
1934
+ const outcome = await plans[0].run();
1935
+ envelope.result.selection = outcome.selection;
1936
+ return finish(outcome.status, outcome.code, outcome.error);
1937
+ }
1938
+ const statuses = [];
1939
+ const selection = [];
1940
+ // Each group resolves its own org connection, so no API version pin leaks between groups.
1941
+ for (const plan of plans) {
1942
+ let outcome;
1943
+ try {
1944
+ outcome = await plan.run();
1945
+ }
1946
+ catch (error) {
1947
+ // A throw that escapes one group fails that group only; the other groups still run.
1948
+ outcome = { status: 'failed', selection: plan.members, code: 'RETRIEVE_FAILED', error };
1949
+ }
1950
+ statuses.push(outcome.status);
1951
+ selection.push(...outcome.selection);
1952
+ if (outcome.code)
1953
+ envelope.diagnostics.errors.push({
1954
+ code: outcome.code,
1955
+ message: retrievalMessage(outcome.error),
1956
+ retryable: false,
1957
+ family: outcome.family ?? plan.family,
1958
+ });
165
1959
  }
166
- return finish(envelope.diagnostics.errors.length === 0 ? 'success' : failed ? 'failed' : 'blocked');
1960
+ envelope.result.selection = selection;
1961
+ return finish(statuses.includes('failed') ? 'failed' : statuses.includes('blocked') ? 'blocked' : 'success');
167
1962
  }
168
1963
  }