sf-plugin-data 0.1.0 → 0.3.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 (277) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +618 -240
  3. package/docs/artifact-format.md +528 -633
  4. package/docs/capabilities.md +1160 -168
  5. package/docs/git-workflow.md +135 -12
  6. package/docs/handover.md +7826 -12
  7. package/lib/api.d.ts +13 -0
  8. package/lib/api.js +10 -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 +2347 -0
  75. package/lib/commands/data360/deploy.d.ts +235 -16
  76. package/lib/commands/data360/deploy.js +2339 -102
  77. package/lib/commands/data360/list/dataspace.d.ts +53 -0
  78. package/lib/commands/data360/list/dataspace.js +109 -0
  79. package/lib/commands/data360/publish.d.ts +93 -0
  80. package/lib/commands/data360/publish.js +298 -0
  81. package/lib/commands/data360/retrieve.d.ts +283 -14
  82. package/lib/commands/data360/retrieve.js +1945 -95
  83. package/lib/commands/data360/segment/members/export.d.ts +101 -0
  84. package/lib/commands/data360/segment/members/export.js +320 -0
  85. package/lib/errors/codes/calculated-insight.d.ts +2 -0
  86. package/lib/errors/codes/calculated-insight.js +25 -0
  87. package/lib/errors/codes/data-graph.d.ts +2 -0
  88. package/lib/errors/codes/data-graph.js +22 -0
  89. package/lib/errors/codes/data-stream.d.ts +2 -0
  90. package/lib/errors/codes/data-stream.js +70 -0
  91. package/lib/errors/codes/data-transform.d.ts +2 -0
  92. package/lib/errors/codes/data-transform.js +35 -0
  93. package/lib/errors/codes/dependency.d.ts +2 -0
  94. package/lib/errors/codes/dependency.js +11 -0
  95. package/lib/errors/codes/dlo.d.ts +2 -0
  96. package/lib/errors/codes/dlo.js +31 -0
  97. package/lib/errors/codes/dmo.d.ts +2 -0
  98. package/lib/errors/codes/dmo.js +28 -0
  99. package/lib/errors/codes/general.d.ts +2 -0
  100. package/lib/errors/codes/general.js +58 -0
  101. package/lib/errors/codes/identity-resolution.d.ts +2 -0
  102. package/lib/errors/codes/identity-resolution.js +24 -0
  103. package/lib/errors/codes/mapping.d.ts +2 -0
  104. package/lib/errors/codes/mapping.js +42 -0
  105. package/lib/errors/codes/relationship.d.ts +2 -0
  106. package/lib/errors/codes/relationship.js +21 -0
  107. package/lib/errors/codes/segment.d.ts +2 -0
  108. package/lib/errors/codes/segment.js +49 -0
  109. package/lib/errors/registry.d.ts +60 -0
  110. package/lib/errors/registry.js +123 -0
  111. package/lib/exit-code.d.ts +10 -0
  112. package/lib/exit-code.js +24 -0
  113. package/lib/plugin.d.ts +1 -0
  114. package/lib/plugin.js +3 -1
  115. package/lib/services/acquire-retrieve-selection.d.ts +43 -0
  116. package/lib/services/acquire-retrieve-selection.js +145 -0
  117. package/lib/services/bind-identity-resolution-dependencies.d.ts +53 -0
  118. package/lib/services/bind-identity-resolution-dependencies.js +238 -0
  119. package/lib/services/bind-segment-dependencies.d.ts +49 -0
  120. package/lib/services/bind-segment-dependencies.js +115 -0
  121. package/lib/services/bounded-reads.d.ts +17 -0
  122. package/lib/services/bounded-reads.js +42 -0
  123. package/lib/services/calculated-insight-sql-checks.d.ts +33 -0
  124. package/lib/services/calculated-insight-sql-checks.js +193 -0
  125. package/lib/services/command-dlo.d.ts +48 -0
  126. package/lib/services/command-dlo.js +103 -0
  127. package/lib/services/command-native-data-graph.d.ts +54 -0
  128. package/lib/services/command-native-data-graph.js +485 -0
  129. package/lib/services/command-native-data-stream.d.ts +104 -0
  130. package/lib/services/command-native-data-stream.js +257 -0
  131. package/lib/services/command-native-dmo.d.ts +124 -0
  132. package/lib/services/command-native-dmo.js +338 -0
  133. package/lib/services/command-native-mapping.d.ts +65 -0
  134. package/lib/services/command-native-mapping.js +129 -0
  135. package/lib/services/command-native-relationship.d.ts +46 -0
  136. package/lib/services/command-native-relationship.js +103 -0
  137. package/lib/services/cross-dataspace-deploy.d.ts +111 -0
  138. package/lib/services/cross-dataspace-deploy.js +493 -0
  139. package/lib/services/cross-dataspace-rename.d.ts +74 -0
  140. package/lib/services/cross-dataspace-rename.js +1314 -0
  141. package/lib/services/cross-dataspace-sql.d.ts +109 -0
  142. package/lib/services/cross-dataspace-sql.js +1301 -0
  143. package/lib/services/cross-space-context.d.ts +23 -0
  144. package/lib/services/cross-space-context.js +38 -0
  145. package/lib/services/crud-plan.d.ts +137 -0
  146. package/lib/services/crud-plan.js +408 -0
  147. package/lib/services/data-space-check.d.ts +92 -0
  148. package/lib/services/data-space-check.js +169 -0
  149. package/lib/services/data-space-prefix.d.ts +77 -0
  150. package/lib/services/data-space-prefix.js +127 -0
  151. package/lib/services/data-transform-space.d.ts +31 -0
  152. package/lib/services/data-transform-space.js +79 -0
  153. package/lib/services/delete-calculated-insight.d.ts +44 -0
  154. package/lib/services/delete-calculated-insight.js +101 -0
  155. package/lib/services/delete-data-transform.d.ts +52 -0
  156. package/lib/services/delete-data-transform.js +222 -0
  157. package/lib/services/delete-dmo-field.d.ts +211 -0
  158. package/lib/services/delete-dmo-field.js +472 -0
  159. package/lib/services/delete-identity-resolution.d.ts +43 -0
  160. package/lib/services/delete-identity-resolution.js +295 -0
  161. package/lib/services/delete-segment.d.ts +42 -0
  162. package/lib/services/delete-segment.js +248 -0
  163. package/lib/services/deploy-result.d.ts +54 -0
  164. package/lib/services/deploy-result.js +60 -0
  165. package/lib/services/escaped-copy.d.ts +23 -0
  166. package/lib/services/escaped-copy.js +88 -0
  167. package/lib/services/execute-calculated-insight-deploy.d.ts +42 -0
  168. package/lib/services/execute-calculated-insight-deploy.js +96 -0
  169. package/lib/services/execute-data-transform-deploy.d.ts +56 -0
  170. package/lib/services/execute-data-transform-deploy.js +168 -0
  171. package/lib/services/execute-native-identity-resolution-deploy.d.ts +48 -0
  172. package/lib/services/execute-native-identity-resolution-deploy.js +360 -0
  173. package/lib/services/execute-segment-deploy.d.ts +45 -0
  174. package/lib/services/execute-segment-deploy.js +393 -0
  175. package/lib/services/list-data-spaces.d.ts +17 -0
  176. package/lib/services/list-data-spaces.js +24 -0
  177. package/lib/services/local-file-removal.d.ts +36 -0
  178. package/lib/services/local-file-removal.js +103 -0
  179. package/lib/services/native-calculated-insight.d.ts +87 -0
  180. package/lib/services/native-calculated-insight.js +164 -0
  181. package/lib/services/native-crm-data-stream.d.ts +91 -0
  182. package/lib/services/native-crm-data-stream.js +272 -0
  183. package/lib/services/native-data-graph-context.d.ts +12 -0
  184. package/lib/services/native-data-graph-context.js +139 -0
  185. package/lib/services/native-data-graph-crd.d.ts +261 -0
  186. package/lib/services/native-data-graph-crd.js +866 -0
  187. package/lib/services/native-data-stream.d.ts +329 -0
  188. package/lib/services/native-data-stream.js +1830 -0
  189. package/lib/services/native-dlo.d.ts +163 -0
  190. package/lib/services/native-dlo.js +402 -0
  191. package/lib/services/native-dmo.d.ts +191 -0
  192. package/lib/services/native-dmo.js +614 -0
  193. package/lib/services/native-mapping.d.ts +255 -0
  194. package/lib/services/native-mapping.js +1226 -0
  195. package/lib/services/native-relationship.d.ts +132 -0
  196. package/lib/services/native-relationship.js +512 -0
  197. package/lib/services/operation-diagnostic.d.ts +83 -0
  198. package/lib/services/operation-diagnostic.js +272 -0
  199. package/lib/services/preflight-calculated-insight-deploy.d.ts +58 -0
  200. package/lib/services/preflight-calculated-insight-deploy.js +95 -0
  201. package/lib/services/preflight-data-transform-deploy.d.ts +33 -0
  202. package/lib/services/preflight-data-transform-deploy.js +104 -0
  203. package/lib/services/preflight-identity-resolution-deploy.d.ts +107 -0
  204. package/lib/services/preflight-identity-resolution-deploy.js +281 -0
  205. package/lib/services/preflight-segment-deploy.d.ts +31 -0
  206. package/lib/services/preflight-segment-deploy.js +109 -0
  207. package/lib/services/publish-calculated-insight.d.ts +40 -0
  208. package/lib/services/publish-calculated-insight.js +95 -0
  209. package/lib/services/publish-segment.d.ts +65 -0
  210. package/lib/services/publish-segment.js +194 -0
  211. package/lib/services/readback-pace.d.ts +16 -0
  212. package/lib/services/readback-pace.js +23 -0
  213. package/lib/services/retrieve-data-transform.d.ts +26 -0
  214. package/lib/services/retrieve-data-transform.js +65 -0
  215. package/lib/services/retrieve-identity-resolution.d.ts +40 -0
  216. package/lib/services/retrieve-identity-resolution.js +87 -0
  217. package/lib/services/retrieve-inventory.d.ts +32 -0
  218. package/lib/services/retrieve-inventory.js +151 -0
  219. package/lib/services/retrieve-segment.d.ts +120 -0
  220. package/lib/services/retrieve-segment.js +502 -0
  221. package/lib/services/run-retrieve.d.ts +24 -0
  222. package/lib/services/run-retrieve.js +51 -0
  223. package/lib/services/segment-lookup.d.ts +46 -0
  224. package/lib/services/segment-lookup.js +108 -0
  225. package/lib/services/segment-members.d.ts +144 -0
  226. package/lib/services/segment-members.js +402 -0
  227. package/lib/services/select-native-retrieve.d.ts +60 -0
  228. package/lib/services/select-native-retrieve.js +226 -0
  229. package/lib/services/settle-calculated-insight.d.ts +22 -0
  230. package/lib/services/settle-calculated-insight.js +53 -0
  231. package/lib/services/sql-tokens.d.ts +58 -0
  232. package/lib/services/sql-tokens.js +147 -0
  233. package/lib/transport/api-version.d.ts +36 -0
  234. package/lib/transport/api-version.js +89 -0
  235. package/lib/transport/bound-ssot.d.ts +27 -0
  236. package/lib/transport/bound-ssot.js +116 -0
  237. package/lib/transport/calculated-insight-rest.d.ts +28 -0
  238. package/lib/transport/calculated-insight-rest.js +62 -0
  239. package/lib/transport/connect-client.d.ts +94 -32
  240. package/lib/transport/connect-client.js +318 -178
  241. package/lib/transport/connect-diagnostic.d.ts +89 -0
  242. package/lib/transport/connect-diagnostic.js +331 -0
  243. package/lib/transport/data-graph-rest.d.ts +27 -0
  244. package/lib/transport/data-graph-rest.js +76 -0
  245. package/lib/transport/data-stream-rest.d.ts +62 -0
  246. package/lib/transport/data-stream-rest.js +348 -0
  247. package/lib/transport/data-transform-rest.d.ts +25 -0
  248. package/lib/transport/data-transform-rest.js +100 -0
  249. package/lib/transport/dlo-native-rest.d.ts +22 -0
  250. package/lib/transport/dlo-native-rest.js +89 -0
  251. package/lib/transport/dlo-rest.d.ts +23 -0
  252. package/lib/transport/dlo-rest.js +135 -0
  253. package/lib/transport/dmo-native-rest.d.ts +18 -0
  254. package/lib/transport/dmo-native-rest.js +55 -0
  255. package/lib/transport/dmo-rest.d.ts +30 -0
  256. package/lib/transport/dmo-rest.js +163 -0
  257. package/lib/transport/mapping-rest.d.ts +63 -0
  258. package/lib/transport/mapping-rest.js +341 -0
  259. package/lib/transport/project-metadata.d.ts +36 -0
  260. package/lib/transport/project-metadata.js +118 -0
  261. package/lib/transport/relationship-rest.d.ts +43 -0
  262. package/lib/transport/relationship-rest.js +201 -0
  263. package/package.json +29 -6
  264. package/lib/artifacts/dmo-document.d.ts +0 -181
  265. package/lib/artifacts/dmo-document.js +0 -848
  266. package/lib/artifacts/dmo-update-delta.d.ts +0 -28
  267. package/lib/artifacts/dmo-update-delta.js +0 -86
  268. package/lib/artifacts/write-other-dmo.d.ts +0 -17
  269. package/lib/artifacts/write-other-dmo.js +0 -140
  270. package/lib/services/execute-dmo-create.d.ts +0 -24
  271. package/lib/services/execute-dmo-create.js +0 -118
  272. package/lib/services/execute-dmo-deploy.d.ts +0 -33
  273. package/lib/services/execute-dmo-deploy.js +0 -197
  274. package/lib/services/preflight-dmo-deploy.d.ts +0 -69
  275. package/lib/services/preflight-dmo-deploy.js +0 -161
  276. package/lib/services/retrieve-other-dmo.d.ts +0 -46
  277. package/lib/services/retrieve-other-dmo.js +0 -140
@@ -0,0 +1,2347 @@
1
+ import { deleteDataTransform, resolveDataTransformTargetId, } from '../../services/delete-data-transform.js';
2
+ import { GitSelectionError, selectGitDeployInputs } from '../../artifacts/git-deploy-selection.js';
3
+ import { createVerbatimDocument, isVerbatimDocument, verbatimDataSpace, verbatimReason, } from '../../artifacts/verbatim-document.js';
4
+ import { DataGraphError } from '../../artifacts/data-graph-document.js';
5
+ import { createDataTransformClient } from '../../transport/data-transform-rest.js';
6
+ import { DataTransformError, dataTransformSpaceMismatch, validateDataTransformDocument, } from '../../artifacts/data-transform-document.js';
7
+ import { retrieveDataTransform } from '../../services/retrieve-data-transform.js';
8
+ import { deleteSegment } from '../../services/delete-segment.js';
9
+ import { SegmentError, validateSegmentDocument } from '../../artifacts/segment-document.js';
10
+ import { projectSegment, segmentChildNames, segmentSpaceMismatch, } from '../../services/retrieve-segment.js';
11
+ import { deleteIdentityResolution } from '../../services/delete-identity-resolution.js';
12
+ import { IdentityResolutionError, identityResolutionName, identityResolutionSpace, identityResolutionSpaceMismatch, projectNativeIdentityResolution, validateIdentityResolutionDocument, } from '../../artifacts/identity-resolution-document.js';
13
+ import { operateNativeDataGraph, nativeGraphLimitations, } from '../../services/command-native-data-graph.js';
14
+ import { nativeDataGraphReadContext } from '../../services/native-data-graph-context.js';
15
+ import { proveNativeDataGraphAbsent } from '../../services/native-data-graph-crd.js';
16
+ import { createDataGraphClient } from '../../transport/data-graph-rest.js';
17
+ import { nativeDataGraphDocumentFromResponse, nativeDataGraphSpace, nativeDataGraphSpaceMismatch, } from '../../artifacts/native-data-graph-document.js';
18
+ import { DeployInputError } from '../../artifacts/read-deploy-input.js';
19
+ import { CalculatedInsightError, calculatedInsightReference, } from '../../artifacts/native-calculated-insight-document.js';
20
+ import { deleteCalculatedInsight } from '../../services/delete-calculated-insight.js';
21
+ import { acquireCalculatedInsight, calculatedInsightReadContext, } from '../../services/native-calculated-insight.js';
22
+ import { ConnectError } from '../../transport/connect-client.js';
23
+ import { getConnectDiagnostic, retainConnectDiagnostic, } from '../../transport/connect-diagnostic.js';
24
+ import { explainSpaceMismatch, operationDiagnostic, replaceExplanation, } from '../../services/operation-diagnostic.js';
25
+ import { rejectedNextAction } from '../../services/deploy-result.js';
26
+ import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js';
27
+ import { exitCodeOf } from '../../exit-code.js';
28
+ import { nativeDmoFieldName, nativeDmoName, NativeDmoError, } from '../../artifacts/native-dmo-document.js';
29
+ import { writeNativeDmoDocument } from '../../artifacts/write-native-dmo.js';
30
+ import { writeNativeMappingDocument } from '../../artifacts/write-native-mapping.js';
31
+ import { NativeRelationshipError, nativeRelationshipName, relationshipDmoName, } from '../../artifacts/native-relationship-document.js';
32
+ import { createRelationshipClient } from '../../transport/relationship-rest.js';
33
+ import { deleteNativeRelationship, findNativeRelationshipByName, preflightDeleteNativeRelationship, } from '../../services/native-relationship.js';
34
+ import { dmoFieldLocalFiles, executeDmoFieldDelete, localFileExists, mappingLocalFile, planDmoFieldDelete, refreshDmoFieldFiles, } from '../../services/delete-dmo-field.js';
35
+ import { localFilePresent, removeLocalFiles } from '../../services/local-file-removal.js';
36
+ import path from 'node:path';
37
+ import { createDmoClient } from '../../transport/dmo-rest.js';
38
+ import { createNativeDmoDeleteClient } from '../../transport/dmo-native-rest.js';
39
+ import { openBoundSsot } from '../../transport/bound-ssot.js';
40
+ import { deleteNativeDmo, previewDeleteNativeDmo } from '../../services/native-dmo.js';
41
+ import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
42
+ import { AuthInfo, ConfigAggregator, Connection, StateAggregator } from '@salesforce/core';
43
+ import { DloError, dloName } from '../../artifacts/dlo-document.js';
44
+ import { createDloClient } from '../../transport/dlo-rest.js';
45
+ import { createNativeDloDeleteClient } from '../../transport/dlo-native-rest.js';
46
+ import { admitDloDependents, deleteNativeDlo, previewDeleteNativeDlo, waitForDloDependents, } from '../../services/native-dlo.js';
47
+ import { DataSpaceError, dataSpaceCheckOf } from '../../services/data-space-check.js';
48
+ import { reportedIdentity } from '../../artifacts/data-space-field.js';
49
+ import { plugin } from '../../plugin.js';
50
+ import { nativeMappingName, NativeMappingError, normalizeNativeMapping, unwrapNativeMappingCollection, validateNativeMappingDocument, } from '../../artifacts/native-mapping-document.js';
51
+ import { createMappingClient } from '../../transport/mapping-rest.js';
52
+ import { confirmNativeMappingAbsent, deleteNativeMapping, preflightDeleteNativeMapping, resolveNativeMappingTarget, } from '../../services/native-mapping.js';
53
+ import { lstat, readdir, readFile } from 'node:fs/promises';
54
+ import { nativeApiVersion, dataStreamApiVersion, operationApiVersion, } from '../../transport/api-version.js';
55
+ import { DataStreamError } from '../../artifacts/data-stream-document.js';
56
+ import { ConnectClient } from '../../transport/connect-client.js';
57
+ import { createDataStreamClient, createDataStreamReferenceReader, } from '../../transport/data-stream-rest.js';
58
+ import { preflightDeleteDataStream, executeDeleteDataStream, watchStreamAbsence, } from '../../services/command-native-data-stream.js';
59
+ import { retrieveNativeDataStream } from '../../services/native-data-stream.js';
60
+ import { inputKey, planDeleteStages, runCrudStages, selectedDependents, } from '../../services/crud-plan.js';
61
+ /** Families whose definition a delete reads from the org by name (from the base file with Git). */
62
+ const sourceFamilies = new Set([
63
+ 'data-transform',
64
+ 'segment',
65
+ 'identity-resolution',
66
+ 'data-graph',
67
+ 'calculated-insight',
68
+ ]);
69
+ const nativeFamilies = new Set([
70
+ 'dlo',
71
+ 'dmo',
72
+ 'mapping',
73
+ 'relationship',
74
+ ]);
75
+ const developerName = /^[A-Za-z][A-Za-z0-9_]{0,199}$/u;
76
+ /**
77
+ * Family of an exact `family:Name` delete selector.
78
+ * @param {string} selector Raw -m value.
79
+ * @param {boolean} [git] Selector built from a file deleted in a Git range.
80
+ * @returns {DeleteFamily | undefined} The family; undefined for anything not exact.
81
+ */
82
+ function deleteFamily(selector, git = false) {
83
+ const index = selector.indexOf(':');
84
+ if (index === -1)
85
+ return undefined;
86
+ const family = selector.slice(0, index);
87
+ const name = selector.slice(index + 1);
88
+ switch (family) {
89
+ case 'data-transform':
90
+ case 'segment':
91
+ case 'data-graph':
92
+ case 'data-stream': {
93
+ return developerName.test(name) ? family : undefined;
94
+ }
95
+ case 'identity-resolution': {
96
+ return identityResolutionName.test(name) ? family : undefined;
97
+ }
98
+ case 'calculated-insight': {
99
+ return /^[A-Za-z][A-Za-z0-9_]*__cio$/u.test(name) ? family : undefined;
100
+ }
101
+ case 'dlo': {
102
+ return dloName.test(name) ? family : undefined;
103
+ }
104
+ case 'dmo': {
105
+ return nativeDmoName.test(name) ? family : undefined;
106
+ }
107
+ case 'mapping': {
108
+ return nativeMappingName.test(name) ? family : undefined;
109
+ }
110
+ case 'relationship': {
111
+ // -m names the source DMO too (relationship:<SourceDmo__dlm>:<Name>); a file deleted in a
112
+ // Git range carries it in its base content, so its selector is relationship:<Name>.
113
+ const parts = name.split(':');
114
+ return git
115
+ ? parts.length === 1 && nativeRelationshipName.test(name)
116
+ ? family
117
+ : undefined
118
+ : parts.length === 2 &&
119
+ relationshipDmoName.test(parts[0]) &&
120
+ nativeRelationshipName.test(parts[1])
121
+ ? family
122
+ : undefined;
123
+ }
124
+ default: {
125
+ return undefined;
126
+ }
127
+ }
128
+ }
129
+ /**
130
+ * The refusal for a selector that is not exact, in the code of the family it names.
131
+ * @param {string} selector Raw -m value.
132
+ * @returns {Error} Coded refusal.
133
+ */
134
+ function selectorError(selector) {
135
+ if (selector === 'data-transform' || selector.startsWith('data-transform:'))
136
+ return new DataTransformError('INVALID_TRANSFORM_DELETE_SELECTION');
137
+ if (selector === 'data-stream' || selector.startsWith('data-stream:'))
138
+ return new DataStreamError('INVALID_STREAM_DELETE_SELECTION');
139
+ const error = new DloError('INVALID_SELECTION');
140
+ if (selector === 'relationship' || selector.startsWith('relationship:'))
141
+ replaceExplanation(error, 'A relationship is deleted as -m relationship:<SourceDmo__dlm>:<Name>, naming its source DMO and its exact name. Nothing was deleted.');
142
+ return error;
143
+ }
144
+ /**
145
+ * Name part of an exact selector (of relationship:<SourceDmo__dlm>:<Name>, the relationship name).
146
+ * @param {string} selector Exact `family:Name` selector.
147
+ * @returns {string} The name.
148
+ */
149
+ function selectorName(selector) {
150
+ return selector.slice(selector.lastIndexOf(':') + 1);
151
+ }
152
+ /**
153
+ * The data space list a DLO or data stream file names (every space of the DLO), or undefined
154
+ * for a file with a single data space (or a verbatim file).
155
+ * @param {unknown} document Deleted file's base document.
156
+ * @returns {string[] | undefined} Its list.
157
+ */
158
+ function spaceListOf(document) {
159
+ if (isVerbatimDocument(document))
160
+ return undefined;
161
+ const listed = document?.c__dataSpace;
162
+ return Array.isArray(listed) ? listed : undefined;
163
+ }
164
+ /**
165
+ * Native delete order inside P1. Dependents go first: relationships (which need their DMOs),
166
+ * mappings, then DMOs (which take their mappings along), then DLOs.
167
+ * @param {string} selector Exact native selector.
168
+ * @returns {number} Rank.
169
+ */
170
+ function nativeOrder(selector) {
171
+ return selector.startsWith('relationship:')
172
+ ? 0
173
+ : selector.startsWith('mapping:')
174
+ ? 1
175
+ : selector.startsWith('dmo:')
176
+ ? 2
177
+ : 3;
178
+ }
179
+ /**
180
+ * Read-only: the landing DLO a data stream owns, read from the stream itself.
181
+ * @param {string} apiName Exact stream name.
182
+ * @param {object} clients Native stream readers.
183
+ * @returns {Promise<string | undefined>} The linked DLO name.
184
+ */
185
+ async function readStreamLinkedDlo(apiName, clients) {
186
+ const watched = watchStreamAbsence(apiName, clients);
187
+ try {
188
+ const document = await retrieveNativeDataStream(apiName, watched.clients);
189
+ return document.spec.newDlo.name;
190
+ }
191
+ catch (error) {
192
+ // A stream that is already gone links no DLO; its delete reports it unchanged.
193
+ if (watched.absent())
194
+ return undefined;
195
+ // A stream the plugin cannot model names its DLO in the raw GET.
196
+ if (verbatimReason(error) === undefined)
197
+ throw error;
198
+ const raw = (await watched.clients.streams.get(apiName));
199
+ if (raw?.name !== apiName)
200
+ throw error;
201
+ const dlo = raw.dataLakeObjectInfo?.name;
202
+ return typeof dlo === 'string' ? dlo : undefined;
203
+ }
204
+ }
205
+ /**
206
+ * Document kind of a source family, as the plan names it.
207
+ * @param {DeleteFamily} family Source family.
208
+ * @returns {string} The document kind.
209
+ */
210
+ const documentKind = (family) => family === 'data-graph' ? 'native-data-graph' : family;
211
+ /**
212
+ * Read-only: the current definition of one source-family component, read from the org by name.
213
+ * A transform name must match exactly one transform (ignoring case); none is absent.
214
+ * @param {DeleteFamily} family Source family of the selector.
215
+ * @param {string} name Exact name from the selector.
216
+ * @param {Connection} connection API68 connection of the target org.
217
+ * @param {object} readers Command seams used for the transform, CI and graph reads.
218
+ * @param {Function} readers.transformClient Transform client factory.
219
+ * @param {Function} readers.ciContext CI read context factory.
220
+ * @param {Function} readers.graphContext Native graph read context factory.
221
+ * @param {string} dataSpace The run's data space (a component of another data space is refused).
222
+ * @returns {Promise<AdmittedSource>} The definition, or absent.
223
+ */
224
+ async function readOrgSource(family, name, connection, readers, dataSpace) {
225
+ // A GET the plugin cannot model is deleted by type and name, like a verbatim file: the
226
+ // service then checks only identity, scope, protection and dependents. Read failures,
227
+ // absence and identity mismatches stay refusals.
228
+ const byName = (kind, error) => {
229
+ const reason = verbatimReason(error);
230
+ const document = reason === undefined
231
+ ? undefined
232
+ : createVerbatimDocument(kind, { dataSpace, apiName: name }, reason);
233
+ if (document === undefined)
234
+ throw error;
235
+ return { desired: document };
236
+ };
237
+ const project = (kind, projection) => {
238
+ try {
239
+ return { desired: projection() };
240
+ }
241
+ catch (error) {
242
+ return byName(kind, error);
243
+ }
244
+ };
245
+ // Segment and IR: an exact GET; only ITEM_NOT_FOUND is absence.
246
+ const exact = async (route) => {
247
+ try {
248
+ return await new ConnectClient(connection, '68.0').get(route);
249
+ }
250
+ catch (error) {
251
+ if (error instanceof ConnectError &&
252
+ error.statusCode === 404 &&
253
+ error.nativeCode === 'ITEM_NOT_FOUND')
254
+ return undefined;
255
+ throw error;
256
+ }
257
+ };
258
+ switch (family) {
259
+ case 'data-transform': {
260
+ const client = readers.transformClient(connection, '68.0', dataSpace);
261
+ const targetId = await resolveDataTransformTargetId(client, name);
262
+ if (targetId === undefined)
263
+ return { absent: true };
264
+ try {
265
+ // The data space is resolved before anything is projected: a transform of another data
266
+ // space is refused (never a verbatim stand-in) before any phase deletes anything.
267
+ const observed = await retrieveDataTransform(targetId, client, 'retrieve', undefined, dataSpace);
268
+ return { desired: observed.document, transformTargetId: targetId };
269
+ }
270
+ catch (error) {
271
+ return { ...byName('data-transform', error), transformTargetId: targetId };
272
+ }
273
+ }
274
+ case 'segment': {
275
+ const raw = await exact(`/services/data/v68.0/ssot/segments/${name}`);
276
+ if (raw === undefined)
277
+ return { absent: true };
278
+ // A Waterfall names its children, so the plan deletes it before its selected children.
279
+ // A segment of another data space is refused before any phase deletes anything.
280
+ const found = raw?.segments?.[0]?.dataSpace;
281
+ if (found !== dataSpace)
282
+ throw segmentSpaceMismatch(name, found, dataSpace);
283
+ const children = await segmentChildNames(connection, raw);
284
+ return project('segment', () => projectSegment(raw, name, 'retrieve', children).candidate);
285
+ }
286
+ case 'identity-resolution': {
287
+ const raw = await exact(`/services/data/v68.0/ssot/identity-resolutions/${name}`);
288
+ if (raw === undefined)
289
+ return { absent: true };
290
+ // The item route reads a ruleset of any data space by name: one of another data space is
291
+ // refused before anything is projected or any phase deletes anything.
292
+ const found = identityResolutionSpace(raw);
293
+ if (found !== dataSpace)
294
+ throw identityResolutionSpaceMismatch(name, found, dataSpace, 'org');
295
+ return project('identity-resolution', () => projectNativeIdentityResolution(raw, name, 'retrieve').candidate);
296
+ }
297
+ case 'calculated-insight': {
298
+ // The API 68 GET in any status; the delete itself reads it again by name. The planning
299
+ // view orders it before the selected DMOs and insights its SQL names.
300
+ let acquired;
301
+ try {
302
+ acquired = await acquireCalculatedInsight(readers.ciContext(connection, dataSpace), name);
303
+ }
304
+ catch (error) {
305
+ return byName('calculated-insight', error);
306
+ }
307
+ return acquired.state === 'absent'
308
+ ? { absent: true }
309
+ : { desired: calculatedInsightReference(acquired.document) };
310
+ }
311
+ default: {
312
+ const context = await readers.graphContext(connection, dataSpace);
313
+ const read = await context.get(name);
314
+ if (read.status === 200) {
315
+ // A GET answering with another graph is never deleted, also not by name.
316
+ const body = read.body;
317
+ if (body?.name !== name)
318
+ throw new DataGraphError('DATA_GRAPH_IDENTITY_MISMATCH');
319
+ // Graph names are unique in the org: a graph of another data space is refused before
320
+ // anything is projected or any phase deletes anything.
321
+ const found = nativeDataGraphSpace(body);
322
+ if (found !== dataSpace)
323
+ throw nativeDataGraphSpaceMismatch(name, found, dataSpace, 'org');
324
+ // A draft is retrieved as-is, so it is deleted by name like its verbatim file.
325
+ if (body.status === 'draft')
326
+ return byName('native-data-graph', new DataGraphError('DATA_GRAPH_DRAFT'));
327
+ const admitted = project('native-data-graph', () => nativeDataGraphDocumentFromResponse(read.body, 'retrieve'));
328
+ const definition = admitted.desired
329
+ .definition;
330
+ if (definition !== undefined && definition.name !== name)
331
+ throw new DataGraphError('DATA_GRAPH_IDENTITY_MISMATCH');
332
+ return admitted;
333
+ }
334
+ // HTTP400 alone is never absence: the item, metadata, inventory and SOQL reads must agree.
335
+ const proof = await proveNativeDataGraphAbsent(context, name, read);
336
+ if (proof.state === 'absent')
337
+ return { absent: true };
338
+ const error = retainConnectDiagnostic(new Error('Native Graph read unavailable'), getConnectDiagnostic(proof) ?? getConnectDiagnostic(read));
339
+ if (proof.state === 'pending')
340
+ replaceExplanation(error, `The Data Graph ${name} reads as not found, but its metadata, the graph inventory or SOQL still holds it: it is still being created or removed. Nothing was deleted; rerun once it has settled.`);
341
+ throw error;
342
+ }
343
+ }
344
+ }
345
+ /**
346
+ * Validate the base content of one source-family file deleted in a Git range and name the
347
+ * selector it answers. The file is read as retrieve writes it (retrieve mode).
348
+ * @param {DeployInput} input Resolved input.
349
+ * @returns {{family: DeleteFamily, selector: string, desired: unknown}} Admitted source.
350
+ */
351
+ function admitSourceInput(input) {
352
+ switch (input.document.kind) {
353
+ case 'data-transform': {
354
+ const transform = input;
355
+ const desired = validateDataTransformDocument(transform.document, 'retrieve');
356
+ return {
357
+ family: 'data-transform',
358
+ selector: `data-transform:${String(transform.document.definition.name)}`,
359
+ desired,
360
+ };
361
+ }
362
+ case 'segment': {
363
+ const desired = validateSegmentDocument(input.document, 'retrieve');
364
+ return { family: 'segment', selector: `segment:${desired.identity.apiName}`, desired };
365
+ }
366
+ case 'identity-resolution': {
367
+ const desired = validateIdentityResolutionDocument(input.document, 'retrieve');
368
+ return {
369
+ family: 'identity-resolution',
370
+ selector: `identity-resolution:${desired.identity.apiName}`,
371
+ desired,
372
+ };
373
+ }
374
+ case 'calculated-insight': {
375
+ // The planning view of the base content; any status, schedule and SQL is deletable.
376
+ const desired = input.document;
377
+ return {
378
+ family: 'calculated-insight',
379
+ selector: `calculated-insight:${desired.identity.apiName}`,
380
+ desired,
381
+ };
382
+ }
383
+ case 'native-data-graph': {
384
+ const graph = input;
385
+ return {
386
+ family: 'data-graph',
387
+ selector: `data-graph:${String(graph.document.definition.name)}`,
388
+ desired: graph.document,
389
+ };
390
+ }
391
+ default: {
392
+ throw new DloError('INVALID_SELECTION');
393
+ }
394
+ }
395
+ }
396
+ /** Codes that mean Salesforce is still processing a deletion, not a failure. */
397
+ const notSettledCodes = new Set([
398
+ 'DELETE_PHASE_NOT_SETTLED',
399
+ 'IDENTITY_RESOLUTION_NOT_SETTLED',
400
+ ]);
401
+ /**
402
+ * Salesforce is still processing this item's deletion, or the item waits for one in flight.
403
+ * @param {DeleteItem} item Executed item.
404
+ * @returns {boolean} True when the item is still processing.
405
+ */
406
+ const stillProcessing = (item) => item.outcome === 'deletion-processing' ||
407
+ (item.diagnostics ?? []).some((diagnostic) => notSettledCodes.has(diagnostic.code));
408
+ /**
409
+ * Reduce a pair to the names reported in the result; the selector stays internal.
410
+ * @param {DmoFieldPair} pair Planned or removed pair.
411
+ * @returns {{mapping: string, sourceFieldDeveloperName: string, targetFieldDeveloperName: string}} Reported pair.
412
+ */
413
+ function reportedPair(pair) {
414
+ return {
415
+ mapping: pair.mapping,
416
+ sourceFieldDeveloperName: pair.sourceFieldDeveloperName,
417
+ targetFieldDeveloperName: pair.targetFieldDeveloperName,
418
+ };
419
+ }
420
+ /**
421
+ * Say what a stopped field-level delete had already written and what it had not.
422
+ * @param {DmoFieldDeleteProgress} progress State at the failure.
423
+ * @param {DmoFieldDeletePlan} plan Admitted plan.
424
+ * @returns {string} Next action built only from validated identifiers.
425
+ */
426
+ function fieldDeleteStop(progress, plan) {
427
+ const fields = plan.fields.join(', ');
428
+ const stop = progress.step === 'recheck'
429
+ ? 'Nothing was written; no field or mapping pair was removed.'
430
+ : progress.step === 'remove'
431
+ ? `The Metadata API destructive change for ${fields} was sent once and is not confirmed; read the DMO and its mappings before another attempt.`
432
+ : `The Metadata API destructive change for ${fields} was acknowledged, but the result was not confirmed: the field(s) gone, exactly their mapping pairs dropped, everything else unchanged. Read the DMO and its mappings before another attempt.`;
433
+ return `${stop} No local file was refreshed. No retry or rollback.`;
434
+ }
435
+ /**
436
+ * Word the human output of one field-level delete item.
437
+ * @param {DeleteItem} item Item carrying `fields`.
438
+ * @returns {string[]} Lines in the order the work ran.
439
+ */
440
+ function fieldDeleteLines(item) {
441
+ const name = item.identity.apiName;
442
+ const fields = (item.fields ?? []).join(', ');
443
+ const lines = [];
444
+ if (item.operation === 'preview') {
445
+ if (item.outcome !== 'delete')
446
+ lines.push(`Blocked: dmo:${name} field ${fields}; mutation: ${item.mutation}.`);
447
+ for (const step of item.plan ?? [])
448
+ lines.push(step.operation === 'unmap'
449
+ ? `Planned pair drop (Salesforce removes it with the field): ${step.sourceFieldDeveloperName} -> ${step.targetFieldDeveloperName} in mapping ${step.apiName}.`
450
+ : `Planned field delete: ${step.fieldName} from dmo ${name}.`);
451
+ for (const file of item.localFiles ?? [])
452
+ lines.push(file.exists
453
+ ? `Planned file refresh: ${file.path}`
454
+ : `Not present locally, not created: ${file.path}`);
455
+ return lines;
456
+ }
457
+ for (const pair of item.unmappedPairs ?? [])
458
+ lines.push(`dropped pair ${pair.sourceFieldDeveloperName} -> ${pair.targetFieldDeveloperName} in mapping ${pair.mapping}`);
459
+ if (item.removedFields?.length)
460
+ lines.push(`deleted field ${item.removedFields.join(', ')} from dmo ${name}`);
461
+ else
462
+ lines.push(`${item.outcome === 'blocked' ? 'Blocked' : item.outcome === 'deletion-unconfirmed' ? 'Unconfirmed' : 'Failed'}: dmo:${name} field ${fields}; mutation: ${item.mutation}.`);
463
+ for (const file of item.refreshedFiles ?? [])
464
+ lines.push(file.outcome === 'refreshed'
465
+ ? `refreshed ${file.path}`
466
+ : file.outcome === 'unchanged'
467
+ ? `unchanged ${file.path}`
468
+ : file.outcome === 'not-present'
469
+ ? `not present locally, not created: ${file.path}`
470
+ : `refresh failed (${file.code}): ${file.path}`);
471
+ return lines;
472
+ }
473
+ /** Delete exact native DLO definitions, or preview without mutation. */
474
+ export default class Delete extends SfCommand {
475
+ static aliases = ['datacloud:delete', 'd360:delete', 'dc:delete'];
476
+ static summary = 'Delete exact Data360 Transforms, Segments, IR owners, streams, DLOs, DMOs, single custom DMO fields or mappings.';
477
+ static description = "One delete can carry any mix of families, each named exactly with -m. It runs them in reverse dependency order, one phase after the other: graphs, then identity resolution, calculated insights and Segments (a dependent before the component it needs, including a graph or CI/Segment on the unified DMO of a selected IR), then data transforms, then relationships, mappings, DMOs and DLOs, then data streams. A phase starts only after every item of the previous one settled; a blocked, failed or unconfirmed item stops the run, and an item Salesforce is still processing stops the later phases with DELETE_PHASE_NOT_SETTLED (status processing, exit 69, when nothing failed). A -m delete needs no confirmation flag: check the selection with --preview first. Before the first delete, the current definition of each selected transform, Segment, IR, CI and graph is read from the org by its name (read-only); one the org does not have reports unchanged. A transform name resolves to its target ID through the complete transform list: no match is unchanged, two or more matches (ignoring case) are refused with TRANSFORM_TARGET_NOT_RESOLVED. --changed-since <ref> selects the canonical plugin files deleted since the merge base with that reference (every family; changed files are ignored) and deletes their components in the same phase order. Identity and definition come from each file's base content; a path present again is not a delete, while a rename (also one split across commit, index and worktree), an unstaged deletion or a deleted file of no known family blocks before any org call (BLOCKED_GIT_LIFECYCLE). A --changed-since delete needs --confirm-delete (--preview runs without it; --confirm-delete is accepted only with --changed-since), takes no -m or --delete-dlo, and removes no local file. A deleted data transform is resolved by its name like a -m one; a relationship takes its source DMO from the base content; a stream file deleted together with its landing DLO file deletes the stream with its DLO. --preview runs every phase read-only and reports an item whose selected dependents an earlier phase deletes as planned-dependencies (DEPENDENCIES_PLANNED) without checking it further. A stream selected together with its landing DLO is deleted with --delete-dlo semantics and the DLO item reports removedWith the stream; the last mapping of a custom DMO selected together with that DMO is not sent on its own and reports removedWith the DMO; it reports deleted only once its own read answers 404 after the DMO deletion, otherwise deletion-unconfirmed (MAPPING_DELETION_UNCONFIRMED). data-transform:Name uses auto/API68 in the run data space (TRANSFORM_DATASPACE_MISMATCH for another). Preview is GET-only. A target of any owner or namespace is deleted with one native DELETE (Salesforce decides; a 4xx answer is reported as rejected); one whose status is PROCESSING is refused before it (TRANSFORM_DELETE_PROCESSING, in --preview too); settlement needs complete bounded inventory omission of both ID and name, otherwise the result is deletion-unconfirmed (never replay). No DLO, run or data cleanup; exhaustive external-consumer exclusion is not established. segment:Name uses auto/API68 in the run data space (the stored name, <prefix>_<Name> outside default; SEGMENT_DATASPACE_MISMATCH for another). Fresh source bindings and exact runtime/private identity are checked before one native DELETE. Only independent absence or a preserved DELETING/PROCESSING read acknowledges the result; HTTP204 alone is insufficient. No replay, Segment XML, shared-DMO deletion or physical-output cleanup guarantee. identity-resolution:ObjectApiName uses auto/API68 in the run data space (the stored name, <prefix>_<type>_<rulesetId> outside default; IDENTITY_RESOLUTION_DATASPACE_MISMATCH for another) and deletes a present owner that is not PUBLISHING or DELETING. A fresh target-local ID is resolved before one native68 DELETE; bounded exact ID/name absence confirms owner-definition deletion only. Exhaustive external-consumer exclusion and physical profile/output cleanup remain unverified. IR never cascades, runs processing, replays writes or falls back to another API. data-graph:Name uses auto/API68 in the run data space (graph names are unique in the org; DATA_GRAPH_DATASPACE_MISMATCH for a graph of another). Fresh identity, created date, definition, root and ready checks plus explicit empty native dependency/related-segment arrays are mandatory. A draft graph (never built, retrieved as-is) is deleted by name with the same scope and dependency checks. Exhaustive external-consumer exclusion remains unverified; no generated-resource cleanup, storage or credit guarantee. A Graph delete never cascades. calculated-insight:Name__cio uses --api-version auto (68.0) or 68.0 in the run data space (the GET must name it, CI_IDENTITY_CHANGED otherwise). The insight is read by name with the API 68 GET (absent is unchanged; it must answer with that name and data space), deleted with one DELETE in any status, schedule or SQL (Salesforce decides; a 4xx answer is reported as rejected), then read until it answers 404. CI never cascades; no compute, storage or credits guarantee. Exact data-stream:ApiName selects guarded IngestApi stream deletion at auto/API68 in the run data space (its DLO must belong to it). The linked DLO is preserved by default; --delete-dlo explicitly acknowledges deleting that exclusively linked DLO. Selected stream and linked DLO checks only, not unrelated-org preservation. Native routes default to API68; explicit numeric pins are preserved. Relationship deletion (relationship:SourceDmo__dlm:Name; a bare relationship:Name is refused with INVALID_SELECTION) runs first in its phase, before mappings, DMOs and DLOs. The relationships of the named source DMO are listed and the name is looked up ignoring letter case: no match is unchanged, two matches are refused (AMBIGUOUS_RELATIONSHIP_TARGET), and a match whose source object is another DMO is refused (RELATIONSHIP_TARGET_BINDING_MISMATCH). In a --changed-since delete the source DMO and binding come from the deleted file, and when its name is absent but the binding exists under another name the delete is refused with RELATIONSHIP_NAME_MISMATCH. Otherwise one DELETE is sent and its absence confirmed by listing again; a 4xx answer is reported as rejected. --preview only lists. A mapping:Name with a valid local data360/mapping/Name.mapping-meta.json file (with --changed-since, the deleted file's base content) is found in the org the way deploy finds it: by the file's source DLO and target DMO, whatever Salesforce named it (the org name is reported as targetApiName). No org mapping with that binding is unchanged; two or more are refused with AMBIGUOUS_MAPPING_TARGET before any write. Otherwise the exact name is read, and a mapping that reads absent (404) reports unchanged. Mapping deletion runs at native API 61 and up (default 68) and deletes the whole mapping with one Metadata API destructive deployment (ObjectSourceTargetMap), whatever pairs it holds, also onto a standard DMO (Salesforce refuses the last mapping onto a standard DMO copy in a data space other than default; a Failed destructive deployment is reported as rejected). Afterwards the mapping must read absent and the other mappings and the fields of the DMO must be unchanged. The last mapping of a custom DMO is refused before any write (MAPPING_LAST_MAPPING_DELETE_BLOCKED) because Salesforce does not delete it; delete the DMO instead, which removes its mapping. Qualification uses empty custom fixtures, not populated-data guarantees. --preview performs zero writes and reports the planned step. Any partial failure stops the batch; no retries or rollback. Whole-DMO deletion is sent for every DMO, a standard one (creationType Standard) and one read without a creationType included, and Salesforce decides: a 4xx answer is reported as rejected (for example, Salesforce refuses to delete a platform-generated DMO while the identity resolution or graph that owns it exists). Field-level delete: exactly one dmo:Name__dlm with one or more --field Name__c removes the named fields from that DMO. It is the one delete operation that changes mappings it was not given and writes project files. Reads first: every field must exist on the DMO. Any field but the primary key may be named, also the standard, system and generated fields of any DMO: Salesforce decides, and a refused destructive change is reported as rejected. This is the only command that removes such platform-owned fields; every mapping pair targeting a named field is collected, and a mapped field is refused only when the mapping list fails; one that no mapping lists a pair for has no pair to lose and is removed. Then one Metadata API destructive change for all fields, sent once and never retried; Salesforce drops the mapping pairs of the removed fields itself. Fresh reads right before it must still match the plan, and polled reads afterwards must show the fields absent, exactly the collected pairs gone and every other mapping, pair, DMO property and field unchanged; any other difference fails with DMO_FIELD_REMOVAL_SIDE_EFFECT. Nothing is rolled back. After success the existing data360/dmo and data360/mapping files under --output-dir (default: current directory) are overwritten with the current definitions; absent files are not created and no file is deleted. A failed file refresh keeps the confirmed org result and the run is partial (exit 68, LOCAL_REFRESH_FAILED). --field --preview writes nothing and reports pairs, fields and files. --field cannot be combined with another selector, --changed-since or --delete-dlo. Local files: after a confirmed deletion (deleted, or a DLO, DMO, Segment or IR Salesforce accepted and is still deleting) the component's own local file is removed by default, one regular file at a time at its canonical path and never a folder: data360/dlo, data360/dmo, data360/relationship, data360/data-stream, data360/dataTransforms, data360/identityResolution and data360/dataGraphs files, both files of a CI (data360/calculatedInsights/Name__cio.calculatedInsight-meta.json and .calculatedInsight-meta.sql) and the Segment files (data360/segments/Name.segment.json and every Name.segment.*.sql beside it) under the current directory (with --delete-dlo also the linked DLO's file), and the mapping file of that name or the one whose binding matches. Links, hard-linked files and paths outside those folders are refused. Nothing is removed on --preview, which lists the files instead, nor for unchanged, blocked, failed, rejected or unconfirmed deletions. --keep-local-files keeps them. A failed removal keeps the confirmed org result and the run is partial (exit 68) with LOCAL_FILE_REMOVAL_FAILED when a deletion is confirmed, otherwise processing (exit 69).";
478
+ static flags = {
479
+ 'target-org': Flags.string({
480
+ char: 'o',
481
+ summary: 'Authenticated target org alias or username.',
482
+ }),
483
+ metadata: Flags.string({
484
+ char: 'm',
485
+ multiple: true,
486
+ multipleNonGreedy: true,
487
+ exclusive: ['changed-since'],
488
+ summary: 'Exact data-transform:Name, segment:Name, identity-resolution:ObjectApiName, calculated-insight:Name__cio, data-graph:Name, data-stream:ApiName, dlo:Name__dll, dmo:Name__dlm (alone with --field), mapping:ApiName or relationship:SourceDmo__dlm:Name; repeatable.',
489
+ }),
490
+ 'api-version': Flags.string({
491
+ summary: 'Native numeric route >=61, default/auto68.',
492
+ }),
493
+ dataspace: Flags.string({
494
+ aliases: ['data-space'],
495
+ summary: 'The run data space; omitted means default, and the org must have it. --data-space is a compatibility alias. A component of another data space is refused, a stream is deleted when its DLO belongs to the run data space, and a DLO that also belongs to another data space is not deleted, also with --delete-dlo (DLO_DELETE_OTHER_DATASPACES).',
496
+ }),
497
+ preview: Flags.boolean({ default: false, summary: 'Look up and report only; never delete.' }),
498
+ 'changed-since': Flags.string({
499
+ summary: 'Delete in the org the components whose canonical plugin files were deleted since the merge base with a commit reference; needs --confirm-delete (not with --preview).',
500
+ exclusive: ['metadata'],
501
+ }),
502
+ 'confirm-delete': Flags.boolean({
503
+ dependsOn: ['changed-since'],
504
+ summary: 'With --changed-since only: delete the components of the files deleted in the Git range. Not needed with --preview.',
505
+ }),
506
+ 'delete-dlo': Flags.boolean({
507
+ default: false,
508
+ summary: 'Stream-only acknowledgement: delete the exclusively linked DLO; otherwise preserve it.',
509
+ }),
510
+ field: Flags.string({
511
+ multiple: true,
512
+ multipleNonGreedy: true,
513
+ summary: 'Field-level delete: exact custom field Name__c to remove from the one selected dmo:Name__dlm, together with its mapping pairs; repeatable.',
514
+ }),
515
+ 'output-dir': Flags.directory({
516
+ exists: false,
517
+ summary: 'With --field only: project root whose existing DMO and mapping files are refreshed; defaults to the current directory.',
518
+ }),
519
+ 'keep-local-files': Flags.boolean({
520
+ default: false,
521
+ summary: 'Keep the local file of each deleted component. By default a confirmed deletion removes it; no effect with --field.',
522
+ }),
523
+ };
524
+ deleteDataTransform = deleteDataTransform;
525
+ createDataTransformClient = createDataTransformClient;
526
+ nativeGraphContext = nativeDataGraphReadContext;
527
+ nativeGraphClient = createDataGraphClient;
528
+ operateNativeGraph = operateNativeDataGraph;
529
+ selectGitInputs = selectGitDeployInputs;
530
+ deleteIdentityResolution = deleteIdentityResolution;
531
+ deleteSegment = deleteSegment;
532
+ calculatedInsightContext = calculatedInsightReadContext;
533
+ deleteCalculatedInsight = deleteCalculatedInsight;
534
+ /** The org ID of the connection this run resolved (provenance only); unset before that. */
535
+ resolvedOrgId;
536
+ // No configured or resolvable org is TARGET_ORG_REQUIRED, as in publish.
537
+ resolveConnection = async (alias) => {
538
+ try {
539
+ const aggregator = await ConfigAggregator.create();
540
+ const state = await StateAggregator.getInstance();
541
+ const target = alias ?? aggregator.getPropertyValue('target-org');
542
+ return await Connection.create({
543
+ authInfo: await AuthInfo.create({
544
+ username: target ? state.aliases.resolveUsername(target) : undefined,
545
+ }),
546
+ connectionOptions: { version: '68.0' },
547
+ });
548
+ }
549
+ catch {
550
+ throw new DloError('TARGET_ORG_REQUIRED');
551
+ }
552
+ };
553
+ /**
554
+ * Resolve the target org's connection and remember its org ID for the envelope's provenance.
555
+ * @param {string} [alias] Target org alias or username.
556
+ * @returns {Promise<Connection>} The resolved connection.
557
+ */
558
+ async connectTarget(alias) {
559
+ const connection = await this.resolveConnection(alias);
560
+ // A test seam may return a connection without auth info fields: no org ID then.
561
+ const seam = connection;
562
+ this.resolvedOrgId = seam.getAuthInfoFields?.().orgId;
563
+ return connection;
564
+ }
565
+ // Read-only: the landing DLO a selected stream owns, when its DLO is selected too.
566
+ readStreamLinkedDlo = readStreamLinkedDlo;
567
+ preflightDeleteDataStream = preflightDeleteDataStream;
568
+ executeDeleteDataStream = executeDeleteDataStream;
569
+ createDataStreamClients = async (target, version) => {
570
+ const connection = await Connection.create({
571
+ authInfo: await AuthInfo.create({ username: target }),
572
+ connectionOptions: { version },
573
+ });
574
+ const reader = new ConnectClient(connection, version);
575
+ return {
576
+ // DELETE (including the DLO cascade) is sent once on this same bound Connection.
577
+ streams: createDataStreamClient(target, reader, version, openBoundSsot(target, version, async () => connection)),
578
+ ...createDataStreamReferenceReader(reader, version),
579
+ dlo: {
580
+ get: (identity) => reader.get(`/services/data/v${version}/ssot/data-lake-objects/${encodeURIComponent(identity)}`),
581
+ },
582
+ };
583
+ };
584
+ createMappingClient = createMappingClient;
585
+ // Mapping delete GET/DELETE share one bound Connection per selector; tests replace this seam.
586
+ createMappingSender = (target, version) => openBoundSsot(target, version);
587
+ preflightDeleteMapping = preflightDeleteNativeMapping;
588
+ deleteMapping = deleteNativeMapping;
589
+ // A mapping removed with its DMO reports deleted only once its own read answers 404.
590
+ confirmMappingAbsent = confirmNativeMappingAbsent;
591
+ /**
592
+ * The authored mapping file of that name, if one is there: its binding names the org mapping.
593
+ * Like deploy, its identity.apiName must be its file name; a file that is there but is not a
594
+ * valid mapping is refused (INVALID_SOURCE) instead of falling back to the exact org name.
595
+ * @param {string} file Canonical path data360/mapping/<name>.mapping-meta.json.
596
+ * @returns {Promise<NativeMappingDocument | undefined>} The validated file; undefined without one.
597
+ */
598
+ async readAuthoredMapping(file) {
599
+ let present;
600
+ try {
601
+ const stat = await lstat(file);
602
+ present = stat.isFile();
603
+ }
604
+ catch (error) {
605
+ if (error.code === 'ENOENT')
606
+ return undefined;
607
+ present = false;
608
+ }
609
+ const name = path.basename(file).slice(0, -'.mapping-meta.json'.length);
610
+ try {
611
+ if (!present)
612
+ throw new Error('Not a file');
613
+ const value = JSON.parse(await readFile(file, 'utf8'));
614
+ // A verbatim file (retrieved as-is) names no binding: the mapping is deleted by its name.
615
+ if (isVerbatimDocument(value, 'mapping') && value.identity.apiName === name)
616
+ return undefined;
617
+ const document = validateNativeMappingDocument(value, 'retrieve');
618
+ if (document.identity.apiName !== name)
619
+ throw new Error('Identity mismatch');
620
+ return document;
621
+ }
622
+ catch {
623
+ const error = new DeployInputError('INVALID_SOURCE');
624
+ replaceExplanation(error, `The mapping file ${file} is not a valid mapping whose identity.apiName is ${name}, so it names no org mapping. Correct or remove the file, then rerun.`);
625
+ throw error;
626
+ }
627
+ }
628
+ createRelationshipClient = createRelationshipClient;
629
+ preflightDeleteRelationship = preflightDeleteNativeRelationship;
630
+ deleteRelationship = deleteNativeRelationship;
631
+ // Relationship list/DELETE share one bound Connection per selector; tests replace this seam.
632
+ createRelationshipSender = (target, version) => openBoundSsot(target, version);
633
+ // Field-level delete: the only DMO client with the Metadata API route for removeFields.
634
+ createDmoClient = createDmoClient;
635
+ writeNativeDmo = writeNativeDmoDocument;
636
+ writeNativeMapping = writeNativeMappingDocument;
637
+ // Field-level delete readback attempts and spacing; tests replace it to avoid waiting.
638
+ fieldRemovalSettle;
639
+ createDmoNativeDeleteClient = createNativeDmoDeleteClient;
640
+ retrieveDmo = previewDeleteNativeDmo;
641
+ deleteDmo = deleteNativeDmo;
642
+ createDloClient = createDloClient;
643
+ createDloNativeDeleteClient = createNativeDloDeleteClient;
644
+ // The once-per-run data space list read; tests replace this seam or the directory read.
645
+ createDataSpaceSender = (target, version) => openBoundSsot(target, version);
646
+ retrieveDlo = previewDeleteNativeDlo;
647
+ deleteDlo = deleteNativeDlo;
648
+ resolveTarget = async (alias) => {
649
+ const connection = await this.connectTarget(alias);
650
+ const username = connection.getUsername();
651
+ if (!username)
652
+ throw new DloError('TARGET_ORG_REQUIRED');
653
+ return username;
654
+ };
655
+ /**
656
+ * Read-only: a -m source-family component's current definition, read from the org by name.
657
+ * @param {DeleteFamily} family Source family of the selector.
658
+ * @param {string} name Exact name from the selector.
659
+ * @param {Connection} connection API68 connection of the target org.
660
+ * @param {string} [dataSpace] The run's data space.
661
+ * @returns {Promise<AdmittedSource>} The definition, or absent.
662
+ */
663
+ async readDeleteSource(family, name, connection, dataSpace = 'default') {
664
+ return readOrgSource(family, name, connection, {
665
+ transformClient: this.createDataTransformClient ?? createDataTransformClient,
666
+ ciContext: this.calculatedInsightContext ?? calculatedInsightReadContext,
667
+ graphContext: this.nativeGraphContext ?? nativeDataGraphReadContext,
668
+ }, dataSpace);
669
+ }
670
+ /**
671
+ * Read-only: what a verbatim file deleted in a Git range deletes. It is the file itself (type,
672
+ * data space and name); a transform also carries the target ID its name resolves to.
673
+ * @param {VerbatimDocument} document Base content of the deleted verbatim file.
674
+ * @param {Connection} connection API68 connection of the target org.
675
+ * @returns {Promise<AdmittedSource>} The verbatim definition, or absent.
676
+ */
677
+ async verbatimDeleteSource(document, connection) {
678
+ if (document.kind !== 'data-transform')
679
+ return { desired: document };
680
+ const targetId = await resolveDataTransformTargetId((this.createDataTransformClient ?? createDataTransformClient)(connection, '68.0', verbatimDataSpace(document)), document.identity.apiName);
681
+ return targetId === undefined
682
+ ? { absent: true }
683
+ : { desired: document, transformTargetId: targetId };
684
+ }
685
+ /**
686
+ * Field-level delete: remove the named custom fields from one DMO, their mapping pairs first,
687
+ * then refresh the project files that already exist. Never throws; the envelope is completed.
688
+ * @param {FieldDeleteFlags} flags Parsed flags.
689
+ * @param {DeleteEnvelope} envelope Envelope to complete.
690
+ * @returns {Promise<void>} Resolves when the envelope is final.
691
+ */
692
+ async deleteDmoFields(flags, envelope) {
693
+ const refuse = (code, message) => {
694
+ envelope.diagnostics.errors.push({ code, message, retryable: false });
695
+ };
696
+ const selector = flags.metadata?.[0] ?? '';
697
+ if (!flags.field?.length ||
698
+ flags.metadata?.length !== 1 ||
699
+ !selector.startsWith('dmo:') ||
700
+ !nativeDmoName.test(selector.slice(4)) ||
701
+ flags['changed-since'] !== undefined ||
702
+ flags['delete-dlo'])
703
+ return refuse('INVALID_FIELD_DELETE_SELECTION', '--field removes fields from exactly one -m dmo:<Name__dlm> and cannot be combined with another selector, --changed-since or --delete-dlo; --output-dir is valid only with --field. No org call was made.');
704
+ if (flags.field.some((name) => !nativeDmoFieldName.test(name)))
705
+ return refuse('INVALID_DMO_FIELD', '--field takes exact custom field API names ending in __c. No org call was made.');
706
+ let version;
707
+ try {
708
+ version = nativeApiVersion(flags['api-version']);
709
+ }
710
+ catch {
711
+ return refuse('INVALID_SCOPE', '--api-version must be auto or a numeric version from 61.0. No org call was made.');
712
+ }
713
+ envelope.metadata.apiVersion = version;
714
+ const apiName = selector.slice(4);
715
+ const fields = [...new Set(flags.field)];
716
+ // The run's data space, always explicit: --dataspace, or default.
717
+ const effectiveScope = flags.dataspace ?? 'default';
718
+ const root = path.resolve(flags['output-dir'] ?? process.cwd());
719
+ const item = {
720
+ family: 'dmo',
721
+ identity: { dataSpace: effectiveScope, apiName },
722
+ operation: flags.preview ? 'preview' : 'delete-field',
723
+ fields,
724
+ outcome: 'blocked',
725
+ mutation: 'not-attempted',
726
+ routes: [
727
+ { operation: 'dmo.get', transport: 'native', apiVersion: version },
728
+ { operation: 'mapping.list', transport: 'native', apiVersion: version },
729
+ { operation: 'mapping.get', transport: 'native', apiVersion: version },
730
+ { operation: 'dmo.field.delete', transport: 'metadata', apiVersion: version },
731
+ ],
732
+ };
733
+ envelope.result.items.push(item);
734
+ const fieldError = (error, nextAction) => refuse(error instanceof DataSpaceError ||
735
+ error instanceof DloError ||
736
+ error instanceof NativeDmoError ||
737
+ error instanceof NativeMappingError
738
+ ? error.code
739
+ : 'DELETE_FAILED', operationDiagnostic(error, nextAction));
740
+ let clients;
741
+ let plan;
742
+ try {
743
+ const target = await this.resolveTarget(flags['target-org']);
744
+ if (this.resolvedOrgId)
745
+ envelope.provenance.targetOrgId = this.resolvedOrgId;
746
+ // The run's data space must exist in the org: one read, before any other read.
747
+ await dataSpaceCheckOf(this, async () => (this.createDataSpaceSender ?? openBoundSsot)(target, '68.0')).require([effectiveScope]);
748
+ clients = {
749
+ dmo: this.createDmoNativeDeleteClient(target, version),
750
+ remover: (this.createDmoClient ?? createDmoClient)(target, version),
751
+ mappings: (this.createMappingClient ?? createMappingClient)(target, version, undefined, effectiveScope, this.createMappingSender(target, version)),
752
+ // Read only to refresh a mapping file without the pairs Salesforce generated.
753
+ source: (this.createDloNativeDeleteClient ?? createNativeDloDeleteClient)(target, version),
754
+ };
755
+ plan = await planDmoFieldDelete(apiName, fields, clients, effectiveScope);
756
+ item.identity.dataSpace = plan.dataSpace;
757
+ if (flags.preview) {
758
+ const files = await dmoFieldLocalFiles(plan, root);
759
+ const present = await Promise.all(files.map(async (file) => localFileExists(file.path)));
760
+ item.plan = [
761
+ ...plan.mappings.flatMap(({ pairs }) => pairs.map((pair) => ({
762
+ operation: 'unmap',
763
+ apiName: pair.mapping,
764
+ sourceFieldDeveloperName: pair.sourceFieldDeveloperName,
765
+ targetFieldDeveloperName: pair.targetFieldDeveloperName,
766
+ developerName: pair.developerName,
767
+ }))),
768
+ ...fields.map((fieldName) => ({
769
+ operation: 'delete-field',
770
+ apiName,
771
+ fieldName,
772
+ })),
773
+ ];
774
+ item.localFiles = files.map((file, index) => ({
775
+ path: file.path,
776
+ exists: present[index],
777
+ }));
778
+ item.outcome = 'delete';
779
+ envelope.status = 'success';
780
+ return;
781
+ }
782
+ }
783
+ catch (error) {
784
+ return fieldError(error, 'No write attempted; correct the reported check before another attempt.');
785
+ }
786
+ const progress = {
787
+ step: 'recheck',
788
+ unmappedPairs: [],
789
+ removalSent: false,
790
+ };
791
+ try {
792
+ await executeDmoFieldDelete(plan, clients, progress, effectiveScope, this.fieldRemovalSettle);
793
+ }
794
+ catch (error) {
795
+ item.unmappedPairs = [];
796
+ item.removedFields = [];
797
+ if (progress.step === 'readback') {
798
+ item.outcome = 'deletion-unconfirmed';
799
+ item.mutation = 'acknowledged';
800
+ }
801
+ else if (progress.removalSent) {
802
+ item.outcome = 'failed';
803
+ // Salesforce's refusal of the destructive change applied nothing.
804
+ item.mutation =
805
+ progress.step === 'remove' && error instanceof NativeDmoError && error.rejected
806
+ ? 'rejected'
807
+ : 'unknown';
808
+ }
809
+ envelope.status = item.outcome === 'blocked' ? 'blocked' : 'failed';
810
+ return fieldError(error, item.mutation === 'rejected'
811
+ ? 'Salesforce refused the Metadata API destructive change; nothing was removed. No local file was refreshed. No retry or rollback.'
812
+ : fieldDeleteStop(progress, plan));
813
+ }
814
+ item.outcome = 'deleted';
815
+ item.mutation = 'confirmed-deleted';
816
+ item.removedFields = fields;
817
+ item.unmappedPairs = progress.unmappedPairs.map((pair) => reportedPair(pair));
818
+ // Only now, after every org step is confirmed, are existing project files refreshed.
819
+ item.refreshedFiles = await refreshDmoFieldFiles(plan, root, clients, {
820
+ dmo: this.writeNativeDmo ?? writeNativeDmoDocument,
821
+ mapping: this.writeNativeMapping ?? writeNativeMappingDocument,
822
+ }, effectiveScope);
823
+ const failed = item.refreshedFiles.filter((file) => file.outcome === 'failed');
824
+ if (failed.length === 0) {
825
+ envelope.status = 'success';
826
+ return;
827
+ }
828
+ envelope.status = 'failed';
829
+ refuse('LOCAL_REFRESH_FAILED', `The field(s) ${fields.join(', ')} were deleted from ${apiName} in the org, but ${failed.length === 1 ? 'this project file was' : 'these project files were'} not refreshed: ${failed.map((file) => `${file.path} (${file.code})`).join('; ')}. Do not repeat the delete; refresh with sf data360 retrieve and --overwrite.`);
830
+ }
831
+ /**
832
+ * Delete or preview one relationship by name. The source DMO, named in the selector (or with
833
+ * Git in the deleted file's base content), is listed to find it before, and to confirm its
834
+ * absence after, the single DELETE.
835
+ * @param {string} selector Exact relationship:SourceDmo__dlm:Name (Git: relationship:Name) selector.
836
+ * @param {string} target Resolved username.
837
+ * @param {string} version Native API version.
838
+ * @param {boolean} preview Read-only when true.
839
+ * @param {string} effectiveScope The run's data space.
840
+ * @param {DeleteEnvelope} envelope Envelope receiving the item.
841
+ * @param {Map<DeleteItem, string>} selectorsByItem Human labels.
842
+ * @param {Function} track Registers the item's local file for removal or preview.
843
+ * @param {NativeRelationshipDocument} [baseDocument] Git delete: the file's base content.
844
+ * @param {object} [baseNames] Git delete of a verbatim file: the relationship is then found by
845
+ * name under its source DMO, like -m.
846
+ * @param {string} baseNames.sourceDmo Source DMO the verbatim file keeps.
847
+ * @param {string} baseNames.apiName Relationship name.
848
+ * @returns {Promise<void>} Resolves when the item settled; throws to stop the batch.
849
+ */
850
+ async deleteOneRelationship(selector, target, version, preview, effectiveScope, envelope, selectorsByItem, track, baseDocument, baseNames) {
851
+ const [sourceDmo, selectedName] = baseDocument === undefined
852
+ ? baseNames === undefined
853
+ ? selector.slice('relationship:'.length).split(':')
854
+ : [baseNames.sourceDmo, baseNames.apiName]
855
+ : [baseDocument.spec.sourceObjectName, baseDocument.identity.apiName];
856
+ const item = {
857
+ family: 'relationship',
858
+ identity: { dataSpace: effectiveScope, apiName: selectedName },
859
+ operation: preview ? 'preview' : 'delete',
860
+ outcome: 'blocked',
861
+ mutation: 'not-attempted',
862
+ };
863
+ selectorsByItem.set(item, selector);
864
+ envelope.result.items.push(item);
865
+ let dispatched = false;
866
+ // Salesforce's own 4xx answer to the DELETE means nothing was deleted.
867
+ let refusal;
868
+ try {
869
+ const base = (this.createRelationshipClient ?? createRelationshipClient)(target, version, effectiveScope, (this.createRelationshipSender ?? openBoundSsot)(target, version));
870
+ const client = {
871
+ list: base.list,
872
+ remove: async (name) => {
873
+ dispatched = true;
874
+ try {
875
+ await base.remove(name);
876
+ }
877
+ catch (error) {
878
+ if (error instanceof NativeRelationshipError &&
879
+ error.code === 'RELATIONSHIP_HTTP_ERROR' &&
880
+ typeof error.status === 'number' &&
881
+ error.status >= 400 &&
882
+ error.status < 500)
883
+ refusal = error;
884
+ throw error;
885
+ }
886
+ },
887
+ };
888
+ // -m: the relationship as the org lists it under its source DMO; none of that name is absent.
889
+ const document = baseDocument ??
890
+ (await findNativeRelationshipByName(sourceDmo, selectedName, client, effectiveScope));
891
+ if (document === undefined) {
892
+ item.outcome = 'unchanged';
893
+ return;
894
+ }
895
+ const apiName = document.identity.apiName;
896
+ item.identity.apiName = apiName;
897
+ const files = [
898
+ {
899
+ path: path.join(process.cwd(), 'data360', 'relationship', `${apiName}.relationship-meta.json`),
900
+ boundary: path.join(process.cwd(), 'data360'),
901
+ },
902
+ ];
903
+ if (preview) {
904
+ const plan = await (this.preflightDeleteRelationship ?? preflightDeleteNativeRelationship)(apiName, document, client, effectiveScope);
905
+ item.outcome = plan.present ? 'delete' : 'unchanged';
906
+ await track(item, files);
907
+ return;
908
+ }
909
+ const result = await (this.deleteRelationship ?? deleteNativeRelationship)(apiName, document, client, effectiveScope);
910
+ item.outcome = result.outcome;
911
+ if (result.outcome === 'deleted')
912
+ item.mutation = 'confirmed-deleted';
913
+ await track(item, files);
914
+ }
915
+ catch (error) {
916
+ item.outcome = dispatched ? 'failed' : 'blocked';
917
+ item.mutation =
918
+ refusal !== undefined && refusal === error
919
+ ? 'rejected'
920
+ : dispatched
921
+ ? 'unknown'
922
+ : 'not-attempted';
923
+ envelope.status = dispatched ? 'failed' : 'blocked';
924
+ throw error;
925
+ }
926
+ }
927
+ /**
928
+ * Execute the selection in dependency order (relationships, mappings, DMOs, DLOs), stopping on
929
+ * the first error.
930
+ * @returns {Promise<DeleteEnvelope>} Payload-free deletion evidence.
931
+ */
932
+ async run() {
933
+ const { flags } = await this.parse(Delete);
934
+ const effectiveScope = flags.dataspace ?? 'default';
935
+ const envelope = {
936
+ contract: 'sf-data360-delete',
937
+ contractVersion: '1.1.0',
938
+ status: 'blocked',
939
+ metadata: {
940
+ operation: 'delete',
941
+ preview: flags.preview,
942
+ apiVersion: flags['api-version'] ?? 'auto',
943
+ plugin,
944
+ },
945
+ provenance: {
946
+ command: 'sf data360 delete',
947
+ generatedAt: new Date().toISOString(),
948
+ // eslint-disable-next-line unicorn/no-null -- Stable JSON represents unresolved target identity explicitly.
949
+ targetOrgId: null,
950
+ },
951
+ diagnostics: { warnings: [], errors: [] },
952
+ result: { scope: { dataSpace: effectiveScope }, items: [] },
953
+ };
954
+ const selectorsByItem = new Map();
955
+ const keepLocalFiles = flags['keep-local-files'];
956
+ const changedSince = flags['changed-since'];
957
+ // A file deleted in the Git range is already gone: no local file is listed or removed.
958
+ const gitMode = changedSince !== undefined;
959
+ const projectData = path.join(process.cwd(), 'data360');
960
+ // The local files of each item; removed once its deletion is confirmed.
961
+ const localFiles = new Map();
962
+ const inProject = (...segments) => ({
963
+ path: path.join(projectData, ...segments),
964
+ boundary: projectData,
965
+ });
966
+ // The canonical local files of a transform, CI (JSON and SQL), Segment, IR or graph, by name,
967
+ // all under data360/ of the current directory.
968
+ const sourceFiles = async (family, name) => {
969
+ if (gitMode)
970
+ return [];
971
+ switch (family) {
972
+ case 'data-transform': {
973
+ return [inProject('dataTransforms', `${name}.dataTransform.json`)];
974
+ }
975
+ case 'calculated-insight': {
976
+ return [
977
+ inProject('calculatedInsights', `${name}.calculatedInsight-meta.json`),
978
+ inProject('calculatedInsights', `${name}.calculatedInsight-meta.sql`),
979
+ ];
980
+ }
981
+ case 'segment': {
982
+ // The JSON and every `<Name>.segment.<model>.sql` beside it.
983
+ const directory = path.join(projectData, 'segments');
984
+ let entries = [];
985
+ try {
986
+ entries = await readdir(directory);
987
+ }
988
+ catch (error) {
989
+ if (error.code !== 'ENOENT')
990
+ throw error;
991
+ }
992
+ // Matched ignoring case, like the reader and the writer.
993
+ const prefix = `${name}.segment.`.toLowerCase();
994
+ const sql = entries.filter((entry) => {
995
+ const lower = entry.toLowerCase();
996
+ return lower.startsWith(prefix) && lower.endsWith('.sql');
997
+ });
998
+ sql.sort();
999
+ return [
1000
+ inProject('segments', `${name}.segment.json`),
1001
+ ...sql.map((entry) => inProject('segments', entry)),
1002
+ ];
1003
+ }
1004
+ case 'identity-resolution': {
1005
+ return [inProject('identityResolution', `${name}.identityResolution.json`)];
1006
+ }
1007
+ default: {
1008
+ return [inProject('dataGraphs', `${name}.native-dataGraph.json`)];
1009
+ }
1010
+ }
1011
+ };
1012
+ const track = async (item, candidates) => {
1013
+ if (gitMode)
1014
+ return;
1015
+ if (item.operation !== 'preview') {
1016
+ localFiles.set(item, candidates);
1017
+ return;
1018
+ }
1019
+ if (keepLocalFiles || item.outcome !== 'delete' || candidates.length === 0)
1020
+ return;
1021
+ item.localFiles = await Promise.all(candidates.map(async (file) => ({
1022
+ path: file.path,
1023
+ exists: await localFilePresent(file.path),
1024
+ })));
1025
+ };
1026
+ // Confirmed: Salesforce deleted it, or accepted the deletion and is still processing it.
1027
+ const removeConfirmedFiles = async () => {
1028
+ for (const [item, candidates] of localFiles) {
1029
+ const confirmed = (item.outcome === 'deleted' && item.mutation === 'confirmed-deleted') ||
1030
+ (item.outcome === 'deletion-processing' && item.mutation === 'acknowledged-processing');
1031
+ if (confirmed && candidates.length > 0)
1032
+ item.removedLocalFiles = await removeLocalFiles(candidates, keepLocalFiles);
1033
+ }
1034
+ localFiles.clear();
1035
+ const failed = envelope.result.items.flatMap((item) => (item.removedLocalFiles ?? []).filter((file) => file.outcome === 'failed'));
1036
+ if (failed.length === 0)
1037
+ return;
1038
+ envelope.status = 'failed';
1039
+ envelope.diagnostics.errors.push({
1040
+ code: 'LOCAL_FILE_REMOVAL_FAILED',
1041
+ message: `The deletion in the org is confirmed, but ${failed.length === 1 ? 'this local file was' : 'these local files were'} not removed: ${failed.map((file) => `${file.path} (${file.code})`).join('; ')}. Do not repeat the delete; remove the file yourself.`,
1042
+ retryable: false,
1043
+ });
1044
+ };
1045
+ /**
1046
+ * Final status of an executed run: an unknown or unconfirmed mutation keeps the run status, a
1047
+ * success becoming failed;
1048
+ * an item confirmed deleted beside a failed or blocked one is partial, as is a confirmed
1049
+ * deletion whose local file was not removed; otherwise a deletion Salesforce is still
1050
+ * processing (an item, a phase not settled, an identity resolution in flight) is processing.
1051
+ * @returns {string} Envelope status (one of DeleteEnvelope status values).
1052
+ */
1053
+ const settledStatus = () => {
1054
+ const { status } = envelope;
1055
+ if (flags.preview)
1056
+ return status;
1057
+ const executed = envelope.result.items.filter((item) => item.operation !== 'preview');
1058
+ if (executed.some((item) => item.mutation === 'unknown' ||
1059
+ item.mutation === 'acknowledged' ||
1060
+ item.outcome === 'deletion-unconfirmed'))
1061
+ // An unknown mutation never reads as success (exit 1).
1062
+ return status === 'success' ? 'failed' : status;
1063
+ const { errors } = envelope.diagnostics;
1064
+ const written = executed.some((item) => item.mutation === 'confirmed-deleted');
1065
+ const failed = executed.some((item) => (item.outcome === 'failed' || item.outcome === 'blocked') && !stillProcessing(item)) ||
1066
+ // A stop is a failure unless only a deletion still processing or a local file caused it.
1067
+ (status !== 'success' &&
1068
+ (errors.length === 0 ||
1069
+ errors.some((error) => !notSettledCodes.has(error.code) && error.code !== 'LOCAL_FILE_REMOVAL_FAILED')));
1070
+ if (failed)
1071
+ return written ? 'partial' : status;
1072
+ // Partial needs a confirmed deletion; a file of a deletion still processing waits for it.
1073
+ if (written && errors.some((error) => error.code === 'LOCAL_FILE_REMOVAL_FAILED'))
1074
+ return 'partial';
1075
+ return executed.some((item) => stillProcessing(item)) ||
1076
+ errors.some((error) => notSettledCodes.has(error.code))
1077
+ ? 'processing'
1078
+ : status;
1079
+ };
1080
+ const finish = async () => {
1081
+ await removeConfirmedFiles();
1082
+ envelope.status = settledStatus();
1083
+ const exitCode = exitCodeOf(envelope);
1084
+ if (exitCode !== 0)
1085
+ process.exitCode = exitCode;
1086
+ annotateDiagnostics(envelope);
1087
+ if (!this.jsonEnabled()) {
1088
+ this.log(`Delete${flags.preview ? ' preview' : ''}: ${envelope.status}.`);
1089
+ // The default data space goes without saying; any other is named.
1090
+ if (effectiveScope !== 'default')
1091
+ this.log(`Data space: ${effectiveScope}.`);
1092
+ if (gitMode && envelope.result.items.length === 0 && envelope.status === 'success')
1093
+ this.log('No plugin file was deleted in the Git range; nothing to delete.');
1094
+ for (const item of envelope.result.items) {
1095
+ if (item.fields) {
1096
+ for (const line of fieldDeleteLines(item))
1097
+ this.log(line);
1098
+ continue;
1099
+ }
1100
+ if (item.removedWith) {
1101
+ this.log(item.operation === 'preview'
1102
+ ? `Planned removal with ${item.removedWith}: ${selectorsByItem.get(item)}.`
1103
+ : ['deleted', 'deletion-processing'].includes(item.outcome)
1104
+ ? `removed with ${item.removedWith}: ${selectorsByItem.get(item)}`
1105
+ : item.outcome === 'deletion-unconfirmed'
1106
+ ? `Removal with ${item.removedWith} unconfirmed: ${selectorsByItem.get(item)}.`
1107
+ : `Not removed (${item.removedWith} ${item.outcome}): ${selectorsByItem.get(item)}.`);
1108
+ for (const file of item.removedLocalFiles ?? [])
1109
+ if (file.outcome === 'removed')
1110
+ this.log(`removed local file ${file.path}`);
1111
+ continue;
1112
+ }
1113
+ if (item.outcome === 'planned-dependencies') {
1114
+ this.log(`Planned after its dependents: ${selectorsByItem.get(item)}.`);
1115
+ for (const diagnostic of item.diagnostics ?? [])
1116
+ this.log(`${diagnostic.code}: ${diagnostic.message}`);
1117
+ continue;
1118
+ }
1119
+ const action = item.operation === 'preview'
1120
+ ? `Planned ${item.outcome}`
1121
+ : item.outcome === 'deleted'
1122
+ ? 'Deleted'
1123
+ : item.outcome === 'unchanged'
1124
+ ? 'Unchanged'
1125
+ : item.outcome === 'failed'
1126
+ ? 'Failed'
1127
+ : item.outcome === 'deletion-unconfirmed'
1128
+ ? 'Unconfirmed'
1129
+ : 'Blocked';
1130
+ if (['identity-resolution', 'segment', 'dlo', 'dmo'].includes(selectorsByItem.get(item)?.split(':')[0] ?? '') &&
1131
+ ['deleted', 'deletion-processing'].includes(item.outcome))
1132
+ this.log(`deleted ${selectorsByItem.get(item)?.split(':')[0]} ${item.identity.apiName}${item.mutation === 'acknowledged-processing' ? ' (server is still processing)' : ''}`);
1133
+ else if (item.operation !== 'preview' && item.outcome === 'deleted')
1134
+ this.log(`deleted ${selectorsByItem.get(item)?.split(':')[0]} ${item.identity.apiName}`);
1135
+ else
1136
+ this.log(`${action}: ${selectorsByItem.get(item)}; mutation: ${item.mutation}.`);
1137
+ if (item.operation === 'preview' && item.plan?.length)
1138
+ this.log(`Planned mapping delete: ${item.identity.apiName}.`);
1139
+ for (const file of item.localFiles ?? [])
1140
+ if (file.exists)
1141
+ this.log(`Planned local file removal: ${file.path}`);
1142
+ for (const file of item.removedLocalFiles ?? [])
1143
+ switch (file.outcome) {
1144
+ case 'removed': {
1145
+ this.log(`removed local file ${file.path}`);
1146
+ break;
1147
+ }
1148
+ case 'kept': {
1149
+ this.log(`kept local file ${file.path}`);
1150
+ break;
1151
+ }
1152
+ case 'failed': {
1153
+ this.log(`local file removal failed (${file.code}): ${file.path}`);
1154
+ // No default
1155
+ break;
1156
+ }
1157
+ }
1158
+ }
1159
+ for (const diagnostic of envelope.diagnostics.errors)
1160
+ this.log(formatDiagnostic(diagnostic));
1161
+ }
1162
+ return envelope;
1163
+ };
1164
+ const pushError = (error) => {
1165
+ if (error instanceof GitSelectionError) {
1166
+ envelope.diagnostics.errors.push({
1167
+ code: error.code,
1168
+ message: error.code === 'BLOCKED_GIT_LIFECYCLE'
1169
+ ? // Raised before a phase starts, after earlier phases may already have deleted items.
1170
+ envelope.result.items.some((item) => item.outcome === 'deleted' || item.mutation === 'confirmed-deleted')
1171
+ ? 'A file deleted in the Git range is present again, so this phase and the later ones did not start. The items listed before it were deleted. Stage or resolve the change, then rerun; items already deleted report unchanged.'
1172
+ : 'The Git range holds a change the delete cannot take as a deletion: a rename (also one split across commit, index and worktree), a conflict, an unstaged deletion of a plugin file, a deleted file of no known family, a calculated insight with only one of its JSON and SQL files deleted, or a deleted file that is present again. Nothing was deleted; stage or resolve the change, then rerun.'
1173
+ : 'Git selection failed. Use a valid commit reference and run the delete inside the Git repository; deleted files must be canonical plugin files whose base content is valid. Nothing was deleted.',
1174
+ retryable: false,
1175
+ });
1176
+ return;
1177
+ }
1178
+ envelope.diagnostics.errors.push({
1179
+ code: error instanceof DeployInputError ||
1180
+ error instanceof DataSpaceError ||
1181
+ error instanceof DloError ||
1182
+ error instanceof NativeDmoError ||
1183
+ error instanceof NativeMappingError ||
1184
+ error instanceof NativeRelationshipError ||
1185
+ error instanceof DataStreamError ||
1186
+ error instanceof DataTransformError ||
1187
+ error instanceof SegmentError ||
1188
+ error instanceof IdentityResolutionError ||
1189
+ error instanceof DataGraphError ||
1190
+ error instanceof CalculatedInsightError
1191
+ ? error.code
1192
+ : 'DELETE_FAILED',
1193
+ message: operationDiagnostic(error, flags.preview
1194
+ ? 'Preview stopped; nothing was deleted. Correct the reported check before another attempt.'
1195
+ : // Stopped before any delete was sent (every item not attempted): nothing to inspect.
1196
+ envelope.result.items.every((item) => item.mutation === 'not-attempted')
1197
+ ? 'Deletion stopped before any delete was sent; nothing was deleted. Correct the reported check before another attempt.'
1198
+ : 'Deletion stopped. Inspect unknown outcomes before another attempt; no automatic retry or rollback.'),
1199
+ retryable: false,
1200
+ });
1201
+ };
1202
+ const warn = (text) => {
1203
+ if (!envelope.diagnostics.warnings.includes(text))
1204
+ envelope.diagnostics.warnings.push(text);
1205
+ };
1206
+ try {
1207
+ if (flags.field?.length || flags['output-dir'] !== undefined) {
1208
+ await this.deleteDmoFields(flags, envelope);
1209
+ return finish();
1210
+ }
1211
+ // Admission: every check below runs before the first org call.
1212
+ if (gitMode) {
1213
+ if (flags.metadata !== undefined)
1214
+ throw new DloError('INVALID_SELECTION');
1215
+ // A stream follows its DLO file in the range.
1216
+ if (flags['delete-dlo'])
1217
+ throw new DataStreamError('INVALID_STREAM_DELETE_SELECTION');
1218
+ }
1219
+ let gitDeletions = [];
1220
+ if (changedSince !== undefined) {
1221
+ envelope.result.selection = { changedSince };
1222
+ const selected = await this.selectGitInputs({ cwd: process.cwd(), ref: changedSince });
1223
+ envelope.provenance.git = selected.provenance;
1224
+ gitDeletions = selected.deletions ?? [];
1225
+ if (gitDeletions.length === 0) {
1226
+ envelope.status = 'success';
1227
+ return await finish();
1228
+ }
1229
+ }
1230
+ const gitBySelector = new Map(gitDeletions.map((candidate) => [
1231
+ `${candidate.family}:${candidate.identity.apiName}`,
1232
+ candidate,
1233
+ ]));
1234
+ const selectors = gitMode ? [...gitBySelector.keys()] : (flags.metadata ?? []);
1235
+ for (const selector of selectors)
1236
+ if (!deleteFamily(selector, gitMode))
1237
+ throw selectorError(selector);
1238
+ if (selectors.length === 0)
1239
+ throw new DloError('INVALID_SELECTION');
1240
+ const familyOf = (selector) => deleteFamily(selector, gitMode);
1241
+ const has = (family) => selectors.some((selector) => familyOf(selector) === family);
1242
+ const sourceSelectors = selectors.filter((selector) => sourceFamilies.has(familyOf(selector)));
1243
+ if (has('data-transform') && !['auto', '68.0'].includes(flags['api-version'] ?? 'auto'))
1244
+ throw new DataTransformError('INVALID_TRANSFORM_SCOPE');
1245
+ if (flags['delete-dlo'] && !has('data-stream'))
1246
+ throw new DataStreamError('STREAM_DELETE_DLO_REQUIRES_STREAM_SELECTION');
1247
+ if (new Set(sourceSelectors).size !== sourceSelectors.length)
1248
+ throw new DloError('INVALID_SELECTION');
1249
+ // Every family is deleted in the run's data space.
1250
+ if ((has('segment') || has('identity-resolution') || has('calculated-insight')) &&
1251
+ !['auto', '68.0'].includes(flags['api-version'] ?? 'auto'))
1252
+ throw new DloError('INVALID_SCOPE');
1253
+ if (has('data-graph'))
1254
+ try {
1255
+ operationApiVersion(flags['api-version'] ?? 'auto', 'data-graph');
1256
+ }
1257
+ catch {
1258
+ throw new DloError('INVALID_SCOPE');
1259
+ }
1260
+ const streamSelectors = Object.freeze(
1261
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh selection within the ES2022 library target.
1262
+ [...new Set(selectors.filter((selector) => familyOf(selector) === 'data-stream'))].sort());
1263
+ let streamVersion = '68.0';
1264
+ if (streamSelectors.length > 0)
1265
+ streamVersion = dataStreamApiVersion(flags['api-version']);
1266
+ const nativeSelectors = [
1267
+ ...new Set(selectors.filter((selector) => nativeFamilies.has(familyOf(selector)))),
1268
+ ];
1269
+ let nativeVersion = '68.0';
1270
+ if (nativeSelectors.length > 0)
1271
+ try {
1272
+ nativeVersion = nativeApiVersion(flags['api-version']);
1273
+ }
1274
+ catch {
1275
+ throw new DloError('INVALID_SCOPE');
1276
+ }
1277
+ const snapshot = JSON.stringify(flags);
1278
+ // The definition each source-family selector deletes: from the org by name, or with Git
1279
+ // from the base content of the deleted file.
1280
+ const admitted = new Map();
1281
+ // A file deleted in the range names its component in its own (base) data space.
1282
+ // A DLO or stream file lists every data space of the DLO; it must list the run's.
1283
+ for (const candidate of gitDeletions) {
1284
+ const listed = spaceListOf(candidate.document);
1285
+ if (listed === undefined
1286
+ ? candidate.identity.dataSpace !== effectiveScope
1287
+ : !listed.includes(effectiveScope)) {
1288
+ // A segment or transform names its own refusal, with both data spaces.
1289
+ const named = String(candidate.identity.dataSpace);
1290
+ if (candidate.family === 'segment')
1291
+ throw segmentSpaceMismatch(candidate.identity.apiName, named, effectiveScope);
1292
+ if (candidate.family === 'data-transform')
1293
+ throw dataTransformSpaceMismatch(candidate.identity.apiName, named, effectiveScope);
1294
+ if (candidate.family === 'data-graph')
1295
+ throw nativeDataGraphSpaceMismatch(candidate.identity.apiName, named, effectiveScope, 'file');
1296
+ if (candidate.family === 'identity-resolution')
1297
+ throw identityResolutionSpaceMismatch(candidate.identity.apiName, named, effectiveScope, 'file');
1298
+ throw new DloError('INVALID_SCOPE');
1299
+ }
1300
+ }
1301
+ if (gitMode)
1302
+ for (const [selector, candidate] of gitBySelector) {
1303
+ // A verbatim file (retrieved as-is) is read from the org by name below, like -m.
1304
+ if (!sourceFamilies.has(candidate.family) || isVerbatimDocument(candidate.document))
1305
+ continue;
1306
+ const source = admitSourceInput({
1307
+ path: candidate.path,
1308
+ ...(candidate.companionPath === undefined
1309
+ ? {}
1310
+ : { companionPath: candidate.companionPath }),
1311
+ document: candidate.document,
1312
+ inputDigest: candidate.baseDigest,
1313
+ });
1314
+ if (source.selector !== selector)
1315
+ throw source.family === 'data-transform'
1316
+ ? new DataTransformError('INVALID_TRANSFORM_DELETE_SELECTION')
1317
+ : new DloError('INVALID_SELECTION');
1318
+ admitted.set(selector, { desired: source.desired });
1319
+ }
1320
+ // A Git delete is never an implicit destructive run; a -m delete needs no confirmation.
1321
+ if (gitMode && !flags.preview && flags['confirm-delete'] !== true) {
1322
+ const error = new DloError('DESTRUCTIVE_CONFIRMATION_REQUIRED');
1323
+ replaceExplanation(error, 'Files deleted in the Git range are deleted in the org only with --confirm-delete. Check the selection with --preview, then rerun with --confirm-delete. Nothing was deleted.');
1324
+ throw error;
1325
+ }
1326
+ // Right before each stage: a file deleted in the range must still be gone.
1327
+ const stillDeleted = async (candidate) => {
1328
+ if (candidate === undefined)
1329
+ return;
1330
+ for (const file of [
1331
+ candidate.path,
1332
+ candidate.companionPath,
1333
+ ...(candidate.codePaths ?? []),
1334
+ ])
1335
+ if (file !== undefined && (await localFilePresent(file)))
1336
+ throw new GitSelectionError('BLOCKED_GIT_LIFECYCLE');
1337
+ };
1338
+ let connection;
1339
+ const connect = async () => {
1340
+ connection ??= await this.connectTarget(flags['target-org']);
1341
+ if (this.resolvedOrgId)
1342
+ envelope.provenance.targetOrgId = this.resolvedOrgId;
1343
+ return connection;
1344
+ };
1345
+ let username;
1346
+ const resolveUsername = async () => {
1347
+ username ??= await this.resolveTarget(flags['target-org']);
1348
+ if (this.resolvedOrgId)
1349
+ envelope.provenance.targetOrgId = this.resolvedOrgId;
1350
+ return username;
1351
+ };
1352
+ // The run's data space and every space a selected file names must exist in the org: one
1353
+ // read per run, before any phase deletes anything (preview too).
1354
+ await dataSpaceCheckOf(this, async () => (this.createDataSpaceSender ?? openBoundSsot)(await resolveUsername(), '68.0')).require([
1355
+ effectiveScope,
1356
+ ...gitDeletions.flatMap((candidate) => spaceListOf(candidate.document) ?? []),
1357
+ ]);
1358
+ // A DELETE removes a DLO from every data space it belongs to, so a selected DLO that also
1359
+ // belongs to another data space than the run's is refused here, before any phase deletes
1360
+ // anything (preview too). An absent DLO is reported unchanged by its phase.
1361
+ for (const selector of nativeSelectors.filter((value) => value.startsWith('dlo:'))) {
1362
+ const name = selectorName(selector);
1363
+ try {
1364
+ // The delete preview's own read: the same membership checks, nothing deleted.
1365
+ await (this.retrieveDlo ?? previewDeleteNativeDlo)(name, this.createDloNativeDeleteClient(await resolveUsername(), nativeVersion), effectiveScope);
1366
+ }
1367
+ catch (error) {
1368
+ if (error instanceof DloError && error.code === 'DLO_HTTP_ERROR' && error.status === 404)
1369
+ continue;
1370
+ const blocked = {
1371
+ family: 'dlo',
1372
+ identity: { dataSpace: effectiveScope, apiName: name },
1373
+ operation: flags.preview ? 'preview' : 'delete',
1374
+ outcome: 'blocked',
1375
+ mutation: 'not-attempted',
1376
+ };
1377
+ selectorsByItem.set(blocked, selector);
1378
+ envelope.result.items.push(blocked);
1379
+ throw error;
1380
+ }
1381
+ }
1382
+ // Read-only, preview too, before any phase deletes anything: each -m source-family
1383
+ // component's current definition by name, and the target ID of a Git-deleted transform.
1384
+ for (const selector of sourceSelectors) {
1385
+ const verbatim = isVerbatimDocument(gitBySelector.get(selector)?.document);
1386
+ if (gitMode && !verbatim && familyOf(selector) !== 'data-transform')
1387
+ continue;
1388
+ const target = await connect();
1389
+ if (familyOf(selector) === 'data-transform' && !target.getUsername())
1390
+ throw new DloError('TARGET_ORG_REQUIRED');
1391
+ if (verbatim) {
1392
+ // Deleted by type and name: the services check identity, scope, protection and
1393
+ // dependents on the raw GET and never project it into the plugin's model.
1394
+ admitted.set(selector, await this.verbatimDeleteSource(gitBySelector.get(selector).document, target));
1395
+ continue;
1396
+ }
1397
+ if (!gitMode) {
1398
+ admitted.set(selector, await this.readDeleteSource(familyOf(selector), selectorName(selector), target, effectiveScope));
1399
+ continue;
1400
+ }
1401
+ const source = admitted.get(selector);
1402
+ const targetId = await resolveDataTransformTargetId(this.createDataTransformClient(target, '68.0', effectiveScope), selectorName(selector));
1403
+ // No transform of that name (also on a rerun after it was deleted): nothing to delete.
1404
+ admitted.set(selector, targetId === undefined ? { absent: true } : { ...source, transformTargetId: targetId });
1405
+ }
1406
+ const planInputs = [
1407
+ ...sourceSelectors.map((selector) => {
1408
+ const source = admitted.get(selector);
1409
+ return {
1410
+ path: selector,
1411
+ selector,
1412
+ // An absent component has no definition: it carries only its kind and name.
1413
+ document: (source.absent
1414
+ ? {
1415
+ kind: documentKind(familyOf(selector)),
1416
+ identity: { apiName: selectorName(selector) },
1417
+ }
1418
+ : source.desired),
1419
+ source,
1420
+ ...(gitBySelector.has(selector) ? { git: gitBySelector.get(selector) } : {}),
1421
+ };
1422
+ }),
1423
+ ...[...streamSelectors, ...nativeSelectors].map((selector) => ({
1424
+ path: selector,
1425
+ selector,
1426
+ document: { kind: familyOf(selector), identity: { apiName: selectorName(selector) } },
1427
+ ...(gitBySelector.has(selector) ? { git: gitBySelector.get(selector) } : {}),
1428
+ })),
1429
+ ];
1430
+ let streamClients;
1431
+ const streamClientsFor = async () => {
1432
+ streamClients ??= await this.createDataStreamClients(await resolveUsername(), streamVersion);
1433
+ return streamClients;
1434
+ };
1435
+ // A selected stream owns its landing DLO: when both are selected, the stream is deleted
1436
+ // with --delete-dlo semantics and the DLO is never deleted on its own (read-only lookup).
1437
+ const pairedDlo = new Map();
1438
+ if (streamSelectors.length > 0 && nativeSelectors.some((value) => value.startsWith('dlo:')))
1439
+ for (const selector of streamSelectors) {
1440
+ const linked = await (this.readStreamLinkedDlo ?? readStreamLinkedDlo)(selectorName(selector), await streamClientsFor());
1441
+ const dlo = nativeSelectors.find((value) => value.startsWith('dlo:') &&
1442
+ typeof linked === 'string' &&
1443
+ selectorName(value).toLowerCase() === linked.toLowerCase());
1444
+ if (dlo)
1445
+ pairedDlo.set(selectorName(selector), dlo);
1446
+ }
1447
+ const pairedSelectors = new Set(pairedDlo.values());
1448
+ const stageInputs = planInputs.filter((input) => !pairedSelectors.has(input.selector));
1449
+ const stages = planDeleteStages(stageInputs);
1450
+ const dependents = selectedDependents(stageInputs);
1451
+ const keyOfSelector = new Map(planInputs.map((input) => [input.selector, inputKey(input)]));
1452
+ // The definition a source-family item deletes (read from the org, or the Git base content).
1453
+ const desiredOf = (entry) => entry.source;
1454
+ // The org's spelling of a transform or graph name (a by-name read may match ignoring
1455
+ // case); the item and the local files use it, as the delete never renames anything.
1456
+ const definitionName = (desired, fallback) => {
1457
+ const name = desired.definition?.name;
1458
+ return typeof name === 'string' && name !== '' ? name : fallback;
1459
+ };
1460
+ // A source-family component the org does not have: nothing to delete, no request sent.
1461
+ const reportAbsent = (entry) => {
1462
+ const item = {
1463
+ family: familyOf(entry.selector),
1464
+ identity: { dataSpace: effectiveScope, apiName: selectorName(entry.selector) },
1465
+ operation: flags.preview ? 'preview' : 'delete',
1466
+ outcome: 'unchanged',
1467
+ mutation: 'not-attempted',
1468
+ };
1469
+ selectorsByItem.set(item, entry.selector);
1470
+ envelope.result.items.push(item);
1471
+ return 'success';
1472
+ };
1473
+ const runGraph = async (entry) => {
1474
+ const { desired } = desiredOf(entry);
1475
+ const name = definitionName(desired, selectorName(entry.selector));
1476
+ const verifyInput = async () => {
1477
+ if (JSON.stringify(flags) !== snapshot)
1478
+ throw new DloError('INVALID_SELECTION');
1479
+ await stillDeleted(entry.git);
1480
+ };
1481
+ await verifyInput();
1482
+ const target = await connect();
1483
+ const context = await this.nativeGraphContext(target, effectiveScope);
1484
+ envelope.metadata.apiVersion = '68.0';
1485
+ warn(nativeGraphLimitations);
1486
+ const result = await this.operateNativeGraph(desired, context, this.nativeGraphClient(target, '68.0', effectiveScope), {
1487
+ operation: 'delete',
1488
+ preview: flags.preview,
1489
+ confirmed: true,
1490
+ verifyInput,
1491
+ });
1492
+ const item = {
1493
+ family: 'data-graph',
1494
+ identity: { dataSpace: effectiveScope, apiName: name },
1495
+ operation: flags.preview ? 'preview' : 'delete',
1496
+ outcome: result.outcome === 'delete'
1497
+ ? 'delete'
1498
+ : result.outcome === 'deleted'
1499
+ ? 'deleted'
1500
+ : result.outcome === 'unchanged'
1501
+ ? 'unchanged'
1502
+ : result.outcome === 'failed'
1503
+ ? 'failed'
1504
+ : 'blocked',
1505
+ mutation: result.mutation === 'confirmed-deleted'
1506
+ ? 'confirmed-deleted'
1507
+ : result.mutation === 'rejected'
1508
+ ? 'rejected'
1509
+ : result.mutation === 'unknown'
1510
+ ? 'unknown'
1511
+ : 'not-attempted',
1512
+ routes: [{ operation: 'data-graph.delete', apiVersion: '68.0', transport: 'native' }],
1513
+ };
1514
+ envelope.result.items.push(item);
1515
+ selectorsByItem.set(item, entry.selector);
1516
+ await track(item, await sourceFiles('data-graph', name));
1517
+ const status = result.outcome === 'failed'
1518
+ ? 'failed'
1519
+ : result.outcome === 'blocked'
1520
+ ? 'blocked'
1521
+ : 'success';
1522
+ if (status !== 'success')
1523
+ envelope.diagnostics.errors.push({
1524
+ code: 'DELETE_FAILED',
1525
+ message: operationDiagnostic(result,
1526
+ // No delete was sent for this graph: nothing to inspect for it. The run-wide
1527
+ // wording only when no item of the run sent a delete either.
1528
+ item.mutation === 'not-attempted'
1529
+ ? envelope.result.items.every((entry) => entry.mutation === 'not-attempted')
1530
+ ? 'Deletion stopped before any delete was sent; nothing was deleted. Correct the reported check before another attempt.'
1531
+ : 'This data graph was not deleted; no delete was sent for it. Correct the reported check before another attempt; check the outcomes of the other items.'
1532
+ : 'Deletion stopped. Inspect unknown outcomes before another attempt; no automatic retry or rollback.'),
1533
+ retryable: false,
1534
+ });
1535
+ return status;
1536
+ };
1537
+ const runTransform = async (entry) => {
1538
+ const { desired, transformTargetId } = desiredOf(entry);
1539
+ const name = definitionName(desired, selectorName(entry.selector));
1540
+ const verifyInput = async () => {
1541
+ if (JSON.stringify(flags) !== snapshot)
1542
+ throw new DataTransformError('TRANSFORM_DELETE_INPUT_DRIFT');
1543
+ await stillDeleted(entry.git);
1544
+ };
1545
+ await verifyInput();
1546
+ const item = {
1547
+ family: 'data-transform',
1548
+ identity: { dataSpace: effectiveScope, apiName: name },
1549
+ operation: flags.preview ? 'preview' : 'delete',
1550
+ outcome: 'blocked',
1551
+ mutation: 'not-attempted',
1552
+ routes: flags.preview
1553
+ ? [{ operation: 'data-transform.get', apiVersion: '68.0', transport: 'native' }]
1554
+ : [
1555
+ { operation: 'data-transform.delete', apiVersion: '68.0', transport: 'native' },
1556
+ { operation: 'data-transform.get', apiVersion: '68.0', transport: 'native' },
1557
+ ],
1558
+ };
1559
+ selectorsByItem.set(item, entry.selector);
1560
+ envelope.result.items.push(item);
1561
+ envelope.metadata.apiVersion = '68.0';
1562
+ let dispatched = false;
1563
+ try {
1564
+ const target = await connect();
1565
+ if (!target.getUsername())
1566
+ throw new DloError('TARGET_ORG_REQUIRED');
1567
+ await verifyInput();
1568
+ const base = this.createDataTransformClient(target, '68.0', effectiveScope);
1569
+ const client = {
1570
+ ...base,
1571
+ delete: async (value) => {
1572
+ dispatched = true;
1573
+ await base.delete(value);
1574
+ },
1575
+ };
1576
+ warn('Transform definition deletion only, for a transform of any owner (Salesforce decides; its 4xx refusal is reported as rejected). Settlement is the absence of the transform from the bounded visible inventory; exhaustive external-consumer exclusion is not established. No DLO, run or data cleanup; no retry, atomic concurrency guarantee or fallback.');
1577
+ const result = await this.deleteDataTransform(desired, client, {
1578
+ // Resolved from the transform's name during admission.
1579
+ targetId: transformTargetId,
1580
+ preview: flags.preview,
1581
+ confirmDelete: true,
1582
+ verifyInput,
1583
+ });
1584
+ item.outcome = result.outcome === 'preview' ? 'delete' : result.outcome;
1585
+ item.mutation = result.mutation;
1586
+ await track(item, await sourceFiles('data-transform', name));
1587
+ if (result.mutation === 'rejected') {
1588
+ envelope.diagnostics.errors.push({
1589
+ code: 'REQUEST_FAILED',
1590
+ message: operationDiagnostic(result.error, rejectedNextAction),
1591
+ retryable: false,
1592
+ });
1593
+ return 'failed';
1594
+ }
1595
+ if (result.outcome === 'deletion-unconfirmed') {
1596
+ envelope.diagnostics.errors.push({
1597
+ code: 'TRANSFORM_DELETE_UNCONFIRMED',
1598
+ message: 'DELETE outcome is not confirmed. Do not replay; reconcile by reading the Transform inventory before any further action.',
1599
+ retryable: false,
1600
+ });
1601
+ return 'failed';
1602
+ }
1603
+ if (result.outcome === 'blocked') {
1604
+ envelope.diagnostics.errors.push({
1605
+ code: 'DESTRUCTIVE_CONFIRMATION_REQUIRED',
1606
+ message: 'The transform delete was not confirmed; nothing was changed.',
1607
+ retryable: false,
1608
+ });
1609
+ return 'blocked';
1610
+ }
1611
+ return 'success';
1612
+ }
1613
+ catch (error) {
1614
+ item.outcome = dispatched ? 'failed' : 'blocked';
1615
+ item.mutation = dispatched ? 'unknown' : 'not-attempted';
1616
+ envelope.status = dispatched ? 'failed' : 'blocked';
1617
+ throw error;
1618
+ }
1619
+ };
1620
+ // Record an owner-family result (Segment, IR, CI) as its item; map it to the stage status.
1621
+ const settleOwner = async (result, item, selector, files) => {
1622
+ envelope.result.items.push(item);
1623
+ selectorsByItem.set(item, selector);
1624
+ await track(item, files);
1625
+ envelope.diagnostics.errors.push(...result.diagnostics.map((diagnostic) => ({ ...diagnostic, retryable: false })));
1626
+ return result.outcome === 'failed'
1627
+ ? 'failed'
1628
+ : result.outcome === 'blocked'
1629
+ ? 'blocked'
1630
+ : 'success';
1631
+ };
1632
+ const runSegment = async (entry) => {
1633
+ const desired = desiredOf(entry).desired;
1634
+ const verifyInput = async () => {
1635
+ if (JSON.stringify(flags) !== snapshot)
1636
+ throw new DloError('INVALID_SELECTION');
1637
+ await stillDeleted(entry.git);
1638
+ };
1639
+ await verifyInput();
1640
+ const target = await connect();
1641
+ await verifyInput();
1642
+ envelope.metadata.apiVersion = '68.0';
1643
+ warn('Segment definition deletion only. Selected source compatibility is checked; exhaustive external-consumer exclusion and physical membership/output cleanup remain unverified. No shared DMO is deleted.');
1644
+ const result = await this.deleteSegment(desired, target, { requested: '68.0', restSelector: 'v68.0', soapNumeric: '68.0' }, effectiveScope, { preview: flags.preview, confirmDelete: true, verifyInput });
1645
+ const item = {
1646
+ ...result,
1647
+ family: 'segment',
1648
+ identity: reportedIdentity(desired, effectiveScope),
1649
+ operation: flags.preview ? 'preview' : 'delete',
1650
+ routes: [
1651
+ { operation: 'segments.delete', apiVersion: '68.0', transport: 'native' },
1652
+ { operation: 'segments.get', apiVersion: '68.0', transport: 'native' },
1653
+ { operation: 'dependency.read', apiVersion: '68.0', transport: 'native' },
1654
+ ],
1655
+ };
1656
+ return settleOwner(result, item, entry.selector, await sourceFiles('segment', desired.identity.apiName));
1657
+ };
1658
+ const runIdentityResolution = async (entry) => {
1659
+ const desired = desiredOf(entry).desired;
1660
+ const verifyInput = async () => {
1661
+ if (JSON.stringify(flags) !== snapshot)
1662
+ throw new DloError('INVALID_SELECTION');
1663
+ await stillDeleted(entry.git);
1664
+ };
1665
+ await verifyInput();
1666
+ const target = await connect();
1667
+ await verifyInput();
1668
+ envelope.metadata.apiVersion = '68.0';
1669
+ warn('IR owner-definition deletion only. Exhaustive external-consumer exclusion and physical profile/output cleanup remain unverified; no generated DMO or source DMO/DLO is manually deleted.');
1670
+ const result = await this.deleteIdentityResolution(desired, target, { requested: '68.0', restSelector: 'v68.0', soapNumeric: '68.0' }, effectiveScope, {
1671
+ preview: flags.preview,
1672
+ confirmDelete: true,
1673
+ verifyInput,
1674
+ });
1675
+ const item = {
1676
+ ...result,
1677
+ family: 'identity-resolution',
1678
+ identity: { dataSpace: effectiveScope, apiName: desired.identity.apiName },
1679
+ operation: flags.preview ? 'preview' : 'delete',
1680
+ routes: [
1681
+ {
1682
+ operation: 'identity-resolutions.delete',
1683
+ apiVersion: '68.0',
1684
+ transport: 'native',
1685
+ },
1686
+ {
1687
+ operation: 'identity-resolutions.get',
1688
+ apiVersion: '68.0',
1689
+ transport: 'native',
1690
+ },
1691
+ { operation: 'dependency.get', apiVersion: '68.0', transport: 'native' },
1692
+ ],
1693
+ };
1694
+ return settleOwner(result, item, entry.selector, await sourceFiles('identity-resolution', desired.identity.apiName));
1695
+ };
1696
+ const runCalculatedInsight = async (entry) => {
1697
+ const desired = desiredOf(entry).desired;
1698
+ const verifyInput = async () => {
1699
+ if (JSON.stringify(flags) !== snapshot)
1700
+ throw new DloError('CI_INPUT_DRIFT');
1701
+ await stillDeleted(entry.git);
1702
+ };
1703
+ await verifyInput();
1704
+ const target = await connect();
1705
+ const context = this.calculatedInsightContext(target, effectiveScope);
1706
+ await verifyInput();
1707
+ const result = await this.deleteCalculatedInsight(desired.identity, target, { requested: '68.0', restSelector: 'v68.0', soapNumeric: '68.0' }, effectiveScope, {
1708
+ context,
1709
+ preview: flags.preview,
1710
+ confirmDelete: true,
1711
+ verifyInput,
1712
+ });
1713
+ const item = {
1714
+ ...result,
1715
+ family: 'calculated-insight',
1716
+ identity: desired.identity,
1717
+ operation: flags.preview ? 'preview' : 'delete',
1718
+ routes: [
1719
+ {
1720
+ operation: 'calculated-insight.delete',
1721
+ apiVersion: '68.0',
1722
+ transport: 'native',
1723
+ },
1724
+ {
1725
+ operation: 'calculated-insight.get',
1726
+ apiVersion: '68.0',
1727
+ transport: 'native',
1728
+ },
1729
+ ],
1730
+ };
1731
+ return settleOwner(result, item, entry.selector, await sourceFiles('calculated-insight', desired.identity.apiName));
1732
+ };
1733
+ const streamSnapshot = () => JSON.stringify({
1734
+ metadata: flags.metadata,
1735
+ version: flags['api-version'],
1736
+ scope: flags.dataspace,
1737
+ cascade: flags['delete-dlo'],
1738
+ preview: flags.preview,
1739
+ target: flags['target-org'],
1740
+ });
1741
+ // The stream's file, and when its DLO goes too, the file of that DLO.
1742
+ const streamFiles = (apiName, deleteDlo, dlo) => [
1743
+ inProject('data-stream', `${apiName}.data-stream-meta.json`),
1744
+ ...(deleteDlo && typeof dlo === 'string' && dloName.test(dlo)
1745
+ ? [inProject('dlo', `${dlo}.dlo-meta.json`)]
1746
+ : []),
1747
+ ];
1748
+ // Preview: a dependent of a stream or its DLO is planned when an earlier phase of this delete
1749
+ // plans to delete it: a selected DMO, a DMO whose every mapping from the landing DLO is a
1750
+ // selected mapping, or a selected mapping. The real run checks the org after those phases.
1751
+ const planned = (family) => new Set(envelope.result.items
1752
+ .filter((item) => item.family === family &&
1753
+ item.operation === 'preview' &&
1754
+ (item.outcome === 'delete' || item.outcome === 'planned-dependencies'))
1755
+ .flatMap((item) => [
1756
+ item.identity.apiName,
1757
+ ...(item.targetApiName === undefined ? [] : [item.targetApiName]),
1758
+ ])
1759
+ .map((value) => value.toLowerCase()));
1760
+ const plannedStreamDependent = async (dependent, dloName) => {
1761
+ const name = dependent.name.toLowerCase();
1762
+ const mappings = planned('mapping');
1763
+ if (dependent.componentType !== 'DataModelObject')
1764
+ return /mapping/iu.test(dependent.componentType) && mappings.has(name);
1765
+ if (planned('dmo').has(name))
1766
+ return true;
1767
+ if (mappings.size === 0 || !nativeDmoName.test(dependent.name))
1768
+ return false;
1769
+ try {
1770
+ const target = await resolveUsername();
1771
+ const names = unwrapNativeMappingCollection(await (this.createMappingClient ?? createMappingClient)(target, nativeVersion, undefined, effectiveScope, this.createMappingSender(target, nativeVersion)).list(dependent.name, dloName), effectiveScope).map((entry) => String(entry.developerName).toLowerCase());
1772
+ return names.length > 0 && names.every((value) => mappings.has(value));
1773
+ }
1774
+ catch {
1775
+ return false;
1776
+ }
1777
+ };
1778
+ const runStreams = async (selected) => {
1779
+ envelope.metadata.apiVersion = streamVersion;
1780
+ const expected = streamSnapshot();
1781
+ const verifyInput = async () => {
1782
+ if (streamSnapshot() !== expected)
1783
+ throw new DataStreamError('STREAM_DELETE_INPUT_DRIFT');
1784
+ };
1785
+ await verifyInput();
1786
+ const clients = await streamClientsFor();
1787
+ for (const selector of selected) {
1788
+ const apiName = selectorName(selector);
1789
+ const ownedDlo = pairedDlo.get(apiName);
1790
+ const deleteDlo = flags['delete-dlo'] === true || ownedDlo !== undefined;
1791
+ const item = {
1792
+ family: 'data-stream',
1793
+ identity: { apiName, dataSpace: effectiveScope },
1794
+ operation: flags.preview ? 'preview' : 'delete',
1795
+ outcome: 'blocked',
1796
+ mutation: 'not-attempted',
1797
+ deleteDlo,
1798
+ routes: [
1799
+ { operation: 'data-stream.delete', transport: 'native', apiVersion: streamVersion },
1800
+ { operation: 'dlo.get', transport: 'native', apiVersion: streamVersion },
1801
+ { operation: 'dependency.read', transport: 'native', apiVersion: streamVersion },
1802
+ ],
1803
+ };
1804
+ selectorsByItem.set(item, selector);
1805
+ envelope.result.items.push(item);
1806
+ // The selected landing DLO is reported with the stream's outcome; no separate call.
1807
+ const reportOwnedDlo = () => {
1808
+ if (ownedDlo === undefined)
1809
+ return;
1810
+ const owned = {
1811
+ family: 'dlo',
1812
+ identity: { dataSpace: effectiveScope, apiName: selectorName(ownedDlo) },
1813
+ operation: item.operation,
1814
+ outcome: item.outcome,
1815
+ mutation: item.mutation,
1816
+ removedWith: selector,
1817
+ };
1818
+ selectorsByItem.set(owned, ownedDlo);
1819
+ envelope.result.items.push(owned);
1820
+ };
1821
+ await verifyInput();
1822
+ const options = { deleteDlo, verifyInput, dataSpace: effectiveScope };
1823
+ if (flags.preview) {
1824
+ let preview;
1825
+ try {
1826
+ preview = await this.preflightDeleteDataStream(apiName, clients, {
1827
+ ...options,
1828
+ covered: plannedStreamDependent,
1829
+ });
1830
+ }
1831
+ catch (error) {
1832
+ // A refused stream names its cause on its item too; the command reports it as well.
1833
+ if (error instanceof DataStreamError)
1834
+ item.diagnostics = [
1835
+ {
1836
+ code: error.code,
1837
+ message: operationDiagnostic(error, 'Preview stopped; nothing was deleted. Correct the reported check before another attempt.'),
1838
+ },
1839
+ ];
1840
+ throw error;
1841
+ }
1842
+ await verifyInput();
1843
+ item.outcome = preview.outcome;
1844
+ if ('plannedDependencies' in preview && preview.plannedDependencies)
1845
+ item.diagnostics = [
1846
+ {
1847
+ code: 'DEPENDENCIES_PLANNED',
1848
+ message: `Selected dependent ${preview.plannedDependencies.map((dependent) => `${dependent.componentType} ${dependent.name}`).join(', ')} is deleted earlier in this delete and must settle before this item is checked; no existence or delete outcome is asserted.`,
1849
+ },
1850
+ ];
1851
+ await track(item, streamFiles(apiName, deleteDlo, 'targetDloName' in preview ? preview.targetDloName : undefined));
1852
+ reportOwnedDlo();
1853
+ }
1854
+ else {
1855
+ const result = await this.executeDeleteDataStream(apiName, clients, options);
1856
+ item.outcome = result.outcome;
1857
+ item.mutation = result.mutation;
1858
+ if ('targetApiName' in result)
1859
+ item.targetApiName = result.targetApiName;
1860
+ if ('targetDloName' in result)
1861
+ item.targetDloName = result.targetDloName;
1862
+ await track(item, streamFiles(apiName, deleteDlo, item.targetDloName));
1863
+ reportOwnedDlo();
1864
+ // Already gone (a rerun after it was deleted): nothing to delete.
1865
+ if (result.outcome === 'unchanged')
1866
+ continue;
1867
+ if (result.outcome !== 'deleted') {
1868
+ // The refusal is reported on the stream's item as well as on the command.
1869
+ item.diagnostics = result.diagnostics.map(({ code, message }) => ({ code, message }));
1870
+ envelope.diagnostics.errors.push(...result.diagnostics);
1871
+ return result.outcome;
1872
+ }
1873
+ }
1874
+ }
1875
+ return 'success';
1876
+ };
1877
+ const runNative = async (selected) => {
1878
+ const version = nativeVersion;
1879
+ // eslint-disable-next-line unicorn/no-array-sort -- Sort a fresh array within the ES2022 library target.
1880
+ const ordered = [...selected].sort((a, b) => nativeOrder(a) - nativeOrder(b));
1881
+ const target = await resolveUsername();
1882
+ const mappingReader = () => (this.createMappingClient ?? createMappingClient)(target, version, undefined, effectiveScope, this.createMappingSender(target, version));
1883
+ // Like deploy, an authored mapping (the file of that name, or with --changed-since its base
1884
+ // content) names the org mapping by its binding, whatever Salesforce named it; absent when
1885
+ // the org has no mapping with that binding. Resolved before the stage's first write.
1886
+ const orgMappingNames = new Map();
1887
+ const absentMappings = new Set();
1888
+ for (const selector of ordered.filter((value) => value.startsWith('mapping:'))) {
1889
+ const name = selector.slice(selector.indexOf(':') + 1);
1890
+ try {
1891
+ const base = gitBySelector.get(selector)?.document;
1892
+ // A verbatim base file names no binding: the mapping is deleted by its name.
1893
+ const binding = gitMode
1894
+ ? isVerbatimDocument(base)
1895
+ ? undefined
1896
+ : base
1897
+ : await this.readAuthoredMapping(path.join(projectData, 'mapping', `${name}.mapping-meta.json`));
1898
+ if (binding === undefined)
1899
+ continue;
1900
+ if (binding.c__dataSpace !== effectiveScope)
1901
+ throw explainSpaceMismatch(new NativeMappingError('MAPPING_DATASPACE_MISMATCH'), binding.identity.apiName, binding.c__dataSpace, effectiveScope);
1902
+ const found = await resolveNativeMappingTarget(binding, mappingReader());
1903
+ if (found)
1904
+ orgMappingNames.set(selector, found.identity.apiName);
1905
+ else
1906
+ absentMappings.add(selector);
1907
+ }
1908
+ catch (error) {
1909
+ const blocked = {
1910
+ family: 'mapping',
1911
+ identity: { dataSpace: effectiveScope, apiName: name },
1912
+ operation: flags.preview ? 'preview' : 'delete',
1913
+ outcome: 'blocked',
1914
+ mutation: 'not-attempted',
1915
+ };
1916
+ selectorsByItem.set(blocked, selector);
1917
+ envelope.result.items.push(blocked);
1918
+ throw error;
1919
+ }
1920
+ }
1921
+ const resolvedMappings = new Set(orgMappingNames.values());
1922
+ // A DLO dependent is covered when this command deletes it: its DMO, or every mapping
1923
+ // between the DLO and that DMO.
1924
+ const coveredBySelection = (dlo) => async (dependent) => {
1925
+ if (dependent.componentType !== 'DataModelObject')
1926
+ return false;
1927
+ if (nativeSelectors.includes(`dmo:${dependent.name}`))
1928
+ return true;
1929
+ if (!nativeDmoName.test(dependent.name))
1930
+ return false;
1931
+ let names = [];
1932
+ try {
1933
+ names = unwrapNativeMappingCollection(await mappingReader().list(dependent.name, dlo), effectiveScope).map((entry) => String(entry.developerName));
1934
+ }
1935
+ catch {
1936
+ return false;
1937
+ }
1938
+ return (names.length > 0 &&
1939
+ names.every((name) => nativeSelectors.includes(`mapping:${name}`) || resolvedMappings.has(name)));
1940
+ };
1941
+ // Every DLO of this stage has its dependents checked before the stage's first write.
1942
+ const admittedDependents = new Map();
1943
+ for (const selector of ordered.filter((value) => value.startsWith('dlo:'))) {
1944
+ const name = selector.slice(4);
1945
+ try {
1946
+ admittedDependents.set(name, await admitDloDependents(name, this.createDloNativeDeleteClient(target, version), coveredBySelection(name)));
1947
+ }
1948
+ catch (error) {
1949
+ // An absent DLO has nothing to check; the item loop reports it unchanged.
1950
+ if (error instanceof DloError &&
1951
+ error.code === 'DLO_HTTP_ERROR' &&
1952
+ error.status === 404) {
1953
+ admittedDependents.set(name, []);
1954
+ continue;
1955
+ }
1956
+ const blocked = {
1957
+ family: 'dlo',
1958
+ identity: { dataSpace: effectiveScope, apiName: name },
1959
+ operation: flags.preview ? 'preview' : 'delete',
1960
+ outcome: 'blocked',
1961
+ mutation: 'not-attempted',
1962
+ };
1963
+ selectorsByItem.set(blocked, selector);
1964
+ envelope.result.items.push(blocked);
1965
+ throw error;
1966
+ }
1967
+ }
1968
+ // The last mapping of a custom DMO selected with that DMO goes with the DMO delete.
1969
+ // No request deletes it; a confirmed DMO deletion counts for it only once its own read
1970
+ // answers 404, otherwise it is unconfirmed.
1971
+ const withDmo = [];
1972
+ let withDmoUnconfirmed = false;
1973
+ const settleWithDmo = async () => {
1974
+ for (const entry of withDmo) {
1975
+ const owner = envelope.result.items.find((candidate) => selectorsByItem.get(candidate)?.toLowerCase() ===
1976
+ entry.item.removedWith?.toLowerCase());
1977
+ if (owner) {
1978
+ entry.item.outcome = owner.outcome;
1979
+ entry.item.mutation = owner.mutation;
1980
+ }
1981
+ if (entry.item.mutation === 'confirmed-deleted') {
1982
+ let absent = false;
1983
+ let failure;
1984
+ try {
1985
+ absent = await (this.confirmMappingAbsent ?? confirmNativeMappingAbsent)(entry.name, entry.reader, effectiveScope);
1986
+ }
1987
+ catch (error) {
1988
+ failure = error;
1989
+ }
1990
+ if (!absent) {
1991
+ withDmoUnconfirmed = true;
1992
+ entry.item.outcome = 'deletion-unconfirmed';
1993
+ entry.item.mutation = 'acknowledged';
1994
+ const text = `${owner ? selectorsByItem.get(owner) : 'The DMO'} was deleted, but mapping ${entry.name} ${failure === undefined ? 'was still readable afterwards' : 'could not be read back'}. Do not replay; read the mapping again before any further action.`;
1995
+ envelope.diagnostics.errors.push({
1996
+ code: 'MAPPING_DELETION_UNCONFIRMED',
1997
+ message: failure === undefined ? text : operationDiagnostic(failure, text),
1998
+ retryable: false,
1999
+ });
2000
+ }
2001
+ }
2002
+ await track(entry.item, entry.files);
2003
+ }
2004
+ };
2005
+ try {
2006
+ for (const selector of ordered) {
2007
+ if (selector.startsWith('relationship:')) {
2008
+ const base = gitBySelector.get(selector);
2009
+ // A verbatim base file: the relationship is found by name under its source DMO.
2010
+ const verbatim = isVerbatimDocument(base?.document);
2011
+ await this.deleteOneRelationship(selector, target, version, flags.preview, effectiveScope, envelope, selectorsByItem, track, verbatim ? undefined : base?.document, verbatim && base?.sourceObjectName !== undefined
2012
+ ? { sourceDmo: base.sourceObjectName, apiName: base.identity.apiName }
2013
+ : undefined);
2014
+ continue;
2015
+ }
2016
+ const native = selector.startsWith('dmo:');
2017
+ const mapping = selector.startsWith('mapping:');
2018
+ const apiName = selector.slice(selector.indexOf(':') + 1);
2019
+ const baseClient = mapping
2020
+ ? (this.createMappingClient ?? createMappingClient)(target, version, undefined, effectiveScope, this.createMappingSender(target, version))
2021
+ : native
2022
+ ? this.createDmoNativeDeleteClient(target, version)
2023
+ : this.createDloNativeDeleteClient(target, version);
2024
+ let dispatched = false;
2025
+ // Salesforce's own 4xx answer to the DELETE means nothing was deleted.
2026
+ let refusal;
2027
+ const client = mapping
2028
+ ? baseClient
2029
+ : {
2030
+ ...baseClient,
2031
+ delete: async (id) => {
2032
+ dispatched = true;
2033
+ try {
2034
+ await baseClient.delete(id);
2035
+ }
2036
+ catch (error) {
2037
+ const status = error.status;
2038
+ if ((error instanceof DloError || error instanceof NativeDmoError) &&
2039
+ error.code.endsWith('_HTTP_ERROR') &&
2040
+ typeof status === 'number' &&
2041
+ status >= 400 &&
2042
+ status < 500)
2043
+ refusal = error;
2044
+ throw error;
2045
+ }
2046
+ },
2047
+ };
2048
+ const item = {
2049
+ family: mapping ? 'mapping' : native ? 'dmo' : 'dlo',
2050
+ identity: { dataSpace: effectiveScope, apiName },
2051
+ operation: flags.preview ? 'preview' : 'delete',
2052
+ outcome: 'blocked',
2053
+ mutation: 'not-attempted',
2054
+ };
2055
+ selectorsByItem.set(item, selector);
2056
+ envelope.result.items.push(item);
2057
+ // The first read of the mapping names its binding, which finds a hand-written file.
2058
+ let firstRead;
2059
+ // The org mapping: the one the authored binding resolved to, otherwise the exact name.
2060
+ const resolved = orgMappingNames.get(selector);
2061
+ const orgName = resolved ?? apiName;
2062
+ try {
2063
+ if (mapping) {
2064
+ if (absentMappings.has(selector)) {
2065
+ // No org mapping has the authored binding: nothing to delete.
2066
+ item.outcome = 'unchanged';
2067
+ continue;
2068
+ }
2069
+ if (orgName !== apiName)
2070
+ item.targetApiName = orgName;
2071
+ const mappingBase = baseClient;
2072
+ const mappingClient = {
2073
+ ...client,
2074
+ get: async (name) => {
2075
+ const value = await mappingBase.get(name);
2076
+ if (name === orgName && firstRead === undefined)
2077
+ firstRead = value;
2078
+ return value;
2079
+ },
2080
+ remove: async (name) => {
2081
+ dispatched = true;
2082
+ await mappingBase.remove(name);
2083
+ },
2084
+ };
2085
+ // The DMO read uses the bound single-attempt GET client. The prefix (from the run's
2086
+ // one data space read) tells a standard DMO copy, which drops a field with its
2087
+ // last mapping.
2088
+ const dataSpacePrefix = effectiveScope === 'default'
2089
+ ? undefined
2090
+ : await dataSpaceCheckOf(this, async () => (this.createDataSpaceSender ?? openBoundSsot)(target, '68.0')).prefixOf(effectiveScope);
2091
+ const dependencies = {
2092
+ target: this.createDmoNativeDeleteClient(target, version),
2093
+ ...(dataSpacePrefix === undefined ? {} : { dataSpacePrefix }),
2094
+ };
2095
+ // The file named after the mapping, otherwise the one whose binding matches it.
2096
+ const mappingFiles = async () => {
2097
+ const canonical = inProject('mapping', `${apiName}.mapping-meta.json`);
2098
+ // The authored file whose binding named the org mapping.
2099
+ if (resolved !== undefined)
2100
+ return [canonical];
2101
+ try {
2102
+ const found = await mappingLocalFile(normalizeNativeMapping(firstRead, effectiveScope, 'retrieve'), process.cwd());
2103
+ return [{ path: found.path, boundary: projectData }];
2104
+ }
2105
+ catch {
2106
+ // Without a readable binding or folder only the canonical name is considered.
2107
+ return [canonical];
2108
+ }
2109
+ };
2110
+ // The selected DMO this mapping is the last mapping of, if the guard refused it.
2111
+ const ownerDmo = (error) => {
2112
+ if (dispatched ||
2113
+ !(error instanceof NativeMappingError) ||
2114
+ error.code !== 'MAPPING_LAST_MAPPING_DELETE_BLOCKED')
2115
+ return undefined;
2116
+ let dmo;
2117
+ try {
2118
+ dmo = normalizeNativeMapping(firstRead, effectiveScope, 'retrieve').spec
2119
+ .targetEntityDeveloperName;
2120
+ }
2121
+ catch {
2122
+ return undefined;
2123
+ }
2124
+ return nativeSelectors.find((value) => value.toLowerCase() === `dmo:${dmo}`.toLowerCase());
2125
+ };
2126
+ try {
2127
+ if (flags.preview) {
2128
+ await (this.preflightDeleteMapping ?? preflightDeleteNativeMapping)(orgName, mappingClient, dependencies, effectiveScope);
2129
+ item.plan = [{ operation: 'delete', apiName: orgName }];
2130
+ item.outcome = 'delete';
2131
+ }
2132
+ else
2133
+ await (this.deleteMapping ?? deleteNativeMapping)(orgName, mappingClient, dependencies, effectiveScope);
2134
+ }
2135
+ catch (error) {
2136
+ const owner = ownerDmo(error);
2137
+ if (owner === undefined)
2138
+ throw error;
2139
+ item.removedWith = owner;
2140
+ withDmo.push({
2141
+ item,
2142
+ files: await mappingFiles(),
2143
+ name: orgName,
2144
+ reader: mappingBase,
2145
+ });
2146
+ continue;
2147
+ }
2148
+ await track(item, await mappingFiles());
2149
+ }
2150
+ else {
2151
+ const definitionClient = client;
2152
+ // Dependents were admitted before the first write; execution waits for them to clear.
2153
+ if (!native && !flags.preview)
2154
+ await waitForDloDependents(apiName, baseClient, admittedDependents.get(apiName) ?? []);
2155
+ if (flags.preview) {
2156
+ const document = await (native
2157
+ ? (this.retrieveDmo ?? previewDeleteNativeDmo)(apiName, definitionClient, effectiveScope)
2158
+ : this.retrieveDlo(apiName, definitionClient, effectiveScope));
2159
+ // A DLO is reported in the run's data space.
2160
+ item.identity = native
2161
+ ? document.identity
2162
+ : { dataSpace: effectiveScope, apiName: document.identity.apiName };
2163
+ item.outcome = 'delete';
2164
+ }
2165
+ else {
2166
+ const receipt = await (native
2167
+ ? (this.deleteDmo ?? deleteNativeDmo)(apiName, definitionClient, effectiveScope)
2168
+ : this.deleteDlo(apiName, definitionClient, effectiveScope));
2169
+ item.identity.dataSpace = receipt.dataSpace;
2170
+ if ('processing' in receipt && receipt.processing) {
2171
+ // DLO/DMO read back in a DELETING state: acknowledged, server still processing.
2172
+ item.outcome = 'deletion-processing';
2173
+ item.mutation = 'acknowledged-processing';
2174
+ }
2175
+ }
2176
+ await track(item, native
2177
+ ? [inProject('dmo', `${apiName}.dmo-meta.json`)]
2178
+ : [inProject('dlo', `${apiName}.dlo-meta.json`)]);
2179
+ if (item.outcome === 'deletion-processing')
2180
+ continue;
2181
+ }
2182
+ item.outcome = flags.preview ? 'delete' : 'deleted';
2183
+ if (!flags.preview)
2184
+ item.mutation = 'confirmed-deleted';
2185
+ }
2186
+ catch (error) {
2187
+ if (!dispatched &&
2188
+ (error instanceof DloError ||
2189
+ error instanceof NativeDmoError ||
2190
+ error instanceof NativeMappingError) &&
2191
+ !mapping &&
2192
+ ['DLO_HTTP_ERROR', 'DMO_HTTP_ERROR'].includes(error.code) &&
2193
+ error.status === 404) {
2194
+ item.outcome = 'unchanged';
2195
+ continue;
2196
+ }
2197
+ // The mapping's own first read answered 404: it is already gone, like a DLO or DMO.
2198
+ if (mapping &&
2199
+ !dispatched &&
2200
+ firstRead === undefined &&
2201
+ error instanceof NativeMappingError &&
2202
+ error.code === 'MAPPING_HTTP_ERROR' &&
2203
+ error.status === 404) {
2204
+ item.outcome = 'unchanged';
2205
+ continue;
2206
+ }
2207
+ if (dispatched &&
2208
+ ((error instanceof DloError && error.code === 'DLO_DELETE_NOT_CONFIRMED') ||
2209
+ (error instanceof NativeDmoError && error.code === 'DMO_DELETE_NOT_CONFIRMED'))) {
2210
+ const noun = native ? 'DMO' : 'DLO';
2211
+ item.outcome = 'deletion-unconfirmed';
2212
+ item.mutation = 'acknowledged';
2213
+ envelope.diagnostics.errors.push({
2214
+ code: error.code,
2215
+ message: error.status === 200
2216
+ ? `Salesforce acknowledged the DELETE, but the ${noun} was still readable afterwards. Do not replay; read the ${noun} again before any further action.`
2217
+ : operationDiagnostic(error, `Salesforce acknowledged the DELETE, but its absence could not be confirmed. Do not replay; read the ${noun} again before any further action.`),
2218
+ retryable: false,
2219
+ });
2220
+ return 'failed';
2221
+ }
2222
+ item.outcome = dispatched ? 'failed' : 'blocked';
2223
+ item.mutation =
2224
+ (refusal !== undefined && refusal === error) ||
2225
+ (dispatched &&
2226
+ error instanceof NativeMappingError &&
2227
+ error.code === 'MAPPING_DELETE_FAILED' &&
2228
+ error.rejected === true)
2229
+ ? 'rejected'
2230
+ : dispatched
2231
+ ? 'unknown'
2232
+ : 'not-attempted';
2233
+ envelope.status = dispatched ? 'failed' : 'blocked';
2234
+ throw error;
2235
+ }
2236
+ }
2237
+ }
2238
+ finally {
2239
+ await settleWithDmo();
2240
+ }
2241
+ if (withDmoUnconfirmed) {
2242
+ envelope.status = 'failed';
2243
+ return 'failed';
2244
+ }
2245
+ return 'success';
2246
+ };
2247
+ // One stage: items whose selected dependents an earlier preview stage plans to delete are
2248
+ // reported as planned; the rest run through their family's executor.
2249
+ const runStage = async (stage, planned) => {
2250
+ const before = envelope.result.items.length;
2251
+ envelope.status = 'blocked';
2252
+ let status = 'success';
2253
+ try {
2254
+ for (const input of stage.inputs)
2255
+ await stillDeleted(input.git);
2256
+ const ready = [];
2257
+ for (const input of stage.inputs) {
2258
+ const waiting = flags.preview
2259
+ ? (dependents.get(input) ?? []).filter((key) => planned.has(key))
2260
+ : [];
2261
+ if (waiting.length === 0) {
2262
+ ready.push(input);
2263
+ continue;
2264
+ }
2265
+ const item = {
2266
+ family: familyOf(input.selector),
2267
+ identity: { dataSpace: effectiveScope, apiName: selectorName(input.selector) },
2268
+ operation: 'preview',
2269
+ outcome: 'planned-dependencies',
2270
+ mutation: 'not-attempted',
2271
+ diagnostics: [
2272
+ {
2273
+ code: 'DEPENDENCIES_PLANNED',
2274
+ message: `Selected dependent ${waiting.join(', ')} is deleted earlier in this delete and must settle before this item is checked; no existence or delete outcome is asserted.`,
2275
+ },
2276
+ ],
2277
+ };
2278
+ selectorsByItem.set(item, input.selector);
2279
+ envelope.result.items.push(item);
2280
+ }
2281
+ if (stage.phase === 'P1') {
2282
+ if (ready.length > 0)
2283
+ status = await runNative(ready.map((input) => input.selector));
2284
+ }
2285
+ else if (stage.phase === 'P0') {
2286
+ if (ready.length > 0)
2287
+ status = await runStreams(ready.map((input) => input.selector));
2288
+ }
2289
+ else
2290
+ for (const input of ready) {
2291
+ const family = familyOf(input.selector);
2292
+ status = input.source?.absent
2293
+ ? reportAbsent(input)
2294
+ : family === 'data-graph'
2295
+ ? await runGraph(input)
2296
+ : family === 'data-transform'
2297
+ ? await runTransform(input)
2298
+ : family === 'segment'
2299
+ ? await runSegment(input)
2300
+ : family === 'identity-resolution'
2301
+ ? await runIdentityResolution(input)
2302
+ : await runCalculatedInsight(input);
2303
+ if (status !== 'success')
2304
+ break;
2305
+ }
2306
+ }
2307
+ catch (error) {
2308
+ pushError(error);
2309
+ // A handler marks the envelope failed when its request was sent before the error.
2310
+ status = envelope.status === 'failed' ? 'failed' : 'blocked';
2311
+ }
2312
+ const added = envelope.result.items.slice(before);
2313
+ const processing = added.filter((item) => item.outcome === 'deletion-processing');
2314
+ // A later phase starts only after this one settled; accepted-but-processing has not.
2315
+ if (status === 'success' &&
2316
+ !flags.preview &&
2317
+ stage !== stages.at(-1) &&
2318
+ processing.length > 0) {
2319
+ envelope.diagnostics.errors.push({
2320
+ code: 'DELETE_PHASE_NOT_SETTLED',
2321
+ message: `Salesforce accepted the deletion of ${processing.map((item) => selectorsByItem.get(item)).join(', ')} and is still processing it, so the later phases of this delete were not started. Rerun the same delete once it reads absent; items already deleted report unchanged.`,
2322
+ retryable: false,
2323
+ });
2324
+ status = 'blocked';
2325
+ }
2326
+ return {
2327
+ status,
2328
+ planned: added
2329
+ .filter((item) => item.outcome === 'delete' || item.outcome === 'planned-dependencies')
2330
+ .flatMap((item) => {
2331
+ const key = keyOfSelector.get(selectorsByItem.get(item) ?? '');
2332
+ return key ? [key] : [];
2333
+ }),
2334
+ };
2335
+ };
2336
+ // Preview runs every stage read-only, even after a blocked one; execution stops there.
2337
+ const outcome = await runCrudStages(stages, runStage, {
2338
+ continueAfterBlocked: flags.preview,
2339
+ });
2340
+ envelope.status = outcome.status;
2341
+ }
2342
+ catch (error) {
2343
+ pushError(error);
2344
+ }
2345
+ return finish();
2346
+ }
2347
+ }